Sub topic 16
Checking reproducibility in CI
This chapter assumes you can read a GitHub Actions workflow and that you already have a hash-pinned lock file (requirements.lock or uv.lock) and a Dockerfile that installs from it. If you don't, read the earlier chapters on lock files and Dockerfiles first.
A lock file and a Dockerfile only help while they stay true. Someone edits requirements.in and forgets to recompile. Someone runs pip install inside a running container. A base image tag moves. A CI job catches these problems on every pull request, before they reach a training run.
What CI should verify
CI can't prove that a result is reproducible everywhere. It can check a small set of claims that, if false, make reproducibility impossible.
| Claim | Check | Failure it catches |
|---|---|---|
| The lock file matches the declared dependencies | Recompile and diff, or `uv lock --check` | Edited `requirements.in` or `pyproject.toml` without relocking |
| The lock file installs cleanly | `pip install --require-hashes` or `uv sync --locked` | Missing hashes, yanked packages, unpinned entries |
| The installed set is consistent | `pip check` | Conflicting requirements among resolved packages |
| The image builds from the repository alone | `docker build --pull` in a clean runner | Files that exist only on a developer machine |
| The code is deterministic on the same environment | Run a seeded check twice and compare | Missing seeds, nondeterministic operations |
Each check is cheap, and each one fails with a message that points at the cause.
Checking that the lock file is fresh
With pip-tools, recompile into the same output path and see whether the file changed. When the output file already exists, pip-compile keeps the pinned versions it finds there unless you pass --upgrade. The result changes only when requirements.in no longer matches the lock.
pip-compile --generate-hashes -o requirements.lock requirements.in
git diff --exit-code requirements.lockgit diff --exit-code returns a non-zero status when the file differs, which fails the job. Don't compile to a different output path and diff against that. A fresh resolution would pick up every new release published since the lock was written, and the check would fail for reasons unrelated to your change.
With uv, the tool has the check built in:
uv lock --check
uv sync --lockeduv lock --check fails if uv.lock would change. uv sync --locked fails if the lock is out of date with pyproject.toml, and otherwise installs exactly the locked set.
Match the Python version and platform
A lock file is generated for one Python version and one operating system. The header that pip-compile writes records the command used. If CI runs Python 3.12 while you locked on 3.11, markers and wheel hashes can differ, and the diff fails even though nothing is wrong with the dependencies. Pin the CI interpreter to the same minor version as the Dockerfile base image. Better still, run the lock check inside the same image you ship.
Checking the install and the image
The install step is the same one the Dockerfile runs. Running it in CI first gives a faster, clearer failure than a Docker build log.
name: reproducibility
on:
pull_request:
jobs:
lock:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Lock file is up to date
run: |
pip install pip-tools
pip-compile --generate-hashes -o requirements.lock requirements.in
git diff --exit-code requirements.lock
- name: Lock file installs with hashes
run: |
python -m venv .venv
.venv/bin/pip install --require-hashes -r requirements.lock
.venv/bin/pip check
image:
needs: lock
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
- name: Build from scratch
run: docker build --pull -t ml-train:ci .
- name: Environment is consistent
run: docker run --rm ml-train:ci pip check
- name: Seeded run is repeatable
run: docker run --rm ml-train:ci python -m src.check_determinism--pull makes Docker check the registry for the base image instead of trusting a stale local copy. If the Dockerfile pins the base image by digest, this step fails when the digest has been removed from the registry, which is a useful early warning. Add --no-cache to a scheduled (nightly) build, not to every pull request. A scheduled cold build proves the image can still be rebuilt from nothing, for example after an upstream package index changes. Pull requests keep the layer cache for speed.
A determinism check that runs in CI
CI runners usually have no GPU, so the check below runs on the CPU. It trains a tiny model twice with the same seed and compares a hash of the final weights. It catches missing seeds and operations that raise under use_deterministic_algorithms. Save it as src/check_determinism.py.
import hashlib
import random
import numpy as np
import torch
def seed_everything(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
def train_once(seed: int) -> str:
seed_everything(seed)
model = torch.nn.Linear(4, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
x = torch.randn(32, 4)
y = x.sum(dim=1, keepdim=True)
for _ in range(20):
optimizer.zero_grad()
loss = torch.nn.functional.mse_loss(model(x), y)
loss.backward()
optimizer.step()
weights = torch.cat([p.detach().flatten() for p in model.parameters()])
return hashlib.sha256(weights.numpy().tobytes()).hexdigest()
if __name__ == "__main__":
torch.use_deterministic_algorithms(True)
first = train_once(42)
second = train_once(42)
if first != second:
raise SystemExit(f"Nondeterministic: {first} != {second}")
print(f"Repeatable: {first}")Comparing two runs inside one job is reliable. Comparing against a hash stored in the repository is fragile. The hash depends on the CPU instruction set, the BLAS library and the thread count, so a new runner type can change it without any bug. If you want a stored reference, store a metric such as validation loss and compare it within a tolerance.
Common failure modes
- The check passes locally and fails in CI. The local Python version or platform differs from the runner. Lock inside the CI image or a matching container.
- The diff fails with only a header change. Someone ran
pip-compilewith different flags. Put the exact command in aMakefiletarget and use it in both places. - The build is green but the image changed. The base image is referenced by tag. Pin it by digest, and let a dependency bot propose digest updates as pull requests.
- The hash check fails on a single package. The package was re-uploaded, or the lock was generated on a different platform with different wheels. Relock deliberately and review the diff. Never remove
--require-hashesto make the job pass.
Exercise
A teammate adds pandas to requirements.in and opens a pull request without changing requirements.lock. Which CI step fails, and why does recompiling to the same output path work better for this check than compiling to a new file?
Show answer
The "Lock file is up to date" step fails. pip-compile rewrites requirements.lock to include pandas and its dependencies, so git diff --exit-code returns non-zero. Recompiling to the same path reuses the existing pins, so only the missing pandas entries change. Compiling to a new file would resolve everything fresh and show differences for any package that released a new version, which would fail unrelated pull requests.