You train a small classifier twice with the same code. The first run reaches accuracy on a test set of 2000 examples. The second reaches . Nothing is broken. The only difference is the seed, the number that sets the random choices inside the run: the starting weights and the order in which the examples are visited. (The code cell at the end of this lesson makes exactly these two runs.)
Randomness is everywhere in machine learning, and it creates two opposite problems. You want to repeat a run exactly, to find a bug or to check a claim. And you want to know whether a difference between two models is real, or only the luck of one run. Seeds help with both, and this lesson shows what they do and where they stop.
What “random” means for a computer
A computer follows instructions, and the same instructions on the same input give the same output. It cannot throw dice. What it can do is run a pseudo-random number generator (PRNG): a rule that takes a number called the state and produces the next state and an output number. The outputs look like independent draws, although they come from a formula. P1.D9 introduced this; here we open the box.
The starting state is the seed. Everything after it is fixed. Think of a recipe that turns one number into a long scrambled list: give the recipe the same starting number and you get the same list, give it another and you get a different list. The picture breaks in one place: a good recipe does not scramble by hand-picked tricks, it is built so that the list passes many statistical tests for randomness.
A generator you can run by hand
The simplest classic rule is the linear congruential generator (LCG). Take the remainder after division () of a linear function of the state:
Here is the output, a number in . Choose , , and the seed . Then
- ,
- ,
- ,
- .
Carrying on gives , then and then again. The outputs are , , , and so on. Every number from to appears exactly once, and then the whole list repeats. The length of the cycle before it repeats is the period: here . Start from instead and you land inside the same cycle, at another place: .
This toy generator is also a good example of how a generator can be weak.
- A short period. With only 16 numbers come out before the cycle repeats. A real generator needs a period far larger than the number of draws a program will make.
- Patterns in the low bits. The lowest bit of the output alternates , so the numbers are odd, even, odd, even. Anyone using “is the number odd?” as a coin flip would get a perfectly regular pattern.
- A bad choice of constants. With , , and the sequence is : it gets stuck at for ever.
- Hidden structure in a large LCG. RANDU was a widely used LCG with . Every output satisfies , so points built from consecutive triples fall on only 15 planes in 3D, according to the usual account of the generator (Marsaglia, 1968). The second code cell below checks the relation.
Modern generators keep the state-in, number-out idea but use a much larger state and scramble the output. Two you will meet:
- PCG64, the default of NumPy’s
np.random.default_rng, with a period of (NumPy documentation). - The Mersenne Twister, used by Python’s
randommodule (period , from the Python documentation) and by NumPy’s older, legacy interface.
A period of is about . A program that draws a billion numbers per second would not get through it in the age of the universe, so the period is never the practical limit for ML. The quality of the numbers and the care taken with seeds are.
The widget: run the program again
Press Run the program several times with the seed on. Then switch to Without a seed. Each run draws five numbers and then shuffles six letters, which is a small version of “draw random numbers, then shuffle the data”.
Things to try, all read from the widget’s own generator:
- Seed 42, defaults. The first run gives and the letters
EAFCBD. Press Run the program again: the same row comes back, tagged as the same as run 1. That is what “reproducible” means. - Change the seed to 7. The numbers become and the letters
DEBAFC. A different seed gives a different stream. - Seed 42 with the extra draw. The numbers become : the same stream, shifted by one place, because one number was used up. The letters change to
CAFEDB. The result depends on the order of the calls, and not only on the seed. Adding one random call at the start of a program changes everything after it. - Without a seed. Every row is different, and a repeated row would be a very unlikely coincidence, because the seed is a random 32-bit number.
What a seed promises, and what it does not
A seed gives a repeatable sequence. It does not make the numbers less random in a statistical sense (P1.D9). Four conditions matter.
- Same seed, same code path. The generator is only consistent if the program makes the same calls in the same order. In NumPy, calling
rng.random()five times is not guaranteed to give the same numbers asrng.random(5), according to the NumPy compatibility notes. - Same library version and platform. NumPy’s documentation promises the same stream for the same seed on the same build of NumPy, in the same environment, on the same machine. Across versions the stream of a
Generatormay change. The legacyRandomStateis frozen, which is its reason to exist. PyTorch’s documentation says that fully reproducible results are not guaranteed across releases, individual commits or platforms. - Different seeds, different streams. Seeds and are unrelated in practice: NumPy mixes the seed thoroughly before it starts, so nearby seeds do not give similar streams.
- A seed is not a tuning knob. Trying seeds until one gives the best number is a form of cheating that P1.D9 warned about and the last section returns to.
Use a generator object, not hidden global state
There are two ways to ask NumPy for random numbers.
rng = np.random.default_rng(0) # preferred: an explicit generator object
rng.random(3)
np.random.seed(0) # legacy: reseeds one hidden, global generator
np.random.rand(3)
The first line creates a generator object (a PCG64 by default) that you own. You pass it to every function that needs randomness, and each object keeps its own state. The second way uses one global generator shared by the whole program, including any library you import. The NumPy documentation says that this global state means “results will change as the code changes”, and it describes the older RandomState interface as frozen legacy (a Mersenne Twister), kept for code that needs the old streams. For new code, NumPy points to Generator. Python’s built-in random module also has one global Mersenne Twister, seeded with random.seed(...).
With an explicit generator, the data-order stream and the weight-initialization stream can be two separate objects. Then changing how many numbers one part draws does not shift the other part, which is the problem the extra-draw tick box above showed.
Many streams for many workers
Training often runs in parallel: several data-loading workers, several experiments at once, several machines. Each needs its own random numbers, and they must not repeat each other.
Two traps:
- Copying one generator. A worker that starts with a copy of the same generator state draws exactly what its siblings draw. In the first code cell below, three copies of one generator each give : three identical “random” workers.
- Adding 1 to a seed. Giving worker the seed
root_seed + iis marked unsafe in the NumPy documentation: a run with another root seed gets overlapping sets of worker seeds, so two experiments that you meant to be independent share streams.
The recommended tool is SeedSequence.spawn, or rng.spawn(k) (NumPy 1.25 or newer; SeedSequence.spawn also works on older versions), which makes child generators from one parent. NumPy’s documentation says these children are independent with very high probability, and that you can spawn from a child again. The streams depend on the parent seed, so one root seed in your record still reproduces everything. Another option from the documentation is a list seed such as default_rng([worker_id, root_seed]).
True randomness, and why a PRNG is not for secrets
Sometimes you want numbers nobody can predict, not even by knowing the algorithm. Operating systems collect unpredictable events from the hardware and make them available: in Python, os.urandom gives random bytes, and the secrets module is the tool for passwords and tokens. The Python documentation says that the generators in random should not be used for security purposes and points to secrets.
Machine learning wants the opposite: numbers that are fast, statistically good, and repeatable. So training uses PRNGs, and you may use OS randomness once to pick a fresh seed when you do not care about repeating the run (record the seed it gave you).
Where randomness enters training
| Where | What is random | Lesson |
|---|---|---|
| Weight initialization | The starting weights | P4.12 |
| Shuffling, mini-batches | The order of the examples and which ones form a batch | P1.F4 |
| Dropout | Which units are switched off at each step | P4.17 |
| Data augmentation | Which flips, crops or colour changes are applied | P4.18 |
| Train and validation splits | Which examples are held out | P3.A4 |
| Bagging and random forests | The bootstrap samples of the data | P3.B4 |
| Hyperparameter search | Which settings are tried | P4.23 |
| Text generation | Which token is drawn from the model’s probabilities | P10.A5 |
Every row is a place where two runs can part. Mini-batch sampling is also the Monte Carlo estimate of the gradient in P1.F4.
How to repeat a run
- Seed every source of randomness you use. Python’s
random, NumPy, and the framework. In PyTorch,torch.manual_seed(seed)seeds the generators of all devices, CPU and CUDA. PyTorch’s notes also show seeding Python’srandomand NumPy, because custom code can use them. A NumPyGeneratorobject is not seeded bynp.random.seed: seed it where you create it. - Pass generators explicitly and keep separate ones for separate jobs (data order, initialization, augmentation).
- Handle data-loader workers. PyTorch’s notes say to use
worker_init_fnand a seededgeneratorforDataLoaderso that the workers’ randomness is reproducible. - Record what you need to replay the run. The seed, the library versions, the hardware, and the settings. A seed without the version it was used with may not reproduce anything.
- Save the seed with the result. A result with no seed on record cannot be replayed.
Why a GPU run can still differ
Suppose all the seeds are set and the program is identical. On a GPU the loss curve can still change between two runs. The cause is not the random-number generator.
Floating-point addition is not associative. Computer numbers have limited precision (P1.G1), so each addition rounds. Adding the same numbers in a different order can round differently:
(0.1 + 0.2) + 0.3 # 0.6000000000000001
0.1 + (0.2 + 0.3) # 0.6
The difference is tiny in one sum. A big sum has many roundings, and the third code cell shows that a million 32-bit numbers can give visibly different totals depending on the order and the method of adding.
Parallel sums choose their order at run time. A GPU adds up a large array with thousands of threads, each making a partial sum that is then combined. If the combining order can change from run to run (for example when threads add into the same memory location), then the rounding changes too, and the result is not bit-for-bit repeatable. PyTorch’s documentation lists operations that are nondeterministic on the GPU, and deterministic mode can raise an error for them. The thread explanation above is this lesson’s own.
The library may choose differently. NVIDIA’s cuDNN library, which PyTorch uses for convolutions, has several algorithms for the same operation. PyTorch’s notes say that setting torch.backends.cudnn.benchmark = False makes cuDNN choose its algorithm deterministically, possibly at reduced performance, while True may improve speed when you do not need the same results across runs. Even then, the selected algorithm may itself be nondeterministic unless torch.backends.cudnn.deterministic = True or torch.use_deterministic_algorithms(True) is set.
Small differences can grow. A last-digit difference does not stay a last-digit difference through thousands of training steps. A study of neural-network training (Summers and Dinneen, 2021) reports that even a one-bit change in the initial parameters can lead to models that converge to very different values, so nondeterminism on the GPU has an effect similar to changing the seed.
The fix and its price
torch.use_deterministic_algorithms(True) asks PyTorch to use deterministic algorithms where they exist and to raise an error for an operation that has none (with warn_only=True it warns instead). PyTorch’s notes also say that deterministic operations are often slower, so the speed of a single run can drop. The trade-off is yours: turn determinism on while you debug or when you need an exact replay, and weigh the cost for long training runs. PyTorch also says results can differ between CPU and GPU even with the same seed.
Different seeds are information
Go back to the two runs at the top. If the accuracy changes by two points between seeds, then a new method that gains one point on one seed has shown nothing yet. The right habit has four steps.
- Run several seeds (five or ten, more for small differences) with the same settings.
- Report the mean and the spread, for example the standard deviation or the range, as in P1.D12. The fourth code cell below runs five seeds: accuracies , and , mean , sample standard deviation .
- Compare methods over the same seeds and use the interval ideas of P1.D13 before calling one better.
- Never search for a lucky seed. Over 30 seeds the same model scored between and . Setting the best seed of one method against the worst seed of another would show a gap of more than 4 points that comes from luck alone.
Record the seed you used, say that you used several, and show the spread. Fixing a single seed for a paper is fine for repeating that exact number, and says nothing about whether the method works in general.
Intuition
A seed is the page number where you start reading a very long book of scrambled digits. Same page, same digits. Give each worker its own starting page, picked by mixing the root seed with the worker’s number, so the passages almost surely never overlap (that is what spawning does). On a GPU, even with the same page, the arithmetic that uses the digits can be done in a different order, and a different order of additions gives a slightly different total.
Math
A PRNG is a map on a finite set of states with an output function . Finite states mean that the sequence eventually enters a cycle, and the cycle length is the period. The LCG has and period at most . The Hull and Dobell theorem gives the condition for full period : and share no prime factor, is divisible by every prime factor of , and by 4 if is. For , , both hold, and the code cell confirms that all 16 values appear.
Rounding: in floating point, with , the machine epsilon (P1.G1). Each addition adds its own , and a different order gives a different sequence of values, so in general.
Code
import random
import numpy as np
import torch
def set_seed(seed: int) -> np.random.Generator:
random.seed(seed) # Python's random module
np.random.seed(seed) # legacy global NumPy generator, in case a library uses it
torch.manual_seed(seed) # CPU and all CUDA devices
return np.random.default_rng(seed) # an explicit generator for your own code
rng = set_seed(0)
# To ask PyTorch for deterministic algorithms (an error is raised for an operation that has none):
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark = FalseThe PyTorch lines are for your own machine or a Colab notebook, not for the in-browser cells of this page. For spawning streams in plain NumPy:
children = np.random.default_rng(12345).spawn(4) # four independent generatorsGo deeper Counter-based generators and the order of calls
Some modern generators (for example Philox, which NumPy offers as a bit generator and which GPU random-number libraries also use) are built so that the number at position of a stream can be computed directly from the seed and , without computing the earlier ones. That helps parallel code: each thread computes its own part of the stream, and the result does not depend on the order in which the threads run. It is one way to make randomness on a GPU reproducible even when the work is split differently.
Go deeper Why a very long period is not enough
A period of says the sequence does not repeat soon, and nothing about whether it looks random. RANDU has a period of exactly for odd seeds and still fails because its outputs lie on a few planes. Real generators are tested with batteries of statistical tests, and their authors publish the results. For machine learning, the standard generators of NumPy and PyTorch are far more than good enough, and the practical risk comes from reusing streams, as in the section on workers.
Try it: same seed, same result
The first cell shows the basic facts with NumPy: same seed, different seed, the order of calls, the legacy interface, spawning, and the copy trap.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
With NumPy 2.2.1 the cell prints twice for seed and for seed , the order-of-calls lines for the second call and after the extra draw, for the legacy seed , for Python’s random, three identical copies , and three different spawned pairs. If the browser’s NumPy is another version, some of these values may differ; what stays true is that equal seeds give equal rows and the three copies give identical rows. Challenge: compare default_rng(0).random(3) with three separate calls of rng.random(). On the machine used for this lesson they match, although the NumPy documentation does not promise it. Why is it safer not to rely on that?
The second cell runs the toy LCG, checks its period, shows the lowest-bit pattern, and checks the RANDU relation.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
The third cell shows that the order of adding changes the result.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
With NumPy 2.2.1 the first lines print versus and versus . The 64-bit reference is . np.sum gave , , and for the four orders, and adding one after another gave , , and . The exact digits can change with the NumPy version, but the totals are not all equal, and adding in sorted order one after another is far off. Floating-point details are in P1.G1.
The fourth cell trains the tiny classifier of the hook with several seeds. The data are fixed, and only the starting weights and the order of the examples change with the seed.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
With NumPy 2.2.1 it prints twice, then the five accuracies , and with mean and sample standard deviation , and for 30 seeds a mean of , a standard deviation of and a range from to . A different NumPy version may give other digits. Challenge: change epochs to 30 and eta to 0.1. Does the spread across seeds grow or shrink?
Check your understanding
A program calls
rng = np.random.default_rng(7)and then draws numbers. Which statement is correct?A seed fixes the whole sequence, so a repeated run with the same library build and the same calls repeats it. Pseudo-random numbers pass statistical tests of randomness, so being made by a formula does not make them statistically poor. NumPy documents that a Generator stream may change between versions, and a different seed starts an unrelated stream, not a shifted copy.
The generator has . What are , , ?
; and ; and . The other triples come from forgetting the remainder step, or from using the wrong constants.
Four data-loading workers each receive a copy of the same generator object. What happens?
A copy carries the same state, and the next number depends only on the state, so every copy produces the same sequence. Separate processes do not change that. The seed value does not matter, and there is no shifting between copies. The fix is to spawn children from one parent with
SeedSequence.spawn.All seeds are set, the code is identical, and two GPU training runs still end with slightly different losses. Which explanation fits?
Each addition rounds, so a different order of the same numbers can give a slightly different total, and parallel reductions or library algorithm choices can change the order between runs. The seed still sets the starting weights. GPUs use floating-point numbers for training, and Python code runs on the CPU in any case.
A new method scores on seed 0 and the baseline scores on seed 0, and across seeds each method varies by about . What is the best next step?
A gap of is smaller than the seed-to-seed variation of , so one seed cannot tell the methods apart. Several seeds with their mean and spread can. Picking the seed with the largest gap is cherry-picking, and the legacy interface does not change how large the variation is.
Exercises
- Run the generator from for three steps.
Show answer
, , . This is the same cycle as the one from in the lesson, entered at another place: . - The generator starts at . What happens, and what does it show?
Show answer
It gives , because and . The sequence is stuck at one value, a period of 1: the constants matter, and a rule that looks random can be useless. - A generator uses a state of 32 bits and every state can occur. What is the largest possible period?
Show answer
, because the sequence must repeat once a state repeats. At a billion draws per second this is used up in about four seconds, which is why modern generators use far more state, such as the period of PCG64. - A teammate gives worker the seed
42 + i. Another teammate runs the same job with root seed 43. What goes wrong, and what should be done?Show answer
Worker 1 of the first run (seed 43) and worker 0 of the second run (seed 43) have the same seed, so their streams are identical although the two experiments were meant to be independent. Usenp.random.default_rng(root_seed).spawn(k)to make the worker generators. - Five seeds give accuracies , and . Give the mean and the range.
Show answer
The mean is and the range is to , a width of . The standard deviation is . A difference between two methods smaller than about this spread needs more seeds or a proper interval (P1.D13) before it is believed. - In floating point, . Name two reasons that this matters for a GPU run with all seeds set.
Show answer
Parallel sums add partial results in an order that may change from run to run, so the roundings change and the total can differ in its last digits. Library algorithm choices (such as the cuDNN algorithm for a convolution) can also change the order of the arithmetic. Small differences can then grow over thousands of training steps. - Which would you use to generate a password reset token:
random.random()or thesecretsmodule?Show answer
Thesecretsmodule. The Python documentation says the generators ofrandomshould not be used for security, because their output is meant to be fast and repeatable, and not unpredictable to an attacker.
Next: P1.G4 counts how the cost of an algorithm grows with the size of its input. P1.D13 gives the tools to decide when a difference between seeds or models is real, and P1.F4 shows the random mini-batches that make gradient descent stochastic.