Fill-in-the-middle (FIM) = “I give the model a prefix and a suffix and ask it to invent the missing chunk in-between.”
Although most popular LLMs are trained as left-to-right “next-token predictors,” we can make them very good at FIM with only a few tricks—no exotic architecture required.
────────────────────────────────────────
- Why does FIM work with an autoregressive model?
────────────────────────────────────────
• A causal-LM can only look at previous tokens.
• So we re-order the training text so that the suffix appears before the middle to be predicted.
The model still predicts left-to-right, but from its point of view it has already “seen” the suffix.
Illustrative sequence (real text):
prefix = "def add(a, b):"
middle = " return a + b"
suffix = "\n\nprint(add(2, 3))"
Training example that a causal-LM can ingest:
<fim_prefix> def add(a, b):
<fim_suffix>
print(add(2, 3))
<fim_middle> return a + b
The model’s loss is computed only on the middle span, yet it has both prefix and suffix in its context when it makes those predictions.
────────────────────────────────────────
2. Concrete Training Pipeline
────────────────────────────────────────
step 0 – add three new tokens to the tokenizer
<fim_prefix>, <fim_suffix>, <fim_middle>
step 1 – sample spans
Randomly pick two split points i, j inside each training sequence (often 40–60 % of the text becomes the middle).
step 2 – permute & wrap
Create the reordered sequence shown above.
step 3 – causal training
Standard next-token-prediction objective, but you mask loss for everything up to (and including) <fim_middle> so the gradient flows only through the true “hole.”
Result → one model that can:
• continue as usual (if you never send the special tokens), or
• infill a hole (if you do).
This is exactly how StarCoder, CodeLlama-Infill, Mistral-Instruct-FIM, Gemma-Infill, etc. are built.
────────────────────────────────────────
3. Inference Time
────────────────────────────────────────
Prompt pattern
<fim_prefix>{PREFIX}<fim_suffix>{SUFFIX}<fim_middle>
Then sample/generate until you decide to stop (e.g., on a newline, an explicit <end> token, max-length, etc.).
Because the suffix was provided before generation started, the model can stay consistent with it.
With llama.cpp (≥ v0.2.17) the CLI already ships with FIM support:
./main -m models/codellama-7b-instruct.Q5_K_M.gguf \
-p "<fim_prefix>def fib(n):\n<fim_suffix>\nprint(fib(10))\n<fim_middle>" \
--temperature 0.1 --top-k 50
────────────────────────────────────────
4. Variants & Extensions
────────────────────────────────────────
• Span-Corruption (T5, UL2) – mask multiple spans, replace each by a numbered sentinel; the decoder predicts all missing chunks in one shot.
• Prefix-LM – attend bidirectionally inside a window, remain causal outside (used in some GPT-NeoX variants).
• Multi-FIM – train on 2–4 holes at once (rare—for code editors you usually need only one).
────────────────────────────────────────
5. Common Pitfalls
────────────────────────────────────────
| Problem | Fix |
|---|
| Model leaks prefix/suffix copies | Increase diversity of masks during training; raise temperature. |
| Invalid indentation / syntax | Keep the suffix short in the prompt so the model isn’t forced to “look too far.” |
| Poor quality on natural language | Train FIM only on code? Add NL examples to dataset. |
────────────────────────────────────────
6. Can I retrofit an existing model?
────────────────────────────────────────
Yes, with lightweight continued pre-training (a few billion tokens):
- Add the three FIM tokens to the tokenizer (they become new vocab IDs).
- Keep the optimizer states frozen; train 1–2 epochs on your corpus with the permutation recipe above.
- Optional: LoRA / QLoRA for cheap adapters instead of full fine-tune.
Even a single GPU and ~24 h can give a noticeable bump.
────────────────────────────────────────
TL;DR
- Insert three sentinel tokens.
- During training, shuffle “suffix → middle” so a causal-LM can still learn.
- At inference, feed
<fim_prefix>PREFIX<fim_suffix>SUFFIX<fim_middle> and sample.
That’s how LLMs do fill-in-the-middle—all without changing the transformer architecture itself.