Loading...
Searching...
No Matches
MlflowFileStore.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4#include "MlflowFileStore.h"
5
6#include <netdb.h>
7#include <sys/socket.h>
8#include <sys/time.h>
9#include <unistd.h>
10
11#include <algorithm>
12#include <cctype>
13#include <charconv>
14#include <chrono>
15#include <cmath>
16#include <cstdlib>
17#include <cstring>
18#include <fstream>
19#include <iomanip>
20#include <iostream>
21#include <limits>
22#include <random>
23#include <stdexcept>
24
25namespace gpr {
26namespace track {
27
28namespace {
29
30MlflowRun* g_active_run = nullptr;
31
32long nowMilliseconds()
33{
34 return std::chrono::duration_cast<std::chrono::milliseconds>(
35 std::chrono::system_clock::now().time_since_epoch())
36 .count();
37}
38
39std::string jsonEscape(std::string_view text)
40{
41 std::string out;
42 out.reserve(text.size() + 2);
43 for (const char c: text) {
44 switch (c) {
45 case '"':
46 out += "\\\"";
47 break;
48 case '\\':
49 out += "\\\\";
50 break;
51 case '\n':
52 out += "\\n";
53 break;
54 case '\r':
55 out += "\\r";
56 break;
57 case '\t':
58 out += "\\t";
59 break;
60 default:
61 if (static_cast<unsigned char>(c) < 0x20) {
62 char buffer[8];
63 std::snprintf(buffer, sizeof(buffer), "\\u%04x",
64 static_cast<unsigned>(c));
65 out += buffer;
66 } else {
67 out += c;
68 }
69 }
70 }
71 return out;
72}
73
75std::string shortestDecimal(double value)
76{
77 char buffer[32];
78 const auto result = std::to_chars(buffer, buffer + sizeof(buffer), value);
79 return std::string(buffer, result.ptr);
80}
81
82std::string jsonNumber(double value)
83{
84 if (!std::isfinite(value)) return "null";
85 return shortestDecimal(value);
86}
87
89std::string yamlQuoted(std::string_view text)
90{
91 std::string out = "'";
92 for (const char c: text) {
93 if (c == '\'')
94 out += "''";
95 else
96 out += c;
97 }
98 out += "'";
99 return out;
100}
101
105std::string experimentIdFor(std::string_view name)
106{
107 // FNV-1a, 64-bit offset basis and prime.
108 unsigned long long hash = 14695981039346656037ULL;
109 for (const unsigned char c: name) {
110 hash ^= c;
111 hash *= 1099511628211ULL;
112 }
113 return std::to_string(hash % 1000000000000000ULL);
114}
115
116std::string newRunId()
117{
118 std::random_device device;
119 std::mt19937_64 engine(device());
120 std::uniform_int_distribution<unsigned long long> uniform;
121 std::ostringstream out;
122 out << std::hex << std::setfill('0') << std::setw(16) << uniform(engine)
123 << std::setw(16) << uniform(engine);
124 return out.str();
125}
126
127std::string fileUri(const std::filesystem::path& path)
128{
129 return "file://" + std::filesystem::absolute(path).string();
130}
131
132void writeText(const std::filesystem::path& file, const std::string& text)
133{
134 std::ofstream out(file, std::ios::trunc);
135 if (!out) throw std::runtime_error("cannot write " + file.string());
136 out << text;
137}
138
139} // namespace
140
141std::string sanitizeKey(std::string_view key)
142{
143 std::string out;
144 out.reserve(key.size());
145 for (const char c: key) {
146 const bool ok = std::isalnum(static_cast<unsigned char>(c)) ||
147 c == '_' || c == '-' || c == '.' || c == ' ' ||
148 c == '/';
149 out += ok ? c : '_';
150 }
151 if (out.empty()) out = "_";
152 return out;
153}
154
155std::string jsonStringField(std::string_view json, std::string_view key)
156{
157 const std::string needle = "\"" + std::string(key) + "\"";
158 std::size_t at = json.find(needle);
159 while (at != std::string_view::npos) {
160 std::size_t p = at + needle.size();
161 while (p < json.size() &&
162 std::isspace(static_cast<unsigned char>(json[p])))
163 ++p;
164 if (p < json.size() && json[p] == ':') {
165 ++p;
166 while (p < json.size() &&
167 std::isspace(static_cast<unsigned char>(json[p])))
168 ++p;
169 if (p < json.size() && json[p] == '"') {
170 std::string out;
171 for (++p; p < json.size() && json[p] != '"'; ++p) {
172 if (json[p] == '\\' && p + 1 < json.size()) ++p;
173 out += json[p];
174 }
175 return out;
176 }
177 return "";
178 }
179 at = json.find(needle, at + 1);
180 }
181 return "";
182}
183
184MlflowRestClient::MlflowRestClient(std::string_view tracking_uri,
185 double timeout_seconds)
186 : timeout_seconds_(timeout_seconds)
187{
188 const std::string_view scheme = "http://";
189 if (tracking_uri.substr(0, scheme.size()) != scheme)
190 throw std::invalid_argument(
191 "mlflow tracking uri must be plain http://host:port: " +
192 std::string(tracking_uri));
193 std::string_view rest = tracking_uri.substr(scheme.size());
194 const std::size_t slash = rest.find('/');
195 std::string_view authority = rest.substr(0, slash);
196 if (slash != std::string_view::npos) {
197 prefix_ = std::string(rest.substr(slash));
198 while (!prefix_.empty() && prefix_.back() == '/')
199 prefix_.pop_back();
200 }
201 const std::size_t colon = authority.rfind(':');
202 if (colon != std::string_view::npos) {
203 host_ = std::string(authority.substr(0, colon));
204 port_ = std::atoi(std::string(authority.substr(colon + 1)).c_str());
205 } else {
206 host_ = std::string(authority);
207 }
208 if (host_.empty() || port_ <= 0)
209 throw std::invalid_argument("mlflow tracking uri has no host:port: " +
210 std::string(tracking_uri));
211}
212
214 const std::string& json) const
215{
216 return request("POST", path, json, "application/json");
217}
218
220 const std::string& path, const std::string& body,
221 const std::string& content_type) const
222{
223 return request("PUT", path, body, content_type);
224}
225
227{
228 return request("GET", path, "", "");
229}
230
231MlflowRestClient::Response MlflowRestClient::request(
232 const std::string& method, const std::string& path, const std::string& body,
233 const std::string& content_type) const
234{
235 addrinfo hints{};
236 hints.ai_family = AF_UNSPEC;
237 hints.ai_socktype = SOCK_STREAM;
238 addrinfo* info = nullptr;
239 const std::string port = std::to_string(port_);
240 if (getaddrinfo(host_.c_str(), port.c_str(), &hints, &info) != 0 ||
241 info == nullptr)
242 throw std::runtime_error("cannot resolve " + host_);
243 int fd = -1;
244 for (addrinfo* a = info; a != nullptr; a = a->ai_next) {
245 fd = socket(a->ai_family, a->ai_socktype, a->ai_protocol);
246 if (fd < 0) continue;
247 timeval tv{};
248 tv.tv_sec = static_cast<long>(timeout_seconds_);
249 tv.tv_usec = static_cast<long>((timeout_seconds_ - tv.tv_sec) * 1e6);
250 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
251 setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
252 if (connect(fd, a->ai_addr, a->ai_addrlen) == 0) break;
253 close(fd);
254 fd = -1;
255 }
256 freeaddrinfo(info);
257 if (fd < 0)
258 throw std::runtime_error("cannot connect to " + host_ + ":" + port);
259 std::ostringstream req;
260 req << method << ' ' << prefix_ << path << " HTTP/1.1\r\nHost: " << host_
261 << ':' << port
262 << "\r\nConnection: close\r\nAccept: application/json\r\n";
263 if (!content_type.empty())
264 req << "Content-Type: " << content_type << "\r\n";
265 req << "Content-Length: " << body.size() << "\r\n\r\n" << body;
266 const std::string wire = req.str();
267 std::size_t sent = 0;
268 while (sent < wire.size()) {
269 const ssize_t n = send(fd, wire.data() + sent, wire.size() - sent, 0);
270 if (n <= 0) {
271 close(fd);
272 throw std::runtime_error("send failed to " + host_);
273 }
274 sent += static_cast<std::size_t>(n);
275 }
276 std::string raw;
277 char buffer[4096];
278 for (;;) {
279 const ssize_t n = recv(fd, buffer, sizeof(buffer), 0);
280 if (n < 0) {
281 close(fd);
282 throw std::runtime_error("receive timed out from " + host_);
283 }
284 if (n == 0) break;
285 raw.append(buffer, static_cast<std::size_t>(n));
286 }
287 close(fd);
288 Response response;
289 const std::size_t header_end = raw.find("\r\n\r\n");
290 if (raw.size() < 12 || raw.compare(0, 5, "HTTP/") != 0 ||
291 header_end == std::string::npos)
292 throw std::runtime_error("malformed HTTP response from " + host_);
293 response.status = std::atoi(raw.c_str() + 9);
294 std::string headers = raw.substr(0, header_end);
295 for (auto& c: headers)
296 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
297 std::string payload = raw.substr(header_end + 4);
298 if (headers.find("transfer-encoding: chunked") != std::string::npos) {
299 std::string decoded;
300 std::size_t p = 0;
301 while (p < payload.size()) {
302 const std::size_t line_end = payload.find("\r\n", p);
303 if (line_end == std::string::npos) break;
304 const std::size_t length = std::strtoul(
305 payload.substr(p, line_end - p).c_str(), nullptr, 16);
306 if (length == 0) break;
307 decoded += payload.substr(line_end + 2, length);
308 p = line_end + 2 + length + 2;
309 }
310 payload = decoded;
311 }
312 response.body = payload;
313 return response;
314}
315
316void JsonRecord::separator(std::string_view key)
317{
318 out_ << (first_ ? "{" : ",") << '"' << jsonEscape(key) << "\":";
319 first_ = false;
320}
321
322JsonRecord& JsonRecord::add(std::string_view key, double value)
323{
324 separator(key);
325 out_ << jsonNumber(value);
326 return *this;
327}
328
329JsonRecord& JsonRecord::add(std::string_view key, long value)
330{
331 separator(key);
332 out_ << value;
333 return *this;
334}
335
336JsonRecord& JsonRecord::add(std::string_view key, bool value)
337{
338 separator(key);
339 out_ << (value ? "true" : "false");
340 return *this;
341}
342
343JsonRecord& JsonRecord::add(std::string_view key, std::string_view value)
344{
345 separator(key);
346 out_ << '"' << jsonEscape(value) << '"';
347 return *this;
348}
349
350JsonRecord& JsonRecord::add(std::string_view key, const Eigen::VectorXd& value)
351{
352 separator(key);
353 out_ << '[';
354 for (Eigen::Index i = 0; i < value.size(); ++i)
355 out_ << (i ? "," : "") << jsonNumber(value(i));
356 out_ << ']';
357 return *this;
358}
359
360JsonRecord& JsonRecord::add(std::string_view key, const Eigen::MatrixXd& value)
361{
362 separator(key);
363 out_ << '[';
364 for (Eigen::Index r = 0; r < value.rows(); ++r) {
365 out_ << (r ? ",[" : "[");
366 for (Eigen::Index c = 0; c < value.cols(); ++c)
367 out_ << (c ? "," : "") << jsonNumber(value(r, c));
368 out_ << ']';
369 }
370 out_ << ']';
371 return *this;
372}
373
374JsonRecord& JsonRecord::addRaw(std::string_view key, std::string_view json)
375{
376 separator(key);
377 out_ << json;
378 return *this;
379}
380
381std::string JsonRecord::str() const
382{
383 return first_ ? std::string("{}") : out_.str() + "}";
384}
385
386std::unique_ptr<MlflowRun> MlflowRun::start(const Options& options)
387{
388 if (options.store.empty() && options.tracking_uri.empty()) return nullptr;
389 std::unique_ptr<MlflowRun> run(new MlflowRun());
390 // Streaming without a local store still needs somewhere for the
391 // record streams before they are uploaded: a scratch store.
392 run->store_ = std::filesystem::absolute(
393 options.store.empty()
394 ? std::filesystem::temp_directory_path() / "gpr_mlflow_scratch"
395 : options.store);
396 run->experiment_id_ = experimentIdFor(
397 options.experiment.empty() ? "Default" : options.experiment);
398 run->run_id_ = newRunId();
399 run->run_name_ = options.run_name;
400 run->start_time_ms_ = nowMilliseconds();
401 run->tracking_uri_ = options.tracking_uri;
402 // The server assigns the run id; the local layout then uses the same
403 // id, so the two views of one run coincide.
404 if (!options.tracking_uri.empty()) run->connectRemote(options);
405 const std::filesystem::path experiment_dir =
406 run->store_ / run->experiment_id_;
407 run->run_dir_ = experiment_dir / run->run_id_;
408 std::filesystem::create_directories(run->run_dir_ / "artifacts");
409 std::filesystem::create_directories(run->run_dir_ / "metrics");
410 std::filesystem::create_directories(run->run_dir_ / "params");
411 std::filesystem::create_directories(run->run_dir_ / "tags");
412 std::filesystem::create_directories(run->store_ / ".trash");
413 if (!std::filesystem::exists(experiment_dir / "meta.yaml")) {
414 std::ostringstream meta;
415 meta << "artifact_location: " << yamlQuoted(fileUri(experiment_dir))
416 << "\ncreation_time: " << run->start_time_ms_
417 << "\nexperiment_id: " << yamlQuoted(run->experiment_id_)
418 << "\nlast_update_time: " << run->start_time_ms_
419 << "\nlifecycle_stage: active\nname: "
420 << yamlQuoted(options.experiment.empty() ? "Default"
421 : options.experiment)
422 << "\n";
423 writeText(experiment_dir / "meta.yaml", meta.str());
424 }
425 run->writeMeta(Status::Running, 0);
426 run->setTag("mlflow.runName", options.run_name);
427 run->setTag("mlflow.source.type", "LOCAL");
428 if (const char* user = std::getenv("USER"))
429 run->setTag("mlflow.user", user);
430 for (const auto& [key, value]: options.tags)
431 run->setTag(key, value);
432 run->flush();
433 return run;
434}
435
436void MlflowRun::connectRemote(const Options& options)
437{
438 try {
439 rest_ = std::make_unique<MlflowRestClient>(options.tracking_uri,
440 options.timeout_seconds);
441 const std::string name =
442 options.experiment.empty() ? "Default" : options.experiment;
443 JsonRecord create_experiment;
444 create_experiment.add("name", name);
445 auto created = rest_->post("/api/2.0/mlflow/experiments/create",
446 create_experiment.str());
447 remote_experiment_id_ = jsonStringField(created.body, "experiment_id");
448 if (remote_experiment_id_.empty()) {
449 std::string encoded;
450 for (const unsigned char c: name) {
451 if (std::isalnum(c) || c == '-' || c == '_' || c == '.') {
452 encoded += static_cast<char>(c);
453 } else {
454 char buffer[4];
455 std::snprintf(buffer, sizeof(buffer), "%%%02X", c);
456 encoded += buffer;
457 }
458 }
459 auto found = rest_->get(
460 "/api/2.0/mlflow/experiments/get-by-name?experiment_name=" +
461 encoded);
462 remote_experiment_id_ =
463 jsonStringField(found.body, "experiment_id");
464 }
465 if (remote_experiment_id_.empty())
466 throw std::runtime_error("server returned no experiment id for " +
467 name);
468 std::ostringstream tags;
469 tags << "[{\"key\":\"mlflow.runName\",\"value\":\""
470 << jsonEscape(options.run_name) << "\"}";
471 for (const auto& [key, value]: options.tags)
472 tags << ",{\"key\":\"" << jsonEscape(key) << "\",\"value\":\""
473 << jsonEscape(value) << "\"}";
474 tags << ']';
475 JsonRecord create_run;
476 create_run.add("experiment_id", remote_experiment_id_)
477 .add("start_time", start_time_ms_)
478 .add("run_name", options.run_name)
479 .addRaw("tags", tags.str());
480 auto run = rest_->post("/api/2.0/mlflow/runs/create", create_run.str());
481 const std::string remote_id = jsonStringField(run.body, "run_id");
482 if (run.status / 100 != 2 || remote_id.size() != 32)
483 throw std::runtime_error("runs/create failed with status " +
484 std::to_string(run.status) + ": " +
485 run.body.substr(0, 200));
486 run_id_ = remote_id;
487 remote_artifact_uri_ = jsonStringField(run.body, "artifact_uri");
488 } catch (const std::exception& error) {
489 disableStreaming(error.what());
490 }
491}
492
493void MlflowRun::disableStreaming(const std::string& why)
494{
495 std::cerr << "[mlflow] streaming to " << tracking_uri_
496 << " disabled: " << why << " (the local store continues)\n";
497 rest_.reset();
498 pending_metrics_.clear();
499 pending_params_.clear();
500 pending_tags_.clear();
501}
502
504{
505 if (!rest_) return;
506 if (pending_metrics_.empty() && pending_params_.empty() &&
507 pending_tags_.empty())
508 return;
509 try {
510 std::ostringstream body;
511 body << "{\"run_id\":\"" << run_id_ << "\",\"metrics\":[";
512 for (std::size_t i = 0; i < pending_metrics_.size(); ++i) {
513 const auto& m = pending_metrics_[i];
514 body << (i ? "," : "") << "{\"key\":\"" << jsonEscape(m.key)
515 << "\",\"value\":" << jsonNumber(m.value)
516 << ",\"timestamp\":" << m.timestamp << ",\"step\":" << m.step
517 << '}';
518 }
519 body << "],\"params\":[";
520 for (std::size_t i = 0; i < pending_params_.size(); ++i)
521 body << (i ? "," : "") << "{\"key\":\""
522 << jsonEscape(pending_params_[i].first) << "\",\"value\":\""
523 << jsonEscape(pending_params_[i].second) << "\"}";
524 body << "],\"tags\":[";
525 for (std::size_t i = 0; i < pending_tags_.size(); ++i)
526 body << (i ? "," : "") << "{\"key\":\""
527 << jsonEscape(pending_tags_[i].first) << "\",\"value\":\""
528 << jsonEscape(pending_tags_[i].second) << "\"}";
529 body << "]}";
530 const auto response =
531 rest_->post("/api/2.0/mlflow/runs/log-batch", body.str());
532 if (response.status / 100 != 2)
533 throw std::runtime_error("runs/log-batch failed with status " +
534 std::to_string(response.status) + ": " +
535 response.body.substr(0, 200));
536 pending_metrics_.clear();
537 pending_params_.clear();
538 pending_tags_.clear();
539 } catch (const std::exception& error) {
540 disableStreaming(error.what());
541 }
542}
543
544void MlflowRun::uploadRecordStreams()
545{
546 if (!rest_) return;
547 // Only a server that proxies its artifact store accepts uploads over
548 // the REST surface (`mlflow server --serve-artifacts`); the run's
549 // artifact_uri says so. Otherwise the streams stay in the local store.
550 const std::string scheme = "mlflow-artifacts:";
551 if (remote_artifact_uri_.compare(0, scheme.size(), scheme) != 0) return;
552 std::string base = remote_artifact_uri_.substr(scheme.size());
553 while (!base.empty() && base.front() == '/')
554 base.erase(base.begin());
555 try {
556 for (const auto& stream: record_streams_) {
557 const std::filesystem::path file =
558 run_dir_ / "artifacts" / (stream + ".jsonl");
559 std::ifstream in(file, std::ios::binary);
560 std::stringstream contents;
561 contents << in.rdbuf();
562 const auto response =
563 rest_->put("/api/2.0/mlflow-artifacts/artifacts/" + base + "/" +
564 stream + ".jsonl",
565 contents.str(), "application/octet-stream");
566 if (response.status / 100 != 2)
567 throw std::runtime_error("artifact upload of " + stream +
568 " failed with status " +
569 std::to_string(response.status));
570 }
571 } catch (const std::exception& error) {
572 disableStreaming(error.what());
573 }
574}
575
577{
578 if (!finished_) {
579 try {
581 } catch (...) {
582 }
583 }
584 if (g_active_run == this) g_active_run = nullptr;
585}
586
587void MlflowRun::writeMeta(Status status, long end_time_ms) const
588{
589 const char* user = std::getenv("USER");
590 std::ostringstream meta;
591 meta << "artifact_uri: " << yamlQuoted(fileUri(run_dir_ / "artifacts"))
592 << "\nend_time: ";
593 if (end_time_ms > 0)
594 meta << end_time_ms;
595 else
596 meta << "null";
597 meta
598 << "\nentry_point_name: ''\nexperiment_id: "
599 << yamlQuoted(experiment_id_)
600 << "\nlifecycle_stage: active\nrun_id: " << yamlQuoted(run_id_)
601 << "\nrun_name: " << yamlQuoted(run_name_)
602 << "\nrun_uuid: " << yamlQuoted(run_id_)
603 << "\nsource_name: ''\nsource_type: 4\nsource_version: ''\nstart_time: "
604 << start_time_ms_ << "\nstatus: " << static_cast<int>(status)
605 << "\ntags: []\nuser_id: " << yamlQuoted(user ? user : "unknown")
606 << "\n";
607 writeText(run_dir_ / "meta.yaml", meta.str());
608}
609
610void MlflowRun::logParam(std::string_view key, std::string_view value)
611{
612 writeText(run_dir_ / "params" / sanitizeKey(key), std::string(value));
613 if (rest_)
614 pending_params_.emplace_back(sanitizeKey(key), std::string(value));
615}
616
617void MlflowRun::logParam(std::string_view key, double value)
618{
619 logParam(key, jsonNumber(value));
620}
621
622void MlflowRun::logParam(std::string_view key, long value)
623{
624 logParam(key, std::to_string(value));
625}
626
627void MlflowRun::appendLocal(const std::filesystem::path& file,
628 const std::string& text)
629{
630 auto [entry, inserted] = append_streams_.try_emplace(file);
631 if (inserted) {
632 std::filesystem::create_directories(file.parent_path());
633 entry->second.open(file, std::ios::app);
634 }
635 auto& stream = entry->second;
636 stream << text;
637 // Readers observe each complete record without reopening its writer.
638 stream.flush();
639 if (!stream) {
640 append_streams_.erase(entry);
641 throw std::runtime_error("cannot append " + file.string());
642 }
643}
644
645void MlflowRun::logMetric(std::string_view key, double value, long step)
646{
647 if (!std::isfinite(value)) return;
648 std::ostringstream line;
649 line << nowMilliseconds() << ' ' << shortestDecimal(value) << ' ' << step
650 << '\n';
651 appendLocal(run_dir_ / "metrics" / sanitizeKey(key), line.str());
652 if (rest_) {
653 pending_metrics_.push_back(
654 {sanitizeKey(key), value, nowMilliseconds(), step});
655 // The REST log-batch call accepts at most 1000 metrics per
656 // request (MLflow API limit); send a full batch as it fills.
657 if (pending_metrics_.size() >= 1000) flush();
658 }
659}
660
661void MlflowRun::setTag(std::string_view key, std::string_view value)
662{
663 writeText(run_dir_ / "tags" / sanitizeKey(key), std::string(value));
664 if (rest_) pending_tags_.emplace_back(sanitizeKey(key), std::string(value));
665}
666
667void MlflowRun::logArtifact(const std::filesystem::path& file,
668 const std::string& name)
669{
670 if (!std::filesystem::exists(file)) return;
671 const std::filesystem::path target =
672 run_dir_ / "artifacts" /
673 (name.empty() ? file.filename().string() : name);
674 std::filesystem::create_directories(target.parent_path());
675 std::filesystem::copy_file(
676 file, target, std::filesystem::copy_options::overwrite_existing);
677}
678
679void MlflowRun::appendRecord(std::string_view stream, const JsonRecord& record)
680{
681 const std::string name = sanitizeKey(stream);
682 const std::filesystem::path file =
683 run_dir_ / "artifacts" / (name + ".jsonl");
684 appendLocal(file, record.str() + "\n");
685 if (std::find(record_streams_.begin(), record_streams_.end(), name) ==
686 record_streams_.end())
687 record_streams_.push_back(name);
688}
689
691{
692 if (finished_) return;
693 append_streams_.clear();
694 const long end_time_ms = nowMilliseconds();
695 writeMeta(status, end_time_ms);
696 finished_ = true;
697 flush();
698 uploadRecordStreams();
699 if (rest_) {
700 try {
701 const char* name = status == Status::Finished ? "FINISHED"
702 : status == Status::Failed ? "FAILED"
703 : status == Status::Killed ? "KILLED"
704 : "RUNNING";
705 JsonRecord update;
706 update.add("run_id", run_id_)
707 .add("status", name)
708 .add("end_time", end_time_ms);
709 const auto response =
710 rest_->post("/api/2.0/mlflow/runs/update", update.str());
711 if (response.status / 100 != 2)
712 throw std::runtime_error("runs/update failed with status " +
713 std::to_string(response.status));
714 } catch (const std::exception& error) {
715 disableStreaming(error.what());
716 }
717 }
718}
719
720std::string MlflowRun::identityJson() const
721{
722 JsonRecord record;
723 record.add("store", store_.string())
724 .add("experiment_id", experiment_id_)
725 .add("run_id", run_id_)
726 .add("run_name", run_name_)
727 .add("run_dir", run_dir_.string())
728 .add("tracking_uri", tracking_uri_)
729 .add("remote_experiment_id", remote_experiment_id_)
730 .add("streaming", rest_ != nullptr);
731 return record.str();
732}
733
734void setActiveRun(MlflowRun* run) noexcept
735{
736 g_active_run = run;
737}
738
740{
741 return g_active_run;
742}
743
744} // namespace track
745} // namespace gpr
A JSON object assembled field by field; one line of a record stream.
JsonRecord & add(std::string_view key, double value)
JsonRecord & addRaw(std::string_view key, std::string_view json)
A nested object, already rendered.
std::string str() const
int port() const noexcept
Response post(const std::string &path, const std::string &json) const
MlflowRestClient(std::string_view tracking_uri, double timeout_seconds)
Throws std::invalid_argument on a URI that is not plain http.
Response put(const std::string &path, const std::string &body, const std::string &content_type) const
Response get(const std::string &path) const
void setTag(std::string_view key, std::string_view value)
void logMetric(std::string_view key, double value, long step=0)
void logArtifact(const std::filesystem::path &file, const std::string &name="")
Copy a file into artifacts/ (optionally under a relative name).
void logParam(std::string_view key, std::string_view value)
void finish(Status status)
void appendRecord(std::string_view stream, const JsonRecord &record)
Append one JSON line to artifacts/STREAM_NAME.jsonl.
std::string identityJson() const
MlflowRun(const MlflowRun &)=delete
static std::unique_ptr< MlflowRun > start(const Options &options)
void flush()
Send buffered metrics, params and tags to the tracking server.
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
eon_relax_band_t eon_relax_surface_fn void * user
MlflowRun * activeRun() noexcept
void setActiveRun(MlflowRun *run) noexcept
std::string sanitizeKey(std::string_view key)
MLflow key alphabet: alphanumerics, underscore, dash, dot, space, slash.
std::string jsonStringField(std::string_view json, std::string_view key)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
std::string tracking_uri
http://host:port of mlflow server
std::filesystem::path store
local file store (mlruns)
std::map< std::string, std::string > tags