Dimension-Checked Repair Loops for Ill-Scaled Scientific Code

Scientific code often runs without errors and still produces nothing useful. A battery model written in SI units feeds a solver numbers ranging from Boltzmann's constant to current densities. A pipeline model mixes megapascals with kilograms per second. Either way, the optimizer stalls, diverges, or reports "restoration failed." The usual fix is non-dimensionalization: rewrite every variable as a ratio to a characteristic scale so that all terms land near one. Human experts do this by hand. Coding agents, meanwhile, repair programs by reading error messages and test failures, which say almost nothing about why a numerically valid program refuses to converge. We propose a repair loop in which an LLM agent must justify each edit in physical units and is fed a diagnostic report tying numerical trouble to specific physical quantities in the source. Every edit then has to pass a symbolic check proving that the rescaled program still describes the same physics.

The two-sentence version is this. Give a code-repair agent a "scale report" that says which quantity, in which line, carries which order of magnitude and how badly it distorts the solver's linear algebra. Accept only rewrites that a checker can prove are a pure change of units, never a change of the problem. We expect this to beat both the solver's built-in automatic scaling and a generic agent that sees the full solver log. The equivalence check should also stop the agent from "fixing" convergence by quietly deleting physics, a failure mode that generic loops invite.

Why this gap is real

The motivating evidence comes from the scientific-computing side. Modelica2Pyomo translates Modelica physical models into Pyomo optimization problems and applies automatic variable and constraint normalization. Its authors state that without this step, industrial models such as a solid-oxide fuel cell with roughly 850,000 equality constraints are "inevitably bound to fail" in IPOPT or CONOPT 4. Their normalization is a fixed rule applied before the solve, and the tool cannot read a failed solve and try again. Forward and Inverse Simulation of Pseudo-Two-Dimensional Model of Lithium-Ion Batteries Using Neural Networks shows the same pathology for physics-informed neural networks, which are networks trained to satisfy differential equations through a loss. A naive model reached losses of $10^{48}$, and a hand-engineered stabilization brought the final loss to $10^{-6}$ with relative $L^2$ error near $10^{-2}$. Related work on electromigration (Ngai Wong et al.) and hemodynamics (Georgios Kissas et al.) documents parameter spreads of up to thirty orders of magnitude. All of these fixes required an expert to choose the scales.

The code-refinement side supplies the method but also constrains it. Execution-feedback loops work well when the feedback says what is wrong. Examples include traceback-driven repair (Hollmann et al.), role-split repository agents such as MAGIS, and profiler-guided optimization in POLO, which accepts only edits that measurably speed up a build. Yan et al. report that such loops plateau after a few iterations and cycle when the signal stops being actionable. Srivastava et al. show that iterating against an immediate pass/fail signal can amplify hidden defects. In our setting, the analogous defect is an agent that loosens tolerances or drops a stiff term to make the solver report success. POLO's oracle is wall-clock time and MAGIS's is test outcomes, and neither can see conditioning or units. We borrow their accept-only-verified-improvements discipline and replace the oracle.

Core Claim

Convergence failures caused by bad scaling are diagnosable at the source level. An agent that receives source-attributed magnitude diagnostics, and whose edits are restricted to provably equivalent changes of variables, will repair substantially more ill-scaled solver programs than solver auto-scaling, static rule-based normalization, or a generic log-reading agent with the same model and budget. It will also never return a "converged" program whose solution violates the original equations.

The equivalence restriction can be stated precisely. Let the original program pose residual equations $F(x)=0$ in unknowns $x$. Allowed rewrites substitute $x = S x^\ast$ and solve $F^\ast(x^\ast) = D\,F(S x^\ast) = 0$. Here $S$ and $D$ are diagonal matrices of positive characteristic scales the agent proposes, built from products of the problem's physical parameters so that each entry carries the right units. The only other allowed rewrite is a small whitelisted set of reformulations, such as $x = e^{y}$ for strictly positive quantities, that a symbolic algebra system can verify. Any such rewrite has exactly the original solution set mapped through $S$, so success on $F^\ast$ is success on $F$.

Research Program

We would build three components around an off-the-shelf code LLM.

The first is a units layer. The agent annotates the program's parameters and unknowns with physical units, using a units library in Python or a lightweight symbolic tag. A checker verifies dimensional consistency term by term. This catches genuine unit bugs and makes the scales proposed for $S$ and $D$ checkable.

The second is the scale report, the proposal's key ingredient. At the initial point and at the solver's last iterate, we evaluate every additive term in every residual and the Jacobian's row and column norms. These numbers are mapped back to source lines and named physical quantities using the units annotations. The report ranks terms by the log-magnitude spread within each equation. It also gives an estimate of the condition number of the Jacobian, which measures how much small errors get amplified when the solver inverts it. A typical line reads: "line 41, Butler–Volmer exchange term, $\sim 10^{19}$ larger than the diffusion term in the same equation." For the neural-network track, the report gives per-term gradient magnitudes in the loss instead of Jacobian norms.

The third is the verifier and acceptance rule. A proposed edit is accepted only if three conditions hold. The symbolic check confirms that it is an allowed equivalent rewrite. The scaled program converges. The solution, mapped back through $S$, satisfies the original unscaled residuals to a tolerance relative to the reference solution. Rejected edits are rolled back, following the rollback discipline of Fang et al., and the rejection reason is returned to the agent.

No benchmark for this task exists in the material we found, so we would construct one, ScaleBench, from the systems in our sources. The nonlinear-programming track uses Pyomo/IPOPT and JuMP/KNITRO. It includes the hydrogen-blending pipeline problems of Dynamic Optimization and Optimal Control of Hydrogen Blending Operations in Natural Gas Networks, Pyomo models in the style of the Modelica2Pyomo boiler-turbine and fuel-cell cases (where the models are obtainable), and electromigration stress equations. The neural-network track uses PyTorch physics-informed networks and includes the pseudo-two-dimensional battery model, the beam and hemodynamics systems, and PDEBench equations (PDEBench) re-expressed in raw SI units with realistic material constants. Each instance comes as an "as an engineer first writes it" raw-unit program paired with a reference solution from an expert-scaled formulation. To test generalization rather than recall, we would also include held-out variants with randomized but physically consistent parameter magnitudes and renamed variables, so that the agent cannot pattern-match textbook dimensionless groups.

Baselines

The naive reference point runs each raw-unit program unchanged with the solver's default settings. For IPOPT this includes its built-in gradient-based scaling; for the networks, Adam with a standard learning-rate sweep. This tells us how often scaling is actually the binding problem. The reported anchor is the battery paper's naive model, which ended at loss $10^{48}$.

The strongest non-LLM competitor is solver-side scaling tuned per problem. For IPOPT, this means its gradient-based and user-supplied nominal-value scaling, with nominal values taken from variable bounds and initial guesses, plus Jacobian equilibration. For the networks, it means per-term loss reweighting by gradient norm. We give it the same wall-clock budget as the agent for a grid search over its options. Beating it means solving instances it cannot solve, not merely solving the same instances faster.

The rule-based competitor reimplements Modelica2Pyomo-style automatic normalization, which divides each variable and constraint by a nominal magnitude before the solve. The original tool is tied to Modelica input and index-1 differential-algebraic equations, so we port only its scaling logic. Modelica2Pyomo reports that the boiler-turbine case solves in under one second with normalization and fails without it. That is a reported qualitative success, and no aggregate convergence rate was found on Lacuna for a multi-problem suite.

The strongest LLM competitor is a generic execution-feedback repair loop using the same model, token budget, and iteration cap. It receives the full solver log, tracebacks, and the loss history, and is free to make any edit. This is the obvious "just use an agent" approach in the line of Hollmann et al. and the loops surveyed in Code to Think, Think to Code. No reported result was found on Lacuna for any LLM repair loop on scientific-solver convergence. The surveyed numbers, such as AgentCoder's 96.3% on HumanEval, are on unrelated tasks and do not transfer.

Three ablations isolate the ingredients: removing the scale report, leaving units and verifier; removing the equivalence verifier, leaving units and report; and adding only the verifier to the generic loop. We also compare against a one-shot prompt that asks the model to non-dimensionalize the program before any solve. On the neural-network track, the hand-engineered battery stabilization (final loss $10^{-6}$, relative $L^2$ error $\approx 10^{-2}$) serves as an expert ceiling rather than a baseline to beat. Our rewrites are restricted to equivalent changes of variables, while that method changes the training formulation.

The primary metric is verified success: the fraction of instances whose back-mapped solution satisfies the original equations and matches the reference. Secondary metrics are raw solver-reported success, so that the gap between the two exposes physics-altering "fixes," along with iterations, tokens, and Jacobian condition-number reduction. Beating the generic loop means a statistically clear gain in verified success at equal budget, with no rise in silently wrong solutions.

Why not just…?

Why not just rely on the solver's automatic scaling? Built-in scaling is computed from local magnitudes at the starting point. It cannot account for terms such as an exponential reaction rate that become huge only later in the solve. The Modelica2Pyomo authors report failure on industrial models with modern solvers unless a separate normalization step precedes the solve. Our tuned-auto-scaling baseline tests this directly. If it matches the agent on the nonlinear-programming track, the honest conclusion is that the contribution is confined to the neural-network track and to code outside solver ecosystems.

Why not just hand the solver log to a generic coding agent? This is the real threat, because strong models already know textbook non-dimensionalization. Two things suggest it falls short. Raw logs report symptoms ("restoration phase failed") rather than which source term is responsible, which is the non-actionable feedback that Yan et al. associate with plateaus. And an unconstrained agent can reach "convergence" by changing the problem, in the spirit of Srivastava et al.. The verifier-only ablation settles which of these matters. If the generic loop plus the equivalence check closes most of the gap, the scale report is not pulling its weight and we will say so.

Why not just ask the model to non-dimensionalize once, up front? One-shot rewriting must guess the dominant scales before seeing any solver behavior, and in coupled multi-physics problems the dominant balance is exactly what is unknown. The one-shot baseline on the randomized-magnitude variants measures how much the closed loop adds. We expect one-shot prompting to do well on textbook instances and degrade on held-out ones.

Why not just use a scale-invariant learned optimizer? Metamizer handles multiscale residuals by normalizing gradients inside a U-Net, which is a convolutional network for grid data, and reaches machine precision on Laplace problems. However, it works on fixed grids with Dirichlet boundaries and produces no editable program. Pyomo or JuMP models with algebraic constraints are outside its scope, so it is complementary rather than competing, and we do not run it as a baseline.

Decisive Checks

The proposal succeeds if, on held-out randomized-magnitude instances, the full system's verified success clearly exceeds both tuned solver auto-scaling and the generic log-reading agent. The no-report ablation must lose a meaningful share of that gain, and the no-verifier ablation must show a nonzero rate of solver-reported successes that fail the back-mapped check. The proposal fails if the generic agent plus verifier matches the full system. In that case the lesson would be that guarding against physics-altering edits matters, but source-level scale attribution adds little beyond what the model infers from logs.