Reproducibility: Environments, Seeds and Versions
How do you make sure that running the same code six months later gives the same result?
The five elements
| Element | Tool | What you save |
|---|---|---|
| Code | Git | The commit hash |
| Environment | A lock file or Docker | The exact versions |
| Data | DVC or a hash | The data version |
| Randomness | Seeds | The seed value |
| Settings | YAML or JSON | All the parameters |
Fixing the seeds
import os, random, numpy as np, torch
def set_seed(seed: int = 42, deterministic: bool = False):
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
if deterministic:
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True) # may require CUBLAS_WORKSPACE_CONFIG
set_seed(0)Note that PYTHONHASHSEED only takes effect if it is set before the interpreter starts.
Environment
- A virtual environment for each project (
venvorcondaoruv). - A file of exact versions:
pip freeze > requirements.txtor a lock file from the management tool. - Binary packages may differ between Windows and Linux; containers unify the environment.
The run log
Save with each result:
import json, subprocess, sys, platform, torch
meta = {"commit": subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip(),
"python": sys.version, "platform": platform.platform(),
"torch": torch.__version__, "cuda": torch.version.cuda, "seed": 0}
json.dump(meta, open("run_meta.json", "w"), indent=2)Bitwise reproduction is a hard goal; the practical goal is for the results to be statistically consistent and for you to know the source of any difference.
Lesson terms
- Reproducibility
- The ability to obtain the same results by re-running the same code on the same data in the same environment.
- Lock file
- A file that records the exact versions of all packages and their dependencies so the same environment can be rebuilt.
Abstract
Reproducibility requires pinning the code (Git), the environment (library versions in a lock file or a container image), the data (a version or a hash), randomness (seeds for all libraries), and the settings (a configuration file saved with the results). Some GPU operations are non-deterministic by default, and determinism can be enforced at a cost in performance. Even with all this, results may differ slightly between hardware, so it is better to report the spread across several seeds.
Review questions
-
Name five elements that must be pinned to reproduce an experiment.
The code, the environment and versions, the data, the seeds, and the settings.
-
Why is fixing the seed sometimes not enough on a GPU?
Because some parallel operations are non-deterministic by default, such as some cuDNN algorithms and atomic additions.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate