Code Foundation Models, Fill-in-the-Middle (FIM), Execution-Guided Program Synthesis, and Repository-Level Software Engineering Agents in 2026: Codex & Unbiased Pass@k, AlphaCode Clustering, StarCoder2, DeepSeek-Coder-V2, and SWE-bench / SWE-agent ACIs

How do artificial intelligence systems evolve from left-to-right natural language token predictors that score 0% on standalone Python function synthesis (GPT-3 on HumanEval) into execution-grounded code foundation models and autonomous repository-level software engineering agents capable of solving 70.2%–77.5% of HumanEval via repeated sampling and unit-test verification (Codex-12B & Codex-S, arXiv:2107.03374v2), infilling arbitrary missing code spans between prefix and suffix contexts for free at 50%–90% transformation rates with zero degradation to autoregressive perplexity (Fill-in-the-Middle, arXiv:2207.14255v1), filtering millions of sampled C++ and Python programs down to 10 behavioral equivalence clusters to rank in the top 54.3% of real Codeforces competitions with >5,000 participants (AlphaCode 41.1B, arXiv:2203.07814v1), training open-weights models across 619 programming languages and 4.3 trillion tokens (StarCoder2-15B, arXiv:2402.19173v1) and 10.2 trillion tokens in a 236B-total / 21B-active Mixture-of-Experts architecture reaching 90.2% on HumanEval and 75.7% on MATH (DeepSeek-Coder-V2, arXiv:2406.11931v1), and autonomously navigating multi-thousand-file repositories to resolve 2,294 real-world GitHub issues via custom Agent-Computer Interfaces (SWE-bench & SWE-agent, arXiv:2310.06770v3, arXiv:2405.15793v3)?

Unlike natural language text—where minor syntactic variations or synonym substitutions rarely alter human comprehension—computer source code is governed by formal grammars, strict type systems, nonlocal cross-file symbol resolution, and unforgiving runtime execution semantics. A single off-by-one index, unclosed parenthesis, or mutated return type transforms a syntactically plausible program into a total runtime failure. Scaling neural networks from single-line autocomplete to autonomous software engineering required overcoming three foundational mathematical and systems bottlenecks:

  1. The Inadequacy of $n$-Gram String Overlap (BLEU) and the Variance of Naive $\text{pass}@k$ Estimation (arXiv:2107.03374v2): Evaluators borrowed from machine translation—such as BLEU or CodeBLEU—measure surface token overlap against a single reference implementation, penalizing functionally identical algorithms that use different variable names, loop structures, or control flow. Conversely, evaluating functional correctness via unit test execution across $k$ stochastic samples using the naive empirical estimator $1 - (1 - \hat{p})^k$ introduces systematic downward statistical bias and high variance whenever $k$ approaches the total sample budget $n$, necessitating an exact combinatorial unbiased estimator (https://ar5iv.labs.arxiv.org/html/2107.03374).
  2. The Left-to-Right Causal Context Blindness and Competitive Search Explosion (arXiv:2207.14255v1, arXiv:2203.07814v1): Real-world software editing rarely occurs purely at the end of a file; developers insert statements, refactor function bodies, and repair bugs surrounded by both preceding (prefix) and succeeding (suffix) code. Standard left-to-right causal masks condition only on the prefix. Meanwhile, in algorithmic program synthesis (CodeContests, Codeforces), the reward signal is binary and sparse: existing datasets suffered from 30%–60% false-positive rates due to weak test coverage, and finding a valid algorithm requires generating $10^5$ to $10^6$ candidates per problem and collapsing them to at most 10 submissions without access to hidden test cases (https://ar5iv.labs.arxiv.org/html/2203.07814).
  3. The Repository-Level Localization Bottleneck and Human-Shell Interface Mismatch (arXiv:2310.06770v3, arXiv:2405.15793v3): While function-level benchmarks (HumanEval, MBPP) average fewer than 20 lines of self-contained code, real GitHub issues (SWE-bench) span repositories averaging hundreds of thousands of lines across thousands of files. Feeding retrieved files into non-interactive language models (BM25 RAG) yields a mere 1.96%–1.97% resolution rate for Claude 2 and 1.31% for GPT-4 Turbo, while giving an autonomous agent raw Linux bash and sed/vim commands causes severe context pollution, line-numbering drift, and unrecovered syntax corruption (https://arxiv.org/html/2310.06770v3, https://arxiv.org/html/2405.15793v3).

Between 2021 and 2026, six landmark engineering milestones established the mathematical and architectural foundations of Code Foundation Models and Autonomous Software Engineering Agents:

  1. OpenAI Codex, HumanEval, and the Unbiased Combinatorial $\text{pass}@k$ Estimator (Chen et al., arXiv:2107.03374v2): Fine-tuning GPT models up to 12B parameters on 159 GB of unique Python files filtered from 54 million public GitHub repositories (179 GB raw) and introducing HumanEval (164 hand-written Python problems averaging 7.7 unit tests per problem) along with the unbiased combinatorial estimator $\text{pass}@k = \mathbb{E}[1 - \binom{n-c}{k}/\binom{n}{k}]$. While GPT-3 solves 0% and GPT-J-6B solves 11.4%–11.62%, Codex-12B achieves 28.8% (28.81%) $\text{pass}@1$ and 70.2% (72.31%) $\text{pass}@100$, and standalone-function-tuned Codex-S-12B reaches 37.7% $\text{pass}@1$, 44.5% via mean log-probability reranking, and 77.5% $\text{pass}@100$ (https://ar5iv.labs.arxiv.org/html/2107.03374).
  2. Fill-in-the-Middle (FIM) Character-Level Span Permutations and the FIM-for-Free Property (Bavarian et al., arXiv:2207.14255v1): Splitting training documents at the character level into (Prefix, Middle, Suffix) spans and relocating the middle span to the end using sentinel tokens in Prefix-Suffix-Middle (PSM) and Suffix-Prefix-Middle (SPM) modes. Evaluated across 100B tokens of pre-training, joint FIM training up to a 50%–90% FIM transformation rate establishes the FIM-for-free property: models acquire bidirectional code infilling capabilities with zero degradation to left-to-right causal language modeling loss or downstream autoregressive benchmarks (https://ar5iv.labs.arxiv.org/html/2207.14255).
  3. AlphaCode 41.1B, CodeContests Mutation Synthesis, and Execution-Filtered Behavioral Clustering (Li et al., Science / arXiv:2203.07814v1): Pre-training an asymmetric Multi-Query Attention (MQA) encoder-decoder Transformer up to 41.1B parameters ($d_{\text{model}} = 6144$, 8 encoder / 56 decoder blocks) on 715.1 GB of GitHub code and fine-tuning on CodeContests (13,328 train / 117 valid / 165 test problems where synthesized test inputs slash false-positive rates from 30%–60% down to 4%). By sampling millions of C++/Python programs with randomized tag/rating metadata, filtering >99% via example tests, and clustering surviving programs by their execution outputs on model-generated test inputs, AlphaCode solves 34.2% of CodeContests test problems and achieves an average top 54.3% ranking across 10 Codeforces contests (https://ar5iv.labs.arxiv.org/html/2203.07814).
  4. StarCoder2 and The Stack v2 Software Heritage Commons (Lozhkov et al., arXiv:2402.19173v1): Building an open, auditable training corpus atop the Software Heritage (SWH) archive spanning 619 programming languages (6,457.14 GB / 784.30M files across 32 popular languages in The-stack-v2-dedup, $4\times$ larger than The Stack v1) plus 3.3M GitHub pull requests (67.3 GB), issues, notebooks, and compiler IRs. Training StarCoder2-3B (3.3T tokens), 7B (3.7T tokens), and 15B (4.3T tokens) with Grouped-Query Attention (GQA, 2 to 4 KV heads), Sliding Window Attention (4,096 base $\to$ 16,384 full-attention long-context fine-tuning with RoPE $\theta = 10^5 \to 10^6$), and repository-context grouping enables StarCoder2-15B to achieve 46.3% HumanEval, 37.8% HumanEval+ ($80\times$ tests), 66.2% MBPP, and 53.1% MBPP+ ($35\times$ tests), matching or outperforming CodeLlama-34B (https://arxiv.org/html/2402.19173v1).
  5. DeepSeek-Coder-V2 236B MoE Code & Mathematical Intelligence (DeepSeek-AI, arXiv:2406.11931v1): Continuing pre-training from a 4.2T-token DeepSeek-V2 checkpoint with 6 trillion additional tokens (10.2T total tokens: 60% code across 338 programming languages, 10% math, 30% natural language) across DeepSeek-Coder-V2-Lite (16B total / 2.4B active) and DeepSeek-Coder-V2 (236B total / 21B active) with Multi-Head Latent Attention (MLA) and 128K YaRN context. DeepSeek-Coder-V2-Instruct breaks the closed-source barrier with 90.2% Python HumanEval, 76.2% MBPP+, 75.3% 14-language average (beating GPT-4-Turbo-0409 at 72.3% and Claude-3-Opus at 70.8%), 43.4% LiveCodeBench (tying GPT-4o), 73.7% Aider code editing (beating GPT-4o at 72.9%), 94.9% GSM8K, and 75.7% MATH (https://arxiv.org/html/2406.11931v1).
  6. SWE-bench and SWE-agent Agent-Computer Interfaces (ACI) (Jimenez et al., arXiv:2310.06770v3; Yang et al., arXiv:2405.15793v3): Benchmarking real-world patch generation across 2,294 GitHub issue-PR pairs from 12 Python repositories (filtered from 93,139 crawled PRs) verified by FAIL_TO_PASS and PASS_TO_PASS test suites, and introducing SWE-agent's LM-centric ACI—a 100-line windowed file viewer, 50-result-capped repository search commands, a built-in syntax-linted edit <start>:<end> guardrail, and 5-observation context folding—which elevates GPT-4 Turbo from 1.31% (RAG) to 12.47% (286 / 2,294) on full SWE-bench, 18.00% (54 / 300) on SWE-bench Lite (a 64% relative gain over a raw Linux shell agent), and 87.7%–89.7% on HumanEvalFix (https://arxiv.org/html/2405.15793v3).
📌 Key Takeaways & Empirical Code Foundation Model / SWE-Agent Benchmarks
  • ✓OpenAI Codex, HumanEval & Unbiased Pass@k (arXiv:2107.03374v2): Fine-tuned on 159 GB of unique Python files from 54M GitHub repositories and evaluated on 164 hand-written HumanEval problems (avg 7.7 unit tests) using $\text{pass}@k = \mathbb{E}[1 - \binom{n-c}{k}/\binom{n}{k}]$, Codex-12B reaches 28.8% (28.81%) pass@1 and 70.2% (72.31%) pass@100 (vs. 0% GPT-3 and 11.4%–11.62% GPT-J-6B), while standalone-tuned Codex-S-12B hits 37.7% pass@1, 44.5% mean log-prob reranking, and 77.5% pass@100.
  • ✓Fill-in-the-Middle (FIM) Character Spans & FIM-for-Free (arXiv:2207.14255v1): Applying character-level random span splits into PSM (<PRE> P <SUF> S <MID> M) and SPM (<PRE> <SUF> S <MID> P M) sentinel formats across 100B tokens proves that pre-training with a 50%–90% FIM rate delivers bidirectional infilling with zero cost to left-to-right causal perplexity or HumanEval pass@1.
  • ✓AlphaCode 41.1B & Execution-Filtered Behavioral Clustering (arXiv:2203.07814v1): Pre-trained on 715.1 GB of GitHub code and fine-tuned on CodeContests (13,328 train / 117 valid / 165 test problems; false-positive rate cut from 30%–60% to 4%), AlphaCode samples millions of solutions, filters >99% via example tests, and clusters outputs on synthetic inputs to solve 34.2% of CodeContests test tasks and rank in the top 54.3% across 10 Codeforces contests (best 20.9%).
  • ✓StarCoder2 & The Stack v2 Across 619 Languages (arXiv:2402.19173v1): Trained on Software Heritage source code (619 languages, 4× larger than Stack v1) + 3.3M PRs across 3.3T (3B), 3.7T (7B), and 4.3T (15B) tokens with GQA and 4K SWA → 16K full-attention context ($\theta = 10^5 \to 10^6$), StarCoder2-15B achieves 46.3% HumanEval, 37.8% HumanEval+ (80× tests), 66.2% MBPP, and 53.1% MBPP+ (35× tests).
  • ✓DeepSeek-Coder-V2 236B/21B MoE Across 338 Languages (arXiv:2406.11931v1): Exposed to 10.2T total tokens (4.2T + 6T continued pre-training: 60% code, 10% math, 30% NL) with MLA and 128K YaRN context, DeepSeek-Coder-V2-Instruct (236B/21B) reaches 90.2% Python HumanEval, 76.2% MBPP+, 75.3% 14-language avg, 43.4% LiveCodeBench, 73.7% Aider, 12.7% SWE-bench, 94.9% GSM8K, and 75.7% MATH, while 16B/2.4B Lite hits 86.4% mean FIM accuracy.
  • ✓SWE-bench (2,294 Tasks) & SWE-agent ACI (arXiv:2310.06770v3, arXiv:2405.15793v3): Across 2,294 real GitHub issues from 12 Python repos (filtered from 93,139 PRs), non-interactive BM25 RAG resolves only 1.96%–1.97% (Claude 2) and 1.31% (GPT-4 Turbo). Equipping GPT-4 Turbo with SWE-agent's 100-line file viewer, 50-result search cap, and syntax-linted edit ACI lifts resolution to 12.47% (286/2,294) on full SWE-bench, 18.00% (54/300) on SWE-bench Lite, and 87.7%–89.7% on HumanEvalFix.
77.5% Pass@100
Codex-S-12B on HumanEval

Trained on 159 GB from 54M GitHub repos; solves 37.7% pass@1, 44.5% via log-prob reranking, and 77.5% at 100 samples across 164 tasks (arXiv:2107.03374v2).

Top 54.3% / 41.1B
AlphaCode Behavioral Clustering

Filters >99% of millions of samples via example tests and clusters execution outputs on synthetic inputs across 10 Codeforces contests (arXiv:2203.07814v1).

90.2% HE / 75.7% MATH
DeepSeek-Coder-V2 (236B / 21B)

10.2T tokens across 338 languages with MLA & 128K YaRN context; hits 76.2% MBPP+, 73.7% Aider, and 86.4% FIM on 16B/2.4B Lite (arXiv:2406.11931v1).

12.47% / 18.00% Lite
SWE-agent ACI vs 1.31% RAG

100-line viewer, 50-result search cap, and syntax-linted edit guardrail solve 286/2,294 full SWE-bench issues and 87.7% HumanEvalFix (arXiv:2405.15793v3).


1. OpenAI Codex, the 164-Problem HumanEval Benchmark, and the Unbiased Combinatorial Pass@k Estimator (arXiv:2107.03374v2)

In Evaluating Large Language Models Trained on Code (arXiv:2107.03374v2; https://ar5iv.labs.arxiv.org/html/2107.03374), Mark Chen, Jerry Tworek, Heewoo Jun, and colleagues at OpenAI demonstrated that scaling autoregressive Transformer language models on curated public source code unlocks general-purpose program synthesis from natural language docstrings—while exposing why match-based NLP metrics fail to measure algorithmic correctness.

Transformer encoder-decoder and autoregressive attention architecture underpinning modern code foundation models

Transformer encoder-decoder and autoregressive attention architecture underpinning modern code foundation models

1. Corpus Curation Across 54 Million GitHub Repositories and Tokenizer Whitespace Compression

To construct the Codex pre-training corpus in May 2020, OpenAI collected 179 GB of unique Python source files under 1 MB from 54 million public software repositories hosted on GitHub (https://ar5iv.labs.arxiv.org/html/2107.03374, Section 3.1). Because raw repository dumps contain machine-generated serialization files, minified bundles, and data dumps, the pipeline removed any file that satisfied any of four exclusion criteria:

  • Likely auto-generated files identified by header heuristics;
  • Average line length exceeding 100 characters;
  • Maximum single-line length exceeding 1,000 characters; or
  • A low fraction of alphanumeric characters.

After filtering, the final training dataset totaled 159 GB of unique Python code (https://ar5iv.labs.arxiv.org/html/2107.03374, Section 3.1). Crucially, whereas the standard GPT-3 Byte-Pair Encoding (BPE) tokenizer splits every individual space character into a separate token—wasting roughly 30% of the sequence context window on Python's 4-space and 8-space indentation blocks—Codex augmented the GPT-3 vocabulary with dedicated multi-whitespace tokens representing runs of $2, 3, \dots, 24$ consecutive spaces, allowing the model to represent indented Python control flow with ~30% fewer tokens (https://ar5iv.labs.arxiv.org/html/2107.03374, Section 3.2).

2. The 164-Problem HumanEval Benchmark and the Unbiased Combinatorial $\text{pass}@k$ Estimator

Why did OpenAI create HumanEval instead of using existing competitive programming archives from Codeforces or GitHub? Because models trained on 54 million GitHub repositories have already memorized public solutions to older algorithmic contests (for example, more than ten public repositories contained solutions to the APPS benchmark's Codeforces tasks; https://ar5iv.labs.arxiv.org/html/2107.03374, Section 2.2). HumanEval consists of 164 original, hand-written Python programming problems, each containing a function signature, a natural language docstring with input-output examples, a reference body, and an average of 7.7 hidden unit tests per problem executed inside a network-isolated gVisor sandbox (https://ar5iv.labs.arxiv.org/html/2107.03374, Section 2.2).

To evaluate whether a model can synthesize a working program within $k$ attempts (pass@k), early studies generated exactly $k$ samples per problem or estimated empirical success probability $\hat{p} = c / n$ from $n$ samples ($c$ passing) and plugged it into $1 - (1 - \hat{p})^k$. Chen et al. proved that $1 - (1 - \hat{p})^k$ systematically underestimates true $\text{pass}@k$ (byJensen's inequality on the concave function $f(p) = 1 - (1-p)^k$). Instead, drawing $n \ge k$ independent samples per problem (typically $n = 200$) and counting the exact number of correct samples $c$ yields the minimum-variance unbiased combinatorial estimator (https://ar5iv.labs.arxiv.org/html/2107.03374, Section 2.1, Eq. 1):

$$\text{pass}@k := \mathbb{E}{\text{Problems}}\left[1 - \frac{\binom{n - c}{k}}{\binom{n}{k}}\right] = \mathbb{E}{\text{Problems}}\left[1 - \prod_{i = n - c + 1}^{n} \left(1 - \frac{k}{i}\right)\right]$$

Why is the product identity $1 - \prod_{i=n-c+1}^{n} (1 - k/i)$ essential in production evaluation harnesses? Because evaluating factorials $\binom{n-c}{k} / \binom{n}{k}$ directly for $n = 200, k = 100$ overflows 64-bit IEEE floating-point arithmetic, whereas multiplying $c$ ratios $(1 - k/i) \in (0, 1)$ is exact and numerically stable (https://ar5iv.labs.arxiv.org/html/2107.03374, Figure 3).

3. Scaling Laws Across Codex (12M to 12B) and Standalone-Function Fine-Tuning (Codex-S)

Because raw GitHub Python files contain class definitions, configuration scripts, license headers, and non-terminating module imports, base Codex frequently generates extraneous top-level code after completing a function. To align the model with functional synthesis from docstrings, OpenAI curated a supervised fine-tuning (SFT) dataset of standalone, correctly implemented Python functions extracted from competitive programming websites and continuous integration (CI) test suites (pytest and unittest repositories), filtering out functions that failed unit tests or accepted trivial constant solutions—producing Codex-S (https://ar5iv.labs.arxiv.org/html/2107.03374, Section 3.4 & Section 4).

Model Architecture & ScaleParameter CountHumanEval $\text{pass}@1$ (%)HumanEval $\text{pass}@10$ (%)HumanEval $\text{pass}@100$ (%)Training Corpus & Selection Methodology (https://ar5iv.labs.arxiv.org/html/2107.03374)
GPT-3 (All Scales)Up to 175B0.0%0.0%0.0%Standard natural language pre-training without code fine-tuning
GPT-Neo 125M / 1.3B / 2.7B125M / 1.3B / 2.7B0.75% / 4.79% / 6.41%1.88% / 7.47% / 11.27%2.97% / 16.30% / 21.37%Trained on The Pile (~8% GitHub code mixture)
TabNineAutocomplete LM2.58%4.35%7.59%Commercial IDE code completion baseline (Section 3.3)
GPT-J 6B6B11.62% (11.4%)15.74%27.74%Trained on The Pile; falls between Codex-85M and Codex-300M
Codex-12M / 25M / 42M / 85M12M / 25M / 42M / 85M2.00% / 3.21% / 5.06% / 8.22%3.62% / 7.1% / 8.8% / 12.81%8.58% / 12.89% / 15.55% / 22.4%Fine-tuned on 159 GB GitHub Python corpus (Section 3.3 table)
Codex-300M / 679M / 2.5B300M / 679M / 2.5B13.17% / 16.22% / 21.36%20.37% / 25.7% / 35.42%36.27% / 40.95% / 59.5%Log-linear scaling of cross-entropy test loss vs. non-embedding parameters
Codex-12B (Base Code Pre-Training)12B28.81% (28.8%)46.81%72.31% (70.2% @ 100 samples)Solves 70.2% with 100 samples at $\tau = 0.8$ (72.31% unbiased pass@100)
Codex-S-12B (Standalone Function SFT)12B37.7%59.5%+77.5% (44.5% mean log-prob @ 100)Fine-tuned on verified standalone functions + CI test suites (44.5% without test execution)

Crucially, when unit tests are unavailable at inference time, generating 100 samples from Codex-S-12B at temperature $\tau = 0.8$ and ranking them by highest mean token log-probability solves 44.5% of HumanEval (+6.8 percentage points over greedy decoding), whereas heuristics like sum of log-probabilities fail by favoring overly short completions (https://ar5iv.labs.arxiv.org/html/2107.03374, Section 4.2).


2. Fill-in-the-Middle (FIM) Autoregressive Infilling, PSM vs. SPM Transformations, and the FIM-for-Free Property (arXiv:2207.14255v1)

In real software engineering workflows—such as writing a missing try/except block inside an existing method, adding a docstring above a return statement, or completing an import header—the cursor sits between a preceding code block (prefix) and a following code block (suffix). In Efficient Training of Language Models to Fill in the Middle (arXiv:2207.14255v1; https://ar5iv.labs.arxiv.org/html/2207.14255), Mohammad Bavarian, Heewoo Jun, Nikolas Tezak, John Schulman, and colleagues at OpenAI demonstrated how any standard causal decoder-only Transformer can learn conditioned infilling $P(M \mid P, S)$ via a simple data-level permutation without altering the attention mask or architecture.

1. Character-Level Document Splitting and PSM vs. SPM Sentinel Encodings

Why must FIM split a document $D$ into three pieces—Prefix $P$, Middle $M$, and Suffix $S$—at the character level before tokenization rather than splitting token ID arrays after BPE encoding? Because in live IDE use, a user's cursor frequently sits in the middle of an identifier or subword token (or adjacent to indentation spaces that merge with tokens during BPE encoding). Splitting token sequences after BPE tokenization never exposes the model to broken boundary subwords, causing severe likelihood drops when prefix or suffix boundaries split a token at inference time (https://ar5iv.labs.arxiv.org/html/2207.14255, Section 3 & Section 8.1).

With probability $p_{\text{FIM}} \in [0, 1]$ (the FIM rate), each document (or packed context chunk in context-level FIM) is cut at two character positions sampled uniformly at random, yielding character spans $(P, M, S)$, which are independently tokenized and concatenated with three dedicated sentinel tokens (<PRE>, <SUF>, <MID>) in one of two modes (https://ar5iv.labs.arxiv.org/html/2207.14255, Section 3 & Section 3.1):

  1. Prefix-Suffix-Middle (PSM) Mode: $$\text{PSM}(P, M, S) = \texttt{<PRE>} \circ \text{Enc}(P) \circ \texttt{<SUF>} \circ \text{Enc}(S) \circ \texttt{<MID>} \circ \text{Enc}(M) \circ \texttt{<EOT>}$$
  2. Suffix-Prefix-Middle (SPM) Mode: $$\text{SPM}(P, M, S) = \texttt{<PRE>} \circ \texttt{<SUF>} \circ \text{Enc}(S) \circ \texttt{<MID>} \circ \text{Enc}(P) \circ \text{Enc}(M) \circ \texttt{<EOT>}$$

Why did Bavarian et al. formulate SPM mode with <PRE><SUF> Enc(S) <MID> Enc(P) Enc(M) instead of introducing a fourth sentinel token? Because keeping the exact same three sentinels allows maximum cross-transfer between PSM and SPM, while placing $\text{Enc}(P)$ immediately before $\text{Enc}(M)$ ensures that $P$ and $M$ form a single contiguous token sequence during inference—allowing theKV cache of the prefix $P$ and generated middle $M$ to be appended directly without re-encoding if the user continues typing past the infill span (https://ar5iv.labs.arxiv.org/html/2207.14255, Section 3.1 & Appendix D). Importantly, standard causal cross-entropy loss is computed across all three spans ($P$, $S$, and $M$, including the sentinel tokens), so every token in the training batch still contributes gradient signal.

2. The FIM-for-Free Property and Hyperparameter Optimality Across 100B Tokens

Prior infilling models (such as InCoder) assumed that relocating 50% of documents into PSM order would cannibalize standard left-to-right (AR) causal generation capacity, leading earlier work to restrict FIM rates to timid values like $15\%$. Bavarian et al. trained a suite of 8 transformer scales (from 50M to 6.9B parameters) across 100 billion tokens of code and natural language at FIM rates $p_{\text{FIM}} \in \{0\%, 25\%, 50\%, 75\%, 90\%, 100\%\}$ and proved the FIM-for-Free Property (https://ar5iv.labs.arxiv.org/html/2207.14255, Figure 1, Section 4.1, Section 4.2 & Section 8.1):

  • Zero Autoregressive Tax up to 90% FIM Rate: Models pre-trained from scratch with a 50% to 90% FIM rate achieve identical standard left-to-right autoregressive validation loss and identical downstream HumanEval left-to-right $\text{pass}@k$ scores compared to a pure $0\%$ baseline—even though the $50\%$ FIM model observes natural unpermuted left-to-right order only half the time (https://ar5iv.labs.arxiv.org/html/2207.14255, Figure 1 & Section 4.2).
  • Pre-Training vs. Fine-Tuning Asymmetry: While FIM can be learned for free from scratch during pre-training, attempting to bolt FIM onto an already pre-trained left-to-right checkpoint via brief fine-tuning requires substantially higher learning rates and longer token budgets to match native FIM infilling accuracy (https://ar5iv.labs.arxiv.org/html/2207.14255, Section 5).
  • Recommended Production Configuration (Section 8.1): Apply context-level FIM (splitting packed context sequences so <EOT> markers inside long contexts are respected), sample character-level random spans, use a 50%–90% FIM rate, and train jointly with a 50/50 mixture of PSM and SPM (using PSM at inference time for maximal mid-token boundary robustness; https://ar5iv.labs.arxiv.org/html/2207.14255, Section 8.1).

3. AlphaCode, CodeContests False-Positive Reduction, Asymmetric Multi-Query Encoder-Decoder Scaling, and Execution-Filtered Behavioral Clustering (arXiv:2203.07814v1)

While Codex and FIM transformed function-level synthesis and IDE infilling, solving unseen competitive programming problems on platforms like Codeforces—where an agent receives a multi-paragraph narrative problem statement involving graph theory, dynamic programming, or number theory and must emit a full C++ or Python program that passes strict time and memory limits on hidden adversarial edge cases—remained out of reach (<1%–5% solve rates). In Competition-Level Code Generation with AlphaCode (Science 2022 / arXiv:2203.07814v1; https://ar5iv.labs.arxiv.org/html/2203.07814), Yujia Li, David Choi, Junyoung Chung, Nate Kushman, Julian Schrittwieser, Oriol Vinyals, and colleagues at DeepMind combined three breakthroughs to achieve human-competitive performance.

1. Pre-Training on 715.1 GB of GitHub Code and the CodeContests Mutation-Verified Dataset

DeepMind pre-trained AlphaCode on a 715.1 GB snapshot of public GitHub code across 12 major programming languages (C++, Python, Java, C#, C, Go, JavaScript, PHP, Ruby, Rust, Scala, TypeScript), removing files larger than 1 MB or shorter than 100 bytes, lines exceeding 1,000 characters, and whitespace-agnostic duplicate files (https://ar5iv.labs.arxiv.org/html/2203.07814, Section 3.1).

However, existing competitive programming datasets (APPS, Description2Code, CodeNet) suffered from a critical flaw: because Codeforces truncates public test case displays longer than ~400 characters, benchmarks contained far too few hidden tests, resulting in false-positive rates of 30% to 60% (where buggy or brute-force programs passed all benchmark tests) (https://ar5iv.labs.arxiv.org/html/2203.07814, Section 1 & Section 3.2.1). DeepMind curated CodeContests (combining Codeforces, Description2Code, and CodeNet under a strict temporal split so all validation/test contests occurred after the training cutoff) and synthesized up to 200 additional high-coverage test cases per problem by mutating existing test inputs (bit flips, integer increments/decrements, array swaps) and verifying outputs across 30 known-correct human submissions (https://ar5iv.labs.arxiv.org/html/2203.07814, Table 1 & Section 3.2.1):

CodeContests SplitNumber of ProblemsAvg. Example Tests / ProblemAvg. Hidden Tests / ProblemAvg. Generated Mutation TestsAvg. C++ Solutions (% Correct)Avg. Python Solutions (% Correct)Avg. Java Solutions (% Correct)
Train Split13,3282.014.879.1493.4 (27%)281.1 (47%)147.9 (46%)
Validation Split1171.512.9190.0231.6 (47%)137.2 (55%)131.1 (54%)
Test Split1651.79.4192.7196.0 (45%)97.3 (54%)105.2 (51%)

Adding these generated tests slashed the benchmark false-positive rate from 30%–60% down to just 4% (https://ar5iv.labs.arxiv.org/html/2203.07814, Section 1 & Section 3.2.1).

2. Asymmetric Multi-Query Attention (MQA) Encoder-Decoder Architecture Across Scales (300M to 41.1B)

Why did AlphaCode adopt an asymmetric encoder-decoder Transformer (with a shallow bidirectional encoder for the natural language problem description of length 1,536 tokens and a deep causal decoder for the program code of length 768 tokens) paired with Multi-Query Attention (MQA) (sharing KV heads while maintaining full query heads, head size 128, FFN fan-out $6\times$)? Because competitive programming requires sampling $10^5$ to $10^6$ candidate solutions per problem: the encoder processes the 1,536-token problem statement only once, and MQA drastically reduces KV-cache memory bandwidth during massive-batch autoregressive decoding on TPUv4 pods (https://ar5iv.labs.arxiv.org/html/2203.07814, Section 4.1 & Table 3):

Model NameTotal Parameters ($n_{\text{params}}$)Hidden Dim ($d_{\text{model}}$)Query HeadsKV HeadsEncoder BlocksDecoder BlocksBatch SizeUpdate StepsTraining Tokens
AlphaCode 300M284M76861424256600k354B
AlphaCode 1B1.1B14081115302561,000k590B
AlphaCode 3B2.8B2048161636512700k826B
AlphaCode 9B8.7B30722448481024530k1,250B
AlphaCode 41B41.1B614448168562048205k967B

During pre-training, AlphaCode combines standard autoregressive next-token cross-entropy loss on the decoder with Masked Language Modeling (MLM) on the encoder. During CodeContests fine-tuning, it incorporates Tempering (dividing logits by temperature $T = 0.2$ during training to sharpen token distributions and prevent entropy collapse during large-scale sampling), GOLD off-policy importance weighting ($P_\theta(x)\log P_\theta(x)$ to concentrate capacity on high-likelihood modes rather than memorizing noisy human solutions), metadata conditioning (sampling random tags from the top 50, uniform ratings $\in [800, 3500]$, and language C++/Python), and an auxiliary value-conditioning head predicting whether a submission is correct (https://ar5iv.labs.arxiv.org/html/2203.07814, Section 4.2 & Section 4.3).

3. Million-Scale Sampling, >99% Example Filtering, and Behavioral Execution Clustering

In a real Codeforces competition, a participant is penalized for incorrect submissions and evaluated across at most 10 submissions per problem. AlphaCode bridges the gap between $10^6$ stochastic samples and 10 final submissions via a two-stage execution funnel (https://ar5iv.labs.arxiv.org/html/2203.07814, Section 4.4–4.6 & Section 5):

  1. Example-Test Filtering (>99% Reduction): Every generated candidate program is compiled and executed against the 1.5–2.0 public example input-output pairs printed in the problem statement. This step immediately eliminates more than 99% of invalid or syntactically broken samples, though thousands of passing candidates still remain (many of which handle only trivial cases).
  2. Behavioral Execution Clustering on Model-Generated Test Inputs: A separate neural model (same architecture as AlphaCode, trained to generate valid, challenging test inputs from problem descriptions) synthesizes new test inputs. All surviving candidate programs are executed on these synthetic inputs and grouped into equivalence clusters based on identical execution outputs. Why? Because correct algorithms agree with one another on valid test inputs and coalesce into the largest equivalence clusters, whereas buggy programs fail in divergent ways and scatter into tiny singleton clusters! AlphaCode selects one canonical program from each of the top 10 largest clusters (round-robin from largest to smallest).

Across the held-out CodeContests test split (165 problems), the ensemble of AlphaCode 41B + 9B solves 34.2% of problems within 10 submissions (10@1M) (https://ar5iv.labs.arxiv.org/html/2203.07814, Section 1 & Section 5.2). In simulated live evaluations across 10 recent Codeforces competitions with >5,000 human participants, AlphaCode achieved an overall average ranking in the top 54.3% (reaching top 20.9% in Contest 10, with an estimated Codeforces Elo rating of 1238, placing it in the top 28% of all users who competed in the prior 6 months; https://ar5iv.labs.arxiv.org/html/2203.07814, Table 4 & Section 5.1).


4. StarCoder2, The Stack v2 Software Heritage Archive (619 Languages), Grouped-Query Sliding-Window Attention, and Repository-Context Pre-Training (arXiv:2402.19173v1)

To establish a fully open, auditable, and license-compliant foundation for code intelligence, the BigCode collaboration (ServiceNow, Hugging Face, NVIDIA, and Software Heritage) introduced StarCoder2 and The Stack v2 in StarCoder 2 and The Stack v2: The Next Generation (arXiv:2402.19173v1; https://arxiv.org/html/2402.19173v1).

1. The Stack v2 on the Software Heritage (SWH) Digital Commons Across 619 Languages

Built atop the persistent SoftWare Hash IDentifiers (SWHIDs) of the Software Heritage archive (2023-09-06 graph snapshot), The Stack v2 expands training data volume to $4\times$ the size of the original StarCoder corpus (https://arxiv.org/html/2402.19173v1, Abstract & Section 2). After language detection via go-enry (identifying 658 languages and excluding 39 noisy/data extensions), MinHash Locally Sensitive Hashing (LSH) near-deduplication (prioritizing repositories with higher star/fork counts and recent commits), long-line filtering (>100k lines or avg >100 / max >1,000 chars), opt-out removal (22,066 files across 91 users/orgs), malware removal, benchmark decontamination, and StarPII redaction (anonymizing names, API keys, emails, IP addresses, and conversation usernames into username_0, username_1), the final source code archive spans 619 programming languages (https://arxiv.org/html/2402.19173v1, Section 2 & Section 3). Across the 32 most popular languages alone (Table 1), The-stack-v2-dedup scales from 875.85 GB (181.00M files) in The Stack v1 to 6,457.14 GB (784.30M files) (1,922.82 GB / 528.44M files in The-stack-v2-swh-full), augmented with 3.3M GitHub pull requests (67.3 GB capped at 100K chars), GitHub issues, Jupyter and Kaggle notebooks, StackExchange threads, OpenWebMath, and LLVM/assembly intermediate representations (<code_to_intermediate>).

Furthermore, to teach cross-file dependency resolution, StarCoder2 groups files by repository: with 50% probability, files from the same repository are concatenated using <repo_name>, <file_sep>, and filepath headers arranged in a random breadth-first or depth-first directory traversal order, trained jointly with a 50% context-level FIM rate (https://arxiv.org/html/2402.19173v1, Section 4 & Section 5.1).

2. StarCoder2 Model Family (3B, 7B, 15B), Two-Stage 4K-SWA to 16K Long-Context Training, and EvalPlus Benchmarks

StarCoder2 replaces learned positional embeddings and Multi-Query Attention with Rotary Positional Encodings (RoPE) and Grouped-Query Attention (GQA), maintaining a byte-level BPE vocabulary of 49,152 tokens (https://arxiv.org/html/2402.19173v1, Section 6.1–6.3, Table 6, Table 7, Table 8 & Table 9). Base pre-training runs at sequence length 4,096 with Sliding Window Attention (SWA, window 4,096) for 1.0M–1.2M iterations, followed by a 200B-token long-context stage that removes the sliding window to enable 16,384-token full attention via FlashAttention-2 while scaling the RoPE base period $\theta$ by $10\times$:

Architecture & Benchmark MetricStarCoder2-3BStarCoder2-7BStarCoder2-15BReference Comparison (CodeLlama-34B / DeepSeekCoder-33B)
Hidden Dimension / Layers3,072 / 30 layers4,608 / 32 layers6,144 / 40 layersVocabulary size 49,152 tokens across all three scales (Table 6)
Query Heads / GQA KV Heads24 Query / 2 KV36 Query / 4 KV48 Query / 4 KVLow KV head counts preserve high-throughput autoregressive decoding
Base Training (4K SWA) + Long-Context (16K Full)3.1T ($\theta=10^5$) + 200B ($\theta=10^6$) = 3.3T tokens3.5T ($\theta=10^5$) + 200B ($\theta=10^6$) = 3.7T tokens4.1T ($\theta=10^4$) + 200B ($\theta=10^5$) = 4.3T tokensMulti-epoch Chinchilla over-training (4.98 / 5.31 / 4.49 epochs, Table 7 & 8)
Total Compute ($6ND$ FLOPs) & Hardware$5.94 \times 10^{22}$ FLOPs (97,120 A100-80GB hrs)$1.55 \times 10^{23}$ FLOPs (145,152 H100 hrs)$3.87 \times 10^{23}$ FLOPsEstimated $\text{CO}_2$: 16,107.01 $\text{kgCO}_2\text{eq}$ (3B) / 29,622.83 $\text{kgCO}_2\text{eq}$ (7B)
HumanEval / HumanEval+ ($80\times$ tests) Pass@131.7% / 27.4%35.4% / 29.9%46.3% / 37.8%StarCoderBase-15B: 29.3% / 25.6%; CodeLlama-34B: 48.2% / 44.3% (Table 9)
MBPP / MBPP+ ($35\times$ tests) Pass@157.4% / 47.4%54.4% / 45.6%66.2% / 53.1%StarCoder2-3B beats StarCoderBase-15B (50.6%/43.6%); 15B beats CodeLlama-34B (65.4%/52.4%)

Notice the dramatic Chinchilla-overtraining efficiency in Table 9 (https://arxiv.org/html/2402.19173v1): StarCoder2-3B (31.7% HumanEval, 57.4% MBPP) outperforms the $5\times$ larger first-generation StarCoderBase-15B (29.3% HumanEval, 50.6% MBPP), while StarCoder2-15B matches or surpasses CodeLlama-34B (a model more than twice its size) on MBPP (66.2% vs. 65.4%) and MBPP+ (53.1% vs. 52.4%).


5. DeepSeek-Coder-V2, 10.2T-Token MoE Code Intelligence Across 338 Languages, YaRN 128K Context, and Open-vs-Closed Frontier Benchmarks (arXiv:2406.11931v1)

Can an open-source Mixture-of-Experts (MoE) code foundation model close the performance gap with proprietary frontier models (GPT-4-Turbo, Claude 3 Opus, Gemini 1.5 Pro) across both multilingual software engineering and competition-level mathematical reasoning? In DeepSeek-Coder-V2: Breaking the Barrier of Closed-Source Models in Code Intelligence (arXiv:2406.11931v1; https://arxiv.org/html/2406.11931v1), DeepSeek-AI demonstrated how combining Multi-Head Latent Attention (MLA) and DeepSeekMoE with a 10.2-trillion-token code-and-math training curriculum breaks the closed-source barrier.

1. Continued Pre-Training on 10.2 Trillion Tokens Across 338 Languages and 128K YaRN Context Extension

Rather than initializing from random weights, DeepSeek-Coder-V2 continues pre-training from an intermediate checkpoint of DeepSeek-V2 (already trained on 4.2 trillion tokens) by adding 6 trillion additional tokens—bringing total pre-training exposure to 10.2 trillion (10.2T) high-quality tokens (https://arxiv.org/html/2406.11931v1, Abstract & Section 3.3, Table 2). The 6T continued pre-training mixture is composed of:

  • 60% Source Code (1,170B unique code-related tokens) sourced from GitHub and CommonCrawl via fastText classifier recall pipelines, expanding language coverage from 86 to 338 programming languages (Table 1 shows that pre-training a 1B ablation model on 1T tokens of the new corpus boosts Python HumanEval from 30.5% to 36.0% and MBPP from 44.6% to 49.0%, rising to 37.2% and 54.0% at 2T tokens);
  • 10% Mathematical Reasoning Corpus collected from CommonCrawl; and
  • 30% General Natural Language Corpus sampled directly from the DeepSeek-V2 pool to preserve general reasoning and instruction-following capabilities (https://arxiv.org/html/2406.11931v1, Section 2).

DeepSeek-Coder-V2 is released in two MoE scales (Table 2):

  1. DeepSeek-Coder-V2-Lite (16B Total Parameters / 2.4B Active Parameters): Trained with both Next-Token-Prediction and 50% PSM Fill-in-the-Middle (FIM) (<|fim_begin|> f_pre <|fim_hole|> f_suf <|fim_end|> f_middle <|eos_token|>), achieving an average single-line infilling exact-match accuracy of 86.4% across Python (80.0%), Java (89.1%), and JavaScript (87.2%) (Table 6), matching the $13.7\times$-more-active-parameter DeepSeek-Coder-Base 33B (86.4%) and outperforming Codestral-22B (83.0%) and StarCoder-16B (80.2%).
  2. DeepSeek-Coder-V2 (236B Total Parameters / 21B Active Parameters): Trained with Next-Token-Prediction and extended to a 128K-token context window via two-stage YaRN (scale $s = 40, \alpha = 1, \beta = 32$: 1,000 steps at 32K sequence length with batch size 1,152, followed by 1,000 steps at 128K sequence length with batch size 288), followed by 40K-sample reinforcement learning alignment (GRPO) with compiler and test-case execution reward models (https://arxiv.org/html/2406.11931v1, Section 3.4 & Section 3.5).

2. Comprehensive Empirical Comparison: Open-Weights vs. Closed-Source Frontier Models

Across Tables 3, 4, 7, 8, 9, and 10 of arXiv:2406.11931v1 (https://arxiv.org/html/2406.11931v1), DeepSeek-Coder-V2-Instruct (236B / 21B active) matches or surpasses proprietary frontier models while activating only 21B parameters per token:

Benchmark & Evaluation MetricDeepSeek-Coder-V2-Lite-Instruct (16B / 2.4B)DeepSeek-Coder-V2-Instruct (236B / 21B)Codestral-22B (22B Dense)Llama-3-70B-Instruct (70B Dense)Claude-3-Opus (Closed)GPT-4-Turbo-0409 (Closed)GPT-4o-0513 (Closed)
Python HumanEval (Pass@1)81.1%90.2%78.1%81.1%84.2%88.2%91.0%
Multilingual HumanEval (C++ / Java / JS / Rust)75.8% / 76.6% / 77.6% / 62.2%84.8% / 82.3% / 84.5% / 78.2%71.4% / 71.5% / 73.9% / 67.3%64.0% / 67.7% / 70.2% / 58.3%81.4% / 78.5% / 75.8% / 71.2%78.3% / 81.7% / 80.8% / 78.8%87.0% / 80.4% / 87.6% / 80.1%
MBPP+ ($35\times$ Extended Unit Tests)68.8%76.2%68.2%68.8%72.0%72.2%73.5%
14-Language HumanEval + MBPP+ Average65.6%75.3%63.2%60.6%70.8%72.3%76.4%
LiveCodeBench (1201–0601 Overall / Easy / Med / Hard)24.3% (58.5 / 8.0 / 0.0%)43.4% (84.1 / 29.9 / 5.3%)31.0%28.7%34.6%45.7%43.4%
USACO (307 Olympiad Problems)6.5%12.1%4.6%3.3%7.8%12.3%18.8%
Software Repair: Aider (133 Tasks) / Defects4J / SWE-bench44.4% / 9.2% / 0.0%73.7% / 21.0% / 12.7%51.1% / 17.8% / 2.7%49.2% / 16.2% / —68.4% / 25.5% / 11.7%63.9% / 24.3% / 18.3%72.9% / 26.1% / 26.7%
Math: GSM8K / MATH / AIME 2024 / Math Odyssey86.4% / 61.8% / 0/30 / 44.4%94.9% / 75.7% / 4/30 (5/30 maj@64) / 53.7%—93.0% / 50.4% / 1/30 / 27.9%95.0% / 60.1% / 2/30 / 40.6%93.7% / 73.4% / 3/30 / 46.8%95.8% / 76.6% / 2/30 / 53.2%

6. SWE-bench (2,294 Real-World GitHub Issues) and SWE-agent Agent-Computer Interfaces (ACI) for Autonomous Repository Engineering (arXiv:2310.06770v3, arXiv:2405.15793v3)

As function-level synthesis benchmarks like HumanEval approached saturation (>90% pass@1), Carlos E. Jimenez, John Yang, Alexander Wettig, Yao, Narasimhan, and Ofir Press at Princeton University introduced SWE-bench (SWE-bench: Can Language Models Resolve Real-World GitHub Issues?, ICLR 2024 / arXiv:2310.06770v3; https://arxiv.org/html/2310.06770v3) and SWE-agent (SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering, NeurIPS 2024 / arXiv:2405.15793v3; https://arxiv.org/html/2405.15793v3).

SWE-bench evaluation pipeline connecting real GitHub issues and pull requests across Python repositories to FAIL_TO_PASS and PASS_TO_PASS execution test suites

SWE-bench evaluation pipeline connecting real GitHub issues and pull requests across Python repositories to FAIL_TO_PASS and PASS_TO_PASS execution test suites

1. Construction of SWE-bench Across 93,139 Crawled Pull Requests and 12 Python Repositories

Unlike self-contained docstring prompts, a task instance in SWE-bench provides an issue description (averaging 195 words) and a complete repository snapshot at the base commit prior to the fix. To construct SWE-bench, Jimenez et al. crawled 93,139 pull requests across 12 widely used open-source Python repositories, filtered down to 11,407 candidate instances whose PRs resolved a linked GitHub issue and modified at least one test file, and executed every candidate inside an isolated Conda container to verify two strict execution invariants (https://arxiv.org/html/2310.06770v3, Section 2.1 & Appendix A.2, Table 10):

  1. FAIL_TO_PASS Validation: At least one test added or modified by the PR must fail on the pre-PR base codebase and pass after applying the PR's gold code patch.
  2. PASS_TO_PASS Regression Prevention: All existing tests that passed prior to the patch must continue to pass without regression.

This execution filter eliminated nearly 80% of candidate PRs, leaving 2,294 verified real-world software engineering tasks (plus a curated 300-instance SWE-bench Lite subset):

  • django/django: 16,914 PRs crawled $\to$ 2,880 post-conversion $\to$ 850 final verified tasks
  • sympy/sympy: 11,928 PRs crawled $\to$ 1,897 post-conversion $\to$ 386 final verified tasks
  • scikit-learn/scikit-learn: 15,159 PRs crawled $\to$ 1,169 post-conversion $\to$ 229 final verified tasks
  • sphinx-doc/sphinx: 4,931 PRs crawled $\to$ 645 post-conversion $\to$ 187 final verified tasks
  • matplotlib/matplotlib: 16,545 PRs crawled $\to$ 1,057 post-conversion $\to$ 184 final verified tasks
  • pytest-dev/pytest: 5,147 PRs crawled $\to$ 750 post-conversion $\to$ 119 final verified tasks
  • pydata/xarray: 3,416 PRs crawled $\to$ 812 post-conversion $\to$ 110 final verified tasks
  • astropy/astropy: 9,469 PRs crawled $\to$ 1,016 post-conversion $\to$ 95 final verified tasks
  • pylint-dev/pylint: 3,848 PRs crawled $\to$ 787 post-conversion $\to$ 57 final verified tasks
  • psf/requests: 2,344 PRs crawled $\to$ 84 post-conversion $\to$ 44 final verified tasks
  • mwaskom/seaborn: 1,004 PRs crawled $\to$ 203 post-conversion $\to$ 22 final verified tasks
  • pallets/flask: 2,434 PRs crawled $\to$ 107 post-conversion $\to$ 11 final verified tasks

When evaluated in a non-interactive Retrieval-Augmented Generation (BM25 RAG) pipeline, state-of-the-art language models failed almost completely (https://arxiv.org/html/2310.06770v3, Table 5): ChatGPT-3.5 solved 0.17%, SWE-Llama 7B / 13B solved 0.70%, GPT-4 Turbo solved 1.31% (2.67% Lite), Claude 2 solved 1.96%–1.97% (3.00% Lite, and only 4.8% even when given an Oracle file retriever), and Claude 3 Opus solved 3.79% (4.33% Lite).

🎥 Architectural Deep-Dive: SWE-bench: The AI Coding Benchmark Every Dev Must Know (Better Stack) — walking through repository-level patch synthesis, FAIL_TO_PASS / PASS_TO_PASS execution verification, and why repository navigation requires interactive agent loops.

2. SWE-agent and the Four Pillars of Agent-Computer Interface (ACI) Design

Why do language models perform poorly when given a raw Linux bash terminal (Shell-only agent)? In arXiv:2405.15793v3 (https://arxiv.org/html/2405.15793v3, Section 2 & Section 3), Yang et al. posited that human User Interfaces (VSCode, vim, raw bash + grep + sed) are mismatched to the cognitive constraints of stateless autoregressive Transformers. Specifically, raw grep queries dump thousands of matching lines that overflow the context window, printing entire 3,000-line Python files degrades attention localization, and constructing non-interactive sed or unified diff patches frequently introduces indentation or syntax errors that cascade across subsequent turns.

SWE-agent introduces a purpose-built Agent-Computer Interface (ACI) governed by four empirically ablated components (https://arxiv.org/html/2405.15793v3, Section 3 & Section 5, Table 1, Table 2 & Table 3):

  1. 100-Line Windowed File Viewer (open, scroll_down, scroll_up, goto): Instead of cat-ing entire files or tiny snippets, open <path> renders a 100-line viewport displaying explicit line numbers, the full filepath, total lines in the file, and the exact count of lines omitted above and below. Ablating the viewport on SWE-bench Lite proves that 100 lines achieves 18.0% resolution, whereas shrinking the window to 30 lines drops performance to 14.3% ($\downarrow 3.7\%$) and displaying the full file drops performance to 12.7% ($\downarrow 5.3\%$) (Table 3).
  2. Summarized Repository Search Capped at 50 Results (find_file, search_file, search_dir): Search commands return concise line/file summaries but enforce a strict 50-result ceiling: if a query matches $>50$ hits, the ACI suppresses the output entirely and instructs the agent to narrow its search query. Summarized search achieves 18.0% on SWE-bench Lite, compared to 12.0% ($\downarrow 6.0\%$) for iterative multi-step cursor search and 15.7% ($\downarrow 2.3\%$) without custom search commands (Table 3).
  3. Line-Range File Editor with Built-In Syntax Linter Guardrail (edit <start>:<end>): The agent replaces lines $s$ through $e$ of the currently open file in a single atomic action: $$\texttt{edit } s:e \;\backslash\text{n}\; \langle\text{replacement text}\rangle \;\backslash\text{n}\; \texttt{end\_of\_edit}$$ Immediately upon execution, the ACI runs a static code syntax linter on the modified buffer. If the edit introduces any syntax or indentation error, the ACI automatically discards the invalid edit, displays a before/after snippet pinpointing the linter error, and prompts the agent to retry. Removing the linter guardrail drops SWE-bench Lite accuracy from 18.0% to 15.0% ($\downarrow 3.0\%$), while removing the edit command altogether (No edit, forcing raw bash file manipulation) collapses accuracy to 10.3% ($\downarrow 7.7\%$) (Table 3).
  4. Rolling 5-Observation Context Folding: To keep the ReAct trajectory concise over 20–40 turns, all environment observations prior to the last 5 steps are collapsed into single-line action summaries. Maintaining only the last 5 full observations achieves 18.0%, outperforming raw full history retention at 15.0% ($\downarrow 3.0\%$) (Table 3).
System Configuration & Interface ParadigmSWE-bench Full (2,294 Tasks) % ResolvedSWE-bench Full Avg. Cost ($)SWE-bench Lite (300 Tasks) % ResolvedSWE-bench Lite Avg. Cost ($)HumanEvalFix Pass@1 (Python / JS / Java)
RAG (BM25 Non-Interactive) w/ GPT-4 Turbo1.31%$0.132.67%$0.13GPT-4 baseline: 47.0% / 48.2% / 50.0%
RAG (BM25 Non-Interactive) w/ Claude 3 Opus3.79%$0.254.33%$0.25Non-interactive single-pass patch generation
Shell-Only Agent (Default Linux Bash, No ACI) w/ GPT-4 Turbo——11.00% (7.33% w/o demo)$1.46 ($0.79)Raw Linux shell without windowed viewer or linted editor
SWE-agent (ACI) w/ Claude 3 Opus10.46%$2.5913.00%$2.18Demonstrates cross-model ACI portability (Table 1)
SWE-agent (ACI) w/ GPT-4 Turbo12.47% (286 / 2,294)$1.5918.00% (54 / 300)$1.6787.7% Python / 89.7% JS / 87.9% Java (Table 1 & 2)

7. Reference Python Implementation: Unbiased Pass@k Estimator, Character-Level PSM/SPM FIM Transformation, and Syntax-Guarded ACI File Editor

The following self-contained Python 3 reference module implements the three core algorithmic primitives analyzed in this guide:

  1. OpenAI Codex's numerically stable unbiased $\text{pass}@k$ estimator (arXiv:2107.03374v2, Section 2.1, Eq. 1 & Figure 3);
  2. OpenAI's character-level Fill-in-the-Middle (FIM) PSM and SPM span transformer (arXiv:2207.14255v1, Section 3); and
  3. Princeton SWE-agent's 100-line windowed file viewer and AST syntax-linted edit <start>:<end> ACI guardrail (arXiv:2405.15793v3, Section 3) that automatically rolls back syntax-corrupting edits.
from __future__ import annotations

import ast
import random
from dataclasses import dataclass
from typing import Literal, Sequence
import numpy as np

def estimate_unbiased_pass_at_k(
    num_samples: Sequence[int] | int,
    num_correct: Sequence[int],
    k: int,
) -> float:
    """Compute the minimum-variance unbiased pass@k estimator (Chen et al., arXiv:2107.03374v2 Eq. 1).

    Evaluates E[1 - C(n - c, k) / C(n, k)] via the numerically stable product:
        1.0 - prod_{i = n - c + 1}^{n} (1.0 - k / i)
    to prevent factorial overflow when n >= 100.
    """
    if isinstance(num_samples, int):
        n_arr = [num_samples] * len(num_correct)
    else:
        n_arr = list(num_samples)

    def _single_problem(n: int, c: int) -> float:
        if n < k:
            raise ValueError(f"Total samples n={n} must be >= k={k}")
        if n - c < k:
            return 1.0
        # Product over i in [n - c + 1, ..., n] of (1.0 - k / i)
        denominator = np.arange(n - c + 1, n + 1, dtype=np.float64)
        return float(1.0 - np.prod(1.0 - float(k) / denominator))

    scores = [_single_problem(n, c) for n, c in zip(n_arr, num_correct)]
    return float(np.mean(scores))

def apply_character_level_fim(
    document: str,
    fim_rate: float = 0.5,
    mode: Literal["PSM", "SPM", "JOINT"] = "JOINT",
    rng: random.Random | None = None,
) -> str:
    """Apply character-level Fill-in-the-Middle (FIM) transformation (Bavarian et al., arXiv:2207.14255v1 Sec. 3).

    Splits document into character spans (Prefix P, Middle M, Suffix S) prior to BPE tokenization
    to preserve mid-token boundary robustness at inference time.
    """
    gen = rng or random.Random()
    if gen.random() >= fim_rate or len(document) < 3:
        return document + "<|endoftext|>"

    c1, c2 = sorted(gen.sample(range(len(document) + 1), 2))
    prefix, middle, suffix = document[:c1], document[c1:c2], document[c2:]

    chosen_mode = gen.choice(["PSM", "SPM"]) if mode == "JOINT" else mode
    if chosen_mode == "PSM":
        return f"<|fim_prefix|>{prefix}<|fim_suffix|>{suffix}<|fim_middle|>{middle}<|endoftext|>"
    # SPM mode keeps Prefix and Middle contiguous for KV-cache reuse
    return f"<|fim_prefix|><|fim_suffix|>{suffix}<|fim_middle|>{prefix}{middle}<|endoftext|>"

@dataclass(frozen=True)
class SWEAgentACIView:
    """Immutable 100-line windowed viewport state for SWE-agent ACI (Yang et al., arXiv:2405.15793v3 Sec. 3)."""

    filepath: str
    lines: tuple[str, ...]
    cursor_top: int = 1
    window_size: int = 100

    def render_window(self) -> str:
        """Render at most window_size (100) lines with explicit line numbers and omission headers."""
        total = len(self.lines)
        start_idx = max(0, min(self.cursor_top - 1, max(0, total - 1)))
        end_idx = min(total, start_idx + self.window_size)
        omitted_above = start_idx
        omitted_below = max(0, total - end_idx)

        header = f"[File: {self.filepath} ({total} lines total)]"
        above_msg = f"({omitted_above} more lines above)" if omitted_above > 0 else "(top of file)"
        body = "\n".join(f"{idx + 1}:{self.lines[idx]}" for idx in range(start_idx, end_idx))
        below_msg = f"({omitted_below} more lines below)" if omitted_below > 0 else "(end of file)"
        return f"{header}\n{above_msg}\n{body}\n{below_msg}"

    def linted_edit(
        self,
        start_line: int,
        end_line: int,
        replacement_block: str,
    ) -> tuple[SWEAgentACIView, bool, str]:
        """Replace 1-indexed lines [start_line, end_line] with AST syntax-linter rollback guardrail."""
        if start_line < 1 or end_line < start_line or end_line > len(self.lines):
            return self, False, f"Invalid line range {start_line}:{end_line} for file of {len(self.lines)} lines."

        new_middle = tuple(replacement_block.splitlines())
        candidate_lines = self.lines[: start_line - 1] + new_middle + self.lines[end_line:]
        candidate_source = "\n".join(candidate_lines)

        try:
            ast.parse(candidate_source, filename=self.filepath)
        except SyntaxError as exc:
            error_msg = (
                f"Your edit introduced a syntax error at line {exc.lineno}: {exc.msg}. "
                "Invalid edit was automatically discarded; please inspect the window and retry."
            )
            return self, False, error_msg

        new_top = max(1, start_line - 10)
        updated_view = SWEAgentACIView(
            filepath=self.filepath,
            lines=candidate_lines,
            cursor_top=new_top,
            window_size=self.window_size,
        )
        return updated_view, True, f"File updated successfully.\n{updated_view.render_window()}"

if __name__ == "__main__":
    # 1. Verify Codex Unbiased pass@k Estimator
    pass1 = estimate_unbiased_pass_at_k(num_samples=200, num_correct=[58, 0, 200, 34], k=1)
    pass100 = estimate_unbiased_pass_at_k(num_samples=200, num_correct=[58, 0, 200, 34], k=100)

    # 2. Verify Character-Level PSM & SPM Fill-in-the-Middle
    rng = random.Random(42)
    sample_code = "def clamp(x: float, lo: float, hi: float) -> float:\n    return max(lo, min(x, hi))"
    fim_psm = apply_character_level_fim(sample_code, fim_rate=1.0, mode="PSM", rng=rng)
    fim_spm = apply_character_level_fim(sample_code, fim_rate=1.0, mode="SPM", rng=rng)
    assert "<|fim_prefix|>" in fim_psm and "<|fim_prefix|><|fim_suffix|>" in fim_spm

    # 3. Verify SWE-agent ACI Linted Edit Guardrail (rejects broken syntax, accepts valid patch)
    view = SWEAgentACIView(
        filepath="sklearn/decomposition/_kernel_pca.py",
        lines=("def fit_transform(X):", "    vals = compute_svd(X)", "    return vals"),
    )
    view_after_bad, ok_bad, msg_bad = view.linted_edit(2, 2, "    vals = compute_svd(X")
    assert not ok_bad and view_after_bad.lines == view.lines
    view_after_good, ok_good, _ = view.linted_edit(2, 2, "    vals = svd_flip(compute_svd(X))")
    assert ok_good and "svd_flip" in view_after_good.lines[1]
    print(f"Verified Unbiased pass@1={pass1:.4f}, pass@100={pass100:.4f} | Linter Rollback: {not ok_bad}")

8. Frequently Asked Questions (FAQ): Code Foundation Models, FIM, AlphaCode, and SWE-agent ACIs

Why is the naive empirical formula $1 - (1 - \hat{p})^k$ biased for evaluating code generation, and how does OpenAI Codex's combinatorial $\text{pass}@k$ estimator solve it? In Evaluating Large Language Models Trained on Code (https://ar5iv.labs.arxiv.org/html/2107.03374, Section 2.1, Eq. 1 & Figure 3), if a benchmark draws $n$ samples for a problem and observes $c$ unit-test passes ($\hat{p} = c / n$), plugging $\hat{p}$ into $1 - (1 - \hat{p})^k$ systematically underestimates true $\text{pass}@k$ because $f(p) = 1 - (1-p)^k$ is strictly concave for $k > 1$ (so $\mathbb{E}[f(\hat{p})] < f(p)$ by Jensen's inequality). Evaluating $\text{pass}@k = \mathbb{E}[1 - \binom{n-c}{k}/\binom{n}{k}] = \mathbb{E}[1 - \prod_{i=n-c+1}^{n}(1 - k/i)]$ across $n = 200$ samples per problem provides an exact, minimum-variance unbiased estimate at all $k \le n$ without factorial floating-point overflow.

Why must Fill-in-the-Middle (FIM) split documents at the character level before BPE tokenization, and what is the FIM-for-free property? In arXiv:2207.14255v1 (https://ar5iv.labs.arxiv.org/html/2207.14255, Section 3, Section 4.2 & Section 8.1), splitting a file after Byte-Pair Encoding (BPE) tokenization guarantees that every prefix $P$ and suffix $S$ ends and begins cleanly on an existing subword token boundary. In real IDE use, however, a developer's cursor often sits inside an identifier or adjacent to whitespace that merges across subwords during BPE encoding—causing token-level FIM models to fail on mid-token boundaries. Splitting at the character level before BPE tokenization exposes the model to arbitrary subword boundary splits during training. Moreover, across 100B tokens of pre-training, joint FIM training at a 50%–90% FIM rate incurs zero degradation to standard left-to-right causal test loss or downstream HumanEval $\text{pass}@1$ (the FIM-for-free property).

How did AlphaCode reduce competitive programming benchmark false positives from 30%–60% down to 4% and narrow millions of samples to 10 submissions? In arXiv:2203.07814v1 (https://ar5iv.labs.arxiv.org/html/2203.07814, Section 3.2.1 & Section 4.5–4.6), public competitive programming platforms truncate displayed test cases longer than ~400 characters, leaving existing datasets with weak test coverage where 30% to 60% of passing submissions are actually buggy (false positives) or algorithmically too slow (slow positives). When building CodeContests (13,328 train / 117 valid / 165 test problems), DeepMind synthesized up to 200 additional test inputs per problem by mutating existing inputs and verifying output agreement across 30 correct human submissions, slashing the false-positive rate to 4%. At inference time, AlphaCode generates millions of C++/Python candidates, filters out >99% using the problem's public example tests, executes the survivors on synthetic test inputs generated by a separate model, and clusters candidates by identical execution outputs—selecting 1 submission from each of the 10 largest behavioral clusters to rank in the top 54.3% across 10 Codeforces contests.

How does StarCoder2 scale context length from 4,096 to 16,384 tokens and why does StarCoder2-3B outperform the $5\times$ larger StarCoderBase-15B? In arXiv:2402.19173v1 (https://arxiv.org/html/2402.19173v1, Section 6.1–6.3 & Table 9), StarCoder2-3B is trained on 3.3 trillion tokens (4.98 epochs over the-stack-v2-train-smol), more than $3\times$ the 1T-token budget of first-generation StarCoderBase-15B, while upgrading from learned positional embeddings and MQA to RoPE and Grouped-Query Attention (GQA). As a result, StarCoder2-3B achieves 31.7% on HumanEval and 57.4% on MBPP, outperforming StarCoderBase-15B (29.3% and 50.6%). All three StarCoder2 models pre-train at sequence length 4,096 with Sliding Window Attention (SWA) ($\theta = 10^5$ for 3B/7B) before undergoing a 200B-token long-context fine-tuning stage that switches to 16,384-token full attention with FlashAttention-2 and a $10\times$ higher RoPE base period ($\theta = 10^6$).

How does DeepSeek-Coder-V2 achieve GPT-4-Turbo-level code and math performance while activating only 21B parameters per token? In arXiv:2406.11931v1 (https://arxiv.org/html/2406.11931v1, Section 2, Section 3 & Tables 2–9), DeepSeek-Coder-V2 continues pre-training from a 4.2T-token DeepSeek-V2 checkpoint (which combines Multi-Head Latent Attention MLA and fine-grained DeepSeekMoE with 236B total / 21B active parameters) on an additional 6 trillion tokens (10.2T total tokens: 60% source code across 338 languages, 10% math, 30% natural language) and extends context to 128K tokens via two-stage YaRN ($s=40, \alpha=1, \beta=32$). This joint code-and-math curriculum enables DeepSeek-Coder-V2-Instruct to achieve 90.2% Python HumanEval, 76.2% MBPP+, 75.3% 14-language average, 43.4% LiveCodeBench, 73.7% Aider code editing, 94.9% GSM8K, and 75.7% MATH.

Why does SWE-agent's Agent-Computer Interface (ACI) outperform both RAG and a raw Linux shell agent on SWE-bench? In arXiv:2310.06770v3 and arXiv:2405.15793v3 (https://arxiv.org/html/2310.06770v3, https://arxiv.org/html/2405.15793v3, Table 1 & Table 3), non-interactive BM25 RAG with GPT-4 Turbo resolves only 1.31% of full SWE-bench (2.67% Lite) because static retrieval fails to localize cross-file causal chains and cannot verify edits against tests. Giving GPT-4 Turbo a raw Linux bash shell (Shell-only agent) reaches 11.00% on SWE-bench Lite, but suffers from context flooding and broken sed/diff edits. SWE-agent's custom ACI boosts GPT-4 Turbo to 18.00% on SWE-bench Lite (a 64% relative gain over Shell-only) and 12.47% (286 / 2,294) on full SWE-bench by combining a 100-line windowed file viewer (18.0% vs. 12.7% full-file), search commands capped at 50 results (18.0% vs. 12.0% iterative), rolling 5-observation context folding (18.0% vs. 15.0% full history), and a syntax-linted edit <start>:<end> guardrail that automatically rejects syntax-corrupting edits (18.0% vs. 15.0% unlinted and 10.3% without edit).


9. Primary Technical Sources & Foundations

  1. Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Jared Kaplan, Wojciech Zaremba et al. (OpenAI) — Evaluating Large Language Models Trained on Code (Codex & HumanEval) (arXiv:2107.03374v2 Full Experimental HTML): https://ar5iv.labs.arxiv.org/html/2107.03374
  2. Mark Chen et al. (OpenAI) — Evaluating Large Language Models Trained on Code (arXiv:2107.03374 Official Abstract & Metadata Repository): https://arxiv.org/abs/2107.03374
  3. Mohammad Bavarian, Heewoo Jun, Nikolas Tezak, John Schulman, Christine McLeavey, Wojciech Zaremba, Mark Chen (OpenAI) — Efficient Training of Language Models to Fill in the Middle (FIM) (arXiv:2207.14255v1 Full Experimental HTML): https://ar5iv.labs.arxiv.org/html/2207.14255
  4. Mohammad Bavarian et al. (OpenAI) — Efficient Training of Language Models to Fill in the Middle (arXiv:2207.14255 Official Abstract & Metadata Repository): https://arxiv.org/abs/2207.14255
  5. Yujia Li, David Choi, Junyoung Chung, Nate Kushman, Julian Schrittwieser, Rémi Leblond, Tom Eccles, Pushmeet Kohli, Nando de Freitas, Koray Kavukcuoglu, Oriol Vinyals et al. (DeepMind) — Competition-Level Code Generation with AlphaCode (Science 2022 / arXiv:2203.07814v1 Full Experimental HTML): https://ar5iv.labs.arxiv.org/html/2203.07814
  6. Yujia Li et al. (DeepMind) — Competition-Level Code Generation with AlphaCode (arXiv:2203.07814 Official Abstract & DOI Repository): https://arxiv.org/abs/2203.07814
  7. Anton Lozhkov, Raymond Li, Loubna Ben Allal, Federico Cassano, Joel Lamy-Poirier, Jiawei Liu, Yuxiang Wei, Harm de Vries et al. (BigCode / ServiceNow / Hugging Face / Software Heritage) — StarCoder 2 and The Stack v2: The Next Generation (arXiv:2402.19173v1 Full Experimental HTML): https://arxiv.org/html/2402.19173v1
  8. DeepSeek-AI (Qihao Zhu, Daya Guo, Zhihong Shao, Dejian Yang, Peiyi Wang, Runxin Xu, Y. Wu, Liang Zhao, Wenfeng Liang et al.) — DeepSeek-Coder-V2: Breaking the Barrier of Closed-Source Models in Code Intelligence (arXiv:2406.11931v1 Full Experimental HTML): https://arxiv.org/html/2406.11931v1
  9. Carlos E. Jimenez, John Yang, Alexander Wettig, Shunyu Yao, Kexin Pei, Ofir Press, Karthik Narasimhan (Princeton University) — SWE-bench: Can Language Models Resolve Real-World GitHub Issues? (ICLR 2024 / arXiv:2310.06770v3 Full Experimental HTML): https://arxiv.org/html/2310.06770v3
  10. Carlos E. Jimenez et al. (Princeton University) — SWE-bench: Can Language Models Resolve Real-World GitHub Issues? (arXiv:2310.06770 Official Abstract & Metadata Repository): https://arxiv.org/abs/2310.06770
  11. John Yang, Carlos E. Jimenez, Alexander Wettig, Kilian Lieret, Shunyu Yao, Karthik Narasimhan, Ofir Press (Princeton University) — SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering (NeurIPS 2024 / arXiv:2405.15793v3 Full Experimental HTML): https://arxiv.org/html/2405.15793v3
🔗 Share Post

Reading next story...

العودة إلى المنشورات