PyTorch primer5 / 6

Lesson 5 · Gradients, randomness and numbers

Randomness and distributions

The problem

The Maths toolkit was full of chance. A spinner chose delivery times. A mix of two bell curves gave times like 31.7 minutes. A customer wandered between three pizza shops. Each time, you learned the exact answers on paper: the expected value is 32 minutes, and the customer's long-run shares are (0.45,0.35,0.20)(0.45, 0.35, 0.20).

Code can't know those answers in advance. It draws random numbers and averages them, like the Monte Carlo figures did. This lesson shows how PyTorch does that. You'll make the same draws every run, build distributions as objects, and simulate the shops. Every result should land near a number you already know.

Random numbers you can repeat

Seeds

A computer makes "random" numbers with a formula. Each number is worked out from the one before. The formula starts from a number called the seed. The same seed always gives the same list of numbers, called a stream.

torch.manual_seed(n) restarts PyTorch's main stream from seed n. Call it at the top of any experiment you want to repeat. If you forget it, you can't reproduce a result you saw yesterday.

The same seed gives the same numbers
def seeded_draws(seed: int) -> tuple[torch.Tensor, torch.Tensor]:
    """Seed the global generator, then draw twice. The same seed always gives the same pair."""
    torch.manual_seed(seed)
    first = torch.rand(3)   # shape (3,): uniform numbers in [0, 1)
    second = torch.rand(3)  # the next 3 numbers in the same stream: different from `first`
    return first, second


a1, a2 = seeded_draws(0)
b1, b2 = seeded_draws(0)
assert torch.equal(a1, b1) and torch.equal(a2, b2)  # same seed, same stream
assert not torch.equal(a1, a2)                      # but each call moves the stream on

torch.rand(3) makes a tensor of 3 random numbers. Each one is between 0 and 1, and every value is equally likely.

Predict first

You call torch.manual_seed(0), then torch.rand(3) twice. Are the two tensors equal?

Generators: a stream of your own

Every call to torch.rand without extra arguments takes numbers from the one main stream. So if some code adds an extra draw early on, every draw after it changes.

A torch.Generator is a separate stream with its own seed. Pass it as generator= to the random functions:

A private generator
gen = torch.Generator().manual_seed(2)        # a private stream with its own seed
u = torch.rand(3, generator=gen)              # drawn from gen, not the global stream
gen.manual_seed(2)                            # rewind gen to the start of its stream
assert torch.equal(u, torch.rand(3, generator=gen))

Try both streams below. Seed the main stream, draw a few numbers, then seed it again. Draw from the generator in between, and watch the main stream ignore it.

Global stream

Stream seeded with 0

  1. nothing drawn yet

g = torch.Generator().manual_seed(2)

  1. nothing drawn yet
Two random streams. torch.manual_seed restarts the main one, and the same numbers come out again. Drawing from g never moves the main stream. A small stand-in generator makes these numbers, so they differ from PyTorch's; the pattern is the same.

Use torch.manual_seed for a whole script. Use a Generator when one part of the code needs its own repeatable stream, like the customer simulation later in this lesson. The distribution objects below have no generator= argument: their .sample() always draws from the main stream, so seed that with torch.manual_seed.

Random tensors

Four functions cover most needs:

rand, randn, randint and multinomial
torch.manual_seed(0)
uniform = torch.rand(2, 3)               # shape (2, 3): uniform in [0, 1)
bell = torch.randn(5)                    # shape (5,): normal, mean 0, SD 1
toppings = torch.randint(0, 4, (10,))    # shape (10,): integers 0, 1, 2 or 3 (high is excluded)
spins = torch.multinomial(probs, num_samples=10, replacement=True)  # shape (10,): indices 0-3
print(toppings.dtype, spins.dtype)       # torch.int64 torch.int64
  • torch.rand(2, 3) gives a tensor of shape (2, 3), uniform between 0 and 1.
  • torch.randn(5) draws from the normal distribution with mean 0 and standard deviation 1. The "n" stands for normal.
  • torch.randint(0, 4, (10,)) gives 10 whole numbers from 0 up to 3. The upper end, 4, is never drawn, as in Python's range. The shape comes last, as a tuple.
  • torch.multinomial(probs, num_samples=10, replacement=True) draws 10 positions with the chances in probs. Without replacement=True, each position can come up only once.

Predict first

You call torch.multinomial(probs, num_samples=10) with the spinner's 4 probabilities, and leave out replacement=True. What happens?

DigressionSpinning by handDraw a uniform u, then find the slice it lands in, as the spinner in 1.11 did. · 2 min

The spinner from 1.11 drew one uniform number uu and found the slice it landed in. That's the idea behind drawing from a list of probabilities. In code:

Spinning by hand
def spin_by_hand(probs: torch.Tensor, u: torch.Tensor) -> torch.Tensor:
    """Turn uniform numbers u in [0, 1) into outcomes: find the slice each u lands in (1.11)."""
    ends = torch.cumsum(probs, dim=0)                 # where each slice ends: [0.2, 0.7, 0.9, 1.0]
    index = torch.searchsorted(ends, u, right=True)   # first slice whose end is past u
    return index.clamp(max=len(probs) - 1)            # guard against rounding at the very end


print(spin_by_hand(probs, torch.tensor([0.1, 0.5, 0.75, 0.95])))  # tensor([0, 1, 2, 3])
  • torch.cumsum(probs, dim=0) gives running totals, [0.2, 0.7, 0.9, 1.0]: where the slices end.
  • torch.searchsorted(ends, u, right=True) finds, for each u, the first slice end past it. That's the slice's position.
  • .clamp(max=3) caps every position at 3. Rounding can leave the last end a hair below 1.

Distributions as objects

Categorical: the spinner

Writing the spinner by hand works, but PyTorch has ready-made distributions in torch.distributions. Each one is an object with the same methods. The spinner is a categorical distribution:

The spinner as a Categorical
torch.manual_seed(0)
spinner = Categorical(probs=probs)      # a distribution over the outcomes 0, 1, 2, 3
draws = spinner.sample((1000,))         # shape (1000,): 1000 spins at once, as indices
minutes = times[draws]                  # shape (1000,): the same spins in minutes
shares = torch.bincount(draws, minlength=4) / 1000  # close to probs, not equal
print(shares)                           # tensor([0.1990, 0.5070, 0.1840, 0.1100])
print(spinner.log_prob(torch.tensor(1)))  # tensor(-0.6931) = log 0.5
  • Categorical(probs=probs) is a distribution over the positions 0, 1, 2 and 3. Name the argument. Categorical also accepts scores as logits=, and naming it says which one you mean.
  • .sample((1000,)) draws 1,000 spins at once. The argument is the shape you want. The result holds positions, not minutes. times[draws] indexes with a whole tensor of positions: it picks one entry of times per draw, so it turns 1,000 positions into 1,000 minutes.
  • torch.bincount(draws, minlength=4) counts each position. minlength=4 keeps all four counts, even for an outcome that never came up.
  • .log_prob(x) gives the log-probability of x. For position 1, that's log⁡0.5=−0.6931\log 0.5 = -0.6931.

The shares come out as (0.199, 0.507, 0.184, 0.110). They're close to (0.2, 0.5, 0.2, 0.1), but not equal, as in the spinning figure in 1.11.

Normal and Uniform

Continuous distributions have the same methods. For a density, .log_prob(t) is the log of the curve's height at t.

A normal and a uniform
light = Normal(loc=30.0, scale=4.0)     # N(30, 4²): scale is the SD, not the variance
t = torch.tensor([25.0, 30.0, 35.0])
print(light.log_prob(t).exp())          # tensor([0.0457, 0.0997, 0.0457]): heights, not probabilities
print(light.cdf(t))                     # tensor([0.1056, 0.5000, 0.8944]): areas to the left
wait = Uniform(low=2.0, high=6.0)       # a door wait of 2 to 6 minutes
print(wait.log_prob(torch.tensor(3.0)).exp())  # tensor(0.2500)
  • Normal(loc=30.0, scale=4.0) is light traffic, N(30,42)\mathcal{N}(30, 4^2). loc is the mean. scale is the standard deviation, not the variance.
  • .log_prob(t).exp() undoes the log, giving the height of the density. A height is not a probability.
  • .cdf(t) gives the CDF: the area to the left of t.
  • Uniform(low=2.0, high=6.0) is the door wait from 1.13. Its height is 1/4=0.251/4 = 0.25 everywhere from 2 to 6.

Distributions check their inputs. Normal(loc=30.0, scale=-1.0) raises a ValueError, because a standard deviation can't be negative.

Batches of distributions

The delivery model in 1.13 had two normals: light traffic N(30,42)\mathcal{N}(30, 4^2) and heavy traffic N(40,82)\mathcal{N}(40, 8^2). Give Normal a tensor of means and a tensor of standard deviations, and one object holds both:

Two normals in one object
both = Normal(loc=torch.tensor([30.0, 40.0]), scale=torch.tensor([4.0, 8.0]))  # light, heavy
print(both.batch_shape, both.event_shape)   # torch.Size([2]) torch.Size([])
x = both.sample((5,))                        # shape (5, 2): 5 draws from each normal
print(both.log_prob(torch.tensor(35.0)))     # tensor([-3.0865, -3.1937]): 35 scored by each normal
print(both.log_prob(x).shape)                # torch.Size([5, 2])

spinners = Categorical(probs=torch.tensor([[0.2, 0.5, 0.2, 0.1],
                                           [0.4, 0.3, 0.2, 0.1],
                                           [0.25, 0.25, 0.25, 0.25]]))  # 3 spinners, one per row
print(spinners.batch_shape, spinners.sample((5,)).shape)  # torch.Size([3]) torch.Size([5, 3])

The object's batch_shape is torch.Size([2]): it holds a batch of 2 separate distributions. Its event_shape is empty, because each draw is a single number.

Predict first

both = Normal(loc=torch.tensor([30., 40.]), scale=torch.tensor([4., 8.])). What is the shape of both.sample((5,))?

The rule is: .sample(sample_shape) returns sample_shape + batch_shape + event_shape. .log_prob(x) scores each number, so it returns sample_shape + batch_shape. Change the distribution and the sample shape below:

dist = Normal(loc=torch.tensor([30.0, 40.0]), scale=torch.tensor([4.0, 8.0]))

x = dist.sample((5,))

dist.batch_shape = torch.Size([2])

x.shape = torch.Size([5, 2])

dist.log_prob(x).shape = torch.Size([5, 2])

Each colour is one of the 2 distributions in the batch: the batch shape goes last.

The shape of a sample is the sample shape, then the batch shape. Each colour is one distribution in the batch. log_prob gives one score per drawn number, so it has the same shape here.

.log_prob(torch.tensor(35.0)) gives tensor([-3.0865, -3.1937]): 35 minutes scored by each normal. The single 35 is broadcast against the batch of 2. A Categorical whose probs has shape (3, 4) is a batch of 3 spinners, one per row.

DigressionThe 80/20 mixture as one distributionMixtureSameFamily picks the kind of trip, then draws from that kind's normal. · 2 min

The shop's model in 1.13 was a mixture: 80% of trips are light traffic and 20% heavy. To draw a time, first spin a two-slice spinner for the kind of trip, then draw from that kind's normal.

The delivery-time model
def delivery_model() -> MixtureSameFamily:
    """80% light traffic, N(30, 4²); 20% heavy traffic, N(40, 8²). The mixture from 1.13."""
    traffic = Categorical(probs=torch.tensor([0.8, 0.2]))  # which kind of trip
    kinds = Normal(loc=torch.tensor([30.0, 40.0]), scale=torch.tensor([4.0, 8.0]))  # batch of 2
    return MixtureSameFamily(traffic, kinds)


model = delivery_model()
print(model.batch_shape, model.mean, model.stddev)  # torch.Size([]) tensor(32.) tensor(6.4498)

MixtureSameFamily(traffic, kinds) takes a Categorical (which kind) and a batch of distributions of the same type (one per kind). The two normals combine into one distribution, so batch_shape is empty. It has .sample, .log_prob, .cdf, .mean and .stddev. The mean is 32 and the standard deviation 6.4498, as worked out by hand in 1.13. Like every distribution's, its .log_prob works with autograd, so a model can learn the means and standard deviations.

Estimating by sampling

Monte Carlo

A Monte Carlo estimate averages a function over samples. In code, that's .mean() over a sampled tensor:

Monte Carlo estimates
def monte_carlo(dist: MixtureSameFamily, n: int) -> tuple[torch.Tensor, torch.Tensor]:
    """Estimate E[T] and P(T > 40) by averaging over n samples."""
    samples = dist.sample((n,))                    # shape (n,)
    mean_estimate = samples.mean()                 # average of t
    late_estimate = (samples > 40).float().mean()  # average of "1 if over 40, else 0"
    return mean_estimate, late_estimate


torch.manual_seed(0)
for n in [10, 1_000, 100_000]:
    m, over_40 = monte_carlo(model, n)
    print(f"n={n:>7,}: E[T] ~ {m.item():.2f}, P(T > 40) ~ {over_40.item():.3f}")

(samples > 40) gives a tensor of True/False. .float() turns those into 1.0 and 0.0, so .mean() gives the share of samples over 40 minutes. The output:

n=     10: E[T] ~ 30.21, P(T > 40) ~ 0.100
n=  1,000: E[T] ~ 31.80, P(T > 40) ~ 0.091
n=100,000: E[T] ~ 32.02, P(T > 40) ~ 0.106

The exact answers are 32 and 0.105. The estimates get closer as nn grows, at the 1/n1/\sqrt{n} rate from 1.12. This is the Monte Carlo figure from 1.13, now with the code that matches it:

01020304050607000.050.1delivery time (minutes)density

Ticks on the axis: the sampled times.

0246810203040number of samplesestimatetrue 32.00

After 1 sample: estimate 29.61 min

The average of the sampled times. The true value is 32.00 min.

Step 0 of 12
Monte Carlo: each step draws more delivery times. The running average of t estimates E[T] = 32, and the share over 40 minutes estimates P(T > 40) = 0.105.

The incremental mean in code

The incremental mean updates an estimate one sample at a time: μ^←μ^+α(x−μ^)\hat\mu \leftarrow \hat\mu + \alpha(x - \hat\mu). When every running average is wanted at once, there's no need for a loop:

Running means, with and without a loop
def running_means(x: torch.Tensor) -> torch.Tensor:
    """The average of the first 1, 2, 3, ... samples, all at once, with no loop."""
    n = torch.arange(1, len(x) + 1, dtype=x.dtype)  # [1, 2, 3, ...]
    return torch.cumsum(x, dim=0) / n                # running total / count


def incremental(x: torch.Tensor, alpha: float | None = None, start: float = 0.0) -> torch.Tensor:
    """estimate <- estimate + step * (sample - estimate). alpha=None means step = 1/n (1.12)."""
    estimates = torch.empty_like(x)  # same shape and dtype as x; every entry is filled below
    estimate = torch.tensor(start, dtype=x.dtype)
    for i, sample in enumerate(x):
        step = 1.0 / (i + 1) if alpha is None else alpha
        estimate = estimate + step * (sample - estimate)
        estimates[i] = estimate
    return estimates


hand = torch.tensor([30.0, 40.0, 20.0, 30.0, 50.0])
print(incremental(hand))             # tensor([30., 35., 30., 30., 34.])
print(incremental(hand, alpha=0.5))  # tensor([15.0000, 27.5000, 23.7500, 26.8750, 38.4375])
assert torch.allclose(incremental(hand), running_means(hand))
  • running_means divides the running totals, torch.cumsum(x, dim=0), by the counts 1,2,3,…1, 2, 3, \dots from torch.arange(1, n + 1). One line, no loop.
  • incremental is the update rule, line for line. Each estimate needs the one before, so it loops. torch.empty_like(x) makes a tensor with the shape and dtype of x, with its values not yet set. The loop fills it in.
  • With α=1/n\alpha = 1/n the two agree: 30, 35, 30, 30, 34, as in the worked example in 1.12. With α=0.5\alpha = 0.5 you get 15, 27.5, 23.75, 26.875, 38.4375.

Predict first

You call incremental(torch.tensor([30, 40, 20, 30, 50]), alpha=0.5). The numbers have no decimal points. What comes back?

To repeat a whole experiment many times, add an axis instead of a loop:

10,000 runs at once
def spread_of_means(n: int, runs: int = 10_000) -> torch.Tensor:
    """Average n spins, `runs` times at once, and measure how much the averages vary."""
    grid = spinner.sample((runs, n))     # shape (runs, n): one row per run
    means = times[grid].mean(dim=1)      # shape (runs,): one average per run
    return means.std()                   # about 8.72 / sqrt(n)


torch.manual_seed(0)
print([round(spread_of_means(n).item(), 2) for n in (1, 4, 16)])  # [8.75, 4.34, 2.18]

spinner.sample((runs, n)) draws a table with one row per run, and .mean(dim=1) averages each row. .std() measures how much the averages spread out. The last line prints [8.75, 4.34, 2.18] for nn = 1, 4 and 16, close to 8.72/n8.72/\sqrt{n}. The table in 1.12 says 8.74, 4.35 and 2.19, because it came from a separate simulation with other random numbers.

Simulating the pizza shops

In 1.14, one customer moved between shops A, B and C each week, with the transition matrix TT. Its stationary distribution is d=(0.45,0.35,0.20)\mathbf{d} = (0.45, 0.35, 0.20). Now simulate her:

One customer's walk
T = torch.tensor([[0.8, 0.1, 0.1],   # from A
                  [0.2, 0.7, 0.1],   # from B
                  [0.1, 0.3, 0.6]])  # from C      shape (3, 3); each row adds to 1


def simulate_walk(T: torch.Tensor, start: int, weeks: int, seed: int = 0) -> torch.Tensor:
    """One customer's path: each week, draw next week's shop from this week's row of T."""
    gen = torch.Generator().manual_seed(seed)  # its own seeded stream
    path = [start]
    for _ in range(weeks):
        row = T[path[-1]]                      # shape (3,): chances of each shop next week
        path.append(torch.multinomial(row, num_samples=1, generator=gen).item())
    return torch.tensor(path)                  # shape (weeks + 1,)


path = simulate_walk(T, start=1, weeks=10_000, seed=2)
print(torch.bincount(path, minlength=3) / len(path))  # tensor([0.4505, 0.3510, 0.1986])

Each week, T[path[-1]] picks this week's row: the chances for next week. torch.multinomial(row, num_samples=1, generator=gen) draws one position from it, as a tensor like tensor([0]). .item() turns that into a plain Python number. A Python loop is right here, because week 5 needs week 4.

Step through the loop below. Each week shows the row, the uniform number uu and the slice it lands in. The bars are the visit shares so far.

Week 0: path = [1] (she starts at B)

ABC

torch.bincount(path, minlength=3) / len(path), weeks 0 to 0

  • A0.00
  • B1.00
  • C0.00

Dashed lines: d = (0.45, 0.35, 0.20)

Week 0 of 200
The simulation loop, week by week. The row of T for this week's shop is split into slices, and u lands in one of them. torch.multinomial never shows its u, so the figure draws u by hand as in 1.11, with a stand-in generator: its path is not the code's path. The visit shares creep towards d (dashed), slowly, because her weeks are linked.

With seed 2 and 10,000 weeks, the code's visit shares are (0.4505, 0.3510, 0.1986), close to d\mathbf{d}.

Many customers at once

One customer takes many weeks to settle. Instead, follow 100,000 customers for a few weeks, all in one tensor:

100,000 customers, one call per week
def simulate_crowd(T: torch.Tensor, start: int, customers: int, weeks: int, seed: int = 0) -> torch.Tensor:
    """Many customers at once: one multinomial call per week moves all of them."""
    gen = torch.Generator().manual_seed(seed)
    shops = torch.full((customers,), start)    # shape (customers,): everyone starts at `start`
    for _ in range(weeks):
        rows = T[shops]                        # shape (customers, 3): each customer's row
        shops = torch.multinomial(rows, num_samples=1, generator=gen).squeeze(1)  # (customers,)
    return torch.bincount(shops, minlength=3) / customers


print(simulate_crowd(T, start=1, customers=100_000, weeks=1, seed=0))   # close to row B: (0.2, 0.7, 0.1)
print(simulate_crowd(T, start=1, customers=100_000, weeks=30, seed=0))  # close to d = (0.45, 0.35, 0.20)
  • torch.full((customers,), start) makes a tensor with every entry equal to start: everyone begins at B.
  • T[shops] picks one row per customer, giving shape (100000, 3).
  • torch.multinomial on a 2-D tensor draws once from each row, giving shape (100000, 1). .squeeze(1) drops the size-1 axis to give (100000,).

After 1 week the shares are close to row B, (0.2,0.7,0.1)(0.2, 0.7, 0.1). After 30 weeks they are (0.4475, 0.3499, 0.2026), close to d\mathbf{d}. These are the chances d0Tn\mathbf{d}_0 T^n from 1.14, estimated by Monte Carlo. The figure from 1.14 shows the exact chances week by week; the crowd's shares follow the same path.

A0.00B1.00C0.000.80.10.10.20.70.10.10.30.6
05101520253000.20.40.60.81weekchance

Week 0: d = (0.00, 1.00, 0.00)

Next week at A: 0.00 × 0.8 + 1.00 × 0.2 + 0.00 × 0.1 = 0.20

Largest gap from (0.45, 0.35, 0.20): 0.6500

Week 0 of 30
The exact chances d₀Tⁿ, week by week. With the start at B (the default), the simulated crowd of 100,000 customers lands within about 0.005 of these bars.

Common misconceptions

"torch.manual_seed makes every draw the same." It fixes the stream. Each draw takes the next numbers from it, so two draws differ, but the whole sequence repeats when you run the script again.

"Normal(30, 16) is the normal with variance 16." Normal takes the standard deviation, so this is N(30,162)\mathcal{N}(30, 16^2). For variance 16, write Normal(30.0, 4.0).

".sample((5,)) always has shape (5,)." Only for a single distribution. A batch of 2 gives (5, 2).

".log_prob gives a probability." It gives a log. For a continuous distribution it's the log of a density's height, which can be above 0.

Recap

  • A seed fixes a whole random stream. torch.manual_seed restarts the main one; a Generator is a stream of your own.
  • torch.distributions objects share .sample(shape) and .log_prob(x). Samples have shape sample_shape + batch_shape.
  • Parameters given as tensors make a batch of distributions in one object.
  • A Monte Carlo estimate is .mean() over samples. Running means need no loop; the constant-step update does.
  • Simulations that step through time loop over time, but handle many runs at once in one tensor.
  • PyTorch names in this lesson: torch.manual_seed, torch.Generator, torch.rand, torch.randn, torch.randint, torch.multinomial, torch.cumsum, torch.searchsorted, torch.bincount, torch.distributions (Categorical, Normal, Uniform, MixtureSameFamily, .sample, .log_prob, .cdf, batch_shape), torch.arange, torch.empty_like, torch.full, .std, .float, .item and .squeeze.