Sub topic 12
Controlling randomness
Machine learning code makes random choices in many places: shuffling rows, splitting data, initializing weights, dropping units, sampling batches. If those choices change on every run, two runs with the same code, config, and data can give different metrics. You then cannot tell whether a change in score came from your edit or from chance.
This chapter assumes you can read the config loader from the previous chapters, know basic NumPy, and have trained a model with scikit-learn or PyTorch. It covers where randomness enters a project, how to seed it from the config, and where seeding stops being enough.
What a seed does
Most random number generators are deterministic algorithms. They start from an internal state and produce a sequence of numbers that looks random. A seed is an integer that sets that starting state. The same seed gives the same sequence, as long as the same calls are made in the same order.
Two consequences follow from that last clause:
- Adding or removing one random call earlier in the program shifts every later value.
- Running work in a different order, for example with threads or workers, changes which call gets which value.
A seed makes a run repeatable. It does not make a result correct or stable. A model that scores well on one seed may score badly on another, which is why you should also try several seeds before claiming an improvement.
Keep the seed in the config
The seed is a value that changes between runs, so it belongs in the config file with the other parameters. The config from earlier chapters already has it:
data_path: data/processed/train.csv
seed: 42
learning_rate: 0.001
batch_size: 32A hard-coded random.seed(42) buried in a training script cannot be overridden or recorded. A seed read from the config can be overridden on the command line (seed=7), logged with the experiment, and listed under params: in a pipeline so a change reruns the right stages.
Seeding the standard library and NumPy
Put the seeding in one function and call it once, at the start of each entry point.
import random
import numpy as np
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
if __name__ == "__main__":
set_seed(42)
first = (random.random(), np.random.rand())
set_seed(42)
second = (random.random(), np.random.rand())
assert first == second
print("same seed, same values:", first)The function seeds two separate generators. Python's random module and NumPy's legacy global generator do not share state, so seeding one leaves the other unseeded.
Prefer explicit generators
Global seeding has a weakness. Any library that draws from the global generator changes your sequence, and any code you add can silently shift later values. A more robust pattern is to create a generator object from the seed and pass it to the code that needs randomness.
import numpy as np
def split_indices(n_rows, test_fraction, rng):
order = rng.permutation(n_rows)
n_test = int(n_rows * test_fraction)
return order[n_test:], order[:n_test]
rng = np.random.default_rng(42)
train_idx, test_idx = split_indices(100, 0.2, rng)
print(len(train_idx), len(test_idx))Now the split depends only on the generator you passed in, and the function's dependence on randomness is visible in its signature. This also makes it easy to test.
When one run needs several independent random streams (one for splitting, one for augmentation), derive them from the single config seed instead of reusing the same number:
import numpy as np
seed = 42
split_seq, augment_seq = np.random.SeedSequence(seed).spawn(2)
split_rng = np.random.default_rng(split_seq)
augment_rng = np.random.default_rng(augment_seq)
print(split_rng.integers(0, 10), augment_rng.integers(0, 10))SeedSequence.spawn produces child sequences that are statistically independent, so changing how much randomness one component consumes does not alter the other.
Library-level seeds
Many libraries take their own seed argument. Pass the config value to each of them. In scikit-learn the argument is random_state:
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
seed = 42
X, y = make_classification(n_samples=200, random_state=seed)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=seed
)
model = RandomForestClassifier(n_estimators=50, random_state=seed)
model.fit(X_train, y_train)
print(round(model.score(X_test, y_test), 3))Any scikit-learn object or function that is random accepts random_state. If you leave it as None, it uses NumPy's global state, so the result depends on whatever ran earlier.
Deep learning frameworks
Deep learning frameworks keep their own generators, so random.seed and np.random.seed do not reach them. For PyTorch, extend the function:
import os
import random
import numpy as np
import torch
def set_seed(seed, deterministic=False):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if deterministic:
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
torch.use_deterministic_algorithms(True)torch.manual_seed seeds the CPU generator and all CUDA devices. With deterministic=True, PyTorch raises an error when an operation has no deterministic implementation, instead of silently running a nondeterministic one. The CUBLAS_WORKSPACE_CONFIG variable is required for deterministic CUDA matrix multiplication, and it must be set before the first CUDA operation runs.
Deterministic mode can make training slower, and some operations will raise errors until you replace them. Treat it as a setting you choose, not a default.
Data loading workers
A DataLoader with num_workers > 0 runs shuffling and augmentation in separate processes. Give the loader a seeded generator and seed each worker:
import random
import numpy as np
import torch
from torch.utils.data import DataLoader, TensorDataset
def seed_worker(worker_id):
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
seed = 42
generator = torch.Generator()
generator.manual_seed(seed)
dataset = TensorDataset(torch.arange(100).float().unsqueeze(1))
loader = DataLoader(
dataset,
batch_size=10,
shuffle=True,
num_workers=2,
worker_init_fn=seed_worker,
generator=generator,
)
if __name__ == "__main__":
first_batch = next(iter(loader))[0].flatten().tolist()
print(first_batch)The generator fixes the shuffle order. The worker_init_fn seeds NumPy and Python inside each worker, derived from PyTorch's per-worker seed.
Where the seed enters a run
What a seed does not guarantee
Even with every seed set, results can still differ. Common causes:
- Nondeterministic GPU operations. Some CUDA kernels add numbers in an order that varies between runs. Floating-point addition is not associative, so the totals differ in the last digits, and training can amplify that.
- Different hardware or library versions. A different GPU model, CPU instruction set, or framework release can change results even with the same seed. Pinning the environment, covered earlier, reduces this.
- Multithreading and multiprocessing. If the order of work varies, the order of random draws varies.
- Hash randomization. Python randomizes string hashes per process, which changes the iteration order of sets of strings. Setting
PYTHONHASHSEED=0must happen before the interpreter starts, so set it in the shell or pipeline command, not inside your code. - Unseeded components. One forgotten
random_state=Noneis enough.
Testing that seeding works
Seeding bugs are quiet, so test them. A useful check runs the same step twice with the same seed and compares the outputs:
import numpy as np
from my_project.data.prepare import split_indices
def test_split_is_repeatable():
a_train, a_test = split_indices(50, 0.2, np.random.default_rng(1))
b_train, b_test = split_indices(50, 0.2, np.random.default_rng(1))
assert (a_train == b_train).all()
assert (a_test == b_test).all()
def test_different_seed_changes_split():
a_train, _ = split_indices(50, 0.2, np.random.default_rng(1))
b_train, _ = split_indices(50, 0.2, np.random.default_rng(2))
assert not (a_train == b_train).all()This test assumes split_indices lives in my_project.data.prepare. The second test guards against the opposite bug, where the seed is ignored and the output never varies.
Practical rules
- Store one
seedin the config and log it with every experiment. - Seed in one function, called at each entry point.
- Pass explicit generators or
random_stateinstead of relying on global state where you can. - Use
SeedSequence.spawnwhen a run needs several independent streams. - Enable deterministic mode only when you need bit-for-bit repeatability, and expect a speed cost.
- Report results over several seeds when comparing models. A difference smaller than the spread across seeds is not evidence of improvement.
Exercise
You set seed: 42 in your config and call random.seed(config.seed) and np.random.seed(config.seed). Your PyTorch model's training loss still differs between two runs on the same machine. Name two likely causes and one fix for each.
Show answer
One cause is that PyTorch's own generator is unseeded, because random.seed and np.random.seed do not affect it. The fix is to add torch.manual_seed(config.seed) to set_seed. Another cause is a DataLoader with workers whose shuffling or augmentation is not seeded. The fix is to pass a seeded torch.Generator and a worker_init_fn that seeds each worker. A third possible cause is a nondeterministic GPU operation, which you can expose with torch.use_deterministic_algorithms(True) and CUBLAS_WORKSPACE_CONFIG=:4096:8.
Exercise
Why is rng = np.random.default_rng(seed) passed into a function often better than calling np.random.seed(seed) once at the top of the script?
Show answer
The generator is local state. Other code that draws from NumPy's global generator cannot shift its sequence, and the function's signature shows that it uses randomness. The function can also be tested with a known seed. Global seeding makes every later draw depend on the exact order of all random calls in the program.