id
stringlengths
3
8
text
stringlengths
1
115k
st116268
Yes, what can be the reason to get such error in a different GPU (Tesla K-20) while it works fine in GeForce or Titan X GPU? Moreover what the error means? Is it related to memory overflow which I don’t think so.
st116269
Workaround for this:- Replace the following lines in adam.py 40:- bias_correction1 = 1 - beta1 ** state[‘step’] bias_correction2 = 1 - beta2 ** state[‘step’] WITH bias_correction1 = 1 - beta1 ** min(state[‘step’],1022) bias_correction2 = 1 - beta2 ** min(state[‘step’],1022)
st116270
It is just for numerical reasons, practically beta1 or beta2 are 0.9 (between 0 and 1). And 0.9^1000 = 1.7478713e-46, which is almost zero for all practical purposes. (You can take 1000 instead of 1022 and nothing will change).
st116271
I am assuming that Pytorch is not supported in Pypy environment. I had an existing system which was slow in CPython so we moved to Pypy. Now I need to integrate that system with some Pytorch model. Turns out the default wheel is built for CPython. Is there any way I can install the Pytorch (any version) in Pypy implementation?
st116272
Hi, I can’t speak for anyone, but it seems that far as pytorch is concerned, pypy is not supported. And the reason is that pypy is fairly closely written for the C python extension api, which is not how pypy usually supports extensions. Now, it seems that even though this has not fully arrived in the pypy documentation, pypy moved from modifying numpy to actually providing a C extension api close enough to cpython to run numpy as is in pypy. (With stuff still to do etc.) So it is apparently possible to compile c extensions for pypy, they have a compatibility wiki page 161. Now if that works for pytorch is anyones guess. If you wanted to try (and if successful the result could be truly awesome), you will probably need more pypy help than pytorch. The pytorch blog 131 features a tour of pytorch internals, that might be useful to you. Best regards and good look! Thomas
st116273
Hi everyone, Is there a way to construct modules using nn.Sequential dynamically? For example, I would like to implement a [[CONV -> RELU] * N -> POOL] * M -> [FC -> RELU] * K -> FC architecture where I can loop through different values of N, M, and K on the fly to see which architecture works best. Cheers!
st116274
yes, feel free to do this in your python code. You dont need an nn.Sequential, you can construct this as a few for-loops in your forward function of an nn.Module subclass, for example you can insert a few for-loops here: https://github.com/pytorch/examples/blob/master/mnist/main.py#L62 1.0k
st116275
Question: in this way, we are looping through the same layer, i.e. same weight, multiple times, right? And what if I want the layers to be different. Can we do that in a loop? Thanks!
st116276
Could you kindly provide a sample code for generating different layers in a loop? Thanks!
st116277
Hi I am new to pytorch and Deep Learning and I am trying to implement a name generator which will the accept first two letters of a name as an input and generate the rest of the characters the end of the name is identifed using “#” sign and i have a limit to number characters a name can have as 10, The problem is that I’m not able to create the graph properly so the model is showing 0 error and it is not backpropagation.I strongly feel that the reason behind such problem is that because of concatenation of Variable but I am not sure about. please can some help me debug the code and please lemme know if there is a easier way to do this.Thanks import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.optim as optim class next_char(nn.Module): def __init__(self,number_of_characters,input_size): super(next_char,self).__init__() self.lstm = nn.LSTM(input_size,input_size) self.number_of_characters = number_of_characters self.input_size = input_size def inithiddenlayer(self): return (Variable(torch.rand(1,1,self.input_size),requires_grad = True),Variable(torch.rand(1,1,self.input_size),requires_grad = True)) def forward(self,x): out,hidden = self.lstm(torch.cat(x).view(-1,1,self.input_size),self.inithiddenlayer()) i = -1 out,hidden = self.lstm(Variable(torch.FloatTensor(1,1,self.input_size).zero_(),requires_grad = True),hidden) op = nn.Softmax()(hidden[0][0]) flag = 0 while i == -1 or (flag == 0 and i < 10): out,hidden = self.lstm(Variable(torch.FloatTensor(1,1,self.input_size).zero_(),requires_grad = True),hidden) #print nn.Softmax()(hidden[0][0]).max(1)[1].data[0][0] if nn.Softmax()(hidden[0][0]).max(1)[1].data[0][0] == 0: flag = 1 op = torch.cat([op,nn.Softmax()(hidden[0][0])]) i = i + 1 #print op return op def make_vect(letter,corpa): vect = torch.FloatTensor(1,len(corpa)).zero_() vect[0][corpa[letter]] = 1.0 return vect ef make_corpa(data): corpa = {"#" : 0} for i in data.split(" "): for j in list(i.lower()): if j not in corpa.keys(): corpa[j] = len(corpa) return corpa def make_training_data(data,number_of_characters): corpa = make_corpa(data) all_words = data.split(" ") input_data = [] output_data = [] for i in all_words: temp1 = [] temp2 = [] i = i.lower() for j in xrange(len(i)): if j < number_of_characters or j == number_of_characters: temp1.append(Variable(make_vect(i[j].lower(),corpa),requires_grad = True)) else: output_data.append(Variable(torch.LongTensor([make_vect(i[j].lower(),corpa).max(1)[1][0][0]]))) output_data.append(Variable(torch.LongTensor([make_vect("#",corpa).max(1)[1][0][0]]))) input_data.append(temp1) return input_data,torch.cat(output_data),corpa def train_the_network(data,number_of_characters): input_data,output_data,corpa = make_training_data(data,number_of_characters) model = next_char(number_of_characters,len(corpa)) loss = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(),lr= 0.01) k = 0 for i in xrange(len(input_data)): op = model(input_data[i]) l = Variable(torch.FloatTensor(1).zero_(),requires_grad = True) j = 0 while output_data.data[k] != 0: print op[j] #print output_data[k] l = l + loss(op[j].view(1,-1),output_data[k]) k = k + 1 j = j + 1 model.zero_grad() #l.creator.previous_functions[0][0].previous_functions[0][0] returns none object HERE LIES THE PROOF THAT THE GRAPH IS NOT BEING CREATED PROPERLY. l.backward() optimizer.step() return model
st116278
I have found that there is a TemporaRowConvilution implementation in C available here: https://github.com/pytorch/pytorch/blob/master/torch/lib/THNN/generic/TemporalRowConvolution.c 23 How it is possible to use it from pytorch? Should I write cffi extension? Would appreciate any advice/direction! Thank you in advance.
st116279
It is indeed not exposed. You can access it via something like this which is an autogenerated binding: https://github.com/pytorch/pytorch/blob/master/torch/nn/functional.py#L473 29 torch.nn._functions.thnn.auto.TemporalRowConvolution.forward torch.nn._functions.thnn.auto.TemporalRowConvolution.backward torch.nn._functions.thnn.auto.TemporalRowConvolution.apply These should be available, but we haven’t exposed them as PyTorch nn modules yet.
st116280
can I have an example? self.trc = torch.nn._functions.thnn.auto.TemporalRowConvolution(rnn_input_size, 5) … x = self.trc(x) yields ValueError: missing required argument ‘weight’
st116281
Hi I am new to Pytorch. In Keras, model = Sequential() model.add(LSTM(4, input_shape=(1, look_back))) model.add(Dense(1)) model.compile(loss=‘mean_squared_error’, optimizer=‘adam’) model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2) 4 means a hidden layer with 4 LSTM blocks. How to set this parameter in Pytorch? Is it the hidden size? (“hidden_size – The number of features in the hidden state h”) Thanks.
st116282
I was wondering, how are biases initialized in pytorch for the linear layer? I inspected it out of curiosity and it seems randn(0,1) would be my guess: >>> l = torch.nn.Linear(3,2) >>> l.bias Parameter containing: 0.2137 0.0904 [torch.FloatTensor of size 2]
st116283
also how did u find out about these methods like fill_ and normal_? It doesn’t seem to me that they are super well documented (sort of mysterious how people even know how to do these things)
st116284
also is there anything wrong with doing: x = torch.FloatTensor(3,2) l.bias.data = x obviously assuming x is the initialization that we might want. Whats the difference?
st116285
http://pytorch.org/docs/master/tensors.html 433 you can check it in doc, maybe using torch.nn.init is no difference
st116286
Hey, I’m trying to do something like c = torch.div(a, b) # <=> c = a.div(b) with: type(a) = torch.autograd.variable.Variable type(b) = torch.FloatTensor Using Pytorch 0.2.0+38b42e0 this raises an AssertionError (assert not torch.is_tensor(other)) in torch/autograd/variable.py, line 353. I do understand what does it mean, and in fact, here, other (I called b) is a tensor. But I don’t see why this is forbidden. I guess I should wrap into a Variable object but tbh it does not really makes sense to me (or maybe should it be wrapped automatically instead of raising error?)
st116287
Hi, as a rule, Variables only interact with Variables, tensors with tensors. (But quite possibly it might be nice to give a message…) I think automatic wrapping is something that people think about now and then, but then it seems that it is not something is a lot of bother to most people. This is in contrast to the automatic broadcasting, which to me really improved the experience of coding things up in pytorch (between 0.2 and 0.1.12)… Best regards Thomas
st116288
hmm it makes sense. It still confuses me when I should use Variable or Tensor. I’m talking about requires_grad=False Variable specifically (otherwise ofc it needs to be a Variable).
st116289
Just wrap all tensors with Variable. It’s still a tensor but now just gives you option to use the functionality of Variable. Yeah the auto wrapping I saw in works but not implemented yet, think the holdup is over how it would make a much more high level view and cause people some ambiguity
st116290
Look at it in 1d and compute the index: Finding indices of a global maximum value in a variable Hi, one way to solve it is to flatten the tensor, take the maximum index along dimension 0 and then unravel the index, either using numpy or your own logic (probably you will come up with something less clumsy ): rawmaxidx = mytensor.view(-1).min(0)[1] idx = [] for adim in list(mytensor.size())[::-1]: idx.append(rawmaxidx%adim) rawmaxidx = rawmaxidx / adim idx = torch.cat(idx) (Note that pytorch / on LongTensor is similar to python2 / or python3 // for ints. Best rega… Best regards Thomas
st116291
I am trying to recreate a paper where the neural network takes in N matrices (each are say 4 x 500) from different sources and tries to learn joined features. Each matrix goes into a NN and gets converted into a 1 x 500 vector through convolutions etc. These vectors are then stacked to make a N x 500 matrix which undergoes more transformations to produce a final 1x 500 vector. The backprop etc must link all the sub neural networks so the final loss can backprop through to the filters learned in the sub networks. Is this possible in pytorch?
st116292
YES. This should be taken automatically via autograd if you do the forward() correctly.
st116293
Hello, l tried the following and l get stuck at visualizing the features of my model. my_model=torch.load(my_pre_trained_mode) my_model.keys() ['cnn.conv0.weight', 'cnn.conv0.bias', 'cnn.conv1.weight', 'cnn.conv1.bias', 'cnn.conv2.weight', 'cnn.conv2.bias', 'cnn.batchnorm2.weight', 'cnn.batchnorm2.bias', 'cnn.batchnorm2.running_mean', 'cnn.batchnorm2.running_var', 'cnn.conv3.weight', 'cnn.conv3.bias', 'cnn.conv4.weight', 'cnn.conv4.bias', 'cnn.batchnorm4.weight', 'cnn.batchnorm4.bias', 'cnn.batchnorm4.running_mean', 'cnn.batchnorm4.running_var', 'cnn.conv5.weight', 'cnn.conv5.bias', 'cnn.conv6.weight', 'cnn.conv6.bias', 'cnn.batchnorm6.weight', 'cnn.batchnorm6.bias', 'cnn.batchnorm6.running_mean', 'cnn.batchnorm6.running_var', 'rnn.0.rnn.weight_ih_l0', 'rnn.0.rnn.weight_hh_l0', 'rnn.0.rnn.bias_ih_l0', 'rnn.0.rnn.bias_hh_l0', 'rnn.0.rnn.weight_ih_l0_reverse', 'rnn.0.rnn.weight_hh_l0_reverse', 'rnn.0.rnn.bias_ih_l0_reverse', 'rnn.0.rnn.bias_hh_l0_reverse', 'rnn.0.embedding.weight', 'rnn.0.embedding.bias', 'rnn.1.rnn.weight_ih_l0', 'rnn.1.rnn.weight_hh_l0', 'rnn.1.rnn.bias_ih_l0', 'rnn.1.rnn.bias_hh_l0', 'rnn.1.rnn.weight_ih_l0_reverse', 'rnn.1.rnn.weight_hh_l0_reverse', 'rnn.1.rnn.bias_ih_l0_reverse', 'rnn.1.rnn.bias_hh_l0_reverse', 'rnn.1.embedding.weight', 'rnn.1.embedding.bias'] conv0=my_moel.get('cnn.conv0.weight') ... (63,0 ,.,.) = 0.5229 -1.4523 1.0662 0.1048 -1.8494 1.5810 -0.4727 -1.4437 1.9553 [torch.FloatTensor of size 64x1x3x3] rnn=my_mode.get('rnn.1.embedding.weight') [torch.FloatTensor of size 37x512] How can l visualize the weights of each layer for instance cnn.conv0 and rnn.1 ? Thank you
st116294
l have a variable preds : preds.dim() 3 [torch.cuda.FloatTensor of size 26x1x37 (GPU 0)] l want to apply softmax on this : m=torch.nn.Softmax() assert input.dim() == 2, 'Softmax requires a 2D tensor as input' AssertionError: Softmax requires a 2D tensor as input Do l have to change the dimension of my variable ? if yes , how can l do that 26x1x37 to become 26x37 Thank you
st116295
Go through squeeze option to reduce the dimension: http://pytorch.org/docs/master/torch.html?highlight=squeeze#torch.squeeze 67
st116296
Hey there, I would like to get a vector from two vectors indices and values. It sounds like a sparse vector (give values and indices, or implicitly use 0), but I didn’t find much doc about it and failed this way. I looked about scatter that does not helps. In fact I would like a kind of fill_values similar to existing fill but with a vector as argument, not a scalar. In order words: Given two vectors: v FloatTensor, [n, 1] i LongTensor, [n, 1] I would like to make a FloatTensor r [dim, 1] such as: for each j in [0, n[: r[i[j]] = v[j] (A) dim is known, and for each i in [0, n[ we have dim > i[j] Since I haven’t found any built-in function I tried to do it with loops, starting with a zeros(dim) vector, iterating over j and using (A) to copy the value, but I’m facing an error: ~RuntimeError: copy from Variable to torch.FloatTensor isn't implemented~ Edit: using .data solves this, it was in fact a variable, not a tensor my bad here. Are loops the only way to do it? I’m not sure how efficient it would be. Thx
st116297
In the website http://pytorch.org/ 571, using pip to install pytorch is still "pip install http://download.pytorch.org/whl/cu80/torch-0.1.12.post2-cp35-cp35m-linux_x86_64.whl 177 ", that means the version is 0.1.12. And in the other side, if I use source code to install pytorch, how to update it? Making the new source code means update the version?
st116298
I try to use the dilation convolution layer described in Multi-Scale Context Aggregation by Dilated Convolutions to make a new Vgg net,but it takes too much memory than I thought,I can’t run it on my 980Ti with [1,3,224,224] tensor here is my net: (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True) (2): ReLU (inplace) (3): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(2, 2), dilation=(2, 2)) (4): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True) (5): ReLU (inplace) (6): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(4, 4), dilation=(4, 4)) (7): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True) (8): ReLU (inplace) (9): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(4, 4), dilation=(4, 4)) (10): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True) (11): ReLU (inplace) (12): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(8, 8), dilation=(8, 8)) (13): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True) (14): ReLU (inplace) (15): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(8, 8), dilation=(8, 8)) (16): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True) (17): ReLU (inplace) (18): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(16, 16), dilation=(16, 16)) (19): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True) (20): ReLU (inplace) (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(16, 16), dilation=(16, 16)) (22): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True) (23): ReLU (inplace) def make_layers(cfg, batch_norm=False): layers = [] in_channels = 3 i=1 for v in cfg: if v == ‘M’: i=i*2; else: conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1,dilation=(i,i)) if batch_norm: layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] else: layers += [conv2d, nn.ReLU(inplace=True)] in_channels = v return nn.Sequential(*layers)
st116299
-Do you have cuDNN6 or above installed properly? -Can you run the model with all dilations set to 1 (and paddings appropriately adjusted)?
st116300
Some dataloader processes are dead after runing for several hours. I use version 0.2+5254846. Is there any solution for this problem? image.jpg707×181 85.7 KB
st116301
I am training a simple cnn (2 conv layers) with a triplet margin loss. At some point during training the weights of the first conv layer become nan (I am still trying to figure that one out). The output from the first conv layer at this point is a tensor full of -Inf or +Inf values. Nevertheless the output to the entire network is a valid tensor with real numbers. In fact if I forward a tensor with Infs through a conv layer the output seems to be a bunch of 1s. Is this the expected behavior?
st116302
NaN is very common in deep learning training. The reason usually is gradient exploding, so you can try to monitor gradient norm and apply gradient clipping.
st116303
Indeed I have been trying to check model weights and gradients. Since the problem seems to be at the level of the first conv2d in my model I tried attaching a backward hook to that nn.conv2d module. I am finding that at every epoch during my training the hook is called more and more times (it’s called 18 times the first epoch and then several hundreds of times by epoch 60). Since I am updating the network at every batch I was expecting the hook to be called number-of-batches times every epoch. Is this a bug?
st116304
I’m trying a basic averaging example, but the validation and loss don’t match and the network fails to converge if I increase the training time. I’m training a network with 2 hidden layers, each 500 units wide on three integers from the range [0,9] with a learning rate of 1e-1, Adam, batch size of 1, and dropout for 3000 iterations and validate every 100 iterations. If the absolute difference between the label and the hypothesis is less than a threshold, here I set the threshold to 1, I consider that correct. Could someone let me know if this is an issue with the choice of loss function, something wrong with Pytorch, or something I’m doing. Below are some plots:     val_diff = 1     acc_diff = torch.FloatTensor([val_diff]).expand(self.batch_size) Loop 100 times to during validation:     num_correct += torch.sum(torch.abs(val_h - val_y) < acc_diff) Append after each validation phase:     validate.append(num_correct / total_val) Here are some examples of the (hypothesis, and labels):     [...(-0.7043088674545288, 6.0), (-0.15691305696964264, 2.6666667461395264),     (0.2827358841896057, 3.3333332538604736)] I tried six of the loss functions in the API that are typically used for regression:                                                     torch.nn.L1Loss(size_average=False)                                                                       torch.nn.L1Loss()                                                      torch.nn.MSELoss(size_average=False)                                                                    torch.nn.MSELoss()                                              torch.nn.SmoothL1Loss(size_average=False)                                                                torch.nn.SmoothL1Loss() Thanks.
st116305
Hi, I have understood that we need to do the following for loading models in pytorch checkpoint = torch.load(opt.model, map_location=lambda storage, loc: storage) However, my models are in Torch. So instead of load I do the following: from torch.utils.serialization import load_lua checkpoint = torch.load_lua(opt.model) However, this does not lead to automatic assignment of devices. Right? Is there a way out?
st116306
You should look at this topic: Convert/import Torch model to PyTorch So far, there is no clean way to do it, but you can probably do some hacks to make it.
st116307
Can anyone help me with training a network (e.g. alexnet) from scratch on a dataset (e.g. imagenet, or CIFAR10)? I read the transfer learning tutorial but it was for finetuning
st116308
The finetuning example is enough. You just need to set pretrained =False and send all params to your optimizer. From scratch models.resnet18() Pretrained: models.resnet18(pretrained=True)
st116309
Hi All, Working on training a classification model but instead of using standard linear+logSoftmax+NLLLoss I would like to use Euclidean+MulConstant+MultiMarginLoss. This was straight forward with torch7, but in pytorch all these modules don’t work with autograd. How can I go about it ? I searched the discuss forum but couldn’t find anything relevant. Apologies if I missed it. Kind regards Sagar M W
st116310
In the documentation of nn.RNN it is written that “x_t is the hidden state of the previous layer at time t or input_t for the first layer.” I couldn’t understand the “hidden state of the previous layer” part. Is not x_t just input of RNN?
st116311
Hi, suppose you pile two RNN layers. Then the input to the first layer is of course input_t then the input to the second layer is the output from the first layer, that is, hidden state of the first layer.
st116312
Thanks for the answer. I am very new to area so maybe I am wrong. Correct me when I am wrong please. In the Elman network, inputs to a hidden layer at time t are outputs of the hidden layer from t-1 and the inputs fed to network at time t: h_t = f(x_t, h_{t-1}). So, x_t and h_{t-1} are supposed to be two different inputs. But what I understood from the documentation and your explanation is that h_{t-1}=x_t.
st116313
Is it known that if you do torch.sum(y_hat == y), if the sum is larger than 255, the sum will be whatever - 255? I am seeing this behavior with the conda version of PyTorch. If you do torch.sum((y_hat == y).float()) then it is fine.
st116314
What is the your verson of PyTorch? print(torch.__version__) I tried it in PyTorch 0.1.12_2 and found both are fine.
st116315
>>> x = torch.autograd.Variable(torch.LongTensor([1]*300)) >>> y = torch.autograd.Variable(torch.LongTensor([1]*300)) >>> torch.sum(x == y) Variable containing: 44 [torch.ByteTensor of size 1] >>> print(torch.__version__) 0.1.12_2 >>> torch.sum((x == y).int()) Variable containing: 300 [torch.IntTensor of size 1]
st116316
Hi As you observed, the comparison operators return ByteTensor. I would even recommend to use .long() to convert to a LongTensor. You are safer from overflow even if you do calculations but more importantly it is the type that is most often used in pytorch when things expect integers (e.g. indexing, .gather,…). If you need to do things with other tensors .float() is often needed (e.g. for batch averaging) with a mask or so as you can’t use operators with different tensor types in general. Best regards Thomas
st116317
The point is that if the Variable wrapping is causing the different behavior. For example: >>> x = torch.LongTensor([1]*300) >>> y = torch.LongTensor([1]*300) >>> x = x.cuda() >>> y = y.cuda() >>> torch.sum(x == y) 300 I am not entirely sure if they should have the same behavior with and without the Variable wrapper, but I am just trying to put it out there.
st116318
The difference is actually whether it becomes a python int or a Tensor again. With (x==y).sum(1) you get the overflow with tensors. Now, Variables never are converted to python numbers (because it would lose autograd). Best regards Thomas
st116319
HI I am new Deep Learning and PyTorch , I have coded CBOW model in pytorch but when I am trying to run the code it throws class torch.LongTensor error can anyone help me debug it?please code: import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.optim as optim class CBOW(nn.Module): def __init__(self,vocab_size,embedding_size,context_size): super(CBOW,self).__init__() self.fc1 = nn.Linear(vocab_size,embedding_size) self.fc2 = nn.Linear(embedding_size,vocab_size) def forward(self,x): y = [] for i in xrange(0,174,29): y.append(self.fc1(x[:,i:i+29])) embedding = Variable(torch.zeros(1,128)) for i in xrange(len(y)): embedding = embedding + y[i] embedding = embedding/len(y) x = self.fc2(embedding) return [F.softmax(x),embedding] def make_corpa(data): vocab = "" for i in data: vocab = vocab + " " + i vocab.strip(" ") corpa = {} all_words = list(set(vocab.split(" "))) for i in xrange(len(all_words)): corpa[all_words[i]] = i return [corpa,len(corpa),corpa.keys()] def conv_vect(word,corpa): temp = torch.FloatTensor(1,len(corpa)).zero_() temp[0][corpa[word]] = 1.0 return temp def train_word2vec(vocab_size,embedding_dim,number_of_epochs,data): model = CBOW(vocab_size,embedding_dim,6) loss = nn.CrossEntropyLoss() context,word = make_training_data(data,3) corpa = make_corpa(data)[0] optimizer = optim.SGD(model.parameters(),lr= 0.01) for epoch in xrange(number_of_epochs): for i in xrange(len(context)): context_vec_tmp = [conv_vect(j,corpa) for j in context[i]] context_vec = Variable(torch.cat(tuple([context_vec_tmp[j] for j in xrange(len(context_vec_tmp))]),1)) word_vec = Variable(conv_vect(word[i],corpa)) predict = model(context_vec)[0] predicted = torch.LongTensor(predict.size()[0],predict.size()[1]).zero_() for i in xrange(predict.size()[1]): predicted[0][i] = int(predict[0][i].data[0]/torch.max(predict.data[0])) word_vec.data = torch.Tensor.long(word_vec.data) predicted = Variable(predicted) print predicted.data print word_vec.data model.zero_grad() l = loss(predicted,word_vec) l.backward() optimizer.step() return model def make_training_data(data,context_size): context = [] word = [] for i in data: temp = i.split(" ") for j in xrange(context_size,len(temp)-context_size,1): context.append([temp[j - context_size],temp[j - context_size + 1],temp[j - context_size + 2],temp[j + context_size - 2],temp[j + context_size - 1],temp[j + context_size]]) word.append(temp[j]) return context,word train_word2vec(make_corpa(po)[1],128,10000,po) the error is : KeyError Traceback (most recent call last) <ipython-input-12-c4d942812d63> in <module>() ----> 1 train_word2vec(make_corpa(po)[1],128,10000,po) <ipython-input-10-aa65a56267f9> in train_word2vec(vocab_size, embedding_dim, number_of_epochs, data) 20 print word_vec.data 21 model.zero_grad() ---> 22 l = loss(predicted,word_vec) 23 l.backward() 24 optimizer.step() /usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.pyc in __call__(self, *input, **kwargs) 204 205 def __call__(self, *input, **kwargs): --> 206 result = self.forward(*input, **kwargs) 207 for hook in self._forward_hooks.values(): 208 hook_result = hook(self, input, result) /usr/local/lib/python2.7/dist-packages/torch/nn/modules/loss.pyc in forward(self, input, target) 319 _assert_no_grad(target) 320 return F.cross_entropy(input, target, --> 321 self.weight, self.size_average) 322 323 /usr/local/lib/python2.7/dist-packages/torch/nn/functional.pyc in cross_entropy(input, target, weight, size_average) 531 for each minibatch. 532 """ --> 533 return nll_loss(log_softmax(input), target, weight, size_average) 534 535 /usr/local/lib/python2.7/dist-packages/torch/nn/functional.pyc in log_softmax(input) 432 433 def log_softmax(input): --> 434 return _functions.thnn.LogSoftmax()(input) 435 436 /usr/local/lib/python2.7/dist-packages/torch/nn/_functions/thnn/auto.pyc in forward(self, input, *params) 108 109 def forward(self, input, *params): --> 110 self._backend = type2backend[type(input)] 111 112 for param in params: /usr/local/lib/python2.7/dist-packages/torch/_thnn/__init__.pyc in __getitem__(self, name) 13 14 def __getitem__(self, name): ---> 15 return self.backends[name].load() 16 17 KeyError: <class 'torch.LongTensor'> Thank you
st116320
The predicted of CrossEntropyLoss should be a FloatTensor , but predicted in your code contains LongTensor.
st116321
Hi there, I have a simple question. I want to build a simple DNN, but have the number of linear layer passed in as a parameter, so that the users can define variable number of linear layers as they see fit. But I have not figured out how to do this in pytorch. For example, I can easily define a three layer DNN like this, class DNN(nn.Module): def __init__(self, nb_units, input_dim, output_dim) super(DNN, self).__init__() self.fc1 = nn.Linear(input_dim, nb_units) self.fc2 = nn.Linear(nb_units, nb_units) self.fc3 = nn.Linear(nb_units, output_dim) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.sigmoid(self.fc3(x)) return x Now I also want to be able to pass the number of layers as a parameter as well, I have tried this solution: class DNN(nn.Module): def __init__(self, nb_layers, nb_units, input_dim, output_dim) super(DNN, self).__init__() self.nb_layers = nb_layers fc = [] for i in range(nb_layers): if i == 0: fc.append(nn.Linear(input_dim, nb_units)) elif i == nb_layers-1: fc.append(nn.Linear(nb_units, output_dim)) else: fc.append(nn.Linear(nb_units, nb_units)) self.fc = fc def forward(self, x): for i in range(self.nb_layers): if i == self.nb_layers-1: x = F.sigmoid(self.fc[i](x)) else: x = F.relu(self.fc[i](x)) return x You can see that I essentially put layer definitions in a list and use them one by one in this forward call. But with this approach. Pytorch gave me an error. So can anyone gives me some help for this problem? How can do what I want to do with in Pytorch? Thanks a lot!
st116322
Oh my. So many indent problems in your code. You should have put your error code here. Your code is fine, I think you forgot to set self.nb_layers. Also, I think it is better to use torch.nn.Sequential 125 The editor is really hard to use… I also got some indent problems with pasting my code. import torch from torch import nn from torch.autograd import Variable from torch.nn import functional as F class DNN(nn.Module): def __init__(self, nb_layers, nb_units, input_dim, output_dim): super(DNN, self).__init__() fc = [] self.nb_layers = nb_layers for i in range(nb_layers): if i == 0: fc.append(nn.Linear(input_dim, nb_units)) elif i == nb_layers-1: fc.append(nn.Linear(nb_units, output_dim)) else: fc.append(nn.Linear(nb_units, nb_units)) self.fc = fc def forward(self, x): for i in range(self.nb_layers): if i == self.nb_layers-1: x = F.sigmoid(self.fc[i](x)) else: x = F.relu(self.fc[i](x)) return x a = DNN(3, 100, 500, 500) input = Variable(torch.Tensor(10, 500)) output = a(input)
st116323
ShuokaiPan: self.fc = fc Should be self.fc = nn.ModuleList (fc) or you use ModuleList instead of []. Best regards Thomas
st116324
HI Zeng, THanks for your reply. I also feel the code editor is quite hard to use. But the problem with my code is not that I did not define self.nb_layers. I defined that in my code, I just did not copy that in this post. I achieve what I want to do with Thomas’ s solution. CHeers
st116325
HI Thomas, I tried with your answer and my code now works fine. Thanks a lot Shuokai
st116326
HI, There is cudnn5.0 lib on my PC, however I got warning: UserWarning: PyTorch was compiled without cuDNN support. To use cuDNN, rebuild PyTorch making sure the library is visible to the build system. "PyTorch was compiled without cuDNN support. To use cuDNN, rebuild " How to build pytorch with cuDNN support? cudnn.h is in /usr/local/cuda-8.0/include/cudnnv5/ and cudnn.so.5 is in /usr/local/cuda-8.0/lib64/cuDNNv5/. The path has been added in system environment variable. export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64/cuDNNv5:$LD_LIBRARY_PATH I build the pytorch from source code. cd pytorch-root/ & python setup.py install THANKS
st116327
export CUDNN_INCLUDE_DIR="/usr/local/cuda-8.0/include/cudnnv5/" export CUDNN_LIB_DIR="/usr/local/cuda-8.0/lib64/cuDNNv5/"
st116328
Thanks for your reply. However it does not work, and blow is buidling log running build_ext -- Building with NumPy bindings -- Not using cuDNN -- Detected CUDA at /usr/local/cuda -- Building NCCL library building 'torch._C' extension Is there any other variable needed to specify CUDNN? I just build the pytorch: python setup.py build
st116329
oh, i realized that when you mentioned the paths, for include dir you said it’s cudnnv5 but for lib dir it’s cuDNNv5. The paths are case-sensitive, so check if one of them is the wrong case.
st116330
cudnn is not being detected even after exporting the paths. I tried the following: My cudnn libraries are in ~/cuda/ export CUDNN_INCLUDE_DIR=~/cuda/include/ export CUDNN_LIB_DIR=~/cuda/lib64/ And then in python3, it returns nothing when I query for the cudnn version. >>> import torch >>> torch.backends.cudnn.version() >>>
st116331
Hi everone, I using this code: self.conv = nn.Conv1d(input_dim, output_dim, 1, 1) but get the error: RuntimeError: kernel size should be greater than zero, but got kH: 1 kW: 0 at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/THNN/generic/SpatialConvolutionMM.c:11 the strides has the same problem. self.conv = nn.Conv1d(input_dim, output_dim, (1,1),(1,1)) is correct. why did this case take place?In the document, the kernel_size and strides can use int or tuple. Thanks for help I find my input Dimension is error, if use Conv1D, the input shape must be 3D-Tensor (N,Cin,Lin)
st116332
Hi, In one dimensional convolution, I think tuple is incorrect. Why? because you are dealing with 1 dimension (1, 1) means stride in direction X and Y. Just specify int, I think that might fix your problem.
st116333
I’m getting the following error when trying to move my network and tensors to GPU. Could someone tell me what I’m doing wrong? Thanks. Traceback (most recent call last): File "/media/project/train.py", line 78, in train hypo = self.network(x) File "/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "model/network.py", line 35, in forward hidden = self.input_layer(x.view(1, input_size)).clamp(min=0) File "/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "/usr/local/lib/python2.7/dist-packages/torch/nn/modules/linear.py", line 54, in forward return self._backend.Linear()(input, self.weight, self.bias) File "/usr/local/lib/python2.7/dist-packages/torch/nn/_functions/linear.py", line 10, in forward output.addmm_(0, 1, input, weight.t()) TypeError: addmm_ received an invalid combination of arguments - got (int, int, torch.cuda.FloatTensor, torch.FloatTensor), but expected one of: * (torch.cuda.FloatTensor mat1, torch.cuda.FloatTensor mat2) * (torch.cuda.sparse.FloatTensor mat1, torch.cuda.FloatTensor mat2) * (float beta, torch.cuda.FloatTensor mat1, torch.cuda.FloatTensor mat2) * (float alpha, torch.cuda.FloatTensor mat1, torch.cuda.FloatTensor mat2) * (float beta, torch.cuda.sparse.FloatTensor mat1, torch.cuda.FloatTensor mat2) * (float alpha, torch.cuda.sparse.FloatTensor mat1, torch.cuda.FloatTensor mat2) * (float beta, float alpha, torch.cuda.FloatTensor mat1, torch.cuda.FloatTensor mat2) didn't match because some of the arguments have invalid types: (int, int, torch.cuda.FloatTensor, torch.FloatTensor) * (float beta, float alpha, torch.cuda.sparse.FloatTensor mat1, torch.cuda.FloatTensor mat2) didn't match because some of the arguments have invalid types: (int, int, torch.cuda.FloatTensor, torch.FloatTensor) torch.manual_seed(1) class Train(object): def __init__(self, network, training, address): self.network = network self.address = address self.batch_size = training['batch_size'] self.iterations = training['iterations'] self.samples = training['samples'] self.data = training['data'] self.lr = training['lr'] self.noisy_lr = training['nlr'] self.cuda = training['cuda'] self.save = training['save'] self.scale = training['scale'] self.limit = training['limit'] self.replace = training['strategy'] self.optimizer = torch.optim.Adam(self.network.parameters(), lr=self.lr) logging.basicConfig(filename='gradient.log',level=logging.DEBUG) def tensor_to_Variable(self, t): if next(self.network.parameters()).is_cuda and not t.is_cuda: t = t.cuda() return Variable(t) def train(self): if self.cuda: self.network.cuda() dh = DataHandler(self.data) loss_fn = torch.nn.MSELoss() losses = [] validate = [] val_size = 100 val_diff = 1 total_val = float(val_size * self.batch_size) hypos = [] labels = [] # training loop for i in range(self.iterations): x, y = dh.get_batch(self.batch_size) x = self.tensor_to_Variable(x) y = self.tensor_to_Variable(y) self.optimizer.zero_grad() hypo = self.network(x) loss = loss_fn(hypo, y) loss.backward() self.optimizer.step() if i % 100 == 0: losses.append(loss.data.tolist()[0]) num_correct = 0.0 acc_diff = torch.FloatTensor([val_diff]).expand(self.batch_size) for j in range(val_size): val_x, val_y = dh.get_batch(self.batch_size) val_h = self.network(self.tensor_to_Variable(val_x)) hypos.extend(val_h.data.tolist()) labels.extend(val_y.data.tolist()) num_correct += torch.sum(torch.abs(val_h.data - val_y.data) < acc_diff) validate.append(num_correct / total_val) class Feedforward(nn.Module): def __init__(self, topology): super(Feedforward, self).__init__() self.input_dim = topology['features'] self.num_hidden = topology['hidden_layers'] self.hidden_dim = topology['hidden_dim'] self.output_dim = topology['output_dim'] self.input_layer = nn.Linear(self.input_dim, self.hidden_dim) self.hidden_layer = nn.Linear(self.hidden_dim, self.hidden_dim) self.output_layer = nn.Linear(self.hidden_dim, self.output_dim) self.dropout_layer = nn.Dropout(p=0.2) def forward(self, x): batch_size = x.size()[0] feat_size = x.size()[1] input_size = batch_size * feat_size self.input_layer = nn.Linear(input_size, self.hidden_dim) hidden = self.input_layer(x.view(1, input_size)).clamp(min=0) for _ in range(self.num_hidden): hidden = self.dropout_layer(F.relu(self.hidden_layer(hidden))) output_size = batch_size * self.output_dim self.output_layer = nn.Linear(self.hidden_dim, output_size) return self.output_layer(hidden).view(output_size)
st116334
Hi, chenjus: TypeError: addmm_ received an invalid combination of arguments - got (int, int, torch.cuda.FloatTensor, torch.FloatTensor), but expected one of Your model is on the CPU and your input is on the GPU. The error says the input to linear received a mix of FloatTensor and cuda.FloatTensor.
st116335
Yeah, turns out the issue was that I was re-initializing the input and output layers in forward(), so they were moved off the GPU. Fixed it by just adding .cuda() each time I reinitialized them.
st116336
Is it necessary to account for batch size in forward()? Do I need to change the size of the input and output layers? When I didn’t do this, the dimensions were off, but someone else told me that it’d not necessary to change the dimensions. Is this true?
st116337
The input to a nn.Module is a Variable of shape batch_size * feature_size. Let’s say you have a nn.Linear(3,5) module. This module take as input a tensor of shape batch_size * 3. So the definition of the module is independent of the batch size. Does this answer your question? PS. That being said the batch_size has to be at least 1
st116338
Hi I am new to Pytorch. I use Dropout layer in my LSTM. If I fix the number for torch.manual_seed(number), the test accuracy won’t change, but varying torch.manual_seed(number) can get the different accuracies. Can I choose a best model by adjusting torch.manual_seed(number)? Thank you.
st116339
It has been proven that a good pre-initialization can improve the perfomance of Neural Network. But I don’t think it would be a good way to achive it by changing seed simply. You may need this. All you need is a good init (Mishkin et al) https://arxiv.org/abs/1511.06422 31
st116340
Thank you very much for answering my questions. I will read the paper carefully. Have a nice day.
st116341
hello everyone, i found a bug about nn.Sequential function: i write my network: convs = nn.Sequential( nn.Conv1d(512, 64, 3, stride=1, padding=1), nn.ReLU(), nn.BatchNorm1d(64), nn.Conv1d(64, 64, 3, stride=1, padding=1), nn.ReLU(), nn.BatchNorm1d(64) ) the input matrix dimension is (80, 512, 33), there is an error which is : RuntimeError: expected 3D tensor however, if i use OrderedDict in Sequential and all other codes are the same, which is as follows, it works : convs = nn.Sequential( OrderedDict([ ('conv1', nn.Conv1d(512, 64, 3, stride=1, padding=1)), ('relu1', nn.ReLU()), ('batchnorm1', nn.BatchNorm1d(64)), ('conv2', nn.Conv1d(64, 64, 3, stride=1, padding=1)), ('relu2', nn.ReLU()), ('batchnorm2', nn.BatchNorm1d(64)) ]) )
st116342
I wrote a simple demo for short text classification but the speed is unexpectedly slow. When I tried to find out where the bottleneck is, it turns out to be intractable. At first, the bottleneck is this line: running_loss += loss.data[0] However, after commenting out the above line, it slows down at these lines in get_batch() function: data = data.cuda() target = target.cuda() Is there any problem in the code? I ran this script on GPU (Titan X) with cuda 8.0, python 2.7, ubuntu 16 and pytorch was installed by pip. The data was randomly generated. The code is attached below: import numpy as np import time import torch import torch.nn as nn from torch.autograd import Variable import torch.optim as optim import torch.nn.functional as F class Net(nn.Module): def __init__(self, vocab_size, emb_dim): """ :param vocab_size: an int value, representing the total number of vocabs in the pre-defined lookup table :param emb_dim: an int value, representing the dimension of each word vector """ super(Net, self).__init__() self.lookup_table = nn.Embedding(vocab_size, emb_dim) self.init_embedding() self.encoder = nn.Conv2d(in_channels=1, out_channels=200, kernel_size=(3, 300)) self.hid_1 = nn.Linear(200, 200) self.hid_2 = nn.Linear(200, 10) def forward(self, x, training=False): """ :param x: input x is in size of [N, C, H, W] N: batch size C: number of channel, in text case, this is 1 H: height, in text case, this is the length of the text W: width, in text case, this is the dimension of the embedding :param training: boolean value, whether the forward is for training purpose :return: a tensor [N, L], where L is the number of classes """ x = self.lookup_table(x) x = x.unsqueeze(1) enc = F.relu(self.encoder(x)) enc = F.max_pool2d(enc, kernel_size=(48, 1)) enc = enc.squeeze() enc = F.dropout(F.relu(self.hid_1(enc)), training=training) enc = F.relu(self.hid_2(enc)) pred_prob = F.softmax(enc) return pred_prob def init_embedding(self): initrange = 0.1 self.lookup_table.weight.data.uniform_(-initrange, initrange) def get_batch(source, batch_size, i): data = source[0][batch_size * i: batch_size * (i + 1)] target = source[1][batch_size * i: batch_size * (i + 1)] if torch.cuda.is_available(): print "moving data..." st = time.time() data = data.cuda() target = target.cuda() dt = time.time() - st print "moving data time: {}".format(dt) return data, target print "Setting seed..." seed = 1234 torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) train_batch_size = 100 test_batch_size = 100 rng = np.random.RandomState(seed) num_train_instances = 20000 num_test_instances = 2000 max_text_len = 50 vocab_size = 62639 num_classes = 10 emb_dim = 300 print "Generating random data..." train_set_numpy = rng.randint(0, vocab_size, (num_train_instances, max_text_len)), rng.randint(0, num_classes, (num_train_instances,)) test_set_numpy = rng.randint(0, vocab_size, (num_test_instances, max_text_len)), rng.randint(0, num_classes, (num_test_instances,)) print "Converting numpy data into Tensor..." train_set = torch.from_numpy(train_set_numpy[0]), torch.from_numpy(train_set_numpy[1]) test_set = torch.from_numpy(test_set_numpy[0]), torch.from_numpy(test_set_numpy[1]) n_train_batch = train_set[0].size()[0] / train_batch_size + 1 n_test_batch = test_set[0].size()[0] / test_batch_size + 1 model = Net(vocab_size=vocab_size, emb_dim=emb_dim) if torch.cuda.is_available(): print "move model to GPU" model.cuda() print "move done" print model criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters()) for epoch in xrange(10): running_loss = 0. for i in xrange(n_train_batch): start_time = time.time() print "batch: %d" % i text, labels = get_batch(train_set, train_batch_size, i) text, labels = Variable(text), Variable(labels) print "zero optimizer" optimizer.zero_grad() print "compute forward" st = time.time() outputs = model(text, training=True) dt = time.time() - st print "compute forward time: {}".format(dt) print "compute loss" st = time.time() loss = criterion(outputs, labels) dt = time.time() - st print "compute loss time: {}".format(dt) print "compute backword" st = time.time() loss.backward() dt = time.time() - st print "compute backword time: {}".format(dt) print "update gradient" st = time.time() optimizer.step() dt = time.time() - st print "update gradient time: {}".format(dt) print "accumulate loss" st = time.time() running_loss += loss.data[0] dt = time.time() - st print "accumulate loss time: {}".format(dt) duration = time.time() - start_time if i % 1 == 0: print "training speed: {}/sec".format(train_batch_size / duration) running_loss = 0. if i % 4 == 3: start_time = time.time() correct = 0. total = 0. for j in xrange(n_test_batch): text, labels = get_batch(test_set, test_batch_size, j) text, labels = Variable(text), Variable(labels) outputs = model(text) _, predicted = torch.max(outputs.data, dim=1) total += labels.size()[0] correct += (predicted == labels.data).sum() duration = time.time() - start_time print "acc: {}".format(100 * correct / total) print "testing speed: {}/sec".format(total / duration) print "loop done"
st116343
The points where your benchmarking indicates slowdowns are CUDA synchronization points. All host-GPU scalar copies (e.g. accessing individual elements like loss.data[0]), or transferring tensors that aren’t in pined memory (e.g. .cuda()) will make the CPU and GPU synchronize. Your CPU quickly gets through the model definition, and then stop in one of these points, waiting for the GPU to finish computing the forward pass. If you want to reliably benchmark the compute time of your model do this: torch.cuda.synchronize() start = # get start time output = model(input) torch.cuda.synchronize() end = # get end time Can you expect what “unexpectedly slow” means? What is the runtime and what did you expect? It seems that you’re using a convolutional kernel size of 3x300, and that will be incredibly costly to compute (especially with 200 output channels).
st116344
PS. you don’t need to pass training argument to forward. You can use self.training and call model.eval() and model.train() to change the flag.
st116345
Thanks for the reply! Now I know why the timing is weird. For the slow part, I time the training on one batch and print it in the code. It shows that the training speed is around 13 instances per sec. With larger graph using tensorflow, the same machine can easily achieve thousands of instances per sec. In the pytorch code above, every batch takes about 8 sec. Thanks.
st116346
Try to use more batches, the first one will be always slower, because lot of time will be spent allocating memory that will be cached for subsequent runs. Are the batch sizes and model parameters exactly the same as in tensorflow? I can try to run your model tomorrow, but it would be helpful if you could also provide me with the code for tensorflow implementation.
st116347
The 8 sec is not the first batch, it is on average. The batch size for tensorflow is 1024. There are four parallel convolutional layers for my tensorflow model, the kernel sizes are 1X250, 3X250, 4X250, 5X250. And then some hidden layers. That is a much larger graph than the example I showed above. Sorry, the tensorflow code has too many dependencies, I don’t think I can simply show it here. Thank you very much!
st116348
I wrote a demo tensorflow code, and graph is the same as that of pytorch. On same machine. tensorflow 0.12 the timing info is: batch duration: 0.0545980930328 s training speed: 1831.56580102/sec here is the code: import time import tensorflow as tf import numpy as np with tf.Graph().as_default(): max_text_len = 50 num_classes = 10 vocab_size = 62639 emb_dim = 300 num_train_instances = 20000 num_test_instances = 2000 train_batch_size = 100 test_batch_size = 100 # model part filter_size = 3 num_filters = 200 # generating random data seed = 1234 rng = np.random.RandomState(seed) train_set = rng.randint(0, vocab_size, (num_train_instances, max_text_len)), rng.randint(0, num_classes, (num_train_instances)) test_set = rng.randint(0, vocab_size, (num_test_instances, max_text_len)), rng.randint(0, num_classes, (num_test_instances)) n_train_batch = train_batch_size / train_batch_size + 1 n_test_batch = test_batch_size / test_batch_size + 1 def get_batch(source, i, batch_size): data = source[0][i * batch_size: (i + 1) * batch_size] target = source[1][i * batch_size: (i + 1) * batch_size] return data, target # describe graph input_x = tf.placeholder(tf.int32, [None, max_text_len], name="input_x") input_y = tf.placeholder(tf.int32, [None], name="input_y") with tf.device('/cpu:0'), tf.name_scope("embedding"): emb_w = tf.Variable(tf.random_uniform([vocab_size, emb_dim], -1.0, 1.0), name="emb_w") embedded = tf.nn.embedding_lookup(emb_w, input_x) embedded_expanded = tf.expand_dims(embedded, -1) with tf.name_scope("conv-maxpool-%s" % filter_size): filter_shape = [filter_size, emb_dim, 1, num_filters] W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W") b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b") conv = tf.nn.conv2d( embedded_expanded, W, strides=[1, 1, 1, 1], padding="VALID", name="conv") # Apply nonlinearity h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu") # Maxpooling over the outputs pooled = tf.nn.max_pool( h, ksize=[1, max_text_len - filter_size + 1, 1, 1], strides=[1, 1, 1, 1], padding='VALID', name="pool") h_pool_flat = tf.reshape(pooled, [-1, num_filters]) with tf.name_scope("dropout"): h_drop = tf.nn.dropout(h_pool_flat, 0.5) with tf.name_scope("hidden"): W = tf.get_variable( "h_W", shape=[num_filters, num_filters], initializer=tf.contrib.layers.xavier_initializer()) b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b") hidden_out = tf.nn.xw_plus_b(h_drop, W, b, name="hidden_out") with tf.name_scope("output"): W = tf.get_variable( "o_W", shape=[num_filters, num_classes], initializer=tf.contrib.layers.xavier_initializer()) b = tf.Variable(tf.constant(0.1, shape=[num_classes]), name="b") scores = tf.nn.xw_plus_b(hidden_out, W, b, name="scores") with tf.name_scope("loss"): losses = tf.nn.sparse_softmax_cross_entropy_with_logits(scores, input_y) # training session_conf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) sess = tf.Session(config=session_conf) optimizer = tf.train.AdamOptimizer(1e-3) grads_and_vars = optimizer.compute_gradients(losses) train_op = optimizer.apply_gradients(grads_and_vars) sess.run(tf.global_variables_initializer()) for epoch in xrange(10): for i in xrange(n_train_batch): start_time = time.time() x_batch, y_batch = get_batch(train_set, i, train_batch_size) print x_batch.shape print y_batch.shape feed_dict = { input_x: x_batch, input_y: y_batch, } _, loss_ = sess.run([train_op, losses], feed_dict) duration = time.time() - start_time print "duration: {} s".format(duration) print "speed: {}/sec".format(train_batch_size / duration) Thank you very much!
st116349
Seems like that there are some problems or pitfalls in Conv2d on GPU. When I used in_channels = 1, out_channels = 200, kernel height = 3, kernel width = 300 (original setting) then backward was very slow. I changed it to in channels = 300, out channels = 200, kernel height = 1, kernel width = 3 then model works well. (I got 9500/sec on GTX 1080 8) ) This seems like GPU-specific problem because no problem occurred when ran on CPU.
st116350
Hmm yeah that will likely use make cuDNN pick a different algorithm. I don’t think it’s optimized for 3x300, so it probably falls back to a slow gemm implementation, while 1x3 is quite commonly used, and will likely use a smarter algo.
st116351
If it is a GPU-specific problem, then why tensorflow code works well with the same kernel size? Thanks
st116352
It’s not a GPU specific problem, we’re probably just using different cuDNN calls to select algorithms, and for some reason they fail to pick the fast ones for this use case. I don’t know if there’s no other way, it will take me some time until I properly benchmark it and see what’s the issue. If you want to use it now, just reshape the input.
st116353
Ok, I’ve confirmed the issue. The fix for now is to reshape the inputs as @kim.seonghyeon said, or to set torch.backends.cudnn.enabled = False. Still, the first approach is likely to be faster for you. With cudnn disabled the training runs at 1k samples/sec for me. With it slows down to 12.
st116354
Ok, @colesbury made a good point. The fix is to add torch.backends.cudnn.benchmark = True This is a flag that controls cudnn benchmark mode and should be used only if every forward pass uses the same data dimensions. After this your code runs @ 7k/s for training and 64k/s for test on my machine.
st116355
Also, a small improvement at test time can be achieved by using volatile=True on the input to the network.
st116356
Thanks for the follow up. I will stick to @kim.seonghyeon 's method, where my code get 8K/s for training and 80K/s for testing. Thanks!
st116357
If I set this: apaszke: torch.backends.cudnn.benchmark = True What do you mean by same data dimension? Do I have to have a fixed batch size? If that is the case, what if the data size is not the integer times of batch size? Thanks.
st116358
I have this code that initializes my recurrent matrices (Whx and Whh) of LSTM to the zero matrix now. However, I wanted to initialize them to the identity matrix. state_shape = self.config.n_cells, batch_size, self.config.d_hidden h0 = c0 = Variable(inputs.data.new(*state_shape).zero_()) I have a little confused as to how to do this neatly since the shape is 3D and I cannot use nn.init.eye which is for 2D tensors. Also, the first dimension is number of cells in the sequence and not batch size which makes it harder to do this in my opinion. Is there any neat way to do this? Please let me know. Thank you!
st116359
Hi Why would your weights include a 3rd (batch_size?) dimension? Your state, which you show does and should, but for the weights that seems unusual. That said, you can mostly assign to parameter’s .data submatrices. Best regards Thomas
st116360
i have some experiments on following toy code, but i have some question about this, can anyone help me ? thank you very much. #dtype = tc.FloatTensor dtype = tc.cuda.FloatTensor x = tc.randn(100000, 50).type(dtype) w1 = tc.randn(50, 30).type(dtype) s = time.time() l = x.mm(w1) e = time.time() print e - s s = time.time() l = [] for i in range(x.size(0)): l.append(x[i].unsqueeze(0).mm(w1).squeeze(0)) l = tc.stack(l, dim=0) e = time.time() print e - s if i run this on CPU, the consuming time are: 0.017 sec and 0.696 sec however, when i run this on GPU, strange things happen, the consuming time became more : 0.314 sec and 1.592 sec. i think calculation on GPU should take less time , right ? besides, for loop takes more time than matrix multiplication, which is reasonable. someone people explain this for me ? thank you.
st116361
I think this is expected. There is some overhead in launching CUDA code and you are launching many kernels, and in your case the matrices are very small so there is no benefit in using GPUs over CPUs. Note that you can use torch.bmm to perform batched matrix multiplication, and it will be orders of magnitude faster than a for loop.
st116362
Hello, I was going through PyTorch tutorials and stuck at the name classification tutorial: http://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html 16 with my slight modifications. After two days of googling and lurking at the forum I can’t figure out how to properly use packed sequences in batches with RNN. Could you please help me with that? Code is properly working if I feed objects one-by-one to the network. I use some not so obvious approaches to vectorization with numpy because I’m more familiar with it, but I hope to learn more “pytorch way” in the future. Also I know about torchtext but I would like to understand the low-level mechanics of PyTorch first. Code: import random import torch from torch import nn from torch.nn import init import torch.nn.functional as F from torch import autograd from torch.autograd import Variable from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence import glob import string import unicodedata import numpy as np import time import math all_letters = string.ascii_letters + " .,;'" n_letters = len(all_letters) N_HIDDEN = 16 USE_CUDA = torch.cuda.is_available() class RNN(torch.nn.Module): def __init__(self, n_classes, gru_size = N_HIDDEN): super(RNN, self).__init__() self.gru = nn.GRU(input_size=n_letters, hidden_size=gru_size) self.linear = nn.Linear(gru_size, n_classes) def forward(self, input, lengths): output, self.hidden = self.gru(input, self.hidden) x = output[-1] x = F.relu(x) x = self.linear(x) x = F.log_softmax(x) return x def init_hidden(self, batch_size): hidden = autograd.Variable(torch.zeros(1, batch_size, N_HIDDEN)) if USE_CUDA: self.hidden = hidden.cuda() else: self.hidden = hidden def unicodeToAscii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and c in all_letters ) def vectorize(seqs): X = np.zeros((30, len(seqs), 1, n_letters), dtype=np.uint8) for i, sequence in enumerate(seqs): for t, letter in enumerate(sequence): X[t, i, 0, all_letters.find(letter)] = 1 return X # Slice numpy arrays by the given indices and convert them to Variables def get_seq(ind): if USE_CUDA: return (autograd.Variable(torch.from_numpy(seq_arr)[:, ind]).cuda(), autograd.Variable(torch.from_numpy(cat_vec[ind])).cuda()) else: return (autograd.Variable(torch.from_numpy(seq_arr[:, ind]).type(torch.FloatTensor)), autograd.Variable(torch.from_numpy(cat_vec[ind]).type(torch.LongTensor))) def timeSince(since): now = time.time() sec = now - since s = sec m = math.floor(sec / 60) s -= m * 60 return '%dm %ds' % (m, s), sec file_paths = glob.glob("./data/names/*.txt") len_vec = [] cat_vec = [] seq_vec = [] all_categories = [] cat_dict = {} for file in file_paths: cat = file.split('/')[-1].split('.')[0] if cat not in cat_dict: cat_dict[cat] = len(cat_dict) with open(file, encoding='utf-8') as inp: for line in inp: seq_vec.append(line.strip()) cat_vec.append(cat_dict[cat]) all_categories.append(cat) len_vec.append(len(line.strip())) # Sort sequences in descending order by their length temp = sorted(zip(seq_vec, cat_vec), reverse=True, key = lambda x: len(x[0])) seq_arr = vectorize([x[0] for x in temp]) cat_vec = np.array([x[1] for x in temp]) len_vec = np.array([len(x[0]) for x in temp]) rnn = RNN(len(cat_dict)) if USE_CUDA: rnn = rnn.cuda() criterion = nn.NLLLoss() learning_rate = .002 optimizer = torch.optim.RMSprop(rnn.parameters(), lr=learning_rate) start = time.time() for iter in range(10): all_loss = [] print(iter+1) for ind in range(64): # Batches of size 16, just get some random indices # And yes, I know this isn't the right way to make batches inds = sorted(np.random.choice(20000, 16, replace=False)) x, y = get_seq(inds) x = pack_padded_sequence(x, len_vec[inds]) rnn.init_hidden(len(inds)) rnn.zero_grad() y_pred = rnn(x, len_vec[inds]) loss = criterion(y_pred, y) loss.backward() optimizer.zero_grad() optimizer.step() all_loss.append(loss.data[0]) tstr, sec = timeSince(start) print(round(sec / (iter+1), 3)) print(sum(all_loss)) print() Error: File "trch.py", line 158, in <module> y_pred = rnn(x, len_vec[inds]) File "/Users/vdn/anaconda/lib/python3.5/site-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "trch.py", line 38, in forward output, self.hidden = self.gru(input, self.hidden) File "/Users/vdn/anaconda/lib/python3.5/site-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "/Users/vdn/anaconda/lib/python3.5/site-packages/torch/nn/modules/rnn.py", line 91, in forward output, hidden = func(input, self.all_weights, hx) File "/Users/vdn/anaconda/lib/python3.5/site-packages/torch/nn/_functions/rnn.py", line 343, in forward return func(input, *fargs, **fkwargs) File "/Users/vdn/anaconda/lib/python3.5/site-packages/torch/nn/_functions/rnn.py", line 243, in forward nexth, output = func(input, hidden, weight) File "/Users/vdn/anaconda/lib/python3.5/site-packages/torch/nn/_functions/rnn.py", line 83, in forward hy, output = inner(input, hidden[l], weight[l]) File "/Users/vdn/anaconda/lib/python3.5/site-packages/torch/nn/_functions/rnn.py", line 154, in forward hidden = (inner(step_input, hidden[0], *weight),) File "/Users/vdn/anaconda/lib/python3.5/site-packages/torch/nn/_functions/rnn.py", line 53, in GRUCell gi = F.linear(input, w_ih, b_ih) File "/Users/vdn/anaconda/lib/python3.5/site-packages/torch/nn/functional.py", line 449, in linear return state(input, weight) if bias is None else state(input, weight, bias) File "/Users/vdn/anaconda/lib/python3.5/site-packages/torch/nn/_functions/linear.py", line 10, in forward output.addmm_(0, 1, input, weight.t()) RuntimeError: matrices expected, got 3D, 2D tensors at /Users/soumith/miniconda2/conda-bld/pytorch_1493757035034/work/torch/lib/TH/generic/THTensorMath.c:1232
st116363
After careful investigation I found the error and made it work. Here is the final code with highlighted errors: import random import torch from torch import nn from torch.nn import init import torch.nn.functional as F from torch import autograd from torch.autograd import Variable from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence import glob import string import unicodedata import numpy as np import time import math all_letters = string.ascii_letters + " .,;'" n_letters = len(all_letters) N_HIDDEN = 16 USE_CUDA = torch.cuda.is_available() class RNN(torch.nn.Module): def __init__(self, n_classes, gru_size = N_HIDDEN): super(RNN, self).__init__() self.gru = nn.GRU(input_size=n_letters, hidden_size=gru_size) self.linear = nn.Linear(gru_size, n_classes) def forward(self, input, lengths): # New: return and process the last hidden layer values from each input sequence output, y = self.gru(input, self.hidden) x = y.squeeze() x = F.relu(x) x = self.linear(x) x = F.log_softmax(x) return x def init_hidden(self, batch_size): hidden = autograd.Variable(torch.zeros(1, batch_size, N_HIDDEN)) if USE_CUDA: self.hidden = hidden.cuda() else: self.hidden = hidden def unicodeToAscii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and c in all_letters ) def vectorize(seqs): # Error: unnecessary dimension # X = np.zeros((30, len(seqs), 1, n_letters), dtype=np.uint8) X = np.zeros((30, len(seqs), n_letters), dtype=np.uint8) for i, sequence in enumerate(seqs): for t, letter in enumerate(sequence): X[t, i, all_letters.find(letter)] = 1 return X # Slice numpy arrays by the given indices and convert them to Variables def get_seq(ind): if USE_CUDA: return (autograd.Variable(torch.from_numpy(seq_arr[:, ind])).cuda(), autograd.Variable(torch.from_numpy(cat_vec[ind])).cuda()) else: return (autograd.Variable(torch.from_numpy(seq_arr[:, ind]).type(torch.FloatTensor)), autograd.Variable(torch.from_numpy(cat_vec[ind]).type(torch.LongTensor))) def timeSince(since): now = time.time() sec = now - since s = sec m = math.floor(sec / 60) s -= m * 60 return '%dm %ds' % (m, s), sec file_paths = glob.glob("./data/names/*.txt") len_vec = [] cat_vec = [] seq_vec = [] all_categories = [] cat_dict = {} for file in file_paths: cat = file.split('/')[-1].split('.')[0] if cat not in cat_dict: cat_dict[cat] = len(cat_dict) with open(file, encoding='utf-8') as inp: for line in inp: seq_vec.append(line.strip()) cat_vec.append(cat_dict[cat]) all_categories.append(cat) len_vec.append(len(line.strip())) # Sort sequences in descending order by their length temp = sorted(zip(seq_vec, cat_vec), reverse=True, key = lambda x: len(x[0])) seq_arr = vectorize([x[0] for x in temp]) cat_vec = np.array([x[1] for x in temp]) len_vec = np.array([len(x[0]) for x in temp]) rnn = RNN(len(cat_dict)) if USE_CUDA: rnn = rnn.cuda() criterion = nn.NLLLoss() learning_rate = .002 optimizer = torch.optim.RMSprop(rnn.parameters(), lr=learning_rate) start = time.time() for iter in range(10): all_loss = [] print(iter+1) for ind in range(64): # New: put zeroing the gradients here optimizer.zero_grad() # Batches of size 16, just get some random indices # And yes, I know this isn't the right way to make batches inds = sorted(np.random.choice(20000, 16, replace=False)) x, y = get_seq(inds) x = pack_padded_sequence(x, len_vec[inds]) rnn.init_hidden(len(inds)) rnn.zero_grad() y_pred = rnn(x, len_vec[inds]) loss = criterion(y_pred, y) loss.backward() # Error: we are zeroing gradients after the backward pass # optimizer.zero_grad() optimizer.step() all_loss.append(loss.data[0]) tstr, sec = timeSince(start) print(round(sec / (iter+1), 3)) print(sum(all_loss)) print()
st116364
Most of speed efficient libraries like caffe and mxnet requires us to write CUDA when defining new layers. They do allow us to write in python too, but those layers will be slower. Can I know if Pytorch has helped us to do the CUDA stuff or is it just like other libraries whereby the newly defined layers will be slower if written in Python, in which case Pytorch will be slow if we want to define new layers?
st116365
The code of ‘Sampler.lua’ in torch7 is there: require ‘nn’ local Sampler, parent = torch.class(‘nn.Sampler’, ‘nn.Module’) function Sampler:__init() parent.__init(self) self.gradInput = {} end function Sampler:updateOutput(input) self.eps = self.eps or input[1].new() self.eps:resizeAs(input[1]):copy(torch.randn(input[1]:size())) self.ouput = self.output or self.output.new() self.output:resizeAs(input[2]):copy(input[2]) self.output:mul(0.5):exp():cmul(self.eps) self.output:add(input[1]) return self.output end function Sampler:updateGradInput(input, gradOutput) self.gradInput[1] = self.gradInput[1] or input[1].new() self.gradInput[1]:resizeAs(gradOutput):copy(gradOutput) self.gradInput[2] = self.gradInput[2] or input[2].new() self.gradInput[2]:resizeAs(gradOutput):copy(input[2]) self.gradInput[2]:mul(0.5):exp():mul(0.5):cmul(self.eps) self.gradInput[2]:cmul(gradOutput) return self.gradInput end the input has 2 elements:(In lua, elements start with 1 instead of 2) input[1] = (batch_size, size) stand for mean input[2] = (batch_size, size) strand for log_var for example: input[1] = (100, 20) input[2] = (100, 20) use the mean and log_var sampling. After that get output(100, 20) It looks like there is no ‘nn.Sampler’ in pytorch. So how to do it? Thanks~
st116366
I have following code class F(torch.autograd.Function): def forward(self, i): self.save_for_backward(i) return tr.FloatTensor([1]) def backward(self, c): a = tr.zeros(10,10) i = self.saved_tensors a[i] = tr.ones(3,10) # Error!!! return None f = F() f(tr.LongTensor([2,3,4]) But this gives the error TypeError: indexing a tensor with an object of type torch.LongTensor. The only supported types are integers, slices, numpy scalars and torch.LongTensor or torch.ByteTensor as the only argument This is a weird message, Since given i has type tuple not LongTensor If i change my code like below def backward(self, c): a = tr.zeros(10,10) i = self.saved_tensors[0] a[i] = tr.ones(3,10) return None Then error is resolved
st116367
Hi! I can do that without any error In [13]: a = torch.zeros(10, 10) In [14]: b = torch.ones(3, 10) In [15]: a[i] = b In [16]: a Out[16]: 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 [torch.FloatTensor of size 10x10] Give us more information e.g. PyTorch’s version and your OS etc.