Writing the Camera's Degradation as a Program: Residual-Guided Code Refinement for Unknown Forward Models

When a real photograph comes out blurry, noisy and blocky, restoration methods must guess what happened to it. Today's guesses take one of two forms. Some fix a menu of corruptions in advance: blur, noise, JPEG compression. Others hide the corruption inside a large neural network. Both break when a camera does something off the menu, such as sensor blooming around highlights, color fringing that grows toward the frame edges, or a tone curve applied before compression. We propose a different route. A language model writes the degradation itself as a short, executable, differentiable program. The program runs on clean images, and its output is compared against the real degraded photos. The structure of the mismatch is then turned into an error report, much like a compiler traceback, that tells the model which physical component is missing or wrong. The model then edits the program.

The bet is that the leftover error of a forward simulation is an unusually informative feedback signal. Leftover error with an 8×8 grid pattern points to compression. Error that grows with brightness points to signal-dependent noise or saturation. Error that is concentrated on edges and grows radially points to lens blur that varies across the frame. This is the same role compiler and profiler output plays in code repair. Once a camera's degradation exists as a verified program, it can do two jobs. It can serve as the measurement operator inside a diffusion-based restoration sampler, and it can generate unlimited realistic training pairs for an ordinary restoration network.

Core Claim

Given a handful of paired clean/degraded images from one unknown source, an LLM-driven refinement loop can identify a forward degradation program accurately enough to beat fixed parametric pipelines and learned neural degradation models on two tests: reproducing held-out degraded images, and training restorers that transfer to real test images. The gain should come from degradations outside any predefined operator library, and it should depend on the structured residual report rather than on a scalar loss alone. We also propose a blind extension in which the clean images are replaced by diffusion-prior estimates. We treat it as a second-stage result, not the main claim.

Position Relative to Prior Work

Three systems bring agents or iterative reasoning into restoration, and all three leave the forward model implicit. Multi-Agent Image Restoration (MAIR) has a scheduler agent diagnose degradations and dispatch frozen neural tools in a fixed physical order: compression, then imaging, then scene. Its agents never inspect or write operator code, and its authors note that this three-stage order cannot cover all real corruptions. That limitation motivates our work. RealSR-R1 refines images through vision-language chain-of-thought trained with reinforcement learning. Its feedback comes from learned critics rather than execution, and its degradation reward needs synthetic ground-truth parameters. We replace both with an objective residual computed by running code. CL-DPS handles unknown nonlinear blur by training a contrastive encoder that guides diffusion sampling without ever writing down the operator. We instead synthesize the operator explicitly, so CL-DPS is a direct competitor in the blind setting.

Two lines of work supply our methods. On the code side, $A_2$DEPT evolves free-form solver programs in a search tree that keeps ancestral lineage and includes a dependency-repair loop. It has been tested only on combinatorial and ODE tasks, and we borrow its tree search. The HDL work of Fang et al. rolls code back to the last verified checkpoint whenever an edit causes regressions, and we reuse that rollback. On the image side, DAMP showed that a few explicit physical statistics, such as high-frequency energy ratio, describe degradations better than learned prompt vectors. We repurpose such statistics as the vocabulary of our error report. Their role in DAMP is routing features into fixed experts. Ours is debugging a program.

Two findings constrain the design. Yan et al. found that compiler-guided refinement saturates after a few rounds, so we must show that tree search with rollback keeps improving where a simple linear retry loop stalls. Srivastava et al. found that iterative prompting can reinforce errors, which is why every edit must pass a held-out check before it is kept.

Two methods are the alternatives we must beat at forward modeling. GenDeg trains a conditional diffusion model on 550,000 samples to synthesize degradations. Bulat et al. learn degradation with a GAN. Both are opaque and data-hungry. Our programs are short and inspectable, and they are fit from a few pairs.

Research Program

A degradation program $P$ is a PyTorch function from a clean image $x$ to a predicted degraded image, together with a declared per-pixel noise model. It has continuous parameters $\theta$, such as kernel widths, gains and quality factors. Programs are built from a restricted interface of tensor operations. A static check rejects any program that reads the observed degraded image or reaches outside that interface, which closes off the trivial "return the observation" solution. Given calibration pairs $(x_i, y_i)$, we score a program by

$$J(P,\theta) = -\sum_i \log p_P\!\left(y_i \mid x_i;\theta\right) + \lambda\,|P|,$$

where $p_P$ is the likelihood under the program's own noise model, $|P|$ is the program length in tokens, and $\lambda$ trades fit against complexity. The likelihood term penalizes a program that "explains" mismatch by inflating its noise. The length term discourages memorization. This is a minimum-description-length criterion.

The loop works in three steps. First, the LLM proposes or edits $P$. Second, $\theta$ is fit by gradient descent; this is possible because $P$ is differentiable, and non-differentiable steps like JPEG use straight-through surrogates. Third, the sandbox computes residuals on held-out calibration crops and produces a text diagnostic. The diagnostic reports six things: the residual's 2D spectrum and any 8×8 periodicity, its correlation with local brightness and with image gradients, its dependence on distance from the image center, cross-channel correlation, and a whiteness test of residuals normalized by the declared noise. Each finding is phrased against the current program, for example "residual variance rises with intensity, but the declared noise is constant." Candidates live in a search tree with Boltzmann sampling over nodes, following $A_2$DEPT. An edit that raises held-out $J$ is rolled back, following Fang et al.

The resulting program feeds two downstream uses. First, it generates training pairs for a fixed restoration network. Second, it acts as the measurement operator in diffusion posterior sampling. For the blind extension, we alternate two steps. We sample clean estimates under the current program using a diffusion prior, then refine the program against those estimates. Here we expect, and will report, identifiability failures, such as blur being traded off against prior sharpness.

Baselines

The naive reference is a restorer trained on the standard bicubic-plus-Gaussian assumption, the setting that the NTIRE 2018 challenge showed collapses on realistic degradations. Any method that fails to beat it clearly has not modeled anything.

The most important baseline, and the ablation that isolates our key ingredient, is a fixed parametric pipeline. It is a high-order chain of blur, resize, noise and JPEG whose parameters are fit by the same gradient descent, on the same calibration pairs, under the same $J$. Code synthesis is switched off. The only difference from our method is whether the program's structure can change. On in-library degradations we expect parity, and that is acceptable. To beat this baseline, we must show a significant reduction in held-out negative log-likelihood and in restorer error on degradations outside the library. No reported result was found on Lacuna for such a pipeline on RealSR or DRealSR, so we will run it ourselves.

The learned degradation baselines are GenDeg and a GAN degrader in the style of Bulat et al. We will run them in two ways: fit on the same few calibration pairs, and also at their native data scale with GenDS. Each will feed an identical restorer with an identical training budget. The strongest reported number here is from GenDeg, which reports LPIPS 0.143 on O-Haze for NAFNet retrained with GenDS, against 0.183 without it. Beating it means a NAFNet trained only on program-generated pairs reaching LPIPS below 0.143 on O-Haze.

In the blind, nonlinear setting the baseline is CL-DPS, which reports PSNR 22.74 on FFHQ rotational deblurring. BlindDPS reaches 16.87 and GibbsDDRM 18.43 in the same paper. We will run diffusion posterior sampling with our synthesized operator, using the same diffusion prior and the same number of sampling steps, and count PSNR above 22.74 as a win.

For perceptual real-world super-resolution, the reference is RSD, which reports MUSIQ 65.86 on RealSR. We also include MAIR as an agentic system that cannot write code. The file reports only efficiency figures for MAIR (a 44% runtime reduction versus AgenticIR), so no reported quality number was found on Lacuna for MAIR. We will run it on the same images.

Two further ablations test the code-refinement ingredients. One keeps the search tree but gives the LLM only the scalar $J$ instead of the structured diagnostic. The other keeps the diagnostic but uses a linear retry loop with no tree or rollback. Every LLM-based arm gets the same number of model calls and parameter-fitting steps.

Why not just…?

Why not just fit a richer fixed parametric pipeline? This is the real threat, and the proposal is built around it. If the library already contains the right operators, fitting parameters is cheaper and will match us. Our response is to measure where the library runs out. We will build a hidden-degradation suite of human-written forward programs that use components absent from the fixed library: highlight blooming, radially varying chromatic aberration, rolling-shutter shear, and a tone curve applied before JPEG. If the fixed pipeline's held-out likelihood and restorer quality there come within noise of ours, the claim fails. A fair reviewer could also answer "add those operators to the library." We will report how many library additions would be needed to close each gap. The value of synthesis is that it finds them without a human.

Why not just learn the degradation with a neural network, as GenDeg does? Neural degraders fit well at scale; GenDeg's gains on O-Haze come from 550,000 synthesized samples. With only a handful of calibration pairs, they risk memorizing image content. Their output also cannot be inspected or plugged into a posterior sampler as a stable operator. The few-shot comparison, together with a transfer test that applies degraders fit on one RealSR camera's scenes to new scenes from the same camera, will show whether explicit programs generalize better per parameter. If GenDeg wins at full scale but loses at small calibration sizes, that defines the regime where our method matters.

Why not just use a large generative restorer such as SUPIR, or an all-in-one network? SUPIR produces strong perceptual results but needs about 52 GB of GPU memory, per RSD. It also tends to invent structure under heavy degradation, as RealSR-R1 documents. Neither SUPIR nor all-in-one networks commit to a forward model that the output must be consistent with. We will report re-degradation consistency for each output: apply the identified program to the restored image and measure the residual against the input. That number measures hallucination directly, alongside MUSIQ.

Why not just retry with the error number, as in basic self-refinement? Yan et al.'s plateau result predicts that this stalls. The scalar-feedback and linear-loop ablations test that prediction directly. If they match the full system, the residual-as-traceback idea is unnecessary and we will say so.

Proposed Experiments

The first and most decisive check is program identification on the hidden-degradation suite, where the ground-truth forward program is known. We measure held-out likelihood. We also measure whether the synthesized program recovers each true component, judged by ablating components and checking whether the residual structure reappears, as a function of the number of calibration pairs (1, 4 and 16). The second check uses real cameras. For each camera in RealSR and DRealSR, we fit a program on a few pairs and evaluate how well it reproduces held-out low-resolution images. We then train an identical restorer on program-generated pairs and report PSNR, LPIPS and MUSIQ on that camera's test set against the baselines above, with RSD's 65.86 MUSIQ as the reference. The third check is O-Haze, comparing against GenDeg's 0.143 LPIPS. The fourth is the blind extension on FFHQ rotational blur against CL-DPS's 22.74 PSNR. We will report wall-clock time and LLM calls for every arm, since a program that takes hours to identify is still useful if it is reused across thousands of photos from the same device.

The decisive outcome is simple. If, on degradations outside the library, structured-residual code refinement does not beat parameter fitting of a fixed pipeline at equal compute, the idea is wrong. If it does, and the scalar-feedback ablation does not, then execution residuals are working as a debugging signal for physics, which no prior restoration system has used.