Sub topic 12
Controlling Randomness
This chapter assumes basic Python, NumPy, and command-line usage. You should also understand that a machine learning training run combines data, code, configuration, and an execution environment.
Randomness appears in many places:
- Splitting data into training and validation sets.
- Shuffling examples before each epoch.
- Initializing model weights.
- Selecting samples or augmentations.
- Choosing parallel execution order.
- Creating synthetic data.
A seed is an initial value supplied to a pseudorandom number generator. A pseudorandom generator is a deterministic algorithm that produces a sequence that looks random. If the same generator receives the same seed and makes the same calls, it normally produces the same sequence.
Seed the generators you use
Seeding one library does not seed every other library. Python's random module, NumPy, and a deep learning framework usually maintain separate generators.
import random
import numpy as np
def set_seed(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
set_seed(42)
print(random.random())
print(np.random.random())Put the seed in your configuration rather than hiding it inside training code:
seed: 42Load the value once at the start of a run and pass it to data splitting, model construction, and training components. Record it with the run's parameters.
A local generator is often safer than changing global state. It makes a function's random behavior explicit and prevents an unrelated function from changing its sequence.
from numpy.random import Generator, default_rng
def make_sample(seed: int, size: int = 4) -> list[int]:
rng: Generator = default_rng(seed)
return rng.integers(0, 10, size=size).tolist()
first = make_sample(42)
second = make_sample(42)
assert first == second
print(first)Determinism has limits
A fixed seed makes repeatability possible, but it does not guarantee identical results in every environment. Different versions of NumPy, PyTorch, or a hardware driver can implement operations differently. Parallel CPU and GPU operations may also finish in different orders. Some operations are intentionally nondeterministic because deterministic alternatives are slower.
| Source of variation | Typical control |
|---|---|
| Python or NumPy random calls | Seed the relevant generator |
| Data-loader workers | Derive and assign worker seeds |
| GPU operations | Enable the framework's deterministic mode |
| Package behavior | Pin dependency versions |
| Data order | Sort inputs and record the data version |
For PyTorch, seed its generators as well as Python and NumPy:
import random
import numpy as np
import torch
def set_all_seeds(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.use_deterministic_algorithms(True)Deterministic algorithms can reduce performance and may raise an error when an operation has no deterministic implementation. Use this mode when debugging, testing, or investigating a result. For production training, decide whether exact repeatability is worth the cost.
A practical reproducibility check
Run the same small experiment twice and compare its output. Start with a fixed dataset and a short training run. If the outputs differ, inspect randomness in this order:
- Confirm that the configured seed reaches every library.
- Check whether input files are read in a stable order.
- Check data-loader workers and parallel processing.
- Enable deterministic framework settings.
- Compare package, driver, and hardware versions.
- Save intermediate outputs to locate the first difference.
Do not remove randomness merely to obtain a stable metric. Randomness can help optimization and can reveal whether a model depends on a fortunate split. For important experiments, run several recorded seeds and report the mean and spread of the metric.
Exercise
You seed NumPy with 42, but two runs still produce different validation scores. Name two causes to investigate.
Show answer
Check for unseeded randomness in another library or data-loader worker, and check for nondeterministic parallel or GPU operations. Also verify that the input order and dependency versions are unchanged.