Reinforcement Learning for Code Optimization

Pierre Chambon, Kunhao Zheng, Juliette Decugis, Benoît Sagot, Gabriel SynnaeveNeurIPS 2026

TL;DR

Training LLMs to write correct code via Reinforcement Learning (RL) is now standard practice, yet training them to write fast code usually fails miserably due to noisy runtime measurements and reward hacking. By completely re-engineering the testing infrastructure, reward design, and training loop, the authors successfully teach one-shot code models to generate dramatically faster Python programs without sacrificing correctness. Still, a fascinating peek under the hood reveals that while AI has mastered low-level speed tricks, human programmers retain the crown for deep algorithmic leaps.

What Problem Does This Paper Address?

Modern LLMs are great at passing unit tests, but their code is often sluggish. On real-world software engineering benchmarks, top models write correct patches over 80% of the time yet capture barely 4% of human-expert speedups.

In standard RL with verifiable rewards (RLVR), code execution acts as a clean binary switch: pass the tests, get a treat. Extending this to optimize wall-clock speed sounds trivial—just reward shorter runtimes! In practice, this naive approach collapses. Standard unit tests run in milliseconds, meaning random CPU contention easily drowns out actual code improvements. Worse, if you aren't careful, RL will happily optimize for "fast-but-wrong" programs (after all, return 0 executes at lightning speed), or destabilize the optimizer with sparse, noisy reward signals. The authors tackle a fundamental question: what does it take to turn messy wall-clock execution time into a clean, learnable RL signal for one-shot code generation?

Methods

Rather than inventing a brand-new RL algorithm, the authors build a tightly calibrated signal pipeline across three stages:

Figure 1: Making execution time learnable for RL. A DMC-Optim problem is sampled and the LLM generates candidate solutions. All RL environments we introduce share the same evaluation pipeline, but differ in where they inject optimization pressure. First, each candidate solution can be evaluated on standard correctness tests, but also generated large-input optimization tests (1); pre- execution environments may filter optimization tests in or out using test-level criteria. Execution of a solution on these tests is then run on a calibrated remote execution service (2); intra-execution environments apply additional per-test time limits. Finally, post-execution environments can lever- age the returned recorded per-test durations for instance to compare them against calibrated human reference distributions. The environment (3) returns whether all correctness tests pass (c), whether the optimization tests pass (g), and a potential aggregated scalar quality score q. The three signals, correctness gate c, optimization gate g, and quality score q, feed into one of several reward composi- tions (4). An offline RL simulator (6, top left) evaluates candidate environments by replaying refer- ence human solutions, and the most promising environment-reward pairs are used in properly tuned online asynchronous GRPO training (5, bottom), where the best optimization-RL setting reaches strict DMC-Optim pass@1 at p30 of 19.1% on Qwen 2.5 7B and 30.9% on CWM 32B after 10k steps, vs 7.7% and 13.7% for standard RLVR.
  1. Reliable Timing Infrastructure: Running tests locally on GPU training workers causes massive timing swings due to CPU contention. Instead, code is sent to an isolated, remote Code Execution Service (CES) and calibrated against a fixed pool of human reference solutions to correct for server drift.
  2. Environment & Reward Design: Timing pressure can enter the RL environment pre-execution (filtering for heavy tests), intra-execution (strict per-test timeouts), or post-execution (ranking runtimes against human leaderboards). Crucially, correctness acts as a hard outer gate: wrong code gets $-1$, ensuring no partial credit for fast failures. Because testing every reward variation on GPUs is expensive, the authors built an offline simulator that replays stored human runtimes to screen out bad reward shapes before launching live training.
Figure 3: Different RL environments with different ways of inserting an optimization pressure. Top, pre-execution: a filter chooses the optimization tests; dropped tests (faded) never run, kept tests run under a corresponding time limit ℓ(red bars). The absolute-duration filter keeps ¯dt < a; the relative-duration filter drops the slowest τ% of tests by ¯dt; the character-length filter keeps input + output < L characters. Middle, intra-execution: every test runs, and a run with δt(y) ≥λt becomes a timeout (red bars). Absolute: λt = ℓ; relative: λt = max{10−3, Percentileτ(Dt)}; ranked-worst: the slowest duration on test t among the best τ% of human solutions by mean per-test rank. In both families this comes with a tunable timeout tolerance ρ. Bottom, post-execution: one ranking step, two scalarizations, on top of the naive raw duration approach. Tests run under the 10 s execution cap only; on each, the program’s normalized percentile pt(y) is its rank among the reference solutions on this same test. The mean per-test percentile then averages these ranks into an aggregate a(y); the leaderboard percentile ranks a(y) among the humans’ own mean ranks. Every environment returns strict correctness ˜ccor (all correctness tests pass; executed optimization tests may time out but not fail), the optimization gate g and a graded scalar q: ϕ for pre and intra or a(y) or b(y).
  1. Stabilizing GRPO: Using Group Relative Policy Optimization (GRPO—an RL method that scores a batch of generated solutions relative to each other), the authors adapt to sparse, noisy timing rewards by using larger batch sizes, dropping prompts where all generations get the exact same reward, removing standard-deviation scaling, and discarding "stale" rollouts older than 30 optimizer steps so the model doesn't compare timings across different server load states.

Datasets

  • DMC-Optim (New): Built from 12,275 raw DeepMind Code Contests problems, the authors clean labels, generate hundreds of thousands of new correctness and large-input stress tests, and filter for problems where correct human Python solutions show genuine runtime spread. This yields 1,302 timing-ready problems (1,000 train / 302 test), raising 95th-percentile test durations from a noisy $0.145\text{ s}$ to a measurable $1.296\text{ s}$.
  • LiveCodeBench (LCB): Used as an out-of-distribution benchmark to test whether learned speedups transfer to unseen competitive programming tasks.
  • SFT Mix: Base Qwen 2.5 models were warmed up on decontaminated reasoning traces from OpenCodeReasoning-2 and OpenMathReasoning.

Key Insights and Ideas

  • Local sandboxes ruin speed signals: Rerunning identical code on busy training workers shifted human-percentile rankings by over 41 percentage points on average—proving isolated, calibrated execution isn't a luxury, it's mandatory.
  • Simple binary conjunctions beat fancy continuous rewards: Rather than blending continuous runtime scores with correctness, a "collapsed" binary reward—requiring the code to be both 100% correct and land in, say, the top 30% of human speeds—gave the best balance of speed and stability.
  • Models learn implementation polish, not new algorithms: When an LLM judge analyzed how the RL-trained model beat its baseline, 47% of wins came from faster I/O (like swapping input() for sys.stdin.read) and 34% from constant-factor tweaks. True algorithmic or data-structure upgrades remained rare, with the model achieving complexity-class improvements at roughly half the rate of top humans (13% vs. 22%).

Key Results

The authors evaluate models using $p_\tau$: the pass@1 rate where a solution only counts if it is correct and at least as fast as the top $\tau\%$ of human submissions.

  • In-Domain Gains (DMC-Optim): Training with a post-execution top-30% human leaderboard target boosts $p_{50}$ pass@1 from 18.0% to 31.3% on Qwen 2.5 7B, 21.1% to 39.6% on Qwen 2.5 32B, and 30.7% to 50.4% on CWM 32B. Under the stricter $p_{30}$ bar, CWM 32B jumps from 13.7% to 30.9% (a 125% relative gain) while pure correctness ($p_{100}$) stays rock-steady at ~70%.
  • Out-of-Distribution Transfer (LCB): CWM 32B wins 82.9% of median-sample head-to-head speed matchups against standard correctness-trained RLVR, trading off just 2.5 points of raw pass@1.

Limitations and Future Work

DMC-Optim focuses on single-file Python competitive programming, relying on heavy compute, remote sandboxes, and static pools of human reference solutions—luxuries that don't exist for massive, multi-language software repositories. Furthermore, the underlying dataset is not publicly released (though reproduction details are provided). Future work could pair these fast one-shot policies with inference-time search, use the timing pipeline to generate offline training pairs, or design "algorithm-aware" rewards that explicitly incentivize asymptotic complexity leaps rather than just clever I/O hacks.

Summary updated

Abstract

RL for code correctness is now established: have the model generate a program, run it against hidden test cases, and reward solutions that pass. Extending this to code optimization seems straightforward: just add execution time to the reward. But in practice, once timing drives the reward, small problems in measurement noise, reward sparsity, or Group Relative Policy Optimization (GRPO) instability overwhelm the signal and make RL fail: generated solutions are barely faster, and more of them can fail. We make execution time learnable through three stages: (1) how code is tested, by building DMC-Optim with large optimization tests and a calibrated sandbox; (2) how speed is turned into reward, by composing correctness and speed in the RL environment and using an offline simulator to predict the most promising configurations; and (3) how the model learns from that reward, by adapting GRPO and evaluation to the sparser, noisier timed-execution setting. On DMC-Optim, the strongest optimization-aware configurations improve pass@1 under a top-50% speed threshold from 18.0% to 31.3% on Qwen 2.5 7B and from 30.7% to 50.4% on CWM 32B. Under a top-30% threshold, these gains further increase, with CWM 32B showing 125% relative improvement, while pure-correctness scores remain stable. When the timing sandbox is degraded, robust optimization RL reaches roughly 100%–200% improvement over standard RL with verifiable rewards (RLVR), depending on the evaluation criterion. On LiveCodeBench (LCB), CWM 32B wins up to 83% of median-sample speed comparisons against standard RLVR. Relative to the fastest correct human submissions per problem, it reaches about half the human rate of complexity-class improvements (13% vs. 22%).
BibTeX
@inproceedings{chambon2026reinforcement,
  author = {Pierre Chambon and Kunhao Zheng and Juliette Decugis and Benoît Sagot and Gabriel Synnaeve},
  title = {{Reinforcement Learning for Code Optimization}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=qRPKxKFqhP},
}
Figure