argnums chooses which positional argument or arguments a JAX gradient should differentiate with respect to. By default, grad() uses the first parameter, so argnums matters when the differentiated input is not first or when you want several inputs at once. section 4.2.3 section 4.4
Common uses here include:
- Skipping a non-differentiated leading parameter without rewriting the function signature. section 4.2.3
- Differentiating with respect to multiple positional inputs by passing a tuple of indices. section 4.2.3
- Working with structured inputs such as dicts and pytrees through the selected argument. section 4.2.3
Selecting the second argument
For a distance function written as dist(order, x, y), argnums=1 targets x without moving order to the end. The result is a gradient shaped like x, while argnums=(1,2) returns a tuple of gradients for both x and y.
argnums works alongside other gradient options: has_aux returns extra outputs, value_and_grad returns both loss and gradient, and stop_gradient blocks flow through selected expressions.
