Horizon-Length Prediction: Advancing Fill-in-the-Middle Capabilities for Code Generation with Lookahead Planning

Yifeng Ding, Hantian Ding, Shiqi Wang, Qing Sun, Varun Kumar, Zijian Wang · Submission to ICLR 2025 · Rejected

TL;DR

Current Fill-in-the-Middle (FIM) code models struggle to connect infills smoothly to surrounding code because next-token prediction (NTP) optimizes only one token ahead rather than planning for the entire insertion. The authors propose Horizon-Length Prediction (HLP), an auxiliary training task where the model learns to predict the remaining fraction of middle tokens at every step. HLP boosts infilling performance by up to 24% across single-file and repository-level benchmarks—without relying on artificial post-processing hacks—and incurs zero inference overhead.

What Problem Does This Paper Address?

Code generation often requires filling in missing code between an existing prefix and suffix (Fill-in-the-Middle, or FIM). Today's standard recipe rearranges a code segment into prefix-suffix-middle and trains standard autoregressive models with Next-Token Prediction (NTP), ending generation when an <EOI> (end of insertion) token is emitted.

However, models frequently struggle to exit cleanly and fuse with the suffix. Existing FIM benchmarks hide this shortcoming using heavy, rule-based post-processing—such as forcibly truncating output to the exact number of lines in the ground truth or stopping after a specific syntax construct. In realistic, open-domain settings where target length is unknown, these heuristics fail. When the authors remove such post-processing, standard model performance drops by up to 13.8%.

The root problem is that NTP is myopic: it plans one token at a time, whereas FIM requires global, long-horizon planning to ensure the generated code lands naturally on the distant right-hand context.

Methods

To instill lookahead planning into autoregressive transformers, the authors introduce Horizon-Length Prediction (HLP):

  1. Normalized Horizon Target: At each position $t \in [1, M]$ in the middle segment of length $M$, the model must predict how many tokens remain until completion. To remain scale-invariant across variable context lengths, this target is normalized: $$y_t = \frac{M - t}{M} \in (0, 1]$$
  2. Auxiliary Regression Head: A lightweight linear head (hlp_head) is attached to the final-layer hidden state $h_t$, passed through a sigmoid $\sigma$, and trained with an $L_1$ loss: $$\mathcal{L}_{\text{HLP}} = \sum_{t=1}^M \left|\sigma(w_{\text{hlp}}^\top h_t) - y_t\right|$$
  3. Joint Training & Free Inference: The network optimizes $\mathcal{L} = \mathcal{L}_{\text{NTP}} + \lambda \mathcal{L}_{\text{HLP}}$ (with $\lambda = 0.1$). Because the hlp_head adds $<0.01\%$ parameters and is discarded during inference, HLP introduces zero inference cost.
                [ Target: (M - t) / M ]
                          ^
                          |  L1 Loss
                    [ hlp_head ] (Linear + Sigmoid)
                          ^
                          |
[ Prefix / Suffix ] ---> [ Transformer Hidden State h_t ] ---> [ lm_head ] ---> Next Token

Datasets

  • Continual Pre-training: A 4-language subset (Python, Java, C++, C#) of the-stack-v2-train-smol.
  • Single-File Syntax-Aware Evaluation: SAFIM (algorithmic blocks, control-flow, and API completions across Python, Java, C++, and C#).
  • Repository-Level Cross-File Benchmarks: CrossCodeEval, CrossCodeLongEval, and RepoEval across line, chunk, and function granularities.
  • Downstream Code Tasks: Defects4J (313 real-world single-hunk Java bugs) for code fixing, and CRUXEval (CRUXEval-I and CRUXEval-O) for code execution reasoning.

Key Insights and Ideas

  • Post-processing creates an illusion of competence: Standard benchmarks mask generation failures by truncating runaway models. Evaluating completions strictly via <EOI> reveals a major performance gap in current LLMs.
  • Standard LLMs are blind to horizons: Probing linear representations of standard NTP models reveals they carry almost no information about the distance to the suffix ($R^2 \approx 0.35 - 0.52$). With HLP, linear probing achieves $R^2 > 0.91$, proving horizon awareness must be explicitly incentivized.
  • Global budget beats short lookaheads: Multi-token prediction (MTP) predicts the next $n$ tokens ($n \le 8$), but the authors show this local horizon is too short to help close infill boundaries. HLP's sequence-level budget enables true long-range planning.
  • Dense step-by-step supervision is critical: Ablations show that predicting the remaining horizon at every token outperforms predicting total length only at the first token (50.0 vs. 48.5 pass@1 on SAFIM).

Key Results

Experiments on DeepSeek-Coder (1.3B, 6.7B) and StarCoder2 (3B, 7B) show uniform improvements:

  • Syntax-Aware Infilling (SAFIM): HLP improves greedy pass@1 consistently across all model sizes (e.g., DeepSeek-Coder-1.3B climbs from 47.7% to 50.0%).
  • Cross-File Code Completion: On RepoEval and CrossCodeEval, HLP delivers up to 24% relative improvements in Exact Match (EM) and 9% in Edit Similarity (ES).
  • Bug Fixing (Defects4J): Yields up to 18% more plausible bug fixes (e.g., DS-1.3B fixes 39 bugs vs. 33).
  • Code Reasoning (CRUXEval): Demonstrates up to 6% gains on input/output prediction tasks, showing horizon planning transfers to general code execution reasoning.

Limitations and Future Work

  • Impact on Left-to-Right (L2R) Generation: Training HLP exclusively on FIM splits can slightly degrade pure L2R completion. The authors demonstrate that adding a secondary line-completion HLP task for L2R data recovers this performance, but this requires managing two separate heads.
  • Model Scale: Experiments are capped at 7B-parameter models; scaling behavior on 30B+ or frontier models remains unverified.
  • Infilling Orientation: Evaluation was restricted to Prefix-Suffix-Middle (PSM) formatting, leaving Suffix-Prefix-Middle (SPM) validation for future work.

Summary updated

Abstract

Fill-in-the-Middle (FIM) has become integral to code language models, enabling generation of missing code given both left and right contexts. However, the current FIM training paradigm, which reorders original training sequences and then performs regular next-token prediction (NTP), often leads to models struggling to generate content that aligns smoothly with the surrounding context. Crucially, while existing works rely on rule-based post-processing to circumvent this weakness, such methods are not practically usable in open-domain code completion tasks as they depend on restrictive, dataset-specific assumptions (e.g., generating the same number of lines as in the ground truth). Moreover, model performance on FIM tasks deteriorates significantly without these unrealistic assumptions. We hypothesize that NTP alone is insufficient for models to learn effective planning conditioned on the distant right context, a critical factor for successful code infilling. To overcome this, we propose Horizon-Length Prediction (HLP), a novel training objective that teaches models to predict the number of remaining middle tokens (i.e., horizon length) at each step. HLP advances FIM with lookahead planning, enabling models to inherently learn infilling boundaries for arbitrary left and right contexts without relying on dataset-specific post-processing. Our evaluation across different models and sizes shows that HLP significantly improves FIM performance by up to 24% relatively on diverse benchmarks, across file-level and repository-level, and without resorting to unrealistic post-processing methods. Furthermore, the enhanced planning capability gained through HLP boosts model performance on code reasoning. Importantly, HLP only incurs negligible training overhead and no additional inference cost, ensuring its practicality for real-world scenarios.
BibTeX
@inproceedings{ding2024horizon,
  author = {Yifeng Ding and Hantian Ding and Shiqi Wang and Qing Sun and Varun Kumar and Zijian Wang},
  title = {{Horizon-Length Prediction: Advancing Fill-in-the-Middle Capabilities for Code Generation with Lookahead Planning}},
  booktitle = {Sys2-Reasoning @ NeurIPS},
  year = {2024},
  url = {https://openreview.net/forum?id=L0agONQi9X},
}
Figure