Sub topic 6
Autologging and its limits
This chapter assumes you can log parameters, metrics and artifacts by hand inside a run, that you know what an experiment is, and that a tracking server is running as in the earlier chapters. You should also be comfortable with scikit-learn's fit and score methods.
What autologging does
Autologging is a feature that makes MLflow record a training run without explicit log_param or log_metric calls. You enable it once, and MLflow patches the training functions of a supported library. When your code calls one of those functions, the patch wraps it, reads the estimator's configuration and results, and writes them to the active run.
The call that enables it for scikit-learn is mlflow.sklearn.autolog(). Each supported library has its own version, such as mlflow.xgboost.autolog(), mlflow.pytorch.autolog() and mlflow.keras.autolog(). There is also a generic mlflow.autolog() that turns on every integration whose library is installed.
import mlflow
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
mlflow.set_experiment("iris-autolog")
mlflow.sklearn.autolog()
X, y = load_iris(return_X_y=True)
with mlflow.start_run():
RandomForestClassifier(n_estimators=100, random_state=0).fit(X, y)Run this against your tracking server and open the new run. You will see parameters such as n_estimators and random_state, training metrics, and a logged model artifact, all without a single explicit log call.
What gets captured
For scikit-learn, the default capture covers four things:
- Parameters. The output of
estimator.get_params(), including defaults you never set. This is often more useful than your own logging, because defaults can change between library versions. - Training metrics. Scores computed on the data passed to
fit, such astraining_score,training_accuracy_scoreortraining_f1_scorefor classifiers. - The fitted model. Saved as an MLflow model artifact, with a signature and an input example when MLflow can infer them.
- Tags. Including the estimator class name.
The exact metric names depend on the MLflow version and the estimator type, so check a real run instead of relying on a name from memory.
Which calls are tracked
Autologging patches specific methods. For scikit-learn these are fit, fit_predict and fit_transform on estimators, plus helpers such as cross_val_score and the search classes GridSearchCV and RandomizedSearchCV. It does not patch predict or score. Evaluating a model on a test set through model.score(X_test, y_test) therefore logs nothing by default, unless you use the evaluation option described below.
For search classes, MLflow creates the parent run for the search and logs each candidate as a child run, which connects this chapter to the nested runs chapter later in the plan.
import mlflow
from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
mlflow.set_experiment("iris-autolog-search")
mlflow.sklearn.autolog()
X, y = load_iris(return_X_y=True)
grid = GridSearchCV(SVC(), {"C": [0.1, 1, 10], "kernel": ["linear", "rbf"]}, cv=3)
grid.fit(X, y)Here you did not call start_run. When no run is active, autologging creates one for you and ends it when the patched call returns.
The run lifecycle
Whether you open a run yourself matters.
| Situation | What autologging does |
|---|---|
| A run is active (inside `with mlflow.start_run()`) | Logs into that run. It does not end the run. |
| No run is active | Starts a run, logs, and ends it when `fit` returns. |
| Several `fit` calls inside one active run | Logs all of them into the same run, and later values overwrite earlier ones for the same key. |
The third row is a common source of confusion. Parameters in MLflow are write-once for a given key in a run. If you fit two different models inside one with block, the second fit tries to log n_estimators again with a different value, and MLflow raises an exception about changing an existing parameter value. Metrics are different: logging a metric twice just adds a new history point. The safe pattern is one start_run per model you fit.
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
mlflow.sklearn.autolog()
X, y = load_iris(return_X_y=True)
for C in [0.1, 1.0, 10.0]:
with mlflow.start_run(run_name=f"logreg-C={C}"):
LogisticRegression(C=C, max_iter=200).fit(X, y)Combining autologging with manual logging
Autologging and manual calls can share a run. The usual split is that autologging records everything about training, and you add what it cannot know: the test metric, business tags, and the dataset version.
import mlflow
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
mlflow.set_experiment("iris-autolog-plus-manual")
mlflow.sklearn.autolog()
X, y = load_iris(return_X_y=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="rf-100"):
model = RandomForestClassifier(n_estimators=100, random_state=0).fit(X_train, y_train)
mlflow.log_metric("test_accuracy", model.score(X_test, y_test))
mlflow.set_tag("data_version", "iris-2026-11")The training metrics from autologging are computed on the training data. They describe fit, not generalization. Always add a held-out metric yourself, or you will compare runs on a number that rewards overfitting.
Controlling what is logged
autolog() takes arguments that switch parts of the capture on or off. The ones you will use most are in this table.
| Argument | Effect |
|---|---|
| `log_models` | Whether to save the fitted model as an artifact. Set `False` for large models or many trials. |
| `log_input_examples` | Whether to save a few rows of training input next to the model. |
| `log_model_signatures` | Whether to infer and store the input and output schema. |
| `log_datasets` | Whether to record dataset metadata. |
| `disable` | Turns autologging off for that library. |
| `silent` | Suppresses MLflow's own warnings during autologging. |
| `exclusive` | If `True`, logs only to runs that autologging itself created. |
| `max_tuning_runs` | For search classes, limits how many child runs are created. |
Argument availability differs across MLflow releases, so run help(mlflow.sklearn.autolog) on your installed version.
import mlflow
mlflow.sklearn.autolog(
log_models=False,
log_input_examples=False,
max_tuning_runs=10,
)A large grid search with log_models=True can write one model per candidate. For a grid of several hundred candidates, the artifact store grows quickly, and most of those models will never be used. Capping max_tuning_runs and disabling model saving for sweeps, then re-fitting the winner with logging on, keeps storage reasonable.
To turn autologging off again, call mlflow.sklearn.autolog(disable=True). For mlflow.autolog(), the same argument disables all integrations.
How it works internally
The mechanism is monkey patching. When you call autolog(), MLflow replaces selected methods on the library's classes with wrappers. A wrapper does roughly this:
- Check whether autologging is currently enabled and whether the call is a top-level call.
- Start a run if none is active.
- Log the estimator parameters before calling the original method.
- Call the original
fit. - Log metrics and the model after it returns.
- End the run if the wrapper started it.
Because the patching happens at call time, two consequences follow. Enabling autologging after you have imported and instantiated classes still works, because the patch is on the class. But it only affects code that runs after autolog() returns, so call it near the top of the script, before training.
The "top-level call" check matters because a scikit-learn Pipeline calls fit on each of its steps. Without a guard, every inner fit would also be logged. MLflow tracks nesting depth and logs only the outermost call. As a result, a pipeline run records the pipeline as a whole, and the individual steps appear as parameters with prefixed names such as clf__C.
Limits and failure modes
Autologging is convenient, and it has clear limits. Knowing them tells you when to add manual logging.
It cannot know your intent. It records what the library exposes. It does not know your dataset version, the git commit, the reason for the experiment, or which split is the real test set. Tags such as stage, data_version and git_commit are yours to add.
Training metrics only. As covered above, the default metrics are computed on the data passed to fit. Test and validation metrics need either manual calls or the evaluation features available in newer MLflow releases.
Custom code is invisible. If you write your own training loop in plain NumPy, or call a library that has no integration, nothing is patched and nothing is logged. A PyTorch loop written by hand, without Lightning, is a typical case: mlflow.pytorch.autolog() targets PyTorch Lightning, so a raw loop needs manual log_metric calls with step.
Parameters you passed outside the estimator are missed. Preprocessing choices made before fit, such as how you filled missing values or which rows you dropped, are not part of any estimator's parameters. If they affect results, log them yourself.
Version drift. The set of logged metrics, artifact names and defaults changes between MLflow and library versions. A dashboard or query that depends on an exact autologged metric name can break after an upgrade. Pin versions, and log the important metrics under names you control.
Storage cost. Each autologged run can include the model, an environment file and input examples. Over thousands of runs, this adds up. Set log_models=False where models are disposable.
Failures are quiet. Autologging is designed not to break your training. If logging fails, for example because the tracking server is unreachable, MLflow usually emits a warning and training continues. Check that runs actually appear, especially in unattended jobs. Setting silent=True hides the very warnings that would tell you.
Global state. autolog() changes behavior for the whole process. A library function in another module that calls fit will also be logged if a run is active. In a notebook, re-running the enabling cell is harmless, but forgetting it is on can make unrelated cells create runs.
When to prefer manual logging
Use these criteria to decide.
| Situation | Choice |
|---|---|
| Quick baseline with a supported library | Autologging |
| Grid or random search with scikit-learn | Autologging with `max_tuning_runs`, or manual nested runs |
| Custom training loop or unsupported library | Manual logging |
| Metrics must have stable names across versions | Manual logging for those metrics, autologging for the rest |
| Strict storage budget | Autologging with `log_models=False` |
In most teams the practical answer is a mix: turn autologging on for completeness, then add a small, fixed set of manual calls for the metrics and tags that comparisons depend on.
Checking what was recorded
After a run, verify the capture instead of assuming it. You can fetch the run and print its contents with the client.
import mlflow
run = mlflow.last_active_run()
print(run.info.run_id)
print(sorted(run.data.params)[:5])
print(run.data.metrics)
print(run.data.tags.get("estimator_name"))mlflow.last_active_run() returns the most recent run that was active in this process, which is handy right after training. It returns the run object as it was when autologging finished, so metrics logged later may require fetching the run again with MlflowClient().get_run(run.info.run_id).
Exercise
You enable mlflow.sklearn.autolog() and, inside one with mlflow.start_run(): block, fit a RandomForestClassifier with nestimators=50 and then another with nestimators=200. What problem do you expect, and how do you fix it? Also, why is the logged trainingaccuracyscore a poor basis for choosing between the two models?
Show answer
The second fit tries to log nestimators again with a different value in the same run. MLflow parameters cannot be changed once logged, so it raises an error (and the logged metrics would mix the two fits). Fix it by opening a separate run per model, for example one `with mlflow.startrun(runname=...)` per fit inside a loop. The training accuracy is computed on the data passed to fit, so it measures fit, not generalization, and favors the more overfit model. Compute a held-out metric such as test accuracy and log it manually with mlflow.logmetric.
Exercise
A hand-written NumPy gradient descent loop is running with mlflow.autolog() enabled, and the run shows no parameters or metrics. Why, and what do you do?
Show answer
Autologging only patches supported library functions. A plain NumPy loop calls none of them, so nothing is intercepted. Log manually: call mlflow.logparam for the learning rate and similar settings, and mlflow.logmetric with the step argument inside the loop.