Loading...
Searching...
No Matches
gpr::track::MlflowRun Class Reference

#include <gpr/auxiliary/MlflowFileStore.h>

Classes

struct  Options

Public Types

enum class  Status { Running = 1 , Finished = 3 , Failed = 4 , Killed = 5 }

Public Member Functions

 ~MlflowRun ()
 MlflowRun (const MlflowRun &)=delete
MlflowRun & operator= (const MlflowRun &)=delete
void logParam (std::string_view key, std::string_view value)
void logParam (std::string_view key, double value)
void logParam (std::string_view key, long value)
void logMetric (std::string_view key, double value, long step=0)
void setTag (std::string_view key, std::string_view value)
void logArtifact (const std::filesystem::path &file, const std::string &name="")
 Copy a file into artifacts/ (optionally under a relative name).
void appendRecord (std::string_view stream, const JsonRecord &record)
 Append one JSON line to artifacts/STREAM_NAME.jsonl.
void flush ()
 Send buffered metrics, params and tags to the tracking server.
void finish (Status status)
const std::string & runId () const noexcept
const std::string & experimentId () const noexcept
const std::filesystem::path & runDirectory () const noexcept
bool streaming () const noexcept
std::string identityJson () const

Static Public Member Functions

static std::unique_ptr< MlflowRun > start (const Options &options)

Detailed Description

One MLflow run. It is written directly in the tracking file-store layout under a store directory (mlruns/EXPERIMENT_ID/RUN_ID/{meta.yaml, params,metrics,tags,artifacts}, readable by mlflow ui --backend-store-uri file://<store>), and streamed to a running tracking server when a tracking URI is given: the run is created there with the same id, metrics/params/tags go out in log-batch requests on flush(), and the record streams are uploaded as artifacts at finish() when the server proxies artifacts. Metrics carry a step; records are JSON lines appended to a named stream under artifacts/, for the vectors a post-mortem of the surrogate needs.

Definition at line 97 of file MlflowFileStore.h.

Member Enumeration Documentation

◆ Status

enum class gpr::track::MlflowRun::Status
strong
Enumerator
Running 
Finished 
Failed 
Killed 

Definition at line 107 of file MlflowFileStore.h.

107{ Running = 1, Finished = 3, Failed = 4, Killed = 5 };

Constructor & Destructor Documentation

◆ ~MlflowRun()

gpr::track::MlflowRun::~MlflowRun ( )

Definition at line 576 of file MlflowFileStore.cpp.

577{
578 if (!finished_) {
579 try {
581 } catch (...) {
582 }
583 }
584 if (g_active_run == this) g_active_run = nullptr;
585}
void finish(Status status)

◆ MlflowRun()

gpr::track::MlflowRun::MlflowRun ( const MlflowRun & )
delete

Member Function Documentation

◆ appendRecord()

void gpr::track::MlflowRun::appendRecord ( std::string_view stream,
const JsonRecord & record )

Append one JSON line to artifacts/STREAM_NAME.jsonl.

Definition at line 679 of file MlflowFileStore.cpp.

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}
std::string sanitizeKey(std::string_view key)
MLflow key alphabet: alphanumerics, underscore, dash, dot, space, slash.

◆ experimentId()

const std::string & gpr::track::MlflowRun::experimentId ( ) const
inlinenodiscardnoexcept

Definition at line 135 of file MlflowFileStore.h.

136 {
137 return experiment_id_;
138 }

◆ finish()

void gpr::track::MlflowRun::finish ( Status status)

Definition at line 690 of file MlflowFileStore.cpp.

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}
void flush()
Send buffered metrics, params and tags to the tracking server.
int status

◆ flush()

void gpr::track::MlflowRun::flush ( )

Send buffered metrics, params and tags to the tracking server.

Definition at line 503 of file MlflowFileStore.cpp.

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}

◆ identityJson()

std::string gpr::track::MlflowRun::identityJson ( ) const
nodiscard

The run's identity as JSON, for a caller that attaches later (the validation stage of a campaign runner).

Definition at line 720 of file MlflowFileStore.cpp.

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}

◆ logArtifact()

void gpr::track::MlflowRun::logArtifact ( const std::filesystem::path & file,
const std::string & name = "" )

Copy a file into artifacts/ (optionally under a relative name).

Definition at line 667 of file MlflowFileStore.cpp.

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}

◆ logMetric()

void gpr::track::MlflowRun::logMetric ( std::string_view key,
double value,
long step = 0 )

Definition at line 645 of file MlflowFileStore.cpp.

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}
std::string line(const std::string &topic, const std::vector< Field > &fields)

◆ logParam() [1/3]

void gpr::track::MlflowRun::logParam ( std::string_view key,
double value )

Definition at line 617 of file MlflowFileStore.cpp.

618{
619 logParam(key, jsonNumber(value));
620}
void logParam(std::string_view key, std::string_view value)

◆ logParam() [2/3]

void gpr::track::MlflowRun::logParam ( std::string_view key,
long value )

Definition at line 622 of file MlflowFileStore.cpp.

623{
624 logParam(key, std::to_string(value));
625}

◆ logParam() [3/3]

void gpr::track::MlflowRun::logParam ( std::string_view key,
std::string_view value )

Definition at line 610 of file MlflowFileStore.cpp.

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}

◆ operator=()

MlflowRun & gpr::track::MlflowRun::operator= ( const MlflowRun & )
delete

◆ runDirectory()

const std::filesystem::path & gpr::track::MlflowRun::runDirectory ( ) const
inlinenodiscardnoexcept

Definition at line 139 of file MlflowFileStore.h.

140 {
141 return run_dir_;
142 }

◆ runId()

const std::string & gpr::track::MlflowRun::runId ( ) const
inlinenodiscardnoexcept

Definition at line 131 of file MlflowFileStore.h.

132 {
133 return run_id_;
134 }

◆ setTag()

void gpr::track::MlflowRun::setTag ( std::string_view key,
std::string_view value )

Definition at line 661 of file MlflowFileStore.cpp.

662{
663 writeText(run_dir_ / "tags" / sanitizeKey(key), std::string(value));
664 if (rest_) pending_tags_.emplace_back(sanitizeKey(key), std::string(value));
665}

◆ start()

std::unique_ptr< MlflowRun > gpr::track::MlflowRun::start ( const Options & options)
static

Nullptr when neither a store nor a tracking URI is given. Throws on an unwritable store; a server that cannot be reached disables streaming with a warning and the local store continues.

Definition at line 386 of file MlflowFileStore.cpp.

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}
MlflowRun(const MlflowRun &)=delete
eon_relax_band_t eon_relax_surface_fn void * user

◆ streaming()

bool gpr::track::MlflowRun::streaming ( ) const
inlinenodiscardnoexcept

Definition at line 143 of file MlflowFileStore.h.

144 {
145 return rest_ != nullptr;
146 }

The documentation for this class was generated from the following files: