id
stringlengths
3
8
text
stringlengths
1
115k
st102600
Surprisingly I have not found an answer to this question after looking around the internet. I am specifically interested in a 3d tensor. From doing my own experiments, I have found that when I create a tensor: h=torch.randn(5,12,5) And then put a convolutional layer on it defined as follows: conv=torch.nn.Conv1d(12,48,3,padding=1) The output is a (5,48,5) tensor. So, am I correct in assuming that for a 3d tensor in pytorch the middle number represents the number of channels? Edit: It seems that when running a conv2d, the input dimension is the first entry in the tensor, and I need to make it a 4d tensor (1,48,5,5) for example. Now I am very confused… Any help is much appreciated! (I also posteed this question on SO, but no one has answered and it’s sort of urgent
st102601
Solved by justusschock in post #2 The first number represents the Batchsize (N) and for tensors holding data of a dimension of 1 or above the next dimension is usually referred to as channel-dimension. The following dimensions are commonly height, width and depth. So for 2d data (images) you have a 4d tensor of NxCxHxW which you fe…
st102602
The first number represents the Batchsize (N) and for tensors holding data of a dimension of 1 or above the next dimension is usually referred to as channel-dimension. The following dimensions are commonly height, width and depth. So for 2d data (images) you have a 4d tensor of NxCxHxW which you feed into a 2d conv layer. Note that channels only exist for convolutional layers. Linear layers for example need a shape of N x #num_features
st102603
Thank you for your reply. What about if I want to apply a one dimensional convolution on a 2d image? Should I then say instead of just a 1d kernel of size 3, I should define it as a 2d kernel of size (3,1)?
st102604
You can choose between reshaping your tensor to NxCx(H*W), applying a 1d convolution and reshaping the result or use the (1,3) kernel in 2d convolution. Mathematically these approaches should be equivalent, but I would recommend the way using the 2d conv since you don’t have to pay attention on the memory order while reshaping. Edit: just noticed they are not completely equal. If you reshape the image you have informations of the previous and the next row on your current rows border. This is not the case for the 2d convolutional approach.
st102605
In order to do that with desired dimensions, I need to find a way to apply padding only to the left and right side of the image (not the top and bottom). Is there a way to do this easily in pytorch?
st102606
Sure pytorchs conv layer has a padding argument which expects a padding size.if passing an integer the padding will be applied on each side, but you could also pass a tuple containing a separate padding size per side.
st102607
I have a (dense) Tensor X of shape (A, B, C) that I need to (tensor-)multiply with a sparse 1 tensor Y of shape (C,C) along the last axis of the X and first axis of Y independently of the first two axes of X to create a new Tensor of shape (A, B, C). How do I appropriately broadcast Y? I definitely need to avoid looping over the first two axes of X.
st102608
Hi to everyone, I am currently working on a FeedForward network on the MNIST database. It has 784 inputs, two hidden layers of 100 nodes each, and an 10-node output layer. I use PyTorch’s Adam optimizer and CrossEntropyLoss loss function. I started from this official PyTorch example 8 and modified my way through. Regarding the train/test steps, the actual implementation shouldn’t be too much different from that one. My problem is the following: The training loss has sharp jumps at each epochs, as if the Adam optimizer resets in some way (i think). Below a plot of what happens: bokeh_plot(4).png750×330 35.3 KB I am not uploading any of my code yet, as my implementation is quite complex and I am working with some “unusual” constraints (hopefully not relevant to the problem at hand). However, if someone is interested, I will work toward a minimal working example. Any help will be certainly appreciated! Thanks, Davide
st102609
Are you storing and loading the model or optimizer in some way. There were some threads on this topic in the past few weeks and so far most of the time we’ve found some code bugs in the training procedure. I’m really interested in a working example.
st102610
ptrblck: Are you storing and loading the model or optimizer in some way. Yes, I am storing the model, the optimizer, and all the other parameters as well in an ad hoc class. class NNet: def __init__(self, name): self.name = name . . . ## other conf variables self.model = None self.criterion = None self.optimizer = None self.scheduler = None # data # i use these lists to store the training/validation avg. loss and accuracy self.train = [] self.valid = [] self.test = [] # define training step with class method def train_step(self, train_loader, epoch): self.model.train() if self.scheduler is not None: self.scheduler.step() for batch_idx, (data, label) in enumerate(train_loader): inputV = Variable(data) target = Variable(label) output = self.model( inputV ) loss = self.criterion(output, target) self.optimizer.zero_grad() loss.backward() self.optimizer.step() # define validation/test step with class method def test_step(self, test_loader): self.model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, label in test_loader: inputV = Variable(data) target = Variable(label) output = self.model( inputV ) test_loss += self.criterion(output, target, size_average=False).item() # sum up batch loss pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability correct += pred.eq(target.view_as(pred)).sum().item() test_loss /= len(test_loader.dataset) correct /= len(test_loader.dataset) The class is initialized with some empty variables (model, criterion, etc), but then I create the model and save it in the class: def generate_entry(name): entry = NNet(name) entry.model = _user_defined_model_(**entry.model_args) entry.criterion = torch.nn.functional.cross_entropy ... edit: found how to properly embed code
st102611
ptrblck: I’m really interested in a working example. I am afraid that I won’t be able to provide one before next week.
st102612
ptrblck: Are you storing and loading the model or optimizer in some way. He probably meant, whether you save the model/optimizer to a file (for later usage) and load it afterwards?
st102613
Since a.data = b.detach() is not recommended( is it right?), and a.fill_(v) can only cope with 0-dim value, so what’s the recommended value to update one tensor value? My typical case is to write gradients into tensor.grad after using autograd.grad().
st102614
Solved by albanD in post #2 Hi, If you want to change the value of a tensor that requires gradients without it being tracked by the autograd engine, you should do: with torch.no_grad(): a.copy_(b) As is done for weight initialization for example in the nn.init package. If thinks don’t require gradients and have no grad…
st102615
Hi, If you want to change the value of a tensor that requires gradients without it being tracked by the autograd engine, you should do: with torch.no_grad(): a.copy_(b) As is done for weight initialization 41 for example in the nn.init package. If thinks don’t require gradients and have no grad_fn associated with it, you can simply do: a.copy_(b)
st102616
is it possible to apply 1.5 factor scale using ConvTranspose2d it doesn’t work with me for the two dimensions
st102617
do you think that there is any other way to use Deconv to upsample 1.5 and not any interpolation methods.
st102618
Hello, I am quite new to PyTorch and deep learning in general. I am trying to identify a simple problem. I have written a basic image classifier running on the MNIST dataset. Everything works fine up to this point. However, I am trying to use a modified parameter set for the optimizer. It should be a totally custom parameter space and the optimizer should take steps in that parameter space. I am not able to perform this operation since I am only providing the optimizer with a Tensor but not an iterable. My question is that how can I convert a torch.Tensor into an iterable of torch.Tensor. Thanks!
st102619
Eg: say my internal structure is this Sequential( (Conv2D_4): Conv2d(1, 16, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)) (ReLU_4): ReLU() (Conv2D_5): Conv2d(16, 32, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)) (ReLU_5): ReLU() ) and I want to add (Conv2D_3): Conv2d(1, 1, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)) to the very first spot instead of the default last spot like so… Sequential( (Conv2D_3): Conv2d(1, 1, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)) (Conv2D_4): Conv2d(1, 16, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)) (ReLU_4): ReLU() (Conv2D_5): Conv2d(16, 32, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)) (ReLU_5): ReLU() ) How can I achieve this? Should I instead make a new empty sequential, add the layer first then copy over the previous 2 Conv2Ds and 2 ReLUs?
st102620
Solved by John_Smith in post #2 model = nn.Sequential( nn.Conv2d(1, 16, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)), nn.ReLU(), nn.Conv2d(16, 32, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)), nn.ReLU() ) nn.Sequential( nn.Conv2d(1, 1, kernel_size=(4, 4), stride=(2, …
st102621
model = nn.Sequential( nn.Conv2d(1, 16, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)), nn.ReLU(), nn.Conv2d(16, 32, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)), nn.ReLU() ) nn.Sequential( nn.Conv2d(1, 1, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)), *list(model.modules())[1:] ) Sequential( (0): Conv2d(1, 1, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)) (1): Conv2d(1, 16, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)) (2): ReLU() (3): Conv2d(16, 32, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1)) (4): ReLU() )
st102622
I have a dataset with 100 images which occupy around 120 MB and their masks occupy around 4.2 MB. I have written a dataloader. When I try to plot some examples using the following code, the process is killed because of running out of memory. import torchvision import matplotlib.pyplot as plt from augmentations import * path = '/path_to_data_set' batch_size = 1 augs = Compose([RandomRotate(10), RandomHorizontallyFlip()]) root = SegDataset(root=path, split='train', is_transform=True, augmentations = augs) trainloader = data.DataLoader(root, batch_size=batch_size, num_workers=0) for i, data in enumerate(trainloader): print(i) imgs, masks = data imgs = imgs.numpy()[:, ::-1, :, :] imgs = np.transpose(imgs, (0,2,3,1)) f, axarr = plt.subplots(batch_size,2) for j in range(batch_size): axarr[j][0].imshow(imgs[j]) axarr[j][1].imshow(dst.decode_segmap(labels.numpy()[j])) plt.show() a = input() if a =='ex': break else: plt.close() I have tried num_workers=0 and other numbers , still same behaviour.
st102623
Solved by ptrblck in post #13 Thanks for the info. I’ll try to debug your code. In the meanwhile could you remove the recursion in __getitem__: return self.__getitem__(np.random.randint(0, self.__len__())) and just return random data instead: return torch.randn(YOUR_SIZE), torch.randn(YOUR_SIZE)
st102624
Can you show your dataset code and a traceback? Does the error occur directly if you execute the script or only after a certain time?
st102625
The error occurs after a certain amount of time, the RAM slowly increases. I get process killed by signal error. This is the dataset code class SegDataset(data.Dataset): def __init__(self, root, split="train", is_transform = False, augmentations=None): self.root=root self.split = split self.augmentations = augmentations self.is_transform = is_transform self.n_classes = 3 self.files = collections.defaultdict(list) self.images_base = os.path.join(self.root, self.split) self.masks_base = os.path.join(self.root, 'masks' + '/' + self.split) for split in ['train', 'val', 'test']: file_list = recursive_glob(rootdir=self.root + '/' + split , suffix='.jpg') self.files[split] = file_list def __len__(self): return len(self.files[self.split]) def __getitem__(self, index): img_path = self.files[self.split][index].rstrip() img_name = img_path.split(os.sep)[-1].split('.')[0] mask_name = img_name + '_mask.png' mask_path = self.masks_base + '/' + mask_name img = m.imread(img_path) img = np.array(img, dtype=np.uint8) mask = m.imread(mask_path) mask = np.array(mask, dtype=np.uint8) img, window, scale, padding, crop = self.resize_image(img, min_dim=image_size[0], max_dim=image_size[1]) mask = self.resize_mask(mask, padding=padding, crop=crop) if self.augmentations is not None: img, mask = self.augmentations(img, mask) if self.is_transform: img, mask = self.transform(img, mask) return img, mask
st102626
I have removed resize_image and resize_mask lines and ran the code and still I’m getting Killed as output after the RAM slowly filled completely. Any help would be much appreciated.
st102627
I have tested the code removing all the augmentations and transforms. I have tried different image reading methods from scipy, skimage, PIL, cv2. Still the dataloader is hogging RAM and causing it to crash due to running out of memory. Can some one assist me.
st102628
I think the problem is inside __getitem__ method. Remaining parts are working as they should. This is the code after removing augmentations and transformations. class SegDataset(data.Dataset): def __init__(self, root, split="train"): self.root=root self.split = split self.n_classes = 3 self.files = collections.defaultdict(list) self.images_base = os.path.join(self.root, self.split) self.masks_base = os.path.join(self.root, 'masks' + '/' + self.split) for split in ['train', 'val', 'test']: file_list = recursive_glob(rootdir=self.root + '/' + split , suffix='.jpg') self.files[split] = file_list def __len__(self): return len(self.files[self.split]) def __getitem__(self, index): img_path = self.files[self.split][index].rstrip() img_name = img_path.split(os.sep)[-1].split('.')[0] mask_name = img_name + '_mask.png' mask_path = self.masks_base + '/' + mask_name img = io.imread(img_path) mask = io.imread(mask_path) return img, mask When I try to sample one datapoint from the dataset, it still runs out of RAM. code used for sampling. path = '\path\to_dataset\ dst = FootDataset(root=path, split='train') data = dst[22] The process dies after this code snippet runs for some time. Never seen this kind of behaviour in dtaloaders.
st102629
Can you print the length of self.files (and it’s content) at the end of the __init__? Edit: or better the length of every split?
st102630
Could you change the __getitem__ to just return img_path and mask_paths? Then you could observe your RAM usage and load the images outside the Dataset: img_path, mask_path = dataset[0] img = io.imread(img_path) mask = io.imread(mask_path)
st102631
It is working for now. But if I include any image transformations in __getitem__ the RAM is running out.
st102632
It looks like you are using an own implementation for random rotation and horizontal flip. Could you post the code for these functions? Also, let’s see if one of these functions are buggy, by applying them one by one: image = RandomRotate(10)(image) # check ram image = RandomHorizontallyFlip()(image) # check ram The torchvision package provides these functions as well. You can find them here 7 and here 2.
st102633
I have removed them, this is up-to-date ram-hogging code. class SegDataset(data.Dataset): def __init__(self, root, split="train", is_transform = False): self.root=root self.split = split self.augmentations = augmentations self.is_transform = is_transform self.n_classes = 3 self.files = collections.defaultdict(list) self.images_base = os.path.join(self.root, self.split) self.masks_base = os.path.join(self.root, 'masks' + '/' + self.split) for split in ['train', 'val', 'test']: file_list = recursive_glob(rootdir=self.root + '/' + split , suffix='.jpg') self.files[split] = file_list def __len__(self): return len(self.files[self.split]) def __getitem__(self, index): img_path = self.files[self.split][index].rstrip() img_name = img_path.split(os.sep)[-1].split('.')[0] mask_name = img_name + '_mask.png' mask_path = self.masks_base + '/' + mask_name img = io.imread(img_path) mask = io.imread(mask_path) if not (len(img.shape) == 3 and len(mask.shape) == 2): return self.__getitem__(np.random.randint(0, self.__len__())) if self.is_transform: img, mask = self.transform(img, mask) return img, mask def transform(self, img, mask): img = img[:, :, ::-1] img = img.astype(np.float64) img = img.transpose(2, 0, 1) classes = np.unique(mask) mask = mask.astype(int) assert(np.all(classes == np.unique(mask))) labels = encode_mask(mask) img = torch.from_numpy(img).float() mask = torch.from_numpy(mask).long() return img, mask def get_colors(self): return np.asarray([[0, 0, 0], [125, 0, 0], [0, 125, 0]]) def encode_mask(self, mask): mask = mask.astype(int) labels = np.zeros(mask.shape[0], mask.shape[1], dtype=np.int16) for i, label in enumerate(self.get_colors()): labels[np.where(np.all(mask == label, axis=-1))[:2]] = 1 labels = labels.astype(int) return labels The transform method returns only the mask not the encoded labels and I set the is_transform to False. When I run it the process gets killed after some time. If I remove the transform then the code works as expected.
st102634
Thanks for the info. I’ll try to debug your code. In the meanwhile could you remove the recursion in __getitem__: return self.__getitem__(np.random.randint(0, self.__len__())) and just return random data instead: return torch.randn(YOUR_SIZE), torch.randn(YOUR_SIZE)
st102635
Hey guys! When I’m running my pytorch code below: class BatchRNN(nn.Module): def __init__(self, input_size, hidden_size, rnn_type=nn.LSTM, bidirectional=False, batch_norm=True, dropout = 0.1): super(BatchRNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.bidirectional = bidirectional self.batch_norm = SequenceWise(nn.BatchNorm1d(input_size)).cuda() if batch_norm else None self.rnn = rnn_type(input_size=input_size, hidden_size=hidden_size, bidirectional=bidirectional, dropout = dropout, bias=False,batch_first=True).cuda() def forward(self, x): if self.batch_norm is not None: x = self.batch_norm(x).cuda() x, _ = self.rnn(x) self.rnn.cuda().flatten_parameters() return x class CTC_RNN(nn.Module): def __init__(self, rnn_input_size, rnn_hidden_size, rnn_layers=1, rnn_type=nn.LSTM, bidirectional=True, batch_norm=True, num_class=1232, drop_out = 0.1): super(CTC_RNN, self).__init__() self.rnn_input_size = rnn_input_size self.rnn_hidden_size = rnn_hidden_size self.rnn_layers = rnn_layers self.rnn_type = rnn_type self.num_class = num_class self.num_directions = 2 if bidirectional else 1 #cnn self.conv1_cnn=nn.Conv2d(1,256,(2,rnn_input_size)).cuda() self.conv2_cnn=nn.Conv2d(1,256,(2,256)).cuda() self.fc_cnn=nn.Linear(256,rnn_hidden_size).cuda() self.softmax_cnn=torch.nn.Softmax().cuda() rnns = [] rnn = BatchRNN(input_size=rnn_input_size, hidden_size=rnn_hidden_size, rnn_type=rnn_type, bidirectional=bidirectional, batch_norm=False).cuda() rnns.append(('0', rnn)) for i in range(rnn_layers-1): rnn = BatchRNN(input_size=self.num_directions*rnn_hidden_size, hidden_size=rnn_hidden_size, rnn_type=rnn_type, bidirectional=bidirectional, dropout = drop_out, batch_norm = batch_norm).cuda() rnns.append(('%d' % (i+1), rnn)) self.rnns = nn.Sequential(OrderedDict(rnns)).cuda() if batch_norm : fc = nn.Sequential(nn.BatchNorm1d(self.num_directions*rnn_hidden_size).cuda(), nn.Linear(self.num_directions*rnn_hidden_size, rnn_hidden_size, bias=False).cuda()).cuda() else: fc = nn.Linear(self.num_directions*rnn_hidden_size, rnn_hidden_size, bias=False).cuda() self.fc = SequenceWise(fc).cuda() self.inference_log_softmax = InferenceBatchLogSoftmax().cuda() self.softmax=torch.nn.Softmax().cuda() #self.inference_softmax = InferenceBatchSoftmax() #tddf fusion lstm self.tddf_lstm=nn.LSTMCell(rnn_hidden_size,rnn_hidden_size).cuda() self.fc_s=nn.Linear(rnn_hidden_size,2,bias=True).cuda() self.fc_c=nn.Linear(rnn_hidden_size,2,bias=True) .cuda() self.hx=Variable(torch.zeros(100,rnn_hidden_size),requires_grad=True).cuda() self.cx=Variable(torch.zeros(100,rnn_hidden_size),requires_grad=True).cuda() self.fc_tddf=nn.Linear(rnn_hidden_size,num_class).cuda() def forward(self, x,y): #x: packed padded sequence [x.data: the origin data] [x.batch_sizes: the batch_size of each frames] [x_len: type:list not torch.IntTensor] #ipdb.set_trace() x = self.rnns(x) x = self.fc(x) x = self.inference_log_softmax(x)#(max_step,batch_size,dim) x=x.transpose(0,1) #x = self.inference_softmax(x) y=self.conv1_cnn(y) #banben 2_relu y=F.relu(y) y=self.conv2_cnn(torch.transpose(y,1,3)) y=F.relu(y) y=self.fc_cnn(torch.transpose(y,1,3))#(batch_size,1,max_step,dim) #y=torch.transpose(y,1,3) y=y.view(100,-1,self.rnn_hidden_size) y=torch.transpose(y,0,1) output=Variable(torch.zeros(x.cpu().data.numpy().shape[0],100,self.rnn_hidden_size)).cuda() for i in range(x.cpu().data.numpy().shape[0]): #ipdb.set_trace() if i==0: st=F.softmax(self.fc_s(self.hx)) ct=F.sigmoid(self.fc_c(self.hx)) at=st*ct tddf_input_i_x=x[i]*at[:,0].contiguous().view(100,1).expand(100,self.rnn_hidden_size) tddf_input_i_y=y[i]*at[:,1].contiguous().view(100,1).expand(100,self.rnn_hidden_size) tddf_input_i=tddf_input_i_x+tddf_input_i_y hx,cx=self.tddf_lstm(tddf_input_i,(self.hx,self.cx)) output[i]=hx else: st=F.softmax(self.fc_s(hx)) ct=F.sigmoid(self.fc_c(hx)) at=st*ct tddf_input_i_x=x[i]*at[:,0].contiguous().view(100,1).expand(100,self.rnn_hidden_size) tddf_input_i_y=y[i]*at[:,1].contiguous().view(100,1).expand(100,self.rnn_hidden_size) tddf_input_i=tddf_input_i_x+tddf_input_i_y #tddf_input_i=x[i]*at[:,0].contiguous().view(100,1).expand(100,self.rnn_hidden_size)+y[i]*at[:1].contiguous().view(100,1).expand(100,self.rnn_hidden_size) hx,cx=self.tddf_lstm(tddf_input_i,(hx,cx)) output[i]=hx return self.fc_tddf(output) I got this error shows like: Traceback (most recent call last): File "/home/xinhaoran/PycharmProjects/TDDF/PH_ctc_cnn_tddf.py", line 358, in <module> main() File "/home/xinhaoran/PycharmProjects/TDDF/PH_ctc_cnn_tddf.py", line 353, in main train() File "/home/xinhaoran/PycharmProjects/TDDF/PH_ctc_cnn_tddf.py", line 256, in train probs = model(feats,feats_cnn).cuda(async=True) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 357, in __call__ result = self.forward(*input, **kwargs) File "/home/xinhaoran/PycharmProjects/TDDF/model_tddf.py", line 167, in forward x = self.rnns(x) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 357, in __call__ result = self.forward(*input, **kwargs) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/modules/container.py", line 67, in forward input = module(input) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 357, in __call__ result = self.forward(*input, **kwargs) File "/home/xinhaoran/PycharmProjects/TDDF/model_tddf.py", line 115, in forward x, _ = self.rnn(x).cuda() File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 357, in __call__ result = self.forward(*input, **kwargs) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/modules/rnn.py", line 204, in forward output, hidden = func(input, self.all_weights, hx) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/_functions/rnn.py", line 385, in forward return func(input, *fargs, **fkwargs) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/_functions/rnn.py", line 245, in forward nexth, output = func(input, hidden, weight) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/_functions/rnn.py", line 85, in forward hy, output = inner(input, hidden[l], weight[l]) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/_functions/rnn.py", line 158, in forward hidden = inner(step_input, hidden, *weight) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/_functions/rnn.py", line 32, in LSTMCell gates = F.linear(input, w_ih, b_ih) + F.linear(hx, w_hh, b_hh) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/nn/functional.py", line 837, in linear output = input.matmul(weight.t()) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/autograd/variable.py", line 386, in matmul return torch.matmul(self, other) File "/home/xinhaoran/anaconda3/lib/python3.6/site-packages/torch/functional.py", line 174, in matmul return torch.mm(tensor1, tensor2) RuntimeError: Expected object of type Variable[torch.FloatTensor] but found type Variable[torch.cuda.FloatTensor] for argument #1 'mat2' I’d appreciate it if someone could help me out!!!~~ For the record, this seems to work on pytorch0.2.0(I’m using 0.3.0 now)
st102636
Hi, The problem is at this line: gates = F.linear(input, w_ih, b_ih) + F.linear(hx, w_hh, b_hh). In one of these operation, some tensors are on the gpu and some are not. You can use the input.is_cuda flag to check that easily.
st102637
Thanks. But I want to know should I change the data type or change the model running pattern(cpu or cuda)??
st102638
You need to make sure that the data type and device is the same for every inputs. Then whether you model should on cpu or gpu I don’t know. That is your choice. If the rest of the model is on gpu, I would say run everything on gpu.
st102639
But I added .cuda() almost anywhere I could find, but it is still the same mistake…
st102640
You don’t have to add them randomly. Print the .is_cuda flag of each tensor used in the line I showed you and that will tell you which one is not correct.
st102641
So if your code is meant to run on gpu, hx should be moved to the gpu. If you code is meant to run on the cpu, w_hh and w_ih should be moved to the cpu.
st102642
Hi all, I received the following error after transfering the net to the GPU. Things worked fine when the net is in CPU. Since the (int, int) arguments are from pytorch internally. I wonder what I need to do to fix this. Should I simply go the the line and change output.addmm_(0, 1, input, weight.t()) to output.addmm_(0., 1., input, weight.t()) Thanks a lot for your help. /home/nelson/anaconda3/envs/pytorch/lib/python3.6/site-packages/torch/nn/functions/linear.py in forward(self, input, weight, bias) 8 self.save_for_backward(input, weight, bias) 9 output = input.new(input.size(0), weight.size(0)) —> 10 output.addmm(0, 1, input, weight.t()) 11 if bias is not None: 12 # cuBLAS doesn’t support 0 strides in sger, so we can’t use expand TypeError: addmm_ received an invalid combination of arguments - got (int, int, torch.FloatTensor, torch.cuda.FloatTensor), but expected one of: (torch.FloatTensor mat1, torch.FloatTensor mat2) (torch.SparseFloatTensor mat1, torch.FloatTensor mat2) (float beta, torch.FloatTensor mat1, torch.FloatTensor mat2) (float alpha, torch.FloatTensor mat1, torch.FloatTensor mat2) (float beta, torch.SparseFloatTensor mat1, torch.FloatTensor mat2) (float alpha, torch.SparseFloatTensor mat1, torch.FloatTensor mat2) (float beta, float alpha, torch.FloatTensor mat1, torch.FloatTensor mat2) (float beta, float alpha, torch.SparseFloatTensor mat1, torch.FloatTensor mat2)
st102643
the input to your network is on the CPU, but your network is transferred to the GPU (or vice versa). Here’s the critical part of the error that helped me figure this out: got (int, int, torch.FloatTensor, torch.cuda.FloatTensor),
st102644
Hi, what about this situation? I am ture that my input data is on GPU. TypeError: addmm_ received an invalid combination of arguments - got (int, int, torch.cuda.LongTensor, torch.cuda.FloatTensor), but expected one of: Thanks in advance.
st102645
@Ke_Bai You might want to read this post https://discuss.pytorch.org/t/problems-with-weight-array-of-floattensor-type-in-loss-function/381. I too had the issue where both the network and inputs were on GPU, causing the error. But the input type was DoubleTensor, however it should have been FloatTensor instead.
st102646
Sir, I’d like to ask for your help. I adopt a simple feed-forward net to classify feature maps. Following is the code: class FmDataLoad(Dataset): def init(self, npy_file, root_dir): self.npy_data = np.load(npy_file) self.root_dir = root_dir def __len__(self): return self.npy_data.shape[0] def __getitem__(self, index): fm_data = np.array(self.npy_data[:, :-1], dtype = np.float) label_data = np.array(self.npy_data[:, -1], dtype = np.float) return fm_data, label_data train_data = FmDataLoad(npy_file = ‘models/train_data_conv22.npy’, root_dir = ‘models/’) test_data = FmDataLoad(npy_file = ‘models/test_data_conv22.npy’, root_dir = ‘models/’) class Net(nn.Module): def init(self, input_size, hidden_size, num_classes): super(Net, self).init() self.fc1 = nn.Linear(input_size, hidden_size) self.relu = nn.ReLU() self.fc2 = nn.Linear(hidden_size, num_classes) def forward(self, x): out = self.fc1(x) out = self.relu(out) out = self.fc2(out) return out net = Net(input_size, hidden_size, num_classes) net.cuda() criterion = nn.MSELoss() optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate) for epoch in range(num_epochs): for i in range(len(train_data)): for fm_data, label_data in train_data: fm_data = torch.from_numpy(fm_data).float().cuda() fm_data = Variable(fm_data) label_data = torch.from_numpy(label_data).float().cuda() label_data = Variable(label_data) optimizer.zero_grad() # zero the gradient buffer outputs = net(fm_data) loss = criterion(outputs, label_data) loss.backward() optimizer.step() if (i + 1) % 100 == 0: print ('Epoch [%d/%d], Step [%d/%d], Loss: %.4f' %(epoch+1, num_epochs, i+1, len(train_data)//batch_size, loss.data[0])) The error is: Traceback (most recent call last): File “feed_forward.py”, line 64, in loss = criterion(outputs, label_data) File “/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py”, line 224, in call result = self.forward(*input, **kwargs) File “/usr/local/lib/python2.7/dist-packages/torch/nn/modules/loss.py”, line 272, in forward return F.mse_loss(input, target, size_average=self.size_average) File “/usr/local/lib/python2.7/dist-packages/torch/nn/functional.py”, line 819, in mse_loss return _functions.thnn.MSELoss.apply(input, target, size_average) File “/usr/local/lib/python2.7/dist-packages/torch/nn/_functions/thnn/auto.py”, line 47, in forward output, *ctx.additional_args) RuntimeError: input and target have different number of elements: input[6060 x 3] has 18180 elements, while target[6060] has 6060 elements at /pytorch/torch/lib/THCUNN/generic/MSECriterion.cu:12 could you give me an advice to solve this problem? Thank you very much!
st102647
Dami_Mi: MSELoss For MSELoss, the output and target (label_data in your case) must be of same shape. You are likely looking for CrossEntropyLoss. By the way, your question has nothing to do with the original post. So you should post a new thread instead replying in here. Further more, the error message is quite clear in your case, you might be able to solve such issues faster if you think about the message and consult the doc in future…
st102648
Thank you for your advice. I have tried to used CroosEntropy, but the error is: TypeError: CudaClassNLLCriterion_updateOutput received an invalid combination of arguments - got (int, torch.cuda.FloatTensor, torch.cuda.FloatTensor, torch.cuda.FloatTensor, bool, NoneType, torch.cuda.FloatTensor, int), but expected (int state, torch.cuda.FloatTensor input, torch.cuda.LongTensor target, torch.cuda.FloatTensor output, bool sizeAverage, [torch.cuda.FloatTensor weights or None], torch.cuda.FloatTensor total_weight, int ignore_index) I cannot find the answer according to the former related post, so I put the question here. Thank you again.
st102649
Dear all: I know the typical scenio optimizer.zero_grad() loss.backward() optimizer.step() BUT, when my gradients is obtained by grads = autograd.grad(loss, vars_list), in that case, how to apply gradients update using Adam?? grads = autograd.grad(loss, vars_list) for p, g in zip(vars_list, grads): p.grad.fill_(g) optimizer.step() Is this right?
st102650
Hi everyone. Whenever I instantiate a Variable() and call cuda() on it I seem to be unable to create an optimizer that optimizes over it: x = Variable(torch.FloatTensor(some_np_array), requires_grad=True) x = x.cuda() optimizer = optim.SGD([x], lr=1e-2) throws the exception ValueError: can't optimize a non-leaf Variable whereas not calling .cuda() works fine. What is the correct way to optimize over variables that can be processed on the GPU?
st102651
Hi, The problem is that when you do x = x.cuda(), the new x is not the same as the old one. If you do x_cuda = x.cuda(), then you can give x to the optimizer. It is even better to send it to cuda before creating the Variable: x = Variable(torch.FloatTensor(some_np_array).cuda(), requires_grad=True)
st102652
Hi, I met the same problem. Thanks for your tips. I wonder what’s the difference between x and x_cuda? Indeed, when our computing is processed in GPU, why dont we optimize x_cuda since it makes more sense? Thanks.
st102653
That is what the last proposition above says: send the tensor on the GPU before making a Variable so that you can optimize this one directly.
st102654
@albanD I dnt understand why should give optimizer the x_cpu Instead of x_cuda?? Our computation is conducted on x_cuda, why not pass x_cuda to optimizer?
st102655
Hi, It all depends how you create them. Check this 280 post for a detailed answer.
st102656
I installed pytorch 0.4 on the official website using the following code: pip install http://download.pytorch.org/whl/cu80/torch-0.4.0-cp35-cp35m-win_amd64.whl 22 pip install torchvision It seems everything is normal,but I found the usage of GPU is low and CPU is high! I want to use GPU,is this normal? TIM截图20180726152303.png1260×843 30.4 KB
st102657
The GPU usage depends on your workload. Try to increase the calculations and check the usage again, e.g. by creating a large CNN.
st102658
here is the number of parameters that I want to change # input_size = 1 input_size = 2 # 3, 4, 5,... output_size = 1 num_epochs = 60 learning_rate = 0.001 This is training set x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168], [9.779], [6.182], [7.59], [2.167], [7.042], [10.791], [5.313], [7.997], [3.1]], dtype=np.float32) y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573], [3.366], [2.596], [2.53], [1.221], [2.827], [3.465], [1.65], [2.904], [1.3]], dtype=np.float32) This is a training model of linear for epoch in range(num_epochs): # Convert numpy arrays to torch tensors inputs = torch.from_numpy(x_train) targets = torch.from_numpy(y_train) # Forward pass outputs = model(inputs) loss = criterion(outputs, targets) # Backward and optimize optimizer.zero_grad() loss.backward() optimizer.step() if (epoch+1) % 5 == 0: print ('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item())) This is the error I got: RuntimeError Traceback (most recent call last) in () 6 7 # Forward pass ----> 8 outputs = model(inputs) 9 loss = criterion(outputs, targets) 10 /usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in call(self, *input, **kwargs) 489 result = self._slow_forward(*input, **kwargs) 490 else: –> 491 result = self.forward(*input, **kwargs) 492 for hook in self._forward_hooks.values(): 493 hook_result = hook(self, input, result) /usr/local/lib/python3.6/dist-packages/torch/nn/modules/linear.py in forward(self, input) 53 54 def forward(self, input): —> 55 return F.linear(input, self.weight, self.bias) 56 57 def extra_repr(self): /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias) 990 if input.dim() == 2 and bias is not None: 991 # fused op is marginally faster –> 992 return torch.addmm(bias, input, weight.t()) 993 994 output = input.matmul(weight.t()) RuntimeError: size mismatch, m1: [15 x 1], m2: [2 x 1] at /pytorch/aten/src/TH/generic/THTensorMath.c:2033 This error is generalized when I increased the number of inputs. What I want to do here is to make a general case to adapt module linear without any errors or how change make training set without error?
st102659
As far as I understand your question, you would like to create your model based on different input data. You could get the number of features from your input and create the model afterwards: in_features = x_train.shape[1] model = nn.Sequential( nn.Linear(in_features, 2) ) x = torch.from_numpy(x_train) output = model(x)
st102660
Im wondering if there’s any thing wrong while im calculating the “Validation Loss” It seems to be a lit bit weird Hello2.JPG992×375 37 KB Hello.JPG1034×321 37.6 KB
st102661
Just from looking at the loss graphs you posted, it looks like your model is overfitting. What are the hyperparameters of your model ?
st102662
@krishnavishalv I’m training on the Res101 Structure with lr=0.0001. Overfitting also popped out from my mind when seeing this kinda curve but I don’t feel like it’ll overfit that fast. That’s why I’m wondering if i’m implementing the validation loss in the wrong way
st102663
I am trying to measure CPU usage on MNIST example on PyTorch 0.4.0 by following commands, but it failed. How to avoid this issue? $ python -m torch.utils.bottleneck main.py --no-cuda === Traceback (most recent call last): File “/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/main.py”, line 149, in run_prof exec(code, globs, None) File “main.py”, line 110, in main() File “main.py”, line 105, in main train(args, model, device, train_loader, optimizer, epoch) File “main.py”, line 29, in train for batch_idx, (data, target) in enumerate(train_loader): File “/opt/conda/lib/python3.6/site-packages/torch/utils/data/dataloader.py”, line 264, in next batch = self.collate_fn([self.dataset[i] for i in indices]) File “/opt/conda/lib/python3.6/site-packages/torch/utils/data/dataloader.py”, line 264, in batch = self.collate_fn([self.dataset[i] for i in indices]) File “/opt/conda/lib/python3.6/site-packages/torchvision/datasets/mnist.py”, line 77, in getitem img = self.transform(img) File “/opt/conda/lib/python3.6/site-packages/torchvision/transforms/transforms.py”, line 49, in call img = t(img) File “/opt/conda/lib/python3.6/site-packages/torchvision/transforms/transforms.py”, line 143, in call return F.normalize(tensor, self.mean, self.std) File “/opt/conda/lib/python3.6/site-packages/torchvision/transforms/functional.py”, line 167, in normalize for t, m, s in zip(tensor, mean, std): File “/opt/conda/lib/python3.6/site-packages/torch/tensor.py”, line 361, in return iter(imap(lambda i: self[i], range(self.size(0)))) RuntimeError: /pytorch/torch/csrc/autograd/profiler.h:53: out of memory During handling of the above exception, another exception occurred: Traceback (most recent call last): File “/opt/conda/lib/python3.6/runpy.py”, line 193, in _run_module_as_main “main”, mod_spec) File “/opt/conda/lib/python3.6/runpy.py”, line 85, in _run_code exec(code, run_globals) File “/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/main.py”, line 280, in main() File “/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/main.py”, line 261, in main autograd_prof_cpu, autograd_prof_cuda = run_autograd_prof(code, globs) File “/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/main.py”, line 155, in run_autograd_prof result.append(run_prof(use_cuda=True)) File “/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/main.py”, line 149, in run_prof exec(code, globs, None) File “/opt/conda/lib/python3.6/site-packages/torch/autograd/profiler.py”, line 191, in exit records = torch.autograd._disable_profiler() RuntimeError: /pytorch/torch/csrc/autograd/profiler.h:53: out of memory References mnist example https://github.com/pytorch/examples/blob/master/mnist/main.py 3 bottleneck https://pytorch.org/docs/stable/bottleneck.html 2
st102664
Thank you for commenting. In this case, the GPU check works fine. But it failed in the MNIST learning step.
st102665
It seems your GPU is still out of memory. Could you check its memory usage with nvidia-smi?
st102666
I check nvidia-smi output during MNIST training but up to 25% (not fully allocated). And I found following things, 1)MNIST learning with 2epochs works fine under bottleneck profiler. 2)MNIST learning with 3epochs does outputs following error under bottleneck profiler. (I execute it two times, the trace of out of memory is same.) Traceback (most recent call last): File "/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/__main__.py", line 149, in run_prof exec(code, globs, None) File "main.py", line 109, in <module> main() File "main.py", line 104, in main train(args, model, device, train_loader, optimizer, epoch) File "main.py", line 29, in train for batch_idx, (data, target) in enumerate(train_loader): File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 264, in __next__ batch = self.collate_fn([self.dataset[i] for i in indices]) File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 264, in <listcomp> batch = self.collate_fn([self.dataset[i] for i in indices]) File "/opt/conda/lib/python3.6/site-packages/torchvision/datasets/mnist.py", line 77, in __getitem__ img = self.transform(img) File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 49, in __call__ img = t(img) File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 143, in __call__ return F.normalize(tensor, self.mean, self.std) File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/functional.py", line 167, in normalize for t, m, s in zip(tensor, mean, std): File "/opt/conda/lib/python3.6/site-packages/torch/tensor.py", line 361, in <lambda> return iter(imap(lambda i: self[i], range(self.size(0)))) RuntimeError: /pytorch/torch/csrc/autograd/profiler.h:53: out of memory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/conda/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/opt/conda/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/__main__.py", line 280, in <module> main() File "/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/__main__.py", line 261, in main autograd_prof_cpu, autograd_prof_cuda = run_autograd_prof(code, globs) File "/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/__main__.py", line 155, in run_autograd_prof result.append(run_prof(use_cuda=True)) File "/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/__main__.py", line 149, in run_prof exec(code, globs, None) File "/opt/conda/lib/python3.6/site-packages/torch/autograd/profiler.py", line 191, in __exit__ records = torch.autograd._disable_profiler() RuntimeError: /pytorch/torch/csrc/autograd/profiler.h:53: out of memory
st102667
I watch RSS in top.(not nvidia-smi) RSS value is increased to full, then previous call trace appeared. Also, I found “main.py --no-cuda” execute many times(like 3 times) under bottleneck profiler. Is there any good solution to solve this? $ time python -m torch.utils.bottleneck main.py --no-cuda RSS value is increased top - 09:42:05 up 1 day, 9:58, 0 users, load average: 1.42, 2.43, 2.34 Tasks: 15 total, 2 running, 13 sleeping, 0 stopped, 0 zombie %Cpu(s): 25.8 us, 4.6 sy, 0.7 ni, 68.8 id, 0.0 wa, 0.0 hi, 0.1 si, 0.0 st KiB Mem : 16025224 total, 2487640 free, 11505224 used, 2032360 buff/cache KiB Swap: 16379900 total, 6105128 free, 10274772 used. 3980392 avail Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 2319 jovyan 20 0 23.346g 9.652g 318348 R 100.3 63.2 16:09.42 python 1 root 20 0 4364 0 0 S 0.0 0.0 0:03.41 tini 7 root 20 0 49152 180 176 S 0.0 0.0 0:00.00 sudo 16 jovyan 20 0 2110016 25644 4456 S 0.0 0.2 0:51.18 jupyterhub-sing 24 jovyan 20 0 20120 132 128 S 0.0 0.0 0:00.35 bash 63 jovyan 20 0 20120 24 24 S 0.0 0.0 0:00.37 bash 153 jovyan 20 0 20120 136 132 S 0.0 0.0 0:00.43 bash 187 jovyan 20 0 2153728 7640 900 S 0.0 0.0 0:05.49 python 262 jovyan 20 0 20132 2388 1996 S 0.0 0.0 0:00.59 bash 539 jovyan 20 0 20120 256 252 S 0.0 0.0 0:00.43 bash 1119 jovyan 20 0 20120 284 280 S 0.0 0.0 0:00.43 bash 1286 jovyan 20 0 24332 300 296 S 0.0 0.0 0:00.00 git 1287 jovyan 20 0 8376 0 0 S 0.0 0.0 0:00.00 pager 1404 jovyan 20 0 20120 2248 1868 S 0.0 0.0 0:00.54 bash 2352 jovyan 20 0 40392 3600 3128 R 0.0 0.0 0:00.28 top
st102668
@ptrblck I have one question and one request. Would you check it? Question about Memory Usage for torch.utils.bottleneck with MNIST. Training MNIST with --epochs 3 --no-cuda works fine, but failed with --epochs 4 --no-cuda on my server with 16GB-RAM machine. It seems like RAM memory (RES) consumption problem. I guess it needs 64GB-RAM for MNIST Training sample with torch.utils.bottleneck. Is my guess correct? As for the document on torch.utils.bottleneck It is helpful to write a document for trace customization (topk etc). cp torch/utils/bottleneck/__main__.py bottleneck.py pytorch bottleneck.py /script/path/to/source/script.py [args]
st102669
Try to run the code with --epochs 1 and see the memory usage. It should fit on your machine. I don’t quite get your second point. Would you like to use topk in the output of the profiling?
st102670
@ptrblck Thank you for commenting.It is helpful. For MNIST epochs=1 with no-cuda, RES=4.8GB (max). If I want to reduce the memory usage by profile, I need to add following DONT_PROFILE and build again? Or other workaround method exist? https://github.com/pytorch/pytorch/blob/v0.4.0/tools/autograd/gen_variable_type.py#L53 Yes, This is nice to have comment. It is helpful for documenting how to customize profiler output for PyTorch users. My intention is it does not need to remake the package, just copy locally.
st102671
P.S. If I profile the MNIST learning with cProfile i.e. without autograd profile, the process memory consumption keeps around 2GB of RAM. (for epochs 10 (default value)). It seems autograd profiler’s Event memory consumption is high.
st102672
I am running my NN model using DataParallel on 3 GPUs. In one GPU, the memory usage rises to 12gb and as a result, the program stops after giving an out-of-memory error. While one GPU uses a large amount of memory (~12gb), the other two GPU memory usage is quite low (~2-3gb). Is there any way I can make sure that the GPU memory usage is balanced when DataParallel is used in PyTorch? Edit: I am working on Neural Machine Translation (NMT) and I am sharing part of my code where I am using DataParallel. class NMT(nn.Module): """A sequence-to-sequence model for machine translation.""" def __init__(self, dictionary, embedding_index, args): super(NMT, self).__init__() self.config = args self.src_embedding = EmbeddingLayer(len(dictionary[0]), False, self.config) self.tgt_embedding = EmbeddingLayer(len(dictionary[1]), True, self.config) if embedding_index is not None: if isinstance(embedding_index, tuple): self.src_embedding.init_embedding_weights(dictionary[0], embedding_index[0], self.config.emsize) self.tgt_embedding.init_embedding_weights(dictionary[1], embedding_index[1], self.config.emsize) else: self.src_embedding.init_embedding_weights(dictionary[0], embedding_index, self.config.emsize) self.encoder_decoder = Encoder_Decoder(args) if torch.cuda.device_count() > 1: self.encoder_decoder = torch.nn.DataParallel(self.encoder_decoder) # word decoding layer self.out = nn.Linear(self.config.emsize, len(dictionary[1])) # tie target embedding weights with decoder prediction layer weights self.tgt_embedding.embedding.weight = self.out.weight def forward(self, s1, s1_len, s2, s2_len): """ Forward computational step of sequence-to-sequence to machine translation. :param s1: source sentences [batch_size x max_s1_length] :param s1_len: source sentences' length [batch_size] :param s2: target sentences [batch_size x max_s2_length] :param s2_len: target sentences' length [batch_size] :return: decoding loss [batch_size] """ # embedded_s1 = batch_size x max_s1_length x em_size embedded_s1 = self.src_embedding(s1) # embedded_s2 = batch_size x max_s2_length x em_size embedded_s2 = self.tgt_embedding(s2) # decoder_out: batch_size x max_s2_length x em_size decoder_out = self.encoder_decoder(embedded_s1, s1_len, embedded_s2) predictions = f.log_softmax(self.out(decoder_out.view(-1, decoder_out.size(2))), 1) predictions = predictions.view(*decoder_out.size()[:-1], -1) decoding_loss, total_local_decoding_loss_element = 0, 0 for idx in range(s2.size(1) - 1): local_loss, num_local_loss = self.compute_decoding_loss(predictions[:, idx, :], s2[:, idx + 1], idx, s2_len) decoding_loss += local_loss total_local_decoding_loss_element += num_local_loss if total_local_decoding_loss_element > 0: decoding_loss = decoding_loss / total_local_decoding_loss_element return decoding_loss Here, I am using specifically DataParallel. if torch.cuda.device_count() > 1: self.encoder_decoder = torch.nn.DataParallel(self.encoder_decoder) A high-level overview of the model is depicted in the following figure. 4 I have particularly kept the target_embedding layer and the next_word_prediction layer outside DataParallel because the layer is associated with a large number of parameters (24M) and they are tied. Also, I am not training the source_embedding layer, the weights are frozen. Following this setting, I have observed improved runtime but with a small sized data. When I try large dataset, it gives me an out-of-memory error.
st102673
I am trying to make use of multiprocessing to move data batches to GPU in a dedicated process. This process should get values from an input queue of python values or numpy arrays, transform them into pytorch’s cuda tensor, and put the result into an output queue. The main process of training model will then get and use the ready-to-use cuda tensor from the output queue without the need of further processing. My purpose is to save the time consumed by moving tensor to GPU, which may take up to 30% total time in a project I am working on depending on model size. My experimental code is like this: import torch import torch.multiprocessing as mp import time def worker(alert, q1, q2, dev): while True: alert.wait() alert.clear() q2.put(torch.tensor(q1.get(), dtype=torch.float32, device=dev, requires_grad=False)) if __name__ == '__main__': dev = 'cuda' # 'cpu' or 'cuda' alert = mp.Event() q1 = mp.Queue() q2 = mp.Queue() p = mp.Process(target=worker, args=(alert, q1, q2, dev), daemon=True) p.start() for i in range(3): q1.put(i) alert.set() time.sleep(1) for i in range(3): print(q2.get()) But I got this error: THCudaCheck FAIL file=c:\programdata\miniconda3\conda-bld\pytorch_1524546371102\work\torch\csrc\generic\StorageSharing.cpp line=253 error=71 : operation not supported Traceback (most recent call last): File "C:\Users\airium\Anaconda3\lib\multiprocessing\queues.py", line 234, in _feed obj = _ForkingPickler.dumps(obj) File "C:\Users\airium\Anaconda3\lib\multiprocessing\reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) File "C:\Users\airium\Anaconda3\lib\site-packages\torch\multiprocessing\reductions.py", line 108, in reduce_storage metadata = storage._share_cuda_() RuntimeError: cuda runtime error (71) : operation not supported at c:\programdata\miniconda3\conda-bld\pytorch_1524546371102\work\torch\csrc\generic\StorageSharing.cpp:253 Actually if I modify dev = 'cuda' to dev = 'cpu', it works: tensor(0.) tensor(1.) tensor(2.) So I am here seeking help to tackle this problem. My environment is Win10 1803, GTX1070, CUDA 9.1, python 3.6 + pytorch 0.4.0, running in conda. I also tried in native pip environment but got the same result. I want to figure out if I just incorrectly use pytorch’s multiprocessing or actually this operation is literally “not supported” on GPU. I think this problem may be related to multiprocessing’s start method, but I am not very familiar with it and there is only spawn available on Windows. Thanks in advance.
st102674
Solved by peterjc123 in post #2 It’s actually not supported by CUDA. See details in the Windows docs. https://pytorch.org/docs/stable/notes/windows.html#cuda-ipc-operations
st102675
It’s actually not supported by CUDA. See details in the Windows docs. https://pytorch.org/docs/stable/notes/windows.html#cuda-ipc-operations 276
st102676
Hi all, I have combined 3 datasets using ConcatDataset. I was wondering if there is a way to tell from which original dataset a sample from the concatenated dataset came from (to use for weighting in the sampling process). In addition I was wondering if there is an efficient way to determine the class at each index of the dataset - do I have to iterate over the entire dataset and store the class and index? This is quite expensive in my case. Thanks!
st102677
Hello, I’m trying to use 3d tensor as input for CrossEntropyLoss. While I’m reading docs, I found it’s weird. Basically, documentation for nn.CrossEntropyLoss says K >= 2 in the case of k-dimensional loss. (https://pytorch.org/docs/master/nn.html#torch.nn.CrossEntropyLoss 12). However, F.cross_entropy_loss argues that K > 1 for input and K >= 1 for target .(https://pytorch.org/docs/master/nn.html#torch.nn.functional.cross_entropy 16) I don’t understand that why others require K >= 2 and it seems to work with K = 1 in pytorch 0.4.0. I think it needs a fix. Thank you
st102678
I have a instance of a neural network called myNet (that inherits from nn.Module). I would like to Perform a deep copy of this network (including gradient values of all parameters). To perform an initial copy of the parameter values, I performed a deepcopy as follows: myCopy = copy.deepcopy( myNet ) However, this does not copy the gradient values. Thus, I performed the following: optimizerCopy = optim.SGD( netCopy.parameters(), lr=0.1, momentum=0.0 ) optimizerCopy.zero_grad() for paramName, paramValue, in net.named_parameters(): for netCopyName, netCopyValue, in netCopy.named_parameters(): if paramName == netCopyName: netCopyValue.grad = paramValue.grad This only does a shallow copy, though, of the gradient values. How can I perform a deep copy of gradient values from myNet to myCopy?
st102679
Solved by ndwork in post #2 I have found the answer to my own question (in case others would like to know). The code can be altered as follows to get the desired behavior: optimizerCopy = optim.SGD( netCopy.parameters(), lr=0.1, momentum=0.0 ) optimizerCopy.zero_grad() for paramName, paramValue, in net.named_parameters(): …
st102680
I have found the answer to my own question (in case others would like to know). The code can be altered as follows to get the desired behavior: optimizerCopy = optim.SGD( netCopy.parameters(), lr=0.1, momentum=0.0 ) optimizerCopy.zero_grad() for paramName, paramValue, in net.named_parameters(): for netCopyName, netCopyValue, in netCopy.named_parameters(): if paramName == netCopyName: netCopyValue.grad = paramValue.grad.clone()
st102681
I am trying to measure CUDA usage on MNIST example on PyTorch 0.4.0 by following commands, but it failed. How to avoid this issue? $ python -m torch.utils.bottleneck main.py Error message is follows. === Taceback (most recent call last): File "/opt/conda/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/opt/conda/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/__main__.py", line 280, in <module> main() File "/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/__main__.py", line 261, in main autograd_prof_cpu, autograd_prof_cuda = run_autograd_prof(code, globs) File "/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/__main__.py", line 155, in run_autograd_prof result.append(run_prof(use_cuda=True)) File "/opt/conda/lib/python3.6/site-packages/torch/utils/bottleneck/__main__.py", line 149, in run_prof exec(code, globs, None) File "main.py", line 110, in <module> main() File "main.py", line 105, in main train(args, model, device, train_loader, optimizer, epoch) File "main.py", line 29, in train for batch_idx, (data, target) in enumerate(train_loader): File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 286, in __next__ return self._process_next_batch(batch) File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 307, in _process_next_batch raise batch.exc_type(batch.exc_msg) RuntimeError: Traceback (most recent call last): File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 57, in _worker_loop samples = collate_fn([dataset[i] for i in batch_indices]) File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 57, in <listcomp> samples = collate_fn([dataset[i] for i in batch_indices]) File "/opt/conda/lib/python3.6/site-packages/torchvision/datasets/mnist.py", line 68, in __getitem__ img, target = self.train_data[index], self.train_labels[index] RuntimeError: /pytorch/torch/csrc/autograd/profiler.h:52: initialization error === References mnist example https://github.com/pytorch/examples/blob/master/mnist/main.py 7 bottleneck https://pytorch.org/docs/stable/bottleneck.html 14
st102682
Could you check with 'num_workers': 0 in main.py. github.com/pytorch/pytorch Issue: [utils.bottleneck] Bottleneck crashes with multi-threaded data loader 23 opened by fmassa on 2018-04-05 torch.utils.bottleneck doesn't work properly when the code contains a data loader that uses more than 0 threads. Minimum reproducible example (mwe.py): import argparse import... bug todo
st102683
I’ve got a batch of real numbers and list of values representing bins. I want to find the closest matching bin value for each real number, and convert that real number into a one-hot vector for that bin (resulting in a batch of one-hot vectors). I want to be able to do this on the fly (i.e. not preprocess the real values into one-hot vectors before training). If this were in NumPy, I would use something like searchsorted (since the bin value vector is already sorted). Unfortunately, PyTorch doesn’t seem to have an equivalent function yet. I can use a broadcasted version of something like this answer on SO 19, but this assumes no sorting, and probably will take much longer to run than is necessary. Any thoughts on a better alternative? Thanks!
st102684
Here’s what I’ve come up with to use until a faster method is suggested: def indexes_to_one_hot(indexes, n_dims=None): """Converts a vector of indexes to a batch of one-hot vectors. """ indexes = indexes.type(torch.int64).view(-1, 1) n_dims = n_dims if n_dims is not None else int(torch.max(indexes)) + 1 one_hots = torch.zeros(indexes.size()[0], n_dims).scatter_(1, indexes, 1) one_hots = one_hots.view(*indexes.shape, -1) return one_hots def real_number_batch_to_one_hot_vector_bins(real_numbers, bins): """Converts a batch of real numbers to a batch of one hot vectors for the bins the real numbers fall in.""" _, indexes = (real_numbers.view(-1, 1) - bins.view(1, -1)).abs().min(dim=1) return indexes_to_one_hot(indexes, n_dims=bins.shape[0]) Where the bin is represented by it’s middle value.
st102685
Hey folks, Been trying to optimize some code recently. Turns out that there’s a lot of time spent on .cpu() calls (or, more specifically, .data.cpu().numpy() type calls in general), which are becoming are becoming a huge computational bottleneck for me. For instance, the per-single-image forward pass of my (RL) model takes on order ~0.002 seconds on GPU. However, when I need to return this action to do reward-dependent numpy calculations, the detaching from graph takes ~0.02 seconds. Is there any way to optimize this? I feel like I’ve tried a lot of different things, but it all ends up coming down to detaching from the graph/gpu. Thanks
st102686
detach is fast. the reason why copying to cpu is slow is two-folds: it is slow it requires a synchronization, so it appears slower. what operations do you need in numpy?
st102687
This is spot on. If you are timing your model using CPU timers (like whatever is built into Python), then your timings will not reflect GPU times accurately, since kernels are executed asynchronously on the GPU.
st102688
I have the same question as the one unanswered in a previous tread. Is it ever possible to do this: model = nn.Sequential( nn.LSTM(…), # since LSTM will return a tuple, anything here in the middle to make this whole thing work? nn.Linear(…) )
st102689
Because the LSTM gives out a tuple and the next linear needs one input. Basically, I am hoping to be able to define which output of the LSTM sequential should use.
st102690
There isn’t a layer for that in pytorch. Typically you would not use nn.Sequential but nn.Module and spell out the forward. You could also put the things (taking items from the tuple, .view or so) between LSTM and Linear in a layer, but that would feel (to me) a bit artificial in pytorch. That said, don’t believe my style advice, but use what works best for your project. Best regards Thomas
st102691
Thanks to all, so basically this is still impossible. The sequential code needs a slight modification in it’s forward to consider mutli-output modules: def forward(self, input): for module in self._modules.values(): input = module(input) if isinstance(input, tuple): input = input[0] return input I filed this issue 17 as well.
st102692
This is not a bug at all. You are able to use nn.Sequential to acheive this. My previous reply meant that you can indeed insert something in the middle to make it work. Just write a custom nn.Module.
st102693
Multiple options: custom module: class TakeFirst(nn.Module): def forward(self, x): return x[0] Activate nn.Sequential(..., LSTM) first, then feed the first result into a second nn.Sequential. As @tom said, don’t use nn.Sequential altogether. Spell out the steps in a custom module. The reason that this is not a bug is because ``nn.Squential` is just supposed to put the output as the next’s input. Automatically taking the first is something that it never promised to do. nn.Sequential is just a convenient wrapper class. If it doesn’t work the best for you, just use other more suitable approaches.
st102694
Thanks Simon, I was trying to avoid creating a new class and make the code simpler.
st102695
Cannot really see the harm though in making Sequential deal with tuples in that it just takes the first element - would make using Sequential simpler and less surprising because this is what everyone would expect it to do. The error one gets is also not very useful, the Sequential layer could at least complain properly.
st102696
I agree that the error message could be improved, but I think it is important to have a well defined, strict sequential wrapper. One can always create a custom module (be it LSTM or anything else) with the desired specifications, and add it to nn.Sequential.
st102697
Hi. I am training a CNN model using torch text and getting a strange error when trying to perform evaluation on my dev set. I have my data loaded into two CSV’s and have their location stored in pathD and test_path. def twitter_data(text_field, label_field, **kargs): train_data = data.TabularDataset( path=pathD, format='csv', fields=[('twitter_text', text_field), ('label', label_field)]) dev_data = data.TabularDataset( path=test_path, format='csv', fields=[('twitter_text', text_field), ('label', label_field)]) text_field.build_vocab(train_data, dev_data, vectors=GloVe(name='twitter.27B', dim=200)) label_field.build_vocab(train_data, dev_data) train_iter, dev_iter = data.Iterator.splits( (train_data, dev_data), batch_sizes=(args.batch_size, len(dev_data)), **kargs) return train_iter, dev_iter text_field = data.Field(lower=True) label_field = data.Field(sequential=False) train_iter, dev_iter = twitter_data(text_field, label_field, device=-1, repeat=False) This code works fine and returns an iter for both the train and dev set. When I train, I run the following code and all is dandy. optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay = args.weight_decay) scheduler = StepLR(optimizer, step_size = 5, gamma = .25) model.train() for epoch in range(1, args.epochs+1): scheduler.step() for batch in train_iter: .... Though when I try to call my eval() function, I get an error on the last line here. def eval(data_iter, model, args): model.eval() corrects, avg_loss = 0, 0 for batch in data_iter: # error occurs here The stack trace appears as follows. for batch in data_iter: File “/usr/local/lib/python3.5/dist-packages/torchtext/data/iterator.py”, line 164, in iter self.init_epoch() File “/usr/local/lib/python3.5/dist-packages/torchtext/data/iterator.py”, line 140, in init_epoch self.create_batches() File “/usr/local/lib/python3.5/dist-packages/torchtext/data/iterator.py”, line 151, in create_batches self.batches = batch(self.data(), self.batch_size, self.batch_size_fn) File “/usr/local/lib/python3.5/dist-packages/torchtext/data/iterator.py”, line 125, in data xs = sorted(self.dataset, key=self.sort_key) TypeError: unorderable types: Example() < Example() The confusing thing is the error persists even when I cheat and use the same csv file for train and dev splits, so there isn’t an issue with the dev set file.
st102698
I have the same problem as well, were you able to find a solution to the problem @ xs = sorted(self.dataset, key=self.sort_key) ?
st102699
@James I was able to fix this by switching from python3 to python2, not sure the underlying cause.