Created
March 8, 2017 00:20
-
-
Save rguthrie3/2ac45905be0cc4277361084335df87f7 to your computer and use it in GitHub Desktop.
pytorch bug?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
import torch.autograd as autograd | |
import torch.nn as nn | |
import torch.nn.functional as F | |
import torch.optim as optim | |
class WorkingModule(nn.Module): | |
def __init__(self): | |
super(WorkingModule, self).__init__() | |
self.params = nn.Parameter(torch.randn(5,5)) | |
def forward(self, sequence): | |
score = autograd.Variable( torch.Tensor([0]) ) | |
for i in xrange(len(sequence) - 1): | |
score = score + self.params[sequence[i+1], sequence[i]] | |
return score | |
class BuggyModule(nn.Module): | |
def __init__(self): | |
super(BuggyModule, self).__init__() | |
self.params = nn.Parameter(torch.randn(5,5)) | |
def forward(self, sequence): | |
sequence = autograd.Variable(sequence) # Wrap in a variable (or maybe it was passed in like this)... | |
score = autograd.Variable( torch.Tensor([0]) ) | |
for i in xrange(len(sequence) - 1): | |
score = score + self.params[sequence[i+1].data, sequence[i].data] | |
return score | |
input_seq = torch.LongTensor([ 0, 1, 2, 1, 0, 3 ]) | |
model = WorkingModule() | |
score = model(input_seq) | |
score.backward() | |
print model.params.grad # Good! | |
model = BuggyModule() | |
score = model(input_seq) | |
score.backward() | |
print model.params.grad # zero! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment