id
stringlengths
3
8
text
stringlengths
1
115k
st116768
you can try: target = Variable(torch.from_numpy(np.random.randint(2, size=(10)))) or target = Variable(torch.squeeze(torch.from_numpy(np.random.randint(2, size=(10, 1)))))
st116769
I’m still fairly new to PyTorch, and thus far all examples of neural nets I’ve seen have rigid input and output dimensions, they’re defined when the network is initialized. Here’s my situation: There’s this board game called Can’t Stop, I won’t get into specifics but the important part is that every turn the player rolls 4 die, and has to pair them up. There are limits on what pairings are possible, so it’s not always the same number of dice pairings. Our neural net has to intake the board state and the possible dice pairings, and output the probability of winning for each possible dice pairing. The problem is that since there is a variable number of possible dice pairings per turn, the input and output vectors will not always have the same size. Does this mean that I’d have to instantiate a new neural network whenever the number of possible dice pairings changes? Wouldn’t this make training impossible? Are there workarounds, such as having the input and output always contain the maximum number of dice pairings and whenever a certain pairing isn’t possible just leave that spot in the tensor blank? Please offer any insights you may have
st116770
you could just use input vectors and output vectors large enough to encompass all possible outcomes and just use padding when needed to accommodate different sizes as you said.
st116771
From a technical point of view, you can forwar propagate anything you like, at each time step. backpropagation will work fine (ish: within the constraints that you use functions that have backprop implemented). From a conceptual point of view, what you will propagate is I guess out of scope of pytorch itself, and more of a research issue? Note that conv nets can handle inputs of arbitrary size. You can look at neuralstyle for an example that forwards images of arbitrary size through a pretrained convnet. rnns can also handle inputs of arbitrary size.
st116772
Hi, When I want to pass the ToTensor() transform, I get the following error in this line. Line: img = torch.from_numpy(pic.transpose((2, 0, 1))) RuntimeError: some of the strides of a given numpy array are negative. This is currently not supported, but will be added in future releases. Any idea?
st116773
Solved the problem with the following line: img = torch.from_numpy(np.flip(pic.transpose((2, 0, 1)),axis=0).copy()) Thanks
st116774
Hello, I am implementing a GRU rnn using grucells. I have N layers, so I store my hidden states as a N x hidden_dimension variable. The thing is that after the output of my GRUcell, I want to update the values of the hidden state with the output of the GRUCell, but this makes backward() break. So for example: for idxLayer in range(self.n_layers): currentCell = self.grucells[idxLayer] output = currentCell(output, hiddenStates[idxLayer, :].view(1,-1)) hiddenStates[idxLayer,:] = output #this operation makes the backward() operation fail hiddenStates.sum().backward() #Runtime error RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation How can I solve the problem? Thanks!
st116775
But why don’t you use nn.GRU 7 instead of N nn.GRUCell ? If I understand correctly, what you want to do is exactly what GRU does (stacking N GRUCells for a N-layer GRU network)
st116776
Because I need to modify the outputs of each GRUCell in a certain way before passing them as inputs to the next GRUCell
st116777
Ok, then it makes sense. I would suggest first to initialize your hidden with the good shape (1, hidden_size) so you can directly update them: hiddenStates = [] hiddenStates.append(input) # init hidden: for idxLayer in range(self.n_layers): hiddenStates.append(Variable(torch.zeros(1,hidden_size)) # then hiddenStates is a list of Variables of size n_layer+1 for idxLayer in range(self.n_layers): currentCell = self.grucells[idxLayer+1] hiddenStates[idxLayer+1] = currentCell(hiddenStates[idxLayer], hiddenStates[idxLayer+1]) z = 0 for hidden in hiddenStates[1:]: z += hidden.sum() z.backward() That way, you don’t do any inplace operation
st116778
Thank you! This solved the problem So in general I can write something like for idx in range(100): var1 = network(var1) but if I try to assign only part of the variable (making it an inplace operation) then it doesn’t work anymore. Right?
st116779
Yes, all operations containing indexes in brackets would not be “backwardable”, you have to call functions that takes the whole variable as argument
st116780
Hey all , I’m currently working on an implementation of A3C integrated with openai gym. As some of the environments (e.g. CartPole-v0) don’t return an rgb array as an observation, I leverage env.render(mode='rgb_array') to obtain the pixel representation of the current game state. However, this causes my processes to fail silently. It simply doesn’t execute and the program exits the training loop. I was wondering whether anyone already encountered this problem and already found a fix for this. My current machine is a late 2013 Macbook Pro. Tbh, I’m not that familiar with multiprocessing, but from what I have found on stack overflow, this might be related to the fact that you can’t call UI actions on a child thread. Best, Deniz
st116781
They show how to do it in pytorch tutorials here: http://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html 169 Under input extraction section
st116782
Thanks for your input @dgriff! However, this tutorial addresses the DQN algorithm in opposition to A3C, I am trying to implement. The issue I ran into is that I can’t call render(mode='rgb_array') in different processes when using torch.multiprocessing in order to spawn multiple worker agents and asynchronously update the global model as described by Mnih et al. (https://arxiv.org/pdf/1602.01783.pdf 2).
st116783
ah ok didn’t see you u doing on a3c. will try on my a3c real quick and see if I have same issue
st116784
yeah couldn’t get to work either. I think its as you say you call the UI actions in the child threads. A3C kinda overkill for Cartpole anyway try another environment you can try my a3c repo out here if your interested: https://github.com/dgriff777/rl_a3c_pytorch 108 Has the top scores in openai gym Atari games
st116785
Too bad! Thanks for the effort though The overkill part is true, but I’d like to take the cart pole and transform it into a cart pole swingup env with some additional parameters for my master’s thesis as swingup is already a part of my thesis’ name I guess I will dig into the ways that e.g. PongDeterministic-v3 works seamlessly with multiple threads (I guess it’s due to the fact that it has a c++ backend which is called on the main thread) and try to apply it to the python only env. Maybe I can find a way to directly write into an image buffer, without having the need to perform the actual UI updates or offload the rendering onto the main thread. Too bad I’m not that familiar with multiprocessing in python nor graphics
st116786
Pong works cause gym env setup so you don’t have to call env.render to get RGB values and instead states are already set up to receive the raw the values. Where cartpole we need to grab image and extract raw values from that. “At least that’s how it looks like to me in gym env setup at quick glance lol”
st116787
That’s on way but you can also call render(mode='rgb_array') in your run() method. You can check out this gist 7 to reproduce
st116788
Yeah I was saying it’s the fact that you need to use render() which in turn uses rendering code that gets the rgb values from a created image that I think causes the problem. Where rgb values in Atari come from converting just raw pixel data github.com openai/gym/blob/master/gym/envs/classic_control/rendering.py 10 """ 2D rendering framework """ from __future__ import division import os import six import sys if "Apple" in sys.version: if 'DYLD_FALLBACK_LIBRARY_PATH' in os.environ: os.environ['DYLD_FALLBACK_LIBRARY_PATH'] += ':/usr/lib' # (JDS 2016/04/15): avoid bug on Anaconda 2.3.0 / Yosemite from gym.utils import reraise from gym import error try: import pyglet except ImportError as e: reraise(suffix="HINT: you can install pyglet directly via 'pip install pyglet'. But if you really just want to install all Gym dependencies and not have to think about it, 'pip install -e .[all]' or 'pip install gym[all]' will do it.") This file has been truncated. show original
st116789
This is more of a theoretical question. I am wondering about the consequences of processing a padded batch with an RNN. I know that no weights will be updated since the gradient for zero’ed inputs will be zero. However, as far as I understand the hidden state will be updated, since it involves operations with the previous hidden state, which is not zero’ed. This means that when you start processing the next batch, the input hidden state will not be the one you expect (i.e. the one that was output right after finishing the previous sentence). Please note that I am aware of the support for variable length using pack_padded_sequence. However, I have in mind cases where sorting sentences by length would actually disrupt the training data, since you need to respect original sentence order (example, language modelling) and I need to process the dataset sentence by sentence (unlike the word_language_model.py example, where the dataset is processed as a single vector). Of course, you could use the {RNN,LSTM,GRU}Cell implementations and pick the hidden state computed at the last step before the padding, but then you will be incurring a speed penalty for using the {RNN,LSTM,GRU}Cell implementations.
st116790
Now, I’d like to contribute to making convolution layer twice differentiable. Is there any examples that I can follow for implementing this feature?
st116791
Hi Marvin, One pointer is just other PRs converting old style functions to new: https://github.com/pytorch/pytorch/pull/1507 58 https://github.com/pytorch/pytorch/pull/1426 28 Another is this detailed comment: github.com/pytorch/pytorch Autograd refactor pytorch:master ← pytorch:autograd opened Mar 16, 2017 apaszke +2723 -1585 Primarily, you need to define the backward of ConvNdBackward as ConvNd, i think.
st116792
Hi @smth, I have found current master ConvNd is using ConvNd = torch._C._functions.ConvNd in torch.nn.functional.py, so I can not follow the same things like : https://github.com/pytorch/pytorch/pull/1507 27. Finally, I found the core function that should be modified is ConvBackward::apply in torch.csrc.autograd.functions.convolution.cpp. So I have no idea how to convert the old style functions to new ones.
st116793
Hi, Did you worked out all the math of what is the backward of the backward of a convolution ? Intuitively I would guess it corresponds to a regular conv with modified parameters? More explicitely, if your forward is: out = conv2d(input, weight, bias, stride, padding, dilation, groups) Then the backward can be writen as: gradInput = conv_transpose2d(gradOuput, weight, bias, new_stride, new_padding, new_output_paddin, new_groups, new_dilation) Where all the new_* parameters are computed given the parameters from the original conv. Now you would need the following: gradGradOutput = conv2d(gradGradInput, weight, bias, new_new_stride, new_new_padding, new_new_dilation, new_new_groups) where the new_new_* parameters are a function of the new_* parameters (and thus the original parameters). If you have these, I can help you to add this feature.
st116794
Hi Marvin, I think a lot of the mathematics are coded up already in https://github.com/pytorch/pytorch/blob/master/torch/nn/_functions/conv.py 52 in particular, the sizes should be there. The main things to do are probably figure out how to optionally call forward with _cudnn_info instead of all the details, and apply that to grad_output in _grad_input and _grad_output instead. (Or make that a separate class and give back the info for the second derivative? I have not actually looked at it enough to be able to get it out.) do the usual @staticmethod and self → ctx business. In terms of arguments I think the derivative of output w.r.t. input is a ConvND with transpose “flipped”, stride same, the derivative of output w.r.t. filter is the ConvND of input with grad_output, dilation is the stride of the forward (based on the intuition that we need adjoints, maybe the other way round, too), the derivative of output w.r.t. bias should be something like it is for linear. The definition of transpose seems to be so that you don’t need to reverse the filter or things like that. Best regards Thomas
st116795
So the problem with ConvNd is that all the logic is in cpp, so the task of adding support for grad of grad is purely a cpp thing. We didn’t do it for any ops right now so I can’t show you a ready PR/implementation. The code @tom pointed to is not used anymore and should be removed.
st116796
Hi all, I have commit a PR https://github.com/pytorch/pytorch/pull/1569 26. I am not sure about the correctness, so hope for your discussion.
st116797
Hi, all I have problem doing tensor transpose for cuda tensors. std::unique_ptr<Tensor> tp(weight->newTranspose(2, 3)); But when I use the code like above. It raise an RuntimeError. So how can I do transpose to the cuda tensor?
st116798
Using nn.ConvTransposed2d with dilation still throws RuntimeError: unsupported ConvNd parameters
st116799
Hi, Dilated transposed convolutions are not supported by our backends (THNN and THCUNN). I think that if you use cudnn it would work though, but not 100% sure.
st116800
I need to reshape an Variable (named as W) containing a cuda Tensor. I failed to use the transpose function offered by torch because i need to change the order of each element by a pre-defined method. So, I use the torch.cat function as follows: PW=torch.cat([W[idx] for idx in p],0) in which p is an array containing the new order. It turns to be very slow. Is it possible to be speeded up?
st116801
sorry, I didn’t describe my problem clear. W is a Variable containing a torch.Cuda.FloatTensor of size 100, for example. For simplicity let us say W contains 100 elements, i.e., W[0],W[1] …and W[99]. Now I need to produce a new Variable, which contains elements from W, but in a totally different order. Thank you.
st116802
One observation: allocation in cuda is a sync point, which will be slow. If you can somehow create the permuted variable once, before any loop, and simply copy the permuted values across, without allocation, each iteration, that might speed things up?
st116803
Ho, Then PW = W.index_select(0, p), where, if W is a torch.cuda.XXXXTensor(), p has to be a torch.cuda.LongTensor. If you already have some memory allocated for PW, you can use torch.index_select(W, 0, p, out=PW).
st116804
I use this script 185 to finetune inception_v3 model on a custom dataset. The script already supports AlexNet and VGGNet. However, when finetune with pretrained inception_v3 model, there is an error: python main.py 9 -a inception_v3 -b 16 --lr 0.01 --pretrained data => using pre-trained model 'inception_v3’ Traceback (most recent call last): File “main.py 9”, line 352, in main() File “main.py 9”, line 194, in main train(train_loader, model, criterion, optimizer, epoch) File “main.py 9”, line 231, in train output = model(input_var) 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/parallel/data_parallel.py”, line 59, in forward return self.module(*inputs[0], **kwargs[0]) File “/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py”, line 206, in call result = self.forward(*input, **kwargs) File “main.py 9”, line 104, in forward f = self.features(x) 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/container.py”, line 64, in forward input = module(input) 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/torchvision/models/inception.py”, line 311, in forward x = self.fc(x) 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()) RuntimeError: size mismatch at /b/wheel/pytorch-src/torch/lib/THC/generic/THCTensorMathBlas.cu:243 Has anyone finetuned inception_v3 successfully?
st116805
Here’s a recent discussion. Also, someone just released this 886, which finetunes any network from the model zoo.
st116806
@panovr have you identified what was causing the error? Am running into the same error message using the pretrained VGG16.
st116807
ah - in my case it was just a silly error with giving in images in incorrect size…
st116808
import torch.nn as nn from torch.autograd import Variable import unicodedata import string import torch,ipdb import torch.nn.functional as F from envs.nn_env import NnEnv class RNN(nn.Module): def __init__(self, num_hyperparams=4, hidden_size = 20, num_layers=3): super(RNN, self).__init__() self.hidden_size=hidden_size self.num_layers=num_layers self.rnn = nn.LSTM(input_size=num_hyperparams, hidden_size=hidden_size, num_layers=num_layers) self.affine1 = nn.Linear(hidden_size, num_hyperparams) def forward(self, input): output, self.h = self.rnn(input, (self.h, self.c)) output = output.view(-1, output.size(2)) output = affine1(output) return F.softmax(output) def initHidden(self): batch = 1 self.h = Variable(torch.randn(self.num_layers, batch, self.hidden_size)) # (num_layers, batch, hidden_size) self.c = Variable(torch.randn(self.num_layers, batch, self.hidden_size)) def select_action(state): state = torch.from_numpy(state) probs = rnn(state.resize_(1,1,4)) action = probs.multinomial() policy.saved_actions.append(action) return action.data if __name__ == '__main__': # hyperparameters for rnn n_hidden = 128 num_hyperparams=4 rnn = RNN(num_hyperparams, n_hidden, num_hyperparams) # values for the architecture of cnn sampled num_layers=2 num_hyperparams_per_layer=4 num_episodes=8 for i in range(num_episodes): # create an environment env = NnEnv() rnn.initHidden() observation = env.reset() done=False while not done: # forward through the rnn action = select_action(observation) ipdb.set_trace() observation, reward, done, info = env.step(action) policy.rewards.append(reward) Error: Traceback (most recent call last): File "rnn.py", line 57, in <module> action = select_action(observation) File "rnn.py", line 31, in select_action probs = rnn(state.resize_(1,1,4)) File "/Users/abhishek/.virtualenvs/nn_search/lib/python2.7/site-packages/torch/_ result = self.forward(*input, **kwargs) File "rnn.py", line 19, in forward output, self.h = self.rnn(input, (self.h, self.c)) File "/Users/abhishek/.virtualenvs/nn_search/lib/python2.7/site-packages/torch/_ result = self.forward(*input, **kwargs) File "/Users/abhishek/.virtualenvs/nn_search/lib/python2.7/site-packages/torch/d output, hidden = func(input, self.all_weights, hx) File "/Users/abhishek/.virtualenvs/nn_search/lib/python2.7/site-packages/torch/d if cudnn.is_acceptable(input.data): AttributeError: 'torch.DoubleTensor' object has no attribute 'data' Not sure if the way I resize it is correct.
st116809
No attribute data means, its expecting an autograd.Variable, and youre feeding it a torch.Tensor, so just wrap your torch.Tensor in an autograd.Variable, and should work ok. (thinkgin about this, it seems like the modules themselves could handle this conversion themsevles. but, for now, they dont…)
st116810
Note to maintainers: might be interseting to add a dummy property to Tensor, that simply does: @property def data(self): print('data is a property of autograd.Variable. Please wrap your Tensor in autograd.Varaible, and try again') # throw exception or something here
st116811
PR for interpretable error message here: https://github.com/pytorch/pytorch/pull/2058 47
st116812
While Running Pytorch Transfer learning tutorial I am getting following error. Please tell the problem Traceback (most recent call last): File "transfer_learning_tutorial.py", line 121, in <module> inputs, classes = next(iter(dset_loaders['train'])) File "/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py", line 201, in __next__ return self._process_next_batch(batch) File "/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py", line 221, in _process_next_batch raise batch.exc_type(batch.exc_msg) AttributeError: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py", line 40, in _worker_loop samples = collate_fn([dataset[i] for i in batch_indices]) File "build/bdist.linux-x86_64/egg/torchvision/datasets/folder.py", line 116, in __getitem__ img = self.loader(path) File "build/bdist.linux-x86_64/egg/torchvision/datasets/folder.py", line 63, in default_loader return pil_loader(path) File "build/bdist.linux-x86_64/egg/torchvision/datasets/folder.py", line 45, in pil_loader with Image.open(f) as img: File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 528, in __getattr__ raise AttributeError(name) AttributeError: __exit__
st116813
Something is wrong with loading images. Either your Pillow package is outdated or your images are not at right location.
st116814
if it was me, to go fruther with this, I might: hack the library file at “build/bdist.linux-x86_64/egg/torchvision/datasets/folder.py”, line 116, to print the value of path try loading this file using Pillow.Image directly => if it’s a pillow issue, then, it’s probably out of scope for pytorch otherwise, report back to pytorch that pillow itself is working ok, yada yada
st116815
Hi, I wanted to write an RNN from scratch using the pytorch cuda capabilities and I ran some preliminary tests to compare the speed of the CPU vs GPU. The task is very simple and consists of a for loop mimicking the update of the internal state x in an RNN with recurrent weight matrix J. I’m using a Quadro K620 with cuda 8.0. When the size of x is N=1000 there seems to be a trade-off, with the GPU implementation consistently getting slower when the number of iterations increases (I ran some other tests with different sizes of the J matrix and this behaviour seems pretty systematic). This is an example of running times I get when running the enclosed script: cpu: [0.010117292404174805, 0.058980703353881836, 0.45785975456237793, 4.512230634689331] gpu: [0.0019445419311523438, 0.05474495887756348, 0.7503962516784668, 7.011191129684448] I’d really appreciate some help on this. Thanks in advance. The test script is the following: import numpy as np import torch as tr import math import time GPUID = 0 tr.cuda.set_device(GPUID) N = 1000 J = tr.randn(N,N) x = tr.randn(N) r = tr.randn(N) y = tr.randn(N) Jn = J.numpy() xn = x.numpy() rn = r.numpy() yn = y.numpy() cputimes = [] for sampl in (100, 1000, 10000, 100000): start = time.time() for i in xrange(sampl): rn = np.tanh(xn) xn = Jn.dot(xn); end = time.time() cputimes.append(end-start) print(cputimes) Jc = J.cuda() xc = x.cuda() rc = r.cuda() yc = y.cuda() gputimes = [] for sampl in (100, 1000, 10000, 100000): start = time.time() for i in xrange(sampl): rc = tr.tanh(xc) xc = Jc.mv(xc); end = time.time() gputimes.append(end-start) print(gputimes)
st116816
I experienced the same thing. A very simple network runs faster in CPU than GPU.
st116817
Its totally normal that rnns run fast on cpus, compared to gpus. they send lots of teeny-tiny kernel launches, and the gpu cores spend all their time waiting for the next batch to arrive…
st116818
By the way, you’ll get faster per-example times by increasing the batch size, at the expense that effective learning rate will probably decrease.
st116819
I have a dataset where features are of different types, such as float32 and str (categorical). I know that to represent str features, I should embed them first. In fact, each str feature can be considered as a sentence with specific number of vocabs and I need to define their index with torch.LongTensor. However, it’s not clear how to define the forward method. This seems overly complicated! I’m basically looking for an equivalent method like tf.feature_column, tf.feature_column.categorical_column_with_vocabulary_list or tf.feature_column.categorical_column_with_hash_bucket.
st116820
I’ve run into memory leak issues when running various projects (semantic segmentation w/ CUDA 3 and CPU-only RL 3) after building PyTorch from source. This has been an issue for me (Ubuntu 14.04, CUDA 8.0, Python 3.6 via conda) and a colleague (Ubuntu 16.04, no CUDA, Python 3.6 via conda). I’ve tried building from master from several commits, and from the last tagged release (0.1.12), but no difference. Using the conda install works absolutely fine. Any ideas on what to look out for/help me provide more information?
st116821
Could you share a script to replicate the memory leak, please ? I’ve had some issues like that as well, but not quite sure it comes from compiling from sources. I’d be interested to see if we can pin point what leaks.
st116822
Unfortunately I don’t have a minimal script to reproduce it, but have experienced when running the code in the open source projects that I’ve linked above. They are relatively complex, although the segmentation code is not so bad.
st116823
Hi, I recently used pytorch to implement a CNN for text classification. My validation accuracy looks weird that there are peaks appearing at the beginning of each epoch, which I didn’t observe in my tensorflow implementation. DId anyone meet the same issue before? Thanks Screen Shot 2017-07-06 at 10.26.22 PM.png1810×874 42.6 KB
st116824
That does not look like a weird behaviour at all… I’m admitting that you are not randomising the validation set (sample wise or batch wise) when you score your model after each epoch. Therefore, you should probably have somewhat easier examples that your model can express better art the beginning of each epoch. it is fairly common to experience some repetitive patterns in the training and/or validation loss if you keep the order of your sets throughout the train. I think you should not worry about this, as your model seems to be learning something.
st116825
Apparently GRUCells do not accept CUDA tensors, while GRU RNN do. Is it a known problem or is there something I am doing wrong?
st116826
For me, this works: cell = torch.nn.GRUCell(5,5).cuda() h = torch.autograd.Variable(torch.rand(1,5)).cuda() x = torch.autograd.Variable(torch.rand(1,5)).cuda() cell(x,h) `Variable containing: 0.3778 -0.1668 0.7313 0.4934 0.0283 [torch.cuda.FloatTensor of size 1x5 (GPU 0)]
st116827
I am trying to modify some code that uses GRU rnn to use GRUCells instead (I need to experiment on the output of the cells). In the following code I have variables output and hidden that are given to the GRU rnn without problems; when I try to modify them to sue GRUCell, it does not work unless I call .cpu(). Here is what I do and the error message: >>> output.size() torch.Size([1, 1, 256]) >>> hidden.size() torch.Size([1, 1, 256]) >>> self.gru GRU(256, 256) >>> k=self.gru(output, hidden) #no errors >>> cell = torch.nn.GRUCell(256,256) >>> o = output.view(1,-1) >>> h = output.view(1,-1) >>> o.size() torch.Size([1, 256]) >>> h.size() torch.Size([1, 256]) >>> k = cell(o.cpu(), h.cpu()) #no errors >>> k = cell(o, h) Traceback (most recent call last): 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) As you see with .cpu() it works, if I leave them as cuda tensor this error is raised.
st116828
You probably forgot to also send your cell module’s parameters to GPU storage. This should work: cell = cell.cuda() k = cell(o, h)
st116829
I defined a type of loss and encounter *** RuntimeError: a leaf Variable that requires grad has been used in an in-place operation. The loss is defined as follows def SMLoss(feature):     co=feature.mm(feature.t())     l=co.diag().resize(batch_size,1).sqrt()    S=co.div(l.mm(l.t()))+1    W=S.resize(le,1)    P=S.div(S.sum(1).mm(torch.autograd.Variable(torch.ones(1,batch_size)).cuda()))     VP=P.resize(le,1)     VPT=torch.cat(P.t().unsqueeze(2),0)    tmp=VP.mm(VPT.t())     smloss=torch.autograd.Variable(torch.zeros(le,le).cuda(),requires_grad=True)    for u in range(0,le):         for v in range(0,le):               smloss[u,v]=tmp[u,v]*((W[p[u,v]]-W[q[u,v]])**2)     return smloss.sum() in which p and q are index-maps pre-defined. Can someone give me a help to solve the problem, thx a lot
st116830
I will have two GPUs to train a model, but one is a NVIDIA740 GPU, and another is NVIDIA1080 GPU, I wonder if pyTorch can work well in parallel model on these GPUs? Thank you!
st116831
I have a network in which I want to update parameters of only a fixed set of layers (say layer3, layer7). So we basically set the requires_grad attribute to False for parameters of other layers. Now, is is okay to construct optimizer as optimizer = optim.SGD(net.parameters(), lr=0.01) or do I have to make an iterable of layer3, layer7 parameters as optimizer = optim.SGD([net.layer3.parameters(),net.layer7.parameters()], lr = 0.01) . I would assume that first option should be fine because gradients are not being computed for other layers in any case. So is there any difference ?
st116832
I’d think this should work fine optimizer = optim.SGD(list(net.layer3.parameters()) + list(net.layer7.parameters()), lr = 0.01) (despite the extra computation if you didn’t do require_grad=False)
st116833
I’m running cuda 7.5 on ubuntu 16.04. For some reason it hangs on the first call to .cuda() for a few minutes. I’ve looked at some of the other related posts, but haven’t found anything which helps me diagnose the issue. Would anyone be able to give me some pointers? Is there any extra information which I could provide which would be useful? Thanks! Ben
st116834
Some more info which may be helpful: I’m running a GTX 1060 (Pascal) with cuda 7.5. I’ve noticed that the first call to .cuda() causes GPU memory usage to rise to about 200MB before returning. Also, python maxes out a CPU core and eats about a gig of RAM until it returns. Don’t know if it makes a difference, but I installed PyTorch via conda.
st116835
Another note: All of these issues have been present while using Python 2.7. I upgraded PyTorch and Cuda to Cuda 8.0 and the issues persist, but it works fine with Python 3.5.
st116836
1060 needs CUDA 8.0 atleast to not invoke CUDA’s JIT compilation of kernels. If you use the CUDA 8.0 packages you should be good (regardless of the python version)
st116837
I have written a simple model(only the horizontal part of above model) and trained the parameters. Now, I want to apply the simple model’s parameters to the above model(a different one). The complicated model can’t inherit from the simple one(or use simple one as a part), So,is there any way to do this work?
st116838
This will only work if each of the horizontal layers in your diagram are identical. If so then you can save the trained model parameters: torch.save(simple_model.state_dict(), "path/to/file.pth") and then load them into each of the horizontal layers: filepath = "path/to/file.pth" complex_model = [network() for i in range(num_layers)] for layer in complex_model: layer.load_state_dict( torch.load( filepath )) where network is the model you originally trained.
st116839
When debugging my code, I found that torch.rand() sometimes can generate very big numbers. A fraction of my code: u1 = Variable(torch.rand(mu.size()).cuda()) u2 = Variable(torch.rand(mu.size()).cuda()) if mu.data.dim() == 6: print(‘u1’, u1.data.max()) print(torch.rand(1)) Printed result (I use two GPUs): u1 4293885184.0 u1 4293885184.0 1.6911e+09 [torch.FloatTensor of size 1] 1.6911e+09 [torch.FloatTensor of size 1] My pytorch is compiled 3 weeks ago. Is it the problem of torch.rand()? Thanks for help!
st116840
print(torch.rand(1)) 1.6911e+09 [torch.FloatTensor of size 1] That’s the weirdest bug I have ever seen
st116841
Yeah, it’s very strange. However, I avoided this problem by using a single GPU (by setting the nn.DataParallel device_ids = [0]). I will update pytorch and try multi GPU again.
st116842
Things have changed (recently?) with .creator becoming .grad_fn and other stuff disappearing. Is there a documentation somewhere about the precise implementation of the autograd graph? This should probably be the right place, but the current content is quite succint: How autograd encodes the history 13 Ideally, a function in the documentation to visit all the nodes of the said graph would be helpful. That would cover well how all this is done.
st116843
The following is copied from github. I encounter this problem when I am trying to implement seq2seq to familiarize with this new framework. This issue seems related to parameters sharing in mini-batch. I setup a dummy training set with only one mini-batch. This mini-batch has 3 data entries in it. All with the same input, and different outputs: training_data = [ [[[4,5,1,7,8],[4,5,1,7,8],[4,5,1,7,8]], (input 1) [[0],[0],[0]], (input 2) [[1],[3],[5]]] (target) ] In theory, the model will never learn this data because the contradiction. However, the loss reach near 0 after only a few hundred epochs. But if I split 3 data entries into 3 mini-batch, the model will not learn the data set which should be the correct result. So the model must be keeping different set of parameter for each position in mini-batch? And the parameters are not updated to be the same after each mini-batch forward-backward? Can someone tell me if I misunderstood something? import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import torch.optim as optim training_data = [ [[[4,5,1,7,8],[4,5,1,7,8],[4,5,1,7,8]], [[0],[0],[0]], [[1],[3],[5]]] ] def prepare_sequence(all_seq): return autograd.Variable(torch.LongTensor(all_seq)).cuda() class Seq2seqLSTM(nn.Module): def __init__(self, vocab_size, target_size, embed_dim, hidden_dim, num_layers): super(Seq2seqLSTM, self).__init__() self.hidden_dim = hidden_dim self.embed_dim = embed_dim self.vocab_size = vocab_size self.target_size = target_size self.num_layers = num_layers self.word_embeddings = nn.Embedding(vocab_size, embed_dim) self.encoder = nn.LSTM(embed_dim, hidden_dim, num_layers) self.decoder = nn.LSTM(embed_dim, hidden_dim, num_layers) self.curr_hidden = None self.hidden2tag = nn.Linear(hidden_dim, target_size) def init_hidden(self, batch_size): return (autograd.Variable(torch.zeros(self.num_layers, batch_size, self.hidden_dim)).cuda(), autograd.Variable(torch.zeros(self.num_layers, batch_size, self.hidden_dim)).cuda()) def forward(self, enc_seq, dec_seq): batch_size = enc_seq.size()[0] self.curr_hidden = self.init_hidden(batch_size) enc_embeds = self.word_embeddings(enc_seq) dec_embeds = self.word_embeddings(dec_seq) enc_out, self.curr_hidden = self.encoder( enc_embeds.view(-1, batch_size, self.embed_dim), self.curr_hidden) dec_out, self.curr_hidden = self.decoder( dec_embeds.view(-1, batch_size, self.embed_dim), self.curr_hidden) tag_space = self.hidden2tag(dec_out.view(batch_size * len(dec_out), -1)) tag_scores = F.log_softmax(tag_space) return tag_scores EMBED_DIM = 10 HIDDEN_DIM = 10 VOCAB_SIZE = 10 TARGET_SIZE = 10 NUM_LAYERS = 2 model = Seq2seqLSTM(VOCAB_SIZE, TARGET_SIZE, EMBED_DIM, HIDDEN_DIM, NUM_LAYERS).cuda() loss_function = nn.NLLLoss() optimizer = optim.Adam(model.parameters()) print model for epoch in range(1000): one_batch = map(lambda x:prepare_sequence(x), training_data[epoch%len(training_data)]) enc_inp = one_batch[0] dec_inp = one_batch[1] target = one_batch[2] model.zero_grad() tag_scores = model(enc_inp, dec_inp) loss = loss_function(tag_scores, target.view(-1)) loss.backward() optimizer.step() print loss
st116844
I mean I want to use numbers such as 1 integer bits with 15 fractional bits,are there any methods could help? Thanks.
st116845
I try to use torch.cuda API to retrieve details of GPUs (e.g. memory), but i cannot find related API. How can I get the GPU information using pytorch? thanks
st116846
@SherlockLiao: I guess the question was about accessing GPU usage inside python code. If that’s the case, you can try nvidia-ml-py 177 or simply run subprocess and parse the output as shown here 126. I am not aware of any torch.cuda API for doing this.
st116847
@SelvamArul, thanks, that is the case. In nvidia-smi, the gpu id is different from deviceQuery, and i need know which gpu is used in pytorch by checking the memory.
st116848
Hi, As leveraging python ecosystem seems one of the main reasons for switching to pytorch from Torch 7, would you provide guidance to visually overseeing training/evaluating with 3rd party Python libraries that is hard to do in pure Torch 7 ? For example, Something like the tensorboard that can be accessed remotely (Say, I have to run training on a remote machine with gui desktop disabled so I may want to oversee the progress from my local machine) The cool panel shown like: https://deepmind.com/blog/reinforcement-learning-unsupervised-auxiliary-tasks/ 263 Sorry if this topic is out the scope of this forum
st116849
@pengsun there are some scripts provided in this thread: https://www.reddit.com/r/MachineLearning/comments/5pbdnj/d_visualizing_training_with_pytorch/ 805 Particularly, look at: https://github.com/TeamHG-Memex/tensorboard_logger 471
st116850
@pengsun, tensor-board bindings for PyTorch and Torch will be released roughly next week.
st116851
Hi, noob question here - might be especially relevant for people moving over from TensorFlow? I just wonder if anyone has got Crayon working for multi-threads? I can’t figure it out? I keep getting this error Traceback (most recent call last): File "/home/ajay/anaconda3/envs/pyphi/lib/python3.6/multiprocessing/process.py", line 249, in _bootstrap self.run() File "/home/ajay/anaconda3/envs/pyphi/lib/python3.6/multiprocessing/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "/home/ajay/PythonProjects/PyT_Neural_Arch_Search_v1_2/train_v1.py", line 201, in train foo.get_scalar_values("Mean Reward") File "/home/ajay/anaconda3/envs/pyphi/lib/python3.6/site-packages/pycrayon/crayon.py", line 167, in get_scalar_values return json.loads(r.text) File "/home/ajay/anaconda3/envs/pyphi/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/home/ajay/anaconda3/envs/pyphi/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/home/ajay/anaconda3/envs/pyphi/lib/python3.6/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) It works fine through when I run the following from the interpreter, from pycrayon import CrayonClient cc = CrayonClient( hostname="http://127.0.1.1" , port=8889) foo = cc.create_experiment("train_" + str(rank)) foo.add_scalar_value("Mean Reward", mean_reward, step = episode_count) foo.add_scalar_value("Max Reward" , max_reward, step = episode_count) foo.get_scalar_values("Mean Reward") foo.get_scalar_values("Max Reward") Thanks for your help
st116852
Nevermind, it works without the extra lines, foo.get_scalar_values("Mean Reward") foo.get_scalar_values("Max Reward") Also I needed to give distinct date time’s for each of the threads, cc = CrayonClient( hostname="http://127.0.1.1" , port=8889) exp_name = "train_" + str(rank) + "_" + datetime.now().strftime('train_%m-%d_%H-%M') # prevents server errors ?? foo = cc.create_experiment(exp_name)
st116853
Hi everyone, I have met a problem when loading my own dataset, trainset = torchvision.datasets.ImageFolder(root='../dataset/', transform=transforms.Compose([ transforms.ToTensor(), transforms.Scale((64,64)) ])) trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2) data = iter(trainloader) imgs = data.next()[0] And I got the error: AttributeError: Traceback (most recent call last): File “/usr/local/lib/python2.7/dist-packages/torch/utils/data/dataloader.py”, line 41, in _worker_loop samples = collate_fn([dataset[i] for i in batch_indices]) File “/usr/local/lib/python2.7/dist-packages/torchvision/datasets/folder.py”, line 118, in getitem img = self.transform(img) File “/usr/local/lib/python2.7/dist-packages/torchvision/transforms.py”, line 34, in call img = t(img) File “/usr/local/lib/python2.7/dist-packages/torchvision/transforms.py”, line 199, in call return img.resize(self.size, self.interpolation) AttributeError: ‘torch.FloatTensor’ object has no attribute ‘resize’ any idea? thanks.
st116854
Hi, there are two types of transforms: Those that take PIL images as input and those that take Tensors. Scale takes an image (which has a resize method). Note that in order to be able to pass a tuple to the Scale transform, you need to install from the https://github.com/pytorch/vision 276 master branch. Best regards Thomas
st116855
Considering that random is not 16 implemented yet for GPU , my question is: how to create uniformly distributed tensor on GPU?
st116856
For many purposes, the cuda.FloatTensor’s uniform_ method will do: torch.cuda.FloatTensor(10).uniform_() works. Best regards Thomas
st116857
Hi, so I am trying to load pretrained vgg19 in an interactive session within a GPU cluster. I get this permission error while trying the following: Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import torchvision.models as models >>> import torch >>> vgg19 = models.vgg19(pretrained=True) Downloading: "https://download.pytorch.org/models/vgg19-dcbb9e9d.pth" to /.torch/models/vgg19-dcbb9e9d.pth 100%|#########################################################################################################################################| 574673361/574673361 [00:03<00:00, 162997989.65it/s] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/torchvision/models/vgg.py", line 141, in vgg19 model.load_state_dict(model_zoo.load_url(model_urls['vgg19'])) File "/usr/local/lib/python2.7/dist-packages/torch/utils/model_zoo.py", line 56, in load_url _download_url_to_file(url, cached_file, hash_prefix) File "/usr/local/lib/python2.7/dist-packages/torch/utils/model_zoo.py", line 85, in _download_url_to_file shutil.move(f.name, dst) File "/usr/lib/python2.7/shutil.py", line 302, in move copy2(src, real_dst) File "/usr/lib/python2.7/shutil.py", line 130, in copy2 copyfile(src, dst) File "/usr/lib/python2.7/shutil.py", line 83, in copyfile with open(dst, 'wb') as fdst: IOError: [Errno 13] Permission denied: '/.torch/models/vgg19-dcbb9e9d.pth' How can I possibly avoid this issue?
st116858
seems like it’s trying to store ito /.torch rahter than ~/.torch, ie prefixed with the value of $HOME. Is it something like, for some reason $HOME isnt defined?
st116859
I see what’s going on. According to http://pytorch.org/docs/master/model_zoo.html?highlight=torch_home 69 at torch.utils.model_zoo “The default value of model_dir is $TORCH_HOME/models where $TORCH_HOME defaults to ~/.torch. The default directory can be overriden with the $TORCH_MODEL_ZOO environment variable.” Now if I want to load pretrained model directly from torch.utils.model_zoo, then I can use model_dir argument like loaded_state_dict = model_zoo.load_url(model_urls['vgg19'],'/code/cs231n/model') but in this case I am trying to do so through torchvision.models. In this case, how I might override the $TORCH_MODEL_ZOO environment variable? I mean where do i need to do so ? Thanks!
st116860
Hello, I am trying to implement multi-GPU training and testing and I am running it through jupyter notebook. This may be a driver specific issue in my local machine as I dont seem to have this problem while running it on AWS p2.x8large instances. EDIT : Just found another case within the aws instance where the gpu does not get free , is there any way to force the gpu to be free within python itself ? I also noticed that when I load from the same dataset using the same set of gpus from two different processes they both become zombie processes I make the model parallel by doing nn.DataParallel(model,device_ids=[0,1]).cuda() ... and then pass the input and label to cuda as input = input.cuda() label=label.cuda() But when I interrupt the process and restart it seems like GPU memory is not free as nvidia-smi shows that portions of the GPU are still occupied, running the process again returns an out of memory error. the entire code can be found here https://github.com/gtm2122/viewclassification/blob/master/view_testls/nndev.py 4 the relevant lines that use DataParallel are and sending to cuda are line 264 and line 292 in model_pip.train_model() and in model_pip.test() they are in line 405 and 415 from my jupyter notebook this is my usage res = models.resnet18(pretrained=False) res.fc = nn.Linear(res.fc.in_features,7) obj = model_pip(model_in=res,scale=True,batch_size=120,use_gpu=True,gpu=[0,1],data_path=datapath,lr=0.1,lr_decay_epoch=30) model = obj.train_model(epochs=50) obj.store_model(f_name=savepath) del(obj) res = models.resnet18(pretrained=False) res.fc = nn.Linear(res.fc.in_features,7) obj = model_pip(model_in=res,scale=True,batch_size=120,use_gpu=True,gpu=[0,1],data_path=datapath,lr=0.1,lr_decay_epoch=30) obj.load_model(filename=savepath) obj.test(...)
st116861
If you are using an older version of pytorch I think I remember there being an issue with that so upgrading pytorch newest version would help. If not and in addition to that when you interrupt training use Ctrl C to end your training and that should kill the processes properly and free up the gpu memory
st116862
In the lua version of LSTM (https://github.com/Element-Research/rnn#rnn.LSTM 1) there was a rho parameter indicating the amount of backprob trough time (BPTT). Where is this parameter in pytorch version of LSTM? The nn.LSTM(inputSize, outputSize, [rho]) constructor takes 3 arguments: inputSize : a number specifying the size of the input; outputSize : a number specifying the size of the output; rho : the maximum amount of backpropagation steps to take back in time. Limits the number of previous steps kept in memory. Defaults to 9999.
st116863
@smth Ok, so I should always provide the full sequence that I want to train? something Like [batch_size,rho,input_size] (when the batch_is first)
st116864
I am using DataParallel model and multithreading for loading the input and ground truth. I am using python queue for synchronizing between the main thread and the loader threads. The code looks like the following pseudocode. import queue Q_dirs = queue.Queue() Q_tensors = queue.Queue( maxsize=4 ) model = th.nn.DataParallel(model, device_ids=cuda_devices, output_device=cuda_devices[0] ).cuda() def loader(): global Q_dirs global Q_tensors while True: list_dirs = Q_dirs.get() tensor_data = {} # for dir in list_dirs read tensor and load in tensor_data. # tensor_data['features'] = features # tensor_data['q_gt'] = q_gt Q_tensors.put(tensor_data) # in main thread for i in range(no_of_batches): for j in range( current_batch_size ): list_dirs.append ( dirs[ i*bs + j ] ) Q_dirs.put(list_dirs) for i in bar(range(no_of_batches)): tensor_data = Q_tensors.get() features = tensor_data['features'] q_gt = tensor_data['q_gt'] input = Variable( features, requires_grad=False ) q_gt = Variable( q_gt, requires_grad=False) q_pred = model(input) loaders = [] for i in range(4): loaders.append( T.Thread(name='L'+str(i), target=loader) ) for l in loaders: l.start() But the Dataparallel model hangs in the forward pass of the model. At the point when the model hangs, I could see only one of the GPU cards (the card that I set as output_device when I create the DataParallel) has 100% utilization and all other cards have 0% utilization. This happens at variuos epochs and not consistant always. I suspect that there is wrong race condiiton in my code. But given that I am using only thread-safe python 3.5 Queues for synchrnizatoin, I am puzzled about the issue. Could someone throw some light on what is going on here? Some additional information about my system. OS: Ubuntu 16.04.2 LTS python: 3.5 CUDA: 8.0 PyTorch version: 0.1.11_4
st116865
upgrade pytorch to latest version when using CUDA with multiprocessing, you have to use the spawn or forkserver method as mentioned in http://pytorch.org/docs/master/notes/multiprocessing.html#sharing-cuda-tensors 127 I think (2) is the reason for your deadlock.
st116866
@smth Thanks for your suggestions. I am upgrading PyTorch to the latest version and will try the code once again. But just for clarification, I am not using multiprocessing. I using multi-threading. I have 4 threads(updated the pseudocode I posted to reflect this) that loads the next batches while the network is processing the current batch. I am doing this to avoid the time the network has to wait while the data is being loaded. And as I said, I am using queue.Queue which is thread-safe to synchronize between loading threads and the main thread(the network thread).
st116867
@smth After updating PyTorch to the latest version, the issue is not appearing. But I am not very confident that the issue will never show up again. I will use the network frequently in the next days and I will update if I see the issue again. Thanks for your suggestions