Recall or Reformulation? Measuring Memorization in LLM Code Speedups

When a language model is asked to make slow Python code fast, it can win in two very different ways. It can remove the overhead of the Python interpreter, the per-operation cost of dispatching bytecode, checking types, and managing boxed objects, by compiling loops to machine code. Or it can change the algorithm, replacing an expensive computation with a cheaper one. The second kind of win produces the dramatic speedups. It is also the kind most likely to come from remembering a named routine seen during training ("this is an LP, call the specialized solver") rather than from analyzing the code in front of it. Current speedup benchmarks report one number that mixes the two, and they use tasks drawn from famous libraries, so the mix cannot be separated.

We propose to separate them. The design pairs each canonical optimization task with a procedurally generated "twin": a program with the same kind of hidden cost structure (say, a brute-force enumeration that collapses to a dynamic program, or a nested sum that collapses to prefix sums) that matches no textbook routine. The generator knows the fast form by construction. Timing agents across a sweep of input sizes separates constant-factor gains, which is what interpreter removal delivers, from gains that grow with input size, which only algorithmic change delivers. The gap between canonical and twin performance on the algorithmic component is a direct, behavioral estimate of how much of today's reported acceleration ability is recall.

Core Claim

Our hypothesis is that the constant-factor part of LLM speedups, which comes from removing interpreter overhead, is largely insensitive to contamination, while the asymptotic part is concentrated on tasks whose fast form is a named, widely published algorithm. If that holds, average speedups on public suites overstate how well models reformulate unfamiliar code. The contribution is the measurement instrument (a twin generator with known optimal speedup, plus a size-sweep decomposition) and the resulting estimate of what we call the "recall premium."

Relation to Prior Work

The motivating result is AlgoTune. It gives an agent 154 numerical Python tasks built on NumPy, SciPy, CVXPY and similar libraries. It reports an average 1.72x speedup with o4-mini-high and DeepSeek R1, and it observes that gains mostly come from surface edits (Numba wrapping, library substitution), with rare large outliers from reformulation (81x on a semidefinite program, over 800x on lp_mdp). AlgoTune does not audit contamination. Its tasks come from exactly the most-copied scientific code on the web, so it cannot tell whether the outliers are recall. We reuse its agent loop and its insistence on strict correctness checks. We differ by adding twins, known optimal speedups, and a size-sweep decomposition.

ALE-Bench and HeuriGym play a constraining role, and they supply part of the design. ALE-Bench shows that Python loses badly to C++ and Rust in time-bounded heuristic search, which confirms that interpreter overhead is a first-order factor. Its authors also name contamination of its 40 static AtCoder problems as a limitation and defer synthetic generation to future work. HeuriGym reduces contamination by choosing low-citation problems. We argue that this lowers exposure but cannot measure its effect.

The code-contamination audits supply the method for the open-model arm of our study. Quantifying Contamination in Evaluating Code Generation Capabilities of Language Models uses Levenshtein and Dolos syntax-tree similarity to find that 20.8% of MBPP solutions appear verbatim in StarCoderData. Rethinking the effects of data contamination in Code Intelligence shows that only paired problem-plus-solution exposure inflates zero-shot scores. Both measure pass/fail correctness of short functions and never runtime. We carry their similarity tooling over to performance.

Finally, DyVal and the RandomCalculation set from Reasoning or Memorization? show the value of procedurally generated, leakage-free tasks for arithmetic and graph reasoning. Neither measures execution cost. Our generator extends their approach to programs whose score is wall-clock time.

Research Program

The generator composes programs from a small language of kernels: loop nests, recurrences, reductions, stencils, and graph relaxations. It plants one reducible structure in each program. Examples include a triple loop whose inner sum is a prefix-sum in disguise, an exhaustive subset search with optimal substructure, a repeated matrix product whose order can be rearranged, and a fixed-point iteration with a closed form. Because the planted structure is known, each twin comes with a reference fast implementation and a known asymptotic gap. For instance, a cubic-time program might have a quadratic-time fast form.

Each program is instantiated with random names, random constants, random compositions, and random data layouts. We then check it with Dolos-style similarity against public code corpora and discard near-matches.

Every canonical task appears in three forms. The first is the canonical plain task, as in AlgoTune. The second is a canonical disguised version: the same algorithm, renamed, restructured, and stripped of docstrings. The third is a novel twin that matches the canonical task in planted asymptotic gap and in reference runtime at the base input size. Comparing plain with disguised measures recall of names and surface form. Comparing disguised with twin measures recall of the algorithm itself.

Scoring runs each agent's output at five input sizes spanning at least an order of magnitude. We fit the slope of log runtime against log size. A change in slope relative to the reference program indicates an algorithmic change. A shift in intercept at fixed slope indicates a constant-factor gain, which is the interpreter-removal component. We report headroom, defined as

$$h = \frac{\log S}{\log S^{*}},$$

where $S$ is the agent's speedup at the largest input size and $S^{*}$ is the speedup of the planted fast implementation. Normalizing by the planted gap makes twins and canonical tasks comparable even when their hidden structures differ. The recall premium is the mean difference in the algorithmic component of $h$ between disguised canonical tasks and their matched twins.

Correctness is checked on fresh random inputs against generator-computed answers under tight tolerances. This addresses the reward hacking through loosened numerics that AlgoTune reports. Timing runs on a single fixed machine type with repeated trials and bootstrap confidence intervals, following ALE-Bench's practice of standardized instances. Agents may write Numba, Cython, or C extensions. This makes it possible to ask whether cross-language recall, meaning C++ solutions of the same problem seen on GitHub, adds to the premium.

For open models with published corpora, we run StarCoder-family models against StarCoderData. We compute each canonical task's corpus similarity with the pipeline from Quantifying Contamination and test whether the recall premium grows with similarity. This dose-response check ties the behavioral gap to actual exposure rather than to task difficulty.

Baselines

The naive reference point is the unmodified Python program, with speedup 1 by definition. Every other number is reported relative to it on the same machine and inputs.

The mechanical floor is a fixed compiler pass with no model in the loop: Numba applied automatically to hot loops, and PyPy run on the whole program. This isolates the pure interpreter-removal component, and it is the natural competitor for the constant-factor part of any agent's score. An agent beats it only where the agent's gain exceeds this floor, and it demonstrates algorithmic skill only where its runtime slope differs. We found no reported result on Lacuna for automatic Numba or PyPy applied without an agent to AlgoTune-style tasks. We will measure this floor ourselves.

The strongest existing method is the AlgoTuner agent from AlgoTune. The paper reports an average speedup of 1.72x for o4-mini-high and DeepSeek R1, with 59.7% of tasks improved, 1.51x for Gemini 2.5 Pro, and 1.33x for Claude Opus 4. We run it unchanged, under its roughly one-dollar-per-task budget, on all three arms. First, we reproduce its numbers on the canonical plain arm to validate our setup. The key comparison is its twin performance relative to its canonical performance. We also run the iterative-refinement agent style that ALE-Bench found superior to parallel sampling, under the same token and wall-clock budget.

Two ablations isolate the ingredients of the proposal. The first removes the profiler and size-sweep feedback from the agent, which tests whether analysis tools narrow the recall premium. The second forbids library imports beyond NumPy on the canonical arm, which tests how much of the premium is "call the right SciPy function" versus writing the algorithm from memory.

Why not just…?

Why not just run a contamination audit on AlgoTune's existing tasks? For closed models the training data cannot be audited. For any model, an audit shows presence in the data, not effect on speedup. The code audits in Rethinking the effects of data contamination find that only paired exposure changes scores, so presence alone is a weak proxy. We do run the audit, but only as the dose-response check on open models. The twin comparison supplies the causal contrast that an audit cannot.

Why not just rename and obfuscate the canonical tasks? This is a real threat to the need for the generator, which is why obfuscation is a full arm of the study rather than a straw man. If disguised canonical tasks and novel twins score the same, then recall operates through surface names and cheap obfuscation suffices for evaluation. We would report that as a finding and simplify the recommendation. If a gap remains, the model is recognizing the algorithm beneath the disguise. Obfuscation cannot detect that, since an obfuscated LP is still an LP. Only a program whose fast form is not a named routine can.

Why not just use post-cutoff tasks, as LiveBench does? LiveBench refreshes questions monthly, and this works for correctness scoring. New numerical tasks, however, are rare, have no known optimal speedup, and often recombine old algorithms, so being recent does not guarantee being novel in algorithm. Twins provide a known ceiling $S^{*}$ and a matched difficulty that time-based freshness does not.

Why not just apply a JIT compiler and skip agents entirely? For constant-factor gains, this may be nearly enough, and we expect the mechanical-floor baseline to account for much of the intercept shift. That is part of the claim, not a threat to it. JIT compilation cannot change a runtime slope, however, and ALE-Bench's C++-versus-Python gap together with AlgoTune's outliers both indicate that large gains need restructuring. The size sweep shows directly how much of each agent's gain the fixed compiler already delivers.

Decisive Checks

The central test concerns the algorithmic component of headroom for frontier agents. If it falls substantially from disguised canonical tasks to matched twins, with bootstrap intervals excluding zero, while the constant-factor component stays roughly unchanged, the recall hypothesis is supported. If both components are flat across arms, current models reformulate unfamiliar code about as well as familiar code, AlgoTune's surface-edit finding reflects a genuine capability limit rather than memorization, and our instrument becomes a clean contamination-free benchmark. A positive dose-response between StarCoderData similarity and recall premium for open models would link the gap to training exposure.

Two validity checks come first. The generator must preserve difficulty: human-written reference solvers should reach similar headroom on twins and canonical tasks. The size-sweep slope must also correctly classify planted algorithmic changes versus Numba-only rewrites on a labeled calibration set before any model is scored.