Skip to content

Instantly share code, notes, and snippets.

@lfrati
Last active October 20, 2018 18:53
Show Gist options
  • Select an option

  • Save lfrati/d271fa868b6373d1c5af968af5951ad7 to your computer and use it in GitHub Desktop.

Select an option

Save lfrati/d271fa868b6373d1c5af968af5951ad7 to your computer and use it in GitHub Desktop.
"""Toy examples for torch.autograd.grad."""
import torch
from torch.autograd import Variable
# Input
x = torch.tensor([1., 2., 3.], requires_grad=True)
# Weights
w1 = torch.tensor([2., 3., 4.]), requires_grad=True)
w2 = torch.tensor([3., 4., 5.]), requires_grad=True)
# Create a computational graph
h = w1 * x
y = w2 * h
# Compute dy/dh. Since dy/dh is w2, it returns [3, 4, 5].
# If y is a vector, you should provide torch.ones(y.size()). If y is a scalar, you can skip the "grad_outputs" arguments.
dydh = torch.autograd.grad(outputs=y,
inputs=h,
grad_outputs=torch.ones(y.size()),
retain_graph=True) # To prevent buffer initialization
# Compute dh/dx. Since dh/dx is w1, it returns [2, 3, 4].
dhdx = torch.autograd.grad(outputs=h,
inputs=x,
grad_outputs=torch.ones(h.size()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment