Prefix language model

Also known as: prefix LM

On this page 7

A prefix language model (often shortened to prefix LM) is a Transformer that processes an input segment, the prefix, with fully bidirectional attention and then generates the remaining tokens autoregressively under a causal mask. Language models of this kind sit between decoder-only and encoder-decoder designs in artificial intelligence: they share one stack of weights like a decoder-only model, yet they let every prefix token see every other prefix token, as an encoder does.

The idea became prominent through research on unified text-to-text pretraining, including the T5 architecture study, UniLM and later U-PaLM and GLM. It matters wherever a model must condition on a fixed input, such as a document to summarize or a question to answer, and then produce new text that depends on it.

How the prefix attention mask works

The defining feature of a prefix LM is its hybrid attention mask. For a sequence of length n split into a prefix of length p and a target of length n minus p, the mask allows every prefix position to attend to all p prefix positions, while each target position attends to the whole prefix and only to earlier target positions. The result is a block matrix: a full square over the prefix, a lower-triangular region over the target and zeros where the prefix would look into the future target.

Training uses next-token prediction only on the target segment. The loss is not computed on prefix tokens, because those tokens can see each other and predicting them would leak the answer. This is the main cost of the design: a prefix LM receives fewer training signals per sequence than a pure causal model, which computes a loss on every position.

The table below summarizes which positions can see which in the three common mask layouts.

Mask typePrefix tokens seeTarget tokens seeLoss positions
Causal maskEarlier tokens onlyEarlier tokens onlyAll tokens
Prefix maskEntire prefixPrefix and earlier targetsTarget tokens only
Encoder-decoderEntire input (encoder)Encoder output and earlier targetsTarget tokens only
Attention visibility by mask type

At inference time, the prefix is processed in one parallel pass, and its keys and values are stored in the KV cache. Generation then proceeds token by token exactly as in a decoder-only model. Because prefix tokens attend forward within the prefix, the cache for the prefix must be recomputed whenever the prefix changes, which complicates multi-turn chat.

A prefix LM is best understood as a middle point between two families. It keeps the parameter sharing and simple serving of a decoder-only model, and it adds the bidirectional context that makes encoder-decoder models strong on understanding-heavy tasks.

PropertyDecoder-onlyPrefix LMEncoder-decoder
Weight stacksOneOneTwo
Context over inputUnidirectionalBidirectionalBidirectional
Loss densityEvery tokenTarget onlyTarget only
Cross-attention layersNoneNoneRequired
Multi-turn cache reuseSimpleLimitedLimited
Typical examplesGPT familyUniLM, GLM, U-PaLM modeT5, BART
Architectural comparison of common language model designs

Compared with a masked language model such as BERT, a prefix LM can generate free text, whereas a masked model only fills selected positions. Compared with an autoregressive model under a strict causal mask, it builds a richer representation of the input, since early prefix tokens can incorporate information from later ones.

Training objectives and variants

Several pretraining recipes produce prefix LMs, and they differ mainly in how the split point is chosen and what the target contains. A random split teaches general continuation, while span-based objectives teach the model to reconstruct corrupted text.

ObjectiveHow the prefix is formedWhat the target contains
Random splitFirst part of a document at a random pointThe rest of the document
Span corruptionDocument with spans replaced by sentinelsThe missing spans
Mixture of denoisersMixed short, long and sequential corruptionSpans or continuation, by mode
Blank infillingText with blanked spansSpans in random order, as in GLM
Instruction tuningInstruction and inputThe reference response
Common prefix LM training objectives

The UL2 mixture of denoisers showed that a single model can switch between prefix LM and span-corruption behavior through mode tokens. Continued training of a causal model with such objectives, as in U-PaLM, reported gains on few-shot benchmarks at modest extra compute, although the size of the gain depends on the task mix.

When a prefix LM is a good choice

A prefix LM is a strong choice when the input is long, fixed and fully known before generation starts and the output is comparatively short. Summarization, translation, question answering over a passage and image captioning in vision-language models fit this pattern well, because the model benefits from reading the whole input in both directions.

  • Vision-language models such as PaliGemma apply a prefix mask over image tokens and the text prompt, then decode the answer causally.
  • Retrieval-augmented tasks gain when retrieved passages are attended bidirectionally before the answer is generated.
  • Open-ended chat usually favors decoder-only models, because the conversation history grows and cache reuse matters more than bidirectional reading.

Limitations and common misconceptions

The most frequent misunderstanding is that a prefix LM is simply a decoder-only model with a prompt. The difference lies in the attention mask, not the input format: a standard GPT-style model reading a prompt still applies a causal mask to it. The second misconception is that bidirectional prefixes always win; at large scale the advantage narrows, and many frontier systems remain purely causal.

LimitationCausePractical consequence
Sparser training signalNo loss on prefix tokensMore data needed for equal quality
Cache invalidationPrefix tokens see future prefix tokensCostly multi-turn inference
Split ambiguityBoundary must be chosenMismatch between training and use
Tooling supportServing stacks assume causal masksCustom kernels or masks required
Practical limitations and their consequences

Engineers should also keep the prefix boundary consistent between training and deployment. A model trained with instructions inside the prefix but served with instructions in the causal part often shows degraded instruction following.

In plain words

A prefix language model reads the question before it answers. It looks at the whole input at once, front to back and back to front. Then it writes the answer one word at a time. The input is read freely, and the output is written in order.

Think of a student who may reread an exam question as often as needed. Once the student starts writing, however, each new sentence can only build on what is already on the page. This mix of free reading and careful writing is the whole idea.

A real-world example

A team building a document question-answering service for an insurance company feeds each request as a prefix of about 1,500 tokens: the policy text plus the customer question. The model attends to that prefix bidirectionally, so a clause near the end of the policy can shape the representation of a definition near the beginning.

The answer, typically 50 to 150 tokens, is then generated causally with a standard KV cache. In internal tests, the team finds that the prefix model resolves cross-references more reliably than a causal baseline of similar size, while serving cost stays close because only one weight stack is used. For a separate chat feature with long, growing histories, the team keeps a decoder-only model, since recomputing the prefix on every turn would be too slow.