Transformer-XL

The paper extends Transformer language models beyond fixed-length segments using segment-level recurrence and relative positional encoding.

Metadata

FieldValue
PaperTransformer-XL: Attentive Language Models beyond a Fixed-Length Context
AuthorsZihang Dai, Zhilin Yang, Yiming Yang, Jaime Carbonell, Quoc V. Le, Ruslan Salakhutdinov
Year2019
VenueACL 2019
arXiv1901.02860
ACL AnthologyP19-1285
Codekimiyoung/transformer-xl
Statusfull note started

One-Line Takeaway

Transformer-XL changes a fixed-window Transformer language model into a recurrent segment model:

The two durable architecture ideas are:

  1. reuse previous segment hidden states as memory;
  2. use relative position information so cached states remain meaningful when reused.

Question

A vanilla autoregressive Transformer usually trains on fixed-length chunks:

Within a chunk, causal attention can see earlier tokens:

But at the next chunk, the model starts over:

This creates two problems:

ProblemMeaning
fixed contextdependencies beyond the segment length are unavailable
context fragmentationtraining segments cut across natural semantic boundaries

The architecture question is:

Main Claim

Segment-level recurrence lets each segment attend to cached hidden states from previous segments. Relative positional encoding makes that memory reusable across segment boundaries.

For layer and segment , let:

be hidden states for the current segment, and:

be the previous segment hidden states with stopped gradients.

Transformer-XL builds an extended context:

where denotes concatenation along the sequence dimension.

Then the current segment queries attend over previous memory plus current states:

The current segment output remains length , but its attention context is longer than .

Architecture Contract

ItemContract
Inputautoregressive token sequence split into fixed-length segments
Segment lengthcurrent train/eval chunk length
Memory lengthnumber of previous hidden states cached per layer
Query sourcecurrent segment states only
Key/value sourceprevious memory plus current segment states
Gradient through memorystopped at previous segment cache
Position schemerelative positional encoding
Outputnext-token distribution for current segment
Main benefitlonger effective context and faster evaluation via reuse

Transformer-XL is not merely a bigger context window. It is a recurrent Transformer over hidden-state segments.

Segment-Level Recurrence

Let segment contain tokens:

For each layer , Transformer-XL keeps a memory:

The attention context for the current layer is:

Then self-attention is computed with:

The causal mask allows each current token to attend to:

  • earlier cached memory states;
  • earlier positions in the current segment;
  • itself, depending on the implementation convention.

It does not allow attention to future current-segment positions.

Why Stop Gradient

The memory is reused for context but not backpropagated through indefinitely:

This keeps training tractable:

The tradeoff is clear:

ChoiceBenefitCost
stop-gradient memorystable and efficient trainingno gradient credit assignment through all past segments
full prefix recomputationexact full-context gradientsexpensive and fixed by maximum context length
no memorysimple parallel chunkscontext fragmentation

Relative Positional Encoding

If a model uses absolute position embeddings:

cached hidden states from a previous segment carry positions tied to their old segment. Reusing them in a new segment can create positional confusion.

Transformer-XL instead uses relative position information in attention. The attention logit between query position and key position depends on the relative distance:

A simplified relative attention score is:

where:

SymbolMeaning
query vector at current position
content key vector at memory/current position
relative positional embedding for offset

The paper uses a decomposed formulation with content and position terms:

Here and are learned global content and positional biases.

The durable idea:

Attention With Memory

For one layer, current queries:

attend to keys from memory plus current segment:

The attention matrix has shape:

So complexity per segment is:

instead of:

for recomputing all outputs over the full concatenated prefix.

This is why Transformer-XL can be much faster at evaluation: cached hidden states avoid repeated prefix computation.

Context Fragmentation

In fixed-length training, a dependency crossing a segment boundary is invisible:

if the model only sees the current chunk.

Segment memory changes the training signal:

instead of:

This gives the model a better approximation to document-level continuity even when training still uses fixed-size segments.

Relation To Vanilla Transformer

AxisVanilla Transformer LMTransformer-XL
contextfixed current segmentcurrent segment plus memory
recurrencenone across segmentshidden-state recurrence
positionoften absolute or fixed within segmentrelative position for reuse
evaluationrecompute prefix or sliding windowcache previous hidden states
training gradientwithin segmentwithin segment, memory stop-gradient
failure modecontext fragmentationstale/compressed memory and finite cache

Transformer-XL does not remove attention’s quadratic behavior inside the attended span. It changes how the attended span is maintained across time.

Relation To RNNs, Mamba, And Long-Context Models

Transformer-XL reintroduces recurrence into a Transformer:

This looks RNN-like at the segment level, but within each segment it still uses parallel self-attention.

Model FamilyMemory Form
[[concepts/architectures/rnnRNN]] / [[concepts/architectures/lstm
Transformer-XLcached previous hidden states
[[concepts/architectures/state-space-modelState-space model]] / [[concepts/architectures/mamba
Retrieval-augmented modelsexternal retrieved text or vectors
Long-context Transformerslarger direct attention window or sparse attention

The important distinction:

It is not a learned compressed summary unless the hidden states themselves become summary-like through training.

Evidence Pattern

The paper supports the architecture with:

EvidenceWhat It Supports
language modeling benchmarkslower bpc/perplexity across word-level and character-level datasets
ablationsrecurrence and relative position both matter
relative effective context lengthmodel uses longer dependencies than baselines
evaluation speedcached memory avoids repeated computation
long generation examplessegment recurrence improves continuity over thousands of tokens

The strongest architecture evidence is the combination of ablation and effective-context analysis. Benchmark gains alone could come from tuning or compute, but the recurrence/relative-position controls make the architectural mechanism more credible.

Practical Reading For Modern LLMs

Modern LLMs often use KV caches at inference:

so Transformer-XL may feel familiar. The difference is the training and segmentation setup.

Transformer-XL explicitly trains a model to reuse previous segment hidden states with a relative positional scheme. Standard decoder-only LLM inference cache is often a direct consequence of causal attention over the full context used at training.

Reading questions:

QuestionWhy
Was memory used during training or only inference?train/test context mismatch changes behavior
Are positions absolute, relative, rotary, or biased?context extrapolation depends on position scheme
What is cached: hidden states, keys/values, summaries, or retrieved text?memory semantics differ
Is gradient stopped through memory?affects long-range credit assignment
Is evaluation length longer than training length?extrapolation claim needs direct evidence

Why It Belongs In Architecture Papers

Transformer-XL is a canonical architecture note because it creates a clean design axis:

This axis is still relevant when reading:

  • long-context LLMs;
  • recurrent memory Transformers;
  • state-space sequence models;
  • retrieval and memory-augmented agents;
  • protein or genome sequence models with long-range dependencies.

Even when a modern model does not use Transformer-XL directly, the note gives a vocabulary for separating:

Claim TypeCheck
longer contexteffective context length, not only max token count
faster inferencecached computation and memory bandwidth
better continuityboundary-crossing tasks or long generation
better position handlingablation over positional scheme
better memorywhat is stored, how long, and whether it is train-time visible

Limitations

  • Memory length is still finite.
  • Cached hidden states are detached, so long-range gradient flow is limited.
  • More memory increases attention cost and memory bandwidth.
  • Relative position helps reuse, but does not guarantee arbitrary-length extrapolation.
  • It was designed for language modeling; applying the idea to other modalities requires a clear segment boundary and memory contract.
  • Cached hidden states may be stale if later layers would have changed them under full-context recomputation.

The concise limitation:

What To Remember

  • Fixed-length Transformer LMs suffer from context fragmentation.
  • Transformer-XL caches previous segment hidden states as memory.
  • Current queries attend to memory plus current segment keys/values.
  • Gradients through memory are stopped for tractable training.
  • Relative positional encoding is necessary because cached states cross segment boundaries.
  • The paper is a key bridge between Transformers, recurrent memory, KV caching, and long-context architectures.