Skip to content

Instantly share code, notes, and snippets.

@zou3519
Created November 13, 2017 13:19
Show Gist options
  • Save zou3519/4cb1c3a674e9785bf8121e851d4ded0d to your computer and use it in GitHub Desktop.
Save zou3519/4cb1c3a674e9785bf8121e851d4ded0d to your computer and use it in GitHub Desktop.
import numpy as np
import torch
from torch.autograd import Variable
def set_seed(seed):
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
def main():
set_seed(1)
cuda = True
n, e, c = 5, 100, 5
input = torch.randn(n,c)
idxn = torch.from_numpy(np.random.randint(n,size=e)) # indices are repeated
if cuda:
input = input.cuda(); idxn = idxn.cuda()
gradsI, gradsS = [], []
N = 2
# input[0, 2] += 0
input[0, 2] += 0.1
for i in range(N):
inputv = Variable(input, requires_grad=True)
sel_input = torch.index_select(inputv, 0, Variable(idxn))
sel_input.retain_grad()
# the following computation is one of the "random conditions"
data = [torch.sum(sel_input.narrow(0,0,e//2), 0),
torch.sum(sel_input.narrow(0,e//2,e//2), 0) ]
aout = torch.sum(sel_input, 0)
out = torch.cat(data,0)
output = out.exp().sum()
print("output = ", output.data, " input = ", inputv.data[0, 2])
output.backward()
gradsI.append(inputv.grad.data.cpu().clone())
gradsS.append(sel_input.grad.data.cpu().clone())
for i in range(N):
for j in range(N):
print(i,j,(gradsI[i]-gradsI[j]).abs().max(), (gradsS[i]-gradsS[j]).abs().max())
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment