8.2 Series convergence, the EMA as a geometric series, and bias correction
The loss a training loop prints jumps around from batch to batch, and what you care about is its trend. The standard tool for extracting that trend is an exponential moving average, and the first thing it does is lie: started from zero, it reports a loss of 0.55 when every batch says 5.5, and climbs toward the truth over hundreds of steps. Adam, the optimizer every model in AI Engineering trains with, keeps two such averages per parameter and would take wildly wrong first steps without the correction this section derives.
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.
- p-series / harmonic series: , which converges if and only if ; the harmonic series is the case and diverges, growing like , which is why it appears in hashing and coupon-collector analyses. Read more: Chapter 8: Calculus 2
- Geometric sequence: a sequence that multiplies by the same ratio at every step, . Read more: 6.3 Sequences, geometric series, and frequency ladders
- Expected value: the average outcome across many repetitions of a situation under the model. Read more: Chapter 4: Uncertainty and evidence
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3
- Second moment (,
exp_avg_sq): the EMA of the elementwise squared gradient. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay - Decoupled weight decay (AdamW): multiplying the weights by outside the gradient path. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay
- debiased EMA: an exponential moving average divided by so its early values are not pulled toward zero. Read more: 6.6 Training loop and the autograd bigram in AI Engineering
Both the lie and the fix are a fact about one infinite sum, the geometric series. This section defines what it means for a series to converge, sums the geometric series exactly, and builds the EMA and its bias correction on top of the geometric and geometric_sum helpers from Sequences, geometric series, and frequency ladders. The notion of a limit comes from Derivatives and finite differences.
The finished code is course/solutions/python/tinyllm/num/ema.py, which provides ema_weights and the class EMA (with update, value, t, and value_debiased); its interface is fixed by the contract course/contracts/py/tinyllm/num/ema.pyi.
Learning objectives
- Define convergence of a series through its partial sums and show why the harmonic series diverges.
- Derive the partial sum of a geometric series and its limit for .
- Unroll the EMA recursion into a weighted sum with geometric weights, and compute its effective window and half-life.
- Derive the bias correction and explain why it requires the zero start.
- Implement an
EMAclass that rejects non-finite input without corrupting its state and never leaks internal arrays.
Series and convergence
Section titled “Series and convergence”The symbols used throughout are collected here first:
| Symbol | Meaning | Type / shape |
|---|---|---|
| a sequence of numbers | ||
| the -th partial sum | float | |
| the ratio of a geometric sequence, | float | |
| the input at step | float or array | |
| the decay, | float | |
| the EMA after updates, | float or array | |
| the weight of in | float | |
| the bias-corrected average | float or array |
A series is the sequence of its partial sums . It converges to when the partial sums settle on in the sense of a limit: for every tolerance there is a beyond which every is within it. Otherwise it diverges.
Small terms are necessary but not enough. The harmonic series diverges, because the terms from to are numbers each at least , adding to at least for every , so the sum passes any bound.
A useful sufficient condition is the ratio test: if eventually stays below some , the series converges, because from there on its terms are smaller than those of a geometric series with ratio . The previous section, Taylor series, remainder bounds, and range reduction, used exactly this argument to bound the tail of the erf series. Everything therefore rests on the geometric series, which is where we turn next.
The geometric series
Section titled “The geometric series”For , multiply the partial sum by and subtract. Everything but the first and last terms cancels:
If , and the series converges to ; if the terms do not shrink and it diverges.
There is one numerical catch. When is close to 1, subtracts two nearly equal numbers. The geometric_sum helper evaluates it as to keep full precision, and the code here calls it rather than re-deriving it.
The EMA unrolled
Section titled “The EMA unrolled”The update keeps a fraction of the old average and mixes in of the new input. Unroll it from and the geometric series appears:
The newest input has weight , and each step back in time multiplies the weight by : a geometric sequence. ema_weights(beta, t) returns oldest first, which is geometric(1 - beta, beta, t) reversed.
Two numbers summarize how far back the average looks. The effective window is (the sum of the infinite weight sequence divided by its largest weight): 10 steps for , 1000 for . The half-life, after which an input’s weight has halved, is : 6.6 steps for .
Bias correction
Section titled “Bias correction”Now the lie becomes visible. The weights add up to a geometric partial sum:
An average whose weights add to less than 1 is pulled toward 0, which is where it started. If every , then : after one step with , only . Dividing by the total turns the weights back into an average,
and for a constant input at every , exactly in real arithmetic (and to a few in float64). If the inputs are random with the same mean , the expected value of is , so is an unbiased estimate of . That is why Adam’s update has the right size from its first step.
The correction matters only early. falls below 1 percent after steps, and from then on .
Two consequences shape the code. First, the zero start is part of the definition: initializing with and then dividing by corrects a bias that is not there ( for ). Second, at the correction is : nothing has been averaged, so value_debiased raises instead of returning a number.
Working it by hand
Section titled “Working it by hand”Take and inputs , , . The recursion, the weight total, and the corrected value evolve like this:
| 1 | 0.1 | ||
| 2 | 0.19 | ||
| 3 | 0.271 |
Unrolled, : the same number, with weights adding to . The biased is below even the smallest input; the debiased 2.07 is a weighted average of 1, 2, 3 that leans toward the newest.
Designing the interface
Section titled “Designing the interface”The module exposes one function and one class:
def ema_weights(beta: float, t: int) -> NDArray: ... # oldest first, sum 1 - beta**tclass EMA: def __init__(self, beta: float) -> None: ... # 0 <= beta < 1, m_0 = 0 t: int # property: updates so far value: float | NDArray # property: m_t (a copy) def update(self, x: ArrayLike) -> float | NDArray: ... def value_debiased(self) -> float | NDArray: ... # m_t / (1 - beta**t)A number in gives a Python float out; an array in gives a new float64 array, averaged elementwise, and later updates must keep its shape. Non-finite input raises ValueError and leaves the state unchanged; value_debiased before any update raises RuntimeError.
Building it step by step
Section titled “Building it step by step”Each design decision follows from the derivation above.
- The state is two numbers: and . The recursion needs only the previous average, and the correction needs only the count. Keeping the whole history is unnecessary, since the unrolled form shows the recursion is the weighted sum.
- Start at . The bias correction is derived for that start. Seeding with and also dividing by would correct a bias that is not there.
- The correction total comes from
geometric_sum. is exactlygeometric_sum(1 - beta, beta, t), which stays accurate for near 1 where cancels. - has no average. The debiased value would be ; raising is the only honest answer.
- Validate before mutating. A non-finite input or a shape change raises before the state changes, so one bad batch leaves the curve intact. is checked once, at construction: (with the average never moves and the correction divides by 0).
- Never hand out internal state. Returning the internal array would let a caller’s in-place edit change the average, so every array returned is a copy, and scalars come back as Python
float. - The weights are the geometric sequence, reversed.
geometric(1 - beta, beta, t)lists , newest first; the contract lists (the oldest) first, so reverse it.
Validating and listing the weights
Section titled “Validating β\betaβ and listing the weights”def _check_beta(beta: float) -> float: b = float(beta) # isfinite first, so nan fails; beta = 0 is allowed (the EMA is the last value) if not (math.isfinite(b) and 0.0 <= b < 1.0): raise ValueError(f"beta must satisfy 0 <= beta < 1, got {beta}") return b
def ema_weights(beta: float, t: int) -> NDArray: b = _check_beta(beta) if t < 0: raise ValueError(f"t must be >= 0, got {t}") # (1 - b), (1 - b) b, (1 - b) b^2, ... is newest first; x_1 is the oldest. return geometric(1.0 - b, b, int(t))[::-1].copy()The .copy() turns the reversed view into a fresh, contiguous array. For , : geometric(0.1, 0.9, 3) is , reversed to , the weights of the hand example.
The EMA class
Section titled “The EMA class”class EMA: def __init__(self, beta: float) -> None: self.beta = _check_beta(beta) self._t = 0 self._m: float | NDArray = 0.0 # m_0 = 0, the start the correction assumes self._shape: tuple | None = None # fixed by the first update
@property def t(self) -> int: return self._t
@property def value(self) -> float | NDArray: m = self._m return m.copy() if isinstance(m, np.ndarray) else float(m)
def update(self, x: ArrayLike) -> float | NDArray: a = np.asarray(x, dtype=np.float64) if not np.isfinite(a).all(): # checked before any state changes raise ValueError( "x must be finite: one nan or inf would poison every later average" ) if self._shape is not None and a.shape != self._shape: raise ValueError( f"x has shape {a.shape}, earlier updates had {self._shape}" ) # Start from m_0 = 0, never from x_1: the bias correction below # assumes the zero start, and the two together would double-correct. m = self.beta * self._m + (1.0 - self.beta) * (a if a.ndim else float(a)) self._shape = a.shape self._m = m self._t += 1 return self.value # a copy, or a Python float
def value_debiased(self) -> float | NDArray: if self._t == 0: raise RuntimeError( "value_debiased before any update: the average of nothing is 0 / 0" ) # The weights of m_t add up to (1 - b)(1 + b + ... + b^(t-1)) = 1 - b^t. # geometric_sum (M00.3) gets that total right even for b near 1, where # 1 - b**t subtracts two nearly equal numbers. out = self._m / geometric_sum(1.0 - self.beta, self.beta, self._t) return out.copy() if isinstance(out, np.ndarray) else float(out)The expression (a if a.ndim else float(a)) keeps scalars as Python floats, so a scalar EMA stays a float all the way through, while an array input makes m a new float64 array (the expression allocates a new array; nothing is updated in place). Run the hand example through it: after update(1), update(2), update(3) with , value is , t is 3, and value_debiased() divides by geometric_sum(0.1, 0.9, 3) , giving . With , geometric_sum(1.0, 0.0, t) is 1 and , so both values are the latest input.
The full solution is ema.py.
Why this design
Section titled “Why this design”update is per scalar ( for an array of elements) and the state is (or ), however many steps have run. value_debiased adds one geometric_sum, which is . Recomputing from a stored history would cost time and memory per step.
The recursion is preferred over the explicit sum for the same reason. Both give the same number, as the hand example shows, but the recursion needs no history and rounds only a couple of times per step, so its rounding error stays at a few hundred ulps after many steps.
Computing the total beats tracking it. You could keep a running by multiplying by each step and then form , but that rounds once per step and then cancels for near 1. geometric_sum evaluates the total from and directly, accurate at any .
Raising beats skipping bad inputs. Silently dropping a NaN would hide a real failure upstream (a diverged batch); raising with the state unchanged lets the caller decide, and the curve stays valid either way.
One tradeoff is accepted: the EMA keeps one decay for its whole life. Schedules that change over time (annealing) need a new object or a different correction, because assumes a constant .
What can go wrong
Section titled “What can go wrong”A correct implementation must pass the following checks, each tied to something that depends on it:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| the hand-worked EMA | unit | the hand example’s and , the counter, Python floats | everyone agrees on the recursion and the correction |
| the hand-worked weights | unit | , total 0.271 | the unrolled form |
| weights total | property | totals and ratio for five and five | the geometric partial sum |
| recursion equals weighted sum | differential | the recursion equals the dot product with ema_weights on 200 seeded inputs | two definitions, one number |
| a debiased constant is exact | property | for up to 0.9999, up to 3000 | the central property of the EMA |
| exact rational arithmetic | golden | the float64 and against the same recursion in exact rational arithmetic (fractions.Fraction), rounded once, after 200 seeded steps | rounding in the recursion stays at a few hundred ulps |
| the bias fades | property | how long the bias lasts | |
| boundary | returns the latest input | annealed schedules | |
| arrays averaged elementwise | differential | an array EMA equals one scalar EMA per element; returned arrays are copies; shape changes raise | EMA weights over whole tensors in the TinyStories capstone |
| non-finite input | boundary | NaN and inf raise, state unchanged | one bad batch must not poison the curve |
| debiasing before any update | boundary | raises RuntimeError | 0/0 is not a number |
| bad | boundary | , , NaN raise | never moves |
The common mistakes each leave a recognizable fingerprint.
Warning: Swapping and in the update makes the average follow the newest input with weight 0.9 and forget at once. The update must read
self.beta * self._m + (1.0 - self.beta) * x.
Starting from and still dividing by gives for ; _m must start at 0.0. An off-by-one power, or , gives for , or a division by zero at ; the total is geometric_sum(..., self._t) with _t incremented once per update. Accepting NaN or inf makes every later average NaN; np.isfinite(a).all() is checked before any state changes. Forgetting the correction entirely reports the hand example’s 0.1 as the average of 1; value_debiased divides by the weight total.
The remaining mistakes are subtler. Listing the weights newest first produces a weighted sum with the wrong inputs emphasized; ema_weights reverses geometric(...). Rejecting refuses a valid, if trivial, average; _check_beta accepts 0.0 <= b. Returning the internal array from update lets a caller’s in-place edit change the average; update returns self.value, a copy. Having no check at yields a ZeroDivisionError instead of a clear error; value_debiased raises RuntimeError when _t == 0.
Where this leads
Section titled “Where this leads”The EMA shows up as soon as you train anything. In AI Engineering, Training loop and the autograd bigram passes ema=EMA(beta) to train_step, which feeds each step’s loss to update and reports value_debiased() as loss_ema, the smoothed loss curve. The TinyStories capstone keeps an EMA of the model weights and evaluates it alongside the raw weights. And in Adam and AdamW: bias correction and decoupled weight decay, Adam’s first and second moments are EMAs of the gradient and its square, divided by and : exactly this correction, applied twice.
Further reading
Section titled “Further reading”- OpenStax, Calculus Volume 2 (free), sections 5.2 and 5.3: infinite series, the geometric series, and divergence.
- Kingma and Ba, “Adam” (2015), section 3: initialization bias correction. Adam and AdamW in
torch/optim/adam.pyapply the same correction to two moments, often folded into the step size . - PyTorch
torch.optim.swa_utils.AveragedModelwithget_ema_multi_avg_fn(torch/optim/swa_utils.py): an EMA of every parameter tensor and buffer, updated in place on the device. - TensorBoard’s smoothing slider (
tensorboard/plugins/scalar, thesmoothingweight): a debiased EMA of the plotted scalar, exactly the one built here. numpy.expm1andnumpy.log1p, the functions that make accurate for ; see Sequences, geometric series, and frequency ladders.
Key terms
Section titled “Key terms”- Series: the sequence of partial sums of a sequence.
- Convergence: the partial sums settle on a finite limit; otherwise the series diverges.
- Ratio test: if successive term ratios eventually stay below some , the series converges.
- Geometric series: , with partial sum and limit for .
- Exponential moving average (EMA): the recursion , a weighted sum with geometric weights.
- Effective window: , roughly how many recent steps the EMA reflects.
- Bias correction: dividing by its weight total so the zero start no longer pulls the average toward 0.
Summary
Section titled “Summary”- A series converges when its partial sums settle on a number; the geometric series converges to exactly when , and its partial sum is .
- The EMA from is a weighted sum of all inputs with geometric weights .
- Those weights add up to , not 1, so early values are biased toward 0; dividing by fixes it, and the debiased average of a constant is that constant at every step.
- The bias fades on its own as , after roughly steps; with that is a thousand steps of a misleading curve.
- One NaN in the input poisons every later average, so
updaterejects non-finite values and keeps its state.
Review questions
Section titled “Review questions”-
Why must the EMA start at rather than at the first input?
Answer
The correction is derived from the unrolled sum starting at , whose weights total . Starting at already gives an unbiased average (its weights total 1), so dividing by inflates it: with , . One can use either the zero start with the correction or the start without it, never both.
-
Why does
value_debiaseddivide bygeometric_sum(1 - beta, beta, t)instead of computing1 - beta**t?Answer
They are equal in exact arithmetic, but for near 1 and small , is close to 1 and subtracts two nearly equal numbers, keeping only part of its digits.
geometric_sumevaluates the same total withexpm1andlog1p, so it stays accurate at ; that is what keeps the debiased average of a constant equal to the constant. -
What happens to the EMA if
updateaccepts a single NaN, and why does the solution check before changing state?Answer
is NaN, and every later is $\beta \cdot \text{nan} + \ldots = $ NaN: the whole curve is lost from that step on, since nothing ever removes the NaN. Checking first and raising before assigning
_m,_shape, or_tmeans a rejected input leaves the EMA exactly as it was, so the caller can skip the bad batch and continue. -
Why does
updatereturnself.value(a copy) rather thanself._m?Answer
For array inputs
self._mis a numpy array; returning it would hand the caller a reference to the internal state, and an in-place operation on the result (r *= 2,r[0] = 0) would silently change the average.valuereturns a copy, so the EMA can only be changed throughupdate. -
With , roughly how long is the uncorrected curve misleading, and how does that follow from the geometric series?
Answer
The uncorrected of a constant is . , which falls to 1 percent at steps, and to about after steps, the effective window. For the first thousand or so steps the raw curve sits visibly below the true loss, which is why the training loop reports the debiased value.