Example

The optimizer is a model too: two averages and a preconditioner

Build PACS from the chapter's update equations, solve a scalar quadratic with it, and watch the preconditioner erase a thousandfold difference in gradient scale.

An optimizer is a model of sorts: it keeps state, observes gradients, transforms them and decides how far each parameter moves. PACS keeps two statistics per parameter, a mean gradient and a mean squared gradient.

This program builds PACS from the chapter’s update equations, solves a scalar quadratic with it, then hands it two coordinates whose gradients differ by a thousandfold.

Run it

Save this as pacs_optimizer.py and run it with Python 3.11 or later. It needs PyTorch: pip install torch, then python pacs_optimizer.py.

"""PACS: an optimizer built from gradient statistics."""
import torch
from torch.optim import Optimizer


class PACS(Optimizer):
    def __init__(self, params, lr=1e-4, beta=0.9, rho=0.999, eps=1e-8, weight_decay=0.0):
        defaults = dict(lr=lr, beta=beta, rho=rho, eps=eps, weight_decay=weight_decay)
        super().__init__(params, defaults)

    @torch.no_grad()
    def step(self):
        for group in self.param_groups:
            for p in group["params"]:
                if p.grad is None:
                    continue
                g = p.grad
                if group["weight_decay"] != 0:
                    g = g.add(p, alpha=group["weight_decay"])
                state = self.state[p]
                if not state:
                    state["step"] = 0
                    state["m"] = torch.zeros_like(p)
                    state["v"] = torch.zeros_like(p)
                state["step"] += 1
                m, v = state["m"], state["v"]
                m.mul_(group["beta"]).add_(g, alpha=1 - group["beta"])
                v.mul_(group["rho"]).addcmul_(g, g, value=1 - group["rho"])
                p.add_(m / (v.sqrt().add_(group["eps"])), alpha=-group["lr"])


def pacs_update(optimizer, p):
    state = optimizer.state[p]
    return (state["m"] / (state["v"].sqrt() + 1e-8)).tolist()


# 1. a scalar quadratic
w = torch.nn.Parameter(torch.tensor([10.0]))
optimizer = PACS([w], lr=0.05)
for _ in range(200):
    loss = (w - 3.0).pow(2).mean()
    optimizer.zero_grad(set_to_none=True)
    loss.backward()
    optimizer.step()
print(f"w after 200 steps: {w.item():.4f}  (target 3.0)")
print("optimizer state per parameter:",
      {k: (tuple(v.shape) if torch.is_tensor(v) else v) for k, v in optimizer.state[w].items()})

# 2. two gradients, 1000x apart
p = torch.nn.Parameter(torch.zeros(2))
optimizer = PACS([p], lr=1.0)
g = torch.tensor([0.01, 10.0])
p.grad = g.clone()
optimizer.step()
first = pacs_update(optimizer, p)
for _ in range(99):
    p.grad = g.clone()
    optimizer.step()
state = optimizer.state[p]
update = pacs_update(optimizer, p)
effective_lr = (1.0 / (state["v"].sqrt() + 1e-8)).tolist()

print(f"raw gradient      {[round(x, 4) for x in g.tolist()]}")
print(f"SGD step (lr 1)  {[round(x, 4) for x in g.tolist()]}")
print(f"PACS update, step 1   {[round(x, 4) for x in first]}")
print(f"PACS update, step 100 {[round(x, 4) for x in update]}")
print(f"effective lr     {[round(x, 3) for x in effective_lr]}")
print(f"parameter after 100 steps: {[round(x, 3) for x in p.tolist()]}")

Expected outcome

w after 200 steps: 3.0000  (target 3.0)
optimizer state per parameter: {'step': 200, 'm': (1,), 'v': (1,)}
raw gradient      [0.01, 10.0]
SGD step (lr 1)  [0.01, 10.0]
PACS update, step 1   [3.1622, 3.1623]
PACS update, step 100 [3.2408, 3.2408]
effective lr     [324.087, 0.324]
parameter after 100 steps: [-465.672, -465.675]

An optimizer, decomposed

The preconditioner is two lines of arithmetic, and it is worth reading as arithmetic rather than as a name:

precond.mul_(rho).addcmul_(
    grad,
    grad,
    value=1 - rho,
)

denom = precond.sqrt().add(eps)

The second moment is an average of squared gradients, and dividing the smoothed gradient by its square root gives every coordinate a step of roughly the same size.

That is what the last block shows. The raw gradient was [0.01, 10.0], so plain SGD would move the two coordinates by different factors of a thousand. PACS moved both by 3.2408, and the effective learning rate per coordinate was 324.087 against 0.324. The first step was already 3.1622, because nothing corrects the zero start.

Mechanism and limitations

Documented: the chapter gives the update equations m, v, u = m / (sqrt(v) + eps) and theta -= eta * u, states that PACS stores a step counter, a mean gradient and a mean squared gradient per parameter, and notes that it does no bias correction.

Observed: the run above. The scalar quadratic moved from 10.0 to 3.0000 in 200 steps, and the optimizer state held a step count and two tensors shaped like the parameter. The raw gradient was [0.01, 10.0], the SGD step would have been the same vector, the PACS update was [3.2408, 3.2408] after 100 steps, and the effective learning rates were 324.087 and 0.324.

Not shown. The program composes the chapter’s fragments into one run: it drops the closure path and the weight-decay branch is left at its default. The quadratic is a single parameter and the two coordinates are a demonstration, not a training run. Nothing compares PACS with AdamW, so the chapter’s rule still stands: the mechanism exists, the benefit has to be measured.

Canonical source , the chapter this example composes. Read the chapter .

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.