15.5 Fixed-point iteration and fast inverse square root in C
Every layer of a Llama-family model normalizes its activations with RMSNorm, introduced in Pre-LN and RMSNorm in AI Engineering: . In Python that is one np.sqrt per row. When the same normalization moves into C as tl_rmsnorm_f32 in Elementwise kernels in C, the Rust engine calls it once per row, per layer, per token. The C library’s 1.0f / sqrtf(s) would work, but it is two of the slowest float instructions in a hot loop, it is a black box, and it breaks the rule that every kernel in these books is something you can derive and test against its Python version.
Concepts from other sections (5)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- RMSNorm: divides a vector by its root mean square plus eps (inside the root) and multiplies by a learned gain; no mean subtraction, no bias. Read more: 13.1 Pre-LN and RMSNorm in AI Engineering
- Newton’s method: the iteration , jumping to the zero of the tangent line. Read more: 7.2 Newton’s Method
- Subnormal: a value with exponent field 0, no implicit leading 1, and a fixed exponent , filling the gap between zero and the smallest normal. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- Linear convergence: the error shrinks by a constant factor each step. Read more: 15.9 Problem set B: condition numbers, error bounds, Newton, polynomial approximation, and low precision
- Trie: a rooted tree whose edges carry characters so that each node spells the string on its path. Read more: 12.2 Trees and tries, longest-prefix match
The derivation already exists. rsqrt_newton in Newton’s Method is Newton’s method for without a division. This optional section turns it into a C function whose contract is stated in ulps, and proves the contract on every float32 input that matters. Along the way you will see Newton’s method as a special case of fixed-point iteration, understand why the famous 0x5F3759DF constant works, and learn why a third step in double precision is what turns a 73-ulp approximation into a nearly correctly rounded one.
You need the iteration from Newton’s Method and the float32 bit patterns and subnormals of IEEE 754 anatomy, ulps, and round to nearest even. The solution, rsqrt.c, is a standalone C file built under ASan and UBSan; Python and C do not call into each other, and the numerical contract holds without any Python at run time. The interface lives in numerics.h, under the rules of c/ABI.md.
Learning objectives
- Explain the difference between linear and quadratic convergence of a fixed-point iteration in terms of .
- Derive the division-free Newton update for and its exact error recurrence .
- Explain why a float’s bit pattern is a piecewise-linear , and derive the magic-constant first guess from it.
- Justify why checking two binades exhaustively proves the accuracy contract for every normal input, and handle subnormals and special values.
The notation
Section titled “The notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| the input, a positive float32 | float | |
| the exact answer (a real number) | ||
| the -th iterate, an approximation of | float or double | |
| the relative error of | ||
| the iteration map: | ||
| the 32-bit pattern of read as an unsigned integer | uint32_t | |
| the exponent field (8 bits) and mantissa field (23 bits) of | integers | |
| the spacing of float32 values at : for normal | ||
| the tuning offset in the bit-pattern logarithm, about 0.045 |
Fixed-point iteration
Section titled “Fixed-point iteration”A fixed point of a map is a value with . Fixed-point iteration starts from a guess and repeats . If is differentiable near , a Taylor expansion (see Taylor series, remainder bounds, and range reduction) gives
So the distance to shrinks by the factor each step when (a contraction: linear convergence). When the first-order term vanishes and the distance is squared each step (quadratic convergence: the number of correct digits doubles).
Newton’s method as a fixed-point iteration with
Section titled “Newton’s method as a fixed-point iteration with g′(r)=0g'(r) = 0g′(r)=0”Newton’s method is the fixed-point iteration you get by choosing so that . The Newton chapter applied it to , whose positive root is . With :
There is no division and no square root: two multiplies, a subtract, a multiply. Its derivative is , which is at because . Substituting and :
so exactly, in real arithmetic. From you get , , and . In float32 each step also adds a few units of of rounding, which is why the error cannot go below about in float32 no matter how many steps you take.
A first guess from the bits
Section titled “A first guess from the bits”Quadratic convergence is only as good as its starting point, and the starting point here comes from a beautiful observation about the float format. A positive normal float is with . Its bit pattern is , because the exponent field sits above the 23 mantissa bits. Since for with a small constant ,
The bit pattern is a scaled, shifted logarithm. Taking logs of gives ; replacing both logs by the bit-pattern formula and solving for :
With the constant is 0x5F3759DF, and I(x) >> 1 is rounded down. The resulting is never more than 3.44% from . In C the only defined way to read a float’s bits is memcpy into a uint32_t (a pointer cast breaks the aliasing rule); C++20 has std::bit_cast, Rust f32::to_bits, and numpy .view(np.uint32).
The algorithm, and why two binades check everything
Section titled “The algorithm, and why two binades check everything”The contract asks for 2 ulp. Two float32 steps give , which is 40 to 73 ulp, and a third float32 step gets only to about 2.2 ulp because of its own rounding. So the third step runs in float64, where rounding is , and the result is rounded to float32 once. The full algorithm is:
y = bits(0x5F3759DF - (bits(x) >> 1));- twice, in float32,
t = hx * y; t = t * y; t = 1.5f - t; y = y * twithhx = 0.5f * x; - once, in float64, the same four statements on
(double)xand(double)y; return(float)y.
Each statement is separate on purpose. C allows the compiler to fuse a * b + c inside one expression into a fused multiply-add with one rounding instead of two (#pragma STDC FP_CONTRACT OFF forbids it too), and the Python version computes in exactly this order.
The accuracy proof rests on scaling. For normal , replace by : the pattern grows by , so the guess’s pattern shrinks by , which halves exactly. Every product in steps 2 and 3 then scales by a power of two, which is exact, so bit for bit. Every normal float is for one , and holds floats, so an exhaustive check simply tries all of them. The solution’s worst case is 0.5004 ulp.
Two kinds of input fall outside that argument. Subnormals have , so is no longer a logarithm and the guess is far off; multiply by (exact, and the result is normal), compute, and multiply the result by (also exact). Special values have fixed answers: and (as in IEEE arithmetic), , and negative numbers and NaN give NaN. Check them before the bit trick, which would turn each of them into a finite number.
Working it by hand
Section titled “Working it by hand”Take , so . The table follows each stage of the algorithm:
| Step | Computation | Value | Relative error |
|---|---|---|---|
| bits | $I(4) = $ 0x40800000; >> 1 is 0x20400000 | ||
| guess | 0x5F3759DF - 0x20400000 = 0x3EF759DF: , $m = $ 0x7759DF , | 0.48310754 | 0.0338 |
| step 1 (f32) | ; ; ; | 0.49915358 | 1.69e-3 () |
| step 2 (f32) | ; | 0.49999782 | 4.35e-6 () |
| step 3 (f64) | ; | 0.5 after rounding to float32 | 2.8e-11 |
You can watch the error square at each step, exactly as the recurrence predicts. The same steps with give the float32 nearest , 0.70710677, and with give 2.529822. These become the hand-worked test cases.
Designing the API
Section titled “Designing the API”The public interface is a scalar function and an array form:
/* tinyllm/numerics.h, rsqrt section */float tl_rsqrtf(float x); /* within 2 ulp; +-0 -> +-inf, +inf -> +0, x < 0 or NaN -> NaN */void tl_rsqrt_f32(const float *x, float *y, int64_t n); /* elementwise; y == x (exact aliasing) allowed */The solution writes rsqrt_normal (steps 1 to 3 for a positive normal input) as a static helper, then tl_rsqrtf as the dispatcher over the special cases and the subnormal rescale. Neither function can fail, so neither touches the error slot.
Building it step by step
Section titled “Building it step by step”The reasoning chain has six links. First, avoid the division and the square root: Newton on gives , with multiplies and one subtraction only, and with , so the relative error squares each step. Second, quadratic convergence needs a good start: from 3.44% the errors go , , , and because the bit pattern is a scaled logarithm, one integer subtraction gives that start for any normal input. Third, count the steps against the contract: two steps leave , about 73 ulp; a third step in float32 is limited by its own rounding (2.18 ulp); a third step in float64 has error plus roundings, so rounding the result to float32 once gives a correctly rounded or nearly correctly rounded answer (0.5004 ulp worst case). Fourth, keep the arithmetic order fixed: each multiply and subtract is a separate statement with FP_CONTRACT OFF, so no compiler fuses them and the C result matches the Python version bit for bit. Fifth, prove accuracy on two binades: every step commutes with exactly, so checking all of checks every normal float. Sixth, bring every other input into that case or handle it directly: specials are answered before the bit trick, and subnormals are scaled by into the normal range and the answer by back, both exact.
The file begins with the bit-view helpers:
#pragma STDC FP_CONTRACT OFF /* no fused multiply-add: two roundings, as in Python */
#define TL_RSQRT_MAGIC 0x5F3759DFu
static uint32_t f32_bits(float x) { uint32_t u; memcpy(&u, &x, sizeof u); /* the defined way to view a float's bits */ return u;}
static float f32_from_bits(uint32_t u) { float x; memcpy(&x, &u, sizeof x); return x;}memcpy is the only bit reinterpretation the C standard defines; a pointer cast (*(uint32_t *)&x) violates strict aliasing, and UBSan or an optimizer can make it misbehave. Compilers turn this memcpy into a single register move.
The core is the normal-input path:
/* Steps 1 to 3 for a positive normal x. */static float rsqrt_normal(float x) { float hx = 0.5f * x; /* exact: a power of two */ float y = f32_from_bits(TL_RSQRT_MAGIC - (f32_bits(x) >> 1)); /* y0 within 3.44% */ for (int i = 0; i < 2; i++) { /* two float32 Newton steps: 3.44% -> 4.7e-6 */ float t = hx * y; t = t * y; /* (0.5 x) y^2, in the Python version's order */ t = 1.5f - t; y = y * t; /* y (1.5 - 0.5 x y^2) */ } double xd = (double)x, yd = (double)y; /* exact widening */ double hd = 0.5 * xd; double t = hd * yd; t = t * yd; t = 1.5 - t; yd = yd * t; /* error ~3e-11, far below half a float32 ulp */ return (float)yd; /* the only rounding to float32 of the last step */}Trace the hand example through it. For the pattern 0x40800000 shifts to 0x20400000, the subtraction gives 0x3EF759DF , the two float32 passes give and , and the float64 pass gives , which rounds to exactly 0.5f. Note that the shift happens on the bits (f32_bits(x) >> 1); shifting the value converted to an integer is one of the classic mistakes listed below.
The dispatcher and array form complete the file:
float tl_rsqrtf(float x) { if (isnan(x)) return x + x; /* quiet NaN in, NaN out */ if (x == 0.0f) return signbit(x) ? -INFINITY : INFINITY; /* 1/sqrt(+-0) */ if (x < 0.0f) return NAN; if (isinf(x)) return 0.0f; /* only +inf is left here */ if (x < 0x1p-126f) { /* Subnormal: 2^24 x is normal and exact; rsqrt(2^24 x) = rsqrt(x) / 2^12. */ return rsqrt_normal(x * 0x1p24f) * 0x1p12f; } return rsqrt_normal(x);}
void tl_rsqrt_f32(const float *x, float *y, int64_t n) { /* One read and one write per index, in order, so y == x (exact * aliasing) is safe. */ for (int64_t i = 0; i < n; i++) y[i] = tl_rsqrtf(x[i]);}The order of the checks matters. NaN goes first because every comparison with NaN is false, so it would otherwise fall through to the bit trick. Zero is tested before the sign, since is false and must map to , not NaN. After NaN, zero, and negatives are gone, isinf can only see . 0x1p-126f is FLT_MIN, the smallest normal. The subnormal rescale uses because the smallest subnormal is , and is normal; undoes it. The array form uses int64_t for , so simply runs no iterations, and reading x[i] before writing y[i] makes in-place use safe. The full solution is in rsqrt.c.
Why this design
Section titled “Why this design”The normal path costs one integer subtract, nine float32 operations, five float64 operations, and two conversions per call, with no division, square root, table, or branch; the array form is .
Compare it with the alternatives. The library pair 1.0f / sqrtf(x) is correctly rounded and simple, but it uses the two slowest float instructions and cannot be derived and bit-matched against a Python twin; this version is within 0.5004 ulp, inside the 2 ulp contract, and reproducible on any IEEE platform. The Quake III version (two float32 steps) reaches only 73 ulp, too far for a normalization that feeds every layer, and the third step costs only a handful of float64 operations. Three float32 steps would be cheaper on hardware without fast doubles, but their own rounding leaves 2.18 ulp, outside the contract. Finishing in a wider format is what makes the last step’s rounding irrelevant.
The tradeoff accepted is that the float64 step makes the code harder to vectorize with float32 SIMD lanes. A production kernel would use a hardware estimate plus one float32 refinement, as described at the end of the section, and accept a looser bound.
What can go wrong
Section titled “What can go wrong”The tests start from the hand-worked inputs (4, 0.25, 1, 2, 0.15625, with the bits above), so everyone agrees on the algorithm. The central property test runs all floats of and requires each to be within 2 ulp, which checks the worst-case error over two complete binades. A second property checks that rsqrt(4x) == rsqrt(x)/2 bitwise on 2000 seeded normals, which is the reason two binades are enough. All positive subnormals must be within 2 ulp, since RMSNorm of a nearly-zero row produces them. Special values (, , negatives, NaN, FLT_MAX, FLT_TRUE_MIN) must follow the contract, so that a zero row with visibly gives . Finally, the array form must give the scalar’s bits, write exactly elements, work in place, and treat as a no-op, because the RMSNorm kernel runs it on a whole row in place.
The mistakes these tests catch:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| stopping after the two float32 steps (the Quake III version) | 73 ulp worst case | a third step in float64 |
guessing from the value: (float)(MAGIC - ((uint32_t)x >> 1)) | converts the number 4 to the integer 4; the guess is and Newton diverges | reads the bits with memcpy (f32_bits) before shifting |
| no rescale for subnormal inputs | thousands of ulps below FLT_MIN | x < 0x1p-126f scales by and back by |
| the third step in float32 | 2.18 ulp worst case, over the contract | the third step widens to double |
| treating or like any other input | a finite number where the contract says or 0 | NaN, zero, negative, and infinity are answered before the bit trick |
| the array loop off by one | the last element unwritten, or one past the end overwritten | for (int64_t i = 0; i < n; i++), one read and one write per index |
| a different constant shift or step count | caught as accuracy, not as a crash | fixed TL_RSQRT_MAGIC, >> 1, and exactly two plus one steps |
Tip: A fused multiply-add in the float32 steps is worth trying once. It changes in its last bit, yet the float64 step absorbs the difference and the result keeps the same bits, so no accuracy check can see it. That robustness is the point of finishing in a wider format.
Where this leads
Section titled “Where this leads”The optional standalone C normalization kernel of Elementwise kernels in C in AI Engineering uses tl_rsqrtf(mean(x^2) + eps) and includes this file in its build. The next section, Polynomial approximation and range reduction: expf in C, uses the same pattern, a reduction followed by a cheap approximation, for .
Production code takes the idea in several directions. x86 rsqrtps and ARM frsqrte give a hardware 12-bit table estimate, followed by one Newton step (ARM’s frsqrts computes in one instruction). glibc and CORE-MATH provide an rsqrtf that is correctly rounded for every input, with a proof. llama.cpp’s ggml_vec_* RMSNorm and PyTorch’s fused RMSNorm vectorize rows and fuse the norm with the scale (ggml/src/ggml-cpu/ops.cpp, ggml_compute_forward_rms_norm). And Lomont’s 0x5F375A86, or Moroz et al.’s constants with modified Newton coefficients, give a smaller first-step error, so that one Newton step is enough.
Further reading
Section titled “Further reading”- Lomont, Fast Inverse Square Root (2003, free).
- Higham, Accuracy and Stability of Numerical Algorithms, chapter 1.
- Süli and Mayers, An Introduction to Numerical Analysis, chapter 1 (fixed-point iteration).
- Arm A64 ISA reference,
FRSQRTEandFRSQRTS. - The CORE-MATH project (Inria).
- Moroz, Walczyk, et al., Fast calculation of inverse square root with the use of magic constant (2018).
Key terms
Section titled “Key terms”- Fixed point: a value with .
- Contraction: a map with near its fixed point, whose iteration converges linearly.
- Quadratic convergence: convergence in which the error is squared each step, so correct digits double; it happens when .
- Magic constant:
0x5F3759DF, the offset that turns the bit-pattern logarithm into a first guess for within 3.44%. - Strict aliasing: the C rule that forbids reading an object through a pointer of an unrelated type;
memcpyis the defined way to view a float’s bits.
Summary
Section titled “Summary”- Newton’s method is a fixed-point iteration whose map has at the root, so the relative error squares every step: .
- A float’s bit pattern is a piecewise-linear , so one integer subtraction,
0x5F3759DF - (bits >> 1), computes a first guess for within 3.5%. - Two float32 Newton steps reach relative error, which is still about 73 ulp; one more step in float64 lands within 0.5004 ulp of the true value, checked on every input.
- Two binades decide every normal input, because holds bit for bit for this algorithm; subnormals need a rescale first.
- The result is a standalone C kernel whose numerical contract is derived from the Newton chapter and holds without any Python at run time.
Review questions
Section titled “Review questions”-
Why is Newton’s iteration for written on rather than on ?
Answer
gives the update , which needs only multiplies and a subtraction. gives , which divides twice: the expensive operation the routine exists to avoid.
-
Why is the third Newton step done in double instead of float?
Answer
After two steps the mathematical error is , and one more step reduces it to about . In float32, the step’s own roundings (each up to relative) dominate and leave 2.18 ulp. In float64 the roundings are , so the only significant error is the final conversion to float32, at most half an ulp plus a tiny margin.
-
Why does testing every float in cover every normal float32 input?
Answer
Multiplying by 4 adds to its bit pattern, so
>> 1adds and the guess’s pattern drops by : exactly half the guess. Every later product is then scaled by a power of two, which is exact in binary floating point, so bit for bit and the error in ulps is the same. Every normal float is for one . -
Why must NaN and be checked before anything else in
tl_rsqrtf?Answer
Comparisons with NaN are false, so a NaN would pass every later test and reach the bit trick, which turns its pattern into a finite guess. is false, so would skip the negative check, and the bit trick on a zero pattern returns a finite number; IEEE says .
-
Why are subnormals multiplied by and the result by , and why is that exact?
Answer
A subnormal has exponent field 0, so its pattern is not a logarithm and the guess is far off. Multiplying by lifts even the smallest subnormal to , a normal number, without rounding (only the exponent changes). Since , multiplying the result by recovers the answer, again exactly.