id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st99568
|
I used the pre-training model, so I didn’t define it. I didn’t find the source file, so I don’t know how the original file was defined. I printed the model and wrote ResNet.
|
st99569
|
OK, if you used the pretrained model, you can just load it in the same way as before and load your trained state_dict after it:
import torchvision.models as models
model_ft = models.resnet101(pretrained=False)
model_ft.load_state_dict(torch.load(PATH))
|
st99570
|
Thank you, I tried it. This problem has been bothering me for a long time.Since I was fine-tuning the pre-training model and saving it, I still got the following error:
self.class.name, “\n\t”.join(error_msgs)))
RuntimeError: Error(s) in loading state_dict for ResNet:
While copying the parameter named “fc.weight”, whose dimensions in the model are torch.Size([1000, 2048]) and whose dimensions in the checkpoint are torch.Size([11, 2048]).
While copying the parameter named “fc.bias”, whose dimensions in the model are torch.Size([1000]) and whose dimensions in the checkpoint are torch.Size([11]).
|
st99571
|
You’ve changed apparently the architecture of the pretrained model.
Could you post the code for your training?
Basically, you have to define the model in the same way as you did while training.
E.g. if you changed the last linear layer to 11 classes, you would need to do the same again before loading the state_dict.
|
st99572
|
Thank you very much, here is the code for my training and fine-tuning the pre-training model, because I want to do the feature extraction of a single image, so I want to save the model.
######################################################################
Training the model
def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1))
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
scheduler.step()
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
# backward + optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step()
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
# deep copy the model
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
torch.save(model.state_dict(), 'model1.pkl') ###save model
print()
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
time_elapsed // 60, time_elapsed % 60))
print('Best val Acc: {:4f}'.format(best_acc))
# load best model weights
model.load_state_dict(best_model_wts)
return model
######################################################################
Finetuning the convnet
model_ft = models.resnet101(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 11)
model_ft = model_ft.to(device)
criterion = nn.CrossEntropyLoss()
Observe that all parameters are being optimized
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)
Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)
######################################################################
Train and evaluate
model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,
num_epochs=30)
|
st99573
|
i used to save the tensor by transforms it to array,but could i save the tensor directly?
|
st99574
|
@luodahei you can use torch.save 55 to save a tensor. See the example in the doc.
|
st99575
|
Hi! I am a newbie to pytorch and deep learning in general and I have found the documentation on output shape of RNN layers to be a little bit confusing.
I’ve noticed that the default output shape of RNN layers is shape (seq_len, batch, num_directions * hidden_size) but by setting ‘batch_first’ the output shape would become (batch, seq, feature). Why not having batch first as the default output shape? Is it because of some optimization problem?
Thanks!
|
st99576
|
If you organise things sequence first, then each timestep, which is much like a regular layer (linear on hidden + linear on input + nonlinearities + gating) operates on contiguous bits of data, and you have good caching properties etc.
Best regards
Thomas
|
st99577
|
Thank you for the reply Thomas! So does this mean set ‘batch_first=true’ will compromise the computing performance/speed?
|
st99578
|
That is the idea, I haven’t benchmarked it myself, though, so I’m not in the best position to discuss this in detail.
|
st99579
|
What learning rate decay scheduler should I use with Adam Optimizer?
I’m getting very weird results using MultiStepLR and ExponentialLR decay scheduler.
#scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer=optimizer, milestones=[25,50,75], gamma=0.95)
scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer=optimizer, gamma=0.25)
optimizer = torch.optim.Adam(lr=m_lr,amsgrad=True, ...........)
for epoch in range(num_epochs):
scheduler.step()
running_loss = 0.0
for i in range(num_train):
train_input_tensor = ..........
train_label_tensor = ..........
optimizer.zero_grad()
pred_label_tensor = model(train_input_tensor)
loss = criterion(pred_label_tensor, train_label_tensor)
loss.backward()
optimizer.step()
running_loss += loss.item()
loss_history[m_lr].append(running_loss/num_train)
Any Help.
Thanks
|
st99580
|
Hi,
I’m trying to train an LSTM network, and using Adam as optimizer.
What is the recommended learning rate scheduler to use, that usually fits best to Adam?
I was under the impression that Adam controls the learning rate internally, but I see that if I manually reduce the learning rate when the validation loss reaches a plateau, I manage to further reduce the loss.
Thanks,
Guy
|
st99581
|
To my best of my knowledge, it depends on the model you are training.
Personally, I decay it by 0.1 if the validation loss rise.
BTW, it seems RMSprop is used more often in LSTM.
|
st99582
|
Hi @guyrose3, How are you reducing the learning rate while using Adam? I’m trying to do a similar process, but it seems that PyTorch’s implementation of Adam does not account for an external learningrate scheduler.
I’ve started a thread on Stack Exchange. See this for more info:
ai.stackexchange.com
Loss jumps abruptly when I decay the learning rate 336
machine-learning, deep-learning, autoencoders, loss-functions
asked by
vinaykumar2491
on 01:14PM - 20 Sep 18
|
st99583
|
Here are the values of the tensor and its numpy version using X.numpy()
tensor(28.0000)
27.999998
what i did in the original code is to normalize an image using transforms and then apply the inverse. the numbers printed above are the min value in the image.
|
st99584
|
I think it might just be a printing issue. Try to set the precision a bit higher using: torch.set_printoptions 3.
|
st99585
|
this is true I set torch.set_printoptions(precision=8) and the new values are:
tensor(27.99999809)
27.999998
it seems like the normalization inversion is not accurate to get the original value ‘28’ back
|
st99586
|
I think it’s not a problem of accuracy but rather of the floating point precision. Some values can’t be represented exactly. Have a look here 3 for more information.
|
st99587
|
Hi, I have Installed Pytorch1.0 version by the command “conda install pytorch-nightly -c pytorch”.
After installing I imported torch. I am getting error "‘ImportError: libcuda.so.1: cannot open shared object file: No such file or directory’’’
|
st99588
|
Same problem here. The nightly version is broken when you don’t want the gpu version
|
st99589
|
I am working on adversarial attacks in pytorch. I am performing iterative gradient sign based attacks, but as cudnn is not deterministic the input gradient sign may vary and over many iterations this accumulates and gives very different results. For detailed discussion look discussion - 1 2 and discussion - 2.
I looked at other pytorch implementations but they also follow similar procedure.
As answered in those links by @albanD (really appreciated!) I first tried setting torch.backends.cudnn.deterministic = True but it didn’t work out.
Then I also thought of giving cunn a try so I did torch.backends.cudnn.enabled=False but it also didn’t help and still it’s non reproducible and varying significantly.
As adversarial attacks don’t have any kind of training involved but only backpropogation (atleast iterative gradient sign methods!) I think for I need to ensure reproducibility of results consistently
Why didn’t changing those flags work out? how to get deterministic behaviour (I could find only these two methods on searching)
Thanks a lot in advanced!
|
st99590
|
Solved by tom in post #3
Good catch with the Upsample.
I think there currently is no-one systematically investing in determinism.
(For most cases the problem is much less severe because of a continuous dependence on gradients, but the “fast gradient sign” is very discontinuous by design.)
Best regards
Thomas
|
st99591
|
Update follow up:
github.com/pytorch/pytorch
Issue: Non Deterministic Behaviour even after cudnn.deterministic = True and cudnn.benchmark=False 19
opened by Naman-ntc
on 2018-09-30
I was performing adversarial attacks with pytorch and I was not able to reproduce my experiments.
Finally I learned about non deterministic...
|
st99592
|
Good catch with the Upsample.
I think there currently is no-one systematically investing in determinism.
(For most cases the problem is much less severe because of a continuous dependence on gradients, but the “fast gradient sign” is very discontinuous by design.)
Best regards
Thomas
|
st99593
|
Thanks! I didn’t know till yesterday that non-deterministic existed (in pytorch atleast ). It has been really crazy since then.
And thanks a lot for the fix!!!
|
st99594
|
@tom the hack you have mentioned is to expanding the tensor (appropriately).
Th@t won’t be equivalent to a nearest neighbour interpolation right. (default for nn.Upsample).( I was so happy with getting behaviour fixed that I overlooked this lol! )
Can the nearest neighbour interpolation be performed via some fixed convolution kernel after expanding the tensor? (such yhat it is close enough to nearest neighbour interpolation)
Or othewise i guess it may be a good idea to have a 3x3 kernel with learnable parameters posr expanding, (random but I expect ot to work :P)
|
st99595
|
Oh, I’m sorry, I thought it was for scale_factor=2:
a = torch.arange(9, dtype=torch.float).view(1,1,3,3)
b = torch.nn.functional.interpolate(a, scale_factor=2)
b2 = a[:, :, :, None, :, None].expand(-1, -1, -1, 2, -1, 2).reshape(a.size(0), a.size(1), a.size(2)*2, a.size(3)*2)
print((b-b2).abs().max().item())
|
st99596
|
Ohh my bad I thought Upsample also interpolates the values. Seems it depends on interpolate keyword. Should have checked! thanks
|
st99597
|
Hi!
So this is a minimal code which illustrates the issue:
This is the Dataset:
class IceShipDataset(Dataset):
BAND1='band_1'
BAND2='band_2'
IMAGE='image'
@staticmethod
def get_band_img(sample,band):
pic_size=75
img=np.array(sample[band])
img.resize(pic_size,pic_size)
return img
def __init__(self,data,transform=None):
self.data=data
self.transform=transform
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
sample=self.data[idx]
band1_img=IceShipDataset.get_band_img(sample,self.BAND1)
band2_img=IceShipDataset.get_band_img(sample,self.BAND2)
img=np.stack([band1_img,band2_img],2)
sample[self.IMAGE]=img
if self.transform is not None:
sample=self.transform(sample)
return sample
And this is the code which fails:
PLAY_BATCH_SIZE=4
#load data. There are 1604 examples.
with open('train.json','r') as f:
data=f.read()
data=json.loads(data)
ds=IceShipDataset(data)
playloader = torch.utils.data.DataLoader(ds, batch_size=PLAY_BATCH_SIZE,
shuffle=False, num_workers=4)
for i,data in enumerate(playloader):
print(i)
pass
It gives that weird open files error in the for loop…
And this is the state of my machine when getting that weird error:
yoni@yoni-Lenovo-Z710:~$ lsof | wc -l
89114
yoni@yoni-Lenovo-Z710:~$ cat /proc/sys/fs/file-max
791958
My torch version is 0.3.0.post4
If you want the json file, it is available at Kaggle (https://www.kaggle.com/c/statoil-iceberg-classifier-challenge 2)
What am I doing wrong here?!
|
st99598
|
Supposing it’s a unix based system, then everything is a file. Other proc might be using a lot of fds. Try increasing your file num limit or restart.
|
st99599
|
While it is Ubuntu, that isn’t the issue at all, and this isn’t the first time I’m using DataLoader…
Oh the following shows this isn’t the issue(unless DataLoader opens over 800000 files, in which case i would like to know why ):
yoni@yoni-Lenovo-Z710:~$ lsof | wc -l
89114
yoni@yoni-Lenovo-Z710:~$ cat /proc/sys/fs/file-max
791958
|
st99600
|
hi guys,
were you able to get a resolution here? I’m seeing the same error. I’m using torch==0.3.1 and I’m on Ubuntu 16.04. I have other working data-loaders that doesn’t see this problem.
|
st99601
|
I am seeing the same issue of too many open files on Ubuntu 16.04 with dataloader. Any suggestions for a solution?
|
st99602
|
Have you tried @SimonW’s suggestion of increasing the file num limit?
A restart might also help in some cases in case your system holds a lot of files open.
|
st99603
|
Yes, I did and it does not complain now. But I am still concerned that it could happen if the limit is reached in some future cases. I wonder what causes the data loader to open that many files? Is it a bug?
|
st99604
|
How can I use Lamba layer that can force a percentage of weights from a layer to zero during test and train once chosen to be dropped?
I switched to pytorch a couple of days ago and a detailed explanation will be very helpful. Please find the Keras script I was using(below), using Lamba and Dropout for the same.
class PermanentDropout(Dropout):
def init(self, rate, **kwargs):
super(PermanentDropout, self).init(rate, **kwargs)
def build(self, input_shape):
self.uses_learning_phase = False
super(PermanentDropout, self).build()
def call(self, x, mask=None):
if 0. < self.rate < 1.:
noise_shape = self._get_noise_shape(x)
x=Lambda(lambda x: K.dropout(x,self.rate, noise_shape))(x)
return x
|
st99605
|
As far as I understand your code, you are basically using a Dropout layer given a special flag which you defined.
If that’s the case, you can just use the functional dropout 7 in your forward method and use the training argument to activate or deactivate it.
|
st99606
|
I have a tensor
a = tensor([[1,1,1,1],[1,2,3,4]])
b = tensor([[0.1,0.2,0.3,0.4],[0.1,0.2,0.3,0.4]])
i want to fill these values in a tensor of dim 2 x 10[vocab size] like
tensor([[0,0.1+0.2+0.3+0.4,0,0,…],[0,0.1,0.2,0.3,0.4,0,0,…]])
basically fill corresponding values of tensor b into a new tensor indexed with a.
I cannot even do
i = 0
for a_,b_ in zip(a,b):
c[i][a_] += b_
As there are repeated indices as shown in the example. 1 occurs 4 times here , so this method just puts the last value 0.4 at the index of 1 , but i want 0.1+0.2+0.3+0.4 at the index of 1.
Is there any other method than having another for loop over the tensor. Also if i want to have access to the tensor for backprop how do i select these items, torch.index_select (tensor)? Will it keep it in the computational graph still? For example if i am interested in those particular b values which are tensors can include it in loss and call backward will it still backprop through the b_'s
[SOLVED using scatter_add_]
|
st99607
|
When I read the code in this
How can I use different losses to update different branches respectively, and sum grad together to update master(main) branch autograd
I am facing a multi-label problem. My network has 2 branches, which are separated from a conv layers.
There is the sketch of my network
class MultiLabelDemo(nn.Module):
def __init__(self):
super(MultiLabelDemo, self).__init__()
self.main_block = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=96, kernel_size=11, stride=4),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels=96, out_channels=96, kernel_size=1, stride=1),
nn.ReLU(…
class MultiLabelDemo(nn.Module):
def __init__(self):
super(MultiLabelDemo, self).__init__()
self.main_block = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=96, kernel_size=11, stride=4),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels=96, out_channels=96, kernel_size=1, stride=1),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels=96, out_channels=96, kernel_size=1, stride=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)
)
self.tail_block1 = nn.Sequential(
nn.Conv2d(in_channels=96, out_channels=256, kernel_size=5, stride=1, padding=2),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=1, stride=1),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=1, stride=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)
)
self.tail_block2 = nn.Sequential(
nn.Conv2d(in_channels=96, out_channels=256, kernel_size=5, stride=1, padding=2),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=1, stride=1),
nn.ReLU(inplace=True),
nn.Conv2d(in_channels=256, out_channels=256, kernel_size=1, stride=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)
)
def forward(self, data):
x = self.main_block(data)
y1 = self.tail_block1(x)
y2 = self.tail_block2(x)
return y1, y2
When I have multiple branches, is it the same if I use clone() to one of them? or all of them?
def forward(self, data):
x = self.main_block(data)
y1 = self.tail_block1(x)
y2 = self.tail_block2(x**.clone()**)
y3 = self.tail_block3(x**.clone()**)
y1 = y1 * (y2+y3)
return y1
In my code, I found if I dont use colone, I will have the error
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation.
|
st99608
|
Hi,
The only difference it makes is that it copies some tensors. So output value and gradient will be the same.
One difference that makes though is that if you try to modify the tensor inplace, this is not allowed if it’s original value is needed. If you clone, then the inplace operation is done on the cloned tensor and it’s not a problem.
|
st99609
|
albanD:
Hi,
The only difference it makes is that it copies some tensors. So output value and gradient will be the same.
One difference that makes though is that if you try to modify the tensor inplace, this is not allowed if it’s original value is needed. If you clone, then the inplace operation is done on the cloned tensor and it’s not a problem.
Hi
When I don’t use clone(), I found if my tail_block start with
relu(inplace=True)
I will have the error like this
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation.
if the tail_block start with bn or conv, it’s ok.
But if I use clone() for every x, I won’t get any errors.
|
st99610
|
There are several other posts on the forums about nondeterminism. Most of the answers suggest some combination of setting all the random seeds, setting num_workers to 0, and setting backends.cudnn.deterministic = True. I have tried all of the above, and I still get non-deterministic final accuracy numbers. Here is a short script that demonstrates this behavior: a simple convolutional neural network on CIFAR-10. I ran it 4 times in a row (same machine) and got 3 different final accuracies: 64.31, 64.72, 64.67. (Perhaps these aren’t huge differences, but with the real architecture and dataset I am using, I’ve observed final differences over 1% when running the same code, which is quite a bit in my opinion.) I am using Python 3.6.3, PyTorch 0.4.1, and a single NVIDIA Tesla K80 GPU, on CentOS Linux 7.4.1708.
import numpy as np
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 64, 5, padding=1)
self.conv2 = nn.Conv2d(64, 64, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.conv3 = nn.Conv2d(64, 128, 3, padding=1)
self.conv4 = nn.Conv2d(128, 128, 3, padding=1)
self.fc1 = nn.Linear(128 * 7 * 7, 1024)
self.fc2 = nn.Linear(1024, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.pool(self.conv2(x)))
x = F.relu(self.conv3(x))
x = F.relu(self.pool(self.conv4(x)))
x = x.view(-1, 128 * 7 * 7)
x = F.relu(self.fc1(x))
x = F.dropout(x, 0.2, training=self.training)
x = self.fc2(x)
return x
##### Get the data.
train_data = datasets.CIFAR10(root='./data', train=True, download=True, transform=transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(train_data, batch_size=64, pin_memory=True,
shuffle=True, num_workers=0,
worker_init_fn=lambda x: np.random.seed(1))
test_data = datasets.CIFAR10(root='./data', train=False, download=True, transform=transforms.ToTensor())
test_loader = torch.utils.data.DataLoader(test_data, batch_size=64, shuffle=False, num_workers=0)
##### Set the seeds.
torch.manual_seed(2)
torch.cuda.manual_seed_all(2)
torch.backends.cudnn.deterministic = True
np.random.seed(1)
random.seed(1)
device = torch.device('cuda')
torch.backends.cudnn.benchmark = True
##### Train the model.
model = CNN()
model.to(device)
model = nn.DataParallel(model) # Not needed for just one GPU, but removing this doesn't fix the nondeterminism
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
model.train()
for epoch in range(2):
print('Epoch %d' % epoch)
for inputs, labels in train_loader:
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
##### Evaluate the model.
correct, tot = 0, 0
model.eval()
with torch.no_grad():
for inputs, labels in test_loader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
tot += labels.size(0)
correct += (predicted == labels).sum().item()
print(correct / tot * 100)
|
st99611
|
Your issue might be related to this discussion 71.
Basically, even if you set torch.backends.cudnn.deterministic = True, torch.backends.cudnn.benchmark = True might select different deterministic algorithms, which would yield different results.
There is a current PR 25 working on this.
Could you disable benchmarking and try it again?
|
st99612
|
ptrblck:
Basically, even if you set torch.backends.cudnn.deterministic = True , torch.backends.cudnn.benchmark = True might select different deterministic algorithms, which would yield different results.
There is a current PR working on this.
Could you disable benchmarking and try it again?
Hi, I am also facing a similar issue
torch.backends.cudnn.deterministic=True
torch.backends.cudnn.benchmark=False
I do just after the imports, but I am still getting non deterministic behaviour. I have also tried torch.backends.cudnn.enabled=False as I read that cunn modules also provide deterministic behaviour.
I have shuffle turned off, model on eval mode, and backpropogating for the gradients of input image (for performing adversarial attacks), so I believe protocol is fulfilled ?
Link to thread I created 5 (which further contain links to questions I created)
|
st99613
|
i make the model and the input tensor in GPU by model = model.cuda() input_tensor = input_tensor.cuda()
But the Volatile GPU-util is 0% with i occupy the video memory?
If i use cpu to train ,why does it occupy the Video Memory?
And what should i do to use Gpu to train?
Thank you very much!
TIM图片20180930235648.png744×408 23.9 KB
|
st99614
|
I used the pre-training model and fine-tuned it, then I saved the model and then restored the model, then extracted the features, and I got this error:
File "feature-map.py", line 58, in visualize_picture
y=myexactor(inputs)
File "/home/liupu/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 491, in __call__
result = self.forward(*input, **kwargs)
File "feature-map.py", line 45, in forward
x = module(x)
File "/home/liupu/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 491, in __call__
result = self.forward(*input, **kwargs)
File "/home/liupu/anaconda3/lib/python3.6/site-packages/torch/nn/modules/linear.py", line 55, in forward
return F.linear(input, self.weight, self.bias)
File "/home/liupu/anaconda3/lib/python3.6/site-packages/torch/nn/functional.py", line 994, in linear
output = input.matmul(weight.t())
RuntimeError: size mismatch, m1: [4096 x 1], m2: [2048 x 11] at /opt/conda/conda-bld/pytorch_1525909934016/work/aten/src/THC/generic/THCTensorMathBlas.cu:249
What should I do? Can you help me?
|
st99615
|
Are you sure you are passing the images of correct size during evaluation? It seems there could be a mistake in that part. Can you please post your code to have a look? It’s difficult to hypothesize without code.
|
st99616
|
Thank you very much, I posted my code below:
from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
import torchvision
from torchvision import datasets, models, transforms
import time
import os
from PIL import Image
import matplotlib.pyplot as plt
import torch.nn.functional as F
plt.ion() # interactive mode
data_transforms = {
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.5,0.5,0.5], [0.5,0.5,0.5])
]),
}
data_dir = 'feature_pic/'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),
data_transforms[x])
for x in ['val']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=2,
shuffle=False, num_workers=4)
for x in ['val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['val']}
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class FeatureExtractor(nn.Module):
def __init__(self, submodule, extracted_layers):
super(FeatureExtractor,self).__init__()
self.submodule = submodule
self.extracted_layers= extracted_layers
def forward(self, x):
outputs = []
for name, module in self.submodule._modules.items():
if name is "fc": x = x.view(x.size(0), -1)
x = module(x)
if name in self.extracted_layers:
outputs.append(x)
return outputs
# Iterate over data.
def visualize_picture(model):
model.eval()
for i, (inputs, labels) in enumerate(dataloaders['val']):
inputs = inputs.to(device)
labels = labels.to(device)
exact_list=["conv2","layer2","avgpool"]
myexactor=FeatureExtractor(model,exact_list)
y=myexactor(inputs)
#特征输出可视化
for i in range(4):
ax = plt.subplot(2, 2, i + 1)
#ax.set_title('Sample #{}'.format(i))
ax.axis('off')
plt.imshow(y[0].data.cpu().numpy()[0,i,:,:],cmap='jet')
plt.show()
plt.savefig('feature.png')
myresnet =torch.load("./checkpoint/model.pkl")
myresnet = myresnet.to(device)
visualize_picture(myresnet)
plt.ioff()
plt.show()
I think there may be a problem with the model I loaded, because I saved the entire network. If I only load the parameters, I don’t know how to do it.Thanks
|
st99617
|
you can follow the procedure shown here to save and load models.
Saving and loading a model in Pytorch?
Hi! the best and safe way to save your model parameters is doing something like this:
model = MyModel()
# ... after training, save your model
model.save_state_dict('mytraining.pt')
# .. to load your previously training model:
model.load_state_dict(torch.load('mytraining.pt'))
|
st99618
|
Hello,
I’am new to pytorch and other deep learning frameworks.
I want to use the “Position seneitive roi pooling” and found related codes in github -> pytorch -> modules -> detectron -> “ps_roi_pool_op.h”, “ps_roi_pool_op.cc”, “ps_roi_pool_op.cu”.
So… Could you tell me How to compile or import theses codes?
Thank you in advance.
|
st99619
|
The following problem occurs when I am drawing a picture:
MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
warnings.warn(message, mplDeprecation, stacklevel=1)
My program is as follows:
plt.ion() # interactive mode
for i in range(64):
ax = plt.subplot(8, 8, i + 1)
#ax.set_title('Sample #{}'.format(i))
ax.axis('off')
plt.imshow(y[0].data.cpu().numpy()[0,i,:,:],cmap='jet')
plt.show()
plt.savefig('feature.png')
How can I solve it?
plt.ioff()
plt.show()
|
st99620
|
Dear all,
When I use dataloader to load data, when settiing num_workers = 0, nothing happened. But when setting num_workers = 1 or more, the error occures in the following:
RuntimeError: DataLoader worker (pid 5520) exited unexpectedly with exit code 1. Details are lost due to multiprocessing. Rerunning with num_workers=0 may give better error trace.
That is,
test_data = Data(IMGS_TEST, GT_TEST, V_TEST, mode="test")
data_loader = DataLoader(test_data, num_workers=10) # get error
data_loader = DataLoader(test_data, num_workers=0) # OK
And the code of Dataset is as follows:
class Data(data.Dataset): # vis: vessels of images
def __init__(self, imgs_root, gt_root, vessels_path, mode="train"):
# self.imgs = [os.path.join(imgs_root, img) for img in os.listdir(imgs_root)]
self.img_paths = sorted(glob.glob(os.path.join(imgs_root, '*.png')))
self.gt_paths = [os.path.join(gt_root, img.split("/")[-1]) for img in self.img_paths]
vis = load_pkl(vessels_path)
split = int(0.7 * len(self.img_paths))
for split2 in range(len(vis)):
point = vis[split2]
if point[2] >= split:
break
self.mode = mode
if mode == "train":
# self.img_paths = img_paths[:split]
# self.gt_paths = gt_paths[:split]
self.vis = vis[:split2]
elif mode == "val":
# self.img_paths = img_paths[split:]
# self.gt_paths = gt_paths[split:]
self.vis = vis[split2:]
elif mode == "test":
# self.img_paths = img_paths
# self.gt_paths = gt_paths
self.vis = vis
else:
print("the mode must be train / val / test.")
exit()
self.imgs = [T.Grayscale()(Image.open(img_path)) for img_path in self.img_paths]
self.gts = [Image.open(gt_path) for gt_path in self.gt_paths]
self.len = len(self.vis)
def transform(self, image, center_point):
pad = T.Pad(padding=PATCH_SIZE // 2)
image = pad(image)
i, j, h, w = int(center_point[0]) + PATCH_SIZE // 2, \
int(center_point[1]) + PATCH_SIZE // 2, \
PATCH_SIZE, \
PATCH_SIZE
patch = F.crop(image, i, j, h, w) # (40, 40)
totensor = T.ToTensor()
patch = totensor(patch) # torch.Size([1, 40, 40])
return patch
def __getitem__(self, index):
x, y, img_num, v_num = self.vis[index]
if index == self.len - 1 or v_num != self.vis[index + 1][3]:
deta_x, deta_y = 0, 0
else:
deta_x = self.vis[index + 1][0] - self.vis[index][0]
deta_y = self.vis[index + 1][1] - self.vis[index][1]
try:
patch = self.transform(self.imgs[img_num], (x, y))
segmentation = self.transform(self.gts[img_num], (x, y))
label = t.Tensor([deta_x, deta_y])
except Exception as e:
print(e)
print(self.mode)
print(self.len)
print("index and img_num", index, img_num)
exit()
return patch, segmentation, label
def __len__(self):
return len(self.vis)
Can anyone help me?
Regards,
Pt
|
st99621
|
Dear all,
I want to load my data using Dataset which must implement the getitem funciton. The function getitem(self, index) get the data indexed with index. So the data must be linearized.
However, my data is constructed as follows:
64 pictures
points of 64 pictures:
list : [[points of pic1], [points of pic2], … [points of pic64]]
and [points of pic1] is in the format of [ [p1, p2, p3], [p1, p2, p3, p4, p5], [p1, p2]…[p1, p2, p3]] with different lengths.
Each time I want to get one point and corresponding picture, how can I organize my data and use Dataset index to load the data ?
Regards,
Pt
|
st99622
|
You need to write a custom collate function to collect the output of __getitem__() method into a list or tuple. An example of custom collate function:
RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 3 and 2 in dimension 1
Yes. It is not dealing with your exact issue. I was hoping, it might give you some idea.
Please try-out the following collate function:
import torch
import numpy as np
import torch.utils.data as data
def my_collate(batch):
data = torch.stack([item[0].unsqueeze(0) for item in batch], 0)
target = torch.Tensor([item[1] for item in batch])
return [data, target]
class dataset(data.Dataset):
def __init__(self):
super(dataset, self).__init__()
def __len__(self):
…
|
st99623
|
I am having a cryptic issue upon loading data from a custom Dataset with the Dataloader when switching from python 2.7 to 3.5. See below the incriminated piece of code, where train_set and test_set are custom Dataset objects that I use to train/eval a parallelized model in a multi-gpu environment:
train_loader = DataLoader(train_set,batch_size=batch_size, shuffle = True,num_workers=8*self.GPU)
test_loader = DataLoader(test_set, batch_size=batch_size, shuffle=True,num_workers=8*self.GPU)
for n in list(range(nb_epoch + 1)):
train(n,train_loader,test_loader)
def train(self,epoch,train_loader,test_loader):
print ("**** Epoch ",epoch,"********")
for i, batch in enumerate(train_loader):
batch_maps = batch['map']
batch_labels = batch['label']
Here is the error I get:
for i, batch in enumerate(train_loader):
File "/home/julien/.local/lib/python3.5/site-packages/torch/utils/data/dataloader.py", line 281, in __next__
return self._process_next_batch(batch)
File "/home/julien/.local/lib/python3.5/site-packages/torch/utils/data/dataloader.py", line 301, in _process_next_batch
raise batch.exc_type(batch.exc_msg)
TypeError: function takes exactly 5 arguments (1 given)
When I run the same exact code with python 2.7, everything works fine. Any clue?
|
st99624
|
Solved by SimonW in post #2
Run with num_workers=0 to get better trace.
|
st99625
|
Hello everyone!
I am seeing some unexpected behaviour from the ReduceLROnPlateau learning rate scheduler. I have posted a code sample below. I want the learning rate to decrease after the loss doesn’t decrease for consecutive 5 epochs but the learning rate doesn’t change when I use the scheduler.
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(7 * 7 * 64, 1024)
self.fc2 = nn.Linear(1024, 10)
def forward(self, x):
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
net = Net()
optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=0.001)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience = 5, verbose = True, min_lr = 0.000001)
scheduler.step(100)
scheduler.step(10)
scheduler.step(11)
scheduler.step(12)
scheduler.step(13)
scheduler.step(14)
scheduler.step(15)
Thanks for your help in advance!
|
st99626
|
The next step will reduce the learning rate, if the loss hasn’t improved.
The patience is used to ignore these iterations and will lower the learning rate in the next step.
From the docs:
Number of epochs with no improvement after which learning rate will be reduced. For example, if patience = 2, then we will ignore the first 2 epochs with no improvement, and will only decrease the LR after the 3rd epoch if the loss still hasn’t improved then.
|
st99627
|
I used nccl and gloo to train my network, but I can’t find any difference between them. Acturally, I set the backend “ncc”. It still work well.
|
st99628
|
I’ve built Caffe2 with Pytorch for Ubuntu 16.04 with cuda 9 and cudnn 7.
I’m linking both caffe2 and the GPU shared objects into this code snippet:
....
int main(int argc, char** argv) {
caffe2::GlobalInit(&argc, &argv);
Workspace wrk;
auto tcpu = wrk.CreateBlob("tcpu")->GetMutable<TensorCPU>();
std::vector<float> v(10);
std::vector<TIndex> dims({1});
auto val = TensorCPU(dims, v, NULL);
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
And it segfaults with
root@45ca558c940e:/slam/build# ./app
E0824 21:06:44.960511 570 init_intrinsics_check.cc:43] CPU feature avx is present on your machine, but the Caffe2 binary is not compiled with it. It means you may not get the full speed of your CPU.
E0824 21:06:44.960811 570 init_intrinsics_check.cc:43] CPU feature avx2 is present on your machine, but the Caffe2 binary is not compiled with it. It means you may not get the full speed of your CPU.
E0824 21:06:44.960831 570 init_intrinsics_check.cc:43] CPU feature fma is present on your machine, but the Caffe2 binary is not compiled with it. It means you may not get the full speed of your CPU.
*** Aborted at 1535144804 (unix time) try "date -d @1535144804" if you are using GNU date ***
PC: @ 0x40e340 caffe2::TensorImpl::TensorImpl<>()
*** SIGSEGV (@0x0) received by PID 570 (TID 0x7f4f90015880) from PID 0; stack trace: ***
@ 0x7f4f8fc03390 (unknown)
@ 0x40e340 caffe2::TensorImpl::TensorImpl<>()
@ 0x40cdf2 c10::intrusive_ptr<>::make<>()
@ 0x40bcff _ZN3c1014make_intrusiveIN6caffe210TensorImplENS1_19UndefinedTensorImplEJRKSt6vectorIlSaIlEERKS4_IfSaIfEERPNS1_11BaseContextEEEENS_13intrusive_ptrIT_T0_EEDpOT1_
@ 0x40a97f caffe2::Tensor::Tensor<>()
@ 0x407645 main
@ 0x7f4f8b2f3830 __libc_start_main
@ 0x4072e9 _start
@ 0x0 (unknown)
Segmentation fault (core dumped)
I’m running this in a docker container with nvidia runtime. I built pytorch into the docker image and set seccomp=undefined.
|
st99629
|
Solved by steplee in post #2
I’ve fixed it by creating a CPUContext manually and passing it. Looks like the samples I’ve been drawing from are out of date.
|
st99630
|
I’ve fixed it by creating a CPUContext manually and passing it. Looks like the samples I’ve been drawing from are out of date.
|
st99631
|
steplee:
https://github.com/pytorch/pytorch/issues/11317
Thanks that’s helpful.
|
st99632
|
Hello
If I have 2 networks, the output of the first network is passed into the 2nd network.
I would run back-prop on an objective function using output of the 2nd network. However, I only want to update the first network and leave the 2nd network alone (by minimization). Later on, I want to update only the 2nd network and leave the 1st alone (by maximization).
Right now, I am thinking of just reconstructing the network each time and copying the weights, but I was wondering if there’s a better way to do this?
|
st99633
|
Solved by albanD in post #2
Hi,
I think the simplest way is to have two different optimizers.
Each one work with the parameters of one of the two networks. Then you do your forward/backward as usual and just call .step() for the optimizer of the network you currently want to update.
|
st99634
|
Hi,
I think the simplest way is to have two different optimizers.
Each one work with the parameters of one of the two networks. Then you do your forward/backward as usual and just call .step() for the optimizer of the network you currently want to update.
|
st99635
|
I have a square matrix that should be positive semi-definite (PSD). This is because, no matter what it’s value, I always modify it such that:
P = diag(diag(P)) + eye(I) * eps
Where eps is a small number. In other words, the matrix is both symmetric and has non-zero values along its diagonal. Then I try to invert this matrix. When I run it locally or even on my university’s head node machine, the code runs fine. But when I run it on GPUs, the code throws an error:
beta = inv(mm(L, L.t()) + P)
RuntimeError: MAGMA getrf : U(2,2) is 0, U is singular at /opt/conda/conda-bld/pytorch_1524584710464/work/aten/src/THC/generic/THCTensorMathMagma.cu:413
So I can invert the matrix when running on a CPU but not on a GPU. I have no idea what might be causing this, and any help is appreciated.
|
st99636
|
I have two computers, which installed Pytorch with Conda. :
One with Intel CPU + 2 TitanX. (Say this is Intel Conputer)
One with AMD threadripper + 2 1080Ti (Say this is AMD computer).
I tested the same code, with the same model, on the same dataset, but the results from two computer are different.
Let say if I run with a batch 512, then only the first haft (256 results) are matching between two computers, while the latter haft are different. Here is the screen shot of the output of the first(idx=0) and the last(idx=-1) samples in a batch:
Screenshot from 2018-09-29 13-35-54.png1926×183 67.4 KB
The results on the left are from Intel Computer (which are correct), and the AMD on the right.
Does anyone have the same problem, and know how to solve it?
Thanks in advance.
|
st99637
|
Hi,
Does that prevent the model from converging.
I would not expect any learning to give the same results for such different hardwares.
Keep in mind that adding two float numbers can give you different answers depending on the hardware (and both will be correct with respect to the standard).
Nothing makes the answer on one machine more correct than the other, they both are.
Now if that prevent the model from converging, I would first try different random seeds on the original machine to make sure that the model is actually stable and converges all the time, not just for that one random seed.
|
st99638
|
Hi,
So, the results above are obtained from Testing step, where the model weights are already trained. But even though, only the first half of the batch (for all batches) yields identical results ob both AMD and Intel computers, while the second half is very different.
When training on AMD machine with Parallel option, it never converges, no matter what learning rate I set.
Thanks.
|
st99639
|
Can anyone tell me how to do finetuning in pytorch? Suppose, I have loaded the Resnet 18 pretrained model. Now I want to finetune it on my own dataset which contain say 10 classes. How to remove the last output layer and change to as per my requirement?
|
st99640
|
You can find an example at the bottom of this section 10.6k of autograd mechanics notes.
|
st99641
|
Thanks for your reply.
I have another doubt here. While fine-tuning, should we not use a smaller learning rate for the whole network (http://cs231n.github.io/transfer-learning/ 1.6k)? Here the example says us to fix the network and only learn the weights in the newly added layers? Which one in recommended?
|
st99642
|
In the snippet I’ve sent you only the last layer is optimized. The rest will be frozen (base parameters will receive no gradients - they have requires_grad=False). This is as if you used learning rate of 0 for that part. If you want to use a lower lr for the base see this section 1.3k of the optim docs.
|
st99643
|
optimizer = torch.optim.SGD([
{'params': model.conv1.parameters()},
{'params': model.bn1.parameters()},
{'params': model.relu.parameters()},
{'params': model.maxpool.parameters()},
{'params': model.layer1.parameters()},
{'params': model.layer2.parameters()},
{'params': model.layer3.parameters()},
{'params': model.layer4.parameters()},
{'params': model.avgpool.parameters()},
{'params': model.fc.parameters(), 'lr': opt.lr}
], lr=opt.lr*0.1, momentum=0.9)
Is this the correct way of defining different learning rate to different layers of ResNet18? Or is there any other optimized way to do that?
|
st99644
|
This should do it:
ignored_params = list(map(id, model.fc.parameters()))
base_params = filter(lambda p: id(p) not in ignored_params,
model.parameters())
optimizer = torch.optim.SGD([
{'params': base_params},
{'params': model.fc.parameters(), 'lr': opt.lr}
], lr=opt.lr*0.1, momentum=0.9)
|
st99645
|
This may also help to learn how to modify layers without changing other layers’ parameters and construct a new model.
model = models.vgg16(pretrained=True)
print list(list(model.classifier.children())[1].parameters())
mod = list(model.classifier.children())
mod.pop()
mod.append(torch.nn.Linear(4096, 2))
new_classifier = torch.nn.Sequential(*mod)
print list(list(new_classifier.children())[1].parameters())
model.classifier = new_classifier
Also, you may consider to add pretrained models for VGG, which you may found here:
github.com/pytorch/vision
Pretrained VGG models 546
opened
Jan 18, 2017
closed
Feb 21, 2017
jcjohnson
Is there any plan for pretrained VGG models, especially VGG16 or VGG19? These are needed for style transfer; AlexNet and ResNets...
As for finetuning resnet, it is more easy:
model = models.resnet18(pretrained=True)
model.fc = torch.nn.Linear(2048, 2)
|
st99646
|
How do I add new layers to existing pretrained models? Here, the last layer by name is replaced with a Linear layer. How to add another layer after that?
|
st99647
|
class MyModel(nn.Module):
def __init__(self, pretrained_model):
self.pretrained_model = pretrained_model
self.last_layer = ... # create layer
def forward(self, x):
return self.last_layer(self.pretrained_model(x))
pretrained_model = torchvision.models.resnet18(pretrained=True)
model = MyModel(pretrained_model)
|
st99648
|
Thank you for the help.
Another question, I am not able to see classifier attribute when loading a pretrained ResNet-18. However, I can directly access the children attribute without needing classifier. Is the classifier attribute part of old version of PyTorch or something I am missing?
|
st99649
|
ResNets don’t have a classifier attribute. They use only a single fully-connected layer and it’s available as their fc attribute.
|
st99650
|
@zhoubinxyz may you add a more complete example to illustrate how to fine-tuning VGG model on a custom dataset using PyTorch?
|
st99651
|
There is an option named --pretrained in the imagenet main.py file. May I ask that if I use this option with a custom dataset like these:
python main.py --arch=alexnet --pretrained my_custom_dataset
What will happen with this command? It seems that like a fine-tuning.
|
st99652
|
I think --pretrained is meant for evaluation mode. The script doesn’t support finetuning at the moment.
|
st99653
|
apaszke:
ast_laye
@apaszke I reference this PR 76 for fine-tuning. For alexnet and vggnet, the original code replay all the fully-connected layers. May I ask:
how can I only replace the last fully-connected layer for fine-tuning and freeze other fully-connected layers?
Is the forward the right way to code? Because you give some reference code above:
def forward(self, x):
return self.last_layer(self.pretrained_model(x))
Original fine-tuing code:
class FineTuneModel(nn.Module):
def __init__(self, original_model, arch, num_classes):
super(FineTuneModel, self).__init__()
if arch.startswith('alexnet') :
self.features = original_model.features
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(256 * 6 * 6, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, num_classes),
)
self.modelName = 'alexnet'
elif arch.startswith('resnet') :
# Everything except the last linear layer
self.features = nn.Sequential(*list(original_model.children())[:-1])
self.classifier = nn.Sequential(
nn.Linear(512, num_classes)
)
self.modelName = 'resnet'
elif arch.startswith('vgg16'):
self.features = original_model.features
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(25088, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, num_classes),
)
self.modelName = 'vgg16'
else :
raise("Finetuning not supported on this architecture yet")
# Freeze those weights
for p in self.features.parameters():
p.requires_grad = False
def forward(self, x):
f = self.features(x)
if self.modelName == 'alexnet' :
f = f.view(f.size(0), 256 * 6 * 6)
elif self.modelName == 'vgg16':
f = f.view(f.size(0), -1)
elif self.modelName == 'resnet' :
f = f.view(f.size(0), -1)
y = self.classifier(f)
return y
|
st99654
|
I added following lines to imagenet example, using pretrained model of resnet18.
for param in model.parameters():
param.requires_grad = False
# Replace the last fully-connected layer
# Parameters of newly constructed modules have requires_grad=True by default
model.fc = torch.nn.Linear(512, 3)
optimizer = torch.optim.SGD(model.fc.parameters(), args.lr,
momentum=args.momentum,
weight_decay=args.weight_decay)
But then I have following error:
File "main.py", line 234, in train
loss.backward()
File "/usr/local/lib/python2.7/dist-packages/torch/autograd/variable.py", line 146, in backward
self._execution_engine.run_backward((self,), (gradient,), retain_variables)
RuntimeError: there are no graph nodes that require computing gradients
I would like to freeze all parameters of original ResNet18 and just learn the last layer with 3 classes. How I should do this correctly? Based on information from the forum, this should we the working version.
|
st99655
|
What I want to do is gathering elements from 10x20 tensor x according to the class label tensor y whose shape is (10,).
I couldn’t understand this error because I didn’t specify index 19 in dim 0.
Could anyone help me?
❯ ipython
Python 3.6.5 |Anaconda custom (64-bit)| (default, Apr 29 2018, 16:14:56)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import torch
In [2]: x = torch.empty(10, 20).uniform_().float(); y = torch.randint(0, 20, (10,)).long()
In [3]: indices = torch.stack((torch.arange(x.size(0)), y), 1)
In [4]: x[indices]
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-4-a9c39fcc26e5> in <module>()
----> 1 x[indices]
RuntimeError: index 19 is out of bounds for dimension 0 with size 10
In [5]: indices
Out[5]:
tensor([[ 0, 18],
[ 1, 10],
[ 2, 4],
[ 3, 13],
[ 4, 7],
[ 5, 5],
[ 6, 0],
[ 7, 8],
[ 8, 19],
[ 9, 8]])
In [6]: torch.__version__
Out[6]: '1.0.0.dev20180921'
In [8]: x[9, 19]
Out[8]: tensor(0.8050) <- of course, this worked.
|
st99656
|
Hi,
You don’t actually need to create 2D indices, you can use gather for that:
import torch
x = torch.empty(10, 20).uniform_().float(); y = torch.randint(0, 20, (10,)).long()
print(x)
print(y)
out = x.gather(1, y.unsqueeze(-1))
print(out)
|
st99657
|
Oh, appreciate this so much!
I love this simple, readable way!!!
Do you have any idea why my method failed?
|
st99658
|
You should not give it as a 2D tensor, but as two 1D tensors: out = x[torch.arange(x.size(0)), y].
|
st99659
|
I am trying to implement an iterative fast gradient sign adversarial attack on a model. When I run the code for the same model, I get different accuracies for the same image. On further inspection, I found that many times for the same input the gradient differs. Is there any reason for this to happen?
runningAdv = torch.clamp( runningAdv + ((inputcopy.grad > deterministicEps).type(torch.FloatTensor) * self.perIterStep - \
(inputcopy.grad < -deterministicEps).type(torch.FloatTensor) * self.perIterStep).to(self.opts.gpuid) , -1 * self.epsilon, self.epsilon)
Initially I set deterministicEps to 0 and when this caused difference I though it may be due to precision errors as the gradients were of very small magnitude (1e-13) but even on setting deterministicEps as high as 1e-8, the output is variable.
The model is in model.eval() mode and the I generate the gradients as follows:
inp = inp.float().to(self.gpuid)
target = target.float().to(self.gpuid)
runningAdv = torch.zeros_like(inp).to(self.gpuid)
for i in range(self.niter):
inputcopy = torch.clamp(inp + runningAdv, 0, 1)
inputcopy.requires_grad = True
out = self.model(inputcopy)
loss = self.loss(out, target)
loss.backward()
runningAdv = torch.clamp( runningAdv + ((inputcopy.grad > deterministicEps).type(torch.FloatTensor) * self.perIterStep - \
(inputcopy.grad < -deterministicEps).type(torch.FloatTensor) * self.perIterStep).to(self.opts.gpuid) , -1 * self.epsilon, self.epsilon)
Why should there be changes in the gradient for the same image (even if the magnitude of the gradient is very small, shouldn’t its value remain consistent when I use the same input and model)
|
st99660
|
Hi,
Are you using Float or Double tensors? Keep in mind that below 1e-7, a single float will not be precise and such values should not be considered correct.
Some operations (especially on GPU) are non-deterministic and so can give different results where the difference is of the order of floating point precision: 1e-7 1e-8.
If you use cudnn, you can set cudnn.deterministic = True to get deterministic results.
|
st99661
|
Thanks, could you tell more about cudnn deterministic mode (or point to some source). I want to use it for benchmarking and want to know how precise the output will be.
|
st99662
|
On converting the model and the input to double format, the execution time increases around 6-10 times. Is there any way to avoid this without losing such a loss in performance?
|
st99663
|
@sahil_shah Unfortunately that depends on your hardware, you can see here 26 for a more complete answer.
@Naman-ntc Getting deterministic results is tricky, there are many posts on this forum discussing that.
cudnn internaly can use many algorithms, some are deterministic (run twice on the same hardware will give you the same results), some not (run twice on the same hardware can give you different results). You can set the torch.backends.cudnn.determinic flag to True or False to only use deterministic algorithms or all of them.
The output precision will be as all other algorithms up to the input type precision.
|
st99664
|
I am working on adversarial attacks with pytorch.
I was initially using floatTensors but my backpropogation was not consistent.
After searching I found https://github.com/pytorch/pytorch/issues/5351 15 . Due to iteratively using thr wrong values my answers differ significantly across experiments.
Then after I moved to DoubleTensors my answers seem to be very consistent but it has become about 3-4 times slower. This is somewhat expected but is there any workaround into this as 3/4 is a really huge factor!
EDIT Followup:
Since autograd differs in pytorch vs luatorch, does torch autograd pass gradcheck in luatorch pass with float operands??
|
st99665
|
Solved by albanD in post #2
Hi,
This problem is not linked to pytorch itself.
Doing numerical differentiation with finite difference (what gradcheck does) can be quite far from the truth depending on the function, which point you differentiate and the value of epsilon you use.
The autograd in any framework you will use do t…
|
st99666
|
Hi,
This problem is not linked to pytorch itself.
Doing numerical differentiation with finite difference (what gradcheck does) can be quite far from the truth depending on the function, which point you differentiate and the value of epsilon you use.
The autograd in any framework you will use do the exact same computation. There can be minor differences (floating point error) because float operations are not commutative but the answer will be almost the same.
DoubleTensor operations are much slower (especially for some GPUs), because they require diferent hardware and GPU don’t have much of it because they are not really needed most of the time.
|
st99667
|
Hi yeah I am using 1080 Ti GPU and it does have much less flops for double values.
As I said I am working on adversarial attacks and therefore even 1e-8 difference in gradient magnitudes can cause difference (as I use torch.sign and 1e-8 can cause a shift from +ve to -ve)
And over multiple such iterations this difference accumulates and is quite large!
Thanks
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.