Module contents
Lesson 20 of 22Advanced 95 min

Training stability: loss spikes, divergence and NaNs

Investigate loss spikes, late divergence and non-finite values using curvature, optimizer state, logits and numerical tracing, then compare mitigations and learning-rate sensitivity under controlled budgets.

After this lesson you can

  • Estimate curvature using Hessian-vector products and relate it cautiously to loss spikes.
  • Investigate spikes using batch, optimizer-state, logit and precision records.
  • Examine output-logit divergence and z-loss limitations.
  • Locate the first non-finite tensor and address its cause.
  • Build learning-rate sensitivity curves with small proxies and stated limitations.

Before you start

The last batch does not tell the whole story

A long training run can reduce loss for hours and then spike or produce NaN. The last batch is a clue, not an explanation. Before changing learning rate, record its examples, logits, gradient norm, and parameter change, and keep a checkpoint with optimizer state and seeds. Without that state you cannot reproduce the same Adam moment sequence.

InteractiveAnatomy of a spike

Two real Adam episodes on Fashion-MNIST, each with a paired control. Explore the steps, compare both layers and propose a hypothesis. The vertical line marks the selected step; the chart shows batch cross-entropy without an auxiliary penalty.

Preparing chart…
Matrix 1: ‖∇W‖ 10.3880; ‖ΔW‖/‖W‖ 0.030458Matrix 2: ‖∇W‖ 24.7348; ‖ΔW‖/‖W‖ 0.005840

One seed, 512 training images, 256 validation images and 60 steps. The minimum v spans both matrices after the step; gradients are recorded before clipping and ratios measure actual change. Selected run status: complete. Missing steps or non-finite values are indicated without interpolation.

20
Batch loss2.6287
Maximum absolute logit71.8319
Minimum Adam v7.65e-15
Step through records before and after a spike and compare the paired intervention with the original run.

A loss spike can be isolated and recover, or precede divergence. Compare the same checkpoint with and without the suspect batch, a lower rate, or a precision change. A simultaneous gradient peak is a signal, not proof of cause: other variables may change at the same time. When an experiment does not isolate a cause, retain that uncertainty.

In PaLM, the 540-billion-parameter model suffered about 20 spikes despite clipping. The authors restored a checkpoint about 100 steps earlier and skipped approximately 200 to 500 batches; they also tested the same batches from an earlier checkpoint without observing the spike. This is evidence of data–state interaction in that training run, not a rule to automatically discard examples.

Curvature and step: a local approximation

In a quadratic with positive symmetric Hessian, error along the eigenvalue λ>0\lambda>0 direction is multiplied at each gradient descent step by 1−ηλ1-\eta\lambda. The direction contracts if 0<ηλ<20<\eta\lambda<2. This calculation uses constant rate and fixed curvature. A network changes its Hessian as it trains, and minibatches or Adam do not follow the same recurrence.

Cohen and colleagues observed in full-batch gradient descent a regime where the largest training-Hessian eigenvalue stays near and slightly above 2/η2/\eta: loss oscillates at short scales while falling at long scales. This is not a universal safety rule for every optimizer. An edge of stability is an observation about a trajectory and protocol, not a fixed threshold automatically preventing progress.

In the catapult mechanism studied by Lewkowycz and colleagues, certain high rates produce distinct transient dynamics before convergence. A loss jump followed by recovery has several possible explanations: also inspect curvature evolution, the batch, and parameter change before attributing it to catapult. Warmup and clipping can moderate a particular experiment but require controls and do not guarantee stability for every network.

Gilmer and colleagues examined Hessian evolution in classification tasks and effects of initialization, architecture, warmup, and clipping. Their interpretation links early stability to avoiding or leaving high-curvature regions. This perspective is supported by their experiments, not a proven explanation for all numerical failures.

The Hessian without constructing it

For a vector vv shaped like the parameters, a Hessian-vector product is obtained by differentiating the inner product of the gradient with vv. Repeated products explore the spectrum without forming the full matrix. But unshifted power iteration targets the eigenvalue of largest magnitude, which can be negative and not algebraically largest.

The browser cell uses a two-dimensional diagonal matrix: the magnitude-dominant eigenvalue is negative and the algebraically largest is positive. A small residual ∥Hv−ρv∥\|Hv-\rho v\| shows vv approximates an eigenvector, not that the positive extreme was found; it can even miss the dominant one if the initial vector is orthogonal to its subspace. Symmetric Lanczos can estimate both extremes; a positive shift with a justified spectral bound and convergence diagnostic can also be used. Without that bound, label the estimate dominant in magnitude rather than λmax⁡\lambda_{\max}.

Adam when a signal returns

Adam’s second moment accumulates squared gradients. After a period without a signal, its value can be small. When a gradient returns, the update depends on both previous moments, β1,β2\beta_1,\beta_2, ε\varepsilon and bias correction. The current gradient norm alone is not enough.

InteractiveAdam and a returning signal

Simulation calculated in the browser with 1024 coordinates and loss L=½∑(θᵢ−aᵢ)². The target aᵢ ranges from 0.5 to 1.5, θ starts at zero and Adam uses η=0.05. The gradient equals θᵢ−aᵢ except during an artificial pause: zero is supplied for 600 steps, then the gradient returns.

Preparing charts…

The vertical lines mark the first step after the pause. The initial view zooms in from step 620; you can show the whole trajectory. Adam continues updating its state and θ during the pause; the displayed loss is actually calculated after each step. The v, gradient and update samples correspond to the central coordinate. The initial state uses β₁=0 and disables correction to show a jump; typical Adam usually corrects bias. That correction uses the global step counter. Changing β₂ also changes decay during the pause, so its effect is not universal.

Bias correction
Time window
v before return1.67e-15
Gradient on return−0.00181
First coordinate update0.22360
Loss before → after0.21907 → 19.84901
Adjust the moments and epsilon; compare the state before and after the gradient returns.

In the idealized case mt−1=vt−1=0m_{t-1}=v_{t-1}=0, g≠0g\ne0 and without bias correction,

∣Δθt∣=η(1−β1)∣g∣1−β2 ∣g∣+ε.|\Delta\theta_t| =\eta\frac{(1-\beta_1)|g|} {\sqrt{1-\beta_2}\,|g|+\varepsilon}.

If ε\varepsilon is negligible, the ratio relative to η\eta depends on both coefficients. Increasing ε\varepsilon reduces that particular step but can also shrink useful updates. Reducing β2\beta_2 changes both the response to the signal and the rate at which the second moment decays during the pause. In a full run, history matters and no mitigation automatically works for every sequence.

Molybog and colleagues study a richer hypothesis: temporal gradient correlation and changes in the distribution of updates in large networks. The scalar recurrence above helps isolate a mechanism, but does not by itself prove it explains a collective spike. Some large-model configurations use β2=0,95\beta_2=0,95; for example, Wortsman and colleagues use it in their protocol alongside AdamW, clipping and warmup. This does not establish that the value is best for every training run.

Logits, z-loss and attention

Softmax and cross-entropy do not change when the same constant is added to every logit of an example. If z=(z1,…,zC)z=(z_1,\ldots,z_C) and A=logsumexp⁡(z)A=\operatorname{logsumexp}(z), then log⁡pi=zi−A\log p_i=z_i-A. Output-logit divergence can shift that common scale without changing the probabilities in the same way.

The auxiliary z-loss penalty adds αA2\alpha A^2 per example. To evaluate AA, use a stable logsumexp implementation that subtracts the maximum before exponentiation. The penalty favors AA close to zero, but does not bound every difference: for example, logits near [0,−200][0,-200] have AA close to zero while remaining far apart. It does not replace monitoring loss, accuracy and gradients either.

Wortsman and colleagues reproduce two forms of slow divergence in small Transformers, distinct from isolated spikes: growing attention logits and output-logit drift. They observe the latter in their 2.4 million parameter model at learning rate 0.1 and use z-loss with coefficient 10−410^{-4}. In attention, normalizing queries and keys acts before their dot product; it is not the same operation as centering classification logits. Revisit this in attention.

Finding the first non-finite value

InteractiveNon-finite value tracer

An explicit forward chain can produce a non-finite value before backward runs. In the measured local demo, the first non-finite value appears at exp(float16(12)).

1. float16 input
12
2. exp(12)
?
3. Inf / Inf
?
4. backward
?

12 is finite in float16.

In the PyTorch run, the backward error was: Function 'DivBackward0' returned nan values in its 1th output. This is an observation for that graph; recording finiteness during forward identifies the first observed non-finite tensor. Stable cross-entropy avoids explicit exp overflow, but does not guarantee stability for every training run.

Chain
1 of 4
Operationfloat16 input
Value12
Follow each tensor's propagation and distinguish forward checks from errors detected during backward.

A logarithm of zero can produce −∞-\infty; an exponential in float16 can overflow; zero variance without epsilon makes normalization indeterminate; and 0⋅∞0\cdot\infty produces NaN. Record whether inputs and outputs are finite in order until you find the first bad tensor, then repeat with a smaller batch. Do not hide a NaN by replacing it without investigating its origin.

torch.autograd.detect_anomaly(check_nan=True) helps with debugging: it detects NaNs generated during backward and can show the trace of the forward pass associated with that function. It does not guarantee detection of every infinity or location of the first non-finite tensor in the forward pass. Supplement it with torch.isfinite and enable detection only during investigation, because it adds overhead. Finiteness instrumentation offers more tracing patterns.

Learning-rate sensitivity and proxies

InteractiveLearning-rate sensitivity

Measured final validation loss, without adding z-loss to the metric. The vertical line marks the selected rate. The short run uses Fashion-MNIST; the reader’s lab uses CIFAR-10.

Preparing chart…

Discrete rates with final CE below initial CE

Adam base: 0.0003, 0.001, 0.003, 0.01, 0.03. Finite results: 7/7.

z-loss: 0.0003, 0.001, 0.003, 0.01, 0.03. Finite results: 7/7.

LayerNorm: 0.0003, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3. Finite results: 7/7.

β₂=0.95: 0.0003, 0.001, 0.003, 0.01, 0.03, 0.1. Finite results: 7/7.

This improvement criterion compares only tested rates, without interpolation or defining a stability boundary. The lab also separately tests the deliberately extreme η=10²⁰: status nonfinite_logits; it is not part of the chart or practical sweep.

One seed, 512 training images, 256 validation images, 60 updates and paired batches. z-loss uses coefficient 10⁻⁴; LayerNorm changes the MLP and β₂=0.95 changes Adam. Non-finite conditions appear without a point and with their status, not as zero loss. A short run does not prove a configuration is always better and is not the aggregate sensitivity defined in a paper.

Adam base0.740
z-loss0.736
LayerNorm0.849
β₂=0.950.752
Compare validation losses and failed runs in the same learning-rate sweep. A small proxy does not guarantee behavior at another scale.

Learning-rate sensitivity is studied by sweeping learning rates with comparable seeds, data, steps and evaluation. Record both task loss and the auxiliary penalty so different objectives are not compared as if they were the same. Mark a non-finite run as a failure and show the criterion used to call a run stable.

In Wortsman and colleagues, the specific measure averages the excess validation loss over the best value after clipping each loss by the initial loss. Their sweep uses seven rates from 3⋅10−43\cdot10^{-4} to 3⋅10−13\cdot10^{-1}. The width of a stable region is another useful measure, but is not that definition. A small proxy allows hypotheses to be tested at lower cost; it does not guarantee the same threshold when the model, data or budget changes.

A protocol for your projects

  1. Before scaling the model, establish a reproducible baseline with disjoint splits. Save the configuration, seed, precision, optimizer state and each batch identifier.
  2. Define what to measure and how often: unsmoothed loss, gradients, parameter changes and logit scale. Keep enough checkpoints to return to before an anomaly.
  3. If a spike appears, reproduce it from the same state and compare the batch and one intervention at a time. If a non-finite value appears, identify the first affected tensor before adjusting hyperparameters.
  4. Compare the mitigation with the control under the same budget, using separate validation and multiple seeds when affordable. Record attempts that do not improve or reproduce the failure too.
  5. Repeat the sweep when changing scale and reserve the test set for the chosen protocol. In mixed precision you will study how format, loss scaling and accumulation change numerical risks.

Labs

The browser cell checks the differences between power iteration by magnitude and a known shift, as well as non-finite operations and the limit of z-loss. The two local labs instrument an MLP and study non-finite values and sensitivity. The figures use short runs or the explicit model described in them; the reader can run the full budget on their own computer.

The short verification uses Fashion-MNIST resized to 32×32 and repeated across three channels; the cells’ normal mode uses CIFAR-10. In both cases validation is separated from training and the official test set is held out. The short result checks the code and displayed data; it is not a measurement of the full CIFAR-10 experiment.

In that run, at learning rate 0.3, final training loss in the curvature study was approximately 0.285 without mitigation, 0.310 with warmup and 0.358 with clipping. The sampled points do not demonstrate a catapult. The 2/η2/\eta threshold for unclipped SGD does not directly describe the clipped arm’s dynamics.

In the autopsy, multiplying the step 20 batch inputs by ten raised cross-entropy from 0.761 in the control to 2.629 in the altered run. Clipping acts after that forward pass: it cannot retroactively prevent the loss on that batch. In the practical sweep, all 28 runs ended with finite values; a separate test with deliberately extreme learning rate η=1020\eta=10^{20} produced non-finite logits. That test checks failure logging, not a real stability boundary. The NaN example comes from the float16 operation constructed for debugging, not a boundary observed at practical rates.

[ ]Eigenvalues, z-loss and finite arithmeticBrowser
import numpy as np

h = np.diag([-10., 4.])
def power(shift):
    v = np.ones(2)/np.sqrt(2)
    for _ in range(100):
        v = (h+shift*np.eye(2))@v
        v /= np.linalg.norm(v)
    rho = float(v@h@v)
    return rho, float(np.linalg.norm(h@v-rho*v))
print('espectro:', np.linalg.eigvalsh(h))
print('potencia sin desplazamiento:', power(0))
print('potencia con desplazamiento 12:', power(12))
assert np.isclose(power(0)[0],-10) and np.isclose(power(12)[0],4)

z = np.array([0.,-200.])
m = np.max(z)
logz = float(m+np.log(np.exp(z-m).sum()))
print('logsumexp y rango de logits:',logz, float(z.max()-z.min()))
assert np.isclose(logz,0) and z.max()-z.min()==200
with np.errstate(over='ignore',divide='ignore',invalid='ignore'):
    a=np.exp(np.float16(12))
    b=np.log(np.float32(0))
    c=np.float32(0)*np.float32(np.inf)
print('exp float16, log cero, cero por infinito:',a,b,c)
assert np.isinf(a) and np.isneginf(b) and np.isnan(c)
[ ]Sharpness and trainingLocal GPU
"""Curvatura de un MLP en CIFAR-10 con HVP y Lanczos simétrico.

ORYON_VERIFY_SHORT=1 utiliza Fashion-MNIST (28→32 px, tres canales), cacheado,
y reduce datos, red, iteraciones y pasos. El modo normal usa CIFAR-10 real.
Solo se usa train oficial, separado en entrenamiento y validación; el test no se consulta. Salida: cifar-curvature.json
o ruta ORYON_CURVATURE_OUTPUT, más una figura PNG junto al JSON.
"""
import json
import math
import os
from pathlib import Path

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torchvision.datasets import CIFAR10, FashionMNIST

torch.set_num_threads(1)
short=os.environ.get('ORYON_VERIFY_SHORT')=='1'
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_size,valid_size=(128,128) if short else (1024,512)
width=32 if short else 128
steps,measure_every,iters=(60,10,12) if short else (300,20,25)
seed=2020
rates=[.03,.1,.3]
if short:
    dataset=FashionMNIST(Path.home()/'.cache'/'atlas-data',train=True,download=True)
    dataset_name='Fashion-MNIST redimensionado a 32×32 y repetido en tres canales'
else:
    dataset=CIFAR10(Path.home()/'.cache'/'atlas-data',train=True,download=True)
    dataset_name='CIFAR-10'
split=torch.randperm(len(dataset),generator=torch.Generator().manual_seed(seed))
train_ids,valid_ids=split[:train_size],split[train_size:train_size+valid_size]
assert not set(train_ids.tolist()).intersection(valid_ids.tolist())
indices=torch.cat((train_ids,valid_ids))
if short:
    images=dataset.data[indices].float().div_(255).unsqueeze(1)
    images=nn.functional.interpolate(images,size=(32,32),mode='bilinear',align_corners=False).repeat(1,3,1,1)
else:
    images=torch.from_numpy(dataset.data[indices.numpy()]).permute(0,3,1,2).float().div_(255)
images=images.reshape(train_size+valid_size,-1).sub_(.5)
train_x=images[:train_size].to(device);valid_x=images[train_size:].to(device)
targets=torch.as_tensor(dataset.targets)
train_y=targets[train_ids].to(device);valid_y=targets[valid_ids].to(device)
del images,dataset,targets

def make_model():
    torch.manual_seed(seed)
    return nn.Sequential(nn.Linear(3072,width),nn.Tanh(),nn.Linear(width,10)).to(device)

def flat(tensors): return torch.cat([t.reshape(-1) for t in tensors])

def lanczos(loss,params,iterations=iters):
    """Mayor Ritz algebraico, residuo explícito y menor Ritz; no potencia simple."""
    gradient=torch.autograd.grad(loss,params,create_graph=True)
    sizes=[p.numel() for p in params]
    def hvp(vector):
        chunks=vector.split(sizes)
        shaped=[chunk.reshape_as(p) for chunk,p in zip(chunks,params)]
        return flat(torch.autograd.grad(gradient,params,grad_outputs=shaped,retain_graph=True)).detach()
    generator=torch.Generator(device=device).manual_seed(seed+1)
    q=torch.randn(sum(sizes),device=device,generator=generator)
    q=q/q.norm(); previous=torch.zeros_like(q); beta_prev=0.
    vectors=[]; alphas=[]; betas=[]
    for i in range(iterations):
        vectors.append(q)
        z=hvp(q)-beta_prev*previous
        alpha=torch.dot(q,z)
        z=z-alpha*q
        # Reortogonalización completa para evitar duplicar valores de Ritz.
        for old in vectors: z=z-torch.dot(old,z)*old
        beta=z.norm()
        if not torch.isfinite(alpha) or not torch.isfinite(beta): return None
        alphas.append(float(alpha))
        if i==iterations-1 or float(beta)<1e-10: break
        betas.append(float(beta));previous,q=q,z/beta;beta_prev=beta
    matrix=np.diag(alphas)
    for i,b in enumerate(betas): matrix[i,i+1]=b;matrix[i+1,i]=b
    try:
        eigenvalues,eigenvectors=np.linalg.eigh(matrix)
    except np.linalg.LinAlgError:
        return None
    if not np.isfinite(eigenvalues).all() or not np.isfinite(eigenvectors).all(): return None
    vector=sum(float(c)*qv for c,qv in zip(eigenvectors[:,-1],vectors))
    eigen=float(eigenvalues[-1])
    residual=float((hvp(vector)-eigen*vector).norm())
    if not math.isfinite(residual): return None
    return {'lambda_max_ritz':eigen,'lambda_min_ritz':float(eigenvalues[0]),
            'residual':residual,'iterations':len(alphas)}

def run(rate,warmup,clip):
    model=make_model(); params=tuple(model.parameters()); history=[]; status='complete'
    for step in range(steps+1):
        model.train(); logits=model(train_x); loss=nn.functional.cross_entropy(logits,train_y)
        if not bool(torch.isfinite(loss)):
            status='nonfinite_loss';history.append({'step':step,'loss':None,'curvature':None});break
        current_lr=rate*min(1.,(step+1)/10) if warmup else rate
        if step%measure_every==0 or step==steps:
            estimate=lanczos(loss,params)
            with torch.no_grad():
                validation=nn.functional.cross_entropy(model(valid_x),valid_y)
            valid_finite=bool(torch.isfinite(validation))
            history.append({'step':step,'loss':float(loss.detach()),'validation_loss':float(validation) if valid_finite else None,
                            'validation_status':'finite' if valid_finite else 'nonfinite',
                            'learning_rate':current_lr,'threshold_2_over_lr':None if clip else 2/current_lr,'curvature':estimate,
                            'curvature_status':'estimated' if estimate is not None else 'nonfinite_or_failed'})
        if step==steps: break
        gradients=torch.autograd.grad(loss,params)
        if any(not bool(torch.isfinite(g).all()) for g in gradients):
            status='nonfinite_gradient'
            if history and history[-1]['step']==step: history[-1]['gradient_status']='nonfinite'
            else: history.append({'step':step,'loss':float(loss.detach()),'curvature':None,'gradient_status':'nonfinite'})
            break
        if clip:
            total_norm=torch.linalg.vector_norm(torch.stack([g.norm() for g in gradients]))
            if not bool(torch.isfinite(total_norm)):
                status='nonfinite_gradient_norm';break
            scale=min(1.,1./(float(total_norm)+1e-12))
            gradients=tuple(g*scale for g in gradients)
        with torch.no_grad():
            for p,g in zip(params,gradients): p.add_(g,alpha=-current_lr)
    del model,params
    return {'rate':rate,'warmup':warmup,'clip':clip,'status':status,'history':history}

records=[run(rate,warmup,clip) for rate in rates for warmup,clip in ((False,False),(True,False),(False,True))]
output={'dataset':dataset_name+' train oficial; validación disjunta','mode':'short' if short else 'full',
        'device':str(device),'seed':seed,'train_examples':train_size,'validation_examples':valid_size,
        'architecture':f'3072-{width}-10 con tanh','steps':steps,'measure_every':measure_every,
        'method':'SGD sin momento y lote completo; warmup lineal o recorte global a norma 1; Lanczos simétrico con reortogonalización y residual explícito; valores de Ritz aproximados. 2/eta no es el umbral efectivo cuando se recorta el gradiente.',
        'records':records}
target=Path(os.environ.get('ORYON_CURVATURE_OUTPUT','cifar-curvature.json'))
target.parent.mkdir(parents=True,exist_ok=True)
target.write_text(json.dumps(output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
fig,axes=plt.subplots(2,3,figsize=(13,7),constrained_layout=True)
for col,rate in enumerate(rates):
    for run_ in (r for r in records if r['rate']==rate):
        rows=[r for r in run_['history'] if r.get('loss') is not None]
        label='recorte' if run_['clip'] else 'warmup' if run_['warmup'] else 'sin mitigación'
        color='tab:green' if run_['clip'] else 'tab:orange' if run_['warmup'] else 'tab:blue'
        axes[0,col].plot([r['step'] for r in rows],[r['loss'] for r in rows],label=label,color=color)
        rows=[r for r in rows if r.get('curvature') is not None]
        axes[1,col].plot([r['step'] for r in rows],[r['curvature']['lambda_max_ritz'] for r in rows],label=label,color=color)
        if not run_['clip']:
            axes[1,col].plot([r['step'] for r in rows],[r['threshold_2_over_lr'] for r in rows],':',alpha=.7,color=color)
    axes[0,col].set_title(f'η final = {rate}');axes[0,col].set_ylabel('Pérdida');axes[1,col].set_ylabel('Ritz máximo y 2/η');axes[1,col].set_xlabel('Paso');axes[0,col].legend(fontsize=7);axes[1,col].legend(fontsize=7)
fig.savefig(target.with_suffix('.png'),dpi=120);plt.close(fig)
for r in records:
    print('eta',r['rate'],'warmup',r['warmup'],'clip',r['clip'],'estado',r['status'],'ultima medicion',r['history'][-1])
if device.type=='cuda':torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Non-finite values and learning-rate sensitivityLocal GPU
"""Barrido Adam, autopsia de lote atípico y rastreo de no finitos.

ORYON_VERIFY_SHORT=1 usa Fashion-MNIST cacheado, redimensionado a 32×32 y
repetido en tres canales. Modo normal usa CIFAR-10; el test oficial no se usa.
ORYON_STABILITY_OUTPUT define el JSON y el PNG; por defecto stability.json.
"""
import copy
import json
import math
import os
from pathlib import Path
import warnings

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import torch
from torch import nn
from torchvision.datasets import CIFAR10, FashionMNIST

torch.set_num_threads(1)
short=os.environ.get('ORYON_VERIFY_SHORT')=='1'
device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train_size,valid_size=(512,256) if short else (5000,1000)
width,steps,batch=(64,60,64) if short else (256,500,128)
seed=2021
rates=[.0003,.001,.003,.01,.03,.1,.3]
configs=[{'id':'base','z':0.,'layernorm':False,'beta2':.999},
         {'id':'zloss','z':1e-4,'layernorm':False,'beta2':.999},
         {'id':'layernorm','z':0.,'layernorm':True,'beta2':.999},
         {'id':'beta2_095','z':0.,'layernorm':False,'beta2':.95}]
cache=Path.home()/'.cache'/'atlas-data'
dataset=FashionMNIST(cache,train=True,download=True) if short else CIFAR10(cache,train=True,download=True)
dataset_name='Fashion-MNIST redimensionado a 32×32 y tres canales' if short else 'CIFAR-10'
split=torch.randperm(len(dataset),generator=torch.Generator().manual_seed(seed))
train_ids,valid_ids=split[:train_size],split[train_size:train_size+valid_size]
assert not set(train_ids.tolist()).intersection(valid_ids.tolist())
indices=torch.cat((train_ids,valid_ids))
if short:
    images=dataset.data[indices].float().div_(255).unsqueeze(1)
    images=nn.functional.interpolate(images,size=(32,32),mode='bilinear',align_corners=False).repeat(1,3,1,1)
else:
    images=torch.from_numpy(dataset.data[indices.numpy()]).permute(0,3,1,2).float().div_(255)
images=images.reshape(train_size+valid_size,-1).sub_(.5)
train_x=images[:train_size].to(device);valid_x=images[train_size:].to(device)
targets=torch.as_tensor(dataset.targets)
train_y=targets[train_ids].to(device);valid_y=targets[valid_ids].to(device)
del dataset,images,targets
batch_rng=torch.Generator().manual_seed(seed+1)
batches=torch.randint(train_size,(steps,batch),generator=batch_rng)

def model_for(config):
    torch.manual_seed(seed)
    return nn.Sequential(nn.Linear(3072,width),nn.LayerNorm(width) if config['layernorm'] else nn.Identity(),
                         nn.ReLU(),nn.Linear(width,10)).to(device)

def number(value):
    if isinstance(value,torch.Tensor): value=value.detach()
    value=float(value)
    return value if math.isfinite(value) else None

@torch.no_grad()
def validation(model):
    model.eval(); logits=model(valid_x)
    if not bool(torch.isfinite(logits).all()): return None
    value=number(nn.functional.cross_entropy(logits,valid_y))
    return value

def run(config,rate,incident=None):
    model=model_for(config)
    optimizer=torch.optim.Adam(model.parameters(),lr=rate,betas=(.9,config['beta2']))
    weights=[p for n,p in model.named_parameters() if n.endswith('weight') and p.ndim==2]
    initial_validation=validation(model)
    history=[];status='complete'
    for step in range(steps):
        model.train(); ids=batches[step].to(device); x=train_x[ids]
        outlier=incident in ('outlier','clip','warmup','zloss') and step==20
        if outlier:x=x*10
        optimizer.param_groups[0]['lr']=rate*min(1.,(step+1)/20) if incident=='warmup' else rate
        optimizer.zero_grad(set_to_none=True)
        logits=model(x)
        if not bool(torch.isfinite(logits).all()):
            status='nonfinite_logits';history.append({'step':step,'outlier':outlier,'loss':None});break
        ce=nn.functional.cross_entropy(logits,train_y[ids])
        z= torch.logsumexp(logits,dim=1).square().mean()
        # El término apagado no participa en el grafo: 0 * Inf sería NaN.
        total=ce+config['z']*z if config['z'] else ce
        if not bool(torch.isfinite(total)):
            status='nonfinite_loss';history.append({'step':step,'outlier':outlier,'loss':None});break
        total.backward()
        if any(p.grad is not None and not bool(torch.isfinite(p.grad).all()) for p in model.parameters()):
            status='nonfinite_gradient';history.append({'step':step,'outlier':outlier,'loss':number(ce)});break
        before=[p.detach().clone() for p in weights]
        gradients=[number(p.grad.norm()) if p.grad is not None else None for p in weights]
        if incident=='clip':
            try:
                nn.utils.clip_grad_norm_(model.parameters(),1.,error_if_nonfinite=True)
            except RuntimeError:
                status='nonfinite_gradient_norm'
                history.append({'step':step,'outlier':outlier,'loss':number(ce)})
                break
        optimizer.step()
        ratios=[]
        for p,old in zip(weights,before):
            norm=float(old.norm())
            ratios.append(number((p-old).norm()/norm) if norm>0 else None)
        v=[optimizer.state[p].get('exp_avg_sq') for p in weights]
        vmin=min((float(value.min()) for value in v if value is not None),default=math.nan)
        history.append({'step':step,'outlier':outlier,'loss':number(ce),'total_loss':number(total),
                        'z_penalty_unweighted':number(z),'max_abs_logit':number(logits.abs().max()),
                        'layer_gradient_norms':gradients,'layer_update_ratios':ratios,'adam_v_min':number(vmin)})
        if any(not bool(torch.isfinite(p).all()) for p in model.parameters()):
            status='nonfinite_parameters';break
    final=validation(model) if status=='complete' else None
    if status=='complete' and final is None: status='nonfinite_validation'
    del model,optimizer
    return {'config':config['id'],'rate':rate,'incident':incident,'status':status,
            'initial_validation_ce':initial_validation,'validation_ce':final,'history':history}

records=[run(config,rate) for config in configs for rate in rates]
autopsy=[]
for incident in ('clean','outlier','clip','warmup','zloss'):
    config=configs[1] if incident=='zloss' else configs[0]
    autopsy.append(run(config,.001,incident))
# La segunda autopsia reutiliza corridas medidas del barrido. Comparten datos,
# inicialización y lotes; solo cambia η y no se introduce ningún lote atípico.
for name,rate in (('lr_control',.003),('lr_high',.3)):
    trajectory=copy.deepcopy(next(r for r in records if r['config']=='base' and r['rate']==rate))
    trajectory['incident']=name
    autopsy.append(trajectory)
# Caso deliberadamente extremo para poner a prueba el registro de no finitos;
# no forma parte del barrido de tasas prácticas y no define una frontera.
stress=[run(configs[0],1e20,'extreme_rate')]

# Forward y backward son diagnósticos distintos. No inferir que detect_anomaly
# detecte todo Inf: aquí informa de una derivada NaN, no del primer tensor malo.
with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    bad=torch.tensor([12.],dtype=torch.float16,device=device,requires_grad=True)
    first=torch.exp(bad)
    first_nonfinite='exp(float16(12))' if not bool(torch.isfinite(first).all()) else None
    anomaly=None
    try:
        with torch.autograd.detect_anomaly(check_nan=True):
            bad=torch.tensor([12.],dtype=torch.float16,device=device,requires_grad=True)
            first=torch.exp(bad);loss=(first/first).sum();loss.backward()
    except RuntimeError as exc: anomaly=str(exc).splitlines()[0]
    stable=nn.functional.cross_entropy(torch.tensor([[12.,0.]],device=device,dtype=torch.float32),torch.tensor([0],device=device))

output={'dataset':dataset_name+' train oficial; validación disjunta','mode':'short' if short else 'full',
        'device':str(device),'seed':seed,'batch_seed':seed+1,'train_examples':train_size,
        'validation_examples':valid_size,'width':width,'batch_size':batch,'steps':steps,
        'configs':configs,'rates':rates,'records':records,'autopsy':autopsy,'stress_tests':stress,
        'nonfinite_demo':{'first_nonfinite':first_nonfinite,'detect_anomaly_backward':anomaly,'stable_cross_entropy':number(stable)},
        'protocol':'Misma inicialización, particiones e índices para cada configuración. Se muestra CE de validación sin término auxiliar. Sin consulta al test oficial; el lote atípico multiplica entradas por 10 solo en paso 20. La autopsia de tasa usa los registros del barrido con η 0,003 y 0,3 y no altera el lote.'}
target=Path(os.environ.get('ORYON_STABILITY_OUTPUT','stability.json'))
target.parent.mkdir(parents=True,exist_ok=True)
target.write_text(json.dumps(output,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8')
fig,axes=plt.subplots(1,3,figsize=(15,4),constrained_layout=True)
for config in configs:
    runs=[r for r in records if r['config']==config['id']]
    axes[0].plot([r['rate'] for r in runs],[r['validation_ce'] if r['validation_ce'] is not None else float('nan') for r in runs],marker='o',label=config['id'])
axes[0].set_xscale('log');axes[0].set_xlabel('Tasa');axes[0].set_ylabel('CE validación');axes[0].legend(fontsize=7)
for record in (r for r in autopsy if r['incident'] not in ('lr_control','lr_high')):
    rows=[r for r in record['history'] if r['loss'] is not None]
    axes[1].plot([r['step'] for r in rows],[r['loss'] for r in rows],label=record['incident'])
axes[1].set_xlabel('Paso');axes[1].set_ylabel('CE lote');axes[1].legend(fontsize=7)
for record in (r for r in autopsy if r['incident'] in ('lr_control','lr_high')):
    rows=[r for r in record['history'] if r['loss'] is not None]
    axes[2].plot([r['step'] for r in rows],[r['loss'] for r in rows],label=record['incident'])
axes[2].set_xlabel('Paso');axes[2].set_ylabel('CE lote');axes[2].legend(fontsize=7)
fig.savefig(target.with_suffix('.png'),dpi=120);plt.close(fig)
print('Demo de no finitos:',output['nonfinite_demo'])
for record in records:print(record['config'],record['rate'],record['status'],'CE val',record['validation_ce'])
for record in stress:print('Tasa extrema',record['rate'],record['status'],'pasos guardados',len(record['history']))
for record in autopsy:
    print('Autopsia',record['incident'],record['status'],'pérdidas 19-21',[(r['step'],r['loss']) for r in record['history'] if 19<=r['step']<=21])
if device.type=='cuda':torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofThe first step after silence
Prove: Derive the scalar update when a gradient returns and compare it with a constant-gradient regime.
0
Take g≠0, previous m and v equal to zero, ε≥0, 0≤β₁,β₂<1, and ignore bias correction. In steady state with the same constant gradient, m=g and v=g².

Step 1 of 3. What are the moments immediately after observing g?

NumericA slow second moment
In the ideal case from the previous exercise, β₁=0.9, β₂=0.999 and ε is negligible. What is the first step size in units of η?
NumericA shorter window
Under the same assumptions, β₁=0.9 and β₂=0.95. What is the first step size in units of η?
CodeHessian-vector products without constructing H
Using PyTorch implement hvp(loss, params, vec), for a real floating-point scalar Tensor loss and tuples of parameters and vectors with matching shapes, types and devices, and top_eigenvalue(loss, params, iters, shift=0). Require at least one parameter; each parameter must be a nonempty real floating-point Tensor with requires_grad=True. Use double backward and do not change the parameters. top_eigenvalue starts with a normalized vector of ones, applies power iteration to H+shift I and returns (Rayleigh quotient of H, residual norm). With zero shift it seeks the eigenvalue dominant in magnitude; you can interpret the result as algebraically largest only if the shift is justified and the initial vector has a component in its subspace. Treat a constant loss without a graph, a zero Hessian and components without a second derivative as zero. Reject invalid loss or parameters, incompatible shapes, types or devices, and nonpositive iters with ValueError. The tests run locally with PyTorch.
import torch

def hvp(loss, params, vec):
  pass

def top_eigenvalue(loss, params, iters, shift=0.):
  pass
Shift+Enter to run
NumericEdge for a given learning rate
In the edge-of-stability reference for full-batch gradient descent, if η=0.02, what is 2/η?
QuizTwo different spikes
One run has an isolated spike and recovers; another ends in NaN. What do you do first?
QuizDelicate operations
Which operations can produce Inf or NaN at finite precision?

References