What you will be able to do
- Start an MLflow run in a chosen experiment and know where its data lands when no experiment is set
- Choose between log_param, log_params, log_metric and log_metrics, and log a metric history with step
- Attach local files such as plots to a run with log_artifact
- Add manual logging to an autologged run on Databricks
- Log a model with log_model, then reload it by runs:/ or models:/ URI
- Supply a signature, input example and extra pip requirements when MLflow cannot infer them
Key concept
MLflow run — One execution of your training or evaluation code. Everything you log manually (parameters, metrics, tags, artifacts and models) attaches to the active run, and the run belongs to one experiment.
1.Runs, experiments and where logged data lands
Model development is iterative. Two weeks into a project, nobody remembers which learning rate produced the 0.91 AUC unless it was written down at the time. MLflow tracking writes it down for you. Its unit is the run: one execution of model code. A run holds the parameters you set, the metrics you measured, tags that describe it, the output files (artifacts) it produced, and any models it created. An experiment groups related runs, so you can compare and filter them side by side.
On Databricks, the Tracking API sends this data to a hosted tracking server in your workspace, so there is nothing to set up. Two settings control where a run is written. The tracking URI picks the server, and it defaults to the current workspace. The experiment picks the folder of runs on that server. Call mlflow.set_experiment("/Shared/my-experiment") to log to a workspace experiment. If you skip that call, runs from a notebook go to its notebook experiment, which Databricks creates automatically and gives the notebook's name and ID. Only runs started inside a notebook can be logged to a notebook experiment. Runs from jobs or the API need a workspace experiment.
mlflow.start_run() opens a run. Wrap it in a with block and the run ends automatically when the block exits. If you call it without with, you have to close the run yourself with mlflow.end_run(). Every logging call inside the block writes to that run.
Checkpoint 1 of 9· Fill the gap
A training script runs as a scheduled job, so its runs cannot go to a notebook experiment. Which call completes this line so that the runs go to a shared workspace experiment?
mlflow. ? ("/Shared/my-experiment")The experiment setting chooses which folder of runs on the tracking server receives the data. You set it with mlflow.set_experiment. set_tracking_uri chooses the server, which already defaults to the current workspace, and it does not choose an experiment. Runs from jobs or the API need a workspace experiment because only runs started in a notebook can use a notebook experiment.
Source: docs.databricks.com2.Parameters versus metrics, and logging a metric history
Parameters and metrics are both key-value pairs, but they answer different questions. A parameter records an input you chose, such as max_depth=8. It is written once per run. A metric records a measured result, such as validation accuracy. A metric can be written many times, and each value can carry a step. That step is what turns a single number into a history the run page can plot. A per-epoch value logged with log_param gives you a single parameter, not a chart.
| Call | Records | Typical use |
|---|---|---|
| mlflow.log_param(key, value) | One input setting | A single hyperparameter |
| mlflow.log_params({...}) | Several input settings in one call | All hyperparameters of a fit, passed as a dictionary |
| mlflow.log_metric(key, value, step=...) | One measured value, optionally at a step | Validation accuracy each epoch |
| mlflow.log_metrics({...}) | Several measured values in one call | rmse, mae and r2 after evaluation |
The batch forms take a dictionary, with one key per parameter or metric. Passing three hyperparameters to log_params writes three separate parameters. Passing the same dictionary as the value of one log_param call writes a single parameter whose value is the whole dictionary. You cannot then filter or compare runs on max_depth alone. log_metrics does not take parameters either. Logging hyperparameters as metrics makes the inputs look like results.
For a training loop, call log_metric once per iteration and pass the iteration number as step. In the PyTorch example below, accuracy is logged at the current epoch, so the run builds one point per logged epoch. In MLflow 3 the same call can also link the metric to a logged model through model_id and to the dataset it was measured on.
# Log metric on training dataset at step and link to LoggedModel
mlflow.log_metric(
key="accuracy",
value=compute_accuracy(scripted_model, X_train, y_train),
step=epoch,
model_id=model_info.model_id,
dataset=train_dataset
)Checkpoint 2 of 9· Check yourself
An engineer wants the run page to plot validation accuracy across 20 training epochs. Inside the loop they call mlflow.log_param("val_acc", acc). What should they call instead?
A parameter records an input and is written once per run, so it cannot hold a history. A metric can be written many times. When each value is logged with the epoch as its step, the run builds a history that the run page can plot.
“# Log metric on training dataset at step and link to LoggedModel”Source: docs.databricks.com
Checkpoint 3 of 9· Exam question
A data scientist is training a scikit-learn classifier over 20 epochs inside a with mlflow.start_run(): block on Databricks and wants the MLflow UI to plot how validation accuracy changes across epochs, not just show a single final number. Which manual logging call, placed inside the training loop, achieves this?
Correct answer: A — Call mlflow.log_metric("val_accuracy", value, step=epoch) once per epoch, passing the epoch number as step so the metric history builds one point per epoch.
- A. This is correct because passing an explicit
stepvalue on each call is exactly how MLflow builds a per-step metric history for a key, which the UI then renders as a trend line across epochs. - B. This is incorrect because omitting
steplogs every call at the default step of 0, so repeated calls create multiple points stacked at the same step rather than a clean per-epoch trend. - C. This is incorrect because parameters are meant for static configuration values, are not designed to accept repeated updates to the same key across a run, and are not charted as a time series in the UI.
- D. This is incorrect because uploaded files are stored as opaque artifacts; MLflow does not parse artifact contents and turn them into interactive metric charts.
Checkpoint 4 of 9· Exam question
After fitting a RandomForestClassifier with n_estimators=200, max_depth=8, and min_samples_leaf=4, a Databricks user wants to record all three hyperparameters to the active MLflow run with a single API call instead of three separate calls. Which call does this correctly?
Correct answer: A — mlflow.log_params({"n_estimators": 200, "max_depth": 8, "min_samples_leaf": 4}), passing a dictionary so all three key-value pairs are written to the run in one batched call.
- A. This is correct because
log_paramsis built specifically to batch multiple hyperparameter key-value pairs into the active run in one call, keeping each hyperparameter individually searchable. - B. This is incorrect because tuning configuration like
n_estimatorsandmax_depthare hyperparameters, not measured outcomes, so logging them as metrics misrepresents what they track and how the UI groups them. - C. This is incorrect because it collapses three distinct, individually searchable hyperparameters into a single opaque string value under one key, losing the ability to filter or compare runs by each hyperparameter.
- D. This is incorrect because
log_artifactexpects a path to a local file on disk, not a JSON string, and the resulting file would not be indexed as searchable run parameters.
3.Attaching files with log_artifact
Use an artifact for any output that is not a single number: a ROC curve image, a confusion matrix, a CSV of predictions. Save the file to local disk first, then call mlflow.log_artifact(path) to upload it to the run's artifact store. It then appears in the Artifacts tab of the run page. The getting-started example does exactly this after autologging has already handled the model, so you can see the manual calls that fill the gaps.
# The AUC score on test data is not automatically logged, so log it manually
mlflow.log_metric("test_auc", roc_auc)
# Log the ROC curve image file as an artifact
mlflow.log_artifact("roc_curve.png")Artifacts are stored as a directory tree, and each file has a path relative to the run's root artifact directory. Add artifact_path="plots" to log_artifact to put the file in a plots subfolder, which keeps figures apart from data files and models. log_artifact uploads one file. Its plural sibling, log_artifacts, uploads the contents of a whole local directory. A metric holds a number, not a file path, and a PNG is not a model, so neither log_metric nor log_model will store an image.
Checkpoint 5 of 9· Check yourself
After evaluating a classifier, a data scientist saves a confusion-matrix plot to confusion_matrix.png on local disk. They want it to show up in the Artifacts tab of the active run. Which call does that?
Files that are not single numbers, such as plots, are uploaded with log_artifact. The artifact_path argument places the file in a plots subfolder of the run's artifact directory. A metric holds a number, not a file path. A parameter records an input setting. log_model stores a model, and a PNG is not a model.
“to log additional artifacts such as CSV files or plots, use the MLflow logging API.”Source: docs.databricks.com
Checkpoint 6 of 9· Exam question
A model evaluation script on Databricks saves a confusion matrix as confusion_matrix.png to local disk and needs it attached to the current MLflow run under an artifact subfolder named plots, so it appears grouped separately from other run files in the UI. Which call correctly does this?
Correct answer: A — mlflow.log_artifact("confusion_matrix.png", artifact_path="plots"), uploading the single local file into the plots subdirectory of the run's artifact store.
- A. This is correct because
log_artifactuploads exactly one local file, and itsartifact_pathargument places that file under the named subdirectory within the run's artifact store. - B. This is incorrect because the roles are reversed:
log_artifactsexpects a local directory of files, whilelog_artifactis the one that accepts a single file path. - C. This is incorrect because
log_metricrequires a numeric value and an integerstep, so passing a file path string and a folder name asstepdoes not match the expected types. - D. This is incorrect because
log_modelexpects a fitted model object paired with a supported flavor module, not an arbitrary image file, so it cannot be used to store a PNG.
4.Adding manual logging to an autologged run
Autologging is the quickest way to start tracking. Manual logging covers what autologging misses, such as a metric computed on held-out test data or a custom plot. You can combine the two in one run, as long as you open the run in the right order. Turning on Databricks Autologging is not enough once you open your own run with start_run. To get both kinds of logging in that run:
- Call
mlflow.autolog(exclusive=False). - Open a run with
mlflow.start_run(). - Log pre-training values such as parameters.
- Train the model.
- Log post-training values such as test metrics.
- End the run, or let the
withblock end it for you.
import mlflow
mlflow.autolog(exclusive=False)
with mlflow.start_run():
mlflow.log_param("example_param", "example_value")
# <your model training code here>
mlflow.log_metric("example_metric", 5)Leave exclusive=False set. With it, your manual calls write into the same run as the autologged content instead of being kept apart.
Checkpoint 7 of 9· Put it in order
Your workspace has Databricks Autologging turned on. You want one run that holds the autologged content plus a parameter and a test metric that you log yourself. Put these steps in order.
- 1.End the run with mlflow.end_run() if you did not open it in a with block
- 2.Call mlflow.autolog(exclusive=False)
- 3.Open a run with mlflow.start_run()
- 4.Train the model in a framework that Databricks Autologging supports
- 5.Log post-training values, such as a test metric with mlflow.log_metric()
- 6.Log pre-training values, such as a parameter with mlflow.log_param()
Databricks Autologging does not apply to runs opened with mlflow.start_run(), so call mlflow.autolog(exclusive=False) before you open the run. Inputs are logged before training and results after it. Close the run with end_run unless a with block closes it for you.
“Databricks Autologging is not applied to runs created using the MLflow fluent API with mlflow.start_run(). In these cases, you must call mlflow.autolog()”Source: docs.databricks.com
Sources6
5.Logging a model and loading it back by URI
To log a model, use the call for the model's library, called its flavor: mlflow.sklearn.log_model, mlflow.pytorch.log_model, and so on. Use mlflow.pyfunc.log_model for code that has no built-in flavor. In MLflow 3, log_model creates a LoggedModel, an object of its own with a unique model_id and its own parameters and metrics. Earlier versions stored the model as one more artifact of the run. The LoggedModel stays linked to the run that produced it, and you can view all of an experiment's logged models on its Models tab.
## Log the model
model_info = mlflow.sklearn.log_model(
sk_model=lr,
name="elasticnet",
params={
"alpha": 0.5,
"l1_ratio": 0.5,
},
input_example = train_x
)
# Inspect the LoggedModel and its properties
logged_model = mlflow.get_logged_model(model_info.model_id)
print(logged_model.model_id, logged_model.params)You reload a model by URI with mlflow.<flavor>.load_model(uri), or with mlflow.pyfunc.load_model(uri) to get a generic predict interface. The URI tells MLflow where to find the model.
| URI form | Points to |
|---|---|
| runs:/{run_id}/{model-path} | A model logged inside a specific run, addressed relative to that run |
| models:/{model_id} | An MLflow 3 LoggedModel, addressed by its unique ID |
| models:/{model_name}/{model_stage} | A registered model in the legacy workspace registry, addressed by stage |
| dbfs:/Volumes/catalog_name/schema_name/volume_name/... | A model stored in a Unity Catalog volume path |
model_loaded = mlflow.pyfunc.load_model(
'runs:/{run_id}/model'.format(
run_id=run.info.run_id
)
)Registered models are also addressed with models:/ URIs. In MLflow 3 you register a logged model by passing its models:/{model_id} URI. Registering it under a three-level Unity Catalog name is covered in registering models with the Client API, and loading a model by alias in champion and challenger aliases.
Checkpoint 8 of 9· Match them up
Match each URI form you can pass to load_model with the model it points to.
Tap a term, then the definition that fits it.
A runs:/ URI finds the model through the run that logged it. models:/{model_id} finds an MLflow 3 LoggedModel by its unique ID, which exists only in MLflow 3. models:/{name}/{stage} finds a registered model by stage in the legacy workspace registry. A dbfs:/Volumes path points to files in a Unity Catalog volume.
“a model path (such as models:/{model_id}) (MLflow 3 only)”Source: docs.databricks.com
6.Signature, input example and pip requirements
A logged model has to run somewhere other than the notebook that trained it, such as a serving endpoint or a batch job on a fresh cluster. Three pieces of metadata make that possible. The signature describes the model's inputs and outputs. The input example is a sample of real input data. The requirements list the packages the model needs. For built-in flavors, MLflow records the library version itself. Every log_model call also writes requirements.txt and conda.yaml files next to the model.
Pass these to log_model yourself when MLflow cannot work them out. A signature can be built with mlflow.models.infer_signature(model_input=..., model_output=...) and passed as signature=. Pass sample input as input_example=, as in the scikit-learn example above. Autologging is no substitute here: its default configuration logs signatures but sets log_input_examples=False.
Dependencies are where most serving failures start. For a library without a built-in flavor, mlflow.pyfunc.log_model tries to infer requirements, and older MLflow versions can miss some. Add the missing package with extra_pip_requirements, and pin it exactly, for example f"nltk=={nltk.__version__}" rather than nltk. pip_requirements (and conda_env) also exist, but they replace the whole inferred list. Use them to add one package and you lose every dependency MLflow had detected.
| Parameter | Effect | When it wins |
|---|---|---|
| extra_pip_requirements | Adds packages to the inferred list | MLflow missed one or two libraries |
| pip_requirements | Replaces the inferred list entirely | You must control the full environment yourself |
| code_paths | Stores local .py or wheel files with the model and adds them to the Python path on load | Your code depends on files you cannot pip install |
| artifacts (pyfunc) | Attaches extra files, such as a list of non-Python dependencies | Java, R or native packages that MLflow does not detect |
Checkpoint 9 of 9· Match them up
A pyfunc model is failing in serving because of how its dependencies were logged. Pair each log_model parameter with the situation it is meant for.
Tap a term, then the definition that fits it.
extra_pip_requirements adds to the inferred list. pip_requirements replaces that list, so using it to add one package drops everything MLflow detected. code_paths packages local code that you cannot pip install. The pyfunc artifacts argument attaches extra files, such as a list of non-Python dependencies.
“You can also overwrite the entire set of requirements with the conda_env and pip_requirements parameters, but doing so is generally discouraged”Source: docs.databricks.com
Sources
(9)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/mlflow/trackingOfficial docs
“An experiment is a collection of related runs.”
↩︎ Runs, experiments and where logged data lands“If no active experiment is set, runs are logged to the notebook experiment.”
↩︎ Runs, experiments and where logged data lands“Only MLflow runs initiated within a notebook can be logged to the notebook experiment.”
↩︎ Runs, experiments and where logged data lands“the number of total parameters, tags, and metric steps for all existing and new runs”
↩︎ Parameters versus metrics, and logging a metric history“to log additional artifacts such as CSV files or plots, use the MLflow logging API.”
↩︎ Attaching files with log_artifact“A run is a single execution of model code. During an MLflow run, you can log model parameters and results.”
↩︎ Key concept - 2.
“A notebook experiment shares the same name and ID as its corresponding notebook.”
↩︎ Runs, experiments and where logged data lands - 3.https://docs.databricks.com/aws/en/mlflow/runsOfficial docs
“model parameters and metrics saved as key-value pairs, tags for run metadata”
↩︎ Parameters versus metrics, and logging a metric history“Artifacts saved from the run are available in the Artifacts tab.”
↩︎ Attaching files with log_artifact“In MLflow 3, models are now their distinct first-class object rather than being logged as run artifact.”
↩︎ Logging a model and loading it back by URI - 5.
“Filter artifacts matching this path (a relative path from the root artifact directory).”
↩︎ Attaching files with log_artifact - 6.
“Call mlflow.autolog() with exclusive=False.”
↩︎ Adding manual logging to an autologged run“You can wrap this call in with mlflow.start_run(); when you do this, the run is ended automatically after it completes.”
↩︎ Adding manual logging to an autologged run“log_input_examples=False,”
↩︎ Signature, input example and pip requirements“In these cases, you must call mlflow.autolog() to save autologged content to the MLflow run.”
↩︎ Exam trap 2“Databricks Autologging is not applied to runs created using the MLflow fluent API with mlflow.start_run().”
↩︎ Prediction“Databricks Autologging is not applied to runs created using the MLflow fluent API with mlflow.start_run(). In these cases, you must call mlflow.autolog()”
↩︎ Checkpoint - 7.https://docs.databricks.com/aws/en/mlflow/modelsOfficial docs
“To log a model to the MLflow tracking server, use mlflow.<model-type>.log_model(model, ...).”
↩︎ Logging a model and loading it back by URI“a run-relative path (such as runs:/{run_id}/{model-path})”
↩︎ Logging a model and loading it back by URI“When you log a model, MLflow automatically logs requirements.txt and conda.yaml files.”
↩︎ Signature, input example and pip requirements“a model path (such as models:/{model_id}) (MLflow 3 only)”
↩︎ Checkpoint - 8.
“use mlflow.<model-flavor>.log_model() to create a LoggedModel that ties together all of its critical information using a unique ID.”
↩︎ Logging a model and loading it back by URI“step=epoch,”
↩︎ Exam trap 1“# Log metric on training dataset at step and link to LoggedModel”
↩︎ Checkpoint - 9.
“you can specify additional dependencies with the extra_pip_requirements parameter in the log_model command.”
↩︎ Signature, input example and pip requirements“Be sure to log the requirements with the exact library version”
↩︎ Signature, input example and pip requirements“doing so is generally discouraged because this overrides the dependencies which MLflow picks up automatically”
↩︎ Exam trap 3“You can also overwrite the entire set of requirements with the conda_env and pip_requirements parameters, but doing so is generally discouraged”
↩︎ Checkpoint