PyTorch primer6 / 6

Lesson 6 · Gradients, randomness and numbers

Numbers and stability

The problem

In the Maths toolkit, softmax of the topping scores (2,1,0,−1)(2, 1, 0, -1) was (0.644,0.237,0.087,0.032)(0.644, 0.237, 0.087, 0.032). Adding 100 to every score changed nothing, because only the gaps matter. The chance of 200 orders was about 8×10−1268 \times 10^{-126}.

Ask PyTorch the same questions the textbook way, and two of the answers break:

  • softmax of (102,101,100,99)(102, 101, 100, 99) comes out as nan ("not a number") in every entry
  • the product of the 200 probabilities comes out as exactly 0

The maths isn't wrong. A computer stores each number with a fixed number of digits, so huge, tiny and nearly equal numbers go wrong. This lesson shows where the limits are, and the tools PyTorch gives you to stay inside them. Those tools are also why its loss functions take the arguments they do.

How PyTorch stores numbers

float32 and float64

A tensor's dtype says how each number is stored. PyTorch's default for decimals is float32: 32 bits per number, about 7 significant digits. float64 uses 64 bits, about 16 digits.

Default dtypes and their limits
print(torch.get_default_dtype())             # torch.float32: the default for new float tensors
print(torch.tensor(0.1).item())              # 0.10000000149011612: the nearest float32 to 0.1
print(torch.tensor(0.1, dtype=torch.float64).item())  # 0.1 (to 17 digits, 0.1000000000000000055...)
print(torch.tensor([1, 2]).dtype)            # torch.int64: whole numbers make an integer tensor

f32, f64 = torch.finfo(torch.float32), torch.finfo(torch.float64)
print(f32.eps, f64.eps)        # 1.1920928955078125e-07 2.220446049250313e-16: gap after 1
print(f32.max, f32.tiny)       # 3.4028234663852886e+38 1.1754943508222875e-38
  • torch.tensor(0.1) holds 0.10000000149011612, the float32 closest to 0.1. Most decimals can't be stored exactly.
  • torch.finfo(dtype) reports a float type's limits. eps is the gap between 1 and the next number the type can store. max is the largest number before infinity, and tiny, 1.18×10−381.18 \times 10^{-38}, is the smallest positive number stored with full precision. Below tiny, float32 keeps fewer and fewer digits, down to 1.4×10−451.4 \times 10^{-45}.

Models train in float32 because it uses half the memory of float64 and is much faster on GPUs. That's usually enough, as long as you avoid the traps below. Use float64 for careful checks. Convert with .double() (or .to(torch.float64)), and back with .float().

The gaps between numbers

Floats are spaced out. Near 1, the next float32 is 1+1.19×10−71 + 1.19 \times 10^{-7}. Nothing in between can be stored, so a result in that gap rounds to one of its ends. The gap grows with the size of the number: it doubles at every power of 2.

Move the slider below to see the gap at different sizes.

1e−51e01e51e101e−201e−151e−101e−51e0x (log scale)gap above xfloat32float64

Gap to the next float32: 2.38e−7 (7.95e−8 of x)

Gap to the next float64: 4.44e−16

In float32, x + 1 is stored as 4

The relative gap stays between 5.96e−8 and 1.19e−7: about 7 significant digits.

The gap between neighbouring floats grows with the number: it's always about 10⁻⁷ of the number in float32, and 10⁻¹⁶ in float64. Past 2²⁴ = 16,777,216 the float32 gap is 2, so adding 1 does nothing.
Gaps, and adding numbers that don't fit
def gap_above(x: float, dtype: torch.dtype = torch.float32) -> float:
    """The distance from x to the next number this dtype can store."""
    t = torch.tensor(x, dtype=dtype)
    return (torch.nextafter(t, torch.tensor(float("inf"), dtype=dtype)) - t).item()


print(gap_above(1.0), gap_above(3.0), gap_above(16_777_216.0))  # 1.19e-07  2.38e-07  2.0
three = torch.tensor(3.0)
print(three + 1e-7 == three)                     # tensor(True): the nudge rounds away
print(torch.tensor(16_777_216.0) + 1)            # tensor(16777216.): 2**24 + 1 can't be stored

a, b, c = torch.tensor(0.1), torch.tensor(0.2), torch.tensor(0.3)
print(a + b == c)                                # tensor(True) in float32, by luck of rounding
print(a.double() + b.double() == c.double())     # tensor(False) in float64
print(torch.isclose(a.double() + b.double(), c.double()))  # tensor(True): compare with a tolerance

torch.nextafter(x, y) gives the next float after x in the direction of y. So gap_above(3.0) is 2.38×10−72.38 \times 10^{-7}. A nudge of 10−710^{-7} is less than half that gap, so three + 1e-7 rounds back to exactly 3.

That's why the nudge test fails in float32, as in the float aside in the autograd lesson. The limit in 1.6 shrinks hh towards 0. In float32, hh can't usefully go below about 10−410^{-4}.

Predict first

In float32, is torch.tensor(0.1) + torch.tensor(0.2) == torch.tensor(0.3)?

Overflow: exp past 88.7

The largest float32 is about 3.4×10383.4 \times 10^{38}. Anything bigger becomes inf (infinity). This is called overflow. For the exponential, the limit is log⁡(3.4×1038)≈88.72\log(3.4 \times 10^{38}) \approx 88.72:

exp overflows, and so does the textbook softmax
print(torch.exp(torch.tensor([88.7, 88.8])))     # tensor([3.3260e+38, inf]): past ~88.72, exp overflows
print(torch.log(torch.tensor(f32.max)))          # tensor(88.7228)


def softmax_naive(z: torch.Tensor) -> torch.Tensor:
    """The textbook formula. Breaks once a score passes about 88.7."""
    return torch.exp(z) / torch.exp(z).sum(dim=-1, keepdim=True)


big = scores + 100                               # (102, 101, 100, 99): same gaps, same answer
print(softmax_naive(big))                        # tensor([nan, nan, nan, nan]): inf / inf
print(torch.softmax(big, dim=-1))                # tensor([0.6439, 0.2369, 0.0871, 0.0321])

torch.exp(88.7) is 3.3×10383.3 \times 10^{38}, but torch.exp(88.8) is inf. The textbook softmax, softmax_naive, divides inf by a sum that is also inf. That gives nan.

Predict first

Add 87 to the scores (2, 1, 0, −1) and use softmax_naive. Which entries come out as nan?

Slide the amount added below. The top bars use the textbook formula in float32. The bottom bars subtract the biggest score first.

Scores: (82, 81, 80, 79). exp(82) in float32 = 4.09e+35

Textbook formula, float32

  • pepperoni0.644
  • margherita0.237
  • veggie0.087
  • hawaiian0.032

Subtract the biggest score first

  • pepperoni0.644
  • margherita0.237
  • veggie0.087
  • hawaiian0.032

Both agree

logsumexp(scores) = 82.4402

The probabilities should never change, because only gaps between scores matter. Once a score passes about 88.7, its exp becomes inf. That entry becomes NaN and the smaller ones collapse to 0. Push further and every entry is NaN. The safe version doesn't notice.

The fix is the maths from 1.15: subtract the biggest score, so the biggest exponential is e0=1e^0 = 1 (see logsumexp). torch.softmax(z, dim=-1) applies softmax along one axis, and does this for you. dim=-1 means the last axis. That's why torch.softmax(big, dim=-1) gives the right answer. Call the built-in functions rather than writing torch.exp(z) / torch.exp(z).sum().

Underflow: products of probabilities

The opposite problem is a number too close to 0. The smallest positive float32 is about 1.4×10−451.4 \times 10^{-45}. Anything smaller rounds to exactly 0. This is called underflow.

Take the 200 orders from 1.15, and multiply the model's probability for each one:

The product underflows; the sum of logs doesn't
orders = torch.tensor([0, 1, 0, 2, 0, 1, 3, 0, 1, 2]).repeat(20)  # shape (200,): 200 orders
q = torch.softmax(scores, dim=-1)                # (0.644, 0.237, 0.087, 0.032)
chances = q[orders]                              # shape (200,): the model's chance of each order

running = torch.cumprod(chances, dim=0)          # the product after 1, 2, ..., 200 orders
first_zero = int((running == 0).nonzero()[0]) + 1
print(first_zero, running[72].item())            # 74 1.401298464324817e-45: the smallest float32
print(chances.prod())                            # tensor(0.): underflow
print(chances.double().prod())                   # tensor(8.0671e-126, dtype=torch.float64)
print(torch.log(chances).sum())                  # tensor(-288.0379): sums of logs are fine
  • .repeat(20) copies the 10-order pattern end to end 20 times.
  • q[orders] picks the model's chance for each of the 200 orders, by indexing with a tensor of positions as in 2.5.
  • torch.cumprod gives the running product after 1, 2, …, 200 orders. .nonzero() gives the positions of entries that aren't 0 or False. [0] takes the first, and + 1 turns position 73 into order 74.
  • .prod() multiplies every entry together.

Step through the orders below and watch the product.

050100150200−300−250−200−150−100−500orders so farlog-probabilityproduct hits 0

Order 0: none yet

Product of probabilities (float32): 1.00e+0

Sum of log-probabilities: 0.00

Order 0 of 200
The product of probabilities underflows to exactly 0 after 74 orders. The sum of log-probabilities goes down in steady steps and ends at −288.04, a number any computer can store.

At order 62 the product drops below tiny, and from there it keeps fewer and fewer digits. At order 73 the true product is 1.6×10−451.6 \times 10^{-45}, which rounds to 1.4×10−451.4 \times 10^{-45}, the smallest float32 above 0. One more order and it's 0. float64 gets the right 8.07×10−1268.07 \times 10^{-126}, but about 520 orders would underflow it too. The sum of log-probabilities, −288.04-288.04, never has this problem. So ML code works with log-probabilities.

log_softmax and logsumexp

To get log-probabilities from scores, don't take the log of softmax. Use log-softmax:

Log of softmax, or log_softmax
two = torch.tensor([0.0, -200.0])
print(torch.log(torch.softmax(two, dim=-1)))     # tensor([0., -inf]): softmax rounded e^-200 to 0
print(torch.log_softmax(two, dim=-1))            # tensor([   0., -200.]): never forms the tiny number

log_q = torch.log_softmax(scores, dim=-1)        # tensor([-0.4402, -1.4402, -2.4402, -3.4402])
print(log_q[orders].sum())                       # tensor(-288.0379), straight from the scores

torch.log_softmax(z, dim=-1) gives log-probabilities straight from the scores. Softmax never gives exactly 0 on paper (see 1.16). In float32 it can: with scores (0,−200)(0, -200), e−200e^{-200} rounds to 0, and torch.log of 0 is -inf. torch.log_softmax computes zi−logsumexp(z)z_i - \mathrm{logsumexp}(\mathbf{z}) instead. It never forms the tiny number, so it gives the right −200-200.

torch.logsumexp(z, dim=-1) computes log⁡∑jezj\log \sum_j e^{z_j} safely. For (100,101,102)(100, 101, 102) it gives 102.4076, where torch.log(torch.exp(z).sum()) gives inf. Log-softmax is the scores minus logsumexp. The figure from 1.15 shows that shift:

pepp.marg.veggiehawai.−10−505score / log-probabilitylogsumexp 2.44

Pale bars: scores. Solid bars: log-probabilities = score − 2.44.

logsumexp = 2.44 · biggest score = 2.00 · gap 0.44

Log-probabilities: pepperoni −0.44, margherita −1.44, veggie −2.44, hawaiian −3.44

Log-probabilities are the scores shifted down by logsumexp. torch.log_softmax computes exactly this shift, and torch.logsumexp gives its size.
Digressionlogsumexp by handSubtract the biggest score, then add it back after the log, as in 1.15. · 2 min
logsumexp, built in and by hand
z = torch.tensor([100.0, 101.0, 102.0])
print(torch.log(torch.exp(z).sum()))             # tensor(inf)
print(torch.logsumexp(z, dim=-1))                # tensor(102.4076)


def logsumexp_by_hand(z: torch.Tensor) -> torch.Tensor:
    """m + log Σ exp(z - m): the biggest exponential is e^0 = 1, so nothing overflows."""
    m = z.max(dim=-1, keepdim=True).values       # keepdim so m broadcasts against z
    return (m + torch.log(torch.exp(z - m).sum(dim=-1, keepdim=True))).squeeze(-1)


assert torch.allclose(logsumexp_by_hand(z), torch.logsumexp(z, dim=-1))
assert torch.allclose(log_q, scores - torch.logsumexp(scores, dim=-1))  # log-softmax = z - logsumexp

The by-hand version is the maths from 1.15: subtract the biggest score m, then add it back after the log. z.max(dim=-1, keepdim=True) returns the biggest value along the last axis (in .values), and keepdim=True keeps that axis so m broadcasts against z. .squeeze(-1) removes the kept axis at the end. The last line checks that log-softmax is z−logsumexp(z)\mathbf{z} - \mathrm{logsumexp}(\mathbf{z}).

Loss functions: F.cross_entropy

The cross-entropy measures a model's average surprise at what happened. It's the usual loss for classifiers. torch.nn.functional holds PyTorch's losses, and it's usually imported as F.

F.cross_entropy takes scores
batch_scores = scores.expand(10, -1)             # shape (10, 4): one row of scores per order
targets = orders[:10]                            # shape (10,): the topping index of each order
print(F.cross_entropy(batch_scores, targets))    # tensor(1.4402): mean of -log q[target]
print(F.cross_entropy(batch_scores, targets, reduction="none")[:3])  # tensor([0.4402, 1.4402, 0.4402])
print(F.cross_entropy(scores.unsqueeze(0), p.unsqueeze(0)))  # tensor(1.4402): a probability target, H(p, q)

The code first builds a batch. scores.expand(10, -1) repeats the topping scores as 10 rows without copying memory; -1 means "keep this size". A real model would give each order its own scores.

F.cross_entropy(scores, target) does two jobs in one: log-softmax on the scores, then the cross-entropy. So:

  • Its first argument is scores (logits), not probabilities. Doing both steps together lets it use the safe log-softmax.
  • Classes go on dim 1. The scores have shape (batch, classes), where a batch is a group of examples handled together.
  • The target can be class positions, one int64 per example, like targets. The result is the average of −log⁡qtarget-\log q_{\text{target}} over the batch: 1.4402.
  • Or it can be probabilities, with the same shape as the scores. .unsqueeze(0) gives scores and p a batch axis of size 1, shape (1, 4). Then it computes H(p,q)H(p, q) directly: also 1.4402.
  • reduction="none" returns one loss per example instead of the average.

Predict first

You pass probabilities by mistake: F.cross_entropy(q, p), where q = torch.softmax(scores, dim=-1). What happens?

Pick a target layout below to see where the classes sit:

scores (3, 4)

columns: classes (dim 1)

target (3,), int64

one class position each

F.cross_entropy(scores, targets)

With reduction="none" the loss has shape (3,): one number per example.

F.cross_entropy wants the classes on dim 1 of the scores. Class positions drop that dim; probabilities match the scores' shape. For sequences, the classes still go on dim 1, so (batch, position, class) scores need a transpose.
DigressionSequences: classes still on dim 1Scores shaped (batch, position, class) need a transpose first. · 2 min

When each example has several positions, like a run of orders, the classes still go on dim 1:

Classes on dim 1
seq_scores = torch.randn(2, 5, 4)                # (batch, position, class): 2 runs of 5 orders
seq_targets = torch.zeros(2, 5, dtype=torch.long)  # (batch, position)
# F.cross_entropy(seq_scores, seq_targets) raises: "Expected target size [2, 4], got [2, 5]"
loss = F.cross_entropy(seq_scores.transpose(1, 2), seq_targets)  # classes moved to dim 1: (2, 4, 5)
print(loss.shape)                                # torch.Size([]): one number, averaged over 10 orders

Predict first

seq_scores has shape (2, 5, 4): 2 runs, 5 orders each, 4 toppings. The targets have shape (2, 5). What does F.cross_entropy(seq_scores, seq_targets) do?

Loss functions: F.kl_div

The KL divergence DKL(p ∥ q)D_{\mathrm{KL}}(p \,\Vert\, q) is the extra surprise from believing qq when outcomes follow pp. For the topping model it's 0.1603.

F.kl_div and kl_divergence
log_q_batch = log_q.unsqueeze(0)                 # shape (1, 4): a batch of one
p_batch = p.unsqueeze(0)                         # shape (1, 4)
print(F.kl_div(log_q_batch, p_batch, reduction="batchmean"))  # tensor(0.1603) = KL(p ‖ q)
print(kl_divergence(Categorical(probs=p), Categorical(logits=scores)))  # tensor(0.1603), maths order

F.kl_div(input, target) has three conventions that trip people up:

  • Argument order: the first argument is the model, the second the real distribution. It computes DKL(target ∥ input)D_{\mathrm{KL}}(\text{target} \,\Vert\, \text{input}), so the model comes first in the call but second in the maths.
  • Log-probabilities in: input must be the model's log-probabilities, from torch.log_softmax. target is plain probabilities.
  • reduction="batchmean": this adds up each example's terms and averages over the batch, giving the true KL. It divides by the size of dim 0, so the tensors need a batch axis first. .unsqueeze(0) adds one, turning shape (4,) into (1, 4).

Choose a call below to see which KL it computes:

1st argument: input

the model, as log-probabilities

2nd inside KL

2nd argument: target

reality, as probabilities

1st inside KL

F.kl_div(log_q, p) computes KL(p ‖ q) = 0.1603

Right: the model q goes first, as log-probabilities.

F.kl_div(input, target) computes KL(target ‖ input). The model goes first in the call but second in the maths, and it must be log-probabilities.

torch.distributions.kl_divergence(a, b) takes two distribution objects and gives DKL(a ∥ b)D_{\mathrm{KL}}(a \,\Vert\, b), in the same order as the maths. Prefer it when you have distribution objects.

DigressionFour silent mistakesEach runs without an error and prints a wrong number. · 2 min
Four silent mistakes
# Each line runs without an error and prints a wrong number.
print(F.cross_entropy(q, p))                     # tensor(1.3175): probabilities in, softmax applied twice
print(F.kl_div(q.unsqueeze(0), p_batch, reduction="batchmean"))  # tensor(-1.6291): probabilities, not logs
print(F.kl_div(log_q_batch, p_batch, reduction="mean"))   # tensor(0.0401) and a warning: divides by all 4 entries
print(F.kl_div(log_q, p, reduction="batchmean"))  # tensor(0.0401): no batch axis, so it divides by 4
  • Probabilities into F.cross_entropy: 1.3175, softmax applied twice.
  • Probabilities into F.kl_div: −1.6291-1.6291. A negative KL is impossible, so a negative result is one sign of this mistake.
  • reduction="mean" (the default): 0.0401. It divides by all 4 entries, not by the batch of 1. PyTorch also prints a warning that this will change in the next major release.
  • No batch axis: 0.0401 again. With shape (4,), "batchmean" divides by dim 0, which is the 4 toppings.

Categorical's entropy and log_prob

A Categorical built from scores handles the log-space work for you:

Entropy and log_prob without the traps
model = Categorical(logits=scores)               # applies log-softmax for you
actual = Categorical(probs=p)
print(model.logits)                              # tensor([-0.4402, -1.4402, -2.4402, -3.4402])
print(actual.entropy(), model.entropy())         # tensor(1.2799) tensor(0.9475)
print(-model.log_prob(targets).mean())           # tensor(1.4402): the cross-entropy again
certain = torch.tensor([1.0, 0.0, 0.0, 0.0])
print(-(certain * torch.log(certain)).sum())     # tensor(nan): 0 * log 0 = 0 * -inf
print(torch.special.entr(certain).sum())         # tensor(0.): entr(0) is defined as 0
print(Categorical(probs=certain).entropy())      # tensor(1.1921e-07): about 0, no nan
  • Categorical(logits=scores) normalises the scores. Its .logits holds the normalised log-probabilities, the log-softmax of the scores: (−0.4402,−1.4402,−2.4402,−3.4402)(-0.4402, -1.4402, -2.4402, -3.4402). They are not the raw scores (2,1,0,−1)(2, 1, 0, -1) you passed in.
  • .entropy() gives the entropy. For the real orders it's 1.2799. For the model, 0.9475: the model is more certain than reality.
  • -model.log_prob(targets).mean() is the cross-entropy over those orders again, 1.4402.

The entropy formula −∑ipilog⁡pi-\sum_i p_i \log p_i breaks when some pi=0p_i = 0. torch.log(0) is -inf, and 0 * -inf is nan. torch.special.entr(x) computes −xlog⁡x-x \log x and returns 0 when x=0x = 0. Categorical(probs=certain).entropy() gives 1.2×10−71.2 \times 10^{-7}, not nan: it keeps probabilities a hair away from 0 and 1 before taking logs.

Common misconceptions

"float32 is accurate to 7 decimal places." It keeps about 7 significant digits. Near 10810^8, the gap between floats is 8, so it can't even store every whole number.

"nan means a bug in my maths." Often the maths is fine and a number overflowed. Look for exp of a large number, or a log of 0, and switch to log_softmax, logsumexp or the losses that take scores.

"Pass probabilities to F.cross_entropy." It takes scores. With probabilities it runs, applies softmax twice and gives a number that's too low.

"F.kl_div(a, b) is DKL(a ∥ b)D_{\mathrm{KL}}(a \,\Vert\, b)." It's DKL(b ∥ a)D_{\mathrm{KL}}(b \,\Vert\, a), and a must be log-probabilities.

"The wrong dim= raises an error." torch.softmax(scores, dim=0) on a (batch, classes) tensor runs fine. It normalises down each column, across examples, which means nothing. Always pass dim= and check it's the axis holding the classes.

Recap

  • PyTorch uses float32 by default: about 7 significant digits, gaps that grow with the number, and limits near 3.4×10383.4 \times 10^{38} and 1.4×10−451.4 \times 10^{-45}.
  • exp overflows past about 88.7. Products of many probabilities underflow to 0. Compare floats with a tolerance, never ==.
  • Work in log space: torch.log_softmax and torch.logsumexp subtract the biggest score first, as in 1.15.
  • F.cross_entropy takes scores with classes on dim 1, and targets as positions or probabilities.
  • F.kl_div takes model log-probabilities first, computes KL(target ‖ input), and needs reduction="batchmean" and a batch axis.
  • PyTorch names in this lesson: float32, float64, torch.finfo, torch.nextafter, .double, .float, torch.isclose, torch.allclose, torch.exp, torch.cumprod, .nonzero, .prod and .repeat. Then torch.softmax and torch.log_softmax, torch.logsumexp, .max(dim, keepdim), .squeeze, .unsqueeze, .expand, .transpose, F.cross_entropy, F.kl_div, torch.distributions.kl_divergence, Categorical (.logits, .entropy, .log_prob) and torch.special.entr.