Skip to content
fn

grad

→tuple[Tensor or None, ...]
grad(outputs: Tensor | Sequence[Tensor], inputs: Tensor | Sequence[Tensor], grad_outputs: Tensor | Sequence[Tensor | None] | None = None, retain_graph: bool | None = None, create_graph: bool = False, only_inputs: bool = True, allow_unused: bool | None = None, is_grads_batched: bool = False, materialize_grads: bool = False)

Compute gradients of outputs w.r.t. inputs, returning them as a tuple.

The "functional" gradient interface — invoke once to get the partial derivatives back without touching .grad on any leaf tensor. Useful for higher-order differentiation, gradient-based meta-learning, or any pattern where you want to use the gradients as input to a new computation rather than to update parameters in-place.

Parameters

outputsTensor or list of Tensor
Output tensors to differentiate. Each must have requires_grad set in the graph that produced it.
inputsTensor or list of Tensor
Input tensors w.r.t. which gradients are requested. Each must be a leaf (or non-leaf with requires_grad=True if you want grads flowing into intermediate nodes).
grad_outputsTensor, sequence of (Tensor or None), or None= None
Seed gradients ∂L/∂outputs\partial \mathcal{L} / \partial \text{outputs}, one per output, each of its output's shape and device (another real dtype is cast to the output's). A single tensor stands for a one-element sequence. None — for the whole argument or one entry — is an implicit 1, allowed only for a real output of one element.
retain_graphbool= None
Keep the autograd graph alive after this call so additional backward passes are possible. Defaults to create_graph.
create_graphbool= False
If True, build the autograd graph of the gradient itself so the returned tensors are differentiable — used by gradgradcheck and other higher-order recipes.
only_inputsbool= True
Reserved for reference-framework compatibility; gradients are always restricted to the requested inputs.
allow_unusedbool= None
If True, return None for any inputs entry that lies outside the computation graph of outputs. Defaults to materialize_grads.
is_grads_batchedbool= False
If True, interpret the leading dimension of each tensor in grad_outputs as a batch dimension and compute a batch of vector-Jacobian products. Defaults to False.
materialize_gradsbool= False
If True, replace None gradients for unused inputs with zero-filled tensors matching each input's shape, dtype, and device. Defaults to False.

Returns

tuple[Tensor or None, ...]

One gradient per element of inputs, in the same order. Entries are None only when allow_unused=True (and materialize_grads=False) and the input is disconnected.

Raises

RuntimeError
The number of grad_outputs differs from the number of outputs, a non-scalar output has no seed, or (without allow_unused) an input is unreachable from outputs.
ValueError
If allow_unused=False and materialize_grads=True.
TypeError
A seed is neither a tensor nor None.
(ShapeMismatch, DtypeMismatch, DeviceMismatch)
A seed's shape or device differs from its output's, or only one of the two is complex.

Notes

Mathematically, grad computes the vector-Jacobian product

∂∂x(∑kgrad_outputsk⋅outputsk)\frac{\partial}{\partial \mathbf{x}} \left(\sum_k \text{grad\_outputs}_k \cdot \text{outputs}_k\right)

via one reverse-mode pass. Unlike Tensor.backward, it does NOT accumulate into .grad — leaf tensors' existing .grad values are preserved across the call. For chained gradient computations (Hessian-vector products, MAML inner loops) this is the right primitive.

Examples

Scalar output — no seed needed:
>>> import lucid
>>> from lucid.autograd import grad
>>> x = lucid.tensor([1.0, 2.0, 3.0], requires_grad=True)
>>> y = (x * x).sum()
>>> (gx,) = grad(y, [x])
>>> gx                         # equals 2 * x
tensor([2., 4., 6.])
Vector output — explicit seed:
>>> z = x * x
>>> seed = lucid.ones_like(z)
>>> (gx,) = grad(z, [x], grad_outputs=[seed])
Higher-order with create_graph=True:
>>> y = (x ** 3).sum()
>>> (g,) = grad(y, [x], create_graph=True)
>>> (gg,) = grad(g.sum(), [x])    # second derivative: 6x
>>> gg
tensor([6., 12., 18.])

Used by 3