{"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":"log-sum-exp-and-stable-softmax","title":"The log-sum-exp trick, and why exp(1000) is not a number","url":"https://addaly.com/learn/maths-you-need/log-sum-exp-and-stable-softmax","position":47,"of":76,"minutes":9,"answer":"Because float32 overflows at exp(88.7), softmax is computed by subtracting the maximum logit first, and log-probabilities are computed as z minus log-sum-exp rather than as the log of a softmax.","keyIdea":"Because float32 overflows at exp(88.7), softmax is computed by subtracting the maximum logit first, and log-probabilities are computed as z minus log-sum-exp rather than as the log of a softmax, which is why a loss function takes raw logits and why passing it probabilities trains toward a ceiling."},"body":{"format":"markdown","text":"## The overflow that produces NaN\n\nA float32 number cannot exceed about `3.4 × 10^38`. The exponential passes that at `x = 88.7`, so `exp(89)` in single precision is not a large number: it is `inf`. Logits of 89 are not exotic; an untrained network with a bad initialisation or a training run whose learning rate is too high produces them routinely.\n\nApply the naive softmax formula to `z = (1000, 999)`. Both exponentials are `inf`. The sum is `inf`. Each ratio is `inf / inf`, which the floating-point standard defines as `NaN`. The answer should have been `(0.731, 0.269)`, since the logits differ by exactly 1 and `e / (e + 1) = 0.731`. The arithmetic was easy; the intermediate values were not representable.\n\n## The fix is the shift invariance\n\nThe previous lesson showed that subtracting any constant from every logit leaves the softmax unchanged. Subtract the maximum:\n\n```\nz − max(z) = (0, −1)\ne^0 = 1,  e^(−1) = 0.368,  sum = 1.368\np = (0.731, 0.269)\n```\n\nAfter the shift the largest exponent is exactly 0, so the largest exponential is exactly 1, and nothing can overflow. The smaller logits become negative, and very negative ones underflow to zero, which is harmless: a class with probability `10^-50` contributes nothing to the sum, and the answer is unchanged to every digit float32 can hold.\n\n> Figure: Softmax of the logits 1000 and 999, computed two ways. Straight from the formula: e to the 1000 becomes inf; e to the 999 becomes inf; their sum is inf; inf divided by inf is NaN; one NaN spreads to every weight it touches. Subtract the largest logit first: the logits become 0 and minus 1; e to the 0 is 1, e to the minus 1 is 0.368; their sum is 1.368; the answer is 0.731 and 0.269; exact to every digit float32 can hold. Float32 overflows at exp of 88.7, so a logit of 89 is already infinite. Subtracting the largest logit changes nothing about the answer, because softmax cannot see a shift shared by every logit, and it is the difference between a number and NaN.\n\nThis is not an optimisation. It is the difference between an answer and `NaN`, and every deep-learning library does it silently inside `softmax`.\n\n## Log-sum-exp\n\nThe same idea gives a stable way to compute `log Σ e^(z_i)`, which appears in every log-probability, every normalising constant and every loss:\n\n```\nLSE(z) = m + log Σ_i e^(z_i − m),   where m = max(z)\n```\n\nFor `z = (1000, 999)`: `m = 1000`, the shifted sum is `1 + 0.368 = 1.368`, its log is `0.313`, and `LSE = 1000.313`. No overflow, and the result is exact to float32 precision. The unstabilised version would have returned `inf`.\n\nLog-softmax follows immediately:\n\n```\nlog p_i = z_i − LSE(z)\n```\n\nCompute log-probabilities this way, never as `log(softmax(z))`. In the second form, a class whose exponential underflowed to zero produces `log(0) = −inf`, and a single `−inf` in a loss makes the gradient `NaN` for the whole batch. The first form gives `1000 − 1000.313 = −0.313` for the top class and a large finite negative number for the others, which is what you wanted.\n\n## The bug this explains\n\n`torch.nn.CrossEntropyLoss` takes **raw logits**. Internally it computes log-softmax with the trick above and picks out the correct class, in one fused, stable operation. A common mistake is to apply `softmax` first and pass the probabilities in:\n\n```python\nprobs = torch.softmax(logits, dim=-1)\nloss = F.cross_entropy(probs, targets)    # wrong, and it runs\n```\n\nNothing errors. But the loss function now treats the probabilities, all between 0 and 1, as logits, and applies a second softmax to them. Logits that differ by at most 1 give probabilities that are nearly uniform: three classes with input `(0.9, 0.05, 0.05)` come out as `(0.53, 0.23, 0.23)`. The model trains, slowly, toward a ceiling it cannot pass, and the loss never goes far below `ln(number of classes)`. If a classifier learns but its loss stalls near that value, look for a softmax that should not be there.\n\n## Adding probabilities in log space\n\nSequence models, beam search and hidden Markov models all need `log(p_1 + p_2)` when they hold only `log p_1` and `log p_2`, and the probabilities themselves are too small to form. The answer is log-sum-exp of the two logs: `LSE(log p_1, log p_2)`. For `log p_1 = −700` and `log p_2 = −701`, the direct route underflows both to zero and returns `log 0`; the trick returns `−700 + log(1 + e^(−1)) = −699.69`. This is the single identity that makes probabilistic computation over long sequences possible at all.\n\n## What the trick does not fix\n\nSubtracting the maximum prevents overflow. It does not add precision. Float32 carries about seven significant digits, so a term whose shifted exponential is below `10^-7` relative to the largest is lost from the sum entirely. That happens once a logit trails the maximum by more than about 16. The effect on the top class is nil, but the gradient with respect to a logit that far behind is computed as exactly zero rather than a tiny positive number. Usually harmless; occasionally the reason a rare class never moves. Module 8 explains where the seven digits come from.\n\n## In code\n\n```python\nimport numpy as np\nfrom scipy.special import logsumexp   # does the shift for you\nz = np.array([1000.0, 999.0])\nlog_p = z - logsumexp(z)              # (-0.313, -1.313)\np = np.exp(log_p)                     # (0.731, 0.269)\n```\n\nWrite the naive version once, feed it `(1000, 999)`, and see the `NaN` with your own eyes. After that you will never wonder why the library code has that extra line."},"check":{"question":"A learner writes `probs = softmax(logits)` and then `loss = F.cross_entropy(probs, y)`. Training runs without error but the loss will not go far below ln(number of classes). Why?","options":[{"text":"cross_entropy expects log-probabilities, so it should have been given log(probs) instead.","correct":false,"tempting":"The function expects raw logits, not log-probabilities; it applies log-softmax itself, and the fix is to remove the softmax rather than add a log."},{"text":"softmax should be replaced by a sigmoid, which is what cross-entropy is built for.","correct":false,"tempting":"Sigmoid is for independent binary outputs; the problem here is a duplicated normalisation, not the choice of activation."},{"text":"The learning rate is too low for the probabilities to move.","correct":false,"tempting":"Diagnoses a plateau as an optimisation setting; the ceiling comes from feeding numbers in [0,1] into a second softmax, which flattens every prediction."},{"text":"The loss softmaxed the probabilities a second time, flattening every output.","correct":true}]},"prev":{"slug":"softmax-and-its-gradient","title":"Softmax, its gradient, and the shift it cannot see","url":"https://addaly.com/learn/maths-you-need/softmax-and-its-gradient"},"next":{"slug":"power-laws-and-log-log-plots","title":"Power laws, and the straight line on a log-log plot","url":"https://addaly.com/learn/maths-you-need/power-laws-and-log-log-plots"},"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) 'The log-sum-exp trick, and why exp(1000) is not a number', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/log-sum-exp-and-stable-softmax (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":"The log-sum-exp trick, and why exp(1000) is not a number","courseTitle":"The Maths You Actually Need","module":{"index":5,"slug":"logs-information-and-loss","title":"Logarithms, information and the shape of a loss"},"answer":null,"keyIdea":"Because float32 overflows at exp(88.7), softmax is computed by subtracting the maximum logit first, and log-probabilities are computed as z minus log-sum-exp rather than as the log of a softmax, which is why a loss function takes raw logits and why passing it probabilities trains toward a ceiling.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure","figure":{"caption":"Float32 overflows at exp of 88.7, so a logit of 89 is already infinite. Subtracting the largest logit changes nothing about the answer, because softmax cannot see a shift shared by every logit, and it is the difference between a number and NaN.","left":{"title":"Straight from the formula","items":["e to the 1000 becomes inf","e to the 999 becomes inf","their sum is inf","inf divided by inf is NaN","one NaN spreads to every weight it touches"]},"right":{"title":"Subtract the largest logit first","items":["the logits become 0 and minus 1","e to the 0 is 1, e to the minus 1 is 0.368","their sum is 1.368","the answer is 0.731 and 0.269","exact to every digit float32 can hold"]},"title":"Softmax of the logits 1000 and 999, computed two ways","type":"compare"},"alt":"Figure: Softmax of the logits 1000 and 999, computed two ways. Straight from the formula: e to the 1000 becomes inf; e to the 999 becomes inf; their sum is inf; inf divided by inf is NaN; one NaN spreads to every weight it touches. Subtract the largest logit first: the logits become 0 and minus 1; e to the 0 is 1, e to the minus 1 is 0.368; their sum is 1.368; the answer is 0.731 and 0.269; exact to every digit float32 can hold. Float32 overflows at exp of 88.7, so a logit of 89 is already infinite. Subtracting the largest logit changes nothing about the answer, because softmax cannot see a shift shared by every logit, and it is the difference between a number and NaN."}},"blocks":[{"t":"h2","id":"the-overflow-that-produces-nan","runs":[{"text":"The overflow that produces NaN"}]},{"t":"p","runs":[{"text":"A float32 number cannot exceed about "},{"text":"3.4 × 10^38","code":true},{"text":". The exponential passes that at "},{"text":"x = 88.7","code":true},{"text":", so "},{"text":"exp(89)","code":true},{"text":" in single precision is not a large number: it is "},{"text":"inf","code":true},{"text":". Logits of 89 are not exotic; an untrained network with a bad initialisation or a training run whose learning rate is too high produces them routinely."}]},{"t":"p","runs":[{"text":"Apply the naive softmax formula to "},{"text":"z = (1000, 999)","code":true},{"text":". Both exponentials are "},{"text":"inf","code":true},{"text":". The sum is "},{"text":"inf","code":true},{"text":". Each ratio is "},{"text":"inf / inf","code":true},{"text":", which the floating-point standard defines as "},{"text":"NaN","code":true},{"text":". The answer should have been "},{"text":"(0.731, 0.269)","code":true},{"text":", since the logits differ by exactly 1 and "},{"text":"e / (e + 1) = 0.731","code":true},{"text":". The arithmetic was easy; the intermediate values were not representable."}]},{"t":"h2","id":"the-fix-is-the-shift-invariance","runs":[{"text":"The fix is the shift invariance"}]},{"t":"p","runs":[{"text":"The previous lesson showed that subtracting any constant from every logit leaves the softmax unchanged. Subtract the maximum:"}]},{"t":"code","lang":"","label":"Text","text":"z − max(z) = (0, −1)\ne^0 = 1,  e^(−1) = 0.368,  sum = 1.368\np = (0.731, 0.269)"},{"t":"p","runs":[{"text":"After the shift the largest exponent is exactly 0, so the largest exponential is exactly 1, and nothing can overflow. The smaller logits become negative, and very negative ones underflow to zero, which is harmless: a class with probability "},{"text":"10^-50","code":true},{"text":" contributes nothing to the sum, and the answer is unchanged to every digit float32 can hold."}]},{"t":"p","runs":[{"text":"This is not an optimisation. It is the difference between an answer and "},{"text":"NaN","code":true},{"text":", and every deep-learning library does it silently inside "},{"text":"softmax","code":true},{"text":"."}]},{"t":"h2","id":"log-sum-exp","runs":[{"text":"Log-sum-exp"}]},{"t":"p","runs":[{"text":"The same idea gives a stable way to compute "},{"text":"log Σ e^(z_i)","code":true},{"text":", which appears in every log-probability, every normalising constant and every loss:"}]},{"t":"code","lang":"","label":"Text","text":"LSE(z) = m + log Σ_i e^(z_i − m),   where m = max(z)"},{"t":"p","runs":[{"text":"For "},{"text":"z = (1000, 999)","code":true},{"text":": "},{"text":"m = 1000","code":true},{"text":", the shifted sum is "},{"text":"1 + 0.368 = 1.368","code":true},{"text":", its log is "},{"text":"0.313","code":true},{"text":", and "},{"text":"LSE = 1000.313","code":true},{"text":". No overflow, and the result is exact to float32 precision. The unstabilised version would have returned "},{"text":"inf","code":true},{"text":"."}]},{"t":"p","runs":[{"text":"Log-softmax follows immediately:"}]},{"t":"code","lang":"","label":"Text","text":"log p_i = z_i − LSE(z)"},{"t":"p","runs":[{"text":"Compute log-probabilities this way, never as "},{"text":"log(softmax(z))","code":true},{"text":". In the second form, a class whose exponential underflowed to zero produces "},{"text":"log(0) = −inf","code":true},{"text":", and a single "},{"text":"−inf","code":true},{"text":" in a loss makes the gradient "},{"text":"NaN","code":true},{"text":" for the whole batch. The first form gives "},{"text":"1000 − 1000.313 = −0.313","code":true},{"text":" for the top class and a large finite negative number for the others, which is what you wanted."}]},{"t":"h2","id":"the-bug-this-explains","runs":[{"text":"The bug this explains"}]},{"t":"p","runs":[{"text":"torch.nn.CrossEntropyLoss","code":true},{"text":" takes "},{"text":"raw logits","b":true},{"text":". Internally it computes log-softmax with the trick above and picks out the correct class, in one fused, stable operation. A common mistake is to apply "},{"text":"softmax","code":true},{"text":" first and pass the probabilities in:"}]},{"t":"code","lang":"python","label":"Python","text":"probs = torch.softmax(logits, dim=-1)\nloss = F.cross_entropy(probs, targets)    # wrong, and it runs"},{"t":"p","runs":[{"text":"Nothing errors. But the loss function now treats the probabilities, all between 0 and 1, as logits, and applies a second softmax to them. Logits that differ by at most 1 give probabilities that are nearly uniform: three classes with input "},{"text":"(0.9, 0.05, 0.05)","code":true},{"text":" come out as "},{"text":"(0.53, 0.23, 0.23)","code":true},{"text":". The model trains, slowly, toward a ceiling it cannot pass, and the loss never goes far below "},{"text":"ln(number of classes)","code":true},{"text":". If a classifier learns but its loss stalls near that value, look for a softmax that should not be there."}]},{"t":"h2","id":"adding-probabilities-in-log-space","runs":[{"text":"Adding probabilities in log space"}]},{"t":"p","runs":[{"text":"Sequence models, beam search and hidden Markov models all need "},{"text":"log(p_1 + p_2)","code":true},{"text":" when they hold only "},{"text":"log p_1","code":true},{"text":" and "},{"text":"log p_2","code":true},{"text":", and the probabilities themselves are too small to form. The answer is log-sum-exp of the two logs: "},{"text":"LSE(log p_1, log p_2)","code":true},{"text":". For "},{"text":"log p_1 = −700","code":true},{"text":" and "},{"text":"log p_2 = −701","code":true},{"text":", the direct route underflows both to zero and returns "},{"text":"log 0","code":true},{"text":"; the trick returns "},{"text":"−700 + log(1 + e^(−1)) = −699.69","code":true},{"text":". This is the single identity that makes probabilistic computation over long sequences possible at all."}]},{"t":"h2","id":"what-the-trick-does-not-fix","runs":[{"text":"What the trick does not fix"}]},{"t":"p","runs":[{"text":"Subtracting the maximum prevents overflow. It does not add precision. Float32 carries about seven significant digits, so a term whose shifted exponential is below "},{"text":"10^-7","code":true},{"text":" relative to the largest is lost from the sum entirely. That happens once a logit trails the maximum by more than about 16. The effect on the top class is nil, but the gradient with respect to a logit that far behind is computed as exactly zero rather than a tiny positive number. Usually harmless; occasionally the reason a rare class never moves. Module 8 explains where the seven digits come from."}]},{"t":"h2","id":"in-code","runs":[{"text":"In code"}]},{"t":"code","lang":"python","label":"Python","text":"import numpy as np\nfrom scipy.special import logsumexp   # does the shift for you\nz = np.array([1000.0, 999.0])\nlog_p = z - logsumexp(z)              # (-0.313, -1.313)\np = np.exp(log_p)                     # (0.731, 0.269)"},{"t":"p","runs":[{"text":"Write the naive version once, feed it "},{"text":"(1000, 999)","code":true},{"text":", and see the "},{"text":"NaN","code":true},{"text":" with your own eyes. After that you will never wonder why the library code has that extra line."}]}],"check":{"question":[{"text":"A learner writes "},{"text":"probs = softmax(logits)","code":true},{"text":" and then "},{"text":"loss = F.cross_entropy(probs, y)","code":true},{"text":". Training runs without error but the loss will not go far below ln(number of classes). Why?"}],"options":[{"text":[{"text":"cross_entropy expects log-probabilities, so it should have been given log(probs) instead."}],"correct":false,"tempting":[{"text":"The function expects raw logits, not log-probabilities; it applies log-softmax itself, and the fix is to remove the softmax rather than add a log."}]},{"text":[{"text":"softmax should be replaced by a sigmoid, which is what cross-entropy is built for."}],"correct":false,"tempting":[{"text":"Sigmoid is for independent binary outputs; the problem here is a duplicated normalisation, not the choice of activation."}]},{"text":[{"text":"The learning rate is too low for the probabilities to move."}],"correct":false,"tempting":[{"text":"Diagnoses a plateau as an optimisation setting; the ceiling comes from feeding numbers in [0,1] into a second softmax, which flattens every prediction."}]},{"text":[{"text":"The loss softmaxed the probabilities a second time, flattening every output."}],"correct":true,"tempting":null}],"order":[1,3,2,0],"why":null},"prev":{"slug":"softmax-and-its-gradient","title":"Softmax, its gradient, and the shift it cannot see","minutes":9},"next":{"slug":"power-laws-and-log-log-plots","title":"Power laws, and the straight line on a log-log plot","minutes":9}}}