Computing exp2
Part 1 · Base conversion and range reduction
This series develops a reasonably efficient and accurate hardware unit for exp2(x), the base-two exponential . We will use FP32 inputs and outputs, with a target error of at most two FP32 representable steps (2 ULP) and one result per cycle per lane. The main application is softmax, so negative inputs and behavior near zero deserve particular attention.
Posts in this series
- Computing exp2 (this post) — Motivation, base conversion, range reduction, and the choice of polynomial.
- Range reduction, tables and polynomial degree — Why subdivision and higher degree improve the fit, and how they change storage and arithmetic.
- Remez, coefficient search, accuracy testing and hardware cost — Fit coefficients for finite-precision arithmetic, test accuracy, and compare hardware experiments.
- Generating RTL and searching implementation choices — Identify circuit choices, generate RTL and improve the implementation through measured experiments.
Why focus on exponentials?
For one attention head with queries, keys and head width ,
The rows of are queries; the rows of are keys and their associated values. compares every query with every key. Row-wise softmax turns these scores into weights , and uses those weights to average the value vectors, producing . FlashAttention-2, §2 describes its tiled evaluation and memory costs in more detail.
For a row of scores , softmax computes
Subtracting multiplies numerator and denominator by the same factor, so the weights are unchanged. It prevents overflow by keeping every exponential input nonpositive; the largest input is zero and produces exactly 1.
The two matrix products require approximately FLOPs in total (counting a multiply and an add separately), versus exponentials. Their work ratio is therefore FLOPs per exponential.
The relevant matrix dimension is the attention head width, not the model’s hidden size. Even very large models use short dot products:
| Model | Query heads | Head width |
|---|---|---|
| Llama 3.1 405B | 128 | 128 |
| Qwen3-235B-A22B | 64 | 128 |
With , both matmuls together provide only 512 FLOPs per exponential. A 16,384-token full-attention head has about 137 GFLOPs of matrix work and 268 million exponentials. Causal masking reduces both counts; tiling avoids storing the full score matrix but still computes its unmasked exponentials.
To compare matrix and exponential throughput directly, use one SM and one cycle throughout. If the matrix units produce FLOPs per SM per cycle, then at the corresponding demand is
The table uses dense matrix arithmetic, counting a multiply-add as two FLOPs. Both attention matmuls use the listed operand precision; the exponential remains FP32.
| GPU | Matmul precision | Matmul (FLOPs/SM/cycle) | Exp demand (results/SM/cycle) | FP32 exp capacity (results/SM/cycle) | Demand / capacity |
|---|---|---|---|---|---|
| H100 | BF16/FP16 | 4,096 | 8 | 16 | 0.5× |
| H100 | FP8 | 8,192 | 16 | 16 | 1× |
| B200 | BF16/FP16 | 8,192 | 16 | 16 | 1× |
| B200 | FP8 | 16,384 | 32 | 16 | 2× |
| B300 | BF16/FP16 | 8,192 | 16 | 32 | 0.5× |
| B300 | FP8 | 16,384 | 32 | 32 | 1× |
| Rubin | BF16/FP16 | 8,192 | 16 | 32 | 0.5× |
| Rubin | FP8 | 32,768 | 64 | 32 | 2× |
For example, B200’s FP8 matrix units can do 16,384 FLOPs per SM per cycle. Dividing by 512 gives a demand of 32 exponentials per cycle, but the FP32 exponential units can produce only 16. At these peak rates, exponentials alone need twice as many cycles as the two matmuls. At BF16, demand and capacity are equal. Moving to FP8 shortens the matrix work without reducing the number of scores to normalize.
The Hopper and Blackwell baselines are described in FlashAttention-3 and FlashAttention-4. NVIDIA’s Rubin platform overview, Table 2 and architecture comparison give the exponential rates; the FP8/BF16 matrix rates follow the NVIDIA-contributed Triton implementation and CUTLASS instruction definitions.
Rubin also has a 64-result-per-SM-per-cycle FP16/BF16 exponential path, which would change the balance if we chose that precision for softmax. Here we keep FP32 exponentials so the comparison matches our numerical target. Softmax also needs maxima, sums and normalization; the table isolates its exponential work. NVIDIA’s Blackwell Ultra measurements show why increasing SFU throughput particularly helps FP8 attention.
Why use base two?
Softmax uses , but we can compute it using :
Increasing its input by one doubles its output: . Binary floating point already represents a number as a significand multiplied by a power of two. If we can compute for , changing its scale by a power of two is inexpensive. For normal outputs, multiplication by can be implemented by changing the exponent rather than using a general multiplier.
The identity above is exact, but a rounded multiplication by introduces error. Simply computing that product in FP32 can change the final answer by tens of ULPs. Using exp2 for exp requires an adequately precise base conversion.
Why not compute exp directly?
Direct can also separate a power-of-two scale. Since , split its input at multiples of :
Choosing leaves . The reduced output again lies between 1 and 2. Substituting gives , so the approximation problem is the same curve expressed in a different coordinate.
The distinction is the input arithmetic. For exp2, the interval boundaries are integers, so the reduction amounts to separating an integer and a binary fraction. For exp, we must locate a multiple of the irrational constant and subtract it accurately. An error in that small remainder becomes an error in the exponential. Implementations such as fdlibm’s exp retain extra precision in that subtraction by splitting the constant into high and low parts.
We choose exp2 because its reduction and scaling fit binary arithmetic naturally. Using it for exp moves the nonbinary constant into the input conversion; it does not eliminate the need to represent that constant precisely.
Error from base conversion
Let . If conversion rounds this to , the exponential is changed by
The last approximation is the first-order expansion of near zero. It tells us how an absolute error in the converted input becomes a relative error in the output. Even a perfect exp2 implementation cannot recover the discarded part of its input.
Consider . Using a high-precision conversion gives
Rounded to FP32, this becomes , a change of about . The resulting relative change in the exponential is about . In this example, both paths still round to the same FP32 output, .
Now consider . The converted argument is
but its nearest FP32 value is . Here the change is about , giving a relative output change of about . The correctly rounded outputs are:
| Computation | FP32 output |
|---|---|
| after rounding to FP32 |
FP32 spacing at these outputs is about . The two results are 43 representable steps apart, or 43 ULPs.
The curves and are identical. To see what rounding changes, compare relative input error with relative output error on the same plot. Each line fixes an original input ; moving right means introducing more relative error into its converted argument. Read upward from that input error to find the relative error in the exponential.
Why does the error grow farther from zero? FP32 keeps a fixed number of significant bits, not fractional bits. Around , adjacent inputs are apart; around , they are apart. The latter spacing is 64 times coarser, allowing a larger absolute .
The input error at is only relative to , yet the relative output error is . Since ,
Relative output error is approximately times relative input error: about 76-fold amplification here.
These examples use a high-precision and round the product once. Storing the constant in FP32 introduces another error. The reference outputs above were computed with MPFR; directed lower and upper bounds agree on each FP32 rounding decision.
To obtain an accurate exp from exp2, retain enough precision through the conversion and into range reduction. If a preceding operation already scales the input, its scale can incorporate , but rounding that result to FP32 still has the effect described above.
What does computing exp2 require?
A direct table could store the FP32 answer for every FP32 input. But entries at 32 bits each would occupy 16 GiB. Instead, we can store polynomial coefficients and evaluate a polynomial for each input.
Look at on . Its value rises from to 4, and its slope increases by the same factor of 16. A line cannot follow this changing slope. A quadratic has a slope that changes with , so it can also match how the exponential bends near a chosen point.
To choose its coefficients, write . At zero, its value is , its slope is , and its second derivative is . We want these to match . Since , differentiating gives
At zero, , and . Thus we choose , and :
Here is the natural logarithm of 2, about 0.693147. This is the degree-two Taylor polynomial of at zero. The three matching conditions determine its coefficients; we have not optimized error across an interval.
The animation keeps this polynomial fixed and narrows the interval around zero. Both axes rescale so we can still see the curves.
At , the estimate is about 2.30 times the true value. At , it is about 1.009 times the true value: an error of 0.90%.
Range reduction
For an exponential, integer intervals are scaled copies of one another. For any integer ,
For example, on the values run from to . Multiplying them by 16 gives exactly the curve on : the same shape, starting at 1 and ending at 2. Each integer interval differs only by a binary scale factor.
For any input , choose
Then , so the only curve we need to approximate is on . For example,
Computing gives approximately . Scaling by gives approximately . The same approximation to also serves , , and every other input with fractional part .
This is range reduction: replace the original input with a smaller argument whose function value determines the original answer. At the normal/subnormal boundary, the result must be rounded to the final subnormal spacing.
For implementation examples, the method notes in fdlibm’s exp explicitly separate argument reduction, approximation and scaling by . Arm’s exp2f uses a finer split, , then combines a table-based scale with a polynomial for the small residual. Its reconstruction builds the binary scale through exponent bits.
The animation’s 0.90% error at is still far above our two-ULP target. A bounded interval helps, but we also need a more accurate polynomial.
Why not just use a Taylor series?
The infinite Taylor series represents exactly. Our hardware evaluates a finite polynomial, leaving an error. For the quadratic above,
There are no constant, linear or quadratic terms in this error: matching the value and first two derivatives at zero eliminated them. Near zero, the error therefore shrinks like . At , the absolute error is about ; at , it is about —roughly eight times larger when the distance from zero doubles. Farther away, the cubic grows and the remaining terms also matter. At , the error is about , or 3.33% of the true value. The infinite series still converges there; the same three-term truncation is simply much less accurate.
We can retain more terms, but Horner evaluation then needs more multiply-adds. We can also shorten the interval, at the cost of more table entries.
Taylor has used all three coefficients to make the error and its first two derivatives exactly zero at the center. Those conditions leave no freedom to reduce the endpoint errors. On a symmetric interval around zero, the quadratic underestimates at the positive endpoint and overestimates it at the negative endpoint. Increasing its linear coefficient slightly raises the right side and lowers the left side, reducing both endpoint errors. It also changes the slope at zero, introducing a small linear error nearby. We give up some of Taylor’s very accurate local match to improve the worst error across the interval.
For a fixed degree and interval, a minimax polynomial minimizes the worst error. For example, an absolute-error fit of a quadratic to on solves
We can instead minimize relative error by dividing the expression inside the absolute value by . The choice matters because absolute, relative and FP32-step errors weight the interval differently.
The Remez algorithm finds such fits by repeatedly adjusting the coefficients and the locations of the largest errors. For an unconstrained quadratic absolute-error fit, the optimum has four ordered points where the error reaches the same magnitude with alternating signs. Raising the polynomial to reduce one extreme would worsen another: this balances error across the interval rather than forcing it to vanish at the center. NIST DLMF §3.11(i) gives the alternating-error condition and the equations for iteratively updating the coefficients. For a detailed account of the algorithm, see §2 of Pachón and Trefethen’s Barycentric-Remez algorithms for best polynomial approximation in the chebfun system (2009). It explains both steps: finding new error extrema and solving for the next polynomial with equal, alternating errors.
The real-valued fit is a starting point: rounding coefficients and intermediate results changes its error, so we will also search the actual fixed-point computation.
Conclusions
Range reduction gives us a bounded approximation problem and inexpensive binary scaling. Minimax fitting improves the polynomial at a chosen degree before we add arithmetic or table entries.
The complete computation still needs to preserve accuracy through input conversion and rounding, with exactly and nondecreasing outputs near zero. Part 2 explores how table resolution and polynomial degree trade approximation error against storage and arithmetic.