Sub topic 2
How environments drift and change results
This chapter assumes you can create a Python virtual environment, run pip install, and train a model in PyTorch or scikit-learn. It also assumes you know what a transitive dependency is: a package your requirements don't name but that one of them needs. Later chapters fix the problems described here. This one shows where drift comes from and how to see it.
What drift means
Environment drift is any difference between the environment that produced a result and the environment that tries to reproduce it. The code, the data, and the seed can be identical while the outcome still differs.
Drift happens in two ways:
- Across machines. Your laptop, a teammate's workstation, a CI runner, and a GPU server each have different packages, libraries, and drivers.
- Across time. An unpinned
pip install scikit-learnrun today can install a different version than the same command run six months ago. The machine did not change, but the package index did.
The second kind is easy to miss because nobody edits anything. A new release of a package, or of a package that your package depends on, is enough.
Where drift comes from
The environment is a stack of layers. Each layer can differ independently.
| Layer | Example of what differs | Typical symptom |
|---|---|---|
| Direct Python packages | `scikit-learn` 1.3 versus 1.5 | Changed defaults, removed arguments |
| Transitive packages | `numpy` pulled in at a newer version by another package | Errors in code you did not touch, or small numeric changes |
| Python itself | 3.10 versus 3.12 | Missing wheels, different syntax support |
| System libraries | BLAS/LAPACK builds, `libstdc++`, OpenSSL | Different floating-point results, import errors |
| CUDA userland | CUDA toolkit and cuDNN versions | Different kernels, speed, and numerics |
| GPU driver and hardware | Driver version, GPU model | Failures to start, different kernel selection |
| Operating system | Linux distribution, glibc, macOS versus Linux | Wheels that exist for one platform only |
The upper layers are the ones a lock file can control. The lower layers need a container or an equivalent. Both are covered in later chapters.
How drift changes results
Drift shows up in two ways. Loud failures are easy to notice. Silent changes are the real danger.
Loud failures
A loud failure raises an error. The cause is usually an API that changed between versions. Two real examples:
- scikit-learn renamed the
sparseargument ofOneHotEncodertosparse_outputin version 1.2 and removed the old name in 1.4. Code written for 1.1 raises aTypeErroron 1.4. - PyTorch 2.6 changed the default of
torch.loadtoweights_only=True. A checkpoint that loaded under an older version can fail to load under a newer one if it contains arbitrary pickled objects.
These are annoying, but they stop the run and point at a line of code.
Silent changes
A silent change produces a different number with no error. Common causes:
- Changed defaults. A library alters a default parameter, such as a solver, a tolerance, or a tie-breaking rule. Your code does not mention the parameter, so it changes without any edit on your side.
- Changed algorithms. A new version may use a different implementation internally, for example a different reduction order or a different optimizer step. The model trains, and the metric moves by a small amount.
- Different numeric libraries. NumPy and PyTorch call BLAS libraries (OpenBLAS, MKL, cuBLAS). Different builds, or different CPU instruction sets, can sum numbers in a different order.
- Different GPU kernels. cuDNN can choose different convolution algorithms depending on its version and the GPU model.
Floating-point addition is not associative, so summing the same numbers in a different order can change the last digits:
import numpy as np
rng = np.random.default_rng(0)
x = rng.standard_normal(1_000_000).astype(np.float32)
forward = x.sum(dtype=np.float32)
backward = x[::-1].sum(dtype=np.float32)
print(forward, backward, forward == backward)The two sums usually differ slightly. Both are valid. A library that changes its summation order produces exactly this kind of difference. One tiny difference rarely matters. Millions of them accumulate over a training run, and a small initial gap can grow into a different final model.
Drift over time: the transitive dependency problem
Suppose requirements.txt contains only scikit-learn. Installing it also installs NumPy, SciPy, joblib, and threadpoolctl. You never chose those versions. pip picks the newest ones that satisfy the constraints at the moment you run the install.
When any of these packages releases a new version, the next fresh install picks it up. Your direct dependency list is unchanged, but your environment is not. This is why a project that worked in spring can fail in autumn on a new machine without any commit in between.
Other time-based effects:
- Yanked or deleted releases. A version you used can be marked unavailable, so an old install command resolves to something else.
- Source builds versus wheels. A package without a prebuilt wheel for your Python version and platform is compiled from source, using whatever compiler and system libraries are present.
- Different wheel variants. The same version number can be a CPU build on one platform and a CUDA build on another. For PyTorch, the build you get depends on the package index you use and on the platform.
Making drift visible
Before you can fix drift, you need to see it. A fingerprint script records the facts that matter and can be compared between two environments:
import json
import platform
import sys
from importlib import metadata
def fingerprint() -> dict:
packages = {}
for dist in metadata.distributions():
name = dist.metadata["Name"]
if name:
packages[name.lower()] = dist.version
info = {
"python": sys.version.split()[0],
"platform": platform.platform(),
"machine": platform.machine(),
"packages": dict(sorted(packages.items())),
}
try:
import torch
info["torch_cuda"] = torch.version.cuda
info["cudnn"] = torch.backends.cudnn.version()
info["cuda_available"] = torch.cuda.is_available()
except ImportError:
pass
return info
if __name__ == "__main__":
print(json.dumps(fingerprint(), indent=2))Run it on both machines and compare the output:
python fingerprint.py > env-a.json
# copy the script to the other machine, run it there, and bring the file back
python fingerprint.py > env-b.json
diff env-a.json env-b.jsonEvery line in the diff is a candidate cause. Start with the packages your model code calls most directly, then look at the Python version and the CUDA fields.
What this chapter does not fix
Fixing the environment does not make a run fully reproducible. Seeds, nondeterministic GPU operations, and changes to data are separate causes. Later chapters cover them. Treat environment drift as one cause you can remove, so that any remaining difference points at another cause.
Exercise
A teammate reports that your training script fails with a TypeError on a fresh install, although requirements.txt has not changed since last quarter. It lists only scikit-learn. Name the most likely cause, and say which two pieces of evidence you would collect first.
Show answer
The most likely cause is time-based drift. An unpinned scikit-learn resolves to the newest release at install time, so the teammate got a newer version (or newer transitive dependencies) than you used, and an argument or default changed. Collect first the fingerprint (or pip list) from both environments and diff them for version differences, and the full traceback to see which call raised the error, which tells you which package's API changed.