{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"random-numbers-and-seeds","title":"Random numbers that are not, and what a seed does and does not fix","url":"https://addaly.com/learn/maths-you-need/random-numbers-and-seeds","position":74,"of":76,"minutes":9,"answer":"A pseudo-random generator is a deterministic recipe started from a seed, so seeding makes shuffles, masks and splits repeat, but it cannot fix a GPU's reduction order, a split that shifts when data grow.","keyIdea":"A pseudo-random generator is a deterministic recipe started from a seed, so seeding makes shuffles, masks and splits repeat, but it cannot fix a GPU's reduction order, a split that shifts when data grow, or Python's per-process string hashing, each of which needs its own remedy."},"body":{"format":"markdown","text":"## Determinism wearing a disguise\n\nA computer cannot produce a random number. What it produces is a **pseudo-random** sequence: a fixed recipe that turns one state into the next, chosen so that the output passes every statistical test for randomness while being entirely determined by where it started. The starting state is the **seed**. Same seed, same recipe, same sequence, forever.\n\nThe simplest recipe, a linear congruential generator, is one line: `state = (a × state + c) mod m`. Modern generators, the Mersenne Twister behind older NumPy and Python's `random`, and the PCG64 behind `np.random.default_rng`, are more elaborate but no less deterministic. Their period, the number of outputs before the sequence repeats, is around `2^19937` for the Twister and `2^128` for PCG64. Neither will repeat in your lifetime. But a sequence that never repeats is not the same as one that cannot be predicted; if the seed is known, every number is known.\n\n## What a seed buys\n\nSet it, and a shuffle, a dropout mask, an initialisation and a train-test split are the same on every run. That is what makes a bug reproducible and a comparison fair. Set it in every library that draws numbers, because each keeps its own state:\n\n```python\nimport random, numpy as np, torch\nrandom.seed(0)\nnp.random.seed(0)                       # legacy global state\nrng = np.random.default_rng(0)          # preferred: an explicit generator you pass around\ntorch.manual_seed(0)                    # CPU and all GPUs\n```\n\nThe explicit generator is better than the global seed, because two parts of a program drawing from one global stream change each other's numbers when one of them adds a draw. Give each component its own generator, seeded from a master seed, and adding a draw in one place no longer changes the shuffle in another.\n\n## What a seed does not buy\n\n**Bitwise identical training on a GPU.** The previous lessons showed that floating-point addition depends on order and that a GPU adds in whatever order its threads arrive. The seed fixes the dropout mask and the initial weights; it does not fix the reduction order. Two runs with the same seed diverge in their last bits at the first step and in their third digit within a few thousand. `torch.use_deterministic_algorithms(True)` forces fixed-order kernels, at a cost in speed and with some operations refusing to run; it is the price of exact reproducibility, and it is sometimes worth paying.\n\n**Identical results across machines.** Different hardware, driver versions and library builds choose different kernels with different orders. Reproducibility across machines is a matter of agreeing to three digits, not thirty-two bits.\n\n**A stable split when the data grow.** Shuffling with a seed and taking the first 80 per cent as training is reproducible only until a row is added, after which every row's position shifts and yesterday's test examples leak into today's training set. The fix uses module 7's hashing: assign each row by a hash of its id, `hash(id) mod 100 < 80`, so that a row's split depends on the row alone. New rows land in either split; old rows never move.\n\n**Python's string hashing.** It is randomised per process by design, which changes the order of iteration over a set of strings from one run to the next. A vocabulary built by iterating a set is different on every run unless `PYTHONHASHSEED` is fixed or the set is sorted first. This is the single most common cause of \"the same code produces a different model\".\n\n## Turning uniform into anything\n\nA generator produces uniform numbers between 0 and 1. Every other distribution is manufactured from those. The general method is the **inverse cumulative distribution**: if `F` is the cumulative distribution you want, then `F^(−1)(u)` for uniform `u` has that distribution. For the exponential with rate `λ`:\n\n```\nx = −ln(u) / λ\n```\n\nFor the normal, the inverse has no closed form, and the Box-Muller transform takes two uniforms and returns two independent normals:\n\n```\nz₁ = √(−2 ln u₁) × cos(2π u₂)\nz₂ = √(−2 ln u₁) × sin(2π u₂)\n```\n\nFor a discrete distribution, a token sampled from a softmax, the method is the same: compute the cumulative sums, draw `u`, and pick the first token whose cumulative probability exceeds `u`. That is what `torch.multinomial` does, and it is why sampling a token costs a scan over the vocabulary rather than a lookup.\n\n## Randomness you did not ask for\n\n`DataLoader` workers each get a seed derived from the main one plus their worker id; if you seed NumPy inside a worker without that id, all workers produce the same augmentations. Dropout at evaluation time, if the model was never switched out of training mode, makes the same input give different outputs. Sampling with `temperature > 0` is random by intent. And any code that reads the clock, a network, or the filesystem order has a source of variation no seed touches.\n\n## The habit\n\nSeed everything, pass generators explicitly, hash for splits, sort before assigning ids, and expect two GPU runs to agree to three digits rather than exactly. When they agree to fewer, look for the nondeterminism, and when they agree exactly, check that the second run actually ran."},"check":{"question":"A team seeds Python, NumPy and PyTorch identically and trains twice on the same GPU, yet the two final models differ in the third decimal place of every weight. What is the most likely cause?","options":[{"text":"One of the libraries was not actually seeded, so the initial weights differed.","correct":false,"tempting":"Different initial weights would produce entirely different models, not ones agreeing to two decimal places; near-agreement is the mark of tiny arithmetic differences compounding."},{"text":"The pseudo-random generator has a period shorter than the number of draws in a training run and wrapped around.","correct":false,"tempting":"Periods of 2^128 or more cannot be exhausted; and a wrapped sequence would still be identical between two seeded runs."},{"text":"GPU sums run in a varying order, and the rounding differences compound.","correct":true},{"text":"Dropout produces genuinely random masks that no seed can control.","correct":false,"tempting":"Dropout masks come from the seeded generator and are identical across the two runs; the nondeterminism is in the summation, not the sampling."}]},"prev":{"slug":"variance-through-a-layer","title":"How variance travels through a layer, and the initialisation that follows","url":"https://addaly.com/learn/maths-you-need/variance-through-a-layer"},"next":{"slug":"checking-a-gradient-numerically","title":"Checking a gradient with finite differences, and the step size that lies","url":"https://addaly.com/learn/maths-you-need/checking-a-gradient-numerically"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Random numbers that are not, and what a seed does and does not fix', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/random-numbers-and-seeds (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Random numbers that are not, and what a seed does and does not fix","courseTitle":"The Maths You Actually Need","module":{"index":8,"slug":"numbers-in-a-machine","title":"Numbers inside a machine"},"answer":null,"keyIdea":"A pseudo-random generator is a deterministic recipe started from a seed, so seeding makes shuffles, masks and splits repeat, but it cannot fix a GPU’s reduction order, a split that shifts when data grow, or Python’s per-process string hashing, each of which needs its own remedy.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"determinism-wearing-a-disguise","runs":[{"text":"Determinism wearing a disguise"}]},{"t":"p","runs":[{"text":"A computer cannot produce a random number. What it produces is a "},{"text":"pseudo-random","b":true},{"text":" sequence: a fixed recipe that turns one state into the next, chosen so that the output passes every statistical test for randomness while being entirely determined by where it started. The starting state is the "},{"text":"seed","b":true},{"text":". Same seed, same recipe, same sequence, forever."}]},{"t":"p","runs":[{"text":"The simplest recipe, a linear congruential generator, is one line: "},{"text":"state = (a × state + c) mod m","code":true},{"text":". Modern generators, the Mersenne Twister behind older NumPy and Python’s "},{"text":"random","code":true},{"text":", and the PCG64 behind "},{"text":"np.random.default_rng","code":true},{"text":", are more elaborate but no less deterministic. Their period, the number of outputs before the sequence repeats, is around "},{"text":"2^19937","code":true},{"text":" for the Twister and "},{"text":"2^128","code":true},{"text":" for PCG64. Neither will repeat in your lifetime. But a sequence that never repeats is not the same as one that cannot be predicted; if the seed is known, every number is known."}]},{"t":"h2","id":"what-a-seed-buys","runs":[{"text":"What a seed buys"}]},{"t":"p","runs":[{"text":"Set it, and a shuffle, a dropout mask, an initialisation and a train-test split are the same on every run. That is what makes a bug reproducible and a comparison fair. Set it in every library that draws numbers, because each keeps its own state:"}]},{"t":"code","lang":"python","label":"Python","text":"import random, numpy as np, torch\nrandom.seed(0)\nnp.random.seed(0)                       # legacy global state\nrng = np.random.default_rng(0)          # preferred: an explicit generator you pass around\ntorch.manual_seed(0)                    # CPU and all GPUs"},{"t":"p","runs":[{"text":"The explicit generator is better than the global seed, because two parts of a program drawing from one global stream change each other’s numbers when one of them adds a draw. Give each component its own generator, seeded from a master seed, and adding a draw in one place no longer changes the shuffle in another."}]},{"t":"h2","id":"what-a-seed-does-not-buy","runs":[{"text":"What a seed does not buy"}]},{"t":"p","runs":[{"text":"Bitwise identical training on a GPU.","b":true},{"text":" The previous lessons showed that floating-point addition depends on order and that a GPU adds in whatever order its threads arrive. The seed fixes the dropout mask and the initial weights; it does not fix the reduction order. Two runs with the same seed diverge in their last bits at the first step and in their third digit within a few thousand. "},{"text":"torch.use_deterministic_algorithms(True)","code":true},{"text":" forces fixed-order kernels, at a cost in speed and with some operations refusing to run; it is the price of exact reproducibility, and it is sometimes worth paying."}]},{"t":"p","runs":[{"text":"Identical results across machines.","b":true},{"text":" Different hardware, driver versions and library builds choose different kernels with different orders. Reproducibility across machines is a matter of agreeing to three digits, not thirty-two bits."}]},{"t":"p","runs":[{"text":"A stable split when the data grow.","b":true},{"text":" Shuffling with a seed and taking the first 80 per cent as training is reproducible only until a row is added, after which every row’s position shifts and yesterday’s test examples leak into today’s training set. The fix uses module 7’s hashing: assign each row by a hash of its id, "},{"text":"hash(id) mod 100 < 80","code":true},{"text":", so that a row’s split depends on the row alone. New rows land in either split; old rows never move."}]},{"t":"p","runs":[{"text":"Python’s string hashing.","b":true},{"text":" It is randomised per process by design, which changes the order of iteration over a set of strings from one run to the next. A vocabulary built by iterating a set is different on every run unless "},{"text":"PYTHONHASHSEED","code":true},{"text":" is fixed or the set is sorted first. This is the single most common cause of “the same code produces a different model”."}]},{"t":"h2","id":"turning-uniform-into-anything","runs":[{"text":"Turning uniform into anything"}]},{"t":"p","runs":[{"text":"A generator produces uniform numbers between 0 and 1. Every other distribution is manufactured from those. The general method is the "},{"text":"inverse cumulative distribution","b":true},{"text":": if "},{"text":"F","code":true},{"text":" is the cumulative distribution you want, then "},{"text":"F^(−1)(u)","code":true},{"text":" for uniform "},{"text":"u","code":true},{"text":" has that distribution. For the exponential with rate "},{"text":"λ","code":true},{"text":":"}]},{"t":"code","lang":"","label":"Text","text":"x = −ln(u) / λ"},{"t":"p","runs":[{"text":"For the normal, the inverse has no closed form, and the Box-Muller transform takes two uniforms and returns two independent normals:"}]},{"t":"code","lang":"","label":"Text","text":"z₁ = √(−2 ln u₁) × cos(2π u₂)\nz₂ = √(−2 ln u₁) × sin(2π u₂)"},{"t":"p","runs":[{"text":"For a discrete distribution, a token sampled from a softmax, the method is the same: compute the cumulative sums, draw "},{"text":"u","code":true},{"text":", and pick the first token whose cumulative probability exceeds "},{"text":"u","code":true},{"text":". That is what "},{"text":"torch.multinomial","code":true},{"text":" does, and it is why sampling a token costs a scan over the vocabulary rather than a lookup."}]},{"t":"h2","id":"randomness-you-did-not-ask-for","runs":[{"text":"Randomness you did not ask for"}]},{"t":"p","runs":[{"text":"DataLoader","code":true},{"text":" workers each get a seed derived from the main one plus their worker id; if you seed NumPy inside a worker without that id, all workers produce the same augmentations. Dropout at evaluation time, if the model was never switched out of training mode, makes the same input give different outputs. Sampling with "},{"text":"temperature > 0","code":true},{"text":" is random by intent. And any code that reads the clock, a network, or the filesystem order has a source of variation no seed touches."}]},{"t":"h2","id":"the-habit","runs":[{"text":"The habit"}]},{"t":"p","runs":[{"text":"Seed everything, pass generators explicitly, hash for splits, sort before assigning ids, and expect two GPU runs to agree to three digits rather than exactly. When they agree to fewer, look for the nondeterminism, and when they agree exactly, check that the second run actually ran."}]}],"check":{"question":[{"text":"A team seeds Python, NumPy and PyTorch identically and trains twice on the same GPU, yet the two final models differ in the third decimal place of every weight. What is the most likely cause?"}],"options":[{"text":[{"text":"One of the libraries was not actually seeded, so the initial weights differed."}],"correct":false,"tempting":[{"text":"Different initial weights would produce entirely different models, not ones agreeing to two decimal places; near-agreement is the mark of tiny arithmetic differences compounding."}]},{"text":[{"text":"The pseudo-random generator has a period shorter than the number of draws in a training run and wrapped around."}],"correct":false,"tempting":[{"text":"Periods of 2^128 or more cannot be exhausted; and a wrapped sequence would still be identical between two seeded runs."}]},{"text":[{"text":"GPU sums run in a varying order, and the rounding differences compound."}],"correct":true,"tempting":null},{"text":[{"text":"Dropout produces genuinely random masks that no seed can control."}],"correct":false,"tempting":[{"text":"Dropout masks come from the seeded generator and are identical across the two runs; the nondeterminism is in the summation, not the sampling."}]}],"order":[3,0,2,1],"why":null},"prev":{"slug":"variance-through-a-layer","title":"How variance travels through a layer, and the initialisation that follows","minutes":9},"next":{"slug":"checking-a-gradient-numerically","title":"Checking a gradient with finite differences, and the step size that lies","minutes":9}}}