Primer llms math

Softmax, and everything trying to replace it

Somewhere inside every attention layer and every output head sits the same small function: take a list of scores, exponentiate them, divide by their sum. Softmax turns arbitrary numbers into positive weights that add to exactly 1, and modern AI runs on those weights. It is also, depending on who you ask, numerically fragile, unable to ever say zero, and the reason attention heads waste their mass on tokens they do not care about. This primer starts from the model in your own notes, grades it, then goes past it: the sparse normalizers, the sigmoid and kernel challengers, the algorithm that kept softmax and changed everything else, and the 2025 frontier designs that mostly stopped trying to replace it and started building around it.

The one sentence to keep Softmax turns any list of scores into positive weights that sum to 1, and almost every fight in this field is about one of those three properties: the exponent, the positivity, or the sum.

Researched October 2026, from the primary sources in Sources. Numbers attributed to papers are flagged as paper-reported; every number computed for this primer is worked in the open, on the same three scores.

Flat editorial illustration: three glowing orbs of descending size rest on a brass balance scale, which pours their contents into three jars filled to descending heights, the fills together making one full measure, while a cat watches.
Three scores in, three shares of exactly one whole out. Everything in this primer is a fight over how those shares get computed.

Your model, graded

Your notes are right. Three rows have fine print.

Your starting point: softmax takes scores like 3, 2, 1 and returns 0.665, 0.245, 0.090, converting arbitrary scores into positive weights that sum to 1. That example runs through this entire page, so every alternative gets judged on your numbers, not new ones.

$$\mathrm{softmax}(z)_i = \frac{\exp(z_i)}{\sum_{j=1}^{n} \exp(z_j)}$$

What the letters mean: $z$ is the list of raw scores, also called logits. $z_i$ is the score of option $i$. $n$ is how many options there are. $\exp(z_i)$ means $e$ raised to the power $z_i$. The bottom adds up the exponentiated scores of every option, which is what forces the outputs to sum to 1. The output $\mathrm{softmax}(z)_i$ is the weight given to option $i$.

$$\mathrm{softmax}([3, 2, 1]) = \left[ \frac{20.085537}{30.192875}, \frac{7.389056}{30.192875}, \frac{2.718282}{30.192875} \right] = [0.665241, \; 0.244728, \; 0.090031]$$

What the numbers are: $e$ to the 3, $e$ to the 2, and $e$ to the 1, each divided by their sum, 30.192875. Rounded to three places these are exactly your 0.665, 0.245, and 0.090. Your headline row checks out to the digit.

Softmax exponentiates scores and normalizes

Confirmed, including your numbers. Two things your table does not show: the positivity is strict, meaning softmax never outputs an exact 0 no matter how bad a score is, and only differences between scores matter. Add the same constant to every score and the output does not change, a fact called shift invariance that the stability trick below lives on.

Confirmed
Softmax main advantage: "stable, widely used"

Widely used, yes. Stable is earned, not free. Raw exponentiation overflows float32, the standard number format, for any score above about 89: $e$ to the 89 is about 4.49 times 10 to the 38, past the float32 ceiling of about 3.40 times 10 to the 38. Implementations subtract the largest score first, which by shift invariance changes nothing mathematically and caps the biggest exponent at $e$ to the 0, which is 1. Softmax also has a second stability problem running the other way, saturation, covered in the cracks section.

Nuance
Sparsemax projects scores onto a probability distribution, can produce exact zeros

Confirmed. It is literally the closest point on the probability simplex to the score vector, in the Euclidean geometry sense. The nuance is how aggressive it is: on your own gentle example it does not trim a little, it outputs exactly 1, 0, 0. Worked by hand below.

Confirmed
Entmax generalizes softmax and sparsemax, adjustable sparsity

Confirmed, with the missing symbol restored: the knob is one number, alpha. Alpha equal to 1 is exactly softmax, alpha equal to 2 is exactly sparsemax, and 1.5-entmax is the setting that actually got used inside attention. Alpha can even be learned separately for each attention head.

Confirmed
Sigmoid attention applies sigmoid to individual scores, avoids the coupled normalization

Mechanism confirmed. The recipe needs nuance: the version that works at scale, from Apple's 2024 paper, adds a bias of minus log n to every score and also needs QK-normalization and LayerScale, or training destabilizes with loss and gradient spikes. And the freedom cuts both ways: plain sigmoid on your scores gives weights summing to 2.564, not 1. There is no budget anymore, so there is nothing stopping the output from growing with sequence length except that bias.

Nuance
ReLU attention uses max(0, score), simple and potentially efficient

Needs nuance. Bare max(0, score) leaves the weights unnormalized, so outputs grow with the number of tokens. The published working recipe, from Google DeepMind in 2023, divides by the sequence length L: the weight is ReLU of the score, divided by L. Also separate in your notes: the squared ReLU made famous by the Primer architecture search is a feed-forward activation, not an attention mechanism at all. Same words, different layer, different job.

Nuance
Linear attention changes how attention is computed using feature maps, avoiding quadratic cost

Confirmed, with the tradeoff named: a feature map cannot reproduce the exponential's sharp winner-take-most focus exactly, and the autoregressive form squeezes all of history into a fixed-size state, so recalling one exact token from far back is where it strains. The cosFormer authors note kernel approximations can suffer crucial performance drops on some tasks next to plain softmax.

Confirmed
Your distinction: the first three are normalization functions; sigmoid, ReLU, and linear attention change the mechanism

Confirmed, and it is the spine of this primer. Two refinements. Sigmoid and ReLU sit between your categories: they swap the function, which quietly changes the semantics, since attention stops being a weighted average and becomes a gated sum. And there is a mirror category your notes do not have yet: methods that change the algorithm while keeping the function bit-for-bit, like FlashAttention, and methods that change neither, bolting a gate after softmax or a chooser before it. That third category is where the 2025 frontier work lives.

Confirmed
$$\mathrm{softmax}(z)_i = \frac{\exp(z_i - m)}{\sum_{j=1}^{n} \exp(z_j - m)}, \qquad m = \max_j z_j$$

What the letters mean: $m$ is the largest score in the list, and $\max$ means take that largest value. Everything else is as in the first formula. This is the safe softmax every serious implementation actually computes: identical output, no overflow, at the cost of one extra pass to find $m$. Section 2 of the mechanisms below is about deleting even that pass.

How it works

One function, six ways to fight it

The mechanisms, in the order of your table and then past it: softmax itself, the exact-algorithm school, the sparse normalizers, the pointwise challengers, the kernel family, and the add-ons that leave the function alone. Your scores, 3, 2, 1, get run through all of them.

Fig 1. The temperature lab: your scores, one knob Worked example

Temperature divides every score before the exponentiation. Cold sharpens toward a single winner; hot flattens toward uniform. Drag the slider, or focus it and use the arrow keys. At temperature 1 the readout is your example exactly.

temperature 1.00
score 30.665
score 20.245
score 10.090

The same knob shows up in three jobs: inside attention the 1 over square root of d scaling is a fixed temperature, a single fitted temperature repairs overconfident classifiers without changing any ranking (Guo et al. 2017), and the temperature slider in a chat app reshapes the output distribution at sampling time. Same formula, three different decisions.

Softmax was not invented for neural networks. It is the Boltzmann distribution from statistical mechanics: the probability of finding a system in a given state falls off exponentially with that state's energy, with temperature in the denominator from birth.

$$p_i \propto \exp\left(-\frac{\varepsilon_i}{k_B T}\right)$$

What the letters mean: $p_i$ is the probability of state $i$. $\varepsilon_i$ is the energy of state $i$. $k_B$ is Boltzmann's constant, a fixed conversion factor between energy and temperature. $T$ is temperature. The $\propto$ symbol means "is proportional to": divide by the sum over all states and you get exact probabilities. Read negative energy as score and this is softmax, temperature included.

Choice theory found the same function independently: if each option's utility is perturbed by independent Gumbel noise, the probability of picking option $i$ is exactly softmax of the utilities, the multinomial logit model. And optimization needs it for a third reason: softmax is smooth and differentiable everywhere, the gradient of the log-sum-exp function, so it can stand in for the hard argmax during training. Where it appears: attention weights, the output distribution over the vocabulary, mixture-of-experts routing, RL policies, and inside the cross-entropy loss.

$$\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left(\frac{QK^{\top}}{\sqrt{d}}\right) V$$

What the letters mean: $Q$ is the matrix of query vectors, one per position, each asking what it is looking for. $K$ is the matrix of key vectors, one per position, each advertising what it contains. $V$ is the matrix of value vectors, the content actually copied forward. $QK^{\top}$ is every pairwise dot-product score between queries and keys, the small T meaning transpose, $K$ flipped so the multiplication lines up. $d$ is the dimension of each key vector, and dividing by its square root keeps dot products from growing with dimension, a fixed temperature. Softmax runs row by row, and multiplying by $V$ forms each output as a weighted average of values.

Safe softmax needs two passes over the scores, one for the max, one for the sum. In 2018, Milakov and Gimelshein at NVIDIA showed both can be tracked in a single streaming pass: keep a running max, and when a bigger score arrives, rescale the running sum by the ratio of the old and new exponentials. Fig 3 below runs this recurrence on real numbers.

$$m_j = \max(m_{j-1},\, z_j), \qquad \ell_j = \ell_{j-1} \, e^{\,m_{j-1} - m_j} + e^{\,z_j - m_j}$$

What the letters mean: $z_j$ is the $j$-th score to arrive. $m_j$ is the running maximum of everything seen so far. $\ell_j$ is the running sum of exponentials, measured relative to the current running max. The factor $e$ to the (old max minus new max) is the correction: when the max rises, every previously accumulated exponential shrinks by exactly this factor, because they were all measured against the smaller max. At the end, softmax of $z_i$ is $e$ to the ($z_i$ minus final max) divided by the final $\ell$. Paper-reported speedups: up to 1.3 times for softmax alone, up to 5 times for a fused softmax plus top-k.

FlashAttention (Dao et al. 2022) builds the whole attention computation on this recurrence. Standard attention is slow not from arithmetic but from writing the full score matrix to GPU memory and reading it back, so FlashAttention tiles queries, keys, and values into blocks that fit in on-chip SRAM, rescales a running output accumulator block by block, and recomputes the attention matrix in the backward pass instead of storing it. Extra memory grows linearly with sequence length, not quadratically.

$$O \leftarrow O \cdot e^{\,m_{\mathrm{old}} - m_{\mathrm{new}}} + e^{\,S_{\mathrm{block}} - m_{\mathrm{new}}} V_{\mathrm{block}}, \qquad \text{then finally } O \leftarrow O / \ell$$

What the letters mean: $O$ is the running, still unnormalized output for a block of query rows. $S_{\mathrm{block}}$ is the score block for the current tile of keys, and $V_{\mathrm{block}}$ is the matching tile of values. $m_{\mathrm{old}}$ and $m_{\mathrm{new}}$ are the running max before and after this block, and $\ell$ is the running sum from the formula above. The arrow means "replace with". FlashAttention-2 (2023) then cut the remaining fat: keep the accumulator unnormalized the whole way and divide by $\ell$ exactly once at the end, roughly 2 times faster than the first version, paper-reported.

Your category one, done properly. Sparsemax (Martins and Astudillo, ICML 2016) replaces the exponential with a geometry problem: find the point on the probability simplex closest to the score vector. A projection onto a flat-faced object lands on its faces, and points on a face have zero coordinates. That is why sparsemax can say zero and softmax never can.

$$\mathrm{sparsemax}(z) = \arg\min_{p \in \Delta} \| p - z \|^2, \qquad \Delta = \left\{ p : p_i \ge 0, \; \textstyle\sum_i p_i = 1 \right\}$$

What the letters mean: $p$ is a candidate probability vector. $\Delta$, the Greek letter Delta, is the probability simplex: the set of all vectors with no negative entries that sum to 1. $\| p - z \|^2$ is the squared Euclidean distance between the candidate and the raw scores. $\arg\min$ means "the $p$ that makes this smallest". Nothing is exponentiated anywhere.

$$\mathrm{sparsemax}(z)_i = \max(z_i - \tau, \; 0), \qquad \tau = \frac{\left(\sum_{j \in S} z_j\right) - 1}{|S|}$$

What the letters mean: $\tau$, the Greek letter tau, is a single threshold computed from the scores themselves. $S$ is the support, the set of options that survive, and $|S|$ is how many survive. The max with 0 is the ReLU shape: score minus threshold, floored at zero. Tau is the surviving scores' sum, minus 1, divided by the survivor count, and the support is found by sorting the scores and testing prefixes, worked by hand under Fig 2.

Entmax (Peters, Niculae, and Martins, ACL 2019) unifies the two by swapping Shannon entropy for Tsallis entropy, a one-parameter generalization from statistical physics. Softmax and sparsemax become the two endpoints of one dial.

$$\alpha\text{-}\mathrm{entmax}(z) = \left[ (\alpha - 1)\, z - \tau \, \mathbf{1} \right]_{+}^{\,1/(\alpha-1)}$$

What the letters mean: $\alpha$, the Greek letter alpha, is the dial: $\alpha$ equal to 1 limits to softmax, $\alpha$ equal to 2 is sparsemax, and 1.5 is the attention-ready middle. $\mathbf{1}$ is the vector of all ones, so tau is subtracted from every entry. The $[\,\cdot\,]_{+}$ brackets mean keep the positive part and set negatives to zero, and the exponent $1/(\alpha-1)$ is applied entry by entry. Tau is again chosen so the outputs sum to exactly 1. At $\alpha$ equal to 2 this collapses to the sparsemax formula above.

Inside attention, Correia, Niculae, and Martins (2019) learned alpha separately per head: heads in different layers chose different sparsity, the heads became more diverse and more interpretable, at no cost in accuracy on their translation benchmarks, paper-reported. The honest adoption note: as of October 2026, no primary source shows sparsemax or entmax attention inside a frontier production LLM. They won the interpretability argument and lost the market, a point the camps section returns to.

Ramapuram and co-authors at Apple asked whether the row-wise softmax is necessary at all, and replaced it with the sigmoid applied to each score independently. Three things change: the weights stop summing to 1, the output stops being a weighted average, and a bias term appears that turns out to carry the whole design.

$$\mathrm{SigmoidAttn}(X) = \sigma\left( \frac{Q K^{\top}}{\sqrt{d_{qk}}} + b \right) V, \qquad b = -\log n$$

What the letters mean: $Q$, $K$, $V$ are the query, key, and value matrices as before. $d_{qk}$ is the query and key dimension. $\sigma$ is the sigmoid function, $\sigma(u)$ equal to 1 divided by (1 plus $e$ to the minus $u$), applied to each score separately. $b$ is a bias added to every score before the sigmoid, and $n$ is the sequence length, so the recommended bias is minus the natural log of the sequence length.

Why the bias matters: with $b$ equal to 0, every token contributes on average $\sigma(0)$, which is 0.5, so outputs grow linearly with sequence length and early attempts at sigmoid attention sank on exactly this. With $b$ equal to minus log $n$, each weight behaves like the token's exponential divided by (its exponential plus $n$), and outputs stay finite as $n$ grows. The paper's working recipe adds QK-normalization and LayerScale on top; without QK-norm their sigmoid models were unstable, with loss and gradient spikes. With the full recipe, sigmoid attention matched softmax across language, vision, and speech in their experiments, and their FlashSigmoid kernel ran up to 17 percent faster than FlashAttention-2 on H100, both paper-reported. This is the strongest published evidence that softmax is not necessary inside attention, and equally strong evidence that "just apply sigmoid" is not the recipe.

Read softmax attention as a similarity function, exp of the query-key dot product, and a classical trick opens up: if a similarity can be written as a dot product in some transformed space, matrix associativity lets you summarize all the keys once and query the summary, instead of comparing everything with everything.

$$o_i = \frac{\varphi(q_i)^{\top} \left( \sum_{j} \varphi(k_j) \, v_j^{\top} \right)}{\varphi(q_i)^{\top} \left( \sum_{j} \varphi(k_j) \right)}$$

What the letters mean: $o_i$ is the output for position $i$. $q_i$ is position $i$'s query, $k_j$ and $v_j$ are position $j$'s key and value. $\varphi$, the Greek letter phi, is the feature map, a function applied to each query and key separately. $\varphi(k_j) v_j^{\top}$ is an outer product, a matrix that adds position $j$'s content into a running summary. The sums over $j$ no longer depend on $i$, so they are computed once, and the denominator renormalizes so the weights still sum to 1. What changes versus softmax: the exponential similarity is replaced by a dot product of transformed vectors, and no cheap feature map reproduces the exponential's sharpness exactly.

Linear attention (Katharopoulos et al., ICML 2020) picks the simplest possible map, elu plus 1, the plus 1 keeping every entry positive so similarities cannot go negative. In the autoregressive setting the running sums become a recurrence: attention turns into an RNN whose memory is a fixed-size matrix.

$$\varphi(x) = \mathrm{elu}(x) + 1, \qquad S_t = S_{t-1} + \varphi(k_t)\, v_t^{\top}, \qquad o_t = \frac{\varphi(q_t)^{\top} S_t}{\varphi(q_t)^{\top} z_t}$$

What the letters mean: $x$ is a single query or key vector, and elu is the exponential linear unit activation, applied entry by entry. $t$ counts positions in order. $S_t$ is the state matrix after reading $t$ tokens, the entire memory of the past, fixed in size no matter how long the sequence runs. $z_t$ is the matching normalizer vector, $z_{t-1}$ plus $\varphi(k_t)$. Paper-reported: up to 4,000 times faster autoregressive generation on very long sequences, with the fixed state as both superpower and weakness.

The Performer (Choromanska et al., ICLR 2021) goes the other way: keep the true softmax kernel as the target and approximate it with orthogonal random features, unbiased with uniform convergence guarantees, paper-reported. cosFormer (Qin et al., ICLR 2022) argues softmax works because of two properties, non-negative weights and a non-linear concentration, and rebuilds both in linear time with a ReLU map times a cosine distance factor that favors nearby positions. And ReLU attention proper, your row 5 with its fix, divides by the sequence length instead of by any sum:

$$A_{ij} = \frac{1}{L} \, \mathrm{ReLU}\left( \frac{q_i^{\top} k_j}{\sqrt{d}} \right), \qquad o_i = \sum_{j} A_{ij} \, v_j$$

What the letters mean: $A_{ij}$ is the attention weight from position $i$ to position $j$. $L$ is the sequence length, the total number of positions. ReLU of a number is that number if positive, else 0. $d$ is the key dimension, as before. Wortsman and co-authors at Google DeepMind (2023) found the 1 over $L$ division, missing from earlier attempts, is the ingredient that makes the swap work, approaching or matching softmax's scaling behavior on vision transformers, paper-reported.

The most recent designs barely touch the normalizer. QK-normalization (Henry et al. 2020) bounds what reaches it: normalize each query and key to unit length and replace the fixed scale with a learned one, so logits live in a bounded range and softmax cannot saturate arbitrarily. Paper-reported gain: plus 0.928 BLEU on average across five low-resource translation pairs, and QK-norm is now standard plumbing, including inside the sigmoid recipe of card 4.

$$\text{logit}_{ij} = g \cdot \frac{q_i^{\top} k_j}{\|q_i\| \, \|k_j\|}$$

What the letters mean: $\|q_i\|$ is the length, the L2 norm, of the query vector, and likewise for the key. Dividing the dot product by both lengths makes the fraction a cosine similarity, always between minus 1 and 1. $g$ is a single learnable scale that stretches that bounded range back out. Softmax itself is untouched; its inputs can no longer run away.

The Differential Transformer (Ye et al., ICLR 2025) runs softmax twice and subtracts, noise-canceling style: the second map estimates the common-mode dumping described in the cracks section, and the attention weights can go negative on purpose. Gated attention (Qiu et al., Qwen Team, 2025) keeps plain softmax and multiplies its output, per head, by a sigmoid gate that can shut a head's output off entirely, the escape hatch of the cracks section delivered without touching the normalizer. It won a NeurIPS 2025 Best Paper Award and shipped in Qwen3-Next-80B-A3B.

$$Y' = Y \odot \sigma\left( X W_{\theta} \right)$$

What the letters mean: $Y$ is the ordinary softmax attention output and $Y'$ is the gated output actually passed onward. $X$ is the layer's input, $W_{\theta}$ are learned gate parameters, theta being the conventional symbol for parameters, and $\sigma$ is the sigmoid, so every gate value sits between 0 and 1. $\odot$ means elementwise multiplication: each entry of $Y$ scaled by its matching gate value.

DeepSeek Sparse Attention (DeepSeek-V3.2, September 2025) puts a chooser in front instead: a cheap FP8 indexer scores every past token with a ReLU score, only the top 2,048 KV entries are retrieved, and the real attention over just those is ordinary softmax. ReLU gets away with being unnormalized here because the indexer only ranks; its scores are never used as weights.

$$I_{t,s} = \sum_{j} w^{I}_{t,j} \cdot \mathrm{ReLU}\left( q^{I}_{t,j} \cdot k^{I}_{s} \right)$$

What the letters mean: $I_{t,s}$ is the index score saying how relevant past token $s$ looks to the token being generated at step $t$. The sum runs over the indexer's few heads $j$. $q^{I}_{t,j}$ is the indexer's query for head $j$, $k^{I}_{s}$ is the indexer's key stored for token $s$, one per token, and $w^{I}_{t,j}$ is a learned per-head weight. Main attention cost falls from order $L$ squared to order $L$ times $k$ for context length $L$ and the 2,048 kept entries; the indexer itself stays quadratic but is deliberately tiny.

And the deepest departure still keeps softmax in the building. Kimi Linear (Moonshot AI, 2025) replaces three of every four attention layers with KDA, a gated delta-rule recurrence with no softmax anywhere in the layer, and keeps MLA softmax layers for the remaining quarter. Paper-reported: KV cache down up to 75 percent, and up to 6 times decoding throughput at 1M context. The same softmax also does quieter jobs elsewhere: mixture-of-experts routers softmax over experts after top-k truncation and added noise, and Gumbel-softmax adds Gumbel noise to log-probabilities so discrete choices can be sampled differentiably, a sampling trick, not an attention alternative.

Fig 2. The alternatives lab: one set of scores, five functions Worked example

Your scores, 3, 2, 1, through every function from your table. Watch the third bar: only the sparse family can make it exactly zero, and watch the sum, because two of these functions refuse to give you one.

score 30.665
score 20.245
score 10.090
Sum of the weights1.000

Worked example: sparsemax by hand, then the dial Checkable arithmetic

Finding sparsemax's threshold tau for your scores, exactly as the algorithm does it. Sort the scores descending (already sorted: 3, 2, 1), take running sums (3, 5, 6), and test each prefix $j$ with the rule $1 + j \cdot z_{(j)} > \text{sum of the top } j$:

j = 1: 1 + 1 x 3 = 4 > 3 keep

j = 2: 1 + 2 x 2 = 5 > 5? no, 5 equals 5, test fails

j = 3: 1 + 3 x 1 = 4 > 6? no

support size k = 1, so tau = (3 - 1) / 1 = 2

output = [max(3 - 2, 0), max(2 - 2, 0), max(1 - 2, 0)] = [1, 0, 0]

The gap of exactly 1 between consecutive scores is precisely the margin sparsemax needs to zero everything below the top, so your gentle example comes out maximally sparse. The 1.5-entmax middle setting solves its own threshold, tau equal to (5 minus the square root of 7) over 4, about 0.589, and lands between the two. The whole family on your scores, as one dial:

Softmax, alpha 1

3 / 2 / 10.665 / 0.245 / 0.090

1.5-entmax

3 / 2 / 10.831 / 0.169 / 0

Sparsemax, alpha 2

3 / 2 / 11 / 0 / 0

Same scores, three sparsity levels, one knob. In Fig 2 the bars show each winner's share; here you can see the threshold arithmetic that produces the zeros.

Flat editorial illustration: a river of small paper tiles flows downhill in batches toward a fox at a workbench, who catches each batch in a net, updates an abacus tally, and keeps a stack of bowls balanced so nothing overflows.
The online normalizer, as a river: every tile gets counted exactly once, the tally is corrected as bigger tiles arrive, and nothing ever piles up waiting for a second pass.
Fig 3. Online softmax: the denominator, computed in one pass Click per step

Six scores arrive in three blocks of two, the way a FlashAttention tile sees one row of the attention matrix. The algorithm keeps only two running numbers. One tap per step, or use the arrow keys.

Fig 5. What the kernel family is running from: quadratic state Derived

One attention head, one layer, FP32 numbers, head dimension 64. Softmax attention, computed the naive way, keeps a score for every pair of positions: the count grows with the square of the sequence length $N$. Linear attention's running state $S$ is one 64 by 64 matrix plus a normalizer, the same size at every length. Bar lengths are log scale so all six fit on one screen; the numbers are exact.

Materialized score matrix, softmax attention

N = 1,0244 MB

1,048,576 scores, one per pair

N = 16,3841.07 GB

268 million scores

N = 1,048,5764.40 TB

1.1 trillion scores, per head, per layer

Running state, linear attention

N = 1,024about 16 KB

the state matrix S and its normalizer

N = 16,384about 16 KB

unchanged: the state does not grow

N = 1,048,576about 16 KB

unchanged, which is the whole pitch and the whole risk

Two honest caveats. First, nobody serves softmax attention by materializing this matrix anymore: FlashAttention (Fig 3) computes exact softmax without storing it, so the quadratic number is the memory traffic FlashAttention refuses to pay, not a bill anyone currently pays in full. Second, the flat 16 KB is not free: it is a fixed-size memory being asked to hold an arbitrarily long past, which is why exact recall of one distant token is where linear attention strains, and why Kimi Linear keeps real softmax layers in the mix.

The cracks

Three things wrong with softmax itself

Separate from speed: the function has three documented defects, and each one has spawned a fix that keeps the rest of it intact.

Crack 1: it cannot say "nothing" (forced choice, sinks, and the off-by-one fix)

The weights must sum to 1, so a head with nothing useful to attend to still has to spend its full budget somewhere. It parks the mass on semantically empty tokens, which is the attention sink phenomenon: Xiao et al. (2023) showed models dump strong attention on the initial tokens even when they are not important, and that keeping just a few of those sink tokens lets StreamingLLM run stably to 4 million tokens, up to 22.2 times faster than the sliding-window baseline, paper-reported. Evan Miller's 2023 essay "Attention Is Off By One" makes the mechanistic version of the argument and proposes the smallest fix in this whole primer: add 1 to the denominator.

$$\mathrm{softmax}_1(z)_i = \frac{\exp(z_i)}{1 + \sum_{j=1}^{n} \exp(z_j)}$$

What the letters mean: the only new object is the literal 1 added to the denominator; $z$, $i$, $j$, $n$, and $\exp$ are as in the first formula. The outputs now sum to less than 1, and the missing mass reads as weight placed on "attend to nothing". On your scores the nothing bucket absorbs 1 divided by 31.192875, about 0.032: the off-by-one weights are 0.644, 0.237, 0.087, totaling 0.968.

Fig 4. The sum-to-1 trap: a head that wants to attend nowhere Illustrative, hand-checkable

One query, five keys. The first token is a beginning-of-sequence sink with score 1.5; the four content tokens all score minus 2, because this head genuinely finds nothing here. Scores this small are chosen so you can verify every weight with the formulas on this page.

Mass on real tokens1.000

This is also why the gated attention of card 6 works: the gate gives the head an abstention channel downstream, and its authors report the attention sink largely disappears.

Crack 2: once it is confident, it stops learning (saturation)

Softmax's derivative couples every output to every input, and when the output is nearly one-hot, every term in that derivative collapses toward 0. The winner's gradient is proportional to $p_i (1 - p_i)$, which vanishes as $p_i$ approaches 1. A saturated softmax produces almost no gradient, so the example it is most sure about teaches it almost nothing. This is the stated motivation behind QK-normalization's bounded logits in card 6.

$$\frac{\partial \, \mathrm{softmax}(z)_i}{\partial z_j} = p_i \, (\delta_{ij} - p_j)$$

What the letters mean: the left side reads "how much output $i$ moves when score $j$ moves". $p_i$ is softmax's output for option $i$. $\delta_{ij}$, the Kronecker delta, is 1 when $i$ equals $j$ and 0 otherwise. Read it as: every gradient term carries a factor of some $p$ times (something minus another $p$), so when one $p$ is near 1 and the rest are near 0, all the products are near 0.

Crack 3: the output softmax has a rank ceiling (the bottleneck)

This one is about the other softmax, the output layer over the vocabulary. Yang, Dai, Salakhutdinov, and Cohen (ICLR 2018) wrote language modeling as factorizing a giant matrix of true log-probabilities, one row per context and one column per word. A single softmax output layer can only produce log-probability matrices whose rank is at most the hidden dimension, while real language's matrix is high-rank. Some distributions are literally unrepresentable, no matter how good the rest of the network is.

$$\mathrm{rank}(A) \le d$$

What the letters mean: $A$ is the matrix of true log-probabilities for every (context, next word) pair. Rank is the number of independent patterns a matrix can express. $d$ is the hidden dimension, hundreds to a few thousand, while contexts and words run to the hundreds of thousands and beyond. The inequality says the model's output matrix can carry at most $d$ independent patterns.

Their fix, Mixture of Softmaxes, averages several softmax distributions with context-dependent weights. A blend of low-rank pieces can be high-rank, and it set state-of-the-art perplexities at the time: 47.69 on Penn Treebank and 40.68 on WikiText-2, paper-reported.

$$P_\theta(x \mid c) = \sum_{k=1}^{K} \pi_{c,k} \; \frac{\exp\left(h_{c,k}^{\top} w_x\right)}{\sum_{x'} \exp\left(h_{c,k}^{\top} w_{x'}\right)}$$

What the letters mean: $P_\theta(x \mid c)$ is the model's probability that word $x$ follows context $c$, theta standing for the model's parameters. $K$ is the number of mixture components. $\pi_{c,k}$ is the weight of component $k$ for this context, the pi weights summing to 1 over $k$. $h_{c,k}$ is the context vector produced for component $k$, $w_x$ is the output embedding of word $x$, and $x'$ ranges over the whole vocabulary in the normalizing sum. What changes versus plain softmax: one distribution becomes a weighted blend of $K$ distributions.

Timeline

From statistical mechanics to the 2025 bolt-ons

One tap per stop, or use the arrow keys.

Key voices

Who thinks what

The people and teams behind each position, in their own claims, with the disagreements left in.

Fix the algorithm

Tri Dao

FlashAttention, NeurIPS 2022; FlashAttention-2, 2023

The function is fine; the memory traffic is the problem. FlashAttention's papers position exact, IO-aware attention against the approximate-methods literature, arguing approximations trade away model quality and often fail to deliver wall-clock speedups anyway. Keep softmax exact and bit-identical; change how it is computed.

Source: FlashAttention, arXiv:2205.14135

Density is a defect

André Martins and collaborators

Sparsemax, ICML 2016; entmax, ACL 2019; Adaptively Sparse Transformers, 2019

Softmax spreads mass over everything, which the entmax work calls wasteful and hard to interpret. Exact zeros give selective, compact attention a reader can actually inspect, per-head learned sparsity diversifies the heads, and on their benchmarks it costs no accuracy. The market disagreed about adoption, not about the math.

Source: Sparse Sequence-to-Sequence Models, arXiv:1905.05702

Softmax is not necessary

Jason Ramapuram and the Apple sigmoid team

Theory, Analysis, and Best Practices for Sigmoid Self-Attention, ICLR 2025

Elementwise sigmoid, with the minus log n bias and the right normalization companions, matches softmax across language, vision, and speech, with better-behaved gradient bounds and a kernel up to 17 percent faster on H100. The strongest published case against necessity, and it comes with a recipe, not a slogan.

Source: Sigmoid Self-Attention, arXiv:2409.04431

It is off by one

Evan Miller

Attention Is Off By One, essay, July 24, 2023

Sum-to-1 is a bug in attention specifically: a head that wants to attend to nothing is forced to annotate something anyway, and the dumped mass lands on whitespace and punctuation, producing the outlier activations that plague quantization. One extra 1 in the denominator is the fix.

Source: evanmiller.org

The output layer is the ceiling

Zhitao Yang, Russ Salakhutdinov, and co-authors

Breaking the Softmax Bottleneck, ICLR 2018

The attention softmax gets the attention, but the output softmax is an expressivity bottleneck: rank at most the hidden dimension, against a high-rank truth. Their answer is mixture, not replacement: blend several softmaxes and the ceiling lifts.

Source: arXiv:1711.03953

Gate it, do not touch it

Zihan Qiu and the Qwen Team

Gated Attention for Large Language Models, 2025; NeurIPS 2025 Best Paper

After comparing over 30 gating variants on models trained on 3.5 trillion tokens, the winning recipe leaves standard softmax attention alone and multiplies its output by a head-specific sigmoid gate. Sinks largely disappear, training stabilizes, and the design shipped in Qwen3-Next-80B-A3B.

Source: arXiv:2505.06708

Exp is one similarity among many

Angelos Katharopoulos and the kernel camp

Transformers are RNNs, ICML 2020; Performer, ICLR 2021; cosFormer, ICLR 2022

Replace or approximate the exponential kernel with a feature map and attention becomes linear in sequence length, with quality close enough to matter on long sequences. The camp's own members supply the caution: cosFormer's authors note naive kernel approximations can suffer crucial performance drops, which is why the good ones engineer softmax's two key properties back in.

Source: arXiv:2006.16236

Route around it

The DeepSeek and Moonshot teams

DeepSeek Sparse Attention, September 2025; Kimi Linear, October 2025

Revealed by what they shipped. DeepSeek kept softmax and put a cheap ReLU chooser in front of it, retrieving 2,048 entries per query. Moonshot replaced three of four layers with a softmax-free recurrence and kept MLA softmax layers for the rest. Neither lab replaced softmax wholesale; both changed what surrounds it.

Sources: DeepSeek-V3.2, arXiv:2512.02556 and Kimi Linear, arXiv:2510.26692

Where leaders think this goes

One consensus, three live splits

Positions as of October 2026, attributed to the people and papers above. Nobody here is quoted predicting softmax's death date; the splits are about which of its properties deserve to survive.

Where they agree

Numerics are first-order. Every camp's design is secretly a stability story: safe softmax's max subtraction, QK-norm's bounded logits (Henry et al.), Apple's minus log n bias (Ramapuram et al.), gated attention's stability gains (Qiu et al.). Nobody ships the mathematically naive version of anything.

Quadratic cost is the pressure point. Dao optimizes its memory traffic, the kernel camp removes it, DeepSeek shrinks the attended set to 2,048, Kimi Linear removes the growing cache from most layers. Nobody defends order N squared at million-token contexts.

Attention sinks are real. StreamingLLM found them empirically (Xiao et al. 2023), Miller explained them mechanistically (2023), and Qwen measured a fix on 15B models (2025). Three directions, one phenomenon.

Split 1: is exact sparsity good?

Martins, Niculae, Peters, Correia: yes

Exact zeros are selectivity and interpretability for free. A head's support can be read at a glance, dropped options get exactly no gradient and no compute downstream, and per-head learned alpha costs no accuracy on their benchmarks.

Katharopoulos, Choromanska, Qin: unnecessary

Keep everything dense and make the state cheap instead, by approximation or by feature maps. The Apple team lands nearby from a third direction: independent gates in (0, 1), no zeros required, no sum constraint either.

Split 2: is sum-to-1 a feature or a bug?

The shippers, by revealed preference: a feature

A convex combination is a proper weighted average with probability semantics, and every frontier model's full-attention layers still run softmax as of October 2026. No manifesto defends density; production behavior does. That is an inference from what shipped, stated as one.

Miller; Ye et al.; Qiu et al.: a bug to route around

Three independent designs, 2023 to 2025, each exist to let a head not spend its mass: Miller's extra 1 in the denominator, the Differential Transformer's subtracted second map, and Qwen's output gate. When three teams build the same escape hatch, the constraint is the story.

Split 3: fix the function or fix the algorithm?

Dao: the algorithm

Exactness is non-negotiable and the function is fine. FlashAttention and FlashAttention-2 changed only how softmax attention is computed and took the field's default with them.

Ramapuram et al.; the Kimi Team: the mechanism

Accept new failure modes, bias tuning and hybridization, in exchange for removing the normalizer's coupling or the softmax layer itself. The 2025 production record currently favors a fourth answer neither camp led with: fix around the function, gate after it or choose before it.

Takeaways

The short version

Your model of softmax was right, and it is the rare case where the interesting story is entirely in the fine print: the function is three properties (an exponential, strict positivity, a sum of 1), and a decade of research is the story of researchers keeping two and attacking the third. The replacements that changed the function won arguments; the designs that changed the algorithm or built around the function won production.

  • Your numbers are exact. Softmax of 3, 2, 1 is 0.665, 0.245, 0.090, and "stable" is a property implementations earn by subtracting the max, since raw exponentiation overflows float32 above a score of about 89.
  • The sparse family is a dial, not a zoo. Alpha runs from softmax at 1 through 1.5-entmax at 0.831, 0.169, 0 to sparsemax at a flat 1, 0, 0 on your own scores. Exact zeros are real, interpretable, and, so far, unshipped at the frontier.
  • Pointwise challengers work, with adult supervision. Sigmoid attention matches softmax in Apple's tests, but only with its minus log n bias plus QK-norm and LayerScale; ReLU attention only with its 1 over L scaling. The naive version of each fails in a specific, predictable way.
  • The biggest win kept the function. Online softmax plus FlashAttention made exact softmax attention fast and linear-memory without changing a single output, and the 2025 frontier mostly bolted on gates, choosers, and hybrid layers rather than replacing the normalizer.
  • Sum-to-1 is the contested property. It forces the attention sink, it caps the output layer's rank, and three separate designs exist just to let a head abstain. Whether it is a feature or a bug is the live argument, and the abstention camp is gaining production ground.

Keep exploring

Adjacent primers

Sources

Primary sources

Every factual claim above traces to one of these: the paper itself, the author's own essay, or the official announcement.

Paper
Attention Is All You Need
Vaswani et al. · NeurIPS 2017 · arXiv:1706.03762
Essay
Attention Is Off By One
Evan Miller · evanmiller.org · July 24, 2023
Paper
Breaking the Softmax Bottleneck: A High-Rank RNN Language Model
Yang, Dai, Salakhutdinov, Cohen · ICLR 2018 · arXiv:1711.03953
Paper
Online Normalizer Calculation for Softmax
Milakov and Gimelshein (NVIDIA) · 2018 · arXiv:1805.02867
Paper
FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness
Dao, Fu, Ermon, Rudra, Ré · NeurIPS 2022 · arXiv:2205.14135
Paper
From Softmax to Sparsemax: A Sparse Model of Attention and Multi-Label Classification
Martins and Astudillo · ICML 2016 · arXiv:1602.02068
Paper
Sparse Sequence-to-Sequence Models
Peters, Niculae, Martins · ACL 2019 · arXiv:1905.05702
Paper
Adaptively Sparse Transformers
Correia, Niculae, Martins · EMNLP-IJCNLP 2019 · arXiv:1909.00015
Paper
Theory, Analysis, and Best Practices for Sigmoid Self-Attention
Ramapuram et al. (Apple) · ICLR 2025 · arXiv:2409.04431
Paper
Replacing Softmax with ReLU in Vision Transformers
Wortsman, Lee, Gilmer, Kornblith (Google DeepMind) · 2023 · arXiv:2309.08586
Paper
A Study on ReLU and Softmax in Transformer
Shen et al. · 2023 · arXiv:2302.06461
Paper
Primer: Searching for Efficient Transformers for Language Modeling
So et al. · 2021 · arXiv:2109.08668 · the squared ReLU that lives in the feed-forward layer, not attention
Paper
Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention
Katharopoulos, Vyas, Pappas, Fleuret · ICML 2020 · arXiv:2006.16236
Paper
Rethinking Attention with Performers
Choromanska et al. · ICLR 2021 · arXiv:2009.14794
Paper
cosFormer: Rethinking Softmax in Attention
Qin et al. · ICLR 2022 · arXiv:2202.08791
Paper
Memory-efficient Transformers via Top-k Attention
Gupta et al. · SustaiNLP 2021 · arXiv:2106.06899
Paper
Categorical Reparameterization with Gumbel-Softmax
Jang, Gu, Poole · ICLR 2017 · arXiv:1611.01144
Paper
The Concrete Distribution: A Continuous Relaxation of Discrete Random Variables
Maddison, Mnih, Teh · ICLR 2017 · arXiv:1611.00712
Paper
On Calibration of Modern Neural Networks
Guo, Pleiss, Sun, Weinberger · ICML 2017 · arXiv:1706.04599
Paper
Mixture-of-Experts with Expert Choice Routing
Zhou et al. · NeurIPS 2022 · arXiv:2202.09368
Paper
Differential Transformer
Ye et al. · ICLR 2025 · arXiv:2410.05258
Paper
Query-Key Normalization for Transformers
Henry, Dachapally, Pawar, Chen · Findings of EMNLP 2020 · arXiv:2010.04245
Paper
Efficient Streaming Language Models with Attention Sinks (StreamingLLM)
Xiao, Tian, Chen, Han, Lewis · ICLR 2024 · arXiv:2309.17453
Award
Announcing the NeurIPS 2025 Best Paper Awards
NeurIPS blog · November 26, 2025 · gated attention among the four Best Paper Awards from 5,290 accepted papers
Report
DeepSeek-V3.2 report (DeepSeek Sparse Attention)
DeepSeek-AI · 2025 · arXiv:2512.02556 · DeepSeek Sparse Attention; the September 2025 experimental report lives in the DeepSeek-V3.2-Exp repo
Paper
Kimi Linear: An Expressive, Efficient Attention Architecture
Kimi Team, Moonshot AI · 2025 · arXiv:2510.26692