Skip to content

Instantly share code, notes, and snippets.

View Bigpig4396's full-sized avatar

Shuo Jiang Bigpig4396

  • Northeastern University
  • Boston, MA, USA
View GitHub Profile
import torch
def jacobian(y, x, create_graph=False):
jac = []
flat_y = y.reshape(-1)
grad_y = torch.zeros_like(flat_y)
for i in range(len(flat_y)):
grad_y[i] = 1.
grad_x, = torch.autograd.grad(flat_y, x, grad_y, retain_graph=True, create_graph=create_graph)
jac.append(grad_x.reshape(x.shape))