Fill-in-the-middle (FIM) is a training objective and inference mode in which a language model generates the missing span between a known prefix and a known suffix, rather than only continuing text from left to right. In AI for coding, FIM is the mechanism behind most inline completions in editors: the model sees the code above the cursor and the code below it, and proposes the text that belongs in between. The task is also called code infilling.
FIM matters because programmers rarely write code strictly from top to bottom. They insert a function body under an existing signature, add an argument in the middle of a call or complete a block that already has a closing brace. A model trained with FIM uses both sides of the cursor as context, which makes its suggestions syntactically consistent with the surrounding file.
How FIM training transforms documents
FIM keeps a standard causal (left-to-right) transformer and changes only the training data. A document is split at two random positions into a prefix, a middle and a suffix. The pieces are then rearranged so that the middle comes last, separated by sentinel tokens that mark each part. The model learns to predict the middle after it has already read the prefix and the suffix.
The approach was formalized in 2022 research showing that a model can learn infilling without measurable loss of ordinary left-to-right ability, a result often called the FIM-for-free property. Typical training mixes apply the transformation to roughly 50 to 90 percent of documents, while the rest are kept in normal order. Some models choose split points at random characters, others at line or syntax-tree boundaries.
The two common orderings differ in where the suffix appears in the sequence.
| Ordering | Sequence layout | Practical property |
|---|---|---|
| PSM (prefix-suffix-middle) | PRE prefix SUF suffix MID middle | Intuitive, widely used format |
| SPM (suffix-prefix-middle) | SUF suffix PRE prefix MID middle | Prefix sits next to the middle, better key-value cache reuse |
| Mixed PSM and SPM | Both layouts during training | Model works with either at inference |
Sentinel tokens and prompt format
At inference time the editor builds a prompt in exactly the format used during training. Each model family defines its own sentinel tokens, such as <fim_prefix>-style markers in StarCoder or dedicated prefix, suffix and middle tokens in Code Llama, Codestral, DeepSeek-Coder and Qwen-Coder. Using the wrong sentinel spelling or order silently degrades results, because the model then treats the markers as ordinary text.
Generation stops when the model emits an end-of-middle or end-of-text token, or when the client truncates the output at a heuristic boundary such as the end of a block. Good clients also trim suggestions that would duplicate the first lines of the suffix, a frequent artifact of infilling.
The parameters below shape the quality and speed of an FIM completion.
| Parameter | Typical range | Effect |
|---|---|---|
| Prefix length | Hundreds to several thousand tokens | More context, higher latency |
| Suffix length | A few hundred to a thousand tokens | Anchors the end of the suggestion |
| Maximum new tokens | About 16 to 256 | Single line versus whole block |
| Temperature | 0 to 0.3 | Low values give stable completions |
| Latency budget | About 100 to 500 milliseconds | Decides model size and hardware |
FIM compared with other completion methods
FIM is one of several ways an assistant can propose code. Plain left-to-right completion ignores what follows the cursor, while chat-based editing rewrites larger regions on request. Newer features such as next edit suggestion predict changes elsewhere in the file, often building on FIM-style training with edit histories.
| Method | Context used | Best suited for |
|---|---|---|
| Left-to-right completion | Prefix only | Writing new code at the end of a file |
| Fill-in-the-middle | Prefix and suffix | Inline completion inside existing code |
| Inline chat | Selection plus instruction | Targeted rewrites described in language |
| Next edit suggestion | File plus recent edits | Propagating a change to related lines |
| Multi-file editing | Several files and a plan | Refactoring across a codebase |
Repository context and evaluation
Real projects spread relevant information across many files, so production systems extend FIM with repository-level context. The client retrieves snippets such as imported type definitions or similar functions and places them before the prefix, often with file path headers. Models such as StarCoder 2 and DeepSeek-Coder were trained with this repository-aware layout, which improves completions that depend on project-specific names.
Evaluation typically uses single-line, multi-line and random-span infilling benchmarks, scored by exact match or by executing unit tests on the completed function. In deployment, teams track the suggestion acceptance rate and the share of accepted characters that survive later edits, because benchmark scores do not capture latency or user trust.
Limitations and common mistakes
FIM models still produce plausible but wrong code, including calls to functions or packages that do not exist. Because the suffix constrains the output, the model may also force a fit that compiles yet changes behavior. Instruction-tuned chat models often lose FIM ability unless it is preserved during fine-tuning, so a strong chat model is not automatically a good infilling model.
- Mismatched sentinel tokens produce repetitive or empty suggestions.
- Overly long prefixes increase latency without improving accuracy beyond a point.
- Accepted completions still require review and tests, especially in security-sensitive code.
The simple explanation
Imagine a sentence with a gap in the middle. You can read the words before the gap and the words after it. With both sides, guessing the missing words is much easier. Fill-in-the-middle teaches an AI model to fill such gaps in code.
When a programmer types inside a file, the code above and below is already there. The model looks at both parts. It then suggests the piece that fits in between, much like completing a puzzle with the edges already in place.
How it is used in practice
A backend developer is adding input validation to an existing Python function. The function signature sits above the cursor, and below it a return statement already uses a variable named cleaned_order. The editor sends roughly 2,000 tokens of prefix and 400 tokens of suffix to a locally hosted 7-billion-parameter code model using its FIM format.
Within about 200 milliseconds, the model proposes six lines that check required fields, normalize currency codes and assign the result to cleaned_order, matching the name it saw in the suffix. The developer accepts the suggestion, adjusts one error message and runs the unit tests, which pass. The team later reports that inline FIM completions handle much of this routine glue code, while design decisions remain with the developers.