Shangzhen Zhublogpublications

How Much Softmax Do You Need in LLMs?

Papers: Approximating Softmax in Pretrained LLMs: Model Sensitivity and Kernel Acceleration (inference) · Pretraining Transformers with Quantized Softmax in Attention (training)

Authors: Shangzhen Zhu, Muyan Hu, Tomasz Kozlowski · University of Illinois Urbana-Champaign · contact: szhu48@illinois.edu

Headlines

  1. In a pretrained LLM, softmax can drop a large share of positions and round scores coarsely, but the weights have to keep a roughly exponential shape.
  2. When the resolution budget is fixed, spend it near the row maximum.
  3. When you train with an approximate softmax, the feedback rule through the approximation matters as much as the approximation itself.

In a transformer, each attention layer lets a token gather information from earlier positions, mixing them with a set of weights that sum to one. Softmax is the step that turns the raw attention scores into those weights. This post asks how much of that step can be simplified. We measure the cost with perplexity, which tracks how well the model predicts the next token (lower is better).

Figure 1. The smooth curve (softmax) and the staircase (approximation): the weight \(2^x\) and its approximation with a few levels per octave; one octave is a factor of 2 in weight. “Linear interpolation (no rounding)” is \(S(x)\), the straight line between neighboring powers of two: it rounds nothing but is still an approximation. Pick a level to see its measured whole-model perplexity change for Qwen2.5-1.5B relative to softmax (dots on a log scale, with 95% CIs); the same values reappear in Figure 7.

Watch on YouTube

The video above is the short version. This post adds the experimental settings, the full numbers, the kernel’s bit-level construction and the training-side backward rules. Collapsed Details blocks hold the material most readers can skip. Result plots are drawn from the recorded outputs; illustrations and schematics are labeled as such.

Why care about the exponential in softmax?

Attention is

\[\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^{\top}}{\sqrt d}+M\right)V ,\]

where the mask \(M\) is 0 for allowed positions and \(-\infty\) for future ones. For one query, the row of scores \(s_j\) becomes weights

\[p_j=\frac{e^{\,s_j-\max_k s_k}}{\sum_k e^{\,s_k-\max_k s_k}} .\]

That is one exponential for every valid score. For Qwen2.5-1.5B (28 layers, 12 query heads), one causal forward pass over 2,048 tokens has

\[28\times 12\times\frac{2048\times 2049}{2}=704{,}987{,}136\approx 705\text{ million}\]

per-score exponentials. This number is counted from the valid positions of the causal mask. It is not a measured instruction count.

Figure 2. Left: a single example, the scores of the opening 8 tokens of the WikiText-103 test set in Qwen2.5-1.5B (layer 8, head 11); cells marked −∞ are masked. Right: B200 throughput per SM per clock, and the per-score exponential count for one 2K-token forward pass of the whole model (arithmetic, not a measured instruction count).

The hardware makes this count matter. On an NVIDIA B200, each streaming multiprocessor (SM) can do 8,192 FP16/BF16 matrix-multiply operations per clock, but its special-function unit (MUFU) produces only 16 exponentials per clock. That is a 512× gap. FlashAttention-4 (FA4) already works around it: it computes 10–25% of each row’s exp2 calls with a cubic polynomial on the regular floating-point pipeline instead of the MUFU.

So the question is whether a trained model needs every one of those exponentials at full precision. We split it into three questions about one frozen model, then build a kernel from the answers, then ask what changes in training:

  1. How many positions does it need?
  2. How precise must the scores be?
  3. Must the weights be exponential?

Unless noted, inference numbers come from Qwen2.5-1.5B with all parameters frozen. We report next-token perplexity on about 200K tokens of the WikiText-103 test set, relative to the same model with softmax. Cross-model checks use ten decoder-only models from 0.5B to 72B.

Details: evaluation protocol
  • Models: Qwen2.5-0.5B/1.5B/3B, Llama-3.2-1B/3B, Llama-3.1-8B, Gemma-2-2B, Mistral-7B-v0.3, plus Qwen2.5-72B and Llama-3.1-70B on a subset of experiments. All parameters are frozen; only the map from a row of scores to its weights is replaced, in every head and layer unless stated otherwise.
  • Data: WikiText-103 test, tokenized per model, cut into 97 aligned blocks of 2,048 tokens (198,559 next-token predictions). BF16 weights, FP32 score-to-probability computation.
  • Endpoint: \(\Delta\mathrm{NLL}\) is the mean next-token negative log-likelihood (nats) under the intervention minus that under softmax, same model, same blocks. Perplexity change is \(e^{\Delta\mathrm{NLL}}-1\), so 0.01 nats is about 1%.
  • Uncertainty: 95% CI from a paired block bootstrap, 5,000 replicates, seed 0. A contrast is resolved when its 95% CI excludes zero. No effect is pooled across models.

Question 1: How many positions does it need?

Start with one row. Figure 3 shows a real row (layer 16 of 28, head 5, query token “ to”), sorted by weight. In this row, 3 of the 2,048 positions carry 54.5% of the weight, and the smallest 1,536 carry 0.8%.

The whole model shows the same picture. Over all layers, heads and rows of the evaluation text, positions with \(p\ge 0.1\) are 0.15% of valid positions and carry 54% of the attention weight. Positions with \(p<10^{-4}\) are 75% of positions and carry 1.2% in total.

So we drop the smallest weights. In every row of every layer we keep only the largest fraction of valid positions, zero the rest and renormalize. Perplexity changes relative to softmax:

Kept per row 50% 25% 10% 1%
Perplexity change +0.13% +0.83% +7.8% +90%
Figure 3. Left and top right: one row (single example: Qwen2.5-1.5B, layer 16, head 5, query “to”). Middle right and the two cards: whole-model results on about 200K WikiText-103 tokens. The slider stops only at the eight measured fractions.

Positions can be cut a lot: keeping half costs almost nothing. But the cut has a limit: at a tenth of the row the damage becomes visible, and below that it grows fast.

Details: the full support sweep and the larger models
  • Full top-\(k\) sweep on Qwen2.5-1.5B (softmax weights renormalized over the kept set): keeping 50%, 25%, 15%, 10%, 6.5%, 2.6%, 1% and 0.65% of each row raises perplexity by 0.131%, 0.828%, 3.092%, 7.821%, 15.185%, 37.861%, 90.478% and 144.670%. The last two targets keep pooled densities of 1.05% and 0.70%.
  • A row-mean threshold (keep the scores above the row’s mean valid score) keeps a fraction of 0.493 and costs +0.310%.
  • The position sweep was run on Qwen2.5-1.5B only. The papers have no ten-model position sweep. The larger models have one related check: the row-mean threshold raises LAMBADA perplexity by 6.727% in Qwen2.5-72B and 11.649% in Llama-3.1-70B. On the same zero-shot suite, the \(K=32, R=4\) grid of the next section changes their task scores by a mean absolute 0.114 percentage points (max 0.256).

Question 2: How precise must the scores be?

This time we keep every position and round the scores instead.

Start with seven scores and a coarse grid (Figure 4). Each score moves to its nearest grid value, so different scores end up sharing a value. Scores on the same grid value also share one exponential: a row needs one exponential per grid value it uses, not one per score. For a row of 2,048 scores, a 16-step grid has at most 17 distinct exponential values.

Figure 4. Illustration with seven made-up scores. Switch between the scores before rounding (one exponential each; a red arrow points from each score to its nearest grid value) and after rounding to that value: scores on the same grid value share one exponential.

Terms. For each row, we cut the score range from the row minimum to the row maximum into \(K\) steps, which gives \(K+1\) grid values. Each score is rounded to the nearest grid value, and the weights stay exponential in the rounded score. Step widths shrink geometrically toward the maximum. The ratio

\[R=\frac{\text{width of the step next to the row minimum}}{\text{width of the step next to the row maximum}}\]

sets the allocation: \(R=1\) gives uniform steps, and \(R>1\) makes steps finer near the maximum.

Illustration (not data). The same row range cut into \(K=6\) steps. With \(R=1\) the steps are equal; with \(R=4\) the widths shrink geometrically toward the row maximum, by \(\rho=R^{-1/(K-1)}\) from one step to the next, so the lowest step is 4 times as wide as the top step.

With \(R=4\), perplexity rises by 0.28% at \(K=16\), 0.09% at \(K=32\) and 0.007% at \(K=64\), all relative to softmax. In other words, each score only needs to land on one of a few dozen values. That is a statement about grid values, not storage: the paper reports \(\log_2(K+1)\) only as a descriptive index budget and says explicitly that it is not a storage specification. Across all ten models, the \(K=32, R=4\) grid stays below a 1% perplexity increase in every point estimate. The largest is Gemma-2-2B at 0.85%, whose 95% CI spans 1%.

Where the steps go matters more

Now fix the number of steps at \(K=21\) and change only \(R\), from ¼ to 8:

\(R\) ¼ ½ 1 2 4 8
Perplexity change +1.6% +1.0% +0.49% +0.25% +0.14% +0.10%

Pushing steps toward the bottom of the row makes things worse. Squeezing them toward the row maximum makes things better, and the improvement is monotonic over the tested range.

The surprising part is what happens to the error. From \(R=1\) to \(R=4\):

Measured uniformly over positions, the \(R=4\) grid is the worse approximation. The model says it is the better one. The effect holds across models: the extra loss is lower at \(R=4\) than at \(R=1\) in all ten point estimates, and the 95% CI excludes zero in nine of them (Figure 6 in the Details below). Gemma-2-2B is unresolved.

Figure 5. Top: one attention row (single example) with \(K=21\) steps; the slider sets how the steps are spaced and stops only at the six measured values of \(R\). Bottom: whole-model results for Qwen2.5-1.5B on about 200K WikiText-103 tokens, relative to softmax (left) and relative to \(R=1\) (right).

The reason is Question 1: attention is concentrated near the maximum, so resolution spent there does far more than resolution spread evenly. Put the limited resolution near the row maximum.

Details: allocation numbers, ten models, reconstruction
  • Grid: with \(u_j=s_j-\min_k s_k\in[0,C]\), the boundaries are \(e_a=C\,\frac{1-\rho^a}{1-\rho^K}\) with \(\rho=R^{-1/(K-1)}\), \(a=0,\dots,K\) (uniform at \(R=1\)). The grid is recomputed for every row and never clips support. Weights are exponential with nearest-boundary reconstruction.
  • \(\Delta\mathrm{NLL}\) along the \(K=21\) sweep (\(R=\) ¼, ½, 1, 2, 4, 8): 0.0161, 0.00997, 0.00489, 0.00251, 0.00138, 0.00100.
  • Error summaries (natural-log weight error on the softmax trajectory): unweighted RMS 0.314 at \(R=1\), 0.401 at \(R=4\), 0.483 at \(R=8\); probability-weighted RMS 0.178, 0.126, 0.124. The errors are measured with softmax-trajectory scores, while the extra loss applies the approximation in every layer.
  • Ten-model contrast \(D_R(21)=\Delta\mathrm{NLL}_{R=1}-\Delta\mathrm{NLL}_{R=4}\) (Figure 6). The interaction \(I_R=D_R(16)-D_R(32)\) is resolved positive in all four Qwen2.5 sizes and in Llama-3.1-70B: the allocation benefit is larger with 16 steps than with 32. \(R=4\) is one tested setting, and no optimum was searched.
  • Long context: in the two largest models, \(D_R\) is resolved positive at 2K, 8K and 16K, and \(R=4\) removes 64.9–78.1% of the \(R=1\) degradation.
  • Reconstruction at \(K=21, R=4\): rounding up to the upper boundary costs +0.726%, nearest boundary +0.138%, and linear interpolation of the weights within a step +0.00808%. Interpolation uses each score’s position inside its step, so it does not produce finitely many output values.
Figure 6. Allocation contrast at \(K=21\) for ten models (whole model), shown as perplexity at \(R=1\) relative to \(R=4\), \(e^{D_R}-1\), with 95% CIs. Values from Table D1 of the inference paper.

Question 3: Must the weights be exponential?

Now we change how a score is converted into a weight.

Start with the extreme case. Keep the same top half of each row, but give every kept position the same weight. Perplexity is multiplied by more than 5,000 (×5,268). Because that intervention runs in every layer, it also changes the scores that later layers see, so a cleaner control changes one layer at a time. Both conditions reach that layer with identical scores and keep the same positions; they differ only in equal versus softmax weights. Equal weights make the model worse in every one of its 28 layers, and each layer’s 95% CI excludes zero.

Weights that grow along a straight line are almost as bad. With weight proportional to the grid index, perplexity is multiplied by 4,172 at 32 steps, and by about 4,100 to 5,200 at every grid size tested (4 to 1,024 steps). Exponential weights on the same 32-step grid cost about 1%.

You can cut positions, but you can’t lose the shape.

How precise does the shape need to be?

Rewrite the exponential in base 2:

\[e^{x}=2^{\,x/\ln 2}.\]

This step is exact, and FlashAttention-4 already computes softmax this way, with exp2. Measure each score in octaves below the row maximum,

\[x_j=\frac{s_j-\max_k s_k}{\ln 2}\le 0 ,\]

so that one step down in \(x\) halves the weight. That step is one octave. The approximation is to put a limited number of levels in each octave.

Figure 7. The shape ladder for Qwen2.5-1.5B (whole model, same evaluation text). Left: the wrong shapes, on a perplexity-ratio axis. Each bar is relative to dense softmax; softmax-shaped weights under the same setting cost almost nothing (+0.13% on the top half; +0.99% for all positions on the same 32-step grid), so each bar is essentially the cost of the shape. Right: each row is one of the staircases drawn in Figure 1, with its perplexity change relative to softmax on a log axis and 95% CIs. The level chosen in Figure 1 is highlighted here.

One detail matters here. The in-between levels lie on straight lines between neighboring powers of two. The half-octave level is therefore \(1.5\times 2^{n}\), not \(\sqrt2\times 2^{n}\).

Why integer exponents are attractive. A power of two with an integer exponent does not need to be computed. A floating-point number already stores an exponent field, so you write the integer into it: one addition and one shift. A half-octave level sets one extra bit, the leading mantissa bit, which means “× 1.5”. Schraudolph (1999) used the same idea for a fast, compact approximation of the exponential. Writing a fraction into the mantissa as well gives exactly the linear interpolation \(S(x)\) above.

Figure 8. The bit construction for one input \(x\), computed in your browser (round = round half to even). Top: the exact weight \(2^x\). Middle: one level per octave, \(n=\mathrm{round}(x)\) shifted left by 23 plus the bits of 1.0. Bottom: Rowmax-H15, where \(n=\mathrm{round}(2x)\) counts half-octaves and is shifted left by 22, so its lowest bit lands on the leading mantissa bit (×1.5). At \(x=-1.5\) the exact value is 0.354; one level gives 0.25 and Rowmax-H15 gives 0.375.

The reference point matters too. Take the same octave grid, but place it on a fixed absolute scale: the fixed \(\log_2\) lattice used by post-training quantizers such as FQ-ViT, here at 8 bits. The row maximum then falls between grid values, with a different phase in every row. Perplexity rises by 0.66% instead of 0.30%, so the extra loss is 2.17× larger than with the grid anchored at each row’s maximum.

Figure 9. Top: the same octave grid anchored two ways, shown on the largest weight of the example row (single example). Bottom: whole-model perplexity change for Qwen2.5-1.5B relative to softmax, and the ratio of the two extra losses.

Answer to Question 3. In these frozen-model tests, the weights need a roughly exponential shape, and anchoring the grid at the row maximum reduces the loss. Two levels per octave already come close.

Details: FP32 bit layout, the 22-bit shift, and the √2 alternative

FP32 layout. 1 sign bit, 8 exponent bits (bias 127), 23 mantissa bits. The value is \((1+\text{mantissa}/2^{23})\cdot 2^{\text{exponent}-127}\).

  • Integer exponent (1 level per octave). For an integer \(n\), \(2^n\) has mantissa 0 and exponent field \(n+127\). Shifting \(n\) left by 23 places it in the exponent field, and adding the bit pattern of 1.0 (0x3F800000 = 127 « 23) adds the bias. Example: \(n=-3\) gives exponent field 124 and the value 0.125.
  • Half-octave index (Rowmax-H15). Here \(n=\mathrm{round}(2x)\) counts half-octaves, and the value is \(\left(1+\tfrac12(n \bmod 2)\right)2^{\lfloor n/2\rfloor}\). Shifting \(n\) left by 22 instead of 23 sends its lowest bit to the leading mantissa bit (worth 0.5, so the significand becomes 1.5) and the remaining bits, \(\lfloor n/2\rfloor\), into the exponent field. With two’s complement this also works for negative \(n\).
  • Worked example, \(n=-3\): \(-3 \ll 22\) = 0xFF400000; adding 0x3F800000 gives 0x3EC00000 (mod \(2^{32}\)). That is sign 0, exponent field 125, leading mantissa bit 1, i.e. \(1.5\times 2^{-2}=0.375\), which matches \(\left(1+\tfrac12\right)2^{\lfloor -3/2\rfloor}\).
  • Relation to Schraudolph (1999). With \(S(x)=2^{\lfloor x\rfloor}(1+x-\lfloor x\rfloor)\) (his construction, unshifted, base 2) and \(Q_{1/2}(x)=\mathrm{round}(2x)/2\), the ideal Rowmax-H15 operator is \(H(x)=S(Q_{1/2}(x))\). This is an identity of ideal operators, not bitwise equivalence with his macro. Its octave error lies in \([-0.25,\,0.335]\).
  • Cost of the half-octave input rounding: Rowmax-H15 versus unrounded \(S(x)\) is \(\Delta\mathrm{NLL}=0.00107\) [0.000747, 0.00140], i.e. +0.107% perplexity (offline whole-row path, not the kernel).
  • The √2 alternative. Rounding the log weight to half octaves gives levels \(\{1,\sqrt2\}\times2^n\) (PoT \(m=2\)) and costs +0.093%. Its difference from Rowmax-H15’s \(\{1,1.5\}\times2^n\) is not resolved: paired \(\Delta\mathrm{NLL}\) −0.000122 [−0.000551, +0.000301].
  • Anchor × spacing. At octave spacing, moving only the anchor from absolute to rowmax lowers \(\Delta\mathrm{NLL}\) by 0.00355 [0.00268, 0.00448]. Halving the spacing at the absolute anchor lowers it by 0.00443 [0.00367, 0.00517]. The effects are not additive: at half-octave spacing, the anchor gain is 0.00122 [0.000708, 0.00171].
  • Shape controls. Uniform weights with the row-mean threshold multiply perplexity by 4,155. In the single-layer control, \(D_W(\ell)=\Delta\mathrm{NLL}_{\text{uniform}}-\Delta\mathrm{NLL}_{\text{softmax}}\) ranges from 0.0181 to 0.2000 over layers 1–27, and layer 0 gives 8.1733. The linear map is tested at full support, \(R=1\) and upper-edge reconstruction; its \(\Delta\mathrm{NLL}\) is 8.55, 8.44 and 8.40 at \(K\) = 4, 8 and 12, and between 8.32 and 8.37 from \(K=16\) to 1,024. The paired linear-minus-exponential contrast at \(K=32\) is 8.33 [8.15, 8.51].
  • The 1-level row is the octave power-of-two perturbation (PoT \(m=1\), no tail cutoff; anchor table, Table B1). The 2-, 4- and 8-level rows and \(S(x)\) come from a separate exponential-map ablation with the same blocks and bootstrap.

Putting it together: Rowmax-H15

The grid experiments measure what the model tolerates; turning that into speed needs an implementation. The kernel replaces per-score exponentials only; it does not drop positions as in Question 1.

The answers give four design rules:

  1. Keep the exponential shape (Question 3).
  2. Anchor to the running row maximum that online softmax already keeps (Question 2 and the anchor control). There is no scale to calibrate.
  3. Use two levels per octave, \(\{1, 1.5\}\times 2^n\).
  4. Replace each per-score exponential with an add and a shift. No calibration parameters are needed.

We built this into FlashAttention-4 and call it Rowmax-H15. For the base-2 exponent \(x\) that FA4’s online exponential path receives (measured from the running maximum),

\[n=\mathrm{round}_{\mathrm{RNE}}(2x),\qquad \hat w(x)=\left(1+\tfrac12\,(n\bmod 2)\right)2^{\lfloor n/2\rfloor},\]

so even \(n\) gives \(2^k\) and odd \(n\) gives \(1.5\cdot 2^k\) (RNE is round-to-nearest-even).

What is replaced, and what is not. Only the per-score exponential changes. The running maximum, the rescaling of the accumulators, the log-sum-exp and the pipeline are unchanged, and the row sum and the \(PV\) product use the same approximated weights. FA4 rescales lazily: it skips the rescale while the row maximum grows by less than a threshold (\(\tau=8.0\)). The anchor can therefore lag the final row maximum, which makes \(x\) positive; the formula covers both signs.

For Qwen2.5-1.5B, the 705 million per-score exponentials of a 2K-token forward pass become zero. Each score instead costs three cheap integer and floating-point instructions. That count comes from a static instruction audit of isolated micro-kernels (3 instructions against 8 for FA4’s cubic emulation), not from the B200 kernel itself.

Figure 10. Accuracy, measured inside the kernel on the BF16 path at 2K tokens (about 200K WikiText-103 tokens per model), relative to stock FlashAttention-4. Values from Table 2 of the inference paper.
Figure 11. Speed, measured separately: attention-forward call latency on one B200 (FP8, 8K tokens, batch 1, 16 heads, head dimension 128, pooled median of three rounds). Attention forward only, not the whole model.

Accuracy was measured inside the kernel, on the BF16 path at 2K context, over the same ~200K WikiText-103 tokens, against stock FA4:

Speed was measured on one B200 with FP8 inputs at 8K tokens, using the standard shape of batch 1, 16 heads and head dimension 128 (not Qwen2.5-1.5B’s own shape). The metric is attention-forward call latency, the pooled median over three rounds, and “faster” means stock latency divided by patched latency, minus one:

These speedups are for the attention forward computation, not the whole language model. Note also that accuracy (BF16, 2K) and speed (FP8, 8K) come from different settings. Kernel accuracy was not measured at FP8 or at 8K.

Details: the three instructions, and the other kernel measurements

Pseudocode for one element. FA4 already folds the softmax scale into the exponent path. The patch doubles the two exponent-path constants (scale_log2, max_offset), so the input arrives as \(2x\) at no extra cost. In the code, bits(f) reads the 32 bits of a float32 as an integer and from_bits(i) reads 32 integer bits as a float32: both are bitcasts (bit-for-bit reinterpretations), not numeric conversions.

# y = 2x: base-2 exponent of this score, measured from the running row max, already doubled
y = max(y, -252.0)                  # keep the result a normal float: n >= -252 gives 2^-126 or larger
                                    # (n = -254 gives 0, n = -255 wraps to NaN)
t = y + from_bits(0x4B400000)       # bit pattern of 2^23 + 2^22 = 12582912.0
                                    # 1) FP32 add: rounds to n = round_RNE(2x),
                                    #    which now sits in the low mantissa bits of t
b = bits(t) << 22                   # 2) integer shift: bit 0 of n -> leading mantissa bit (x1.5),
                                    #    the rest -> exponent field (the 0x4B4... bits shift out)
w = from_bits(b + 0x3F800000)       # 3) integer add of the bit pattern of 1.0 supplies the bias
# w == (1 + 0.5*(n % 2)) * 2**(n // 2)

The constant 0x4B400000 is the one FA4 uses for its floor construction, applied here with round-to-nearest-even. The doubling is absorbed by separate exponent-path constants. Doubling the shared constants instead would square the rescale factor and corrupt the log-sum-exp. The patch applies at 10 textual anchors with fail-closed checks.

Other measurements reported in the paper (B200 attention forward, call latency unless noted):

  • FP8 causal: +7.1% at 4K (largest round-to-round spread, sd 2.13 points), +12.4% at 8K, +12.5% at 16K. At 32K the gain falls to +9.9%, with a lower patched-kernel clock.
  • Short sequences: call latency is slower at 2K (−3.7% in a retest), and the 1K result changes sign between sessions. A separate traced run shows a positive kernel-duration gain at every length, so a shorter kernel does not always shorten the call.
  • dtype × mask at causal 8K: +5.4% at BF16, +5.3% at FP16 and +12.4% at FP8, which has twice the tensor-core rate. Without the mask the FP8 gain rises to +25.8%.
  • Pre-registered predictions (sealed before any B200 run): an FP8 causal gain of +10–15% was met. The prediction that BF16 gains would stay below 3% failed: they were +3.8%, +5.4% and +7.1% at 4K–16K. Four predictions about counters (MUFU utilization, pipeline utilization, softmax-stage time, registers) remain unverified, because counter profiling (ncu) was refused on every instance where it was tried. The mechanism is inferred, not measured.
  • Against FA4’s own emulation settings (FP8 causal 8K): +12.3% over FA4’s default and +9.3% over the fastest of eight stock settings tested. That comparison crosses measurement sessions.
  • Energy: GPU board energy per FP8 causal 16K forward fell from 742.5 to 680.3 mJ (−8.4%) at unchanged mean board power. This is one loop per kernel, and no CI was estimated; the saving comes from the shorter runtime.
  • Head dimension 64: +2.0% to +3.7%, but stock FA4 falls back to a default emulation setting there, so the comparison is not like-for-like.
  • FP8 accuracy was only simulated (Qwen2.5-1.5B, +0.072%). A direct FP8 run was unusable because per-tensor quantization of the BF16 activations dominated its error. A BF16 simulation lands 11% below the measured BF16 kernel, with overlapping 95% CIs.
  • Measured kernel \(\Delta\mathrm{NLL}\) [95% CI]: Qwen2.5-1.5B 0.00121 [0.000862, 0.00156]; Qwen2.5-72B 0.00101 [0.000665, 0.00139]; Mistral-7B-v0.3 0.000914 [0.000600, 0.00125]; Llama-3.1-8B 0.00246 [0.00206, 0.00289]; Llama-3.1-70B 0.00491 [0.00402, 0.00582].
  • Scope: attention forward only, not backward, decode or full-model latency. In Qwen2.5-1.5B prefill, the causal attention forward is 21% of decoder FLOPs at 8K and 35% at 16K. Those are workload shares, not a measured prefill speedup. The 4- and 8-level variants have not been tested inside FA4. No claim is made about B300.

Scalar distortion metrics can mislead

A common way to judge an approximation is a single distortion number, such as a pointwise error bound or the divergence between the approximate and the softmax attention distributions. On Qwen2.5-1.5B such a number does track damage: across 56 interventions, log extra loss against log mean row-wise Jensen–Shannon divergence (JSD) has slope 1.05 and \(R^2=0.945\) (in-sample). But it does not determine the damage. Flattening the scores (scaling them by \(\alpha<1\)) and sharpening them (\(\alpha>1\)), tuned to the same mean JSD, cost different amounts, and which one hurts more depends on the model: flattening in seven of ten models, sharpening in two (Figure 12). Question 2 showed the same thing: the grid with more unweighted error had less extra loss. So approximations are judged here by model loss, including the kernel above, whose per-element error is far above one BF16 unit in the last place.

Figure 12. Left: perplexity under matched flattening relative to matched sharpening, per model (whole model, symlog axis); hollow markers have 95% CIs that include zero; values from Table D2 of the inference paper. Right: 56 interventions on Qwen2.5-1.5B, perplexity change relative to softmax against mean row-wise JSD, with the in-sample log–log fit.
Details: the matched comparison
  • Both perturbations multiply the scores by \(\alpha\) and then apply softmax. Each \(\alpha\) is tuned by bisection on the divergence alone, without access to the loss. Two targets are used: \(J_0\), the JSD of the 1-level-per-octave rounding in that model, and \(10J_0\).
  • At \(J_0\), flattening hurts more in seven models; sharpening hurts more in two, Llama-3.2-1B and Qwen2.5-72B (both resolved); Llama-3.1-70B is unresolved. At \(10J_0\), flattening hurts more in eight models, and the other two are unresolved. Neither direction is worse in all models, and the pattern does not follow model size. The Llama-3.2-1B reversal also appears when total variation is matched instead of JSD.
  • The probability shifts look alike even when the losses differ. In all ten models, matched flattening moves probability out of the set carrying 90% of the softmax mass, and matched sharpening moves it in, including Llama-3.2-1B. The change in the attention output \(pV\) is nearly the same for both directions. For Qwen2.5-1.5B the relative RMS change is 0.0733 versus 0.0732.
  • Caveat: matching equalizes the mean JSD over all layers, heads and rows on eight calibration blocks. It does not equalize how that divergence is distributed.
  • \(D_T(J)=\Delta\mathrm{NLL}_{\text{flatten}}(J)-\Delta\mathrm{NLL}_{\text{sharpen}}(J)\), so \(D_T>0\) means flattening raises NLL more. \(J_0=0.00261\) for Qwen2.5-1.5B. The largest matching error over all 48 matched conditions is 0.962%.
  • At \(J_0\): Llama-3.2-1B \(D_T=-0.00313\) [−0.00428, −0.00202], Qwen2.5-72B −0.00119 [−0.00208, −0.000375], Llama-3.1-70B −0.00107 [−0.00220, +0.0000282]. Gemma-2-2B lies on a different scale: +0.246 [+0.218, +0.273].
  • Mass-partition “rescue” (restoring the softmax mass inside and outside the 90% set) changes the signed contrast in every model at \(10J_0\), but it is neither universal nor a causal mediation result: Qwen2.5-1.5B’s rescued contrast is resolved negative, −0.00278 [−0.00510, −0.000565], and Llama-3.2-1B stays negative.

What changes when you train with an approximate softmax?

The training study uses related K-interval grid operators, not the Rowmax-H15 kernel itself.

At inference time, an approximation only perturbs a function that has already been trained. Training is different. It also works out how each parameter should change, and that feedback (gradient) has to pass through the approximation too.

The training paper puts a grid like the one in Question 2 into every attention layer of a GPT-2-style model trained from scratch. Each row gets \(K\) equal steps and \(K+1\) exponential grid values, simulated in fp32.

Same forward, different feedback

Take two copies of the same model with the same grid inside attention. In these runs the grid spans each row from its lowest to its highest score, and weights are linearly interpolated between neighboring grid values (LERP, \(K=32\)). The setup is a 124M model on WikiText-103 for 100M tokens. The forward rule is identical: given the same parameters, both compute exactly the same output.

Figure 13. Schematic (no data). Both models run the same forward pass. Model B detaches the row min and max: only the calibration path is cut, and every score, the two end scores included, keeps its direct feedback.

Initially, the two train almost identically. After about 25–30 million tokens they separate. At 100M tokens, Model B’s validation perplexity is 2.09× Model A’s, while Model A shows no detectable difference from softmax.

Figure 14. Validation perplexity relative to softmax (GPT-2 124M, LERP, \(K=32\), WikiText-103, one seed). Lines are validation losses logged during training on a fixed sample of 100 validation windows, at the token counts where the softmax run was logged too. Model A’s run was resumed from its 80.2M checkpoint, after which its evaluations fell on other token counts; its last four points (81.9–97.3M) come from re-running it from that checkpoint and evaluating at the softmax run’s token counts, which reproduces its original logged losses to within 0.0004 nats. Diamonds are separate full-validation evaluations at 100M tokens; Model B’s last logged point (97.3M, ×2.28) sits above its diamond because the small logged sample fluctuates (×2.04 one log earlier).

What Model B does has a name: detach. For plain softmax it is harmless, because subtracting the maximum does not change the result and its feedback cancels exactly. So people detach the maximum out of habit. With a grid, the ends set the grid itself, so that feedback must stay.

The result holds up in the paper’s checks. It replicates on two more seeds. With hard rounding instead of LERP, detach also fails against its matched full-feedback run at every \(K\) tested. Forcing Model B’s feedback to sum to zero, the identity that shift invariance implies, does not fix it; that run ends worse. Restoring only the row maximum’s calibration path recovers about 98% of the gap.

Three choices

That was one of three choices that decide whether training works:

  1. Feedback through the grid’s ends: keep it; do not detach.
  2. Where the grid’s ends come from: the row minimum and maximum (“MinMax”), or a fixed-width window of 6 nats below the maximum, with zero weight below it (“fixed window”). Under MinMax, each step is (max − min)/K wide. Whenever the lowest score drifts further down, every grid value is pulled apart, including those near the top, where most of the weight is. With a fixed window, the lowest score can keep drifting, but the grid near the top stays where it is.
  3. The feedback rule for rounding: rounding turns smooth changes into steps. Nudge a score a little and the rounded value does not move, so rounding gives no feedback by itself. Training needs a hand-chosen surrogate: the forward pass uses the rounded weights, and the backward pass uses the interpolated ones. The question is where the surrogate sits, before normalization (on the unnormalized weights) or after it (on the probabilities). In these tests it worked much better after normalization.

A longer run

The next results come from a separate setup. It is longer than the A/B experiment: GPT-2 124M on FineWebEdu for 2.5B training tokens, with hard rounding and only \(K=4\) steps per row. All of these runs keep the feedback through the grid’s ends (choice 1). They start from MinMax calibration with the surrogate before normalization, then change the surrogate, the calibration, or both, all at \(K=4\) (Figure 15).

Figure 15. Perplexity increase over softmax after 2.5B training tokens (GPT-2 124M, FineWebEdu, \(K=4\) steps, hard rounding, one seed). Rows: where the grid’s ends come from (choice ②); columns: where the surrogate sits (choice ③). Cell names give the change from MinMax calibration with the pre-normalization surrogate; the outlined cell changes both. For reference, no rounding (LERP) at \(K=4\) costs +0.48%, and the fixed window with the pre-normalization surrogate at \(K=16\) costs +0.39%.

With MinMax calibration and the pre-normalization surrogate, validation perplexity ends at 2.4× softmax’s (+144%), and the model also loses 3.9 to 19.4 accuracy points on downstream tasks (six benchmarks in seven configurations). It does something specific: it stretches its score range to about seven times the softmax model’s, and the step width reaches 53 nats. It sharpens scores that the grid cannot even resolve (Figure 16). Changing either choice removes most of the gap, and changing both leaves perplexity about 2% above softmax.

Figure 16. Score range (row max minus row min, layer mean, on each model’s own scores) at every checkpoint of the 2.5B-token runs with \(K=4\) (whole model, one seed).

Shorter checks (two separate experiments, both shorter than the 2.5B-token run):

What was not measured. These runs simulate the grid in fp32 attention arithmetic. No training kernel was built, and training speed was not measured.

The common thread with inference: keep the limited resolution near the top scores, which matter most. In training, the feedback rule has to be right too.

Details: backward rules and full training numbers

Notation (one causal row): scores \(s_j\), row max \(M\) and min \(m\), step width \(h=(M-m)/K\) (MinMax) or \(\tau/K\) (fixed window, \(\tau=6\) nats), unnormalized weights \(w_j\), \(W=\sum_l w_l\), \(P_j=w_j/W\), \(g_j=\partial L/\partial P_j\). The normalization Jacobian gives \(\gamma_j=\partial L/\partial w_j=(g_j-\sum_i P_ig_i)/W\). Inside a step, the LERP slope is the secant \(\Delta_j=(e^{b_{r_j+1}}-e^{b_{r_j}})/h\), where \(b_r\) (\(r=0,\dots,K\)) are the grid positions in \(z=s-M\) coordinates (the grid values are \(e^{b_r}\)) and \(t_j\in[0,1]\) is the position within step \(r_j\).

Calibration derivatives (MinMax). With \(\rho_j=(r_j+t_j)/K\) and \(X_j=\tfrac1K\left[(1-t_j)\,r_j e^{b_{r_j}}+t_j(r_j+1)e^{b_{r_j+1}}\right]\):

\[\frac{\partial w^L_j}{\partial M}=-w^L_j-\Delta_j\rho_j+X_j,\qquad \frac{\partial w^L_j}{\partial m}=-\Delta_j(1-\rho_j)+w^L_j-X_j,\] \[\frac{\partial L}{\partial s_i}=\gamma_i\Delta_i+\mathbb 1[i=\arg\max]\sum_j\gamma_j\frac{\partial w_j}{\partial M}+\mathbb 1[i=\arg\min]\sum_j\gamma_j\frac{\partial w_j}{\partial m}.\]

The three terms sum to zero over \(i\), which is the identity that shift invariance implies. Detach keeps only \(\gamma_i\Delta_i\) and violates it. Under the fixed window, \(\partial w_j/\partial M=-\Delta_j\) and there is no \(m\) term.

Surrogates (\(\mathrm{sg}\) = stop-gradient). Both define the same hard forward \(P=P^N\) and use the same LERP derivatives. They differ in where the normalization Jacobian is evaluated:

\[\text{Weight-STE: } w=w^L+\mathrm{sg}(w^N-w^L),\qquad \gamma^W_j=\frac{g_j-\langle g\rangle_{P^N}}{W^N};\] \[\text{Prob-STE: } P=P^L+\mathrm{sg}(P^N-P^L),\quad P^L=\frac{w^L}{W^L},\qquad \gamma^P_j=\frac{g_j-\langle g\rangle_{P^L}}{W^L}.\]

Detach record (\(\Delta\mathrm{NLL}\) is validation NLL minus softmax, nats/token; ratio \(=e^{\Delta\mathrm{NLL}}\)):

  • LERP \(K=32\) (seed 1337): full-feedback run −0.0008 [−0.004, +0.002]; detach minus full +0.737 [+0.721, +0.752] (×2.09). Seeds 7 and 42: +0.802 and +0.780 at 100M.
  • Projecting detach onto the zero-sum subspace: +0.997 above full (worse than plain detach).
  • Single channel (seeds 7 / 42): keeping only the maximum’s calibration path recovers 98.1% / 98.8% of the gap, and keeping only the minimum’s recovers 0.3% / 7.2%.

2.5B-token endpoints (124M, FineWebEdu, 976 validation blocks): MinMax–Weight \(K=4\) +0.890; MinMax–Prob +0.061; fixed window–Weight +0.043; fixed window–Prob +0.019; LERP \(K=4\) +0.005; fixed window–Weight \(K=16\) +0.004; MinMax–Weight \(K=64\) +0.038.

Cross-suite \(K=4\) condition gaps (nats vs softmax):

Condition 124M @ 250M (FineWebEdu) 124M @ 2.5B (FineWebEdu) 1B @ 100M (WikiText-103, 1 seed) 124M @ 100M (WikiText-103, 5 seeds)
MinMax–Weight +0.389 +0.890 +0.220 +0.208
MinMax–Prob +0.074 +0.061 +0.146 +0.137
fixed window–Weight +0.039 +0.043 +0.061 +0.032
fixed window–Prob +0.007 +0.019 +0.038 +0.013
LERP +0.052 +0.005 +0.096 +0.098

Averaged over \(K\) on five seeds, the fixed window lowers NLL by 0.067 nats relative to MinMax and Prob-STE by 0.021 relative to Weight-STE, with a +0.031 interaction (the two changes substitute for each other). All three effects shrink with \(K\).

Show related work and positioning

The two papers build on three established lines of work. Post-training quantizers for vision transformers already put softmax probabilities on logarithmic grids. Integer and low-precision softmax designs already quantize the exponent relative to the row maximum. And writing an integer into the IEEE-754 exponent field to get a power of two is a classical way to approximate the exponential, used by Schraudolph (1999) and, for its partial exp2 emulation, by FlashAttention-4. On that basis the papers contribute three things:

  • a systematic characterization of which properties of the score-to-weight map a frozen pretrained model needs (positions, resolution and its allocation, shape, anchor), and of where scalar distortion metrics fail;
  • a calibration-free kernel, Rowmax-H15 inside FlashAttention-4, measured for model fidelity, latency and energy;
  • on the training side, a study of the backward rules: calibration derivatives, detach, and surrogate placement.

The related methods, one by one:

  • Coarsening the probability or score domain. Post-training quantization of vision transformers already puts post-softmax probabilities on logarithmic grids: FQ-ViT uses \(\log_2\), RepQ-ViT uses \(\log_{\sqrt2}\), and PTQ4ViT uses twin uniform grids. These grids are anchored to a row-independent scale. Our anchor control measures what that phase costs in a frozen LLM; it is not a reproduction of their vision results.
  • Row-max-relative exponent quantization. ITA’s integer streaming softmax already weights each score by a power of two of its floor-rounded distance to the streaming row maximum, with a clipping threshold obtained by quantization-aware training. EXAQ quantizes the input to the exponential after subtracting the row maximum, with a clipping range calibrated from activation statistics. IntAttention (its operator is called IndexSoftmax) uses a clipped 32-entry lookup table, with the range fixed offline and no training, for integer attention on Armv8 CPUs. Our 1-level-per-octave grid (Rowmax-PoT in the paper) shares ITA’s octave lattice but rounds to nearest without training; Rowmax-H15 halves the spacing.
  • Base-2 and approximate exponentials. Softermax uses base 2 with low-precision online normalization in a custom hardware unit and fine-tunes. I-BERT fits an integer polynomial, and I-ViT uses a base-2 shift with a linear segment; both recover accuracy by quantization-aware fine-tuning. FlashAttention-4 emulates part of exp2 with a cubic polynomial and rebuilds the result by shifting the integer part into the exponent field. That is the same reconstruction step as ours, on a different grid, and FA4 aims for accurate exp2.
  • Bit-level exponentiation. Schraudolph (1999) approximates exponentiation by an affine map into the IEEE-754 exponent and mantissa bits. Rowmax-H15 is a coarse specialization of that construction.
  • Operand quantization (SageAttention, SageAttention2, SageAttention3, INT-FlashAttention, MXAttention) keeps a full-precision exponential and changes the matrix-multiply operands. It could in principle be combined with ours; this was not evaluated.
  • Concurrent work. EFQ-Softmax also removes the dense per-element exponential inside a FlashAttention-style loop, and the positive part of its E2M1 code set, \(\{1,1.5\}\times2^e\), coincides with our lattice. The designs differ in anchor (microscaling-block maximum vs. attention-row maximum), rounding (affine thresholds vs. round-to-nearest-even), parameters (an offline two-parameter search vs. none) and measured scope (a kernel’s vector stage vs. the whole attention forward).
  • Training side. EXAQ and BAPS state that training with their operators is untested, and IndexSoftmax is designed as a training-free replacement. ConSmax learns per-head normalization parameters and keeps the exponential. Quantizer-learning methods (PACT, LSQ, TQT, and ITA’s clipping range) learn quantizer parameters. Our calibration quantities are per-row statistics of the scores, and dropping their derivative changes the feedback to the scores themselves.

Citation

If you find this work useful, please cite:

@misc{zhu2026approximating,
  title  = {Approximating Softmax in Pretrained {LLMs}: Model Sensitivity and Kernel Acceleration},
  author = {Zhu, Shangzhen and Hu, Muyan and Kozlowski, Tomasz},
  year   = {2026},
  eprint = {2609.33586},
  archivePrefix = {arXiv}
}
@misc{zhu2026pretraining,
  title  = {Pretraining Transformers with Quantized Softmax in Attention},
  author = {Zhu, Shangzhen and Hu, Muyan and Kozlowski, Tomasz},
  year   = {2026},
  eprint = {2609.33591},
  archivePrefix = {arXiv}
}

Video: How Much Softmax Do LLMs Need?