Refine the Type, Not the Program: Probe-Certified Structure Rewriting for Numerical Code

A large share of slow scientific and machine-learning code is slow for one reason. It builds a matrix that has hidden algebraic regularity and then treats it as a plain grid of numbers. Examples are a Kronecker product (a big matrix built as a "tensor product" of two small ones), a low-rank-plus-diagonal kernel, or a circulant convolution. Code that multiplies or solves with such a matrix naively pays cubic time and quadratic memory, when log-linear or linear cost is available. Libraries such as CoLA show how large the gains are once the structure is declared. They represent matrices as implicit operators and dispatch to shortcuts like the Woodbury identity. The catch is that a human has to declare the structure. Large-language-model (LLM) agents that refine code against a profiler, such as POLO, can find source-level speedups that gcc -O3 misses. But they rewrite whole programs over many slow rounds, and they never reason about algebraic structure.

This note proposes to move the refinement loop off the program text and onto a short structure hypothesis. An example hypothesis is "this matrix is Kron(B, C) + Diag(d)". The LLM reads the source and proposes a typed expression of a few dozen tokens. Cheap randomized probes run on the actual runtime matrices and either certify it or return a graded residual saying which part failed. The LLM revises only the expression. Once the hypothesis is certified, a deterministic step emits structure-exploiting code through CoLA-style operators. The bet is that each round costs very little, the probe residual is a dense and informative signal, and the final code is correct by numerical certificate. Together these should give large runtime speedups at a small fraction of the LLM latency of whole-program refinement loops.

Core Claim

For numerical code whose bottleneck is a structured linear operator, we claim the following. An iterative loop that refines a compact algebraic type annotation under numerical-probe feedback will match or beat whole-program LLM refinement on final execution speedup. It will do this while cutting total refinement wall-clock and generated tokens by a large factor. The new ingredient is the feedback channel. Existing code-refinement loops get back pass/fail bits, tracebacks, or a runtime number. Here the environment returns a structured residual of the hypothesis against the true operator, computed with matrix-vector products only.

Three threads of prior work motivate this design. ReLoc shows that binary test outcomes give a flat, sparse signal. It fixes this by training a reward model to predict how far a program is from correct. We obtain a similarly graded signal for free from the numerical residual, with no learned model. VERINA and the plateau results of Yan et al. show that unguided multi-round refinement thrashes. VERINA reaches only about 20% proof success even after 64 Lean compiler rounds, so cheaper rounds alone are not enough and the feedback must carry information. Finally, the analysis-by-synthesis loops in iterative feature refinement supply the conceptual template. Systems like 3D Face Reconstruction by Learning from Synthetic Data render a current hypothesis, compare it with the observation, and update on the residual. We apply the same render-compare-update cycle, but the "feature" being refined is a symbolic operator type rather than a hidden vector.

We deliberately keep the loop discrete. The research file notes a tension: a continuous internal pondering loop such as PonderLM or Meta-Reflection cannot be checked against a real runtime without decoding back to text, and Meta-Reflection also needs white-box weights. Our answer is to make the discrete object so small that decoding it is nearly free. This also means the method works over black-box APIs.

Research Program

The system has three parts.

Hypothesis grammar. This is a small typed grammar over operator constructors: Dense, Diag, LowRank(r), Kron, Sum, Product, BlockTriangular, Circulant, Toeplitz, Sparse(stencil), and Symmetric/PSD flags. Each leaf is bound to a slice or factor of program variables. Every expression in the grammar maps mechanically to a CoLA operator, so the code-emission step is a compiler, not a generator.

Probe library. Each probe uses only matrix-vector products with the operator materialized from the user's code, run on a few real input instances.

  • Symmetry is tested by comparing $y^\top A x$ with $x^\top A y$ for random $x, y$.
  • Low rank is tested with a randomized sketch and its singular value decay.
  • Kronecker separability is tested by the rank of the rearranged matrix, using sketched products.
  • Circulant or Toeplitz structure is tested by applying the operator to shifted basis vectors.
  • Diagonal-plus-structure uses CoLA's stochastic diagonal estimator, whose error falls as $O(1/\sqrt{nm})$ with $n$ probes and $m$ samples. That rate is a standard Monte Carlo average, as CoLA reports.

A hypothesis $h$ is certified when the relative residual $\|(A - A_h)Z\|_F / \|AZ\|_F$ on fresh random probe matrices $Z$ falls below a user tolerance. When it fails, the probe report breaks the residual down by sub-expression, so the LLM learns where the hypothesis broke. Probes also run across several input instances, which catches structure that holds for one input but not others.

Loop. The LLM sees the source, the profiler's hotspot, and the history of hypotheses with their probe reports. It emits a new expression, and the loop stops on certification or after a fixed budget. If no hypothesis is certified, the code is left as is. The method can therefore only fail by not speeding code up; it cannot silently change numerics beyond tolerance. Final emitted code is still run against the original's outputs and tests.

The analysis side asks three questions:

  • When does the graded residual prevent the plateaus seen in text-level loops?
  • How does the number of rounds scale with the compositional depth of the true structure?
  • At what problem size does total time (refinement plus execution) break even against the naive code?

Baselines

The naive reference is the original dense implementation run under the standard toolchain: NumPy/PyTorch backed by MKL, plus XLA compilation where applicable. It represents doing nothing. It also tests the claim of Memory safe computations with XLA compiler that compilers lacking a linear-algebra type system miss these identities. Any speedup we report is measured against it at several matrix sizes.

The strongest existing method is a POLO-style whole-program refinement loop. A generator agent proposes full code rewrites, and a decision agent compiles, tests, and profiles them, following POLO. POLO reports 1.34× to 21.5× execution speedups over gcc -O3 on its C/C++ project benchmark. It is the closest system that closes a profiler loop around LLM rewrites, so it is the right competitor on final speedup. We port it to Python numerical kernels. It gets the same LLM, the same profiler hotspot, the same test harness, and the same round budget, and we additionally let it import CoLA. The comparison then isolates where the loop iterates (program text versus type expression), not access to the library. We report both its final speedup and its total refinement wall-clock.

Because our latency claim would be unfair against an unaccelerated text loop, we also run the POLO-style loop with EFFICIENTEDIT speculative decoding. This reuses the previous draft as a free speculative draft, and the paper reports 10.38× generation speedup on CanItEdit and 13.09× on CodeIF-Bench with DeepSeek-Coder-33B. We use DeepSeek-Coder-33B as the shared model so this accelerator applies as published. Beating it means lower end-to-end refinement wall-clock at equal or better final speedup.

Three ablations isolate the key ingredient:

  • Binary-certificate loop: probes return only accept or reject, without the decomposed residual.
  • Probe-only enumeration: no LLM; the grammar is enumerated by brute force up to a size bound, at the same probe budget.
  • One-shot annotation: the LLM proposes a single hypothesis with no loop.

There is no reported result on Lacuna for any method on structure-rewriting of dense numerical code, so the benchmark below is new and all baselines will be run by us.

Why not just…?

Why not just ask the LLM to translate the code into CoLA in one shot? This is a real threat for simple cases. A model that recognizes "multitask GP kernel" may simply write the Kronecker form. The one-shot annotation ablation tests exactly this. Our hypothesis is that one-shot works at compositional depth one and fails at depth two and beyond, for example a Kronecker product of low-rank-plus-diagonal factors, or structure that is only implicit in index arithmetic. If one-shot matches the loop on the depth-stratified benchmark, the contribution shrinks to the certification step, and we will report it that way.

Why not just detect structure numerically without any LLM? Probing can test any single hypothesis cheaply, but the space of compositions grows combinatorially with depth and with the ways variables can bind to factors. Reading the source is what narrows that space. The probe-only enumeration ablation, run at the same probe budget, settles this. We expect enumeration to tie on depth-one tasks and to fall behind sharply at depth three. If it does not, the LLM is unnecessary, and the proposal becomes a structure-detection library instead.

Why not just run a full-program refinement loop with speculative decoding? EFFICIENTEDIT's speedups rest on about 70% of tokens surviving between edits. Structural refactoring, where explicit dense construction becomes a composed operator call, rewrites most of the hotspot. So the reuse phase should help less here than on CanItEdit. Even with perfect reuse, a text loop still gets back runtime numbers or test failures, not a localized residual. The accelerated POLO-style baseline measures both effects. If it matches our wall-clock, the latency claim fails, and only the feedback-quality claim remains.

Why not just rely on the compiler? Compilers transform loops and tiles; they do not reason that a matrix equals a Kronecker product. LGen reports 1.8× to 3× over Eigen, but only through tiling and vectorization of fixed-size kernels. That is a constant factor, against the asymptotic reductions CoLA obtains. The naive-toolchain baseline at increasing $N$ will show the gap grow with problem size if structure, not scheduling, is the bottleneck.

Proposed Experiments

We will build a benchmark of roughly 150 numerical tasks, each a naive dense Python implementation with tests and a known ground-truth structure. Families are drawn from the application domains in CoLA (multitask Gaussian processes with Kronecker kernels, low-rank-plus-diagonal kernel solves, PDE discretizations) and from the PDE systems used by SymMaP (Darcy flow, Poisson, biharmonic). We add block-triangular and Toeplitz convolution cases. Tasks are stratified by compositional depth from one to three. Variable names are obfuscated, and index-arithmetic variants are included, to limit pattern-matching from pretraining.

The metrics are:

  • final execution speedup over the naive code at three sizes;
  • relative output error against the dense reference;
  • test pass rate;
  • certification rate;
  • total refinement wall-clock, generated tokens, and rounds to certification;
  • the break-even problem size, where refinement time plus execution time drops below naive execution time.

The decisive checks are three.

  1. Feedback quality. At equal round budgets, the full residual loop should beat the binary-certificate loop on certification rate at depth two and three. Otherwise the graded signal is not doing work.
  2. Role of the LLM. The loop should beat probe-only enumeration at equal probe budgets on deep tasks.
  3. Latency. Against the EFFICIENTEDIT-accelerated POLO-style loop, our method should reach equal or higher median final speedup with substantially lower end-to-end refinement time.

We also check plateau behavior by plotting certification against rounds, testing whether the residual channel avoids the early saturation reported by Yan et al.. Any task where certified code exceeds tolerance on held-out inputs counts as a failure of the probe design and will be reported separately.