Sub topic 6
Storing files as artifacts
This chapter assumes you can create a run and log parameters and metrics, as covered in the earlier chapters on runs and logging basics. It also assumes you can write a short scikit-learn training script and work in a Databricks notebook. Parameters and metrics describe a run with small values. Many things you want to keep are files: plots, reports, sample predictions, serialized objects. MLflow stores these as artifacts.
What an artifact is
An artifact is a file or directory attached to a run and stored outside the tracking database. The tracking store holds parameters, metrics and tags as rows. Artifacts live in an artifact store, which is file or object storage. Each run has its own artifact directory, and the run's metadata records where it is.
Use this rule of thumb to decide where a value belongs:
| You want to keep | Use | Why |
|---|---|---|
| A number you will sort or filter by | Metric | Searchable and chartable |
| A setting that defines the run | Parameter | Searchable, one value per name |
| A short label | Tag | Searchable, editable after the run |
| A file, plot, table or report | Artifact | Opened or downloaded, not queried |
Logging existing files
Use mlflow.log_artifact when a file is already on the driver's local disk. It copies the file into the run's artifact directory.
import json
import os
import tempfile
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
with mlflow.start_run(run_name="artifacts-demo") as run:
model = LogisticRegression(max_iter=200).fit(X_train, y_train)
report = classification_report(y_test, model.predict(X_test))
with tempfile.TemporaryDirectory() as tmp:
report_path = os.path.join(tmp, "classification_report.txt")
with open(report_path, "w") as f:
f.write(report)
mlflow.log_artifact(report_path, artifact_path="reports")
config_path = os.path.join(tmp, "config.json")
with open(config_path, "w") as f:
json.dump({"max_iter": 200, "test_size": 0.25}, f)
mlflow.log_artifact(config_path)
print(run.info.run_id)The second argument, artifact_path, is a subdirectory inside the run's artifact directory. It is not a file name. The report ends up at reports/classification_report.txt, and the config at the artifact root as config.json. The file name always comes from the local file.
The copy happens when you call the function. If your code changes the file afterward, the stored copy does not change. The temporary directory above is deleted when the with block exits, which is safe because MLflow already has its copy.
Logging a whole directory
mlflow.log_artifacts (plural) uploads the contents of a local directory.
import os
import tempfile
import mlflow
with mlflow.start_run(run_name="artifact-directory"):
with tempfile.TemporaryDirectory() as tmp:
for i in range(3):
with open(os.path.join(tmp, f"sample_{i}.txt"), "w") as f:
f.write(f"example {i}\n")
mlflow.log_artifacts(tmp, artifact_path="samples")The files appear as samples/sample_0.txt and so on. The temporary directory's own name is not part of the stored path. This is a common surprise: you upload the contents, not the folder.
Logging directly from memory
Writing a temporary file first is tedious for small items. MLflow has helpers that take an object and a target file name. The artifact_file argument is the full relative path, including the file name.
| Function | Input | Typical use |
|---|---|---|
| `mlflow.log_text(text, artifact_file)` | A string | Notes, logs, a rendered report |
| `mlflow.log_dict(dictionary, artifact_file)` | A dict | Configs, class labels. The file extension (`.json`, `.yaml`) sets the format |
| `mlflow.log_figure(figure, artifact_file)` | A matplotlib or plotly figure | Plots |
| `mlflow.log_image(image, artifact_file)` | A NumPy array or PIL image | Sample images |
| `mlflow.log_table(data, artifact_file)` | A dict or pandas DataFrame | Per-row predictions you want to browse in the UI |
import matplotlib.pyplot as plt
import mlflow
from sklearn.metrics import ConfusionMatrixDisplay
with mlflow.start_run(run_name="in-memory-artifacts"):
mlflow.log_text("Baseline logistic regression, default C.", "notes/summary.txt")
mlflow.log_dict({"classes": ["setosa", "versicolor", "virginica"]}, "labels.json")
disp = ConfusionMatrixDisplay.from_estimator(model, X_test, y_test)
mlflow.log_figure(disp.figure_, "plots/confusion_matrix.png")
plt.close(disp.figure_)The example reuses model, X_test and y_test from the first snippet, so run that cell first. Closing the figure afterward stops matplotlib from accumulating open figures in a long notebook session.
Viewing and retrieving artifacts
Open the run page in the experiment UI and select the Artifacts section. Text, JSON, images and HTML render inline. Tables logged with log_table display as a grid.
To read artifacts from code, list them first with MlflowClient, then download what you need.
import mlflow
from mlflow import MlflowClient
run_id = run.info.run_id # a run ID from an earlier cell
client = MlflowClient()
for item in client.list_artifacts(run_id):
print(item.path, "(directory)" if item.is_dir else f"{item.file_size} bytes")
local_path = mlflow.artifacts.download_artifacts(
run_id=run_id,
artifact_path="reports/classification_report.txt",
)
with open(local_path) as f:
print(f.read())list_artifacts shows only one directory level. Pass path="reports" as a second argument to look inside a subdirectory. download_artifacts copies the file to the driver's local disk and returns the local path. If you omit artifact_path, it downloads the entire artifact directory for the run, which can be large. You can pass dst_path to choose where the copy goes.
You can also refer to an artifact by URI, in the form runs:/<run_id>/reports/classification_report.txt. Many MLflow functions accept this form, including the model-loading and registration calls you will use later in this tutorial.
Where artifacts live on Databricks
Every experiment has an artifact location, fixed when the experiment is created. A run's artifacts go in a subdirectory of that location named after the run ID. For a notebook experiment, Databricks picks the location for you. For a workspace experiment you can choose it at creation time if your workspace allows it. The location can differ between workspaces and over time, depending on how your administrators have configured storage. Look at the experiment's details, or print mlflow.get_artifact_uri() inside an active run, instead of assuming a path.
import mlflow
with mlflow.start_run():
print(mlflow.get_artifact_uri())Access to artifacts follows experiment permissions. A user who can read the experiment can read its artifacts through MLflow. That has a practical consequence for what you log, covered next.
Gotchas and good habits
- Do not log secrets or personal data. An artifact is readable by everyone with access to the experiment. Sample rows from a training table can contain sensitive columns. Log a sanitized sample, or none.
- Do not store a metric history as a file. If you want to see loss per epoch, call
mlflow.log_metric("loss", value, step=epoch). The UI then draws the curve, andsearch_runscan query the values. A CSV of losses can do neither. - Keep large data out. Artifacts are copied for every run. Logging the full training set in each of 200 tuning trials multiplies storage and slows each run. Log a reference, such as a table name plus a version or timestamp, in a parameter or tag. Keep full datasets in their own governed storage.
- Use unique paths. Two calls that write to the same
artifact_pathand file name in the same run target the same destination. Give files distinct names, for exampleplots/confusion_matrix_epoch_10.png. - Log inside an active run. The fluent API starts a run for you if none is active, and that run is not closed until the notebook session or process ends. Use
with mlflow.start_run():so each run ends when its block does. - Models are artifacts too.
mlflow.sklearn.log_modelwrites a model directory into the run's artifact store, with extra metadata files. The next chapter covers how to log it with a signature and an input example.
Exercise
You train a model for 50 epochs and want to inspect the validation loss at every epoch in the experiment UI and also find the run with the lowest final loss using search_runs. A teammate suggests writing the losses to loss.csv and calling mlflow.log_artifact("loss.csv"). What would you do instead, and what would you still use an artifact for?
Show answer
Call mlflow.log_metric("val_loss", value, step=epoch) inside the training loop. The UI then charts the loss against the step, and search_runs can filter and sort on metrics.val_loss (the last logged value for each run). A CSV artifact supports neither charting nor querying. An artifact is still the right place for a file you want to open or download as-is, such as a plot of the final loss curve logged with mlflow.log_figure, or a text report.
Exercise
A run logs mlflow.log_artifacts("/tmp/out", artifact_path="results"), where /tmp/out contains a.txt and a subdirectory plots/b.png. Which artifact paths exist in the run afterward?
Show answer
results/a.txt and results/plots/b.png. log_artifacts uploads the contents of the directory, preserving its internal structure, under the artifact_path prefix. The name out does not appear in the stored paths.