Skip to content
Hard Framework

Compute Jacobian

A Jacobian records how each output of a vector-valued function changes with each input. Rows correspond to outputs; columns correspond to inputs.

Your task

Implement compute_jacobian(x) for a floating-point vector of shape (2,). The function to differentiate is:

f(x) = [x[0] * x[1], x[0] + x[1]**2]

Return a tensor of shape (2, 2) with x's dtype and device. Leave x unchanged. Entry J[i, j] is the derivative of output i with respect to input j:

J = [[x[1], x[0]],
     [1,    2*x[1]]]

For x=[3, 4], return [[4, 3], [1, 8]]. In the second row, changing x[0] changes the second output at rate 1, while changing x[1] changes it at rate 8. Do not transpose this layout.

Define f using tensor operations and stack its two scalar outputs. Then use torch.autograd.functional.jacobian(f, x) or jax.jacobian(f)(x). The formula above lets you check the result while practicing automatic differentiation.

Differentiating the sum of f's outputs gives only one gradient vector: it adds the Jacobian's rows together. This task needs both rows separately, not that summed gradient and not the original two function values.