Sub topic 4
Weights & Biases: runs, projects, and the hosted service
This chapter assumes you have read the earlier chapters on the shared tracking data model and on MLflow's architecture. It also assumes you can write a Python training loop and use a terminal. By the end, you should be able to instrument a script with W&B, explain where its data lives, and name the points where W&B differs from MLflow in ways that affect a tool choice.
What W&B is
Weights & Biases (W&B, imported as wandb) is an experiment tracker built around a hosted service. Your script uses a Python client library. The library records run data locally and uploads it to a server, where a web application shows it.
MLflow starts from a server you run yourself, with a backend store and an artifact store you choose. W&B starts from a service that already has both. That difference drives most of the trade-offs later in this chapter.
The object model: entity, project, run
W&B organizes data in three levels.
- Entity is the owner of projects. It is either a personal account or a team. Access control and billing attach to the entity.
- Project is a collection of comparable runs. It is the closest match to an MLflow experiment.
- Run is one execution of your code. It holds the config, the logged metrics, the system metrics, the artifacts it produced or consumed, and metadata such as the git commit and command line.
The table maps these objects to the data model from the earlier chapter.
| Shared concept | MLflow | W&B |
|---|---|---|
| Grouping of comparable runs | Experiment | Project (inside an entity) |
| One execution | Run | Run |
| Hyperparameters | Params | `config` |
| Metric series | Metrics with steps | History, logged with `run.log` |
| Final or best value | Latest value, or computed in a query | `summary`, one value per key |
| Labels | Tags | `tags` list, plus `notes` |
| Files and models | Artifacts, model flavors | `wandb.Artifact` with versions and aliases |
Two differences matter in practice.
configis a dictionary and can be nested. MLflow params are flat string key-value pairs. W&B keeps your types, so you can filter onlearning_rate < 0.05as a number.- Each run has a summary next to its history. By default the summary holds the last logged value of each metric. You can change that per metric, which determines what the runs table shows as a column.
Instrumenting a script
This script logs the same hyperparameters and validation AUC series as the MLflow example in the previous chapter.
import wandb
run = wandb.init(
project="churn-model",
name="baseline",
job_type="train",
tags=["baseline"],
config={
"max_depth": 6,
"learning_rate": 0.1,
"data_version": "2026-11-01",
},
)
run.define_metric("val_auc", summary="max")
for step, auc in enumerate([0.84, 0.88, 0.91]):
run.log({"val_auc": auc}, step=step)
print("best val_auc:", run.summary["val_auc"])
run.finish()The call sequence works like this.
wandb.initcreates the run on the server and returns aRunobject. It reads your API key fromwandb loginor from theWANDB_API_KEYenvironment variable. If you do not passentity, it uses your default entity.configis the place for anything that defines the experiment: hyperparameters, data version, seed. Values placed here are searchable and usable as columns and as sweep inputs.define_metric("val_auc", summary="max")changes the summary for that key from "last value" to "maximum". Without it, the runs table would show the final epoch, which is not always the best one.run.logappends one row to the run history. Each call advances the internal step by one unless you passstep=yourself.run.finish()flushes pending data and marks the run as finished. Without it, a script that exits cleanly still finishes the run at exit. A notebook cell does not exit, so you must callfinishthere.
In place of a tags-only convention for data versions, W&B encourages recording them in config. You can still use tags for coarse labels such as baseline or ablation.
Step handling
The most common W&B bug is mismatched steps. Suppose you log training loss every batch and validation AUC every epoch, each with its own run.log call. Both calls increment the internal step, so the two series drift against each other on a shared x-axis. There are two clean fixes.
- Log all values for one step in a single
run.logcall. - Log your own step counter as a metric, then declare it as the x-axis for the others.
import wandb
run = wandb.init(project="churn-model", name="step-demo")
run.define_metric("epoch")
run.define_metric("val_*", step_metric="epoch")
for epoch in range(3):
for batch in range(100):
run.log({"train_loss": 1.0 / (1 + epoch * 100 + batch)})
run.log({"epoch": epoch, "val_auc": 0.84 + 0.035 * epoch})
run.finish()Here train_loss uses the default step, and every val_* metric is plotted against epoch.
What happens when you call `log`
The client does not send each call over the network as it happens. It writes records to a local directory named wandb/ next to your script, and a background process uploads them in batches. This design has three consequences.
- Logging adds little time to your training loop, because the call returns after the local write.
- A network outage does not kill the run. The client keeps the data locally and retries.
- Data is on the server only after the background process has uploaded it, so the web UI can trail your script by a few seconds.
You can control this behavior with the WANDB_MODE environment variable. It accepts online (the default), offline, and disabled.
WANDB_MODE=offline python train.py
wandb sync wandb/offline-run-*Offline mode is useful on compute nodes without internet access. You train there, then sync the run directory from a machine that can reach the server. Disabled mode turns every call into a no-op, which is helpful in unit tests.
Grouping and resuming runs
Two init arguments help with larger jobs.
groupcollects related runs under one label. Distributed training uses it: each process starts its own run with the samegroup, and the UI shows them together. Cross-validation folds fit the same pattern.idandresumelet a restarted job continue the same run instead of creating a new one. Passresume="allow"and a stableid, for example one derived from your job scheduler's ID. If the run exists, W&B continues it. If not, it creates it.
A run that is killed and restarted without a stable id produces two runs, and your comparison tables then contain a truncated run and a complete one. Setting the id up front avoids that.
Artifacts in a run
A W&B artifact is a versioned collection of files with a name and a type, such as dataset or model. Each time you log an artifact with the same name and different content, W&B stores a new version (v0, v1, and so on). Identical content is deduplicated. You can attach aliases such as latest, candidate, or production to a version. The chapter on artifacts and registries covers lineage and registry workflows. Here we show only how artifacts attach to runs.
import pickle
import wandb
with open("model.pkl", "wb") as f:
pickle.dump({"max_depth": 6}, f)
run = wandb.init(project="churn-model", job_type="train", name="log-model")
artifact = wandb.Artifact(
name="churn-model",
type="model",
metadata={"val_auc": 0.91},
)
artifact.add_file("model.pkl")
run.log_artifact(artifact, aliases=["candidate"])
run.finish()
eval_run = wandb.init(project="churn-model", job_type="evaluate", name="use-model")
used = eval_run.use_artifact("churn-model:candidate")
local_dir = used.download()
print("downloaded to", local_dir)
eval_run.finish()The training run lists the artifact as an output and the evaluation run lists it as an input. That pair of edges is what lets W&B draw a lineage graph. The job_type string is a free label that helps organize those graphs.
Hosting options
The same client library works against three deployment types, selected by the server URL (WANDB_BASE_URL or wandb login --host).
- Multi-tenant cloud: W&B runs the service and your data lives on their infrastructure. Setup takes minutes, and you pay per seat or by usage tier.
- Dedicated cloud: W&B operates a single-tenant deployment for you, typically in a cloud account and region you choose.
- Self-managed: you run the W&B server in your own infrastructure. You own upgrades, the database and object storage, and scaling.
Pricing, tiers, and available regions change, so check W&B's current documentation before you commit to a number. The decision pattern is stable: a hosted tier trades control over data location for the absence of operations work. Chapter 9 covers cost and governance criteria in detail.
Two governance points are specific to W&B.
- Run data, such as config, metrics, and system metadata, goes to the server by default. The client also captures the git state and the command line, and it can save your code. Review these defaults before logging from regulated environments.
- Artifacts can be stored by reference. Instead of uploading a large dataset, you register a pointer to an object in your own bucket, and W&B tracks the URI and checksum. The data stays where it was.
Integrations and the rest of the platform
W&B ships integrations for common frameworks, so that a framework's own logging hook sends metrics for you. For example, PyTorch Lightning has a WandbLogger, and Hugging Face Trainer reports to W&B when you set report_to="wandb". The framework-integrations chapter covers autologging in more detail.
Beyond tracking, the platform includes Sweeps for hyperparameter search, Tables for logging tabular samples such as predictions, Reports for writing shareable documents with live charts, and a Registry for promoting artifacts. Each is useful but ties your workflow to W&B more tightly than plain log calls do.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Browser prompt or "api_key not configured" in CI | No credentials in a non-interactive environment | Set `WANDB_API_KEY` from your secret store |
| Metrics plotted against the wrong x-axis | Several `run.log` calls advancing the step | Log together, or use `define_metric` with `step_metric` |
| Runs table shows the last value, not the best | Default summary is the last logged value | Use `define_metric(..., summary="max")` or `"min"` |
| Duplicate runs after a restart | No stable `id` and `resume` | Pass `id` and `resume="allow"` |
| Run stays "running" in a notebook | `finish()` never called | Call `run.finish()` in the last cell |
| Run missing from the UI on an air-gapped node | Online mode with no network | Use `WANDB_MODE=offline`, then `wandb sync` |
Where W&B fits
W&B suits teams that want a working dashboard, comparison tools, and sharing without running infrastructure, and that accept a hosted or paid self-managed server. It is a weaker fit when your data may not leave your network and you cannot buy a self-managed license, or when you want the storage layout fully under your control. Both points feed into the evaluation criteria in a later chapter.
Exercise
A training job logs train_loss every batch with one run.log call and val_auc every epoch with another. In the W&B charts, the validation curve ends up squeezed into the first part of the x-axis. What is happening, and what are two ways to fix it? Also, which setting would make the runs table show the best val_auc instead of the last one?
Show answer
Each run.log call advances the internal step, so the many per-batch calls push the step counter far ahead of the epoch count, and the validation points are plotted at step values that do not match the training steps. Fix it by logging both metrics in the same run.log call for a given step, or by logging an epoch metric and calling run.define_metric("val_*", step_metric="epoch"). To show the best value in the runs table, call run.define_metric("val_auc", summary="max").
Exercise
Your cluster nodes have no internet access, but the login node does. How do you get runs from the training nodes into W&B, and what environment variable and command do you use?
Show answer
Set WANDB_MODE=offline on the training nodes so the client writes the run to the local wandb/ directory without uploading. Then, from the login node, run wandb sync wandb/offline-run-* (pointing at the copied run directories) to upload the runs.