Skip to content

Instantly share code, notes, and snippets.

View guanshaoheng's full-sized avatar
🏠
Working from home

shguan guanshaoheng

🏠
Working from home
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))