6.3 Sequences, geometric series, and frequency ladders
The previous section gave you rotations, and RoPE rotates each pair of a query by an angle proportional to the token’s position. That leaves an open question: how fast should each pair turn? If every pair turned by 1 radian per token, positions tokens apart would look identical; if every pair turned slowly, neighbours would be indistinguishable. RoPE’s answer is a ladder of speeds, a geometric sequence, and so is the answer of ALiBi, the other position scheme in Context extension in AI Engineering.
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.
- RoPE: rotary position embedding, which rotates queries and keys by position to encode relative position. Read more: 5.3 Model landscape and lifecycle in AI Engineering
- ALiBi: a per-head bias that falls linearly with query-key distance, used instead of rotations. Read more: 13.4 Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi in AI Engineering
- Unit roundoff: , the largest relative error of a single round-to-nearest. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- Exponential moving average (EMA): the recursion , a weighted sum with geometric weights. Read more: 8.2 Series convergence, the EMA as a geometric series, and bias correction
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- Bias correction: dividing by its weight total so the zero start no longer pulls the average toward 0. Read more: 8.2 Series convergence, the EMA as a geometric series, and bias correction
- Partial rotary: rotating only the first entries of each head. Read more: 13.3 Rotary Position Embeddings in AI Engineering
- YaRN: a per-pair ramp between keeping and dividing frequencies, by turns over the trained context, plus a temperature . Read more: 13.4 Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi in AI Engineering
The same mathematics turns up in training. The moving averages of Adam weight past gradients by a geometric sequence and correct for its partial sum, which is the subject of Series and the EMA and Adam and AdamW. And when the Llama-family loader reads rope_theta = 100000 from SmolLM2’s config.json, it must turn it into exactly the frequencies Hugging Face computes. This section builds geometric sequences and their sums, accurately, including the hard case near a ratio of 1 where the textbook formula loses half its digits, and then both position ladders.
You need powers, , and the functions log1p and expm1 from Exponents, logarithms, and units of information, and numpy’s arange and power from Python and numpy in Programming and Algorithms. The finished code is course/solutions/python/tinyllm/num/series.py, which provides geometric, geometric_sum (with the helper _ones_sum), rope_inv_freq, and alibi_slopes; its interface is fixed by the contract course/contracts/py/tinyllm/num/series.pyi.
Learning objectives
- Derive the partial sum of a geometric sequence and its infinite limit for .
- Show that an exponential moving average weights its inputs by a geometric sequence whose weights sum to .
- Explain why the closed-form sum cancels near and rewrite it with and so it keeps its digits.
- Build RoPE’s inverse-frequency ladder and ALiBi’s head slopes, including the rule for head counts that are not powers of two.
Sequences
Section titled “Sequences”The symbols used throughout are collected here first:
| Symbol | Meaning | Type / shape |
|---|---|---|
| the first term of a sequence | float | |
| the common ratio | float | |
| the number of terms | int | |
| term , counted from | float | |
| the sum of the first terms, | float | |
| the decay of an exponential moving average, | float | |
| the value seen at step and the moving average after it | float | |
the rotary dimension (d_rot): the number of coordinates RoPE rotates, even | int | |
the RoPE base (rope_theta in a config.json) | float | |
| inverse frequency of pair , , in radians per position | float[d/2] | |
| wavelength of pair , , in positions | float | |
| the number of attention heads | int | |
| the ALiBi slope of head | float[H] | |
| float64 unit roundoff, |
A sequence is a list of numbers indexed by position: . Two families matter here. An arithmetic sequence adds the same step, ; the positions are one. A geometric sequence multiplies by the same ratio, : has and . With the terms shrink toward 0; with they grow without bound; with they alternate in sign.
Compute term as a * r**j, not by multiplying the previous term by . A running product rounds once per step, and its error grows with .
The geometric sum
Section titled “The geometric sum”Let . Multiply by to get . Subtracting, every term but two cancels:
and when , since every term is . When , approaches 0 as grows, so the infinite sum converges: . That is why , and why a repeating decimal is a fraction: .
The exponential moving average is a geometric series
Section titled “The exponential moving average is a geometric series”The first place this sum does real work is the exponential moving average (EMA). With decay , it updates , starting from . Unrolling the recursion,
so the weights are a geometric sequence , newest first, and they add up to , not 1. Early on, the average is biased toward its starting value 0: after one step with , . Adam divides by to undo exactly this. With the ratio is , close to 1, and that is precisely the case where the closed form is numerically dangerous, as we will see shortly.
Frequency ladders: RoPE
Section titled “Frequency ladders: RoPE”RoPE rotates pair of a query or key at position by the angle , with
This is a geometric sequence with first term and ratio . Pair 0 turns one radian per token and repeats every positions; the last pair turns radians per token, slightly faster than , and repeats only after about positions. Like the hands of a clock (seconds, minutes, hours), fast pairs resolve neighbouring tokens and slow pairs tell far-apart ones apart, and the geometric spacing gives every scale the same number of pairs. The exponent steps by because there are pairs spread over the exponents from 0 to almost 1.
Models with partial rotary embeddings rotate only the first coordinates of each head; the formula is the same with that . The SmolLM2-135M config.json says hidden_size = 576 over num_attention_heads = 9, a head size of 64, and rope_theta = 100000. rope_inv_freq(64, 1e5) must match what Hugging Face computes from those (in float32, to float32 precision), or the loaded checkpoint sees the wrong positions.
Frequency ladders: ALiBi
Section titled “Frequency ladders: ALiBi”ALiBi (Press et al.) adds no rotation at all. Head subtracts times the distance between query and key from each attention score, so far tokens are penalized linearly, and each head has its own slope. For a power of two, the slopes are the geometric sequence with first term and ratio :
running from (steep: the head looks at the last few tokens) down to (flat: it looks hundreds of tokens back).
For other , let be the largest power of two below . The paper’s code takes the slopes for heads, then fills the remaining heads with every other slope of the -head ladder, , which fall between the existing ones. Find with integer arithmetic (1 << (H.bit_length() - 1)), never with a floating-point .
Floating point near a ratio of 1
Section titled “Floating point near a ratio of 1”Back to the EMA’s hard case. For close to 1, the closed form divides one small difference by another. is computed exactly, because subtracting nearby floats is exact. But is first rounded to about relative error, and then subtracts two numbers that agree in most of their digits, keeping the rounding error and losing the rest. With and , carries an absolute error near : about 5 correct digits out of 16.
The cure is to never form near 1. Since ,
where and are computed accurately for small arguments by math.log1p and math.expm1. Every quantity in this form is small and accurate, and the result keeps nearly all 16 digits. For this form is used everywhere; for the closed form has no cancellation, because . When the sum overflows (huge and ), the answer is , with the sign of the last term.
Working it by hand
Section titled “Working it by hand”Start with a geometric sum: , so , , .
which agrees with adding . With every term triples, so .
Next, the RoPE ladder for and . There are four pairs, with exponents :
| exponent | wavelength | ||
|---|---|---|---|
| 0 | 0 | 1 | 6.28 positions |
| 1 | 62.8 | ||
| 2 | 628 | ||
| 3 | 6283 |
( because .) The ratio is .
Finally, ALiBi with 6 heads. Since 6 is not a power of two, . The 4-head ladder has first term and ratio : . The 8-head ladder is ; every other entry from the first is , and the two extra heads take the first two:
The extra slopes and sit between the existing ones, so the six heads still cover the range evenly.
Designing the interface
Section titled “Designing the interface”Four functions cover the sequences and both ladders:
def geometric(a: float, r: float, n: int) -> NDArray: ... # [a, a r, ..., a r^(n-1)]def geometric_sum(a: float, r: float, n: int) -> float: ... # accurate near r = 1def rope_inv_freq(d_rot: int, base: float) -> NDArray: ... # base ** (-2 i / d_rot), [d_rot/2]def alibi_slopes(n_heads: int) -> NDArray: ... # Press et al., any head countEverything is float64. Bad counts (negative, fractional, or True), an odd or non-positive d_rot, a base that is not finite and above 1, and a head count below 1 raise ValueError.
Building it step by step
Section titled “Building it step by step”Eight observations fix the implementation.
- Terms are independent powers. Term is by definition, so each term can be computed directly from . Computing it from the previous term would add one rounding per step; computing directly rounds once. So
geometricevaluatesa * r**jover the vector , and is the empty vector. - The sum factors as times the sum of ones. , so all the numerical care goes into one helper for , and
geometric_summultiplies by once at the end. - Two exact cases come first. sums nothing (); makes every term 1 (). Both avoid dividing .
- For , never form . cancels near . Writing and turns the numerator into . The denominator is exact for near 1 (two floats within a factor of 2 of each other subtract exactly), so every piece carries nearly full precision. Far from 1 the form is just as accurate, so there is no threshold to tune: one formula for all .
- For , the closed form is safe. is undefined for , but there , so the denominator is never small and the textbook formula does no harmful cancellation (except for near , which the contract does not promise).
- Overflow has a known answer. If and is large, the sum is dominated by its last term , so the result is with that term’s sign: for , and for , when is even. Python’s
math.expm1andfloat ** intraiseOverflowErrorinstead of returning infinity, so the helper catches it and returns the infinity. - RoPE is a geometric ladder on a fixed exponent grid. With pairs and , the solution builds as floats and raises to in one vectorised step. The arguments must make a decreasing ladder: even and at least 2 (there must be whole pairs), and and finite.
- ALiBi is two ladders. Find , the largest power of two , exactly with bit arithmetic. The first slopes are
geometric(start, start, p)with , which gives . If , build the -head ladder the same way, take every other entry from the first ([0::2]), and keep the first of them, exactly the six-head computation above.
Terms and argument checking
Section titled “Terms and argument checking”Argument checking is shared by every function that takes a count. True is an int in Python, so it must be rejected explicitly:
def _check_n(n: int) -> int: # bool first: isinstance(True, int) is True, but a count of True makes no sense. # int(n) != n rejects 2.5 while accepting 3.0. if isinstance(n, bool) or int(n) != n or n < 0: raise ValueError(f"n must be a non-negative integer, got {n!r}") return int(n)
def geometric(a: float, r: float, n: int) -> NDArray: n = _check_n(n) # a * r**j for each j, not a running product: a running product rounds at # every step and its error grows with j. return float(a) * np.power(float(r), np.arange(n, dtype=np.float64))np.arange(n) starts at 0, so term 0 is , and it stops at , so there are exactly terms.
The accurate sum
Section titled “The accurate sum”The sum of ones carries all the floating-point reasoning:
def _ones_sum(r: float, n: int) -> float: """1 + r + ... + r^(n-1), accurate for every r > 0, including r near 1.""" if n == 0: return 0.0 # the empty sum if r == 1.0: return float(n) # n ones; the closed form would be 0/0 try: if r > 0.0: # (1 - r^n) / (1 - r) = expm1(n ln r) / (r - 1). With r near 1 the # textbook numerator 1 - r**n subtracts two nearly equal numbers; # log1p and expm1 never form that difference. d = r - 1.0 # exact when r is near 1 return math.expm1(n * math.log1p(d)) / d # r <= 0: 1 - r >= 1 and the closed form has no cancellation to fear, # except r^n near 1 (r near -1), which the contract does not promise. return (1.0 - r**n) / (1.0 - r) except OverflowError: # |r| > 1 and n large: the last term r^(n-1) dominates, and so does its sign. return math.inf if (r > 0.0 or (n - 1) % 2 == 0) else -math.inf
def geometric_sum(a: float, r: float, n: int) -> float: n = _check_n(n) return float(a) * _ones_sum(float(r), n)Both branches compute the same quantity, ; the branch only flips both signs, , so that the numerator is an expm1. For the EMA, geometric_sum(1 - beta, beta, t) is then with all its digits, even at .
The RoPE ladder
Section titled “The RoPE ladder”RoPE’s ladder is one line once the arguments are validated:
def rope_inv_freq(d_rot: int, base: float) -> NDArray: # d_rot must split into whole pairs; a base <= 1 would give a flat or # climbing ladder, and an infinite base a ladder of zeros. if isinstance(d_rot, bool) or int(d_rot) != d_rot or d_rot < 2 or d_rot % 2: raise ValueError(f"d_rot must be a positive even integer, got {d_rot!r}") base = float(base) if not (base > 1.0 and math.isfinite(base)): raise ValueError(f"base must be finite and > 1, got {base}") d_rot = int(d_rot) # One frequency per pair i = 0 .. d_rot/2 - 1; the exponent steps by 2/d_rot. i = np.arange(d_rot // 2, dtype=np.float64) return base ** (-2.0 * i / d_rot)i starts at 0, so the first rung is exactly , and the factor 2 in the exponent puts the last rung at , just above . The condition is written not (base > 1.0 and ...) rather than base <= 1.0 or ... so that a NaN base, for which every comparison is false, is rejected too.
The ALiBi slopes
Section titled “The ALiBi slopes”ALiBi builds its two ladders from geometric:
def alibi_slopes(n_heads: int) -> NDArray: if isinstance(n_heads, bool) or int(n_heads) != n_heads or n_heads < 1: raise ValueError(f"n_heads must be a positive integer, got {n_heads!r}") n = int(n_heads) p = 1 << (n.bit_length() - 1) # the largest power of two <= n (exact, no log2) start = 2.0 ** (-8.0 / p) slopes = geometric(start, start, p) # start^1, ..., start^p = 2^-8/p ... 2^-8 if p == n: return slopes # The extra n - p heads take every other slope of the 2p-head ladder, # starting from the first, so they fall between the existing ones. start2 = 2.0 ** (-8.0 / (2 * p)) extra = geometric(start2, start2, 2 * p)[0::2][: n - p] return np.concatenate([slopes, extra])For , the bit_length() of 6 (binary 110) is 3, so . slopes is ; the 8-head ladder is , [0::2] keeps , and [:2] keeps , matching the hand computation.
The full solution is series.py.
Why this design
Section titled “Why this design”Every function is in time and memory for the values it returns, and geometric_sum is , a handful of library calls regardless of . Summing the terms in a loop would be and, for in the millions (an EMA after a million steps), would also accumulate roundings.
The sum uses one formula for all . The alternative is to switch to the textbook form when is “large enough”, but that needs a threshold, and any threshold either leaves a band of cancellation or is unnecessary: the expm1/log1p form is accurate everywhere for , so there is nothing to switch.
Power-of-two detection is exact. math.log2(n) is exact for powers of two in CPython, but math.log(n, 2) and similar routes divide two rounded logarithms and can land just below an integer (math.log(1000, 10) is 2.9999999999999996), and floor then picks the wrong ladder. Bit length has no rounding at all.
Everything is float64. Hugging Face computes RoPE frequencies in float32; computing in float64 and comparing at float32 precision means the solution is at least as accurate as what it must reproduce, and later code can cast down.
One tradeoff is accepted deliberately. For near (for example with even ), cancels and the sum loses digits. No caller uses negative ratios near , so the contract leaves the case out rather than adding a branch nobody exercises.
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 geometric sum | unit | , , and the four terms | everyone agrees on what counts |
| the hand-worked RoPE ladder | unit | , gives | the exponent is |
| the hand-worked six-head ALiBi slopes | unit | the 6-head slopes computed above | the non-power-of-two rule |
| edge-case terms | unit | negative and unit ratios, and (empty) | term 0 is |
| sums against exact rationals | differential | 66 sums against exact Fraction arithmetic on the same inputs | any correct formula passes, any wrong count fails |
| sums near keep their digits | boundary | and : relative error below | the cancellation near |
| the EMA bias-correction identity | property | for up to | Adam’s bias correction |
| sums that overflow | boundary | for sums beyond float64, by the sign of the last term | no OverflowError escapes |
| bad term counts | boundary | , , True raise ValueError | counts are whole numbers |
| Hugging Face RoPE frequencies | golden | Hugging Face’s default RoPE for SmolLM2-135M, Llama 2, Llama 3, and a partial rotary size, to float32 precision | exactly what the Llama-family loader loads |
| the RoPE ladder’s shape | property | first rung 1, constant ratio , last rung above | the ladder’s shape for any and |
| bad RoPE arguments | boundary | odd or zero , bases or infinite raise ValueError | a flat or climbing ladder is a bug |
| ALiBi for powers of two | unit | 8 heads: ; 16 heads: ; 1 head: | the power-of-two rule |
| BLOOM’s ALiBi slopes | golden | BLOOM’s build_alibi_tensor for 20 head counts from 1 to 128 | twelve of them are not powers of two |
| bad head counts | boundary | 0, , heads raise ValueError | a model has whole heads |
The mistake with the most consequence is the textbook formula itself.
Warning: Using the closed form directly near makes Adam’s bias correction with correct to 7 digits instead of 16. The solution uses for every .
The RoPE ladder has two classic errors. Using the exponent instead of makes the frequencies fall only to , so long-range pairs turn far too fast and Hugging Face checkpoints load with the wrong positions; the solution writes base ** (-2.0 * i / d_rot). Starting the ladder at shifts every frequency one rung and loses the 1-radian pair; np.arange(d_rot // 2) starts at 0. For ALiBi, ignoring the non-power-of-two rule, or taking the odd entries of the second ladder instead of the even ones, gives 12-head and 40-head models slopes no published model uses; the solution builds the -head ladder and takes [0::2][: n - p].
The last two are off-by-one errors in the sequence itself. One term too many makes include and throws off every bias correction; np.arange(n) stops at , and the closed form uses in the numerator for exactly terms. Starting the sequence at makes geometric return and shifts the ALiBi slopes by one rung; the exponents start at , and ALiBi passes start as the first term explicitly.
Where this leads
Section titled “Where this leads”In this book, Series and the EMA builds the EMA’s weights as geometric(1 - beta, beta, t) and its bias correction as geometric_sum(1 - beta, beta, t), and learning-rate schedules include step-decay schedules that are geometric sequences of learning rates. In AI Engineering, RoPE calls rope_inv_freq(d_rot, rope_theta) to build its angles as positions * inv_freq, which feed the rotate_pairs of the previous section; Context extension takes ALiBi biases from alibi_slopes and bends the same ladder per frequency for YaRN and NTK scaling; and the positional encodings of the 2017 Transformer use a ladder of the same shape.
Further reading
Section titled “Further reading”- OpenStax, Precalculus 2e (free), chapter 11 on sequences and series.
- Press, Smith, and Lewis, “Train Short, Test Long: Attention with Linear Biases” (ALiBi, 2022), section 3.
- Su et al., “RoFormer” (2021), section 3.3.
- Hugging Face
ROPE_INIT_FUNCTIONSandcompute_default_rope_parametersintransformers/modeling_rope_utils.py: one function per scaling kind (linear,dynamic,yarn,llama3,longrope) that bends this ladder for longer contexts. - BLOOM’s
build_alibi_tensorintransformers/models/bloom/modeling_bloom.py: the slopes built once per model, with the biases fused into the attention kernel in BLOOM and MPT. - PyTorch
torch.optim.Adamintorch/optim/adam.py: the bias corrections1 - beta1 ** stepand1 - beta2 ** step, computed in float32, where the cancellation is worse. - C99
log1pandexpm1(man 3 expm1): the accurate small-argument functions every math library ships.
Key terms
Section titled “Key terms”- Geometric sequence: a sequence that multiplies by the same ratio at every step, .
- Geometric sum: the sum of the first terms, for and for .
- Exponential moving average: , whose weights are a geometric sequence summing to .
- Cancellation: the loss of significant digits when subtracting two nearly equal rounded numbers.
log1p/expm1: and , computed accurately for small arguments.- Inverse frequency: RoPE’s rotation speed for pair , in radians per position.
- ALiBi slope: the per-head factor by which ALiBi penalizes query-key distance.
Summary
Section titled “Summary”- A geometric sequence multiplies by the same ratio at every step: .
- Its first terms add up to , found by subtracting times the sum from the sum.
- Near that formula cancels and loses half its digits; rewriting it with and keeps them all, and Adam’s bias correction lives exactly there.
- RoPE’s inverse frequencies form a geometric ladder from one radian per token down to about , so pairs of dimensions see position at every scale from a few tokens to tens of thousands.
- ALiBi slopes are a geometric ladder of ; head counts that are not powers of two interleave a second ladder.
Review questions
Section titled “Review questions”- Why is the denominator computed as
r - 1.0with no special care, when the numerator neededexpm1andlog1p?Answer
Subtracting two floats that are within a factor of 2 of each other is exact (Sterbenz's lemma), so for $r$ near 1 the value $r - 1$ has no rounding error at all. The danger is only in subtracting a rounded quantity: $r^n$ is already rounded before $1 - r^n$ is formed, and the subtraction exposes that rounding. The denominator subtracts the exact input $r$. - Why does the
expm1branch apply only to ?Answer
It rewrites $r^n$ as $e^{n \ln r}$, and $\ln r$ is undefined for $r \le 0$ (math.log1p(r - 1)with $r - 1 \le -1$ raises). It is also unnecessary there: $1 - r \ge 1$, so the denominator is never small and dividing does not amplify the numerator's rounding. - What is the sum for , , and , and why does the solution not raise?
Answer
The true sum is about $10^{390}$, beyond float64's maximum of about $1.8 \times 10^{308}$, so the right float answer is $+\infty$.math.expm1(40 * math.log1p(1e10))raisesOverflowErrorrather than returning infinity; the helper catches it and returns the sign of the last term $r^{39}$, positive because $r > 0$. For $r = -10^{10}$ the last term $r^{39}$ is negative ($n - 1 = 39$ is odd), giving $-\infty$. - Why does
alibi_slopescallgeometric(start, start, p)rather thangeometric(1.0, start, p)?Answer
ALiBi's first slope is $2^{-8/p}$, not 1: the ladder is $\text{start}^{1}, \ldots, \text{start}^{p}$, ending at $2^{-8}$.geometric(1.0, start, p)would give $\text{start}^0, \ldots, \text{start}^{p-1}$, one rung too high everywhere, with a first head that penalises distance by a full unit per token. - What would break if
rope_inv_freqused the exponent ?Answer
The ladder would end at about $b^{-1/2}$ instead of $1/b$: for $b = 10^5$ the slowest pair would repeat every $2\pi \cdot 316 \approx 2000$ positions instead of about $6 \times 10^5$, so distant tokens alias, and every pretrained checkpoint, whose attention weights were learned with $-2i/d$, would see rotated queries and keys it was never trained on. - Write as a fraction using the infinite geometric sum.
Answer
It is $27/100 + 27/100^2 + \cdots$, a geometric series with $a = 27/100$ and $r = 1/100$, so its sum is $(27/100)/(1 - 1/100) = 27/99 = 3/11$.