fn
grad
→Callablegrad(func: Callable[..., Tensor], argnums: int | tuple[int, ...] = 0, has_aux: bool = False)Build a function returning the gradient of func.
The cornerstone of functional-style autograd: rather than calling
.backward() and reading .grad, grad(func) produces a new
callable that, when invoked, returns the gradient tensor directly.
Transforms compose, so grad(grad(func)) yields a second
derivative and vmap(grad(func)) computes per-sample gradients.
Parameters
funcCallableFunction returning a scalar Tensor (or
(scalar, aux) when
has_aux=True).argnumsint or tuple of int= 0Positional argument index/indices to differentiate. Default
0.has_auxbool= FalseIf
True, func must return (loss, aux); the wrapped
callable then returns (grads, aux) with aux forwarded
through without differentiation. Default False.Returns
CallableFunction with the same signature as func returning the
gradient tensor — or a tuple of gradients when argnums is a
tuple.
Notes
For , grad(f) realises
Implementation is reverse-mode AD: one forward + one backward pass
through func, independent of input dimensionality.
Examples
>>> import lucid
>>> from lucid.func import grad
>>> f = lambda x: (x ** 3).sum()
>>> df = grad(f)
>>> df(lucid.tensor([1.0, 2.0, 3.0])) # 3 * x ** 2
Tensor([ 3., 12., 27.])