34 return std::chrono::duration_cast<std::chrono::milliseconds>(
35 std::chrono::system_clock::now().time_since_epoch())
39std::string jsonEscape(std::string_view text)
42 out.reserve(text.size() + 2);
43 for (
const char c: text) {
61 if (
static_cast<unsigned char>(c) < 0x20) {
63 std::snprintf(buffer,
sizeof(buffer),
"\\u%04x",
64 static_cast<unsigned>(c));
75std::string shortestDecimal(
double value)
78 const auto result = std::to_chars(buffer, buffer +
sizeof(buffer), value);
79 return std::string(buffer, result.ptr);
82std::string jsonNumber(
double value)
84 if (!std::isfinite(value))
return "null";
85 return shortestDecimal(value);
89std::string yamlQuoted(std::string_view text)
91 std::string
out =
"'";
92 for (
const char c: text) {
105std::string experimentIdFor(std::string_view name)
108 unsigned long long hash = 14695981039346656037ULL;
109 for (
const unsigned char c: name) {
111 hash *= 1099511628211ULL;
113 return std::to_string(hash % 1000000000000000ULL);
116std::string newRunId()
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);
127std::string fileUri(
const std::filesystem::path& path)
129 return "file://" + std::filesystem::absolute(path).string();
132void writeText(
const std::filesystem::path& file,
const std::string& text)
134 std::ofstream
out(file, std::ios::trunc);
135 if (!
out)
throw std::runtime_error(
"cannot write " + file.string());
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 ==
' ' ||
151 if (
out.empty())
out =
"_";
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])))
164 if (p < json.size() && json[p] ==
':') {
166 while (p < json.size() &&
167 std::isspace(
static_cast<unsigned char>(json[p])))
169 if (p < json.size() && json[p] ==
'"') {
171 for (++p; p < json.size() && json[p] !=
'"'; ++p) {
172 if (json[p] ==
'\\' && p + 1 < json.size()) ++p;
179 at = json.find(needle, at + 1);
185 double timeout_seconds)
186 : timeout_seconds_(timeout_seconds)
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() ==
'/')
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());
206 host_ = std::string(authority);
208 if (host_.empty() || port_ <= 0)
209 throw std::invalid_argument(
"mlflow tracking uri has no host:port: " +
210 std::string(tracking_uri));
214 const std::string& json)
const
216 return request(
"POST", path, json,
"application/json");
220 const std::string& path,
const std::string& body,
221 const std::string& content_type)
const
223 return request(
"PUT", path, body, content_type);
228 return request(
"GET", path,
"",
"");
232 const std::string& method,
const std::string& path,
const std::string& body,
233 const std::string& content_type)
const
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 ||
242 throw std::runtime_error(
"cannot resolve " + host_);
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;
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;
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_
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);
272 throw std::runtime_error(
"send failed to " + host_);
274 sent +=
static_cast<std::size_t
>(n);
279 const ssize_t n = recv(fd, buffer,
sizeof(buffer), 0);
282 throw std::runtime_error(
"receive timed out from " + host_);
285 raw.append(buffer,
static_cast<std::size_t
>(n));
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) {
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;
312 response.body = payload;
316void JsonRecord::separator(std::string_view key)
318 out_ << (first_ ?
"{" :
",") <<
'"' << jsonEscape(key) <<
"\":";
325 out_ << jsonNumber(value);
339 out_ << (value ?
"true" :
"false");
346 out_ <<
'"' << jsonEscape(value) <<
'"';
354 for (Eigen::Index i = 0; i < value.size(); ++i)
355 out_ << (i ?
"," :
"") << jsonNumber(value(i));
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));
383 return first_ ? std::string(
"{}") : out_.str() +
"}";
389 std::unique_ptr<MlflowRun> run(
new MlflowRun());
392 run->store_ = std::filesystem::absolute(
393 options.
store.empty()
394 ? std::filesystem::temp_directory_path() /
"gpr_mlflow_scratch"
396 run->experiment_id_ = experimentIdFor(
398 run->run_id_ = newRunId();
400 run->start_time_ms_ = nowMilliseconds();
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"
423 writeText(experiment_dir /
"meta.yaml", meta.str());
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);
436void MlflowRun::connectRemote(
const Options& options)
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;
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()) {
450 for (
const unsigned char c: name) {
451 if (std::isalnum(c) || c ==
'-' || c ==
'_' || c ==
'.') {
452 encoded +=
static_cast<char>(c);
455 std::snprintf(buffer,
sizeof(buffer),
"%%%02X", c);
459 auto found = rest_->get(
460 "/api/2.0/mlflow/experiments/get-by-name?experiment_name=" +
462 remote_experiment_id_ =
465 if (remote_experiment_id_.empty())
466 throw std::runtime_error(
"server returned no experiment id for " +
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) <<
"\"}";
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());
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));
488 }
catch (
const std::exception& error) {
489 disableStreaming(error.what());
493void MlflowRun::disableStreaming(
const std::string& why)
495 std::cerr <<
"[mlflow] streaming to " << tracking_uri_
496 <<
" disabled: " << why <<
" (the local store continues)\n";
498 pending_metrics_.clear();
499 pending_params_.clear();
500 pending_tags_.clear();
506 if (pending_metrics_.empty() && pending_params_.empty() &&
507 pending_tags_.empty())
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
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) <<
"\"}";
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());
544void MlflowRun::uploadRecordStreams()
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());
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 +
"/" +
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));
571 }
catch (
const std::exception& error) {
572 disableStreaming(error.what());
584 if (g_active_run ==
this) g_active_run =
nullptr;
587void MlflowRun::writeMeta(Status
status,
long end_time_ms)
const
589 const char*
user = std::getenv(
"USER");
590 std::ostringstream meta;
591 meta <<
"artifact_uri: " << yamlQuoted(fileUri(run_dir_ /
"artifacts"))
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")
607 writeText(run_dir_ /
"meta.yaml", meta.str());
612 writeText(run_dir_ /
"params" /
sanitizeKey(key), std::string(value));
614 pending_params_.emplace_back(
sanitizeKey(key), std::string(value));
624 logParam(key, std::to_string(value));
627void MlflowRun::appendLocal(
const std::filesystem::path& file,
628 const std::string& text)
630 auto [entry, inserted] = append_streams_.try_emplace(file);
632 std::filesystem::create_directories(file.parent_path());
633 entry->second.open(file, std::ios::app);
635 auto& stream = entry->second;
640 append_streams_.erase(entry);
641 throw std::runtime_error(
"cannot append " + file.string());
647 if (!std::isfinite(value))
return;
648 std::ostringstream line;
649 line << nowMilliseconds() <<
' ' << shortestDecimal(value) <<
' ' << step
651 appendLocal(run_dir_ /
"metrics" /
sanitizeKey(key), line.str());
653 pending_metrics_.push_back(
654 {
sanitizeKey(key), value, nowMilliseconds(), step});
657 if (pending_metrics_.size() >= 1000)
flush();
663 writeText(run_dir_ /
"tags" /
sanitizeKey(key), std::string(value));
664 if (rest_) pending_tags_.emplace_back(
sanitizeKey(key), std::string(value));
668 const std::string& name)
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);
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);
692 if (finished_)
return;
693 append_streams_.clear();
694 const long end_time_ms = nowMilliseconds();
695 writeMeta(
status, end_time_ms);
698 uploadRecordStreams();
706 update.
add(
"run_id", run_id_)
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());
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);