A story: filling a hole in a sentence
Suppose someone hands you a fill-in-the-blank sentence: "The cat ___ the mouse." You have no trouble guessing "chases" or "catches." Why? Because you look at what comes before ("The cat") and what comes after ("the mouse"). The missing word has to fit both sides.
Now suppose you are forbidden from looking at what comes after. You are only shown "The cat ___" and asked to continue. Suddenly you could write a thousand things: "sleeps," "meows," "runs in the garden"... The ending "the mouse" will almost never land correctly.
That is exactly the predicament of a standard large language model. And Fill-in-the-Middle (FIM) is the trick that gives it back the use of both sides.
The problem: an LLM only looks left
A large language model (LLM) that is causal (also called "autoregressive", meaning it feeds on what it has just produced itself) is trained on a single task: given the words written so far, predict the next word. Left to right, one token at a time. Formally, it learns:
Take that line apart, because everything else on this page rests on it.
- is the token at position , the one we are trying to guess. The index is simply a place number in the text: first token, second, and so on.
- are all the tokens that precede it, in order. The says "up to the one just before".
- The vertical bar reads "given". It is not a division: it is the symbol for conditional probability.
- is a probability, a number between 0 and 1.
So the whole line reads: "the probability that the next token is this word, given every word that came before". And the decisive point is what does not appear to the right of the bar: nothing that comes after . The model has no access to it, by construction.
"Causal" names exactly that: each token sees only what precedes it, never what follows, like a cause that cannot depend on its effect. This is perfect for continuing text: writing the rest of a paragraph, finishing a function you started.
But many real tasks are not continuations: they are insertions in the middle. The flagship case is code editing. When you put your cursor in the middle of a file, there is code before the cursor and code after it. Completing while ignoring the "after" yields suggestions that fail to connect with the rest of the file.
Models that look both ways do exist: they are called bidirectional. The BERT family is the canonical example, the acronym spells out Bidirectional Encoder Representations from Transformers. They are trained by masking: you hide a word in a sentence and ask the model to recover it using both the text before and the text after.
But such models cannot write long, fluent text token after token. They are built to understand a given sentence, not to produce a new one. Generative models, by contrast, are causal by construction, and that is where their fluency comes from.
So the whole point of FIM is this: gain the insertion ability without giving up the causal model that generates so well. Not choosing between the two, but having both.
The FIM idea: reorder the document during training
The trick is surprisingly simple, and that is what makes it elegant: we change nothing about the model's architecture or about how it learns (still left-to-right). We change only the order of the words we show it during training.
We take a document and cut it into three pieces at random:
- the prefix (what comes before the hole),
- the middle (the piece we want to learn to reconstruct),
- the suffix (what comes after the hole).
Then we rewrite the document in a new order, placing special sentinel tokens (plain reserved markers, something like <PRE>, <SUF>, <MID>) to tell the model which piece is which:
Read this sequence left to right, the way the model does: it first sees the prefix, then the suffix, then the <MID> marker, and at that point it must generate the middle. Because the middle comes last, the model has already read both the prefix AND the suffix by the time it writes. Both sides are now in its past, and therefore accessible. It conditions naturally on both:
The symbols again: the bar still reads "given", and what sits to its right is now the prefix and the suffix. Compare with the formula at the start, where only the past appeared to the right of the bar. That is the only thing that changed, and it is the entire point of the technique.
Worth labouring, because this is the counter-intuitive bit: the causal constraint has not been lifted. The model still looks only into its own past. What has happened is that the suffix has been moved into that past. Training stays exactly the same, predict the next token from what precedes it in the sequence. We have arranged the pieces in a clever order, nothing more.

We don't change the model's brain, we change the order in which we tell it the story: "here's the beginning, here's the ending, now make up the middle." The model then learns that, whenever it sees the <MID> marker, it must produce a piece that connects cleanly to both ends.
At inference time we do the same: we feed the model <PRE> + the code before the cursor + <SUF> + the code after the cursor + <MID>, and let it generate. It stops by emitting a special end-of-middle token (<EOT>, end of text), which is how it signals "I'm done filling the hole."
PSM, SPM: two ways to arrange the pieces
There are two main conventions for the order of the pieces:
- PSM (Prefix-Suffix-Middle): the order described above, prefix, then suffix, then middle.
- SPM (Suffix-Prefix-Middle): put the suffix first, then the prefix, then the middle.
Why this second variant? The reason is purely practical, and it repays understanding, because this is the kind of detail that actually makes the difference.
While the user types in the editor, what changes at every keystroke is the prefix: it grows by one character. The suffix does not move. Now, a model can keep the computations already done on the beginning of a sequence and compute only the rest (that is the attention cache, explained in the KV cache) provided the beginning stays identical.
Compare the two layouts on that criterion. Under PSM the prefix sits at the start of the sequence: it grows, so everything behind it shifts, and the cache is invalidated on every keystroke. Under SPM the suffix (the stable part) goes first, and the moving prefix sits immediately before the middle to be generated, i.e. at the end. The start of the sequence does not change, and the cache stays valid.
In practice, models are often trained on a mix of both conventions, so they can handle either.
The sentinel tokens (<PRE>, <SUF>, <MID>, <EOT>) must be reserved tokens, never present in ordinary text. Otherwise the model confuses a genuine snippet of document with a structural instruction. And at inference time, the pieces must be presented in exactly the format seen during training: a missing or misplaced marker, and the completion goes off the rails.
The key result: "FIM for free"
The big worry was: "if we teach the model to fill holes, won't it get worse at the normal left-to-right continuation task?" This is the most important result of OpenAI's foundational paper, captured by the slogan "FIM for free": by training a model on a mix of normal documents and documents reordered into FIM format, you grant it the infilling ability without degrading its standard left-to-right generation.
In other words, as long as the FIM transformation is applied to a fraction of the training data (on the order of half, per the paper), the model gains an extra skill at near-zero cost on the rest. This is what made FIM standard in modern code models.

This OpenAI work laid down the FIM recipe as it is used today: the "prefix / suffix / middle" transformation with sentinel tokens, the PSM and SPM variants, and above all the empirical demonstration of "FIM for free", you can jointly train middle-infilling and standard generation without sacrificing one for the other.
How it fits with decoding and the editor
Once the model is trained, how we generate the middle is plain decoding: token by token, with the same settings as usual (temperature, sampling, etc.). FIM does not change the mechanics of decoding; it changes only what we put in the context before decoding.
This is what powers the inline suggestion experience in a code editor (the grey text that appears under your cursor):
- The editor takes all the code before the cursor β that's the prefix.
- It takes all the code after the cursor β that's the suffix.
- It assembles the FIM format (
<PRE>β¦<SUF>β¦<MID>) and asks the model to fill in. - The model generates a middle that connects to both sides, up to the
<EOT>token.
And here lies the real engineering difficulty of this task, the one you would never suspect from reading the recipe. Completion in an editor is under a brutal latency constraint. The suggestion must appear within the time it takes a hand to move from one key to the next, a few tens of milliseconds. Beyond that the user has already typed it themselves, and the suggestion arrives for nothing: it is not merely late, it is useless.
That changes the whole specification. On this task a slightly weaker model that is twice as fast is better, because a model that is too slow is worth nothing at all. It is why code-completion models are deliberately small, against the general drift toward the large. The constraint is set out in Codestral.
Two levers make that time budget achievable, and one has already been met above. First, reusing computations already done: as the user types, the prefix grows one character at a time, and recomputing everything on each keystroke would be absurd, that is the job of the attention cache, described in the KV cache. And this is precisely the reason for the SPM convention set out earlier: putting the prefix immediately before the middle keeps that cache usable as the prefix lengthens.
Applications
| Application | Prefix | Suffix | Middle to generate |
|---|---|---|---|
| Code completion | code before the cursor | code after the cursor | the inserted block |
| Docstring insertion | function signature | function body | the docstring that links them |
| Text restoration | passage before the gap | passage after the gap | the missing passage |
| "Middle" editing | start of the paragraph | end of the paragraph | the sentence to insert |
- Code completion. This is the flagship application, and the one that motivated the technique. Specialized code models (Codestral and the other completion models) are trained with FIM precisely so they behave well when you edit in the middle of an existing file, not just at the end of a line. That page is also where you can see what the latency constraint imposes on model size.
- Docstrings and comments. You provide a function's signature (prefix) and its body (suffix), and the model inserts in the middle the documentation describing what the function does.
- Restoring gaps in texts. The same principle serves to reconstruct missing passages: think, for example, of damaged ancient manuscripts with missing chunks, where the model proposes a plausible text that bridges what precedes and what follows the tear.

FIM is the invisible ingredient behind "smart" code autocompletion in the middle of a file. Its power rests on a counter-intuitive point: the value is not in a new architecture, but in a transformation of the training data (the prefix/suffix/middle reordering) and in the sentinel-token protocol that makes it usable at inference time. From an intellectual-property standpoint, inventiveness therefore typically resides in the process details (which fraction of data to transform, how to choose the cut points, how to manage the cache with SPM, how to integrate the whole thing into the editor experience) rather than in the model itself.
Key takeaways
- The problem: a causal LLM only learns to continue left-to-right, whereas completing in the middle of a file requires accounting for the text before AND after the cursor.
- The FIM idea: during training, the document is reordered into (prefix, suffix, middle) with sentinel tokens, so the model learns to generate the middle conditioned on both sides, while remaining a standard causal model.
- No architecture change: only the order of the data changes; the "predict the next token" training stays exactly the same.
- PSM or SPM: two possible orderings. SPM puts the stable part first, which preserves the attention cache as the prefix lengthens under the user's fingers; models are often trained on a mix of both.
- "FIM for free": training on a mix of normal documents and reordered ones adds the infilling ability without degrading left-to-right generation.
- Latency is the real constraint. A suggestion that arrives after the user has typed is worth nothing. That is what keeps code-completion models small, against the general drift, see Codestral.
- Applications: code completion, inserting documentation between a function signature and its body, restoring missing passages in texts.
1. After FIM training, the model fills a gap while taking into account the code located after the cursor. Has it stopped being a causal model?
2. Why does the SPM variant (suffix first, then prefix) exist, when PSM already does the job?
3. What exactly does the Β« FIM for free Β» result of OpenAI's founding paper demonstrate?
4. Why must sentinel tokens like PRE, SUF and MID be reserved tokens, absent from normal text?
5. Why do code-completion models deliberately stay small, against the general trend?