7.2 Newton's Method
Every transformer in AI Engineering normalizes its activations, and from Pre-LN and RMSNorm on the normalization is RMSNorm: divide a vector by . The C kernel in Elementwise kernels in C computes it for every token of every layer, and a division plus a square root per element is the slow way. Hardware and libraries compute directly, by a cheap guess refined with Newton’s method, and Fast inverse square root in standalone C does the same. This section teaches the method on paper and in Python, where you can watch the digits double, so that the C port has a trusted reference to compare against step for step.
Concepts from other sections (8)
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
- central difference: , a second-order approximation of . Read more: 7.1 Derivatives and Finite Differences
- 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
- Negative log-likelihood (NLL): , the surprise of the true token under the model, in nats. Read more: 17.2 Perplexity, bits per byte, NLL accumulator
- Variance: the expected squared distance from the mean; its square root is the standard deviation. Read more: 13.1 Random variables, expectation, variance, and normal draws by Box-Muller
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- Differential test: a check that two implementations of the same contract agree on generated inputs. Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- Magic constant:
0x5F3759DF, the offset that turns the bit-pattern logarithm into a first guess for within 3.44%. Read more: 15.5 Fixed-point iteration and fast inverse square root in C
The general root finder built here is also the first algorithm in the book that can fail in ways a caller must hear about: a flat tangent, a cycle, a runaway. The solution is built to say so rather than return a wrong number. The finished code is in course/solutions/python/tinyllm/num/newton.py: newton finds roots of a scalar function and reports how many updates it took, and rsqrt_newton is the division-free iteration for . The contract is course/contracts/py/tinyllm/num/newton.pyi.
This section builds on Derivatives and finite differences: when no derivative is passed, Newton uses central_diff as its slope.
Learning objectives
- Derive Newton’s step from the tangent line and show that it converges quadratically near a simple root.
- Recognize the failure modes of a locally convergent method (flat tangent, cycle, divergence) and report each one.
- Write a relative stopping test that works for roots of any size.
- Derive the division-free iteration for and predict its error after each step.
- Implement
newtonandrsqrt_newtonwith exact update counting and dtype-preserving arithmetic.
A root of is a number with . Many quantities are roots in disguise: is the positive root of , is the root of , and is a root of . A root is simple when : the graph crosses zero at an angle instead of touching it.
Throughout, is a differentiable function of one real variable, is its derivative (passed as df, or computed by central_diff when df is None), is the -th iterate with the starting guess, and is the error of the -th iterate.
The tangent-line step
Section titled “The tangent-line step”Near the tangent line approximates , which is what the derivative means:
The tangent line is zero at , and Newton’s method takes that point as the next iterate:
For the step is : average your guess with 2 divided by it, the method the Babylonians used for square roots. If the tangent is flat and never crosses zero, so there is no next iterate.
Quadratic convergence
Section titled “Quadratic convergence”How fast does the error shrink? Expand around and evaluate at the root, using Taylor’s formula with the exact remainder from Taylor series: for some between and ,
Divide by and use the definition of to get , that is,
The new error is proportional to the square of the old one. If and , then and : the number of correct digits doubles each step. For , , and the ratio approaches exactly that.
When Newton fails
Section titled “When Newton fails”The proof needs and already close to the root. Far from it nothing is promised. started at 0 jumps to 1 and back to 0 forever. has its tangent at cross zero at , so every step doubles the distance. A method that is only locally convergent must be given an iteration budget, max_iter, and must report when it runs out.
The derivative must also move with the iterate. Computing once and reusing it (the chord method) still converges, but only linearly: the error shrinks by a constant factor per step, and if that factor exceeds 1 it diverges. When no derivative is passed, newton calls central_diff at each ; its relative error near keeps the convergence effectively quadratic.
Knowing when to stop
Section titled “Knowing when to stop”Stop when the step is negligible relative to the iterate, , with a default tolerance of . An absolute test fails for large roots: floats near 12649 are apart, so near the last steps hop between two neighboring floats and an absolute is never met. The keeps the test absolute near zero, where a relative one would demand impossible precision. And if is exactly 0, is a root and no step is needed.
That completes the general method. The same tangent step, aimed at a cleverly chosen function, gives the reciprocal square root that RMSNorm needs.
Newton for the reciprocal square root
Section titled “Newton for the reciprocal square root”Here is a positive number (a float32 or float64 array) whose you want, and is the -th estimate, in the same dtype. Apply the step to , whose positive root is . With :
There is no division and no square root: three multiplications and a subtraction. (The more obvious needs first, a division.) Write , so that is the relative error. Substituting,
so the relative error squares (times ) each step. A good first guess comes from the bits of a float32: the integer , read back as a float, is within 3.5 percent of for every positive normal , because halving the bits roughly halves the exponent. Then and : float32 accuracy (its spacing is relative) after two steps. The C port uses exactly this, so rsqrt_newton computes in the dtype it is given: float32 in, float32 arithmetic, float32 out.
Working it by hand
Section titled “Working it by hand”Start with from , with and the step . The table tracks each iterate, its exact fraction, its error, and the ratio that quadratic convergence predicts:
| as a fraction | ||||
|---|---|---|---|---|
| 0 | 1 | |||
| 1 | 1.5 | 0.50 | ||
| 2 | 1.416666… | 0.33 | ||
| 3 | 1.4142157 | 0.353 | ||
| 4 | 1.41421356237469 | 0.354 | ||
| 5 | 1.4142135623730951 | below one float spacing |
The correct digits go 0, 1, 2, 5, 11, 16. Update 5 moves by , more than , so the method takes update 6, which moves by one unit in the last place, and stops: newton returns , having evaluated at the six points .
Now compute from , so :
Check with the error formula: .
Designing the interface
Section titled “Designing the interface”The two functions have these signatures:
def newton(f, df, x0: float, tol: float = 1e-12, max_iter: int = 50) -> tuple[float, int]: ...def rsqrt_newton(x: ArrayLike, y0: ArrayLike, iters: int) -> NDArray: ...newton returns (root, updates). It raises ValueError for a non-finite x0, tol <= 0, or max_iter < 1, and RuntimeError naming the cause when the derivative is zero or not finite (“derivative”), an iterate is not finite (“diverged”), or max_iter updates do not converge (“no convergence”). rsqrt_newton broadcasts x against y0 and computes in their floating dtype (float64 for integers).
Building it step by step
Section titled “Building it step by step”Eight decisions turn the analysis into code.
- One loop iteration is one tangent step. Evaluate and , then . Count updates, the number of times moved, because that is what the convergence analysis is about and what
max_iterbudgets. - Check for an exact root before computing a slope. If there is nothing to do; return with the updates so far (0 if was already a root).
- Refuse to divide by a useless slope. A zero, NaN, or infinite derivative has no tangent root; dividing would produce inf or NaN that surfaces later as a misleading failure. Raise with the word “derivative” now.
- Re-evaluate the derivative at every iterate. A frozen derivative (the chord method) converges only linearly. When
dfisNone, the slope iscentral_diff(f, x_n)at the current point, accurate to about , which keeps convergence effectively quadratic. - Catch runaways immediately. If is not finite, the method diverged; report it at that step, not one step later as a flat tangent at infinity.
- Stop on a relative step. Stop when : relative for large roots (float spacing grows with ), absolute near 0 (a relative test would demand impossible precision there).
- Treat running out of budget as a failure, not an answer. If
max_iterupdates pass without meeting the test, raise; the last iterate of a cycle is not a root. - Specialize the same idea for rsqrt. Run a fixed number of times on whole arrays. It must compute in the inputs’ float dtype so the float32 version matches the C port operation for operation. The factor does not change between steps, so it is computed once.
Here is newton:
def newton( f: Callable[[float], float], df: Optional[Callable[[float], float]], x0: float, tol: float = 1e-12, max_iter: int = 50,) -> tuple[float, int]: x = float(x0) if not math.isfinite(x): raise ValueError(f"x0 must be finite, got {x0}") if not tol > 0: # also rejects a nan tol raise ValueError(f"tol must be > 0, got {tol}") if max_iter < 1: raise ValueError(f"max_iter must be >= 1, got {max_iter}") # No derivative given: a fresh central difference at each iterate (step 4). deriv = df if df is not None else (lambda t: central_diff(f, t)) for n in range(max_iter): # n = updates made so far fx = float(f(x)) if fx == 0.0: return x, n # x is a root: no step needed (step 2) d = float(deriv(x)) if d == 0.0 or not math.isfinite(d): raise RuntimeError( f"derivative is {d} at x = {x!r} (step {n}): the tangent has no root" ) x_new = x - fx / d # the tangent's zero if not math.isfinite(x_new): raise RuntimeError(f"iterate {n + 1} is {x_new}: Newton diverged") # Relative step test: near a root of size 1e10 an absolute 1e-12 is # below the float spacing and could never be met. if abs(x_new - x) <= tol * max(1.0, abs(x_new)): return x_new, n + 1 # this was update n + 1 x = x_new raise RuntimeError(f"no convergence after {max_iter} updates (last iterate {x!r})")The count works out exactly: in the iteration with index n, n updates have already happened, and computing x_new is update n + 1. On the example the loop runs with n = 0, ..., 5, evaluates at , and returns at n = 5 with 6 updates, which fits max_iter = 6 exactly. On the cycle from 0, every update is a full step of size 1, the test is never met, and after 50 updates the function raises “no convergence” instead of returning 0. On from 1 each step doubles , so with a large enough budget iterate 1024 overflows to inf and the “diverged” branch fires.
The reciprocal square root is shorter:
def rsqrt_newton(x: ArrayLike, y0: ArrayLike, iters: int) -> NDArray: if iters < 0: raise ValueError(f"iters must be >= 0, got {iters}") xa, ya = np.asarray(x), np.asarray(y0) dt = np.result_type(xa, ya) # float32 + float32 stays float32 if not np.issubdtype(dt, np.floating): dt = np.dtype(np.float64) # integers compute in float64 xa, y = np.broadcast_arrays(xa.astype(dt), ya.astype(dt)) y = y.copy() # broadcast views are read-only and may alias y0 half, three_halves = dt.type(0.5), dt.type(1.5) # constants in the working dtype hx = half * xa # 0.5 x, hoisted out of the loop for _ in range(int(iters)): y = y * (three_halves - hx * y * y) # y (3/2 - x y^2 / 2): no division, no sqrt return yEvery operand in the loop has dtype dt, so a float32 call does float32 arithmetic throughout and returns float32, which is what lets the C port compare its output bit for bit; the C code must then group the products the same way, ((hx * y) * y). iters = 0 returns a fresh copy of the broadcast guess.
The function takes the first guess y0 from the caller. The bit-trick guess is one line of numpy, shown here for reference (it is not part of the solution file):
x = np.array([4.0, 2.0, 1e-3, 7e5], dtype=np.float32)y0 = (np.uint32(0x5f3759df) - (x.view(np.uint32) >> np.uint32(1))).view(np.float32)# relative error of rsqrt_newton(x, y0, k) for k = 0, 1, 2: about 3.4e-2, 1.7e-3, 4.4e-6The full solution is in newton.py.
Why this design
Section titled “Why this design”Each update costs one evaluation of and one of (or two more of for the central difference). Quadratic convergence means the number of updates grows only like of the digits wanted: the example goes from 0 to 16 correct digits in 6 updates. rsqrt_newton costs 3 multiplications and 1 subtraction per element per step, with no division or square root.
Failures raise exceptions rather than returning sentinel values. Returning the last iterate or a NaN on failure invites callers like fit_temperature in Logistic regression, ROC-AUC, and calibration to use a wrong temperature. Distinct messages (“derivative”, “diverged”, “no convergence”) tell the caller which assumption broke.
There are safer alternatives. Bisection or Brent’s method cannot diverge, but they converge linearly or superlinearly and need a bracket the caller must supply. A safeguarded Newton combines both; this section keeps plain Newton so its behavior, including its failures, is visible. For , computing 1 / np.sqrt(x) is simpler in Python but is not the operation the C kernel performs, so it cannot serve as a step-for-step reference.
Two tradeoffs are accepted. The stopping test looks at the step, not at , so on a function that is very flat near its root it can stop with a small step but a modest residual. And a multiple root (where ) converges only linearly and may exhaust the budget. Both are documented properties of Newton’s method that the contract leaves to the caller.
What can go wrong
Section titled “What can go wrong”A correct solution reproduces the hand-worked : the fractions, 6 updates, and evaluated at . Its errors must show , the quadratic convergence that is the reason to use Newton at all. An exact root at the start, , returns with no needless step. Large roots such as and must converge, and 30 seeded square and cube roots must match their closed forms to full precision. With df=None, solving must give , exercising the finite-difference slope.
The failure paths are tested as carefully. A flat or NaN tangent raises RuntimeError (“derivative”); the 0, 1, 0, 1 cycle raises RuntimeError; doubles away until inf and raises “diverged”. The budget counts updates exactly: 6 updates fit max_iter = 6, not 5. A NaN or infinite start, tol <= 0, or max_iter = 0 raises at once. For rsqrt_newton, the hand-worked gives 0.472 and then 0.4977; from the bit-trick guess, float32 errors fall as , , ; four float64 steps reach rounding level; float32 must match step for step, bit for bit; integers compute in float64; iters = 0 works and iters < 0 raises.
The usual mistakes and their symptoms:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| not checking for a zero or non-finite derivative | ZeroDivisionError, or a NaN that later looks like “no convergence” | raises “derivative” before dividing |
| returning the last iterate when the method did not converge | the cycle’s last point (0.0) reported as a root of | raises “no convergence” after the loop |
| letting an inf iterate continue | the failure is blamed on a flat tangent one step later | checks math.isfinite(x_new) right after the step |
| an absolute stopping test | no convergence at the right answer near | tol * max(1.0, abs(x_new)) |
| computing the derivative once at (chord method) | linear convergence, or divergence when changes a lot | calls deriv(x) inside the loop, including central_diff at each iterate |
| dropping a factor of in | converges to the wrong value, -like | y * (three_halves - hx * y * y): two factors of inside, one outside |
| computing float32 inputs in float64 | results that differ from the C port in the last bits, and a float64 array where float32 was expected | dt = np.result_type(...) and constants of type dt |
| stepping uphill, , or multiplying by | the hand example’s iterates go wrong at step 1 | x_new = x - fx / d |
| always stepping once, even at an exact root | instead of | the fx == 0.0 check comes before any step |
| one Newton step fewer than asked | the error after two steps is , not | range(int(iters)) runs exactly iters steps |
Warning: Returning the last iterate of a failed run is the most dangerous mistake on this list, because it produces a plausible number. A cycle’s last point looks like any other float.
Where this leads
Section titled “Where this leads”The main call site is fit_temperature in Logistic regression, ROC-AUC, and calibration, which calls newton(g, dg, 0.0) on the derivative of the negative log-likelihood in , with the variance of the logits as dg. Fast inverse square root in standalone C, an optional C side trip, implements the same in float32 from the bit-trick guess, and its differential test compares against rsqrt_newton; tl_rmsnorm_f32 in Elementwise kernels in C multiplies by that reciprocal square root for every token. Error analysis, condition numbers, and tolerance budgets generalizes convergence order and error propagation. A planned optimization section on Muon will use Newton-Schulz iterations, Newton’s method for a matrix function, to orthogonalize momentum.
Further reading
Section titled “Further reading”- OpenStax, Calculus Volume 1 (free), section 4.9: Newton’s method.
- Sauer, Numerical Analysis, sections 1.4 and 1.5: convergence order and when Newton fails.
- Lomont, “Fast inverse square root” (2003): the magic constant.
- x86
rsqrtps, ARMfrsqrte, and CUDArsqrtf: a hardware table lookup for the first 12 bits, then the same Newton refinement. See the Intel intrinsics guide for_mm_rsqrt_psand ggml’sggml_vec_*RMSNorm paths. - SciPy
scipy.optimize.newtonandbrentq(scipy/optimize/_zeros_py.py): secant and Halley variants; Brent’s method brackets the root so it can never diverge. - Press et al., Numerical Recipes, section 9.4: safeguarded Newton (
rtsafe), which falls back to bisection whenever the Newton step leaves the bracket. - Jordan et al., Muon (2024): Newton-Schulz for the matrix sign function, , the same polynomial as the reciprocal square root iteration.
Key terms
Section titled “Key terms”- root: a number with .
- simple root: a root where , so the graph crosses zero at an angle.
- Newton’s method: the iteration , jumping to the zero of the tangent line.
- quadratic convergence: , so correct digits double each step.
- local convergence: convergence guaranteed only from starting points close enough to the root.
- chord method: Newton with the derivative frozen at ; it converges only linearly.
- relative stopping test: .
Summary
Section titled “Summary”- Newton’s method replaces by its tangent line at and jumps to the tangent’s zero: .
- Near a simple root it converges quadratically, with at the root, so the number of correct digits doubles every step.
- It is only locally convergent: it can cycle, diverge, or hit a flat tangent, and a correct implementation reports each of these instead of returning a wrong number.
- The stopping test must be relative, , because floats near a large root are far apart.
- Applied to , Newton computes with only multiplications, ; two steps from a 3.5 percent guess reach float32 accuracy.
Review questions
Section titled “Review questions”-
Why does
newtonreturn(x, n)when , but(x_new, n + 1)when the step test passes?Answer
ncounts updates already made. An exact root needs no further update, so the count staysn(0 if is a root). When the step test passes, the update that producedx_newhas just happened, so it is counted:n + 1. Getting this wrong makesmax_iter = 6fail on a problem that needs exactly 6 updates. -
Why is the stopping test rather than ?
Answer
Float spacing near is about . Near that is , so the last steps hop between neighboring floats and never get below an absolute : the method would report “no convergence” at the right answer. Scaling by makes the test relative; the keeps it absolute near 0, where relative precision is unreachable.
-
Why check
math.isfinite(x_new)separately when the derivative check already rejects non-finite slopes?Answer
A finite and a finite, nonzero, but tiny slope can still produce a step that overflows, and a diverging iteration like reaches inf through finite steps. Without the check the next iteration would evaluate and fail with a misleading message about the derivative; catching it at the step that produced it reports “diverged” accurately.
-
Why does
rsqrt_newtonbuild its constants withdt.type(0.5)and hoisthx = half * xa?Answer
Typed constants keep every operation in the working dtype, so float32 inputs give float32 arithmetic, the same rounding as the C port, rather than being promoted to float64 under older numpy casting rules. Hoisting saves one multiplication per step and fixes the operation order the C code reproduces.
-
With the step needs no division. Why not use the simpler-looking ?
Answer
Its Newton step is , which needs and a division by at each step: exactly the expensive operations the iteration is meant to avoid. puts the unknown in the denominator of , and the division cancels algebraically in the step.