Lesson 6 · Gradients, randomness and numbers
Numbers and stability
The problem
In the Maths toolkit, softmax of the topping scores was . Adding 100 to every score changed nothing, because only the gaps matter. The chance of 200 orders was about .
Ask PyTorch the same questions the textbook way, and two of the answers break:
- softmax of 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.
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-38torch.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.epsis the gap between 1 and the next number the type can store.maxis the largest number before infinity, andtiny, , is the smallest positive number stored with full precision. Belowtiny, float32 keeps fewer and fewer digits, down to .
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 . 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.
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.
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 tolerancetorch.nextafter(x, y) gives the next float after x in the direction of y. So gap_above(3.0) is . A nudge of 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 towards 0. In float32, can't usefully go below about .
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 . Anything bigger becomes inf (infinity). This is called overflow. For the exponential, the limit is :
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 , 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 fix is the maths from 1.15: subtract the biggest score, so the biggest exponential is (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 . 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:
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.cumprodgives the running product after 1, 2, …, 200 orders..nonzero()gives the positions of entries that aren't 0 orFalse.[0]takes the first, and+ 1turns position 73 into order 74..prod()multiplies every entry together.
Step through the orders below and watch the product.
Order 0: none yet
Product of probabilities (float32): 1.00e+0
Sum of log-probabilities: 0.00
At order 62 the product drops below tiny, and from there it keeps fewer and fewer digits. At order 73 the true product is , which rounds to , the smallest float32 above 0. One more order and it's 0. float64 gets the right , but about 520 orders would underflow it too. The sum of log-probabilities, , 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:
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 scorestorch.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 , rounds to 0, and torch.log of 0 is -inf. torch.log_softmax computes instead. It never forms the tiny number, so it gives the right .
torch.logsumexp(z, dim=-1) computes safely. For 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:
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
Digressionlogsumexp by handSubtract the biggest score, then add it back after the log, as in 1.15. · 2 min
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 - logsumexpThe 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 .
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.
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
int64per example, liketargets. The result is the average of over the batch: 1.4402. - Or it can be probabilities, with the same shape as the scores.
.unsqueeze(0)givesscoresandpa batch axis of size 1, shape(1, 4). Then it computes 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.
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:
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 ordersPredict 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 is the extra surprise from believing when outcomes follow . For the topping model it's 0.1603.
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 orderF.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 , so the model comes first in the call but second in the maths.
- Log-probabilities in:
inputmust be the model's log-probabilities, fromtorch.log_softmax.targetis 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.
torch.distributions.kl_divergence(a, b) takes two distribution objects and gives , 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
# 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: . 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:
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 nanCategorical(logits=scores)normalises the scores. Its.logitsholds the normalised log-probabilities, the log-softmax of the scores: . They are not the raw scores 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 breaks when some . torch.log(0) is -inf, and 0 * -inf is nan. torch.special.entr(x) computes and returns 0 when . Categorical(probs=certain).entropy() gives , 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 , 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 ." It's , 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
float32by default: about 7 significant digits, gaps that grow with the number, and limits near and . expoverflows past about 88.7. Products of many probabilities underflow to 0. Compare floats with a tolerance, never==.- Work in log space:
torch.log_softmaxandtorch.logsumexpsubtract the biggest score first, as in 1.15. F.cross_entropytakes scores with classes on dim 1, and targets as positions or probabilities.F.kl_divtakes model log-probabilities first, computes KL(target ‖ input), and needsreduction="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,.prodand.repeat. Thentorch.softmaxandtorch.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) andtorch.special.entr.