Skip to content
fn

compiled_step

→Tensor
compiled_step(model: Module, x: Tensor, loss_fn: Callable[[Tensor], Tensor])

Run one compiled training step: forward + backward + grad accumulation.

Parameters

Module whose forward(x) produces the model output.
Input tensor (single forward pass).
loss_fncallable
Maps model(x) → scalar loss tensor. Typical: lambda y: F.cross_entropy(y, target).

Returns

Tensor

The loss (compiled result, with no graph: its backward has run). Its gradients are added into .grad as loss.backward() adds them — of each parameter that requires grad, of a loss weight loss_fn reads, and of x and the graph behind it when x requires grad. Then run the optimizer.

Raises

NotImplementedError
A gradient passes through a custom Function, whose backward the executable cannot run (make_step runs such a step eagerly).
RuntimeError
A BatchNorm with momentum=None is in training mode (its cumulative average reads the batch count on the host), or the call's running statistics or in-place writes have no tensor for the executable to write back to. There is no eager path to run instead.

Notes

Parameters on the CPU have nothing to compile (Metal only): the step runs eagerly, with a one-time CompileFallbackWarning.

A norm's tracked running statistics (BatchNorm's, an InstanceNorm's) and its num_batches_tracked advance once per call, as in an eager step: the executable returns them and they are written back into the buffers after the run, as in make_step. So is any in-place write to a tensor from outside the call.

A trace it cannot lower raises, there being no eager path, as does one reading a value computed on another thread (the tracer is per thread).

The trace is captured in the caller's grad mode and fresh on every call; cache integration (compile-or-cached) lives in Phase 1.4's CompiledModule.

Examples

>>> import lucid, lucid.nn as nn, lucid.nn.functional as F
>>> import lucid.optim as optim
>>> from lucid.compile._entry.function import compiled_step
>>> model = nn.Linear(8, 4).to('metal')
>>> opt = optim.SGD(model.parameters(), lr=0.1)
>>> for batch in batches:
...     opt.zero_grad()
...     loss = compiled_step(model, batch.x,
...                          lambda y: F.cross_entropy(y, batch.target))
...     opt.step()

See Also

Used by 1