Module contents
Lesson 22 of 23Advanced 120 min

Designing a new algorithm: from bottleneck to validated method

Developing new algorithms by diagnosing bottlenecks, deriving changes, testing implementations, climbing the validation ladder, verifying mechanisms and defining limits, using AdamW as a guided case.

After this lesson you can

  • Diagnose a method's bottleneck with targeted experiments and analysis of its derivation.
  • Derive an algorithmic modification from an objective or principle rather than trial and error.
  • Write algorithm tests using known solutions, invariants and gradient checks.
  • Climb the validation ladder and decide when to stop or step back.
  • Use controls to verify the claimed mechanism and delimit its scope of validity.

Before you start

A modification needs a diagnosis

Designing an algorithm starts with a verifiable limitation. An improvement in a metric does not by itself explain which part of the method caused it. Bottleneck diagnosis combines reading the derivation, predicting the mechanism and experiments that distinguish that prediction from alternatives. Start with a case small enough to check every operation before comparing large models.

The AdamW case starts with confusion between L2 regularization and weight decay. For SGD without momentum, if the original loss has gradient gtg_t and we add λ∥w∥2/2\lambda\|w\|^2/2, then

wt+1=wt−η(gt+λwt)=(1−ηλ)wt−ηgt.w_{t+1}=w_t-\eta(g_t+\lambda w_t)=(1-\eta\lambda)w_t-\eta g_t.

The step on the right applies multiplicative decay and then the original gradient. The equivalence uses the same η\eta, the same convention for λ\lambda and SGD without momentum; do not automatically extend it to SGD with momentum. The factor also depends on the learning rate. If ηλ\eta\lambda is too large, the contraction interpretation no longer holds.

In Adam with L2, gt+λwtg_t+\lambda w_t is fed into the first- and second-moment moving averages. Those averages and the denominator depend on the entire history of the penalized gradient. Therefore, in general the step cannot be decomposed exactly into an unpenalized Adam step plus −ηλw/(v^+ϵ)-\eta\lambda w/(\sqrt{\hat v}+\epsilon): changing the penalty also changes m^\hat m and v^\hat v. If the preconditioner is frozen and a linear penalty term isolated, its inverse scaling with the denominator illustrates the asymmetry, but it is a diagnostic approximation, not the full Adam equation.

InteractiveL2 versus decoupled decay
00.0020.0040.0060.0080.010.012L2, large1e-4L2, small0.01Decoupled, both0.001Penalty step magnitude

Weights equal to 1, rate 0.01 and fixed denominators. Multiplicative decay is equal per coordinate, but its size still depends on the rate.

0.10
10
Small denominator0.1
Illustration with frozen denominators, equal weights and a fixed rate. Only the penalty term is shown; real Adam moments are not frozen.

For example, with denominators 10 and 0.1, equal weights, negligible ϵ\epsilon and the frozen model, the first L2 contribution is one hundredth of the second. This comparison does not predict the exact ratio of complete Adam steps. History can change the direction and magnitude of the moving average. The decisive test compares implemented trajectories, not just this simplified calculation.

Deriving the change

A principled derivation separates the desired effect from the adaptive rule: compute moments with the original gradient and apply multiplicative weight decay outside the preconditioner. In PyTorch’s convention, AdamW applies w←(1−ηλ)ww\leftarrow(1-\eta\lambda)w and then the adaptive update. Regularization does not enter the moments, but contraction still depends on η\eta and the number of steps. “Decoupled” does not mean complete mathematical independence among all hyperparameters.

The original paper reports a lower empirical dependence of the optimal decay choice on learning rate in the regimes studied. A grid on another dataset may not show the same geometry; nor does it establish that AdamW always wins. Compare coefficient and schedule definitions before reading curves or transferring values between implementations.

An explanatory proposal should generate predictions that an alternative does not. If the proposed mechanism is “the penalty is rescaled unequally,” inspect per-coordinate updates under controlled input and compare with a frozen preconditioner. Then run the real implementation with moments, including a case without regularization. If the methods disagree when λ=0\lambda=0, there is probably another difference in the implementation or protocol.

A useful diagnosis starts with a trace someone else can reproduce: initial weights, gradient sequence, moments and values after each operation. Consider two coordinates with different gradient histories, not just two gradients in one step. Compare the L2 trajectory with AdamW and a library reference. If you see a discrepancy, a stage-by-stage comparison indicates whether it appears when constructing the gradient, correcting bias or applying decay. This reduces a final drop in accuracy to a testable hypothesis.

The convention also matters for the schedule. Applying decay at every step produces cumulative contraction ∏t(1−ηtλ)\prod_t(1-\eta_t\lambda) before considering gradient updates. Increasing the steps or changing the rate changes that product even if λ\lambda stays fixed. If biases or normalization parameters are excluded, document which groups received decay. Two runs with the same optimizer name and coefficient can have different effective budgets.

Tests before metrics

Algorithm testing uses a closed-form solution where available, invariants and an independent reference. For a quadratic f(w)=∥w−a∥2/2f(w)=\|w-a\|^2/2 without decay, the minimum is aa; check that loss decreases and the trajectory converges in a chosen configuration. With zero gradient and zero initial state, an AdamW step multiplies the weight by 1−ηλ1-\eta\lambda. If momentum has already accumulated, zero gradient does not immediately eliminate the adaptive update: that invariant holds only for zero state.

Compare your implementation with torch.optim.Adam and torch.optim.AdamW over several steps, sizes and coefficients, using tolerance appropriate to the numerical type. A single step does not test moment updates or their bias correction. An absent gradient is not the same as a zero gradient: in PyTorch a parameter without a gradient is skipped, while a zero gradient can trigger decay. Check both cases and do not assume advanced library options are implemented if they do not appear in your code.

For a differentiable loss, the central difference (f(w+hei)−f(w−hei))/(2h)(f(w+h e_i)-f(w-h e_i))/(2h) approximates each gradient component. If hh is too large there is truncation error; if too small, rounding dominates. Use several hh and double precision. A passing test does not prove the objective is appropriate: it only checks a particular property in the selected cases.

The reference can share the same conceptual defect as your implementation. Therefore supplement a library comparison with independent tests: the zero-gradient case, a hand-calculated contraction and a quadratic with known minimum. Also test boundary coefficients, multidimensional vectors and a sequence of alternating-sign gradients. If the difference appears only in single precision, compare tolerances and magnitudes before attributing it to an error; if it grows systematically at every step, inspect state and bias corrections.

The validation ladder

The validation ladder orders questions from low to high cost. Quadratic: sign, scales and state. Synthetic data: sensitivity to scale and recovery under a controlled model. Small real model: interaction with normalization, compute and training decisions. Benchmark: generalization to different tasks and resources. Failure at a rung calls for stepping back; passing it does not prove that all higher rungs will work.

InteractiveThe validation ladder

Failure it may reveal: A sign or bias-correction error appears in a known trajectory.

Decision: If it does not match the reference, correct it before proceeding.

Step1 / 4
Select a rung to see a possible failure and the associated decision. The diagram is a diagnostic guide, not the result of a run.

With synthetic data the generating truth is known, but an estimator on a finite sample need not recover its parameters exactly. The difference between truth and estimate combines noise, regularization and implementation error. A small real-data experiment introduces preprocessing and hyperparameter selection; keep validation separate from test and record seeds and cost. A benchmark adds other sources of variation and requires following its rules.

If the analytic logistic gradient fails against finite differences, there is no point tuning the learning rate first: fix the loss function or derivative. If it passes but training diverges, inspect scales, rates and numerical saturation. If the small experiment improves but the benchmark does not, consider whether the data, architecture or budget changed the regime. Do not force a single explanation after the fact: record competing hypotheses and which test would distinguish them.

Does it work for the proposed reason?

Mechanism verification compares the explanation with alternatives. An improvement might come from a different effective rate, more accumulated regularization or a larger search. Matching only the name of λ\lambda does not necessarily match total contraction: this depends on rate and steps. Calculate the product of decay factors and document which parameters are regularized.

InteractiveControls for a hypothetical improvement

A hypothetical improvement could have other explanations. Mark controls you would include and specify how to perform them.

Still uncontrolled in the plan: More search budget; Change in effective rate; Different total decay.

Proposed controls0 / 3
Select controls for a fictional plan. A checkbox indicates intent; it does not certify that a control was run or eliminate all alternative explanations.

Zhang and colleagues study several mechanisms of weight decay depending on optimizer and architecture, including changes in effective rate. A performance map can therefore be consistent with an explanation without uniquely identifying it. Design an intervention that changes the mechanism while preserving other conditions, and record which observation would support or weaken the claim. An ablation without matching budgets can confound the effect of the change with the effect of the search.

Validity boundaries are part of the result: architecture, distribution, scale, precision, schedule, learning rate and parameter selection can change behavior. Also report regimes where it does not improve and uncertainty across seeds. Two seeds and one task are an exploration; they do not justify a general claim about all benchmarks. A strong baseline requires the same access to data and a comparable budget.

In a grid, the observed minimum is selected from multiple combinations and can be optimistic due to validation noise. Reserve the test set for the chosen configuration, report the whole grid and repeat with new seeds if making a comparative claim. The lab’s two test results alone do not provide a reliable interval. A strong conclusion would require more repetitions and tasks, a prior selection rule and sufficient resources for both methods.

The following grid comes from the actual CPU run of this lesson’s lab: a small CNN, 1,024 training examples, 256 validation examples, two epochs and seeds 31 and 32. Each cell shows mean validation accuracy, not test accuracy: using the test to choose the best hyperparameter would contaminate it. Rates, decay and budget are defined in the file; these measurements are a small exploration, not a reproduction of the original paper’s results or geometry.

InteractiveLearning rate and decay on CIFAR-10
Adam+L2
η / λ00.010.1
0.0003
0.001
0.003
AdamW
η / λ00.010.1
0.0003
0.001
0.003

Rows: learning rate η; columns: decay λ. More intense color indicates higher mean validation accuracy; common scale 0.170 to 0.287. Two seeds. Selected: Adam+L2, η=0.0003, λ=0; seed 31: 0.184; seed 32: 0.172.

Selected mean0.178
Data measured in the described CPU run, mean validation accuracy over two seeds. Select a cell to see both; scale and result depend on this configuration.

Validation selected rate 0.003 and decay 0 for Adam+L2, with mean 0.283; for AdamW it selected 0.003 and 0.1, with mean 0.287. The two test seeds yielded 0.301 and 0.301, versus 0.305 and 0.301, respectively. These are 256 test images and two seeds: small differences may be noise, and this grid proves neither the mechanism nor general superiority. Download the measurements and configuration to check the complete values.

Local lab: Adam and AdamW from scratch

The following cell implements two torch.optim.Optimizer classes and compares each with PyTorch over 100 double-precision steps, with and without decay. It requires Python, PyTorch and a device-compatible installation; see the official guide. The comparison runs on CPU and does not require downloading data. The implementation covers dense gradients and the options shown; it does not implement AMSGrad, maximization, complex parameters or all library variants.

[ ]Compare with PyTorchLocal GPU
"""Adam con L2 acoplada y Adam con decaimiento desacoplado; sin AMSGrad."""
import math
import torch


class AdamFromScratch(torch.optim.Optimizer):
    def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0):
        if lr < 0 or eps < 0 or weight_decay < 0 or not all(0 <= b < 1 for b in betas):
            raise ValueError('Hiperparámetros fuera de rango')
        super().__init__(params, dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay))

    @torch.no_grad()
    def step(self, closure=None):
        loss = None
        if closure is not None:
            with torch.enable_grad():
                loss = closure()
        for group in self.param_groups:
            beta1, beta2 = group['betas']
            for param in group['params']:
                if param.grad is None:
                    continue
                grad = param.grad
                if grad.is_sparse:
                    raise RuntimeError('Gradientes dispersos no compatibles')
                state = self.state[param]
                if not state:
                    state['step'] = 0
                    state['exp_avg'] = torch.zeros_like(param)
                    state['exp_avg_sq'] = torch.zeros_like(param)
                state['step'] += 1
                step = state['step']
                if self.decoupled:
                    param.mul_(1 - group['lr'] * group['weight_decay'])
                elif group['weight_decay']:
                    grad = grad.add(param, alpha=group['weight_decay'])
                mean, square = state['exp_avg'], state['exp_avg_sq']
                mean.mul_(beta1).add_(grad, alpha=1-beta1)
                square.mul_(beta2).addcmul_(grad, grad, value=1-beta2)
                denom = square.sqrt().div_(math.sqrt(1-beta2**step)).add_(group['eps'])
                param.addcdiv_(mean, denom, value=-group['lr']/(1-beta1**step))
        return loss

    decoupled = False


class AdamWFromScratch(AdamFromScratch):
    decoupled = True

import torch

torch.manual_seed(22)
for ours, reference in ((AdamFromScratch, torch.optim.Adam), (AdamWFromScratch, torch.optim.AdamW)):
    for wd in (0, .1):
        a = torch.nn.Parameter(torch.tensor([.4, -1.2], dtype=torch.float64))
        b = torch.nn.Parameter(a.detach().clone())
        options = dict(lr=.003, betas=(.8,.95), eps=1e-7, weight_decay=wd)
        left, right = ours([a], **options), reference([b], **options)
        for step in range(100):
            grad = torch.randn_like(a) * (1 + step / 100)
            a.grad, b.grad = grad.clone(), grad.clone()
            left.step(); right.step()
            torch.testing.assert_close(a, b, rtol=1e-10, atol=1e-12)
        print(ours.__name__, 'weight_decay', wd, '100 pasos: coincide')

# Si falta gradiente, PyTorch no actualiza ni aplica decay al parámetro.
p = torch.nn.Parameter(torch.tensor([2.]))
optimizer = AdamWFromScratch([p], lr=.1, weight_decay=.2)
optimizer.step()
assert p.item() == 2
p.grad = torch.zeros_like(p)
optimizer.step()
torch.testing.assert_close(p, torch.tensor([1.96]))
print('Gradiente ausente y gradiente cero: comportamiento verificado')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To explore a CNN on CIFAR-10, download the optimizer, its tests and the experiment into the same folder. Install PyTorch, torchvision and NumPy following the official instructions for your system and run python test_adam_scratch.py followed by python cifar_experiment.py --device cuda --data ./cifar-data --out results.json; use --device cpu if you do not have CUDA. The program downloads CIFAR-10 through torchvision and checks its integrity. It requires network access and disk space. The JSON file records version, splits, seed, configuration, validation of the full grid and test of the validation-selected configuration.

As local practice, implement step in your own copy of adam_scratch.py from the equation and run the test file without first consulting the solution. Add a gradient sequence absent from the tests and compare it with torch.optim.AdamW over 100 steps. Save the sequence and tolerances used: passing these examples does not guarantee compatibility with unimplemented options. Keep the original downloaded version for comparison if a discrepancy arises.

The example uses 1,024 training images, 256 validation images, 256 test images, two epochs and two seeds for a small grid. Selection uses validation before consulting test. It does not reproduce the original article’s architecture, duration or budget; such a small grid may not reveal decoupling. If you change epochs or data size, the previous values no longer describe that run. Do not compare a wider search for one method with a smaller one for the other.

Browser lab: a minimal ladder

The NumPy cell implements AdamW with dense gradients and records the tests. It checks the quadratic without decay, the contraction property with zero initial state and a logistic gradient against finite differences. The data are synthetic, generated with a fixed seed; falling loss is an execution check, not proof of performance on real data. An independent 100-step comparison with PyTorch is included in the lesson’s local package.

[ ]Quadratic, invariants and logistic regressionBrowser
"""AdamW NumPy y registro de pruebas para una escalera de validación."""
from dataclasses import dataclass
import numpy as np


@dataclass
class ValidationRecord:
    stage: str
    failure: str
    result: str

    def validate(self):
        if not all(x.strip() for x in (self.stage, self.failure, self.result)):
            raise ValueError('Registra etapa, posible fallo y resultado observado')


class NumpyAdamW:
    def __init__(self, initial, lr=.01, beta1=.9, beta2=.999, eps=1e-8, weight_decay=0.):
        if lr < 0 or eps <= 0 or weight_decay < 0 or not (0 <= beta1 < 1 and 0 <= beta2 < 1):
            raise ValueError('Hiperparámetros fuera de rango')
        self.w = np.array(initial, dtype=float, copy=True)
        self.m = np.zeros_like(self.w)
        self.v = np.zeros_like(self.w)
        self.t = 0
        self.lr, self.beta1, self.beta2, self.eps, self.wd = lr, beta1, beta2, eps, weight_decay

    def step(self, grad):
        grad = np.asarray(grad, dtype=float)
        if grad.shape != self.w.shape or not np.isfinite(grad).all():
            raise ValueError('Gradiente incompatible o no finito')
        self.t += 1
        self.m = self.beta1 * self.m + (1-self.beta1) * grad
        self.v = self.beta2 * self.v + (1-self.beta2) * grad**2
        mhat = self.m / (1-self.beta1**self.t)
        vhat = self.v / (1-self.beta2**self.t)
        self.w = (1-self.lr*self.wd)*self.w - self.lr*mhat/(np.sqrt(vhat)+self.eps)
        return self.w.copy()

rng = np.random.default_rng(22)
target = np.array([2., -1.])
opt = NumpyAdamW([0., 0.], lr=.03)
for _ in range(500):
    opt.step(opt.w - target)
assert np.linalg.norm(opt.w-target) < .01
print('Cuadrática:', np.round(opt.w, 4))

for initial in rng.normal(size=(20, 3)):
    opt = NumpyAdamW(initial, lr=.1, weight_decay=.2)
    np.testing.assert_allclose(opt.step(np.zeros(3)), .98*initial)
print('Contracción inicial: 20 casos')

X = rng.normal(size=(200, 3))
truth = np.array([.7, -1., .4])
prob = 1/(1+np.exp(-(X @ truth)))
y = (rng.random(200) < prob).astype(float)
def loss(w):
    z = X @ w
    return np.mean(np.logaddexp(0, z) - y*z)
def gradient(w):
    z = np.clip(X @ w, -50, 50)
    return X.T @ (1/(1+np.exp(-z))-y)/len(y)
w = np.array([.1, -.2, .3]); h = 1e-5
numeric = np.array([(loss(w+np.eye(3)[i]*h)-loss(w-np.eye(3)[i]*h))/(2*h) for i in range(3)])
np.testing.assert_allclose(gradient(w), numeric, rtol=1e-6, atol=1e-8)
initial_loss = loss(w)
opt = NumpyAdamW(w, lr=.03, weight_decay=.01)
for _ in range(200): opt.step(gradient(opt.w))
assert loss(opt.w) < initial_loss
print('Gradiente logístico: coincide; pérdida:', round(initial_loss,4), '→', round(loss(opt.w),4))
records = [ValidationRecord('Cuadrática','signo o momentos','pasa'),
           ValidationRecord('Logística sintética','gradiente incorrecto','pasa')]
for record in records: record.validate()
print('Etapas registradas:', len(records))

Download the validation extension alongside researchkit.py from the first lesson. Also download the NumPy versus PyTorch test to the same folder and run python test_numpy_adamw.py locally. The cells are standalone and do not depend on another page or an earlier browser session. A “pass” record should be accompanied by the test and its conditions; empty fields are not accepted.

Exercises

Prove on paper the equivalence of SGD without momentum with L2 and decay, indicating how the factor depends on η\eta. Then explain why the same argument cannot be directly applied to Adam: write the updates for mtm_t and vtv_t with the penalized gradient and point out where history changes. Check your proof against the derivation in the first section; an answer that freezes vtv_t must state that additional assumption.

Quiz
What transformation reproduces SGD without momentum with L2 penalty coefficient λ and rate η?
Numeric
In the frozen-preconditioner model, two weights and coefficients are equal, the denominators are 10 and 0.1 and epsilon is negligible. What is the ratio of the first penalty term to the second?
Quiz
An improvement is attributed to decoupling. What control helps rule out its being due only to a different total amount of decay?
Quiz
Which sequence detects inexpensive errors before evaluating generalization?
Code
Implement adamw_step(w, grad, m, v, t, lr, beta1, beta2, eps, decay): return (new_w, new_m, new_v) as NumPy arrays. t is the step number starting at 1; apply bias corrections and decoupled decay (1 - lr * decay). Do not modify the input arrays.
def adamw_step(w, grad, m, v, t, lr, beta1, beta2, eps, decay):
  pass
Shift+Enter to run

Summary

Key idea
A precise derivation, implementation tests and mechanism controls turn a modification into an evaluable claim. Evidence from one task and budget defines its scope; it does not guarantee universal improvement.