Sub topic 5
Logging artifacts: files, plots and data
Parameters, metrics and tags are small values stored in the backend store. Many things you want to keep from a run don't fit that shape: a confusion matrix image, a CSV of predictions, a config file, a fitted preprocessing object. MLflow stores these as artifacts. This chapter covers how to log them and how to read them back. It also covers the edge cases that cause lost or confusing files.
This chapter assumes you can start the local tracking server from earlier in the tutorial and that you know how mlflow.start_run() works. It also assumes you have used matplotlib and pandas.
What counts as an artifact
An artifact is any file or directory attached to a run. MLflow stores the bytes in the artifact store and records only the run's artifact location in the backend store. The artifact store can be a local directory, S3, Azure Blob Storage, Google Cloud Storage or a shared filesystem.
| Kind of information | API | Stored in | Good for |
|---|---|---|---|
| Parameter | `log_param` | Backend store | Inputs you chose, such as `C` |
| Metric | `log_metric` | Backend store | Numbers you compare, optionally per step |
| Tag | `set_tag` | Backend store | Labels for filtering, such as `stage` |
| Artifact | `log_artifact` and relatives | Artifact store | Files, plots, tables, models |
The split has a practical consequence. You can query parameters, metrics and tags with search_runs. You cannot query the contents of an artifact. If you will want to filter by a value later, log it as a metric or tag as well, not only inside a JSON file.
Where artifact bytes go
When you call an artifact function, the client writes to the artifact location of the active run. The tracking server only hands the client that location.
With the server from the setup chapter, --default-artifact-root ./mlartifacts is a relative local path. A client that writes directly to it resolves the path on its own machine. A script launched from another working directory, or from another machine, can write to a different location than you expect, or fail. For anything beyond a single laptop, use an absolute path or an object store URI. Alternatively, start the server with --artifacts-destination and let it proxy uploads. When a client writes directly to S3 or similar storage, it needs its own credentials for that storage.
Logging existing files and directories
mlflow.log_artifact(local_path, artifact_path=None) copies one file into the run. mlflow.log_artifacts(local_dir, artifact_path=None) copies a whole directory tree. The optional artifact_path is a subdirectory inside the run's artifact location, not a path on your disk.
import tempfile
from pathlib import Path
import mlflow
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-artifacts-demo")
with mlflow.start_run(run_name="files-demo"):
with tempfile.TemporaryDirectory() as tmp:
config = Path(tmp) / "config.yaml"
config.write_text("model: logreg\nC: 1.0\n")
mlflow.log_artifact(str(config)) # run root: config.yaml
mlflow.log_artifact(str(config), "configs") # configs/config.yaml
report_dir = Path(tmp) / "report"
report_dir.mkdir()
(report_dir / "summary.txt").write_text("accuracy looks fine\n")
(report_dir / "notes.txt").write_text("no scaling applied\n")
mlflow.log_artifacts(str(report_dir), "reports") # reports/summary.txt, reports/notes.txtTwo details matter here. log_artifacts copies the contents of the directory, not the directory itself, so the report folder name does not appear in the run. The copy also happens before the with tempfile block exits, so the temporary files can safely disappear afterward.
Logging objects without writing files yourself
For common cases, MLflow writes the temporary file for you. In each call the second argument is the file name inside the run, and its extension decides the format.
mlflow.log_dict(dictionary, "config.json")serializes a dictionary as JSON or YAML, depending on the extension.mlflow.log_text("text", "notes.txt")saves a string.mlflow.log_figure(fig, "plots/curve.png")saves a matplotlib or Plotly figure.mlflow.log_image(array_or_pil_image, "samples/img.png")saves a NumPy array or PIL image.mlflow.log_table(data, "tables/preds.json")saves a dict or pandas DataFrame as a JSON table that the UI can show as a grid.
These calls are the least error-prone option. They create the file, upload it and clean up, so you never leave stray files in the working directory.
A complete example
The script below trains a classifier and logs a plot, a table, a raw CSV, a dictionary and a dataset record.
import tempfile
from pathlib import Path
import matplotlib
matplotlib.use("Agg") # no display needed
import matplotlib.pyplot as plt
import mlflow
import mlflow.data
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-artifacts")
X, y = load_iris(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
with mlflow.start_run(run_name="logreg-artifacts") as run:
model = LogisticRegression(max_iter=200).fit(X_train, y_train)
preds = model.predict(X_test)
mlflow.log_metric("test_accuracy", model.score(X_test, y_test))
# 1. A plot
disp = ConfusionMatrixDisplay.from_estimator(model, X_test, y_test)
mlflow.log_figure(disp.figure_, "plots/confusion_matrix.png")
plt.close(disp.figure_)
# 2. A table the UI can render
results = X_test.copy()
results["y_true"] = y_test
results["y_pred"] = preds
mlflow.log_table(results, "tables/test_predictions.json")
# 3. The same data as a CSV file
with tempfile.TemporaryDirectory() as tmp:
csv_path = Path(tmp) / "test_predictions.csv"
results.to_csv(csv_path, index=False)
mlflow.log_artifact(str(csv_path), "predictions")
# 4. A dictionary
mlflow.log_dict({"features": list(X.columns), "n_train": len(X_train)}, "data_info.json")
# 5. Dataset lineage (an input record, not a file in the artifact store)
train_df = X_train.assign(target=y_train)
dataset = mlflow.data.from_pandas(train_df, targets="target", name="iris-train")
mlflow.log_input(dataset, context="training")
print("Run ID:", run.info.run_id)
print("Artifact URI:", mlflow.get_artifact_uri())Step 5 is different from the others. log_input records which dataset the run used, including its name, schema and a content digest. It does not upload the data. To keep a copy of the actual rows, log a file as in step 3.
Reading artifacts back
In the UI, open the run and choose the Artifacts tab. Images and text render inline, and tables logged with log_table appear as grids. In code, list and download with the run ID.
import mlflow
from mlflow import MlflowClient
mlflow.set_tracking_uri("http://127.0.0.1:5000")
client = MlflowClient()
run_id = "PASTE_RUN_ID_HERE" # printed by the previous script
for item in client.list_artifacts(run_id, "plots"):
print(item.path, item.is_dir, item.file_size)
local_path = mlflow.artifacts.download_artifacts(
run_id=run_id,
artifact_path="plots/confusion_matrix.png",
dst_path="downloads",
)
print("Saved to", local_path)
info = mlflow.artifacts.load_dict(f"runs:/{run_id}/data_info.json")
print(info["features"])list_artifacts is not recursive. It returns the entries directly under the path you give, and you call it again for each directory. The runs:/<run_id>/<path> URI works wherever MLflow accepts an artifact URI, which makes it a stable way to refer to a file without knowing the storage backend.
Edge cases and common errors
- No active run starts one for you. Calling
mlflow.log_artifactoutside awith mlflow.start_run()block creates a run implicitly. That run stays open until the process exits. Always wrap logging in an explicit run. - Same name, same path, overwritten. Logging
metrics.jsontwice to the same location in the same run replaces the first copy. Artifacts are not versioned within a run. Include the epoch or a suffix in the file name if you need history, such asplots/loss_epoch_10.png. artifact_pathmust be relative. Absolute paths and..segments are rejected. Useplots/curve.png, not/tmp/plots/curve.png.- A missing local file raises an error.
log_artifactchecks that the source exists when you call it. Write and close the file first. A file that is still buffered may upload truncated. - Figures leak memory.
log_figuredoes not close the figure. In a loop, callplt.close(fig)or memory grows with each epoch. - Large files slow the run. Uploads happen synchronously in the training process. Log a checkpoint every epoch only if you need it. Log final or best checkpoints instead, and keep per-step data as metrics.
- Artifacts survive a failed run. Files uploaded before an exception stay in the store. This helps debugging, but it also means failed runs consume storage until you delete them.
- Deleting a run does not always delete files. In the default setup, deleting a run in the UI marks it deleted in the backend store. The artifact files stay until you run
mlflow gcagainst the server's stores. Check retention rules before you log sensitive data.
Choosing between a file, a table and a metric
Use a metric when you want to sort, filter or chart a number across runs. Use a tag for a short label you will filter on. Use log_table or a CSV for row-level data that you inspect by eye. Use log_figure for anything that is easier to understand visually than numerically. A common pattern is to log the same fact twice: the final accuracy as a metric for querying, and a full classification report as a text artifact for reading.
Exercise
A teammate logs mlflow.log_artifact("results.csv") in every epoch of a training loop, and the final run contains only the last epoch's results. Why, and what are two ways to keep each epoch's file?
Show answer
Each call writes to the same location in the run (results.csv at the artifact root), and artifacts are not versioned within a run, so each upload replaces the previous one. Fix it by giving each epoch a distinct file name such as results_epoch_3.csv, or by using a distinct artifact_path such as epochs/3. If the goal is only a number per epoch, log it with log_metric(..., step=epoch) instead.
Exercise
You call mlflow.log_artifacts("report", "reports") where the local folder report contains summary.txt. What is the path of the file inside the run, and how would you list it with MlflowClient?
Show answer
The path is reports/summary.txt. log_artifacts copies the contents of the folder, not the folder name, into the reports subdirectory. List it with client.list_artifacts(run_id, "reports"), which returns an entry whose path is reports/summary.txt.
Exercise
log_input was called with a pandas dataset. A teammate later tries to download the training rows from that run's artifacts and finds nothing. Explain why, and what you would log to make the rows available.
Show answer
log_input records dataset metadata (name, schema, digest, context) as an input of the run. It does not upload the data to the artifact store. To make the rows retrievable, also save them to a file and log it, for example with df.to_csv(path) followed by mlflow.log_artifact(path, "data"), or use mlflow.log_table.