Fill-in-the-Middle (FiM) turns a language model from “predict-what-comes-next” into “write-what-goes-here.”
Every FiM training example is split into three spans
• Prefix (text that comes before the gap)
• Middle (the gap to be generated)
• Suffix (text that comes after the gap)
To teach the model what to do we shuffle/mark those spans in several ways.
The three most common formats are Prefix-Suffix-Middle (PSM), Suffix-Prefix-Middle (SPM) and Mask.
Below is what each one looks like, why it exists, and a concrete example.
────────────────────────────────────────
Prefix-Suffix-Middle (PSM)
────────────────────────────────────────
Idea
Give the model the beginning and the end, then ask it to fill the hole.
Why it is useful
• Closest to the way a developer would fill a missing chunk when they can already see the surrounding code.
• Lets the model first read both available contexts and then “think” about the missing part.
Example
code
<fim_prefix>
def add(a, b):
<fim_suffix>
return result
<fim_middle>
Desired generation (middle)
code
result = a + b
────────────────────────────────────────
2. Suffix-Prefix-Middle (SPM)
────────────────────────────────────────
Idea
Swap the order of the two known contexts: show the end first, then the beginning.
Why bother?
• Forces the model to be permutation-invariant: it learns that “both chunks matter, order may vary.”
• Provides extra training diversity → better generalisation to quirky real-world prompts.
Example
code
<fim_suffix>
return result
<fim_prefix>
def add(a, b):
<fim_middle>
Desired generation
code
result = a + b
────────────────────────────────────────
3. Mask (a.k.a. In-Place Masking)
────────────────────────────────────────
Idea
Keep the code in its original order but replace the missing span with a sentinel mask token.
Canonical prompt layout
PREFIX-TOKENS <fim_middle> SUFFIX-TOKENS
(model starts generating as soon as it sees <fim_middle>)
Why it is useful
• Looks exactly like what a developer would see in an IDE with a placeholder “/* TODO */”.
• Preserves linear flow, which some autoregressive models prefer.
Example
code
def add(a, b):
<fim_middle>
return result
Desired generation
code
result = a + b
────────────────────────────────────────
How training & inference work
────────────────────────────────────────
During training
Randomly cut a code/document snippet into prefix, middle, suffix.
Randomly pick one of the FiM prompt styles (PSM, SPM, Mask).
Feed the rearranged input to the LM; teach it to generate the middle tokens.
At inference
Choose whichever style you feel is easiest to craft:
• want something IDE-like → Mask
• already have separate prefix/suffix variables → PSM
• need extra diversity/testing → SPM
The model, having seen all three during training, should correctly fill the gap in any of them.