Reactive Optimizers

Every optimizer you have used was fixed before training began. OPAL puts an LLM agent inside the optimizer. It watches the run, then rewrites the update rule while the network trains. On toy landscapes it scores −11.6 where the best of 382,080 fixed recipes scores −7.4.

Learn what an optimizer is, from plain gradient descent to AdamW and Muon. Learn which signals a training run gives off, and how an agent that reads them can beat a recipe it started from.

Set a learning rate and momentum for the blue optimizer. The purple one starts at 0.01 and 0.9, then changes its own settings as it goes. Who reaches the bottom of the well in 300 steps? Then make the agent decide less often.

You need a little calculus (a slope) and a rough idea of what training a neural network means. We build the rest from zero.

Fixed recipe against a reactive one

Ready
0.010
0.90

A toy in the spirit of the post's Figure 6: our own landscape (a gentle slope into a narrow well) and a simple rule-based stand-in for the agent, using the same three powers the post gave it: change its settings, reset its momentum, go back to its best point. The post's numbers, over 34 landscapes: reactive −11.6, best of twelve common recipes −2.2, best of 382,080 swept static recipes −7.4 (mean best log10(f − f*), lower is better) post · §3.3.

Chapter 0

One GPU, one day, one run

Meet the researcher who cannot afford to tune, and see why one fixed recipe cannot suit every task

Picture a PhD student with a new idea. Maybe it is a model of their own design. Maybe it is a new dataset. They have one GPU for one day, and a modest budget of LLM tokens. That is enough for one serious training run post · §1.

What should they do? The obvious move is to copy the most standard training recipe, or one from a recent paper. Then they hope it fits. If it does not, the loss may spike or stall, and the day is gone post · §1.

A recipe here means every choice about how the weights get updated: the optimizer, the learning rate and how it changes over time, momentum, weight decay, clipping. The device below shows why copying a recipe is a gamble. Three tasks, one learning rate.

One recipe, three tasks

Each task is a small model whose loss surface has a different steepness. You must pick one learning rate before training. Slide it and watch all three loss curves.

0.063

A toy: each task is gradient descent on a two-dimensional bowl with a little gradient noise. The steepest directions have curvature 0.25, 2.5 and 30. The numbers are illustrative, not from the post.

No single setting works for all three. Too small, and the gentle task barely moves. Too large, and the steep task blows up. Real tasks hide their steepness, and it changes during training. Large labs answer this with a sweep: many runs, one per setting, keep the best. The student cannot afford a sweep. Few people can, at scale post · §1.

The idea: let the optimizer react

The post proposes a third way. Put an LLM agent inside the optimizer. Let it watch the run and rewrite the update rule while training goes on. The authors call this a reactive optimizer, and their system OPAL (OPtimizer with an Agent in the Loop). It "spends LLM tokens in place of GPU/human hours" post · §1.

"We put an agent at the heart of the optimizer. It watches the training dynamics, reacts to them, and rewrites the optimizer's source code as training goes."Bai, Liang, Teoh and Sitzmann · TL;DR

This lesson is part of the Agentic Vision and Robotics path. Guangzhao He's post "A New Era for Agentic Vision and Robotics Research" cites OPAL as reference 7. It is his example of tasks agents can take on because they never get tired. In his one-line description, an agent "observes training dynamics and modifies the optimizer during training" He · §2. A person could babysit a loss curve. No person can do it every few minutes, for every run, for days.

  1. Gradient descent, momentum, Adam: what an optimizer does, from zero.
  2. The recipe: schedules, weight decay, clipping, Muon, and why it is fixed in advance.
  3. Reading a run: the signals a training run gives off.
  4. OPAL's loop: analysis.py, updater.py, and an agent that thinks while training continues.
  5. Results: NanoGPT, Goldfish, LightningDiT and RAEv2.
  6. Schedules it wrote: clues, A-B-A tests and re-planned cooldowns.
  7. Rules and precision: AdamW to Muon, and bits that rounding throws away.
  8. Momentum on toy landscapes: why no fixed setting matches it.
  9. Loss spikes: corrupted data, clipping, and a gate the agent wrote.
  10. Overfitting: wrong labels, rising learning rates and weight averaging.
  11. Cost, limits, connections: what it costs, where it fails, where it sits.
Why can't the student in the post just copy a good recipe and be safe?

Chapter 1

Gradient descent, momentum, Adam

Walk downhill one step at a time, then add memory and per-weight step sizes, and see what each fix buys

Training a network means finding weights that make the loss small. The loss is one number that says how wrong the model is on a batch of data. Think of the weights as a position on a hilly landscape, and the loss as the height. We want the lowest valley.

We cannot see the whole landscape. We can only feel the slope under our feet. That slope is the gradient: for each weight, how fast the loss rises if that weight grows. So we step downhill, against the gradient.

θt
All the weights at step t, as one long vector.
η
The learning rate: how far to step. The most important knob in the recipe.
∇L(θt)
The gradient of the loss at the current weights. In practice it is computed on a small random batch, so it is noisy: this is stochastic gradient descent (SGD).

L(θ) = θ2, θ = 3 → gradient 2θ = 6. With η = 0.1: θ → 3 − 0.6 = 2.4. With η = 1.0: θ → 3 − 6 = −3, bouncing forever. With η = 1.1: θ → −3.6, and it grows each step.

That worked example holds the whole drama of this lesson. A step too small wastes time. A step too large overshoots, and past a limit it diverges. The limit depends on how sharply the valley curves, which you do not know in advance.

Downhill, one step at a time

The curve has a shallow valley on the right and a deeper one on the left. Press Step to take one gradient step. Change the learning rate and start over.

0.15

The curve is L(θ) = 0.05θ4 − 0.5θ2 + 0.25θ + 2, chosen for illustration.

Momentum: remember where you were going

Real landscapes are long, narrow ravines. The slope across the ravine is steep; the slope along it is gentle. Plain descent zig-zags across the walls and crawls along the floor. The fix is momentum: keep a running velocity, like a heavy ball rolling downhill.

v
The velocity: a decaying sum of past steps.
μ
The momentum coefficient, between 0 and 1. 0 is plain descent; 0.9 is common.

Constant gradient g = 1, η = 0.01, μ = 0.9: the velocity grows 0.01, 0.019, 0.0271, … towards η/(1 − μ) = 0.1, ten times the plain step.

Along the ravine floor the gradients agree, so momentum builds speed. Across the walls they flip sign, so they cancel. This is the heavy-ball method. The catch: near the bottom, a heavy ball overshoots and rolls back and forth.

Adam: a step size for every weight

Adam (Kingma and Ba, 2015) keeps two running averages per weight: of the gradient (m) and of the squared gradient (s). It divides one by the square root of the other. Weights with big, noisy gradients get small steps; weights with small, steady gradients get big ones.

β1, β2
Decay rates of the two averages, usually 0.9 and 0.999.
m̂, ŝ
The averages divided by (1 − βt), which undoes their bias towards zero in the first steps.

First step, g = 0.5: m = 0.1 × 0.5 = 0.05, s = 0.001 × 0.25 = 0.00025. Bias-corrected: m̂ = 0.05/0.1 = 0.5, ŝ = 0.00025/0.001 = 0.25. Step = η × 0.5/√0.25 = η, whatever the gradient's size.

Three optimizers in a ravine

The ravine is 25 times steeper across than along. Pick an optimizer and a learning rate, then watch 60 steps.

0.071

L(x, y) = ½(x2 + 25y2), starting at (−4, 0.8). Adam uses β1 = 0.9, β2 = 0.999. An illustration, not from the post.

# three update rules, from scratch (numpy)
def sgd(theta, g, st, lr):           return theta - lr * g
def heavy_ball(theta, g, st, lr, mu=0.9):
    st["v"] = mu * st.get("v", 0) - lr * g          # velocity remembers past steps
    return theta + st["v"]
def adam(theta, g, st, lr, b1=0.9, b2=0.999, eps=1e-8):
    t = st["t"] = st.get("t", 0) + 1
    st["m"] = b1 * st.get("m", 0) + (1 - b1) * g      # mean of gradients
    st["s"] = b2 * st.get("s", 0) + (1 - b2) * g * g  # mean of squared gradients
    m_hat, s_hat = st["m"] / (1 - b1**t), st["s"] / (1 - b2**t)
    return theta - lr * m_hat / (np.sqrt(s_hat) + eps)
L(θ) = θ2 and θ = 3. What does one gradient step with η = 0.1 give?

Chapter 2

The recipe, fixed in advance

Assemble a full training recipe: schedule, weight decay, clipping, Muon and parameter groups, and see why it is written before the run starts

An optimizer alone is not a recipe. Real training also decides how the learning rate changes over time, how weights are pulled towards zero, what to do with huge gradients, and which rule updates which tensors. Here is a real one: the official recipe of Goldfish, a family of small language models for 350 languages.

Goldfish official recipe post · Figure 1 details: AdamW, learning rate 1e-4, weight decay 0.01, 10% warmup then linear decay, gradient clipping at 1.0. Every Goldfish language gets the same recipe, untuned.

Learning-rate schedules

A schedule changes η with the step number. Warmup starts small and ramps up, because early gradients are wild and Adam's averages are not yet settled. Decay lowers η at the end. A large step keeps the weights bouncing around the valley floor; a small one lets them settle. The most common decay is a cosine:

ηt
The learning rate at step t, after warmup.
ηmax, ηmin
The peak and the floor.
t/T
How far through the decay we are, from 0 to 1.

Peak 3e-4, floor 0, halfway (t/T = 0.5): cos(π/2) = 0, so η = ½ × 3e-4 × 1 = 1.5e-4.

Schedule builder

Pick a schedule shape. Slide the warmup length and the point where you read the rate. Every one of these curves is fixed before step 1.

10%
50%

Peak 3e-4 is illustrative. The hold-then-cooldown shape uses a 1 − √ decay over the last 20%, the shape one OPAL agent wrote for LightningDiT post · Figure 3.

Weight decay, clipping, groups, precision

Weight decay shrinks every weight a little each step: θ ← θ − ηλθ. It keeps weights from growing without limit. AdamW is Adam with this shrinkage applied directly, outside the gradient average.

Gradient clipping caps the size of a step when the gradient is unusually large:

c
The clip threshold, for example 1.0 in Goldfish.
‖g‖
The gradient norm: the length of the whole gradient vector.

‖g‖ = 5, c = 1 → g is scaled by 0.2. The direction stays; the length becomes 1.

Parameter groups let different tensors have different rules. A common split: embeddings, norms and biases in one group, the big hidden matrices in another. That split matters for Muon (Jordan et al., 2024), the optimizer behind many recent speed records. Muon treats each weight matrix as a whole. It takes the momentum matrix and replaces it with the nearest orthogonal matrix, using a few cheap Newton–Schulz iterations. The effect: every direction in the matrix moves by the same amount, so no single direction dominates the update. Muon is meant for 2D hidden matrices; the rest stays on AdamW. The modded-nanogpt leaderboard has a tuned Muon baseline, and RAEv2-B trains with GMuon, a Muon variant post · Figure 1.

Finally, precision: weights and optimizer state can be stored in 32-bit floats or in 16-bit bfloat16, which halves memory but rounds more. Chapter 7 shows when that bites.

Why the recipe is fixed

Every piece above is decided before training. The post lists the priors researchers have built in: adaptive step sizes, preconditioning, orthogonalized updates, schedules tied to the training step, learning rates scaled with model size. Automated discovery searches across many runs for better optimizers. "Whether hand-crafted or automatically discovered, the optimizer then runs unchanged through the end of training" post · intro.

That leaves questions no fixed rule can answer. "How should an optimizer respond to an unexpected loss spike or stall? What if one module's gradients start to oscillate while the others keep improving smoothly?" post · intro.

The gradient norm is 5 and the clip threshold is 1. What does clipping do?

Chapter 3

Reading a training run

Learn the four signals a run gives off, and what each says about the learning rate

A reactive optimizer is only as good as what it can see. It cannot read billions of raw weights and gradients; they "would swamp its context" post · §2. It needs summaries. The post names the kind it means: "the gradient norm of each parameter group, the size of an update next to the weights it changes, the cosine between consecutive gradients, and which tensors exhibit unusually large gradient spikes" post · §2. Let us define each.

The loss curve is the obvious signal. Falling fast is good; flat means a stall or a floor; a sudden jump is a spike. The gradient norm ‖g‖ is the size of the slope. A spike in it means one batch, or one tensor, produced an unusually large gradient.

The update-to-weight ratio compares the size of a step with the size of the weights it changes:

r
How much of the weights one step rewrites. Many practitioners treat about 1e-3 per step as healthy; far larger means the weights are being thrashed, far smaller means they are frozen.

‖Δθ‖ = 0.002, ‖θ‖ = 2 → r = 0.001.

The cosine between consecutive gradients asks: does this step's slope point the same way as the last one?

gt · gt−1
The dot product of the two gradients. Divided by their lengths, it runs from −1 (opposite) to +1 (same direction).

gt−1 = (3, 4), gt = (−2.4, −3.2): dot = −7.2 − 12.8 = −20; lengths 5 and 4; cos = −20/20 = −1. The step jumped right over the valley.

Read it like this. Near +1: the gradient keeps pointing the same way, so you could go faster. Strongly negative: you are bouncing across a valley, so the step is too large. Near zero: noise dominates, so you are at the noise floor the learning rate allows.

The run's dashboard

A small model trains for 300 steps with noisy gradients. Pick a scenario and read the four panels. Which signal gives each problem away?

A toy: stochastic gradient descent on a 20-dimensional quadratic with curvatures from 0.1 to 10. The cosine panel is smoothed over 10 steps. Illustrative, not from the post.

A parameter group's consecutive gradients have a cosine of about −0.5, step after step. What does that suggest?

Chapter 4

OPAL's loop: two programs and an agent

Follow the data from the training process to the agent and back, and see why the agent thinks while training keeps going

OPAL's design is small. The agent gets two files it may rewrite. With "code as the entire interface", it has "maximal freedom to choose what to watch and what to change" post · §2.

ProgramRunsInput → outputStarts as
updater.pyevery step, on every GPUgradients → new weights, per parameter groupa call to your own optimizer and scheduler README
analysis.pyevery check (default every 50 steps), on rank 0the training state → a short report of statisticsa few statistics of the loss and the gradients README

The loop closes like this. Training produces gradients. updater.py turns them into weight changes. analysis.py, written by the agent, measures whatever the agent asked for. At a decision, the agent reads the reports and may rewrite either program, or keep both. "Through analysis.py, training reaches the agent in whatever form the agent chooses to see it, and through updater.py, the agent's decisions reach every step of training" post · §2.

What the agent sees: your one-sentence goal, the names and shapes of the parameters, the training losses, its own analysis reports, and read-only copies of your training script and model code. With a validation option it also sees development-set results. It is asked not to touch the model, data, loss, batch size, number of steps or evaluation README. It keeps one conversation for the whole run, so it remembers what it tried and what happened. Each decision ends with a short rationale README.

Safe swaps

A new updater takes over at the next step, on every GPU at once. It runs on trial for 20 steps. If it raises an error, the run goes back to the previous program. Every version is kept README. The package is careful here because the agent's code runs inside your training process: "this is a rule, not a sandbox" README.

Thinking while training continues

An agent decision takes time, about 40 seconds on average in the authors' runs README. The simplest design pauses training while the agent thinks. OPAL can instead let training continue and swap the edit in later, "a median of 65 updates later on Goldfish" post · §4. Most optimizer decisions are not time-critical, so the delay costs little.

td
Seconds the agent takes for one decision.
ts
Seconds per training step.
n
Number of decisions in the run; Ttrain is the training time without an agent.

td = 40 s, ts = 0.6 s → an edit lands about 67 steps late. With 10 decisions in a 3,000-second run, waiting costs 1 + 400/3,000 ≈ 1.13×.

Wait for the agent, or not?

The top lane is training; the bottom lane is the agent. Slide the step time, the decision spacing and the agent's think time. Then switch waiting on and off.

0.60 s
40 s
500 steps

A 5,000-step run. The 40-second default comes from the README's average; the step times are illustrative. Measured overheads are in Chapter 11.

Here is the whole mechanism in about 40 lines of Python. It is a teaching sketch, not OPAL's code: OPAL adds trials, rollbacks, distributed training and the agent prompt.

import threading, torch

DEFAULT_ANALYSIS = '''
def analyze(params, loss, state):
    norms = [p.grad.norm().item() for p in params]
    return {"loss": loss, "grad_norm": sum(n * n for n in norms) ** 0.5}
'''
DEFAULT_UPDATER = '''
def update(params, step, state):
    for p in params:
        p.add_(p.grad, alpha=-3e-4)          # plain SGD to start
'''

def compile_fn(src, name):
    ns = {"torch": torch}
    exec(src, ns)                 # agent code runs in your process: a rule, not a sandbox
    return ns[name]

class ReactiveOptimizer:
    def __init__(self, params, ask_agent, every=200):
        self.params = [p for p in params if p.requires_grad]
        self.ask_agent = ask_agent        # report (str) -> (analysis_src, updater_src)
        self.every, self.t = every, 0
        self.analyze = compile_fn(DEFAULT_ANALYSIS, "analyze")
        self.update = compile_fn(DEFAULT_UPDATER, "update")
        self.state, self.reports, self.pending = {}, [], None

    @torch.no_grad()
    def step(self, loss):
        self.reports.append(self.analyze(self.params, loss.item(), self.state))
        self.update(self.params, self.t, self.state)      # the current rule
        self.t += 1
        if self.pending:                                   # an edit arrived: swap it in
            a_src, u_src = self.pending; self.pending = None
            self.analyze = compile_fn(a_src, "analyze")
            self.update = compile_fn(u_src, "update")
        if self.t % self.every == 0:                       # decision time
            report = str(self.reports[-self.every:])
            threading.Thread(target=self._think, args=(report,), daemon=True).start()

    def _think(self, report):            # runs while training continues
        self.pending = self.ask_agent(report)

Using the real package is one line around your existing optimizer README:

opt = torch.optim.AdamW(model.parameters(), lr=3e-4)
opt = opal.wrap(opt, model, scheduler=sched, total_steps=steps,
                goal="ResNet-18 on CIFAR-10; judged by test accuracy after the last update",
                max_cost_usd=20)
for step in range(steps):
    loss = criterion(model(x), y); loss.backward()
    opt.step(loss=loss)           # pass the loss so the agent sees it
    opt.zero_grad(); sched.step()
Which program does the agent write to decide what it gets to see about the run?

Chapter 5

Results: training without a recipe

Compare OPAL with the recipe it started from on language models and image generators, with every number from the post

All runs in the post's main figure use Claude Opus 5.5 as the agent post · §1. Each OPAL run starts from a real recipe and is compared with it. First, what the metrics mean.

Recipe against reactive

Pick a task family. Each row runs from the recipe (blue) to OPAL started from that recipe (purple). Lower is better on every row.

Every number is quoted from the post (§1 and Figure 1 details) or from the README's results table. Each axis is zoomed to its own row.

The settings

modded-nanogpt, Track 3. A 162M-parameter GPT trained on FineWeb, with many recipes tuned for exactly this setting. The authors made two near variants with no tuned recipe: the same model on Chinese, Thai and Kyrgyz data, and the original at a quarter of the batch size. Against five leaderboard recipes with natural adjustments, OPAL started from record #36 "outperforms or matches the best baseline" in all these new settings post · §1. On the original task, the leaderboard lists 2,690, 2,930, 4,100 and 3,250 updates to reach the 3.28 target for records #46, #30, #21 (Shampoo) and #36 (tuned Muon); AdamW (#2) took 5,625 post · Figure 1 details.

Goldfish, Amharic. A 125M GPT trained from scratch on 1 GB of Amharic for 10 epochs (64,626 updates). The official recipe ends at 83.48 bits per sentence; OPAL, started from that recipe, ends at 81.11 in one shot. A learning-rate sweep finds a static recipe at 80.89, ahead of that OPAL run. But OPAL started from the swept recipe ends ahead again, at 80.73 post · §1. The sweep had nine static recipes besides the official one post · Figure 1 details.

Image generation. On LightningDiT-XL/1 (ImageNet 256×256, 64 epochs, official recipe AdamW), OPAL reaches FID-50K 1.83 against 2.18 with guidance, and 4.33 against 5.15 without. On RAEv2-B, whose recipe already uses the Muon variant GMuon, 3.19 against 3.39 post · §1.

One way to compare rows is the relative gain:

b
The recipe's final score (lower is better).
o
OPAL's final score, started from that recipe.

Goldfish: (83.48 − 81.11)/83.48 = 2.8%. LightningDiT guided: (2.18 − 1.83)/2.18 = 16.1%. Goldfish from the swept recipe: (80.89 − 80.73)/80.89 = 0.2%.

On Goldfish Amharic, a learning-rate sweep found a static recipe at 80.89, better than OPAL's 81.11 from the official recipe. What happened when OPAL started from the swept recipe?

Chapter 6

The schedules it wrote

See how agents set learning rates from clues, from A-B-A experiments and from the trend of the loss

The schedules the agents built "are intricate, with separate multi-stage schedules for each parameter group, and differ from run to run" post · §3.1. Several raise the learning rate mid-run, which modern schedulers rarely do. The post groups the evidence the agents cited into four kinds.

KindWhat the agent didIn its words
Deduced from cluesA SiT agent measured the cosine between consecutive gradients per group. Where it was negative it cut the rate: the timestep embedder went to 0.3× then 0.15×."…because its cosine is still around −0.22." post · §3.1
A-B-A testA RAEv2 agent alternated two rates over stretches of a few hundred updates and compared the loss. It switched to 2× from update 3,100."2× gives faster real progress than 1.5×." post · §3.1
Trial and errorThe same agent tried 1.3×, then 1.5×, then ran 2×, 2.5× and 2.75× for about 650 updates each, and kept 2×."My explanation from last time was wrong…" post · §3.1
Re-planned cooldownAt step 190K, a SiT agent moved its cooldown from 320K to 280K. The RAEv2 agent started its cooldown at 45% of the run instead of the planned 75%."…holding the weights at a noise floor set by the learning rate, rather than making progress." post · §3.1

Why A-B-A and not A-B?

Suppose you want to know whether rate B beats rate A. You run A for a stretch, then B, and compare how much the loss fell. The trouble is that loss always falls more slowly later in training. So B, run second, looks worse even when it is not. Running A again after B fixes this. Average the two A stretches, and the slowdown cancels to first order:

ΔB
How much the loss fell during the B stretch.
ΔA1, ΔA2
How much it fell in the A stretches before and after.

ΔA1 = 0.050, ΔB = 0.046, ΔA2 = 0.038. Naive A-B: 0.046 < 0.050, so "B is worse". A-B-A: 0.046 − 0.044 = +0.002, so B is better.

Run an A-B-A test

A hidden curve sets how fast the loss falls at each rate multiplier. Choose A and B, then run three stretches of 650 updates. Compare the naive verdict with the A-B-A verdict.

1.50×
2.00×

A toy. Progress per update is proportional to (loss − floor) and to a hidden function of the multiplier that peaks at 2×. The 650-update stretches echo the post's RAEv2 run post · §3.1; everything else is illustrative.

Why does an A-B-A test run rate A a second time after B?

Chapter 7

New rules and the precision of every bit

Watch agents move tensors from AdamW to Muon, and find the bfloat16 rounding that silently swallowed updates

The reactive optimizers do not only tune numbers. They "change which rule updates which tensors" post · §3.2. Many start from AdamW and move the attention and MLP matrices to Muon, keeping AdamW for the rest. Later they make more specific moves.

That last example matters. The agent runs an experiment and reverts it when it does not help, the way a careful engineer would.

Where precision matters

A floating-point number stores a sign, an exponent and a few significant bits. bfloat16 keeps 8 significant bits (7 stored, 1 implicit). So between 2e and 2e+1, neighbouring bfloat16 values are evenly spaced:

w
A weight value.
e
Its binary exponent: the power of two just below |w|.

w = 15: 23 = 8 ≤ 15 < 16, so e = 3 and spacing = 2−4 = 0.0625. An update of 0.01 is less than half a gap, so 15 − 0.01 rounds back to 15. The update is lost.

This is exactly what an OPAL agent found on modded-nanogpt. It measured that token-embedding entries were about 15 in size, where adjacent bfloat16 values are 0.0625 apart. As the learning rate decayed, rounding "would throw away a growing share of each update". From update 1,040 it kept that one matrix's Adam moments in float32 and wrote the weights back with compensated rounding, leaving every other tensor as it was post · §3.2.

Where did my update go?

A weight receives 50 identical small updates. Slide its size and the update size. Turn on compensated rounding, which carries the rounded-away remainder into the next step.

15.0
0.0100

Exact bfloat16 round-to-nearest-even, computed in the page. The weight size 15 and spacing 0.0625 are the post's post · §3.2; the update sizes are yours.

A bfloat16 weight equals 15. Why does an update of 0.01 vanish?

Chapter 8

Momentum on toy landscapes

Sweep every fixed setting of a heavy-ball optimizer, and see why one reactive run can beat the whole sweep

To study momentum cleanly, the authors moved to 2D toy landscapes. There, unrestricted OPAL "would simply replace the default recipe with a second-order method within a few decisions". So they restricted it to the heavy-ball algorithm and let it control only the hyperparameters. They added three new powers: reset the momentum, return to the best point so far, and jump to a random nearby point post · §3.3.

On the post's example landscape, the start sits beside a nearly flat saddle where common optimizers stall. The reactive optimizer raises its momentum to cross the flat stretch. It lowers it as the gradient falls near the minimum. Each time it overshoots, it goes back to its best point and restarts its momentum post · §3.3. The hero at the top of this page plays the same game on our own landscape.

The score is how close the best point gets to the true minimum, on a log scale:

f(xt)
The landscape's height at step t; the best over the 300-step budget counts.
f*
The true minimum height. Each unit lower is ten times closer.

Best gap 2.5 × 10−12 → score ≈ −11.6. Best gap 4 × 10−8 → ≈ −7.4. That difference is about 16,000 times closer.

Optimizer (post, 34 landscapes)Mean best log10(f − f*) ↓
Reactive optimizer−11.6
Best of 382,080 swept static recipes−7.4
Best default setting (Adam, lr 0.1)−2.2
Nesterov 0.9, lr 0.01−0.5
Gradient descent, lr 0.010.6
Adam, lr 0.0011.1

Source: the post's Figure 6 table and §3.3 text post · §3.3. "Best of twelve common recipes" is −2.2.

The whole sweep at once

Each cell is one fixed heavy-ball setting, run for 300 steps on the hero's landscape. Brighter is closer to the minimum. Tap a cell to see its path next to the reactive run.

Computed in your browser: 40 learning rates from 0.001 to 1 by 30 momenta from 0 to 0.99. Our landscape, not the post's; the post's numbers are in the table above.

The sweep shows why a fixed setting struggles. The slope needs high momentum to cross quickly. The narrow well needs low momentum and a small step to settle. One setting must compromise, and the few that work sit on a thin ridge you cannot find without the sweep. The reactive run does not compromise. It changes settings when the landscape changes.

In the post's toy experiments, which three extra powers did the restricted heavy-ball agent get?

Chapter 9

Loss spikes

Inject corrupted data into a run and compare clipping, a fixed recipe and an agent that learns to gate bad batches

A loss spike is a sudden jump in the loss. Some come from the optimizer: one tensor's gradient explodes. Some come from the data: particular batches interact badly with the model's state post · §3.4. Gradient clipping limits each step, but it "does not in general protect against noisy labels" post · §3.4. Many small bad steps in a row still add up.

Spikes from one tensor

In a large SiT run, an agent traced 17 of the 18 gradient spikes it logged to the timestep embedder. It gave each tensor its own clipping threshold, set from that tensor's recent gradient norm. A spike in the embedder no longer cut the updates of every other tensor. The old global threshold stayed only as a backstop post · §3.4. Both moves have precedents: per-tensor clipping against each tensor's history (AdaGC), and damping the one layer that spikes, as GLM-130B did for its embeddings.

Spikes from bad data

The controlled experiment: insert four stretches of random images and random labels into CIFAR-10 and train a ResNet-18. OPAL is not told about the corruption post · §3.4. The first two stretches cost OPAL 50 and 66 points of test accuracy, about as much as the baselines. In between, it added loss damping, replaced it with clipping, then wrote a gate that holds back batches whose loss is far above recent clean ones. After tuning the gate, the third stretch cost 12 points and the fourth none post · §3.4.

OptimizerStretch 1Stretch 2Stretch 3Stretch 4
OPAL−50.0−66.3−12.1+0.7
Muon + clip−74.4−73.6−75.5−28.5
Muon−73.6−77.7−69.1−37.2
AdamW + clip−62.7−60.0−38.1−42.0
AdamW−61.4−32.4−53.8−68.5
Stable-SPAM−54.0−66.3−69.8−70.7

Change in test accuracy (points) across each corrupted stretch, ResNet-18 on CIFAR-10 post · Figure 7.

The gate is a simple rule once you know to write it:

Lbatch
This batch's loss, known before the update is applied.
L̄clean
The mean loss of recent batches that passed the gate.
k
The threshold. Too loose and bad batches pass; too tight and hard but honest batches are skipped.

L̄clean = 0.25, k = 3: any batch with loss above 0.75 is held back. A corrupted batch at loss 2.4 is skipped; a hard clean batch at 0.5 passes.

Four bad stretches

A classifier trains for 1,000 steps. The red bands are stretches of random inputs with random labels. Pick a defence and read the accuracy lost in each band.

A toy run in your browser: logistic regression on 8-dimensional data, batches of 16. The reactive policy is scripted to follow the post's sequence (damping after stretch 1, a loose gate after stretch 2, a tuned gate after stretch 3). Its numbers are ours; the real ones are in the table above.

In the post's corrupted-CIFAR-10 experiment, why did OPAL lose about as much as the baselines in the first two stretches but little in the last two?

Chapter 10

Escaping overfitting

Train on labels that are 10% wrong, and see how rising learning rates plus weight averaging avoid memorising them

Overfitting means the model fits its training set, including its mistakes, and gets worse on new data. Wrong labels make it easy to see. A network trained long enough will memorise them: asked about a mislabeled training image, it answers with the wrong label it was taught.

The setting post · Figure 8: a ResNet-18 trained on CIFAR-10 for 120 epochs, without data augmentation. Of 50,000 training images, 10% are held out with correct labels as a development set. Of the remaining 45,000, 10% get a fixed wrong label. The agent saw training statistics plus development loss and accuracy. It was not told some labels were wrong, and it never saw test performance. AdamW at learning rate 3e-3 is both the baseline and OPAL's starting recipe.

RunTest lossTest acc.Mislabeled images: true label ↑Mislabeled images: wrong label ↓
OPAL (average of its weights from epochs 96–117, chosen on dev)0.68578.6%77.5%3.7%
AdamW, final weights2.49373.5%0.0%100.0%
AdamW, stopped early on dev1.01072.9%59.7%19.4%
EMA strategy adapted from OPAL0.83277.5%70.0%14.2%

From the post's Figure 8 table post · §3.5. "Mislabeled images" are the 4,500 training images with a wrong label.

AdamW trained straight through gives the wrong trained label for all 4,500 mislabeled images: complete memorisation. OPAL gives it for 3.7%, and the true label for 77.5% post · §3.5. Its strategy combined "progressively higher learning rates with weight averaging", choosing the final average on the development set. Its own analysis program called this "extended SWA" post · §3.5.

Why averaging helps

With a large learning rate, SGD cannot settle into the narrow dips that fit individual wrong labels. It bounces around the floor of a wide valley. Each single weight vector is a noisy point. Their average sits near the valley's centre. This is stochastic weight averaging (SWA, Izmailov et al., 2018):

θ̄
The averaged weights used at the end.
θk
Weights saved at K points in the run, for example once per epoch from epoch 96 to 117.

Iterates at x = 0.9, −0.7, 0.4, −0.5 around a centre at 0: each is 0.4 to 0.9 away, but their mean is 0.025, much closer than any of them.

Bounce, then average

SGD with noisy gradients runs 300 steps in a valley. Raise the learning rate: the last point lands far from the centre, but the average of the last 150 points stays close. Press Run again for new noise.

0.30

L(x, y) = ½(x2 + 4y2) with Gaussian gradient noise of size 1. An illustration of the averaging idea, not the post's experiment.

Asked to classify the 4,500 mislabeled training images, how often did the AdamW baseline (final weights) give the wrong label it was trained on?

Chapter 11

Cost, limits and connections

Price the agent against the GPUs, list what OPAL cannot do yet, and place it among other ways to automate optimization

Wall-clock overhead

If training waits at every decision, runs take 1.30× to 4.39× as long. If training does not wait, the overhead drops to 1.01× to 1.14× post · §4. What remains is the cost of running what the agent wrote: an update rule that costs more per step (such as Muon's orthogonalization, or a tensor kept in float32) and the probes of its analysis program post · Figure 9.

TaskHardwareNot waitingWaiting
Goldfish Amharic1 H1001.01×1.30×
modded-nanogpt Track 38 H100s1.11×4.39×
LightningDiT-XL/18 H100s1.14×1.30×
RAEv2-B8 H100s1.06×1.61×

Wall-clock time relative to the same task without an agent, from the labels of the post's Figure 9 post · Figure 9.

Tokens against GPU hours

The LightningDiT agent made about 100 decisions for $6.42 at Claude Opus 5.5 list price, on top of about 74 H100-hours of training, about $510 at AWS's on-demand price post · §4. The ratio is the number to watch:

n
Number of agent decisions.
cd
Token cost of one decision.
H
GPU-hours of training.
p
Price of one GPU-hour.

$6.42 / $510 ≈ 1.3%. The agent's cost does not grow with model size, so on a run ten times larger the share falls to about 0.13%.

What does the agent cost?

Defaults reproduce the post's LightningDiT example. Slide the size of the run and the number of decisions.

74
100

$0.0642 per decision and about $6.90 per H100-hour are derived from the post's $6.42 for about 100 decisions and about $510 for about 74 H100-hours post · §4.

Honest limits

Where it sits

Automating optimization is old. Learned optimizers such as VeLO train a network to be the optimizer, across many tasks. Population Based Training adapts hyperparameters by copying good members of a population of runs. Symbolic discovery found the Lion optimizer by search over programs. Agents such as the AI Scientist search over many runs. Self-Adapting Language Models let a model direct its own fine-tuning post · intro, refs. OPAL differs in two ways: it is zero-shot inside a single run, and it puts the whole optimizer algorithm up for rewriting post · intro.

It is also a clean example of Guangzhao He's "new territory" argument. Each decision is the kind an expert could make. What no expert can do is sit with a run "at countless training steps", watching every module post · §5. An agent can.

The cheat sheet

IdeaIn one line
Gradient descentθ ← θ − η∇L; too small crawls, too large diverges.
Momentum, AdamVelocity crosses ravines; per-weight scaling makes each step about η.
RecipeOptimizer, schedule, decay, clipping, groups, precision: all fixed before step 1.
SignalsLoss, gradient norm, update/weight ratio, gradient cosine, spikes.
OPALAn agent rewrites analysis.py (what to see) and updater.py (how to step) mid-run.
Non-blockingTraining continues while the agent thinks; edits land later (median 65 updates on Goldfish).
ResultsGoldfish 83.48 → 81.11; LightningDiT FID 2.18 → 1.83; RAEv2-B 3.39 → 3.19.
Emergent tacticsA-B-A tests, per-tensor clipping, a batch gate, float32 for one matrix, extended SWA.
Cost$6.42 of tokens against about $510 of GPU time; 1.01× to 1.14× wall-clock when not waiting.

Related lessons

The takeaway. An optimizer has always been a fixed program. OPAL turns it into a program that an agent keeps rewriting while it watches the run. The agent is slow and costs tokens, but it reacts to what this run actually does, and on long runs without a tuned recipe that is worth more than any recipe chosen in advance.
Why did OPAL show its smallest gains on modded-nanogpt?

Now press Present or Teach and explain, from memory, how an agent that rewrites two small programs can beat the recipe it started from, and why it needs a long run to do it. Then go back to the hero and try to find a fixed setting that beats the agent.

Based on "Reactive Optimizers" by Xingjian Bai, Jia-Hao Liang, Jayden Teoh and Vincent Sitzmann (blog post, October 2026) and the OPAL repository README. All quotations are from those sources and are attributed in place.
Read the post · OPAL on GitHub · Back to Veanors