rumblr Work in progressWIP

● The AI Primer · Lesson 7 · Part 1: how a language model works

Positional information

how a transformer knows word order

This lesson covers Why order must be added, sinusoids and RoPE

Members · open during launch 32 min10 figures and diagrams6 interactive

What this is

How does a language model know word order?

Positional information is what an AI language model adds to each word to say where in the sentence it sits, because attention on its own treats the input as an unordered bag. Shuffle "dog bites man" into "man bites dog" and attention with no positions returns the same vectors, only reordered. There are three ways to add position back: a fixed code for each position, a learned table, or a rotation by an angle that grows with position (RoPE), which most current language models use. The scheme a language model uses decides how long a prompt it can read.

Why it matters: You need it the day length matters: a spec sheet claims 128K tokens and you wonder how far to trust it, or quality is fine on short prompts and drops sharply past some longer one, with nothing in the logs.

At a glance

Key takeaways

  1. Attention with no position information is blind to word order: shuffle the words and its outputs are shuffled the same way, so "dog bites man" pools to the same vector as "man bites dog".
  2. The original transformer adds a fixed code of sines and cosines to each word. GPT-2 and BERT learn a table of position vectors instead, and it has no row past its last position.
  3. Most current language models use RoPE, which turns each query and key by an angle that grows with position, so a score depends only on how far apart two words are. Because position lives in angles, a RoPE model can be stretched to longer prompts after training.

How it works, from scratch

Attention scores each pair of words by comparing their vectors, and the comparison comes out the same wherever the two words sit. So the order of the words has to be put in from outside: added to each word's vector, or built into the way attention compares them.

Opening

The problem: attention reads a bag, not a sentence

Three words, each a vector of two numbers, go through one attention layer with no position information. Swap two tiles, or step through all six orders, and watch where each word's output lands.

Think of the words as Scrabble tiles poured into a bag. The bag for "dog bites man" and the bag for "man bites dog" hold the same tiles, and anyone handed only the bag cannot tell a news story from a routine dog attack. Attention with no position information is handed only the bag.

Give each word an embedding of two numbers: dog = (1, 0), bites = (0, 1), man = (1, 1). The simplest way to turn a sentence into one vector is to average its words:

sentence sum of vectors average
dog bites man (1,0)+(0,1)+(1,1) = (2, 2) (0.67, 0.67)
man bites dog (1,1)+(0,1)+(1,0) = (2, 2) (0.67, 0.67)

The averages match because addition ignores order. Attention is an average too, a weighted one, and its weights come from dot products between words, which ignore order in the same way.

Figure 1 · Diagram

Reading it: follow both sentences from left to right. Embedding looks up each word on its own, so both sentences give the same three vectors, and attention receives the same set. Its outputs are the same vectors in a different order, so pooled into one sentence vector the two sentences are identical.

A permutation is a reshuffle of an ordered list. Written as a matrix (a grid of numbers), a permutation matrix is all zeros except one 1 in each row, and multiplying by it reorders rows. Attention without positions is permutation-equivariant: shuffle its input and its output is shuffled the same way.

The formula and its symbols

Symbols

Symbol Meaning here In the example
the sentence's token vectors, one row per word rows dog (1,0), bites (0,1), man (1,1): a 3 × 2 grid
a permutation matrix: reorders the rows of whatever it multiplies swap rows 1 and 3
the same rows in the new order man (1,1), bites (0,1), dog (1,0)
one attention layer with no position information (here with = identity, so q = k = v = the word vector) 3 × 2 in, 3 × 2 out
both sides are exactly the same grid of numbers

In words: "running attention on the shuffled sentence gives the same answer as running it on the original sentence and shuffling afterwards."

With the numbers: in "dog bites man", dog's query (1,0) scores the three keys (1,0), (0,1), (1,1) as 1, 0, 1; divided by √2 that is 0.707, 0, 0.707. Softmax gives weights 0.401, 0.198, 0.401, so dog's output is 0.401·(1,0) + 0.198·(0,1) + 0.401·(1,1) = (0.802, 0.599). In "man bites dog" dog sits in row 3, but it scores the same three keys in a different order, gets the same weights, and outputs the same (0.802, 0.599).

In Python
import math
# q = k = v = the word vector, no positions
def Attn(X):
    out = []
    for q in X:
        scores = [sum(a * b for a, b in zip(q, k)) / math.sqrt(2) for k in X]
        exps = [math.exp(s) for s in scores]
        weights = [e / sum(exps) for e in exps]
        out.append(tuple(round(sum(w * v[c] for w, v in zip(weights, X)), 3) for c in range(2)))
    return out
# dog, bites, man
X = [(1, 0), (0, 1), (1, 1)]
# P swaps rows 1 and 3: man, bites, dog
PX = [X[2], X[1], X[0]]
Attn(X)  # → [(0.802, 0.599), (0.599, 0.802), (0.752, 0.752)]
# the same rows, shuffled the same way
Attn(PX)  # → [(0.752, 0.752), (0.599, 0.802), (0.802, 0.599)]

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

A larger layer, with 16 random numbers per word and random, untrained weights, behaves the same way:

Figure 2 · Chart

no positions sinusoidal RoPE causal mask only 0.5 0.6 0.7 0.8 0.9 1.0 cosine similarity of pooled outputs 'dog bites man' vs 'man bites dog' 1.000 0.995 0.997 0.524

Without positions the two sentences are identical (similarity 1.0); sinusoidal codes and RoPE pull it just below 1, and a causal mask alone drops it to 0.52

Reading it: each bar is the cosine similarity of the two sentences' pooled outputs, where 1.0 means identical. With no positions the bar reaches exactly 1, so the layer cannot tell the sentences apart. Sinusoidal codes and RoPE pull it below 1. So does a causal mask, which lets each word see only the words before it, with no positions added at all.

In code: order_similarity computes the bars, with word_vector giving each word its random numbers. View source

Order carries much of what a sentence means: who did what to whom, what a "not" applies to, what a line of code does. So position has to be injected, and the oldest way is to add a code for each position to the word's vector.

Chapter 1

Sinusoidal codes (the original 2017 transformer)

Each position's code is read off a clock with many hands, one fast and each of the others slower than the last. Pick two positions and watch the hands.

A clock's second hand moves fast and tells nearby moments apart; its hour hand moves slowly and tells morning from evening. Read together, the hands give every moment of the day its own reading. Sinusoidal codes give each position a set of hands like these, each turning at its own speed, and add the reading to the word's embedding.

Each hand is stored as two numbers. Picture the tip of a hand on a circle of radius 1. The angle it has turned is measured in radians (a full turn is 2π ≈ 6.28 radians). The cosine of the angle is how far right the tip is, and the sine is how far up; both lie between −1 and +1, and both repeat every full turn. With 4 numbers per code there are two hands. The fast one turns 1 radian per position, the slow one 1/100 of a radian:

position sin(pos·1) cos(pos·1) sin(pos/100) cos(pos/100)
0 0.000 1.000 0.000 1.000
1 0.841 0.540 0.010 1.000
2 0.909 −0.416 0.020 1.000

From position 1 to position 2 the fast pair changes a lot and the slow pair hardly at all. The slow pair is there to separate positions hundreds apart.

Figure 3 · Diagram

Reading it: two paths meet at the plus sign. The top path says what the word is, the bottom path says where it is, and their sum is one vector carrying both. Everything after it sees only that sum, so position becomes part of what attention compares.

In general, a code of d numbers has d/2 hands, and each turns more slowly than the one before:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the token's position, counting from 0 1
how many numbers each position code has 4
which (sin, cos) pair, counting from 0 up to 0 and 1
, the two columns that pair fills: even column gets sine, odd gets cosine pair 1 fills columns 2 and 3
pair 's speed in radians per position (its frequency) ,
10,000 raised to a fraction; makes each pair slower than the last
, how far up / right a point is after turning by that many radians
the number in row , column of the code table

In words: "for position pos, each pair of columns stores where a hand turning at that pair's speed points after pos steps: sine in the first column, cosine in the second."

With the numbers: d = 4, pos = 1. Pair 0 turns 1 radian: sin 1 = 0.841, cos 1 = 0.540. Pair 1 turns 1/100 radian: sin 0.01 = 0.010, cos 0.01 = 1.000. So position 1's code is (0.841, 0.540, 0.010, 1.000), the second row of the table above.

In Python
import math
d, pos = 4, 1
PE = []
# one (sin, cos) pair per i
for i in range(d // 2):
    # ω_i: pair i's speed
    omega_i = 1 / 10000 ** (2 * i / d)
    # columns 2i and 2i+1
    PE += [math.sin(pos * omega_i), math.cos(pos * omega_i)]
[f"{v:.3f}" for v in PE]  # → ['0.841', '0.540', '0.010', '1.000']

Moving k positions on turns every hand by the same angle, k·ω_i, wherever it starts. So the dot product of two position codes depends only on how far apart the positions are.

In code: sinusoidal_encoding(n, d) builds the whole table, one row per position.

Figure 4 · Chart

0 10 20 30 40 50 60 dimension (left: fast hands, right: slow hands) 0 25 50 75 100 125 150 175 position Sinusoidal position codes −1.00 −0.75 −0.50 −0.25 0.00 0.25 0.50 0.75 1.00 value

Left columns flip colour every few positions and right columns change slowly, so every row is a unique fingerprint and neighbours look alike

Reading it: each row is a position (0 at the top), each column one of 64 numbers, and colour is the value from −1 to +1. The left columns flip colour every few rows: the fast hands. The right columns change slowly over hundreds of rows: the slow hands. No two rows are identical, so every position has its own code, and neighbouring rows look alike, so nearby positions get similar codes.

The codes need no training and exist for every position. Because their similarity depends only on distance, a model can learn "look 3 tokens back" once and use it everywhere. The cost is that position is mixed into the word's vector itself.

Chapter 2

Learned absolute positions (GPT-2, BERT)

GPT-2 and BERT look each position up in a learned table, one row per seat. Drag the prompt past the last seat and choose what happens to the words with no seat.

GPT-2 and BERT keep the addition but learn the position vectors instead of computing them. The model holds a table with one row per position, like numbered seats in a theatre, and the number of seats is fixed when the model is built. GPT-2's table has 1,024 rows of 768 numbers: 786,432 parameters, learned like any other weight. Position 5 reads row 5. Position 1,024, the 1,025th token, has no row.

Figure 5 · Diagram

Reading it: this is the sinusoidal picture with the formula on the bottom path replaced by a second learned table. Then follow the dotted arrow: the table ends at max_len, so a position past it has no row to look up.

Each word's input is a sum of two rows:

The formula and its symbols

Symbols

Symbol Meaning here In the example (GPT-2)
the token's row of the token table (what the word means) 768 numbers
row of the position table, learned during training (where it is) 768 numbers; from 0 to 1,023
add the two lists number by number
the vector the first transformer block receives 768 numbers

In words: "the input vector is the word's meaning plus its seat number's learned vector."

With the numbers: with 2 dimensions, if = (0.5, −0.2) and = (0.1, 0.3), then = (0.6, 0.1). does not exist.

In Python
E_dog = [0.5, -0.2]
# a position table with rows 0 to 3
P = [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.1, 0.3]]
# x_3 = E_dog + P_3
[round(e + p, 2) for e, p in zip(E_dog, P[3])]  # → [0.6, 0.1]
# no row 1024: it cannot be encoded
len(P) > 1024  # → False

In code: primer.ml.transformer.TinyGPT uses a table like this one. View source

A learned table is simple and works well up to its last row. Past it there is nothing to look up, and the table cannot grow after training.

Chapter 3

Rotary position embeddings, RoPE (Llama, Mistral, Qwen)

RoPE turns each word's query and key by an angle that grows with the word's position. Move the two positions and watch which moves leave the score alone.

Both schemes so far add a code to the word's vector, one code per position. RoPE adds nothing to the word. It turns the word's query and key, the two vectors attention compares to score a pair of words, like clock hands, by an angle that grows with the word's position. Two people pointing at a clock face, one at 1 o'clock and one at 4, hold their arms 90° apart. Move them on to 8 and 11 o'clock and the angle is still 90°. In the same way, when a turned query meets a turned key, only the angle between them affects the score, and that angle depends on how far apart the two words are, not on where they sit.

Take a query and a key of two numbers each, q = k = (1, 0), so there is one pair, turning 1 radian per position. Put the query at position 3 and the key at position 7:

  • q turns by 3 rad: (cos 3, sin 3) = (−0.990, 0.141)
  • k turns by 7 rad: (cos 7, sin 7) = (0.754, 0.657)
  • score = −0.990·0.754 + 0.141·0.657 = −0.654 = cos(4)

Move both 100 positions on, to 103 and 107, and the score is still cos(107 − 103) = cos 4 = −0.654. Only the distance between them counts.

Figure 6 · Diagram

Reading it: this is ordinary attention with one extra step on the query and key branches. After projection, each pair of numbers in q and k is turned by an angle that grows with the word's position, fast for the first pairs and slow for the last. The value branch is not turned, so what gets blended is plain content.

A rotation turns a point around the centre by an angle without changing its distance from the centre. For one pair it is a 2 × 2 grid times a column of two numbers, a matrix-vector multiply: each output number is one row of the grid multiplied entry by entry with the input and added up.

The formula and its symbols

Symbols

Symbol Meaning here In the example
pair of a query or key vector, before rotating (1, 0)
the same pair after rotating (−0.990, 0.141)
the token's position 3
which pair, from 0 to 0 (the only pair when d = 2)
pair 's turning speed in radians per position; means
the total angle turned 3 radians
the 2 × 2 grid the rotation: row 1 gives the new first number, row 2 the new second

In words: "new first number = cos(angle) × old first − sin(angle) × old second; new second number = sin(angle) × old first + cos(angle) × old second, where the angle is position times the pair's speed."

With the numbers: x = (1, 0) at m = 3, θ = 1: x′ = (cos 3 · 1 − sin 3 · 0, sin 3 · 1 + cos 3 · 0) = (−0.990, 0.141).

In Python
import math
def rotate(x, m, theta_i=1.0):
    # the angle m θ_i
    a = m * theta_i
    # row 1 of the grid
    return (math.cos(a) * x[0] - math.sin(a) * x[1],
            # row 2 of the grid
            math.sin(a) * x[0] + math.cos(a) * x[1])
[f"{v:.3f}" for v in rotate((1, 0), m=3)]  # → ['-0.990', '0.141']
d, i = 2, 0
# θ_0 = 10000^(-2i/d)
10000 ** (-2 * i / d)  # → 1.0

The score is a dot product (multiply matching numbers and add them up; it is large when the vectors point the same way), and turning both vectors by the same angle does not change it. So turning q by angle a and k by angle b gives the same score as leaving q alone and turning k by b − a:

The formula and its symbols

Symbols

Symbol Meaning here In the example
, a query and a key vector, before rotating (1, 0) and (1, 0)
, the query's and the key's positions 3 and 7
"rotate every pair by its speed times " turn by 3 radians
the rotation for the distance only turn by 4 radians
the dot product of and (same as )

In words: "the score between a query at m and a key at n equals the score you'd get by leaving the query alone and turning the key by the gap n − m."

With the numbers: left side (−0.990, 0.141) · (0.754, 0.657) = −0.654; right side (1, 0) · (cos 4, sin 4) = cos 4 = −0.654. Same number, and the same again at positions 103 and 107.

In Python
import math
# turn a pair by an angle (θ = 1, so the angle is the position)
def R(angle, x):
    return (math.cos(angle) * x[0] - math.sin(angle) * x[1],
            math.sin(angle) * x[0] + math.cos(angle) * x[1])
def dot(a, b): return sum(a_i * b_i for a_i, b_i in zip(a, b))
q = k = (1, 0)
# ⟨R_m q, R_n k⟩ with m = 3, n = 7
round(dot(R(3, q), R(7, k)), 3)  # → -0.654
# ⟨q, R_(n-m) k⟩: only the distance
round(dot(q, R(7 - 3, k)), 3)  # → -0.654
# 100 positions later, the same score
round(dot(R(103, q), R(107, k)), 3)  # → -0.654

The same holds for vectors of 64 numbers, 32 pairs each turning at its own speed θ_i, starting anywhere in the text:

Figure 7 · Chart

0 10 20 30 40 50 60 distance between key and query (n − m) −12 −10 −8 −6 −4 −2 attention score q·k With RoPE the score depends only on distance query at position 0 query at position 100 query at position 1000

The score curves for starting positions 0, 100 and 1,000 lie exactly on top of each other: only the distance matters

Reading it: the distance n − m between query and key runs along the bottom. Each line uses the same q and k but starts the pair at a different position: 0, 100 or 1,000. The lines lie on top of each other, so the score depends only on distance.

The pairs turn at speeds that fall from the first pair to the last, as the sinusoidal hands do:

Figure 8 · Chart

0 25 50 75 100 125 150 175 200 position 0 1 2 3 4 5 6 rotation angle (mod 2π) RoPE: fast hands for local order, slow hands for long range pair 0 (θ=1) pair 4 (θ=0.32) pair 12 (θ=0.032) pair 31 (θ=0.00013)

Pair 0 wraps a full turn about every 6 tokens while the last pairs barely turn across the whole range

Reading it: position runs along the bottom, and each line is one pair, showing how far it has turned, wrapped at one full turn (2π). Pair 0 turns fastest and wraps about every 6 tokens, so it tells neighbours apart. Pair 31, the last, barely turns across the whole range and carries long-range position. These are the sinusoidal clock's hands, now inside attention.

In code: rope_frequencies gives each pair's speed θ_i, and apply_rope turns a vector or a whole sequence. View source

Language works in relative distances ("the word two back"), and RoPE builds them into every score. Turning a vector never changes its length, so the word's content is left as it was. And because position now lives in angles, the angles can be rescaled after training.

Chapter 4

Extending context after training

A RoPE model has only seen the angles produced by positions up to its training length. Past that length its slow pairs turn to angles it never met, and attention degrades. A ruler marked from 0 to 4,000 cannot measure something 32,000 long either. You can shrink the object 8× so it fits the ruler (position interpolation), or redraw the long-distance marks and keep the fine millimetre marks (NTK-aware scaling).

Say a model trained on 4,096 tokens has to read 32,768. Interpolation multiplies every position by 4096/32768 = 1/8, so position 32,000 is treated as 4,000: an angle the model has seen. Neighbours are now 1/8 of a position apart, which a short fine-tune teaches it to resolve.

Figure 9 · Diagram

Reading it: both paths bring the angles back inside the range seen in training. Interpolation slows every hand by the same factor, which also blurs the fast hands that carry local word order. NTK-aware scaling slows the slow hands and leaves the fastest one as it was, so local order stays sharp. Either is usually followed by a short fine-tune on long text.

Position interpolation is one multiplication:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the real position in the long input 32,000
the longest context seen in training 4,096
the context we now want 32,768
the position RoPE is actually given 4,000

In words: "shrink every position by the ratio of old length to new length."

With the numbers: 32,000 × 4,096 / 32,768 = 32,000 / 8 = 4,000.

In Python
pos, L_train, L_new = 32_000, 4_096, 32_768
# pos' = pos · L_train / L_new
pos * L_train / L_new  # → 4000.0

NTK-aware scaling leaves the positions alone and raises the base, the 10,000 in θ_i, instead:

The formula and its symbols

Symbols

Symbol Meaning here In the example
the 10,000 inside 10,000
how many times longer the new context is 8
the head width 128
raised to a power just above 1
the new, larger base ≈ 82,685

In words: "multiply the base by slightly more than the stretch factor."

With the numbers: the fastest pair keeps radian per position. The slowest pair goes from to : exactly 8× slower.

In Python
base, s, d = 10_000, 8, 128
# s^(d/(d-2)): just above 8
round(s ** (d / (d - 2)), 2)  # → 8.27
# base' = base · s^(d/(d-2))
base_new = base * s ** (d / (d - 2))
round(base_new)  # → 82685
# θ_i for the last pair, 2i = 126
slowest = lambda b: b ** (-126 / 128)
f"{slowest(base):.2e}", f"{slowest(base_new):.2e}"  # → ('1.15e-04', '1.44e-05')
# exactly 8× slower
round(slowest(base) / slowest(base_new), 6)  # → 8.0

In code: interpolate_positions and ntk_scaled_base. View source

YaRN refines NTK-aware scaling by treating each band of frequencies differently, and many long-context models use it. ALiBi takes another route: it adds no position vectors at all and subtracts a penalty proportional to distance from each attention score.

Figure 10 · Chart

0 5000 10000 15000 20000 25000 30000 position 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 angle of the slowest RoPE pair (rad) Keeping long contexts inside the trained range angles seen in training raw positions (extended) position interpolation NTK-aware base

Raw positions leave the trained angle band right after 4k and reach 8 times its top by 32k; interpolation and NTK scaling stay inside it

Reading it: position up to 32k runs along the bottom, and the angle of the slowest RoPE pair up the side. The shaded band is the angles the model saw in training, at positions up to 4k. The unscaled line leaves the band right after 4k. The interpolated and NTK-scaled lines stay inside it all the way to 32k.

This is how a model trained on a few thousand tokens is stretched to 100k or more without pretraining it again from scratch.

The two ways of stretching treat the slowest pair and the fastest pair differently, and that difference is the choice between them. Pick a prompt length and a method, then compare the slowest pair's hand with two neighbouring words on the fastest pair.

Chapter 5

The causal mask leaks some order

Each scheme so far puts position in on purpose. A decoder, the kind of model that writes text one word at a time, also gets some order without one. Its causal mask lets each word see only itself and the words before it, so the word at position i sees i + 1 words. Even with no position encoding at all ("NoPE"), the model can partly infer where each word sits from how many words it sees. In bidirectional attention, where every word sees every other (as in BERT), there is no such signal, and attention is blind to order.

In code: encode_sentence with causal=True applies primer.ml.attention.causal_mask and gives the bar chart's "causal mask only" bar. View source

Run the same three tiles through a decoder's mask and watch whether dog still lands in the same place in both sentences.

Test yourself

6 questions

Answer each one out loud or on paper before you open it.

Question 1Why does a transformer need positional information at all?Think it through, then reveal

Attention compares tokens by content only, so it's permutation-equivariant: shuffling the input just shuffles the output. Without positions, word order is invisible.

Question 2How does RoPE encode position, and what property makes it attractive?Think it through, then reveal

It rotates each pair of dimensions in q and k by an angle proportional to position. The q·k score then depends only on the relative distance, and rotation preserves vector length.

Question 3Compute a RoPE score by hand: 2 dimensions, θ = 1, q = k = (1, 0), query at 3, key at 7.Think it through, then reveal

cos(7 − 3) = cos 4 ≈ −0.654, and the same at positions 103 and 107.

Question 4Why do sinusoidal codes use many frequencies?Think it through, then reveal

Fast frequencies distinguish neighbours; slow ones distinguish distant positions. Together every position gets a unique, smoothly varying code, and a shift by k is the same rotation everywhere.

Question 5What goes wrong beyond the trained context length, and how do you fix it?Think it through, then reveal

The model meets position angles or indices it never saw, and attention degrades. Position interpolation, NTK-aware scaling or YaRN rescale positions or frequencies into the trained range, usually followed by a short fine-tune.

Question 6Learned absolute position embeddings: pro and con?Think it through, then reveal

They are simple and effective within the trained length, but they cannot represent any position beyond the table size.

Primary sources

The papers behind this lesson

Vaswani et al. (2017), Attention Is All You Need.

Introduced the transformer and, in section 3.5, the sinusoidal position codes built here.

Read on rumblr →The paper
Su et al. (2021), RoFormer: Enhanced Transformer with Rotary Position Embedding.

Introduced RoPE: rotate queries and keys so attention scores depend only on relative distance.

Read on rumblr →The paper
Chen et al. (2023), Extending Context Window of Large Language Models via Positional Interpolation.

Showed that scaling positions down plus a short fine-tune extends RoPE models to much longer contexts.

The paper
Peng et al. (2023), YaRN.

Refined RoPE context extension by treating fast and slow frequencies differently.

The paper
Press et al. (2021), ALiBi.

Replaced position vectors with a distance penalty on attention scores that extrapolates to longer inputs.

The paper

Researcher's shelf

Further reading

  • Vaswani et al., Attention Is All You Need (sinusoidal codes, section 3.5): https://arxiv.org/abs/1706.03762
  • Su et al., RoFormer: Enhanced Transformer with Rotary Position Embedding (2021): https://arxiv.org/abs/2104.09864
  • EleutherAI, Rotary Embeddings: A Relative Revolution: https://blog.eleuther.ai/rotary-embeddings/
  • Chen et al., Extending Context Window of Large Language Models via Positional Interpolation (2023): https://arxiv.org/abs/2306.15595
  • Peng et al., YaRN: Efficient Context Window Extension of Large Language Models (2023): https://arxiv.org/abs/2309.00071
  • Press et al., Train Short, Test Long: Attention with Linear Biases (ALiBi) (2021): https://arxiv.org/abs/2108.12409
  • Kazemnejad et al., The Impact of Positional Encoding on Length Generalization in Transformers (NoPE, 2023): https://arxiv.org/abs/2305.19466

About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.