id
stringlengths
3
8
text
stringlengths
1
115k
st103800
Hi. This is probably not a common use case, but I am having this issue now. I try to understand how the network is going to update when there are multiple gradients. In my case, given 2 networks: a_network and b_network, the loss function is defined as loss = b - a where b is computed by b_network (using outputs from a_network) and a is computed by a_network. We also need to perform sampling: (1) sampling a_network M times (2) for each samples from a_network, sampling b_network N times The Pseudo-code (sorry that the actual code is very large): #b_network is pre-trained and no updates during this training for param in b_network.parameters(): param.requires_grad = False optimizer.zero_grad() a_sampling_times = M b_sampling_times = N #do sampling with a_network for _ in range(a_sampling_times): a_network_outputs = a_network(inputs) a_network_samples = a_network_sampling(a_network_outputs) a_network_loss = a_network_compute_loss(a_network_outputs) #do sampling with b_network for b_sampling_time in range(b_sampling_times): b_network_outputs = b_network(a_network_outputs) b_network_loss = b_network_compute_loss(b_network_outputs, a_network_outputs) #the loss function loss = b_network_loss - a_network_loss #compute gradients if b_sampling_time == b_sampling_times: loss.backward() else: loss.backward(retain_graph=True) #updates optimizer.step() With retain_graph=True, the gradients of a_network_loss will be computed N times. What will happen when optimizer.step() is called? How are the network’s parameters going to be updated with those N gradients? Thanks
st103801
By default the gradients will be accumulated. If you call N times backward on your output, the N gradients will be summed in for your parameters. w = nn.Parameter(torch.ones(1)) x = torch.ones(1) * 2 for _ in range(3): output = x * w output.backward() print(w.grad) > tensor([2.]) > tensor([4.]) > tensor([6.]) If you need to compute the gradients several times, you might scale your learning rate a bit down, but of course this depends on your use case, the model etc.
st103802
I am wondering why the kernel size of 4 is being used in DCGAN, we could use any odd number kernel for the better approximation, and zero pad the edges.
st103803
it was to match some output dimensions from Theano code of Alec Radford. No other reason.
st103804
l want to finetune a net.I made the following settings. Modified the last three layers of fc net.fc6 = nn.Linear(8192, 4096) net.fc7 = nn.Linear(4096, 4096) net.fc8 = nn.Linear(4096, 74) optimizer = optim.SGD([{‘params’: net.fc6},{‘params’: net.fc7},{‘params’: net.fc8}], lr=0.0003, momentum=0.9) but It was given an error param_group[‘params’] = list(params) TypeError: ‘Linear’ object is not iterable How to optimize multiple fully connected layers?
st103805
I know Giving multiple parameters in optimizer How can i give multiple parameters to the optimizer? fc1 = nn.Linear(784, 500) fc2 = nn.Linear(500, 10) optimizer = torch.optim.SGD([fc1.parameters(), fc2.parameters()], lr=0.01) # This causes an error. In this case, for simplicity, i don’t want to use a class with nn.Module.
st103806
I want to fine tune a classification network.so,I need to make a one-hot label. label = torch.zeros(1,74,dtype=torch.long) //1 batch size 74 categories label = label.scatter_(dim=1,index=torch.LongTensor([[ (0~73) ]]),value=1) print(label) **torch.Size([1, 74])** RuntimeError: multi-target not supported at ClassNLLCriterion.c:22 Offical docs of CrossEntropyLoss : Examples: loss = nn.CrossEntropyLoss() input = torch.randn(3, 5, requires_grad=True) target = torch.empty(3, dtype=torch.long).random_(5) output = loss(input, target) output.backward() print(target.shape) torch.Size([3]) l convert to torch.Size([74]) ValueError: Expected input batch_size (1) to match target batch_size (74). my loss: criterion = torch.nn.CrossEntropyLoss() loss_contrastive = criterion(net_output,label1)
st103807
Solved by ptrblck in post #2 CrossEntropyLoss does not work with one-hot encoded targets. The target dimensions are specified as [batch_size]. Internally the indices are stored. In the example input has a batch size of 3 and provides 5 logits. The target has the same batch size of 3 with random indices.
st103808
CrossEntropyLoss does not work with one-hot encoded targets. The target dimensions are specified as [batch_size]. Internally the indices are stored. In the example input has a batch size of 3 and provides 5 logits. The target has the same batch size of 3 with random indices.
st103809
This question is about best practices for designing subclasses of nn.Module. I am trying to decrease unnecessary coupling in my code. For example, say my network has a Conv2d layer and a Linear layer. The hyperparameters are: size of input image, number of conv. channels, kernel size, stride, number of FC layers. When building the model, I need to know the input size to the Linear layer in advance (as described in this answer 3). The arguments I must pass to initialize the Linear layer are coupled to other hyperparameters: whenever I change some hyperparameters of layers earlier in the chain(for example, image size or stride) I have to (or my code has to) recalculate the value. Presumably this is why there is demand for a Utility function for calculating the shape of a conv output 3. Conversely, the arguments needed to initialize a Conv2d layer are not coupled to hyperparameters earlier in the chain. As a way of reducing coupling when writing custom modules, is it acceptable to move some initialization code from __init__() to forward()? forward() would then look like the pseudocode below. def forward(self, x): if not self.initialized: # Initialize inner modules somehow using the input size self.weights = nn.Parameter(torch.randn(..., x.size(2), x.size(3), ...)) self.initialized = True # Go on to usual forward() function ... What would be the drawbacks of this approach? Are there other approaches to reducing coupling?
st103810
One shortcoming I can think about is that you would need a random forwardpass to create the state_dict in order to pass it to the optimizer. Also the same would apply it you save the trained state_dict, create the model in another script and try to load the state_dict. Your model would be empty until you run a pseudo-forwardpass. I don’t really like the idea. You could evade this by calling the forward in the __init__ method, but that would obviously make your approach useless, since you need to know the shape.
st103811
Thanks @ptrblck for pointing out that shortcoming. There might be some way to work around it by modifying load_state_dict or using placeholder values, but I suppose it will always be better to have __init__ actually initialize the module, not least because that’s what everyone expects. Do you know of any commonly-used approaches to simplify (or make more readable) model-building code? I’m now thinking of something like a helper method which returns the output size of forward given an input size.
st103812
The aspect you would like to simplify is mostly the number of in_features in nn.Linear layers as far as I understand. One way would be to use nn.AdaptiveMaxPool2d 2 or just convolutions. Of course you could try to calculate the shape of in_features using the shape formula for conv layers etc.
st103813
calculate the shape of in_features using the shape formula for conv layers etc. Yes, I suppose I am talking about a way to do that, not specific to nn.Linear. The motivation for my question is I have seen several implementations of experimental network architectures with frustrating (anti)patterns such as magic numbers (e.g. a layer initialized with 1152 neurons as a result of unexplained calculations) user-settable parameters with unnecessary coupling (e.g. a command line parameter --unit-size=1152 which cannot be freely changed in reality, because it is determined by the input image size and other hyperparameters) As a new Pytorch user, I am wondering if there is a “best practices” way to avoid such patterns in my own code, especially when writing custom subclasses of nn.Module. BTW, I see my “helper method” idea is really the same as Carson McNeil’s idea here 5.
st103814
I see the issues. A cleaner way would be to set the in_features as the shape calculations, e.g. in_features=512*7*7. So that it would be clear the last conv layer outputs 512 channels and a volume of spatial size 7x7. Utility function for calculating the shape of a conv output I almost feel like it would be nice if this was just a method of the conv module: pass an input shape, and it returns the formula above. This can be easily done by passing a random input to the conv layer: nn.Conv2d(3, 6, 3, 1, 1)(torch.randn(1, 3, 24, 24)).shape However, you would still need to know the input shape of your image. I’m not sure there is a clean way to achieve the shape inference currently. Maybe someone else has a good idea.
st103815
I just started with PyTorch and tried working my way through the tutorials. When I run the standard neural_networks_tutorial.py I get the following error: Traceback (most recent call last): File "src/pytorch_tests/neural_networks_tutorial.py", line 98, in <module> out = net(input) File "/home/ssudholt/checkouts/pytorch-tests/env/local/lib/python2.7/site-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "src/pytorch_tests/neural_networks_tutorial.py", line 61, in forward x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) File "/home/ssudholt/checkouts/pytorch-tests/env/local/lib/python2.7/site-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "/home/ssudholt/checkouts/pytorch-tests/env/local/lib/python2.7/site-packages/torch/nn/modules/conv.py", line 237, in forward self.padding, self.dilation, self.groups) File "/home/ssudholt/checkouts/pytorch-tests/env/local/lib/python2.7/site-packages/torch/nn/functional.py", line 40, in conv2d return f(input, weight, bias) TypeError: argument 0 is not a Variable I ran the tutorial without any modifications: import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): # Max pooling over a (2, 2) window x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # If the size is a square you can only specify a single number x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = x.view(-1, self.num_flat_features(x)) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x def num_flat_features(self, x): size = x.size()[1:] # all dimensions except the batch dimension num_features = 1 for s in size: num_features *= s return num_features net = Net() net print(net) input = Variable(torch.randn(1, 1, 32, 32)) out = net(input) print(out) PyTorch was installed in a clean virtualenv through pip (version 0.1.12_2). Google did non know anything about this error so I was hoping that maybe someone here can point me in the right direction.
st103816
[bytstander comemnt] Thats pretty weird. Whats ht output of print(input), just before the out = net(input) line? what happens if you insert a new line, just before current line 40, in /home/ssudholt/checkouts/pytorch-tests/env/local/lib/python2.7/site-packages/torch/nn/functional.py, that says print(input), and rerun?
st103817
Thanks for the quick reply. The output in both cases is as I would expect it: Variable containing: (0 ,0 ,.,.) = -0.0318 -0.3270 1.0696 ... 1.0775 -0.6827 -0.2995 2.4808 0.6244 1.3501 ... -0.4092 -0.5541 1.2641 -1.5480 0.8170 -0.2698 ... -0.1328 -0.0383 0.3028 ... ⋱ ... -1.7280 -1.4230 0.8473 ... -1.1345 -1.4235 -0.5488 0.2920 1.7177 0.0864 ... -0.2760 2.3767 0.3261 0.3887 1.6059 0.5631 ... -0.7719 0.8481 0.0843 [torch.FloatTensor of size 1x1x32x32]
st103818
Is there a newer version on pip than 0.1.12_2? I was under the impression that this is the latest
st103819
Right now, 0.1.12_2 is the latest version. Python 3.6.0 |Anaconda custom (x86_64)| (default, Dec 23 2016, 13:19:00) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import torch >>> torch.__version__ '0.1.12_2' $ python neural_networks_tutorial.py gives no error with this setup. So weird.
st103820
So, the error message is a result of the following evaluating to false, in the C code, I think: inline bool THPVariable_Check(PyObject *obj) { return THPVariableClass && PyObject_IsInstance(obj, THPVariableClass); } (python_variable.h) So, seems like it’s not checking some attribute, but looking at the actual class. The type of the class is being obtained, in the C code like: if (PyType_Ready(&THPVariableType) < 0) return false; Py_INCREF(&THPVariableType); PyModule_AddObject(module, "_VariableBase", (PyObject *)&THPVariableType); (python_variable.cpp) Then, that _VariableBase bit seems to be defined on the C side. from variable.py: class Variable(_C._VariableBase): … though I’m not sure where the breadcrumbs lead after this… grep -ir '_VariableBase' torch torch/autograd/variable.py:class Variable(_C._VariableBase): torch/csrc/autograd/python_variable.cpp: "torch._C._VariableBase", /* tp_name */ torch/csrc/autograd/python_variable.cpp: PyModule_AddObject(module, "_VariableBase", (PyObject *)&THPVariableType); However, as others point out, I think reinstalling via conda would be a good place to start. conda provides binaries, unlike pip, which provides source code.
st103821
Thanks for all the help, I’ll follow your hints and get back later when I find the error
st103822
I also encounter this error. So the only way to solve it is update the torch version?
st103823
Yes, would recommend that you update your torch. Instructions on how to install the latest can be found here: http://pytorch.org/ 442
st103824
Hi I am also facing the same issue with pytorch 0.3.0 and I am also feeding a FloatTensor to squezeNet, I have attached the source code to the message. import torchvision from torchvision import transforms import torch import torch.nn as nn from PIL import Image import requests import io squeeze = torchvision.models.squeezenet1_1(pretrained=True) IMG_URL = 'https://s3.amazonaws.com/outcome-blog/wp-content/uploads/2017/02/25192225/cat.jpg' response = requests.get(IMG_URL) img_pil = Image.open(io.BytesIO(response.content)) normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) preprocess = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize ]) img_tensor = preprocess(img_pil) data = img_tensor.unsqueeze(0) squeeze(data)
st103825
You are feeding a Tensor to your model instead of a Variable Warp data in a Variable and your code should run. from torch.autograd import Variable squeeze(Variable(data))
st103826
I’m getting the same error on the CIFAR-10 tutorial with a fresh install of pytorch conda install pytorch torchvision cuda90 -c pytorch
st103827
In the current pytorch version (0.4.0) Variables and tensors are merged, so that shouldn’t be an error. Could you check your version with: print(torch.__version__)
st103828
You could update to 0.4.0, where Variables and tensors are merged or warp your tensor into a Variable or did the aforementioned approaches not work in your case?
st103829
I’ve read a lot of posts about graph visualization in pytorch, but i still can’t find something really usable. I’ve tried with https://github.com/szagoruyko/functional-zoo/blob/master/visualize.py 146 but graphviz’s image conversion seems too heavy if we have a large model (i.e. resnet34) and my process goes on for hours if i try to save a png or any image format. I’ve also read about the tensorboard integration, but i use visdom and would like to stick with it. So are there any new ways to get the pytorch computational graph and get an image from it? My final goal is to send the image to visdom in order to visualize it with all my other logs.
st103830
Hi, One way to go if you have a “classic” network is to export it with onnx and then use tools that can be used for caffe2 or tensorflow models. The problem with exporting directly from pytorch is that you will usually have a graph with very low level operations which makes it (very) big.
st103831
I tried to export my model with onnx since i saw that caffe2 has a simple way to create graph’s png, but i get the following error RuntimeError: torch/csrc/autograd/functions/onnx/convolution.cpp:61: symbolic: output padding is not supported. I guess i can’t export my model because it includes transposed convolutions with output padding and they’re not supported yet. Is there any way around this?
st103832
Unfortunately no as this would require to add this specific function to onnx. I am not sure how easy/hard that would be as this might depend on the other framework’s (caffe2 here) capacity to do the exact same operation.
st103833
you can try this twitter.com PyTorch (PyTorch) 73 Tensorboard-PyTorch plugin now includes graph visualization of your model. Live demo here: bit.ly/2ESDQIN Github page: github.com/lanpa/tensorbo… https://t.co/MyRtrAOKVD 8:01 PM - 18 Jan 2018
st103834
If rendering speed is your main issue, you can export to SVG which creates much smaller files which gets rendered in real time by your viewer (for example, your browser).
st103835
My model is seem like below: class CTCModel(nn.Module): def __init__(self,output_size,rnn_hidden_size=128, num_rnn_layers=1, dropout=0): super(CTCModel, self).__init__() self.num_rnn_layers = num_rnn_layers self.rnn_hidden_size = rnn_hidden_size self.output_size = output_size self.layer1 = nn.Sequential( nn.Conv2d(3,32, kernel_size=(3,3),stride=(1,1),padding=(1,1)), nn.ReLU(), nn.Conv2d(32, 32, kernel_size=(3, 4), stride=(3, 2)), nn.ReLU(), ) self.layer2 = nn.Sequential( nn.Conv2d(32,64, kernel_size=(3,3),stride=(1,1),padding=(1,1)), nn.ReLU(), nn.Conv2d(64, 64, kernel_size=(4, 3), stride=(4, 2)), nn.ReLU(), ) self.layer3 = nn.Sequential( nn.Conv2d(64, 128, kernel_size=(3, 3),stride=(1,1),padding=(1,1)), nn.ReLU(), nn.Conv2d(128, 128, kernel_size=(4, 2), stride=(2, 2)), nn.ReLU(), nn.Conv2d(128, 128, kernel_size=(3, 2), stride=(1, 1)), nn.ReLU(), ) self.gru = nn.GRU(128, rnn_hidden_size, num_rnn_layers, batch_first=True, dropout=dropout,bidirectional=True) self.linear = nn.Linear(rnn_hidden_size*2,output_size) def forward(self, x, hidden): h0 = hidden out = self.layer1(x) out = self.layer2(out) out = self.layer3(out).squeeze() out = out.transpose(1, 2) out, hidden = self.gru(out, h0) out = self.linear(out) return out def initHidden(self,batch_size,use_cuda=False): h0 = Variable(torch.zeros(self.num_rnn_layers*2,batch_size,self.rnn_hidden_size)) if use_cuda: return (h0.cuda()) else: return h0 Evey step of training is like this: def CTCtrain(inputs,targets,lens,ctc,ctc_optimizer,criterion,clip,use_cuda=False): if use_cuda: inputs = inputs.cuda() loss = 0 ctc_optimizer.zero_grad() batch_size = inputs.size()[0] init_hidden = ctc.initHidden(batch_size,use_cuda=use_cuda) ctc_outputs = ctc(inputs,init_hidden) ctcloss_inputs = ctc_outputs.transpose(0,1) #SeqLen * BatchSize * Hidden label_lens = lens act_lens = Variable(torch.IntTensor(batch_size*[ctc_outputs.size()[1]]),requires_grad=False) loss = criterion(ctcloss_inputs,targets,act_lens,label_lens) loss.backward() torch.nn.utils.clip_grad_norm(ctc.parameters(), clip) ctc_optimizer.step() #TODO decoded_outputs = decode_ctc_outputs(ctc_outputs) decoded_targets = np.split(targets.data.numpy(),lens.data.numpy().cumsum())[:-1] accuracy = np.array([np.array_equal(decoded_targets[i],decoded_outputs[i]) for i in range(batch_size)]).mean() return loss.data[0],accuracy And the CTCLoss is from here 11 I have tried to clip the gradient with torch.nn.utils.clip_grad_norm(ctc.parameters(), clip), the clip=0.5. What is more , my learning_rate is 0.0001. However, all these could not help. after sever batches, the loss will become “nan” like belowing: epoch train loss: 8023.35400391 epoch train accuracy: 0.0 epoch train loss: 8019.50976562 epoch train accuracy: 0.0 epoch train loss: nan epoch train accuracy: 0.0 epoch train loss: nan epoch train accuracy: 0.0 I have spent plenty time to figure it out, like changing the structure of my model with more or less channel or more Conv layers. Unfortunately, I’m still fighting with this trouble. Any advice will be appreciated!!
st103836
What is your learning rate? It should be small enough to avoid the “loss nan” problem.
st103837
So to explain it nicely, a = torch.randn(1, 3) a tensor([[ 0.6763, 0.7445, -2.2369]]) torch.max(a) tensor(0.7445) ^ returns the maximum value. But here, a = torch.randn(4, 4) a tensor([[-1.2360, -0.2942, -0.1222, 0.8475], [ 1.1949, -1.1127, -2.2379, -0.6702], [ 1.5717, -0.9207, 0.1297, -1.8768], [-0.6172, 1.0036, -0.6060, -0.2432]]) torch.max(a, 1) (tensor([ 0.8475, 1.1949, 1.5717, 1.0036]), tensor([ 3, 0, 0, 1])) It returns the value along with the index location of each maximum value i.e the argmax. Why isn’t the index location returned in the first case?
st103838
The LongTensor that specifies the argmax values is only returned when a dimension is specified. a = torch.randn(1,3) # tensor([[-0.6392, -0.8940, 0.3799]]) torch.max(a, dim=0) # (tensor([-0.6392, -0.8940, 0.3799]), tensor([ 0, 0, 0])) torch.max(a, dim=1) # (tensor([ 0.3799]), tensor([ 2])) I think the returned LongTensor always has 1 fewer dimension than the input tensor. Without specifying which dimension in which to get the max values, torch won’t know which LongTensor to return. When the dimension isn’t specified, the singular maximal value in the entire tensor will be returned (as a single element tensor). Such as: b = torch.randn(4,4) torch.max(b) # tensor(1.2384)
st103839
The reason is historical: this is the behavior of Lua Torch. We’ve been talking about changing these functions to have consistent behavior when the dimension is specified and when it’s not, but it’s difficult to migrate without breaking backwards compatibility.
st103840
does anyone encounter a similar situation. watch window: in 0.3.1, we can see the data values but in 0.4.0, we only can’t watch the value of the Tensor,we can only watch the shape and other things.
st103841
with other tools,such as vs coder,spyder, We obtain the same results. Can anybody help me?
st103842
If I understand 0.4 correctly, new tensors contain a list of 1-element tensors: >>>list(torch.zeros(5)) [tensor(0.), tensor(0.), tensor(0.), tensor(0.), tensor(0.)] What you can do in emergency is to create a numpy array using ‘Tensor.numpy’ in order to visualize its content in Vstudio
st103843
Because it is now a C++ Tensor, not a raw value in python. Can you please tick C++ Native in the debug window and see if that helps.
st103844
thanks ,Alexis and peterjc123. With print function,I can see the tensor values. I am a little wondering why. 4.0 version gives up these convenience.
st103845
No, it’s not only about convenience. The most important thing is speed, right? It is the fact that the calculations are moved to ATen(C++) that makes it quicker.
st103846
Hi guys, I am trying to develop text classification with RNN. The model runs fine, however the loss after a couple of steps starts stagnating. Below is the code of my model class ClassifierModel(nn.Module): def __init__(self, hidden_size, num_layers, vocab_size, embedding_dim, label_size): super(ClassifierModel, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim) self.lstm = nn.LSTM( input_size=embedding_dim, hidden_size=hidden_size, num_layers=num_layers, dropout=0.5, bidirectional=False) self.dense = nn.Linear( in_features=hidden_size, out_features=label_size) def forward(self, entity_ids, seq_len): embedding = self.embedding(entity_ids) input_size = embedding.size() out, _ = self.lstm( embedding.view(input_size[1], input_size[0], input_size[2])) last_output = torch.index_select(out, 0, seq_len) logits = self.dense(last_output) logits = F.relu(logits[0, :, :]) return logits And this is the code I use for training classifier_model = ClassifierModel(128, 2, len(vocabs), 200, 2) loss_fn = nn.CrossEntropyLoss() optimizer = optim.Adam(classifier_model.parameters()) for data_bucket, category_bucket, seq_len_bucket in train_data: for keys in data_bucket.keys(): entity_ids = Variable(data_bucket[keys], requires_grad=False) category_ids = Variable(category_bucket[keys], requires_grad=False) seq_len = Variable(seq_len_bucket[keys], requires_grad=False) logits = classifier_model(entity_ids, seq_len) loss = loss_fn(logits, category_ids) print("Loss:", loss) pred, pred_idx = torch.max(logits, 1) correct_predictions = (pred_idx.data == category_bucket[keys]).sum() acc = correct_predictions / category_bucket[keys].size()[0] print("Accuracy:", acc) loss.backward() optimizer.step() This is the output Accuracy: 0.5263157894736842 Loss: Variable containing: 0.7016 [torch.FloatTensor of size 1] Accuracy: 0.41379310344827586 Loss: Variable containing: 0.6972 [torch.FloatTensor of size 1] Accuracy: 0.4166666666666667 Loss: Variable containing: 0.6948 [torch.FloatTensor of size 1] Accuracy: 0.4488888888888889 Loss: Variable containing: 0.6918 [torch.FloatTensor of size 1] Accuracy: 0.4492753623188406 Loss: Variable containing: 0.6931 [torch.FloatTensor of size 1] Accuracy: 0.5121951219512195 Loss: Variable containing: 0.6931 [torch.FloatTensor of size 1] Accuracy: 0.51010101010101 Loss: Variable containing: 0.6931 [torch.FloatTensor of size 1] Accuracy: 0.525 Loss: Variable containing: 0.6931 [torch.FloatTensor of size 1] As you can see from the output above, after several steps the loss stuck at 0.6931 Am I doing something wrong with my code? Thanks
st103847
Check the output of your network. It is probably outputting all zeros after a while. Unfortunately, that’s more a diagnosis of the problem. I’m not sure how to solve it. Perhaps try a lower learning rate.
st103848
Did you ever figure out what was wrong? I am having the exact same problem. I am getting the same value 0.6931 in my loss too.
st103849
Hi, Im using a convolutional encoder-decoder network for image segmentation, and my loss also happens to get stuck at 0.6931 using BCELoss() as a loss function. Has any one found a solution to this given there are many cases of the same problem? edit : one observation is 0.6931 ~ log_e(2) , and I changed my learning rate from 0.1 to 0.00001 and it works now
st103850
@Jadiel_de_Armas @mnazaal my suggestion is to check every single layer of your networks to see whether the weights are changed correctly after the gradient loss is propagated (maybe some part of the networks isn’t connected to the next one, something wrong with the way you calculate the loss, learning rate too small, check whether the dimension of the input multiplied by the output match the one that you desired, etc)
st103851
Hi everyone I am swithcing from programin in matlab to pytorch and yet there are alot to learn for me. I have a function as following, it takes an input in 4D, bachsize x channels x dimention1 x dimention2 and do some operations on it and gives the output in the same size. I will really appreciate it if you guys can help me and tell me if there is a more efficient and simple way to write this function in pytorch (so i can get rid of the loops) Thanks in advance … def EdgeDetection(Input_Temp): K1 = torch.FloatTensor([[1,0,0],[0,-1,0],[0,0,0]]).to(device) K2 = torch.FloatTensor([[0,1,0],[-1,0,0],[0,0,0]]).to(device) # print "The input size is" , Input_Temp.size() , "\n" #The input size is for example (128, 3, 32, 32) D = 0 # D is responsible for number of Batches or the 0st dimention for BatchNum in range(Input_Temp.size(0)): C = 0 # C is responsible for number of channels or the 1st dimention for ChannelNum in range(Input_Temp.size(1)): TempImg = Input_Temp[BatchNum,ChannelNum,:,:].clone() TempImgNormalize = TempImg # Makeing the input to have size of d x c x m x m so it can be used in conv2d A1 = torch.unsqueeze(torch.unsqueeze(TempImgNormalize,0),0).to(device) Gx = F.conv2d(A1, torch.unsqueeze(torch.unsqueeze(K1,0),0),padding= K1.size(0)/2 ) Gy = F.conv2d(A1, torch.unsqueeze(torch.unsqueeze(K2,0),0),padding= K2.size(0)/2 ) GM = (Gx**2 + Gy**2)**0.5 # concatinating the results, concatenating along the 1st dimention: if C == 0: APP = GM else: APP = torch.cat((APP,GM),1) C += 1 # concatinating the results, concatenating along the 0st dimention: if D == 0: Final = APP Final = Final.to(device) else: Final = torch.cat((Final,APP),0) D = D + 1 return Final
st103852
Solved by albanD in post #2 Hi, Please find below code that does it with 2 convs. I did not do timings as they might depend on if you use a GPU or not. But that should be significantly faster, especially during the backward pass. import torch from torch.nn import functional as F device = torch.device("cpu") # Original co…
st103853
Hi, Please find below code that does it with 2 convs. I did not do timings as they might depend on if you use a GPU or not. But that should be significantly faster, especially during the backward pass. import torch from torch.nn import functional as F device = torch.device("cpu") # Original code def EdgeDetection(Input_Temp): K1 = torch.FloatTensor([[1,0,0],[0,-1,0],[0,0,0]]).to(device) K2 = torch.FloatTensor([[0,1,0],[-1,0,0],[0,0,0]]).to(device) # print "The input size is" , Input_Temp.size() , "\n" #The input size is for example (128, 3, 32, 32) D = 0 # D is responsible for number of Batches or the 0st dimention for BatchNum in range(Input_Temp.size(0)): C = 0 # C is responsible for number of channels or the 1st dimention for ChannelNum in range(Input_Temp.size(1)): TempImg = Input_Temp[BatchNum,ChannelNum,:,:].clone() TempImgNormalize = TempImg # Makeing the input to have size of d x c x m x m so it can be used in conv2d A1 = torch.unsqueeze(torch.unsqueeze(TempImgNormalize,0),0).to(device) Gx = F.conv2d(A1, torch.unsqueeze(torch.unsqueeze(K1,0),0),padding= K1.size(0)/2 ) Gy = F.conv2d(A1, torch.unsqueeze(torch.unsqueeze(K2,0),0),padding= K2.size(0)/2 ) GM = (Gx**2 + Gy**2)**0.5 # concatinating the results, concatenating along the 1st dimention: if C == 0: APP = GM else: APP = torch.cat((APP,GM),1) C += 1 # concatinating the results, concatenating along the 0st dimention: if D == 0: Final = APP Final = Final.to(device) else: Final = torch.cat((Final,APP),0) D = D + 1 return Final # New one # Pre-allocate these so that this is not done every time # Either in the current file or in the __init__ or the nn.Module K1 = torch.FloatTensor([[1,0,0],[0,-1,0],[0,0,0]]).unsqueeze(0).unsqueeze(0).to(device) pad_k1 = 1 K2 = torch.FloatTensor([[0,1,0],[-1,0,0],[0,0,0]]).unsqueeze(0).unsqueeze(0).to(device) pad_k2 = 1 def EdgeDetectionNew(Input_Temp): # Move the input to the right device (remove this line if this is not needed) Input_Temp = Input_Temp.to(device) # For the conv, make the channel look like batch # Compute the size for the conv inp_size = Input_Temp.size() conv_size = list(inp_size) conv_size[0] = inp_size[0] * inp_size[1] conv_size[1] = 1 # View the input acordingly conv_input = Input_Temp.view(conv_size) Gx = F.conv2d(conv_input, K1, padding=pad_k1) Gy = F.conv2d(conv_input, K2, padding=pad_k2) GM = (Gx**2 + Gy**2)**0.5 # View the output back to get the channel GM = GM.view(inp_size) return GM inp = torch.rand(10, 3, 20, 20) out = EdgeDetection(inp) out2 = EdgeDetectionNew(inp) print((out - out2).max())
st103854
I have a follow up question. If in a tensor T with size AxBxDxD i want to subtract the mean of each layer, do you know a fast way to do that too 8-? Lets say for simplicity B is 1. the classical way is to have two for loop for range(A) and range(B) and then subtract the mean from each layer, i was wondering if there is a fast way to do that too? I cannot do T-torch.mean(T) because torch.mean(T) will give me the average of whole layers in T not each of them separately… Edit: I figured it out M = torch.mean(torch.mean(T,2),2) a = (a.unsqueeze_(-1)) print a.size() a = a.expand(A,D,D) print a.size() a.unsqueeze_(1)
st103855
@albanD I have a follow up question. If i want to keep K1 as it is, but change K2 during training (with backpropagation), how should i do that? K1 = torch.FloatTensor([[1,0,0],[0,-1,0],[0,0,0]]).unsqueeze(0).unsqueeze(0).to(device) pad_k1 = 1 K2 = torch.FloatTensor([[0,1,0],[-1,0,0],[0,0,0]]).unsqueeze(0).unsqueeze(0).to(device) pad_k2 = 1 def EdgeDetectionNew(Input_Temp): # Move the input to the right device (remove this line if this is not needed) Input_Temp = Input_Temp.to(device) # For the conv, make the channel look like batch # Compute the size for the conv inp_size = Input_Temp.size() conv_size = list(inp_size) conv_size[0] = inp_size[0] * inp_size[1] conv_size[1] = 1 # View the input acordingly conv_input = Input_Temp.view(conv_size) Gx = F.conv2d(conv_input, K1, padding=pad_k1) Gy = F.conv2d(conv_input, K2, padding=pad_k2) GM = (Gx**2 + Gy**2)**0.5 # View the output back to get the channel GM = GM.view(inp_size) return GM
st103856
Make K2 an nn.Parameter and store it in the nn.Module. Like it is done for all nn modules. If you don’t use nn.Module, juste make sure that K2 requires gradients and that it is passed to your optimizer.
st103857
The code was copied from here: https://pytorch.org/tutorials/beginner/blitz/data_parallel_tutorial.html 2 No modifications were done. According to the page, it is suppose to print this: # on 2 GPUs Let's use 2 GPUs! In Model: input size torch.Size([15, 5]) output size torch.Size([15, 2]) In Model: input size torch.Size([15, 5]) output size torch.Size([15, 2]) Outside: input size torch.Size([30, 5]) output_size torch.Size([30, 2]) In Model: input size torch.Size([15, 5]) output size torch.Size([15, 2]) In Model: input size torch.Size([15, 5]) output size torch.Size([15, 2]) Outside: input size torch.Size([30, 5]) output_size torch.Size([30, 2]) In Model: input size torch.Size([15, 5]) output size torch.Size([15, 2]) In Model: input size torch.Size([15, 5]) output size torch.Size([15, 2]) Outside: input size torch.Size([30, 5]) output_size torch.Size([30, 2]) In Model: input size torch.Size([5, 5]) output size torch.Size([5, 2]) In Model: input size torch.Size([5, 5]) output size torch.Size([5, 2]) Outside: input size torch.Size([10, 5]) output_size torch.Size([10, 2]) However, it hangs after printing Let's use two GPUs. The code does runs till the second last line in the tutorial and I can see any print statements I put there. output = model(input) Debugging leads to File "/usr/lib/python3.6/threading.py", line 1072, in _wait_for_tstate_lock I suspect it’s a race condition since while debugging, I saw one such message In Model: input size torch.Size([5, 5]) output size torch.Size([5, 2]) The machine has two GPUs (1080 TI) and tensorflow seems to work reasonably smoothly. I understand that pytorch parallelism API is still in active development and not fully tested (according to the documentation itself) Still, I’m hoping that any information regarding debugging the problem any further without having to learn the whole source from someone with the insight. I have a fairly good grasp on both python and the underlying C/C++ programming so don’t hold back anything that could help in debugging. Thank you
st103858
Which PyTorch version are you using? I assume you are using the default DataLoader from the tutorial, i.e. num_workers=0. Could you execute the code line by line in a Python shell and see, if the creation of DataParallel hangs or if it’s the training loop using the DataLoader?
st103859
It’s the processing. Namely the last line that feeds the input to the model. I’ve gotten as far as the parallel_apply which does not return. py(124)parallel_apply() -> return parallel_apply(replicas, inputs, kwargs, self.device_ids[:len(replicas)]) (Pdb) In Model: input size torch.Size([15, 5]) output size torch.Size([15, 2]) Even going deeper, I can trace it down to thread.start() inside parallel_apply. And further down, > /usr/lib/python3.6/threading.py(828)start() -> def start(self): (Pdb) n > /usr/lib/python3.6/threading.py(838)start() -> if not self._initialized: (Pdb) > /usr/lib/python3.6/threading.py(841)start() -> if self._started.is_set(): (Pdb) > /usr/lib/python3.6/threading.py(843)start() -> with _active_limbo_lock: (Pdb) > /usr/lib/python3.6/threading.py(844)start() -> _limbo[self] = self (Pdb) > /usr/lib/python3.6/threading.py(845)start() -> try: (Pdb) > /usr/lib/python3.6/threading.py(846)start() -> _start_new_thread(self._bootstrap, ()) (Pdb) s > /usr/lib/python3.6/threading.py(851)start() -> self._started.wait() (Pdb) In Model: input size torch.Size([15, 5]) output size torch.Size([15, 2]) At this point, it hangs wtihout stepping in. I’m guessing that this is mapped to pthread call. I can fire up gdb and see where it leads. However it would be counterproductive if it is a known issue and/or I’m just doing something silly.
st103860
I am trying to multiply two tensors such that every element of each row vector is multiplied with every element of the corresponding row vector of the other tensor. Say, I have t1 = [ [a1, a2, a3], [b1, b2, b3], [c1, c2, c3] ] #Shape 23 t2 = [ [x1, x2, x3], [y1, y2, y3], [z1, z2, z3] ] #Shape 23 I expect the output tensor to be : out_t = [ [a1x1, a1x2, a1x3, a2x1, a2x2, a2x3, a3x1, a3x2, a3x3], [b1y1, b1y2, b1y3, b2y1, b2y2, b2y3, b3y1,b3y2,b3y3]] #Shape 2*9 Is there a clean way of achieving this is PyTorch?
st103861
I’d recommend to look at broadcasting 133 in the docs: out_t = t1[:, :, None]*t2[:, None, :] Indexing with None (just like numpy.newaxis) inserts a single axis, like unsqueeze(dim) would, too, but for tasks like this, I like the explicit way to see exactly how it aligns (similarly, the trailing colon for t2 is just to make the dimensions explicit). There also is torch.einsum if you want to be fance (or for more elaborate use-cases), but here, I’d use the above in my own code. Best regards Thomas
st103862
Hello, I would like to ask about converting 2D to 3D since GRU layer accept input with 3D format the issue that I have my data with n subjects(rows) and m features and I have the label for them. so the dataset should look like n×m. however what is the best representation for this 2D array to 3D??? Please Advise Abeer
st103863
The input to nn.GRU should be [seq_len, batch_size, input_size]. In your case, you would have to add the batch dimension to your data. I assume the features are supposed to represent the “time dimension”.
st103864
For example, I would like to extract each 2 × 2 submatrix in a 3 × 3 matrix, converting them to column vector, then obtaining a new matrix. Like this: 1…2…3./././././././././1…2…4…5 4…5…6…------->…2…3…5…6 7…8…9./././././././././4…5…7…8 ./././././././././././././././/5…6…8…9 and how to effectively implement the inv-process. Thank you for your attention and answer.
st103865
Solved by SimonW in post #3 The inverse is nn.Fold
st103866
You are looking for nn.Unfold (otherwise commonly known as im2col). See https://pytorch.org/docs/master/nn.html#torch.nn.Unfold 27. The functional form also exists and is at torch.nn.functional.unfold.
st103867
Hi, it seems that this function only exist in pytorch_0.5 which is an unstable version. So, have you been used this version, or is there a good solution to this problem under pytorch_0.4?
st103868
They are actually in 0.4.0! But we forgot to document it, and added the doc reference in 0.5. See: https://github.com/pytorch/pytorch/blob/v0.4.0/torch/nn/modules/fold.py 20
st103869
Hello all, I have seen multiple people with old GPUs looking for the a windows installation of the latest PyTorch and I am one of them. I realize it is possible to compile the windows 0.4.0 whl with support for old compute (in my case 3.0) but unfortunately I do not have VS 2017 nor can I afford it at present. Does anyone out there know of a repository kind enough to provide an old GPU compatible build? Otherwise, is it possible to cross compile a windows whl using linux? Thanks
st103870
I’m trying to wrap my head around REINFORCE and in particular this line 15. This would appear to result in a loss of 0 if log_prob is 0 or if the reward (return) is 0. In the latter case, a very high return with 100% probability would look just like no return with any probability. I’m not sure how it could learn under such confounded signals. What am I missing?
st103871
The underlying logic is that you want to maximize the sum of the rewards under the policy, which can be obtained by a gradient descent with the derivative of this sum. And the derivative of this sum is the sum of R*derivative(log(policy)). That’s the policy-gradient theorem, and it’s easy to prove (using the fact that d(pi) = d(log(pi))*pi ) Now, how to interpret the idea in a less formal way: you want to maximize the log-likelihood where rewards are height and minimalize it when rewards are small. Of course, there is a singularity when the policy is deterministic (p(Si) = Ai with probability 1), but such a case is never reached in a sub-optimal way if the policy is not initialized in that singular way. Usually the policy is initialized with a small normal noise around a uniform distribution.
st103872
Thanks for explanation, @alexis-jacq. However, it is still unclear to me. If there is a reward function that has zero or negative values, e.g. reward=[-1, 0, +1], how math will work out in this line 3? Because when the reward is zero, loss becomes zero, so means no error? but when the reward is +1 (desired one), there is an error? Or may be the reward can not be negative or zero in this code?
st103873
@confused, I believe that I can help explain the math a bit. Notice that in this line 2, the rewards from an episode are standardized to be unit normal, meaning the distribution of the standardized rewards will have mean 0 and a variance of 1. This serves as a measure of the “goodness” of an action, relative to the others in the trajectory. Standardized rewards > 0 means that we want to increase the probability of taking those actions given the state, and the reverse for rewards < 0. Let’s look at the case for the highest loss, which is when there is a very low probability of taking an action that led to a very high reward. Try plugging that into the loss: (-log_prob * reward) term, and you’ll see that it results in a very high loss, which we want to minimize. I hope I was able to help!
st103874
Thanks @kphng. But what happens if reward is zero (in above example rewards can be -1 or 0 or +1), then loss = (-log_prob * 0), so no error will propagate?
st103875
@confused, yes, no error will propagate. This is because the goodness of that standardized action would be neither better or worse than “average”. So we would not want to adjust the probability of taking that action.
st103876
Thanks again, @kphng . Another question, since the goal is to minimize error, if there is reward -1, then loss become smaller than a case where there is +1 reward in the (-log_prob * reward). Example: a) reward -1, prob =0.9 (-log(0.9)*reward), loss = -0.105 b) reward 1, prob =0.9 (-log(0.9)*reward), loss = 0.105 In this scenario, case b has higher error than case a. Am I missing sth here?
st103877
@confused, I think that the concept is that instead of comparing the loss values between your 2 cases there, you should think about minimizing each policy loss value by itself. Let’s look at case b), in order to lower that loss, increasing the probability would lower that loss value. Now for case a), taking a step to minimize the loss would mean decreasing the probability of that action. I wouldn’t try to view the theory as comparing the losses for the separate cases (a, b, etc…), but think about how the loss is a scalar generated by summing the loss for every single case in a trajectory. By minimizing the error in each case by itself, the overall loss will be decreased. To make it more concrete: With your example, loss for cases a, b would be -0.105 + 0.105 = 0. Now if we updated the weights w/a gradient step, let’s say: a) reward=-1, prob=.85, (-log(.85)*reward), loss = -0.162 b) reward=1, prob = .95, (-log(.95)*reward), loss = 0.051 Now the loss (w/our new and improved weights) would be -0.162 + 0.051 = -0.112, which is a lower loss value than 0 above.
st103878
@confused, glad I could help! I updated my above comment to give a concrete example of how the policy update would lower the loss, with the example cases that you provided above.
st103879
Hi everyone, with pytorch 0.4.0, if I do this: R = torch.randn((5,5)) print( torch.tensor(R,device='cuda:0').is_cuda ) I get False. It is normal ? thanks y
st103880
Hello Yann! I’m getting the same result, but this isn’t how you usually put tensors into your GPU’s VRAM anyway. If you wish to put R into the GPU memory, use R = torch.randn((5,5)).cuda() instead. print(R.is_cuda) will then return True. This: print(torch.tensor(torch.randn((5,5), device='cuda:0')).is_cuda) would also return true, but the outer tensor is redundant, so print(torch.randn((5,5), device='cuda:0').is_cuda) is equivalent. I do believe you found a bug though, since print(torch.tensor([1,2,3],device='cuda:0').is_cuda) returns True.
st103881
Thank you very much Anton, In fact, I was looking for a “pytorch 0.4.0”-style alternative this kind of code: x = Variable(torch.randn(5, 5)*2, requires_grad=True).cuda() because of the scaling factor 2, I can’t just write the one-liner you suggested. In the 0.4.0 documentation, it is not clear to me how to write this properly. In the init.py file in the pytorch repo, the initializations are done using the no_grad() function. Here, it would be: x = torch.empty((5,5),requires_grad=True,device='cuda:0') with torch.no_grad(): x.normal_() x.mul_(2) but maybe there is a better (proper one or two lines) way to do this. What about this way: x = torch.randn(5,5).mul(2).to('cuda:0').requires_grad_() cheers y
st103882
Don’t mention it ^^ And if that works, then great! I’ll see if there’s some other way, and if that line works tomorrow. It seem like it would check out okay tho. For now, I need to sleep.
st103883
Hi there, Apologies if this is a basic question. I did go a bit of search but didn’t find quite what I have in mind. Given a model (the forward function) and a given loss, is it possible to find the gradient in the input layer? For example, take AllenNLP’s BiDAF model 2. it has a forward function which defines the network structure, given the inputs, and at some point, it also defines the loss function 2. The question is, for a fixed input, how can I get the gradients in the input layer?
st103884
Solved by ptrblck in post #2 Do you just want the gradient for the first layer (input layer) or the input tensor? For the former you can just print the layer’s parameter’s grad, while you would need to set requires_grad=True for the latter: class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init_…
st103885
Do you just want the gradient for the first layer (input layer) or the input tensor? For the former you can just print the layer’s parameter’s grad, while you would need to set requires_grad=True for the latter: class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.fc1 = nn.Linear(20, 10) self.fc2 = nn.Linear(10, 2) def forward(self, x): x = F.relu(self.fc1(x)) x = self.fc2(x) return x model = MyModel() x = torch.randn(1, 20, requires_grad=True) output = model(x) output.mean().backward() print(model.fc1.weight.grad) print(x.grad)
st103886
In GAN, i want to find latent vector z corresponding to the real image. One way to do this is to train z to minimize the error between sampled image and real image. However, when i ran the code below, Error message appeared: “ValueError: can’t optimize a non-leaf Variable”. targets # target images of shape (batch_size, 3, 64, 64) z = Variable(torch.randn(batch_size, 100), requires_grad=True).cuda() optim = torch.optim.Adam([z], lr=0.01) # This causes an error. (if i delete cuda() above, it solve the problem) samples = generator(z) # sampled images loss = torch.mean((targets - samples)**2) loss.backward() How can i solve this problem? Thanks,
st103887
Solved by smth in post #3 you have a mistake in this code. It should be: z = Variable(torch.randn(batch_size, 100).cuda(), requires_grad=True)
st103888
you can refer to this article http://pytorch.org/tutorials/advanced/neural_style_tutorial.html#sphx-glr-advanced-neural-style-tutorial-py 964
st103889
yunjey: z = Variable(torch.randn(batch_size, 100), requires_grad=True).cuda() you have a mistake in this code. It should be: z = Variable(torch.randn(batch_size, 100).cuda(), requires_grad=True)
st103890
In pytorch 0.4.0, I want to know how do we train this model where i assign one additional tensor task_parameters = torch.ones(2).cuda().requires_grad_() to learn the task weights via precision = torch.exp(-1*self.task_parameters) total_loss = loss * precision[0] + self.task_parameters[0]+ loss_quality * precision[1] + self.task_parameters[1] Now, how do I update task_parameters in optimizer optimizer = optim.SGD(itertools.chain(list(model.parameters()),[task_parameters]), lr=args.lr, momentum=args.momentum)???
st103891
@BestSonny task_parameters should be a leaf Tensor to be optimized, i.e. it’s .grad field should be filled up with gradients. Hence, you define it like this: task_parameters = torch.ones(2, device='cuda', requires_grad=True) OR task_parameters = torch.ones(2).cuda() # what you have in your code task_parameters.detach().requires_grad_() # makes it a leaf variable and sets requires_grad
st103892
I have lots of miss dimensional errors these day. As I am using PyCharm, I thought there would be a debugging functionalities for numpy or tensors shape. But the Pycharm debugger only provide the value it self of any variables. Anyone knows a way to see the dimensions of variables during debugging session?
st103893
Can you post an example of your problem? From what I understand, torch.dim() should solve your problem.
st103894
just add .size() to and tensor get the dimensions. If you want to see it with PyCharm you should click on view (you can see it on the right side when pointing at the tensor) and the dimensions should be at the bottom, below the values.
st103895
Hi, Am trying to use the Adaptive piecewise linear activation unit as my activation function in training my deep neural network so as to improve my network but i don’t know if this activation function is implemented in pytorch. Can some one have and Idea if it is already implemented? Regards,
st103896
Has anyone had RuntimeError: all tensors must be on device[0] errors inside a forward pass? For example, I have this in my training loop: mixed, clean = batch[0], batch[1] znoise = znoise.resize_(batch_size, 1024, 8).normal_(0., 1).float() noise_clean = pnoise.resize_(clean.size()).normal_(0, 1) * input_noise_std mixed = to_gpu(mixed, inference=False, fp16=fp16) clean = to_gpu(clean, inference=False, fp16=fp16) znoise = to_gpu(znoise, inference=False, fp16=fp16) pnoise = to_gpu(pnoise, inference=False, fp16=fp16) print("mixed", mixed.get_device()) # outputs 0 print("znoise", znoise.get_device()) # outputs 0 model(mixed, znoise) with forward: def forward(self, wav, znoise): print(wav.get_device(), znoise.get_device(), cuda.current_device()) # outputs 0, 0, 0 then 1,1,1 # encoder-decoder ladder network with wav and znoise # ... return output_dec Executing model(mixed, znoise) leads to RuntimeError: all tensors must be on device[0]
st103897
What is your model and how are you running the training loop? It’s a little hard to tell from what you’ve provided where the tensors are being moved to another device.
st103898
The model is a Generator like DCGAN with a ladder network structure, Convs with PReLU and “Deconvs” with skip connections and PReLU. Model is instantiated with DataParallel than assigned to the GPU with cuda(). Data batches a reloaded with a DataLoader and at each iteration the training loop is executed. The forward pass executes with no problem until the return, where it outputs the error message. I can be more explicit in code if need be.
st103899
Had the same problem, thank you for figuring it out. The error message could be a lot clearer. RuntimeError: all tensors must be on device[0] should be something like; RuntimeError: Model already contains a DataParallel submodule