Sub topic 11
Pinning the environment
This chapter assumes you can create a Python virtual environment, install packages with pip, and read a pyproject.toml. You should also know the repository layout from earlier chapters. The environment is the third input to reproducibility, next to the config and the data.
Why the environment is part of the result
Suppose you keep the code, the config, and the data version fixed. You rerun the training six months later and the accuracy changes by half a point. The usual cause is that pip install scikit-learn pulled a newer release, or that a library you never named directly (a transitive dependency) changed its default behavior.
Pinning means recording the exact versions that produced a result, so anyone can rebuild the same environment. The environment covers more than your direct imports:
- The Python version.
- Direct dependencies, such as
numpyandscikit-learn. - Transitive dependencies, such as
scipyandjoblib, which those packages install. - Native components: the operating system, C libraries, and for GPU work the CUDA and driver versions.
Declared versus locked dependencies
Keep two files with different jobs.
| File | Contains | Written by | Purpose |
|---|---|---|---|
| `pyproject.toml` | Version ranges for direct dependencies | You | States what the code needs |
| Lock file (`requirements.lock`) | Exact versions of every package, with hashes | A tool | Rebuilds the same environment |
Ranges say what the code is compatible with. The lock file says what you actually ran. Do not hand-edit the lock file. Regenerate it when you change the ranges.
[project]
name = "my_project"
version = "0.1.0"
requires-python = ">=3.11,<3.12"
dependencies = [
"numpy>=1.26,<2",
"pandas>=2.1,<3",
"scikit-learn>=1.4,<2",
"pyyaml>=6",
]
[project.optional-dependencies]
dev = ["pytest>=8", "pip-tools>=7"]The requires-python line pins the interpreter to one minor version. A different minor version can change numeric behavior and which wheels are available, so treat it as part of the pin.
Generating and using a lock file
This chapter uses pip-tools. Other tools (uv, Poetry, conda-lock) follow the same declared-then-locked pattern with different commands.
python3.11 -m venv .venv
source .venv/bin/activate
pip install pip-tools
pip-compile --generate-hashes -o requirements.lock pyproject.toml
pip-compile --extra dev --generate-hashes -o requirements-dev.lock pyproject.toml
pip-sync requirements-dev.lock
pip install --no-deps -e .pip-compile resolves the ranges into exact versions and writes them with SHA-256 hashes. pip-sync then makes the environment match the lock file exactly, which includes removing packages that are not listed. That removal is why the editable install of your own package comes after it. --no-deps stops pip from resolving dependencies a second time.
Commit both files. The lock file is the one that matters when you ask whether a result can be reproduced.
What hashes add
With --generate-hashes, pip switches to hash-checking mode and refuses any file whose hash does not match. This protects you in two cases. A maintainer might re-upload a changed file under the same version number. A package index might also serve something you did not expect. Hash mode also requires every dependency to be pinned, so it fails loudly if the lock file is incomplete.
Pins that depend on the platform
A lock file made on one machine may not install on another. Wheels differ by operating system, CPU architecture, and Python version. Some packages also have different dependencies per platform, such as a Windows-only helper. Two practices reduce surprises:
- Generate the lock file on the platform you deploy and train on, or in the container you use for that.
- If a team uses mixed laptops, use a tool that produces a cross-platform lock (
uv pip compile --universal, orconda-lock) and test it on each platform.
GPU stacks are the hardest case. A PyTorch wheel built for one CUDA version needs a compatible driver. Record the CUDA build in the lock file (for example through the +cu121 local version tag or the extra index URL) and write the driver requirement in the README.
When pip is not enough
Pinned Python packages do not pin system libraries. If results depend on a specific BLAS library, libgomp, or CUDA toolkit, pin the layer beneath pip too:
- A Conda environment file with exact builds, or a
conda-lockfile, covers non-Python binaries. - A container image pins the operating system and system libraries. Reference the base image by digest (
FROM python:3.11-slim@sha256:...) and not by a moving tag likelatest.
Pick one primary mechanism. Mixing conda install and pip install into one environment is a common source of silent version changes, because each tool does not know what the other installed.
Recording the environment with each run
Even with a lock file, store what a run really used. A run might happen from an old branch or an environment someone modified by hand. The snapshot below writes the interpreter, platform, and every installed package version to a JSON file. Save it next to the run's metrics, as described in the experiment-tracking chapter.
import json
import platform
import sys
from importlib import metadata
from pathlib import Path
def snapshot_environment():
packages = {}
for dist in metadata.distributions():
name = dist.metadata["Name"]
if name:
packages[name.lower()] = dist.version
return {
"python": sys.version,
"platform": platform.platform(),
"packages": dict(sorted(packages.items())),
}
def write_snapshot(path):
out = Path(path)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(snapshot_environment(), indent=2))
if __name__ == "__main__":
write_snapshot("runs/environment.json")You can diff two snapshots when a result changes and quickly see which package moved.
Checking the environment
Add a cheap check to your test or CI step. After syncing from the lock file, run:
pip checkpip check reports installed packages whose requirements are not satisfied. It catches the case where someone ran an extra pip install that upgraded a shared dependency. In CI, build the environment only from the lock file, never from pyproject.toml alone. Otherwise CI tests a different environment than you trained in.
Common errors
- Pinning only top-level packages. A
requirements.txtwithscikit-learn==1.4.2still letsscipyfloat. Lock the full resolved tree. - A lock file that is never refreshed. Old pins accumulate security issues. Schedule a regular regeneration, and rerun your tests and a baseline training run when you do it.
- Pinning too tightly in a library. Exact pins belong in the lock file of an application or project. If you publish
my_projectfor others to install, keep ranges inpyproject.tomlor you will cause dependency conflicts for users. - Forgetting the interpreter. The same lock file on Python 3.10 and 3.12 can resolve to different wheels.
- Editing the lock file by hand. The hashes will no longer match. Change
pyproject.tomland recompile. - Assuming pins give bit-identical results. Same versions do not guarantee the same numbers. Hardware, thread counts, and nondeterministic GPU operations can still differ. Pinning removes one source of change, and seeding removes another.
Exercises
Exercise
Your teammate says the lock file is redundant because pyproject.toml already lists scikit-learn>=1.4,<2. Give two reasons the lock file is still needed.
Show answer
First, the range allows many versions, so two installs at different times can resolve to different scikit-learn releases. Second, the range says nothing about transitive dependencies such as scipy and joblib, which can also change. The lock file records the exact version of every package (with hashes), so the same environment can be rebuilt later.
Exercise
After pip-sync requirements-dev.lock, import my_project fails even though it worked before. What is the likely cause and the fix?
Show answer
pip-sync removes packages that are not in the lock file, and that includes the editable install of your own project. Run pip install --no-deps -e . after the sync to reinstall it without re-resolving dependencies.
Exercise
A training run on a GPU server gives different accuracy from your laptop, though both use the same lock file. Name two causes that pinned Python packages do not cover.
Show answer
Possible causes include different CUDA or driver versions, different system libraries such as BLAS, a different CPU or GPU architecture, and nondeterministic GPU operations. A container image pinned by digest, or a recorded CUDA build, covers the first group of causes. Seeding and deterministic-mode settings address the last.