Skip to content

Long contexts: Transformer-XL, Longformer, BigBird and Reformer

Full attention compares every token with every other, so cost grows with the square of the length. Four designs cut that cost with memory, windows, global and random links, or hashing. Read their attention masks and know what each gives up.

Advanced ~14 min9 steps

What runs in CodeSplash

You will be able to

  • Explain why full self-attention costs grow with the square of the input length
  • Read sliding-window, global-token and random-link attention masks
  • Describe segment recurrence and hashing-based attention
  • Say how CodeSplash handles long texts today

Read first

01

The square problem

Read

Self-attentionSelf-attentionEach token builds its next value as a weighted mix of all tokens, with weights from how well their keys match its query. scores every query against every key. A text of n tokens needs an n × n score matrix in every head of every layer. Double the length and the work and memory for scores quadruple.

Each design below keeps fewer entries of that matrix. An attention maskAttention maskBlocks some query–key pairs before the softmax, such as future tokens (causal) or padding, so they get zero weight. of ones and zeros says which query may look at which key, so a design is easiest to understand from its mask. Full causal attention is the lower triangle. The others are sparse attentionSparse attentionAttention that scores only some query–key pairs (windows, global tokens, random links or hash buckets), so cost grows slower than n². patterns, or ways to reach further without a bigger matrix.

Every row of weights covers every key: the source of the quadratic cost.

DExplorable · Attention: scores, masks and heads

Where does each word look, and what do the scaling and the masks change?

With this mask, how much of each word's attention lands on <pad>?

How sure?
6
2

How many of the positions are <pad>.

Width d

Heads

Mask

Without masks or positions the output rows shuffle the same way.

.51.22.16.11.00.00.27.55.07.10.00.00.02.10.59.28.00.00.26.71.02.01.00.00.09.09.69.13.00.00.42.54.03.01.00.00thecatsaton<pad><pad>thecatsaton<pad><pad>
  • Little weight
  • Most weight
  • Masked: score set to −∞

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

02

Windows and global tokens: Longformer

Read

Longformer lets each token attend to neighbors within a radius, and marks a few tokens, such as the classification token, as global: they attend to everyone and everyone attends to them.

In the reference program, six tokens with radius one and token 0 global give a band along the diagonal plus a full first row and column. Cost grows with n times the window, not n². Information between far tokens flows through the global tokens or across layers.

03

Random links too: BigBird

Read

BigBird adds a few random connections to the window and global pattern. In the reference program, links such as token 1 to token 4 and token 2 to token 5 appear outside the band.

Random links act like shortcuts in a network: with a handful per token, any two tokens connect in a few hops. The BigBird authors proved that this pattern keeps the expressive power of full attention, in theory, with linear cost.

04

Memory across segments: Transformer-XL

Read

Transformer-XL splits a long text into segments and processes them in order. While reading a segment, attention can also see the cached hidden states of the previous segment, a form of segment recurrenceSegment recurrenceTransformer-XL's trick: a segment also attends to the cached states of the previous segment, without training through them.. No gradient flows into the cache, so training cost stays per segment.

In the reference program the memory keeps the last two states of the previous segment, so the current segment's two tokens attend over four rows. Because cached states come from different absolute positions, Transformer-XL uses relative position encodings.

Reference · LNG045 · Explained hereTransformer-XLExtends language-model context through segment-level recurrence, reusing hidden states from previous segments. Relative positional representations permit cached context to remain interpretable as segment boundaries move.

Relative positions are what let attention reach past its training length.

DExplorable · Positional encodings: sinusoidal, RoPE, ALiBi

How does attention learn where a word is, and what does each scheme remember about distance?

Shift the query and every key by the same amount. Do the scores change with this scheme?

How sure?

Scheme

16
32

Base

Sets the slowest wavelength: larger bases tell far positions apart.

20
7

Score both positions s places later: does anything change?

3

Each head has its own slope.

query
  • score(20, n)
  • both shifted by 7

cos(p·θᵢ) for each rotation pair: fast pairs on the left

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

05

Hash similar vectors together: Reformer

Read

Reformer only computes attention between tokens likely to have high scores. Locality-sensitive hashing puts vectors that point in similar directions into the same bucket, and attention runs within buckets.

The simplest hash is the sign of a random projection. In the reference program four vectors land in buckets 1, 1, 0 and 0: the two vectors pointing one way share a bucket, the two pointing away share the other. Similar keys that hash apart are missed, so Reformer hashes several times.

06

Long texts in CodeSplash

Predict

Predict first

You embed 3,000-word reports with MiniLM in Semantic search. What does the encoder read?

It reads the whole text, however longIt reads the first part only, up to the encoder's limitIt refuses long texts
Reveal

The first part only: MiniLM reads up to 256 tokens and cuts the rest. For long documents, split them into passages first (one row per passage), as Ask documents does, and search the passages.

07

Where it stands in CodeSplash

Read
EntryIn CodeSplash
Transformer-XL, Longformer, BigBird, Reformer (LNG045–LNG048)Explained here; split long documents into passages instead
08

Check: long contexts

Checkpoint

Check yourself

In Transformer-XL, what can a token in the current segment attend to?

Show the answer

Answer: b

The cache extends the context backward without training through it, which is why relative positions are needed.

Check yourself

Why does Transformer-XL stop gradients from flowing into the cached previous segment?

Show the answer

Answer: a

Backpropagating through every earlier segment would rebuild the cost the cache was meant to avoid.

Check yourself

What does a global token do in Longformer?

Show the answer

Answer: b

A few global tokens (like the classification token) connect distant parts of the text while everything else stays local.

Check yourself

How does Longformer's attention cost grow with input length n, for a fixed window?

Show the answer

Answer: b

Each token compares with a fixed number of neighbors plus a few global tokens, so total work is linear in n.

Check yourself

What do BigBird's random links add to the window-and-global pattern?

Show the answer

Answer: b

A few random edges per token shrink the number of hops between distant tokens, like shortcuts in a network.

Check yourself

A BigBird mask has ones on a diagonal band, a full first row and column, and a few scattered ones. Which part are the scattered ones?

Show the answer

Answer: c

The band is the window, the full row and column belong to the global token, and the scattered entries are random links.

Check yourself

Why does Reformer's hashing find the important attention pairs?

Show the answer

Answer: b

Locality-sensitive hashing groups likely high-scoring pairs; attention within buckets skips most low-scoring ones.

Check yourself

Why does Reformer hash several times with different random projections?

Show the answer

Answer: b

One random cut can split near neighbors. Repeating with fresh projections and combining the buckets reduces those misses.

09

Recap

Recap
  • Full attention costs grow with n²; each design keeps fewer score entries.
  • Longformer: windows plus global tokens. BigBird: adds random links. Reformer: hashes similar vectors into buckets.
  • Transformer-XL: caches the previous segment's states, with relative positions.
  • In CodeSplash, split long documents into passages before searching or embedding.

Concepts in this lesson