Sub topic 7
Framework integrations and autologging
Earlier chapters showed manual logging: you call log_param, log_metric and set_tag yourself. This chapter covers the other route, where the tracker hooks into your training framework and records things for you. It assumes you have read the data model chapter (runs, parameters, metrics, artifacts), can train a model with scikit-learn or a deep learning framework, and know what a callback is.
How integrations work
Trackers use three mechanisms to capture data without explicit calls. Knowing which one you are using tells you what is captured, when, and how it can break.
- Monkey-patching (MLflow autolog). Calling
mlflow.sklearn.autolog()wraps methods such asfiton the library's classes. When your code callsfit, the wrapper opens a run if none is active, logs the estimator's parameters, runs the realfit, then logs metrics and the model. - Callbacks and logger classes. Many frameworks have an extension point for logging. Examples are the Hugging Face
Trainerreport_tosetting, the Lightning logger interface, and Keras callbacks. The tracker ships a class that plugs into it. W&B mostly works this way. - Environment-driven configuration. Some integrations read environment variables such as
WANDB_PROJECTorMLFLOW_EXPERIMENT_NAME, so the training script needs no tracker code at all.
MLflow autologging
MLflow has a per-library autolog function. Each one targets a flavor, which is MLflow's term for a library integration, such as mlflow.sklearn, mlflow.xgboost, mlflow.lightgbm, mlflow.tensorflow and mlflow.pytorch. The generic mlflow.autolog() enables every flavor whose library is installed. Prefer the specific call. The generic one turns on logging for libraries you did not intend to track.
The mlflow.pytorch flavor's autolog applies to PyTorch Lightning, not to plain PyTorch loops. A hand-written loop needs explicit logging or a thin wrapper of your own.
The following script assumes the local server from the earlier chapter is running on port 5000.
import mlflow
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("churn-model")
# Patches fit() on scikit-learn estimators. Call it before training.
mlflow.sklearn.autolog(log_models=True)
X, y = make_classification(n_samples=2000, n_features=20, random_state=0)
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.25, random_state=0
)
with mlflow.start_run(run_name="autolog-rf"):
model = RandomForestClassifier(max_depth=6, n_estimators=100, random_state=0)
model.fit(X_train, y_train) # params, training metrics and model are logged here
# Autolog does not know your validation policy, so log it explicitly.
val_auc = roc_auc_score(y_val, model.predict_proba(X_val)[:, 1])
mlflow.log_metric("val_auc", val_auc)
mlflow.set_tag("data_version", "2026-11-01")In the run you should see every constructor parameter of RandomForestClassifier, including defaults you never set, plus training metrics such as training_score. You should also see a serialized model with its environment files under the run's artifacts. Your val_auc and data_version appear because you logged them yourself.
Useful autolog options
| Option | Effect | When to change it |
|---|---|---|
| `log_models` | Saves the fitted model as an artifact | Set `False` for large models or hyperparameter sweeps where storage grows quickly |
| `log_datasets` | Records dataset metadata for the training data | Set `False` if dataset names or schemas are sensitive |
| `disable` | Turns autologging off for that flavor | Use in tests or notebooks where you do not want runs created |
| `exclusive` | Autolog only logs to runs it created itself | Set `True` if you start runs manually and do not want autolog data in them |
| `silent` | Suppresses MLflow's own event logs and warnings during autologging | Useful in production jobs. It also hides diagnostics, so leave it off while debugging |
Exact option sets differ between flavors and MLflow versions. Check the docs for the version you pin.
Search and tuning behavior
With GridSearchCV or RandomizedSearchCV, scikit-learn autologging creates a parent run for the search and child runs for the candidate parameter sets. Sklearn autolog caps the number of child runs it logs through its max_tuning_runs option. A 500-candidate grid does not produce 500 child runs unless you raise that cap. The parent run records the best parameters and the search's scores.
Weights & Biases integrations
W&B has no single switch that patches every library. You call wandb.init once, and each framework integration then forwards that framework's native logging to the active run. The integration is chosen in the framework's own configuration.
For Hugging Face Trainer, you select it with report_to:
import os
from transformers import TrainingArguments
os.environ["WANDB_PROJECT"] = "churn-model" # project name read by the integration
args = TrainingArguments(
output_dir="out",
run_name="baseline",
report_to="wandb",
logging_steps=50,
num_train_epochs=3,
)
# Pass `args` to Trainer(...). The Trainer logs loss, learning rate and eval metrics.Other common W&B entry points follow the same shape.
- PyTorch Lightning:
WandbLoggerfrompytorch_lightning.loggers, passed as theloggerargument ofTrainer. - Keras: callbacks such as
WandbMetricsLoggerfromwandb.integration.keras. - XGBoost and LightGBM: callbacks from
wandb.integration. - scikit-learn: helper functions such as
wandb.sklearn.plot_classifierthat create charts. These are explicit calls, not an automatic patch. - Plain PyTorch:
run.loginside your loop, plus optionallywandb.watch(model)to record gradient and parameter histograms.
W&B also captures system metrics (CPU, memory, GPU utilization) and the console output of the process by default. MLflow can record system metrics too, but you must enable it (mlflow.enable_system_metrics_logging()).
Comparing the two styles
| Aspect | MLflow | Weights & Biases |
|---|---|---|
| Main mechanism | Per-library patching of training methods | Callbacks and loggers, selected per framework |
| Zero-code option | Environment variables for some integrations | Environment variables and `report_to="wandb"` |
| Model capture | Autolog can save the model with its environment | Done through artifacts, usually explicitly |
| Plain training loops | Manual logging | Manual logging, plus `wandb.watch` |
| System metrics | Opt-in | On by default |
What integrations get wrong or hide
Integrations save work, and they also create specific failure modes.
- Implicit runs. With MLflow autolog active and no run open, calling
fitcreates and ends a run for you. A notebook that fits five models then yields five runs with no names or tags. Open the run yourself and tag it. - Double logging. If a Lightning
Trainerhas its own logger and you also enable MLflow autolog, you may record the same metrics twice under different names. Pick one source of truth per metric. - Inconsistent metric names. Each integration invents its own names (
training_score,loss,train/loss,eval_loss). Comparing runs across frameworks in the UI then fails or gives misleading charts. Log your headline metric under one name you control, such asval_auc, in every project. - Version drift. Autolog depends on library internals. A new release of scikit-learn or XGBoost can fall outside the range the MLflow version supports. MLflow typically emits a warning and logs less, rather than failing the job. Pin both libraries and check a run's contents after upgrades.
- Storage growth.
log_models=Trueon every candidate of a sweep stores one model per run. Decide which runs deserve a stored model. - Missing context. Integrations cannot know your data version, the git commit, or why you ran the experiment. These still need tags or config entries from you.
- Distributed training. With multiple processes (for example, DistributedDataParallel), each process can create its own run. Log from rank 0 only, or follow the integration's documented grouping option.
Integrations as a selection criterion
Integration coverage deserves a line in your evaluation, but weigh it by what you actually use.
- List the frameworks your team trains with now and in the next year.
- For each one, check whether the tracker has a maintained integration, and what it records: parameters only, metrics, the model, or system data.
- Run a short training job and inspect the result in the UI. Documentation claims do not tell you whether metric names are usable.
- Identify the gaps and estimate the cost of writing them yourself. A custom loop needs perhaps ten lines of logging calls. A missing integration for a niche library costs more.
Integrations also interact with lock-in. Autolog code is nearly invisible in your scripts, which is convenient, but it ties behavior to one vendor's patching. If you plan a thin interface, as the lock-in chapter describes, use integrations for convenience in experiments and route your key metrics and parameters through your own interface so that switching trackers does not change what you compare.
Summary
Autologging in MLflow patches library methods and logs parameters, metrics and models when training runs. W&B uses framework callbacks and loggers that you select in the framework's configuration. Both save effort, and both leave gaps: implicit runs, duplicate or inconsistently named metrics, storage growth, version drift and silent partial logging. Treat integrations as a convenient baseline, verify what they record, and log decision-critical values yourself.
Exercise
A teammate runs mlflow.sklearn.autolog() at the top of a notebook, then fits eight models in separate cells without calling mlflow.start_run(). Afterwards the experiment shows eight unnamed runs, and none of them has a val_auc metric. Explain both problems and give a fix for each.
Show answer
Autolog opens a run automatically when fit is called and no run is active, and it closes that run when fit returns. That gives eight separate unnamed runs, each ending right after training. Autolog only knows about training-time information, so it logged parameters, training metrics and the model but not a validation metric from your own split. Fix the first problem by wrapping each experiment in with mlflow.start_run(run_name="...") and adding tags. Fix the second by computing validation AUC after fit and calling mlflow.log_metric("val_auc", value) inside the same with block, so it lands in the same run as the autologged data.
Exercise
Your team trains with scikit-learn, a plain PyTorch loop, and Hugging Face Trainer. You are evaluating MLflow and W&B. List what you would check for each framework and what you expect to write by hand.
Show answer
For scikit-learn, check that the tracker records constructor parameters, metrics and the model, and look at how search runs are grouped. MLflow autolog covers this, while W&B needs its sklearn helpers or explicit calls. For the plain PyTorch loop, expect to write logging calls in both trackers, because MLflow's PyTorch autolog targets Lightning and W&B only offers wandb.watch plus run.log. For Hugging Face Trainer, check the report_to setting. Both trackers have integrations, so run a short job and inspect metric names and stored artifacts. In all three cases, log a standardized validation metric name and a data version tag yourself so runs stay comparable across frameworks.