Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsNumerical Computing

Randomness, seeds and reproducibility

P1.G340 min●○○ BeginnerReviewed Dec 1, 2026

Why this matters for machine learning

Almost every step of training uses random numbers, so the same code gives different results unless you control them. Seeds let you repeat an experiment exactly, and the spread across seeds tells you which differences between models are real.

  • Mini-batch gradient descent shuffles the data and draws batches at random. With a recorded seed you can replay the same sequence of batches to find a bug. (P1.F4: Stochastic and mini-batch gradient descent)
  • Weights start as random numbers, so two runs of the same network start at different points of the loss landscape and can end at different accuracies. (P4.12: Weight initialization)
  • A claim like “model B beats model A” needs several seeds each, reported as a mean and a spread, and not one lucky run. (P1.D13: Statistical thinking for ML)
  • A language model picks its next token by drawing a random number, so the same prompt can give different text, and a fixed seed makes the draw repeatable. (P10.A5: Decoding strategies, coming soon)

Before this: Sampling and Monte Carlo, Descriptive statistics and visualization

After this lesson you can

  • Explain what a pseudo-random number generator is, run a small one by hand, and say what a period is and how a weak generator shows its weakness
  • State what a seed does and does not guarantee, and create and pass around a NumPy generator object instead of using hidden global state
  • Give independent random streams to parallel workers without copying one generator or adding 1 to a seed
  • List where randomness enters machine-learning training and what to seed and record to repeat a run
  • Explain why a seeded GPU run can still change (floating-point addition order, cuDNN choices) and what the fixes cost
  • Report results over several seeds as a mean and a spread

You train a small classifier twice with the same code. The first run reaches 0.81550.8155 accuracy on a test set of 2000 examples. The second reaches 0.79550.7955. 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 ( mod \bmod) of a linear function of the state:

xn+1=(a xn+c) mod m,un=xnm.\begin{aligned} x_{n+1}&=(a\,x_n+c)\bmod m,\\ u_n&=\frac{x_n}{m}. \end{aligned}

Here unu_n is the output, a number in [0,1)[0,1). Choose a=5a=5, c=3c=3, m=16m=16 and the seed x0=7x_0=7. Then

  • x1=(5⋅7+3) mod 16=38 mod 16=6x_1=(5\cdot7+3)\bmod16=38\bmod16=6,
  • x2=(5⋅6+3) mod 16=33 mod 16=1x_2=(5\cdot6+3)\bmod16=33\bmod16=1,
  • x3=(5⋅1+3) mod 16=8x_3=(5\cdot1+3)\bmod16=8,
  • x4=(5⋅8+3) mod 16=43 mod 16=11x_4=(5\cdot8+3)\bmod16=43\bmod16=11.

Carrying on gives 7,6,1,8,11,10,5,127,6,1,8,11,10,5,12, then 15,14,9,0,3,2,13,415,14,9,0,3,2,13,4 and then 77 again. The outputs are 7/16=0.43757/16=0.4375, 6/16=0.3756/16=0.375, 1/16=0.06251/16=0.0625, and so on. Every number from 00 to 1515 appears exactly once, and then the whole list repeats. The length of the cycle before it repeats is the period: here 1616. Start from x0=3x_0=3 instead and you land inside the same cycle, at another place: 3,2,13,4,7,…3,2,13,4,7,\dots.

This toy generator is also a good example of how a generator can be weak.

  • A short period. With m=16m=16 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 1,0,1,0,…1,0,1,0,\dots, 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 a=4a=4, c=2c=2, m=16m=16 and x0=1x_0=1 the sequence is 1,6,10,10,10,…1,6,10,10,10,\dots: it gets stuck at 1010 for ever.
  • Hidden structure in a large LCG. RANDU was a widely used LCG with xn+1=65539 xn mod 231x_{n+1}=65539\,x_n\bmod 2^{31}. Every output satisfies xn+2=6xn+1−9xn(mod231)x_{n+2}=6x_{n+1}-9x_n \pmod{2^{31}}, 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 21282^{128} (NumPy documentation).
  • The Mersenne Twister, used by Python’s random module (period 219937−12^{19937}-1, from the Python documentation) and by NumPy’s older, legacy interface.

A period of 21282^{128} is about 3×10383\times10^{38}. 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”.

Run the same program again

No runs yet. Press Run the program.

Each run draws five numbers in [0, 1) and then shuffles the letters A to F. The generator is a small one for the browser (mulberry32), not NumPy's.

A list of runs of the same small program. With a seed, every run starts from the same state, so it prints the same five numbers and the same shuffled letters, and a green tag says which earlier run it repeats. Without a seed, every run starts from a fresh random state and the rows differ. The tick box makes the program draw one extra number first. Number and letter rows come from a small generator for the browser (mulberry32), not from NumPy.

Things to try, all read from the widget’s own generator:

  • Seed 42, defaults. The first run gives 0.601,0.448,0.852,0.670,0.1750.601, 0.448, 0.852, 0.670, 0.175 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 0.012,0.062,0.977,0.699,0.5210.012, 0.062, 0.977, 0.699, 0.521 and the letters DEBAFC. A different seed gives a different stream.
  • Seed 42 with the extra draw. The numbers become 0.448,0.852,0.670,0.175,0.5270.448, 0.852, 0.670, 0.175, 0.527: 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 as rng.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 Generator may change. The legacy RandomState is 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 00 and 11 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 0.805,0.8080.805, 0.808: three identical “random” workers.
  • Adding 1 to a seed. Giving worker ii the seed root_seed + i is 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 kk 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

WhereWhat is randomLesson
Weight initializationThe starting weightsP4.12
Shuffling, mini-batchesThe order of the examples and which ones form a batchP1.F4
DropoutWhich units are switched off at each stepP4.17
Data augmentationWhich flips, crops or colour changes are appliedP4.18
Train and validation splitsWhich examples are held outP3.A4
Bagging and random forestsThe bootstrap samples of the dataP3.B4
Hyperparameter searchWhich settings are triedP4.23
Text generationWhich token is drawn from the model’s probabilitiesP10.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

  1. 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’s random and NumPy, because custom code can use them. A NumPy Generator object is not seeded by np.random.seed: seed it where you create it.
  2. Pass generators explicitly and keep separate ones for separate jobs (data order, initialization, augmentation).
  3. Handle data-loader workers. PyTorch’s notes say to use worker_init_fn and a seeded generator for DataLoader so that the workers’ randomness is reproducible.
  4. 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.
  5. 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.

  1. Run several seeds (five or ten, more for small differences) with the same settings.
  2. Report the mean and the spread, for example the standard deviation ss or the range, as in P1.D12. The fourth code cell below runs five seeds: accuracies 0.8155,0.7955,0.82150.8155, 0.7955, 0.8215, 0.8290.829 and 0.8370.837, mean 0.81970.8197, sample standard deviation 0.01580.0158.
  3. Compare methods over the same seeds and use the interval ideas of P1.D13 before calling one better.
  4. Never search for a lucky seed. Over 30 seeds the same model scored between 0.79550.7955 and 0.8370.837. 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 sn+1=T(sn)s_{n+1}=T(s_n) on a finite set of states with an output function un=g(sn)u_n=g(s_n). Finite states mean that the sequence eventually enters a cycle, and the cycle length is the period. The LCG has T(x)=(ax+c) mod mT(x)=(ax+c)\bmod m and period at most mm. The Hull and Dobell theorem gives the condition for full period mm: cc and mm share no prime factor, a−1a-1 is divisible by every prime factor of mm, and by 4 if mm is. For a=5a=5, c=3c=3, m=16m=16 both hold, and the code cell confirms that all 16 values appear.

Rounding: in floating point, fl(a+b)=(a+b)(1+δ)\mathrm{fl}(a+b)=(a+b)(1+\delta) with ∣δ∣≤ε\lvert\delta\rvert\le\varepsilon, the machine epsilon (P1.G1). Each addition adds its own δ\delta, and a different order gives a different sequence of δ\delta values, so fl((a+b)+c)≠fl(a+(b+c))\mathrm{fl}\big((a+b)+c\big)\ne\mathrm{fl}\big(a+(b+c)\big) 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 = False

The 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 generators
Go 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 kk of a stream can be computed directly from the seed and kk, 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 21282^{128} says the sequence does not repeat soon, and nothing about whether it looks random. RANDU has a period of exactly 2292^{29} 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.

Try it: seeds, generator objects and independent streams

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 0.637,0.27,0.0410.637, 0.27, 0.041 twice for seed 00 and 0.512,0.95,0.1440.512, 0.95, 0.144 for seed 11, the order-of-calls lines 0.017,0.813,0.9130.017, 0.813, 0.913 for the second call and 0.27,0.041,0.0170.27, 0.041, 0.017 after the extra draw, 0.549,0.715,0.6030.549, 0.715, 0.603 for the legacy seed 00, 0.844,0.758,0.4210.844, 0.758, 0.421 for Python’s random, three identical copies 0.805,0.8080.805, 0.808, 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.

Try it: a linear congruential generator and its weaknesses

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.

Try it: adding the same numbers in a different order

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 0.60000000000000010.6000000000000001 versus 0.60.6 and 0.00.0 versus 1.01.0. The 64-bit reference is 998570.65998570.65. np.sum gave 998570.69998570.69, 998570.44998570.44, 998570.75998570.75 and 998514.50998514.50 for the four orders, and adding one after another gave 998599.31998599.31, 998528.94998528.94, 998541.31998541.31 and 1013485.381013485.38. 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.

Try it: the same model, different seeds

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

With NumPy 2.2.1 it prints 0.81550.8155 twice, then the five accuracies 0.8155,0.7955,0.82150.8155, 0.7955, 0.8215, 0.8290.829 and 0.8370.837 with mean 0.81970.8197 and sample standard deviation 0.01580.0158, and for 30 seeds a mean of 0.82260.8226, a standard deviation of 0.0120.012 and a range from 0.79550.7955 to 0.8370.837. 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

  1. A program calls rng = np.random.default_rng(7) and then draws numbers. Which statement is correct?

  2. The generator xn+1=(5xn+3) mod 16x_{n+1}=(5x_n+3)\bmod16 has x0=2x_0=2. What are x1x_1, x2x_2, x3x_3?

  3. Four data-loading workers each receive a copy of the same generator object. What happens?

  4. All seeds are set, the code is identical, and two GPU training runs still end with slightly different losses. Which explanation fits?

  5. A new method scores 0.840.84 on seed 0 and the baseline scores 0.830.83 on seed 0, and across seeds each method varies by about 0.020.02. What is the best next step?

Exercises

  1. Run the generator xn+1=(5xn+3) mod 16x_{n+1}=(5x_n+3)\bmod16 from x0=2x_0=2 for three steps.
    Show answerx1=13x_1=13, x2=(65+3) mod 16=4x_2=(65+3)\bmod16=4, x3=(20+3) mod 16=7x_3=(20+3)\bmod16=7. This is the same cycle as the one from 77 in the lesson, entered at another place: …,2,13,4,7,…\dots,2,13,4,7,\dots.
  2. The generator xn+1=(4xn+2) mod 16x_{n+1}=(4x_n+2)\bmod16 starts at x0=1x_0=1. What happens, and what does it show?
    Show answerIt gives 1,6,10,10,10,…1,6,10,10,10,\dots, because 4⋅10+2=424\cdot10+2=42 and 42 mod 16=1042\bmod16=10. The sequence is stuck at one value, a period of 1: the constants matter, and a rule that looks random can be useless.
  3. A generator uses a state of 32 bits and every state can occur. What is the largest possible period?
    Show answer232=4,294,967,2962^{32}=4{,}294{,}967{,}296, 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 21282^{128} period of PCG64.
  4. A teammate gives worker ii the seed 42 + i. Another teammate runs the same job with root seed 43. What goes wrong, and what should be done?
    Show answerWorker 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. Use np.random.default_rng(root_seed).spawn(k) to make the worker generators.
  5. Five seeds give accuracies 0.8155,0.7955,0.82150.8155, 0.7955, 0.8215, 0.8290.829 and 0.8370.837. Give the mean and the range.
    Show answerThe mean is 0.81970.8197 and the range is 0.79550.7955 to 0.8370.837, a width of 0.04150.0415. The standard deviation is 0.01580.0158. A difference between two methods smaller than about this spread needs more seeds or a proper interval (P1.D13) before it is believed.
  6. In floating point, (0.1+0.2)+0.3≠0.1+(0.2+0.3)(0.1+0.2)+0.3\ne0.1+(0.2+0.3). Name two reasons that this matters for a GPU run with all seeds set.
    Show answerParallel 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.
  7. Which would you use to generate a password reset token: random.random() or the secrets module?
    Show answerThe secrets module. The Python documentation says the generators of random should 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.

Key takeaways

  • A pseudo-random number generator (PRNG) is a deterministic rule: a state goes in, a number and the next state come out. The seed sets the first state, so the same seed gives the same sequence and a new seed gives a new one.
  • A tiny generator, xn+1=(5xn+3) mod 16x_{n+1}=(5x_n+3)\bmod 16 from 77, runs 7,6,1,8,11,10,5,…7,6,1,8,11,10,5,\dots and repeats after 16 steps (its period). Weak generators show patterns: its lowest bit alternates 1,0,1,01,0,1,0.
  • NumPy's np.random.default_rng(seed) makes a generator object (PCG64 by default). Python's random and the legacy np.random.seed use the Mersenne Twister and hidden global state. Prefer an explicit generator that you pass to the code that needs it.
  • The same seed repeats a run only with the same library version, platform and sequence of calls. Copies of one generator give identical streams, so give parallel workers streams made with SeedSequence.spawn (or rng.spawn), and never seed + worker_id.
  • Randomness in ML: initial weights, shuffling and mini-batches, dropout, data augmentation, train and validation splits, bagging, hyperparameter search and sampling tokens from a language model. Seed each library you use and record versions and settings.
  • GPU runs can differ even with a seed: floating-point addition is not associative, parallel sums add in an order that can change between runs, and cuDNN may pick different algorithms. PyTorch has switches for deterministic algorithms, which are often slower.
  • Different seeds give different results. That spread is real information: run several seeds, report the mean and the spread, and never pick the seed that gives the answer you like.
Found a mistake? Tell us