Mixed Precision Training
A runnable tutorial for lucid.amp — autocast and GradScaler in a training loop, skipping steps on overflow, unscale_ with gradient clipping, gradient accumulation, checkpointing the scaler, and the fused compiled step.
Mixed precision runs the heavy compute of a model in float16 (or bfloat16) while the parameters, the optimizer and the loss stay in float32. lucid.amp has two tools for it: autocast, which lowers the precision of the forward pass, and GradScaler, which keeps small float16 gradients from underflowing and skips a step whose gradients overflowed. This tutorial uses both in a real loop and shows each behaviour you rely on. The Mixed Precision (AMP) guide has the theory; here every block runs.
The blocks form one script. It trains a two-layer MLP on random regression data, which is enough to exercise the machinery and runs in a second on the CPU or Metal GPU.
import lucid
import lucid.nn as nn
import lucid.nn.functional as F
import lucid.optim as optim
from lucid.amp import GradScaler, autocast
from lucid.nn.utils import clip_grad_norm_
device = "metal" if lucid.metal.is_available() else "cpu"
dtype = lucid.float16 if device == "metal" else lucid.bfloat16
lucid.manual_seed(0)
class MLP(nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = nn.Linear(8, 16)
self.fc2 = nn.Linear(16, 4)
def forward(self, x: lucid.Tensor) -> lucid.Tensor:
return self.fc2(self.fc1(x).relu())
model = MLP().to(device)
optimizer = optim.AdamW(model.parameters(), lr=1e-2)
x = lucid.randn(16, 8, device=device)
y = lucid.randn(16, 4, device=device)What autocast does
autocast(device_type, dtype=...) is a context manager. Inside it, the compute-heavy ops cast their inputs to dtype; outside it nothing changes. The parameters are never converted — only the activations are — so the master weights stay in float32.
with autocast(device, dtype=dtype):
out = model(x)
print("activations:", out.dtype)
print("enabled:", autocast.is_autocast_enabled(), autocast.get_autocast_dtype())
loss = F.mse_loss(out.float(), y)
print("loss:", loss.dtype, " parameters:", model.fc1.weight.dtype)
print("enabled after the block:", autocast.is_autocast_enabled())The forward pass returns half-precision activations, and the loss is computed in float32 by casting the output back with .float(). Computing the loss in full precision is the standard recipe: reductions are where half precision loses the most. Scopes nest, and enabled=False turns a scope into a no-op without touching the call site, which is the easiest way to compare a run with and without mixed precision. Use the same dtype that you will train with.
float16 is the Metal default and bfloat16 the CPU default (the script above picks them the same way). On the CPU, a float16 scope computes in float32: nothing is lowered, so out.dtype stays float32. Use bfloat16 to get real half-precision compute on the CPU.
Call .backward() outside the autocast block. autocast governs the forward pass; the backward pass takes its dtypes from the recorded graph.
Why a GradScaler
float16 cannot represent very small numbers: gradients below about 6e-5 lose precision and below roughly 6e-8 flush to zero. GradScaler multiplies the loss by a scale factor S before backward(), so every gradient is S times larger and fits in range, then divides by S again in float32 before the optimizer update. The scale adapts: it halves (backoff_factor) whenever a step's gradients contain inf or NaN, and doubles (growth_factor) after growth_interval consecutive clean steps.
The tutorial uses a small init_scale and a short growth_interval so the schedule is visible in a few iterations. The defaults are 2**16 and 2000.
scaler = GradScaler(init_scale=2.0**8, growth_interval=3)
def train_step(x, y, clip=None):
optimizer.zero_grad()
with autocast(device, dtype=dtype):
loss = F.mse_loss(model(x).float(), y)
scaler.scale(loss).backward()
if clip is not None:
scaler.unscale_(optimizer)
clip_grad_norm_(model.parameters(), max_norm=clip)
scaler.step(optimizer)
scaler.update()
return float(loss.item())
for i in range(6):
loss = train_step(x, y)
print(f"step {i} loss {loss:.4f} scale {scaler.get_scale():g}")The loop is the whole recipe: scale the loss and call backward, scaler.step(optimizer) instead of optimizer.step(), then scaler.update() to adapt the scale. The printed scale doubles on every third step — three clean steps is one growth_interval. zero_grad() is still yours to call.
Overflow: the step is skipped
When a step produces a non-finite gradient, GradScaler does not apply it. The parameters and the optimizer state are left exactly as they were, the scale is halved, and training carries on with the next batch. To provoke one, feed an infinite input:
params_before = model.fc1.weight.numpy().copy()
scale_before = scaler.get_scale()
train_step(x * float("inf"), y)
print("parameters unchanged:", bool((model.fc1.weight.numpy() == params_before).all()))
print(f"scale {scale_before:g} -> {scaler.get_scale():g}")
loss = train_step(x, y)
print("next step is a normal step, loss", round(loss, 4))A skipped step is not an error, and it is not logged — read scaler.get_scale() to notice one. A few skips in the first iterations of a real run are normal while the scale finds its range. A scale that keeps collapsing means the activations or the loss genuinely overflow, which no scale factor fixes.
Clipping gradients: unscale_ first
clip_grad_norm_ has to see the real gradients, not the scaled ones — clipping a gradient that is S times too large would clip almost everything. Call scaler.unscale_(optimizer) after backward() and before clipping; scaler.step then knows the gradients are already unscaled and does not divide again. This is the clip= branch of train_step:
for i in range(4):
loss = train_step(x, y, clip=1.0)
print(f"step {i} loss {loss:.4f} scale {scaler.get_scale():g}")If the gradients contain inf/NaN, clip_grad_norm_ returns a non-finite norm and the step is skipped by the same rule as above — the clip never has to be guarded by hand.
Gradient accumulation
Accumulating gradients across micro-batches works the same way: scale and backward each micro-batch, then step and update once. Divide each loss by the number of micro-batches, as you would without a scaler. If any one micro-batch overflows, the whole accumulated step is skipped, because the overflow is already in the shared .grad.
micro_batches = [(lucid.randn(16, 8, device=device), lucid.randn(16, 4, device=device)) for _ in range(2)]
def accumulate_step(batches):
optimizer.zero_grad()
for mx, my in batches:
with autocast(device, dtype=dtype):
loss = F.mse_loss(model(mx).float(), my) / len(batches)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
accumulate_step(micro_batches)
print("clean accumulated step, scale", scaler.get_scale())
params_before = model.fc1.weight.numpy().copy()
accumulate_step([micro_batches[0], (micro_batches[1][0] * float("inf"), micro_batches[1][1])])
print("one bad micro-batch skipped the whole step:", bool((model.fc1.weight.numpy() == params_before).all()))Checkpoint and resume
The scaler has a state of its own — the current scale and where it is in the growth interval. Save it next to the model and the optimizer, and a resumed run continues the same schedule instead of re-learning the scale from init_scale.
import tempfile
from pathlib import Path
path = Path(tempfile.mkdtemp()) / "amp.lucid"
lucid.save(
{
"model": model.state_dict(),
"optimizer": optimizer.state_dict(),
"scaler": scaler.state_dict(),
},
path,
)
state = lucid.load(path, map_location=device)
resumed_scaler = GradScaler()
resumed_scaler.load_state_dict(state["scaler"])
print("scaler state:", resumed_scaler.state_dict())
print("same schedule:", resumed_scaler.state_dict() == scaler.state_dict())Restore the model and optimizer exactly as in Train a Model End to End.
The compiled path
On the Metal device the whole step — forward, backward, the unscale, the overflow check and the optimizer update — can run as one executable through lucid.compile.fused_step. Pass the scaler in and it follows the same rules: scale in the graph, unscale in float32, skip when found_inf, and drive scaler.update() from the result. autocast goes around the call, and the loss function must be a module-level function.
def mse_fp32(out: lucid.Tensor, target: lucid.Tensor) -> lucid.Tensor:
return F.mse_loss(out.float(), target)
if device == "metal":
fused_model = MLP().to(device)
fused_optimizer = optim.AdamW(fused_model.parameters(), lr=1e-2)
fused_scaler = GradScaler(init_scale=2.0**8, growth_interval=3)
fused = lucid.compile.fused_step(
fused_model, mse_fp32, fused_optimizer, grad_scaler=fused_scaler
)
for i in range(6):
with autocast(device, dtype=dtype):
loss = fused(x, y)
print(f"fused step {i} loss {float(loss.item()):.4f} scale {fused_scaler.get_scale():g}")
with autocast(device, dtype=dtype):
fused(x * float("inf"), y)
print("after an overflow, scale", fused_scaler.get_scale())The scale trajectory and the skip decisions match the eager loop exactly; the loss values agree to a couple of percent, because half-precision rounding differs between the two executors. fused_step does not exist on the CPU — keep the eager loop there.
Practical notes
float16orbfloat16. Both work withautocastandGradScaler.bfloat16hasfloat32's exponent range, so underflow is much rarer;float16has more mantissa bits. Pick the one that trains stably for your model.- A power-of-two scale is lossless. The default scale and the growth and backoff factors are powers of two, which only shift exponents. A run that never overflows is numerically the same as one with
GradScaler(enabled=False)— to round-off on the CPU andbfloat16, and to a few parts per thousand on Metalfloat16, where scaling is what rescues tiny products from flushing to zero. - No memory growth. Repeated scaled steps, skips included, hold the engine's live memory constant.
- Compare against fp32. Wrap the same loop in
autocast(device, dtype=dtype, enabled=False)andGradScaler(enabled=False)to get the full-precision baseline from identical code.