Foundations to Frontier
Tests
E. Deep Learning › E12 Transformer Architectures

Transformer-XL

Transformer-XL (Dai and colleagues, ACL 2019) lets a Transformer language model use context beyond its training segment. Hidden states from the previous segment are cached and reused as extra keys and values, without gradient: segment-level recurrence. To make cached states position-consistent it uses relative positional encodings. It learned dependencies 450% longer than a vanilla Transformer, evaluated up to 1,800 times faster, and was the first model below 1.0 bit per character on enwik8. This page covers the recurrence, relative positions, reach and cost. In the exercises you implement the cache update and reach formulas, then train a one-layer model on 8-token segments to recall the token 12 steps back. With no memory it is at chance (0.117), with one cached segment it reaches its 0.56 ceiling (0.547), and with two segments it solves the task on 4 of 5 seeds.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Remembering the previous page

A standard Transformer reads text in fixed chunks and forgets each chunk when it moves to the next. Transformer-XL keeps a memory of the previous chunk: when reading the new chunk, each word can also look back at the stored states of the last one. Information can then flow across chunk boundaries, like remembering the previous page while reading the next. The demo shows how far attention can reach under different patterns.

Transformer lab
Computed pairs: 136 of 256 for 16 tokens. Sparse patterns grow linearly with length instead of quadratically.
Why engineers care

Long logs, manuals and telemetry streams exceed any fixed window. Cached memory lets models use long history at manageable cost, an idea behind the KV caches used in every modern language model.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Transformer-XL reuses…
  2. 2. Gradients flow into the memory?
  3. 3. It needs positional encodings that are…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Segment recurrence:
    • for segment τ, the keys and values at each layer come from the previous segment’s cached states (with stop-gradient, SG) concatenated with the current segment’s states, while queries come only from the current segment;
    • SG means stop-gradient;
    • the cache keeps the last M states.
  • Reach:
    • each layer can look back one memory length, so N layers reach N × M tokens;
    • 16 layers with M = 512 reach 8192;
    • in one layer with segment length S, position i sees M + i tokens back.
    • With S = 8 and a lag of 12: M = 8 reaches half the positions and M = 16 all of them.
    • If a fraction r of positions can see the target, the best accuracy is r + (1 − r)/V: 0.5625 for r = 0.5 and V = 8.
  • Relative positions:
    • absolute positions would collide: position 0 of each segment would get the same embedding;
    • Transformer-XL scores with content–content, content–position and global bias terms over relative distances;
    • the exercises use RoPE, which has the same relative property.
  • Evaluation cost: a vanilla model must re-encode a full window for every new token (L·S token-steps). Transformer-XL reuses the cache (about L), a speedup of about S, which the paper measured as up to 1,800 times.
  • Cache memory: layers × M × d per sequence. For 18 layers, M = 384 and d = 1024 in 32-bit floats, that is 28.3 MB.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Reach of 16 layers with memory 512:
  2. 2. Ceiling with half the positions reachable, V = 8:
  3. 3. Why not absolute positions?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Transformer-XL in code

Exercise 1.

  • The cache update kept the most recent M states.
  • Reach formulas gave 8192 and 3072.
  • One and two segments of memory made 50% and 100% of positions able to see 12 steps back.

Practice.

  • Keep a per-layer cache list; after each segment, detach the new hidden states and truncate to M.
  • At inference, M can exceed the training memory length.
  • The same caching idea is the KV cache in autoregressive decoding (E12-2). Transformer-XL’s difference is caching during training, across segments.
  • Successors: Compressive Transformer (compresses old memories), Memorizing Transformer (retrieval over a large cache), recurrent memory Transformer.
mems = [None] * n_layers
for seg in segments(stream, S):
    h = embed(seg)
    for l, layer in enumerate(layers):
        h_new = layer(h, memory=mems[l])                   # keys/values over [mem; h]
        mems[l] = torch.cat([mems[l], h], 1)[:, -M:].detach() if mems[l] is not None else h[:, -M:].detach()
        h = h_new
🐍 Exercise 1: recurrence bookkeeping
Implement the memory update, maximum dependency length and reachable share.
📝 Quick check (Level 2)
0/3 answered
  1. 1. After each segment the cache is…
  2. 2. At inference, memory length…
  3. 3. A successor that compresses old memories:

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why recurrence across segments.

  • A vanilla Transformer trained on fixed segments has context fragmentation: tokens at the start of a segment have almost no context, and nothing crosses segment boundaries.
  • Caching the previous segment’s states gives every token at least M tokens of context, with information propagating further through layers.
  • Gradients stop at the cache, as in truncated BPTT (E11-2). The model learns to use cached states but not to write information for later segments.

Why relative positions.

  • Cached states were computed when their tokens had positions 0 … S − 1. In the new segment the same indices denote different tokens.
  • Encoding only relative distances in the attention scores makes the computation consistent whatever segment a key came from.
  • It also generalises to longer memories at test time.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Context fragmentation means…
  2. 2. Stopping gradients at the cache resembles…
  3. 3. Relative positions make cached states…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Does cached memory extend the reach?

History.

  • Z. Dai, Z. Yang, Y. Yang, J. Carbonell, Q. Le and R. Salakhutdinov, “Transformer-XL: attentive language models beyond a fixed-length context” (ACL 2019).
  • It reported 0.99 bits per character on enwik8 and perplexity 18.3 on WikiText-103.
  • It was the backbone of XLNet (E12-12).

Exercise 2.

  • Task: streams of random tokens (vocabulary 8), where the target at time t is the token at t − 12.
  • Model: one causal attention layer with RoPE (gradients checked numerically), reading 8-token segments in order and caching the embeddings of the last 0, 1 or 2 segments as stop-gradient keys and values.
  • Training: 2000 steps.
memory tokens cached positions that can see 12 back ceiling accuracy
none 0 0% 0.125 0.117
1 segment 8 50% 0.5625 0.547
2 segments 16 100% 1.000 0.645

Over seeds 1–4: one segment gave 0.57, 0.57, 0.55 and 0.60; two segments gave 1.0 on all four.

  • Without memory, the target is out of reach: accuracy is at chance.
  • One cached segment reaches exactly half the positions, and the model reaches the corresponding ceiling.
  • Two cached segments make every position solvable. 4 of 5 seeds solved it perfectly, while seed 0 stalled at 0.645, an optimisation failure rather than a reach limit.
  • No gradient ever crossed a segment boundary. Reading from stop-gradient memory was enough here, because the needed information (the token itself) is already present in the cached embeddings.
🐍 Exercise 2 (research): does cached memory extend the reach?
Train a segment-recurrent attention layer with 0, 1 or 2 cached segments to recall the token 12 steps back.

Transformer-XL in AI, robotics and aerospace

  • Streaming telemetry: segment recurrence processes endless sensor streams with bounded memory and compute.
  • Long documents: caches let models summarise or search manuals far longer than one window.
  • Inference engineering: KV and memory caches dominate memory use. Size them deliberately for on-board deployment.

References

  1. Z. Dai, Z. Yang, Y. Yang, J. Carbonell, Q. V. Le, R. Salakhutdinov (2019). “Transformer-XL: attentive language models beyond a fixed-length context.” Proc. ACL.
  2. J. W. Rae, A. Potapenko, S. M. Jayakumar, T. P. Lillicrap (2020). “Compressive Transformers for long-range sequence modelling.” Proc. ICLR.