Skip to content
fn

custom_fwd

→callable
custom_fwd(fwd: Callable[..., R] | None = None, device_type: str, cast_inputs: dtype | None = None)

Decorate a custom Function.forward so backward can follow its autocast state.

Under lucid.amp.autocast an op inside forward computes in half precision, so its result and the gradient that comes back are half precision while the tensors forward saved are still float32 — and the backward's arithmetic on the pair fails. The decorated forward stores the autocast state of device_type on ctx; decorate backward with custom_bwd to run it in that state.

Used bare as custom_fwd(fwd, device_type=...) or, as a decorator factory, @custom_fwd(device_type=...) placed under @staticmethod.

Parameters

fwdcallable= None
The forward to decorate; leave it out to get the decorator.
device_typestr
"metal" or "cpu"; anything else raises ValueError. Keyword-only and required.
cast_inputslucid.dtype= None
When given and autocast is enabled on device_type at the call, every floating-point tensor argument on that device (float64 excepted) is cast to this dtype — nested lists, tuples and dicts included — and forward runs with autocast off; backward then runs with it off too. None (default) leaves the inputs alone and runs forward in the caller's state. Outside an autocast scope cast_inputs does nothing.

Returns

callable

The decorated forward (fwd given), or the decorator.

Raises

ValueError
If device_type is neither "metal" nor "cpu".

Examples

>>> import lucid
>>> from lucid.amp import autocast, custom_bwd, custom_fwd
>>> from lucid.autograd import Function
>>> class MatMul(Function):
...     @staticmethod
...     @custom_fwd(device_type="cpu")
...     def forward(ctx, a, b):
...         ctx.save_for_backward(a, b)
...         return a @ b
...     @staticmethod
...     @custom_bwd(device_type="cpu")
...     def backward(ctx, grad):
...         a, b = ctx.saved_tensors
...         return grad @ b.mT, a.mT @ grad
>>> a = lucid.randn(3, 4, requires_grad=True)
>>> b = lucid.randn(4, 2, requires_grad=True)
>>> with autocast("cpu", dtype=lucid.bfloat16):
...     y = MatMul.apply(a, b)
>>> y.dtype
lucid.bfloat16
>>> y.float().sum().backward()
>>> a.grad.dtype
lucid.float32

See Also

  • custom_bwd—the matching backward decorator.
  • lucid.amp.autocast—the scope whose state is recorded.

Used by 1