Sub topic 10
Limiting lock-in with a thin tracking interface
This chapter assumes you can instrument a script with MLflow or Weights & Biases (W&B), as in the earlier chapters on each tool. It also assumes you know Python's typing.Protocol and context managers. By the end you will have a small, tested tracking layer. Training code will call it instead of calling a vendor SDK directly.
What lock-in means for trackers
Switching trackers is rarely blocked by your history of runs. Most tools can export parameters and metrics, and old runs can stay in the old system. The real cost is the code you wrote against the vendor's API, scattered across training scripts, notebooks, and pipeline steps.
A migration then means editing every one of those files, re-testing them, and retraining models to confirm that the logged numbers still match. Lock-in comes in three layers:
| Layer | Example | How hard to remove |
|---|---|---|
| Call sites | `mlflow.log_metric(...)` in 40 scripts | Low if wrapped early, high if not |
| Semantics | W&B `config` updates versus MLflow immutable params | Medium. Behavior differs, not just names |
| Features | Registry aliases, sweeps, report dashboards | High. No thin interface hides these |
A thin interface addresses the first layer well and the second partly. It does not address the third. Section "What to keep out of the interface" covers that limit.
The shape of the layer
Training code depends on a small Tracker interface. Each tool gets an adapter that implements it. A factory picks the adapter at run time from configuration.
Keep the interface to what every tracker does the same way. The data model chapter listed it: parameters, metric series with steps, tags, and files. Anything beyond that tends to differ between tools.
The interface and a test adapter
Save this as tracking.py. The MemoryTracker stores everything in plain Python objects. It lets you test training code without a server or network access.
import os
import re
from contextlib import contextmanager
from typing import Iterator, Mapping, Protocol
class Tracker(Protocol):
def log_params(self, params: Mapping[str, object]) -> None: ...
def log_metric(self, name: str, value: float, step: int) -> None: ...
def set_tags(self, tags: Mapping[str, str]) -> None: ...
def log_file(self, path: str) -> None: ...
def finish(self, failed: bool = False) -> None: ...
class MemoryTracker:
"""Records calls in memory. Used in unit tests and dry runs."""
def __init__(self) -> None:
self.params: dict = {}
self.metrics: list = []
self.tags: dict = {}
self.files: list = []
self.finished = False
self.failed = False
def log_params(self, params):
self.params.update(params)
def log_metric(self, name, value, step):
self.metrics.append((name, value, step))
def set_tags(self, tags):
self.tags.update(tags)
def log_file(self, path):
self.files.append(path)
def finish(self, failed=False):
self.finished = True
self.failed = failed
@contextmanager
def track_run(tracker: Tracker) -> Iterator[Tracker]:
"""Always closes the run, and marks it failed if the body raises."""
try:
yield tracker
except BaseException:
tracker.finish(failed=True)
raise
else:
tracker.finish()The track_run helper matters more than it looks. A script that crashes without closing its run leaves a run stuck in a "running" state in some trackers. Putting the close logic in one place fixes this for every script.
The two real adapters
Add these to the same file. Each adapter imports its SDK inside __init__, so a machine without W&B installed can still use MLflow.
class MlflowTracker:
def __init__(self, experiment: str, run_name: str) -> None:
import mlflow
self._mlflow = mlflow
# The server address comes from the MLFLOW_TRACKING_URI environment variable.
mlflow.set_experiment(experiment)
mlflow.start_run(run_name=run_name)
def log_params(self, params):
self._mlflow.log_params(dict(params))
def log_metric(self, name, value, step):
self._mlflow.log_metric(name, value, step=step)
def set_tags(self, tags):
self._mlflow.set_tags(dict(tags))
def log_file(self, path):
self._mlflow.log_artifact(path)
def finish(self, failed=False):
self._mlflow.end_run(status="FAILED" if failed else "FINISHED")
class WandbTracker:
def __init__(self, project: str, run_name: str) -> None:
import wandb
self._wandb = wandb
self._run = wandb.init(project=project, name=run_name)
def log_params(self, params):
self._run.config.update(dict(params))
def log_metric(self, name, value, step):
self._run.log({name: value}, step=step)
def set_tags(self, tags):
# W&B tags are a flat list of strings, so encode key and value together.
extra = tuple(f"{k}:{v}" for k, v in tags.items())
self._run.tags = tuple(self._run.tags) + extra
def log_file(self, path):
name = re.sub(r"[^A-Za-z0-9_.-]", "_", os.path.basename(path))
artifact = self._wandb.Artifact(name=name, type="output")
artifact.add_file(path)
self._run.log_artifact(artifact)
def finish(self, failed=False):
self._run.finish(exit_code=1 if failed else 0)
def make_tracker(kind: str, project: str, run_name: str) -> Tracker:
if kind == "mlflow":
return MlflowTracker(project, run_name)
if kind == "wandb":
return WandbTracker(project, run_name)
if kind == "memory":
return MemoryTracker()
raise ValueError(f"Unknown tracker kind: {kind!r}")Notice what each adapter had to decide. MLflow has a native tag mapping, but W&B only has a list of strings, so the W&B adapter invents a key:value convention. File upload is a plain call in MLflow but an artifact object in W&B. These small translation choices are the real content of an adapter. Write them down once, in one file, and every script gets the same behavior.
Using it in training code
The training function receives a tracker and never imports a tracking SDK. The backend choice lives in the environment.
import os
from tracking import Tracker, make_tracker, track_run
def train(tracker: Tracker, max_depth: int, learning_rate: float) -> None:
tracker.log_params({"max_depth": max_depth, "learning_rate": learning_rate})
tracker.set_tags({"data_version": "2026-11-01"})
for step, auc in enumerate([0.84, 0.88, 0.91]):
tracker.log_metric("val_auc", auc, step)
if __name__ == "__main__":
kind = os.environ.get("TRACKER", "memory")
with track_run(make_tracker(kind, "churn-model", "baseline")) as t:
train(t, max_depth=6, learning_rate=0.1)Run TRACKER=mlflow python train.py against a local server, or TRACKER=wandb python train.py with a W&B login. Both produce the same parameters, the same val_auc series, and the same tag. A test needs no server at all:
from tracking import MemoryTracker, track_run
from train import train
def test_train_logs_expected_values():
tracker = MemoryTracker()
with track_run(tracker):
train(tracker, max_depth=6, learning_rate=0.1)
assert tracker.params["max_depth"] == 6
assert [m[1] for m in tracker.metrics] == [0.84, 0.88, 0.91]
assert tracker.finished and not tracker.failedWhere adapters stop hiding differences
An interface hides function names, but several behaviors still leak through. Check these before you trust that two backends are interchangeable.
- Parameter mutability. MLflow rejects a second, different value for the same parameter key within a run. W&B
config.updateaccepts changes. A script that re-logs parameters can pass on W&B and fail on MLflow. Enforce "log each parameter once" in your interface and add a check toMemoryTracker. - Step ordering. W&B drops a logged value whose step is lower than the run's current step, with a warning. MLflow accepts steps in any order. If you log several metrics, increment the step consistently, or the W&B history will silently lose points.
- Name and value limits. Both tools restrict metric and parameter names, and they restrict them differently. Both also limit the length of parameter values. Pick a naming convention such as lowercase with underscores and slashes, and validate it in the interface.
- Types. Parameters that are lists, dicts, or numpy scalars may be stringified, flattened, or rejected. Convert to plain strings, ints, and floats at the interface boundary.
What to keep out of the interface
The interface should cover only the portable core. Resist the urge to wrap everything, for three reasons.
- The lowest common denominator problem. If every call must work on every backend, you can use only features all backends share. That discards the features that likely made you choose a tool.
- Wrapping cost. Every wrapped feature needs an adapter per backend, a test, and documentation. Autologging, sweeps, and registry aliases are large surfaces that change between releases.
- Wrong abstractions. If you design an interface around one tool's model and bolt on a second, the second adapter will be awkward. Design the interface after you understand at least two tools.
A practical split:
| Put behind the interface | Use the vendor SDK directly, in isolated modules |
|---|---|
| Parameters, metrics, tags | Autologging and framework callbacks |
| Run start and finish | Model registry stages and aliases |
| Uploading output files | Hyperparameter sweeps |
| Run naming | Dashboards, reports, and alerts |
Vendor-specific code is fine if it lives in a clearly named place, such as integrations/wandb_sweeps.py. A migration then has a visible list of files to rewrite. Hidden vendor calls inside a notebook are the problem. Visible ones in a labeled module are not.
Other ways to limit exposure
The interface is one tool among several. Combine it with these habits:
- Keep run metadata you own. Write a small
run_info.json(git commit, data version, config) as a file output of every run. It is readable without any tracker. - Dual logging during migration. A
FanoutTrackerthat forwards each call to two trackers lets you compare backends on real training runs. This is also a good way to run the trial described in the final chapter. It doubles the logging overhead, and an exception in one backend should not stop the other. - Export on a schedule. Both ecosystems have APIs to read runs back out. Test that the export actually contains what you need before you depend on it.
- Pin and wrap versions. SDK upgrades change behavior. One adapter file means one place to adjust.
class FanoutTracker:
def __init__(self, *trackers):
self._trackers = trackers
def log_params(self, params):
for t in self._trackers:
t.log_params(params)
def log_metric(self, name, value, step):
for t in self._trackers:
t.log_metric(name, value, step)
def set_tags(self, tags):
for t in self._trackers:
t.set_tags(tags)
def log_file(self, path):
for t in self._trackers:
t.log_file(path)
def finish(self, failed=False):
for t in self._trackers:
t.finish(failed=failed)When the layer is not worth it
A thin interface costs a few hundred lines and some discipline. It pays off when several people write training code, when the tool choice is still uncertain, or when you may need to move to self-hosted infrastructure for governance reasons. It pays off less for a solo project with one stable tool, where a direct SDK call is simpler and easier to read. Decide based on how likely a switch is, and how many call sites would need to change.
Exercise
Your team's script logs max_depth=6 at the start of a run, then logs max_depth=8 after adjusting the config. It works on W&B but fails on MLflow. Where should you fix this, and how?
Show answer
Fix it in the interface layer, not by editing each script. Make the Tracker contract "each parameter key is logged once per run", and have MemoryTracker raise an error when a key is logged twice with a different value. Tests then fail on every backend. Fix the script to log the final config once, or log the change as a separate key or tag.
Exercise
A colleague proposes adding register_model(name, alias) to the Tracker interface so the registry is portable too. Give two reasons to be cautious.
Show answer
Registry models differ between tools (MLflow aliases and versions versus W&B registry collections and artifact links), so a shared method would either hide features or behave differently per backend. It also adds an adapter, tests, and maintenance cost for each backend. Keep registry code in a separate, clearly named vendor-specific module instead.