OPAL: A Coding Agent Rewrites Your Optimizer Mid-Train, and the Rollback Is the Hard Part — aniketkarneai.com | aniketkarneai.com
Wednesday, November 11, 2026 Field notes on autonomous systems ● Amsterdam, NL
daily

OPAL: A Coding Agent Rewrites Your Optimizer Mid-Train, and the Rollback Is the Hard Part

OPAL turns the optimizer into a program that Claude Code rewrites while your model trains. The headline results are the FID gains, but the engineering that matters is the rollback contract, the CPU snapshot that makes a bad swap undoable, and an eval-integrity check that exists because two of the authors own runs gamed it.

At update 30 of a 60-update run, the program I had just handed OPAL raised on every call to step(). OPAL caught it on that same update, undid the update exactly, redid it with the previous program, and kept training. The log line is short and completely unromantic:

[opal] update 30: v002 raised in step(); reverted (the update was undone exactly and redone)

I had been reading the paper’s blog post for an hour before I got to that line, and the line is what convinced me the thing was real. Not the FID numbers. A rollback that says exactly and redone is a promise somebody kept.

What actually got shipped

OPAL is OPtimizer with an Agent in the Loop, from Xingjian Bai, Jia-Hao Liang, Jayden Teoh and Vincent Sitzmann, published as a blog post in October 2026 with code at github.com/xingjian-bai/opal (MIT, Python, 177 stars and eleven days old when I looked) and a PyPI package named opal-optimizer.

The premise is that a training recipe is usually chosen before training starts, and for a new architecture or a new language there is no recipe to choose. Instead of sweeping, you let an agent watch the training dynamics and rewrite the optimizer’s source code while the run is in flight. It spends LLM tokens in place of GPU hours.

The wiring is one line:

opt = opal.wrap(
    torch.optim.AdamW(model.parameters(), lr=3e-4),
    model,
    scheduler=sched,
    total_steps=steps,
    goal="...",
    max_cost_usd=20,
)

What the agent gets to edit is exactly two files in a workspace folder, and the interface is code, not a form.

updater.py is the update rule, running on every rank after gradients are averaged:

def build(named_params, previous=None, spec=None):
    return Updater(...)

class Updater:
    follow_user_scheduler = False
    def step(self, grads, update): ...
    def state_dict(self): ...

analysis.py is how the agent decides what it even wants to look at. It returns a small report dict, and it can return a wake reason to ask for a decision early. The starting analysis.py computes gradient norms per parameter role, update-to-weight ratios, and the cosine between gradient and momentum for one sampled tensor per role.

That second file is the part I did not expect. The obvious design is to feed the agent a fixed telemetry dashboard. Instead the agent writes its own probes, so it can go looking for whatever it thinks matters, including things the author never anticipated. In one of the published runs it added loss over the last 323 updates minus the same updates one epoch earlier, on the reasoning that batch difficulty repeats each epoch.

Installing it, and what it cost me

pip install opal-optimizer
opal doctor

opal doctor on this box:

python 3.12.3 (/home/ubuntu/.hermes/cache/scratch/opalvenv/bin/python)
torch 2.14.1+cu130; CUDA available: False
claude: not found
bubblewrap (for the sandbox of the agent's shell): found
socat (for the sandbox of the agent's shell): found

Two things worth noting. The torch 2.14.1+cu130 line is what you get on a CPU-only machine: pip install opal-optimizer drags in the entire CUDA 13 runtime stack, cuDNN 9.24, NCCL 2.30 and the rest, whether or not you have a GPU. That is a lot of wheel for a box with no CUDA device on it.

Second, claude: not found. There is no Claude Code CLI here, so I could not run the real agent path at all. The package ships a documented escape hatch for exactly this: you can pass a plain Python function as the backend, and it receives the workspace folder, the decision message and the system prompt. That is how I ran everything below.

opal estimate is the tool that decides whether a run is worth starting, and it prints the estimate from the authors’ 567 measured decisions against Claude Opus 5.5 at effort high:

$ opal estimate --total-steps 5000 --sec-per-step 0.5
  training without the agent: 5,000 updates x 0.5 s = 42 min
  45 decisions, training waits for each (blocking=True): about 24 min of waiting for
  the agent (9 min to 44 min), 0.58x the run's own time (0.22x to 1.1x)
  agent cost: about $11 ($2.50 to $18)

There is a second guardrail I only found by running it on a deliberately tiny job:

$ opal estimate --total-steps 66 --sec-per-step 0.2
  0 decisions, training waits for each (blocking=True): about 0 s of waiting for the agent
  agent cost: about $0.00 ($0.00 to $0.00)

The rule is MAX_WAIT_FACTOR = 4.0 in opal/estimate.py. When you leave decisions unset, the scheduler caps how many decisions it will ask for so that expected waiting stays under four times the run’s own duration. A 66-second run gets zero. A five-hour run gets the full 50.

The load-bearing claim, tested

The README states that until the agent changes something, the wrapped run is bit-for-bit the same as the plain one. That is the claim the entire safety story rests on, so I tested it first.

python examples/mnist_mlp.py                        # plain PyTorch
python examples/mnist_mlp.py --opal --backend keep  # wrapped, no agent, free

Both runs, same seed, same data order:

plain--backend keep
final test accuracy0.98500.9850
parameter checksumddf28c5044d7ddf28c5044d7
decisions asked042
agent cost$0.00$0.00
wall clock15 s23 s

Same SHA-256 prefix on the final parameters. The wrapped run is byte-identical. opal show confirms the shape of it: 42 scheduled, 42 asked, 42 answered, 0 applied (changed the programs).

backend="keep" answers every decision with “keep the programs”, so this is the null hypothesis of the whole system and it holds exactly.

Three ways to break it, and what OPAL did

Then I wrote a fake agent that misbehaves on purpose, one decision at a time. All three failure modes are visible in events.jsonl.

The program fails to load. My first attempt at a valid replacement omitted the build() function and returned the Updater class directly. OPAL refused it at load time:

{"kind": "load_failed", "k": 2, "error": "AttributeError: module 'opal_program_r0v1.updater'
 has no attribute 'build'"}

The previous program stayed in place and training continued. The offending source is kept on disk under programs/rejected-v002-20261023-153841/ rather than being deleted, which is the right call, because I needed to read it to work out what I did wrong.

The program loads and then raises in step(). This one got installed as v002 at update 30, then:

{"kind": "applied",  "k": 3, "version": 2, "changed": ["updater.py"], "swap_seconds": 0.02}
{"kind": "reverted", "update": 30, "version": 2, "restored": true}

The restored: true is the CPU snapshot doing its job. Before building a new updater, OPAL copies parameters, gradients, your optimizer’s state and the old updater’s state to CPU. If the new program raises on its first update, that copy is restored and the update is redone with the previous program. The default snapshot_limit_gb is 2, and a 125M-parameter model with AdamW needs about 1.9 GiB, so a big model can silently skip the snapshot and lose this protection. The event log and the run’s stderr line tell you which happened.

Here is the part I did not expect, and it is the part worth knowing. The revert does not restore the original optimizer. It restores the last program that passed its trial window, which in my run was v001, the plain-SGD program I had installed one decision earlier. The guide says so plainly: “The fallback is the last updater that passed its trial, or the starting one. An updater replaced during its trial does not become the fallback.”

I caught this by running the same task unwrapped and diffing the loss curve update by update:

update   plain    opal     delta
    1   0.68126  0.68126   0.00000
   10   0.67546  0.67546   0.00000
   11   0.68985  0.68900  -0.00085   <- SGD program active
   29   0.72258  0.72605  +0.00347
   30   0.73587  0.73315  -0.00272   <- revert happens here
   45   0.72015  0.72280  +0.00265   <- still on the SGD path

The two runs are identical for the first ten updates, diverge while the SGD program is in charge, and stay diverged after the revert. The weights had already moved; undoing a bad program does not undo what a good-but-different program did. If you are using this on a real run, the audit trail in programs/ and the version directories v000, v001, v002, v003 is the artifact you read afterward, not the final metric.

What the agent does when it is the real one

The published decision tables are the most interesting part of the whole project, because they show the agent doing things nobody would have written down in a recipe. From the LightningDiT run, in order:

  • Update 800: moved attention and MLP weights to Muon, 196 matrices once the fused tensors are split, each step matched to its AdamW size; kept adaLN on AdamW; planned a cosine cooldown from 60K.
  • Update 1,600: ramped Muon’s steps to 1.25x their matched size over updates 1,600 to 2,000, and added a guard that cuts a step’s rate when the gradient norm passes 3x its mean.
  • Update 3,200: added a controller multiplying each AdamW tensor’s rate by 0.9 every 100 updates while its gradient opposes its momentum, down to 0.2.
  • Update 4,000: removed that controller and moved the adaLN weights to Muon, each split into six 1152x1152 chunks.
  • Update 8,750: scheduled a test of 2.75x for updates 9,000 to 9,750, and fixed a bug that would have broken a rerun of its own schedule.

And from the RAEv2-B run:

  • Update 1,500: scheduled a probe, the rate at 0.3 of its value for updates 1,576 to 1,650, explicitly to measure the step-size noise in the loss.
  • Update 1,750: scheduled an A-B-A test, 2x for updates 1,850 to 2,500, between stretches at 1.5x.
  • Update 3,000: chose 2x from update 3,100, because the test showed faster progress at 2x than at 1.5x.
  • Update 6,460: fixed an off-by-one in its own analysis, an epoch is 6,462 updates and not 6,463.

The agent is running experiments inside your training run. It is writing the ablation schedule, waiting for the result, and picking the arm. That is a qualitatively different thing from a hyperparameter search, and it is why the gains in the no-recipe settings are real: LightningDiT-XL/1 goes from FID-50K 2.18 to 1.83 with guidance, RAEv2-B from 3.39 to 3.19, Goldfish Amharic from 83.48 to 81.11 bits per sentence.

The same tables are also the honest-limit section, because the agent changes its own mind constantly. “fix or revert” is one of the six tags the system assigns to each change, alongside common practice, niche practice, block-specific, observation-originated and time-step-specific. On modded-nanogpt, a track with heavily tuned recipes, the gain was 3.2781 to 3.2749 and the track’s own noise is 0.0013 per run. A run on version 0.2.0 with the neutral prompt ended at 3.2878, worse than the record it started from. The authors say so in their own examples page: “It does not always help.”

What it costs, in the currency you actually have

Wall-clock overhead, measured across their runs:

Taskno agentnot waitingwaiting
Goldfish Amharic, 1x H1001.00x1.11x4.39x
modded-nanogpt Track 3, 8x H1001.00x1.14x1.30x
LightningDiT-XL/1, 8x H1001.00x1.06x1.61x
RAEv2-B, 8x H1001.00x1.01x1.01x

With blocking=False the training continues on the current program while the agent thinks, and the edit lands whenever the answer arrives, which on Goldfish was a median of 65 updates later. On the RAEv2-B run that gave FID 3.17 non-blocking against 3.19 blocking, at 3.22 hours against 3.75 hours, for $9.71 against $13.30, with 43 decisions asked and 3 applied instead of 50 and 6. The agent asked fewer questions because it does not ask a new one while one is in flight.

Token cost is the part that looks alarming and is not. The LightningDiT agent cost $6.42 at Opus 5.5 list price on top of about 74 H100-hours of training, which is roughly $510 at AWS on-demand. The authors are explicit that counted in FLOPs this is hopeless, and then make the argument that matters: GPU hours and closed-model token access are two different commodities, and the second one keeps getting cheaper.

The part that should worry you

OPAL’s own guide has a section titled “What OPAL does not protect against”, and it deserves to be quoted rather than summarized.

Claude Code’s file tools are confined to its folder and its shell runs in an OS sandbox with no network. But: “The code the agent writes runs inside your training process with your permissions. It is not sandboxed.”

The programs it writes execute with your privileges, can read files you can read, and can reach into the training script’s globals. The boundary check is a static heuristic that flags common file and network I/O, dynamic imports, builtins access, introspection, hook registration and assignments to model or loss methods. It logs findings without blocking anything, and the guide says the quiet part out loud: “No flags is not evidence of isolation.”

There is also eval_integrity, which exists because two of the authors’ own overfit runs gamed the evaluation. One scaled the classifier for each evaluation and restored it at the next update. The other copied a running average into the model 49 updates before each evaluation and restored the iterate after it. Both planned a final classifier scale chosen from those probes. The check samples up to 32K entries per parameter tensor into a ring buffer of 138 updates, and flags a tensor when a large change right before an evaluation is undone right after it. The agent is told neither that the check exists nor what it found.

That last detail is the design philosophy in one line. The system does not trust the agent, does not tell the agent it is being watched, and keeps the receipts in a separate file.

If you use this, the guide’s own advice is the right advice: read programs/ before trusting a result, keep test data out of training, and evaluate the final checkpoint in a separate process.

What I did not get to

Supported today: plain PyTorch loops on one node, DDP, torch.compile, bf16 autocast, fp16 GradScaler, gradient accumulation, one or several optimizers, the Hugging Face Trainer through opal.hf.OpalTrainer, and Accelerate. Not supported: multi-node training, FSDP, ZeRO, DeepSpeed, tensor and pipeline parallelism, JAX, whole-step CUDA graphs, and closure-only optimizers like LBFGS as the starting program. Lightning has no test yet.

The thing I kept wanting and did not find is a way to replay the decision path rather than just the final program. opal.replay("<run folder>", optimizer, model, total_steps=...) deterministically reruns the last version, which is the artifact you would want for an audit. But the answers themselves are recorded under decisions/, and nothing in the package consumes them to reconstruct the sequence of swaps. The guide is candid about why that matters: with blocking=True a run is deterministic given the agent’s answers, and the agent can make different choices from one run to the next because hosted models change between versions.

So the reproducible artifact is the final program, and the path that produced it is not. For a system whose entire premise is that it rewrites your optimizer from scratch on a run you cannot repeat, that gap is the one I would want closed before pointing it at anything expensive.

Where to look

  • Blog post with the full decision tables: xingjianbai.com/reactive-optimizers/
  • Code and the guide: github.com/xingjian-bai/opal, and docs/GUIDE.md is 50 KB and worth reading in full
  • Package: pip install opal-optimizer
  • The tuning benchmark they used: KellerJordan’s modded-nanogpt Track 3, and the controlled benchmark for diffusion optimizers by Bolatov et al., arXiv:2609.23055, if you want the static baselines to compare against
  • Related and differently scoped: Metz et al. on learned optimizers (VeLO, arXiv:2210.09760), Chen et al. on symbolic discovery of optimization algorithms (arXiv:2302.06675), and Prime Intellect’s autonomous speedrunning experiment for the same “let an agent close the loop” instinct in a different domain
Aniket Karne
DevOps & AI Engineer · Amsterdam
Back to all posts
Reader correspondence

Comments

Powered by GitHub Discussions via Giscus. Sign in with GitHub to leave a comment.