TL;DR
Fill-in-the-middle (FIM) is a way to train an ordinary left-to-right language model so that it can write text inside a gap. Each training document is cut into three pieces, a prefix, a middle and a suffix, and the pieces are rearranged so the suffix comes before the middle. The model then predicts the middle one token at a time, exactly as it predicts any other text, but it has already read what comes after the gap.
Builds on: Autoregressive Model, Subword Tokenization · Leads to: code models that complete code at the cursor, such as Code Llama
Where it's used
Code completion in an editor. When you type in the middle of a function, the editor knows the code above the cursor and the code below it. A model trained with FIM can use both, so it can suggest a body that matches the function's closing lines and the calls made elsewhere in the file. Code Llama is trained this way for its infilling mode.
Completing a function body from its signature and callers. Suppose a file calls parse_date(text) in twenty places, but the function itself is empty. A FIM model sees the signature before the gap and the call sites after it, so the predicted body can be checked against how the function is used.
Filling a missing sentence in a document. A writing tool can hand the model the paragraph before a gap and the paragraph after it. The model writes the missing sentence so that it connects to both, instead of only continuing from the left.
How it works
Take one tiny training document, the four words one two three four, and a tiny model that predicts one word at a time.
- Pick a document. Start with an ordinary training document. Here it is
one two three four. - Choose two cut points at random. Cut after
oneand afterthree. The prefix isone, the middle istwo three, and the suffix isfour. Some training documents get this treatment and others are left alone. - Add three sentinel tokens. The model needs to know which piece is which, so three special tokens are added to the vocabulary: one that marks the prefix, one that marks the suffix and one that marks the middle. Write them here as
<PRE>,<SUF>and<MID>. - Rearrange the pieces. The new sequence is
<PRE> one <SUF> four <MID> two three <EOT>, where<EOT>is the end-of-text token that the model already uses to stop. - Train with the usual objective. The rearranged sequence is fed to the same left-to-right model with the same next-token loss. At every position the model predicts the next token from the tokens before it. Nothing about the model or its loss changed.
- Generate a gap. At use time you put the text before the cursor after
<PRE>, the text after the cursor after<SUF>, and end with<MID>. The model then writes the middle, token by token, until it produces<EOT>. The text it wrote is the gap's contents. - Keep normal use working. Because only some documents are rearranged, the same model still writes ordinary left-to-right text when you give it a prompt with no sentinels.
| Stage | Sequence the model sees | What it predicts |
|---|---|---|
| Original document | one two three four | each word from the words before it |
| Rearranged for training | <PRE> one <SUF> four <MID> two three <EOT> | two after <MID>, then three, then <EOT> |
| Infilling at use time | <PRE> (text before) <SUF> (text after) <MID> | the middle, then <EOT> |
The math
Take a document as a sequence of tokens . Pick two positions and split into a prefix , a middle and a suffix . Form the rearranged sequence , and train with the ordinary next-token loss on .
Step 1 in symbols: the cut
The two cut points and are chosen at random for each transformed document. Concatenating the pieces in the original order gives back , so the transformation loses no text. The model is never shown in its original order when the transformation applies.
Step 2 in symbols: the rearrangement
The rearranged sequence has tokens: the original tokens plus four sentinels, , , and . Only the first three are new to the vocabulary, because the model already uses to stop. The architecture does not change.
Step 3 in symbols: the loss
The training loss is the usual autoregressive negative log-likelihood, taken over the rearranged sequence:
Here are the model's parameters and are the tokens before position in . The prediction targets inside the middle are and , and each is predicted with the whole prefix and suffix already in context.
Step 4 in symbols: generation
At use time the model is given and and asked for the middle. It samples the middle one token at a time from
which is a product of ordinary next-token probabilities, conditioned on the prompt built from , and the sentinels.
Worked examples
Take the document with and , so , and .
- Rearrange: . That is 8 tokens.
- Next-token loss on 8 tokens has 7 prediction targets, one for each token after the first.
- The targets that belong to the middle are the ones after : , and . That is 3 targets.
- Check the count: 3 of the 7 targets are on the middle, and the other 4 are on the prefix, the suffix and the sentinels.
- Interpretation: when the model predicts , the suffix has already been read, so it can use to decide what and must be. Without the rearrangement, would come after the gap and would never help.
The file has def double(x): followed by return and then, after the cursor, the lines print(double(4)). The middle the model must write is 2 * x.
- Prefix:
def double(x):\n return. Suffix:\nprint(double(4)). - Rearranged:
<PRE>prefix<SUF>suffix<MID>then the middle. - When the model reaches
<MID>it has already read the calldouble(4). - The call's argument is 4, so a body that returns 8 for that input is the right kind of answer, and
2 * xdoes this. - Interpretation: the suffix does not tell the model the exact text, but it narrows the choice a lot. A left-to-right model that never saw the call would have to guess what the function is for.
A code editor gives a model a 2,048-token window. The text before the cursor is 1,200 tokens, and the text after the cursor is 700 tokens. The three sentinels <PRE>, <SUF> and <MID> take 3 tokens.
- Add the fixed parts: 1,200 + 700 + 3 = 1,903 tokens.
- Subtract that from the window: 2,048 − 1,903 = 145 tokens.
- Those 145 tokens are the most the model can write before it hits the limit. That is enough for a short body, but not for a long one.
- Interpretation: the middle always competes with the context for the same space, so an editor must decide what to keep from each side.
Try it: suppose the suffix is 1,400 tokens instead of 700. How many tokens remain for the middle? Answer: 2,048 − (1,200 + 1,400 + 3) = 2,048 − 2,603 = −555. The prompt does not fit at all, so the editor must trim the suffix, usually by keeping the lines nearest the cursor.
Common mistakes and tradeoffs
It is tempting to think that FIM makes the model read in both directions at once. In fact the model is still left-to-right: during generation it writes the middle token by token, and each middle token sees only the prefix, the suffix and the middle tokens already written. The suffix is simply placed before the middle in the sequence, so it is read first.
It is tempting to think FIM is the same as Masked Language Modeling. In fact masked language modeling replaces tokens with a mask and predicts them from both sides with a bidirectional encoder, and it does not generate text left to right. FIM keeps the decoder-only setup (a model that reads only left to right) of language models, so the same model can also do ordinary continuation.
It is tempting to think the model can see the middle ahead of time. In fact the middle is only ever predicted, one token after another, and the sentinel <MID> marks the point where that prediction starts.
It is tempting to think FIM needs a new architecture. In fact it needs three new sentinel tokens and a change to the training data, and the network is the standard Transformer decoder.
When to use it. Use FIM when a left-to-right model must also fill gaps: code editors, structured documents, or any setting where the text after the cursor is known. When not to use it. Skip it when all you need is continuation, or when the context window is too small to hold both sides of the gap. Alternatives. A bidirectional encoder with masked prediction works for filling gaps but cannot generate open-ended text. Training a separate infilling model is also possible, but then two models must be kept in step. The fraction of training documents that are rearranged is a choice; the paper's main setting mixes both formats rather than training on rearranged text alone.
History
Before 2022, filling a gap with a language model usually meant a bidirectional encoder such as the one trained by masked language modeling (BERT, 2018), which cannot generate open-ended text, or a special architecture for each task. Left-to-right models were the standard for generation, and they had no direct way to use text after the gap.
In 2022 a team at OpenAI showed that a plain left-to-right model could learn infilling by seeing rearranged documents with sentinel tokens, with little loss on ordinary generation. The work is described in Efficient Training of Language Models to Fill in the Middle. The idea spread to code models because code has a natural structure: a function's signature and its callers are often both known while its body is being written.
Recap
- A document is cut into prefix, middle and suffix, and the pieces are rearranged to prefix, suffix, middle with sentinel tokens.
- The model is trained with its ordinary next-token loss on the rearranged text, so nothing about the architecture changes.
- At use time the model writes the middle, left to right, with the suffix already in its context.
- The main limit is the context window: the prefix, suffix and middle must all fit.
Read next: Code Llama, which uses infilling for code, and Masked Language Modeling, the bidirectional alternative this lesson contrasts with.
Check yourself
QuestionA document is cut into prefix, middle and suffix. In what order does the model read these pieces during training, and which one does it predict?Show answer
It reads the prefix, then the suffix, then the middle, each marked by its sentinel. The next-token loss covers the whole rearranged sequence, but the predictions that matter for infilling are the middle tokens and the end-of-text sentinel. At use time only the middle is generated, while the prefix and suffix are given as context.
QuestionThe document is with and , so the middle is . How many next-token prediction targets fall on the middle, counting ?Show answer
The rearranged sequence is . The middle targets are , and , so there are 3.
QuestionWhy does FIM not need a bidirectional architecture, even though the suffix is read before the middle?Show answer
Because the suffix is placed in the input sequence before the middle, a left-to-right model can read it before it predicts any middle token. Each middle token is still predicted from the tokens before it in the rearranged sequence, which is exactly what a decoder-only model already does. No attention has to flow backwards, so the standard decoder works unchanged.
QuestionA team trains a code model with FIM on every document. Their users say the model now writes worse ordinary continuations when they give it a plain prompt. What would you check first?Show answer
Check how many training documents were rearranged. The main setting of the original work mixes rearranged and ordinary documents, so the model keeps its left-to-right skill, and training only on rearranged text can shift it. Compare a model trained with a mixed rate against the all-FIM one on ordinary continuation prompts before changing the architecture.
Sources
- Bavarian et al. Efficient Training of Language Models to Fill in the Middle. arXiv:2207.14255 (2022). arXiv abstract page.
- Rozière et al. Code Llama: Open Foundation Models for Code. arXiv:2308.12950 (2023). arXiv abstract page.