name stringlengths 15 255 | question stringlengths 20 1.77k | questionUpvotes int64 0 23 | timeCreated stringlengths 24 24 | answer stringlengths 9 1.09k | answerUpvotes int64 0 75 | timeAnswered stringlengths 24 24 | answerURL stringlengths 50 285 | context stringlengths 244 1.73k | answer_start int64 0 3.45k | answers stringlengths 46 1.14k |
|---|---|---|---|---|---|---|---|---|---|---|
The same seed but different running results on two executions | I just written a simple model to classify cifar10 like below method:<a href="https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#sphx-glr-beginner-transfer-learning-tutorial-py" rel="nofollow noopener">https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#sphx-glr-beginner-transfer-l... | 0 | 2018-06-01T09:51:38.829Z | Looks good to me. To search for the problematic part, could you repeat this procedure with random tensors as input, i.e. don’t use your Dataset and DataLoader?
Since you are seeding, the random tensor should be the same in each run. | 0 | 2018-06-02T08:57:03.012Z | https://discuss.pytorch.org/t/the-same-seed-but-different-running-results-on-two-executions/19017/13 | I’ve checked another possibility and this is most likely the issue.
In your normalization, you have an additional zero for the third channel, which results in the inf values:
transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0,0.225])
Remove the zero and try it again. Looks good to me. To search for the problema... | 989 | {'text': ['Looks good to me. To search for the problematic part, could you repeat this procedure with random tensors as input, i.e. don’t use your Dataset and DataLoader?\n\nSince you are seeding, the random tensor should be the same in each run.'], 'answer_start': [989]} |
Train/validation loss not decreasing | Hi, I am taking the output from my final convolutional transpose layer into a softmax layer and then trying to measure the mse loss with my target. Problem is that my loss is doesn’t decrease and is stuck around the same point. I figured the problem is using the softmax in the last layer.
I need th… | 1 | 2021-11-26T09:23:47.638Z | Ah, sorry, softmax dim option cannot take tuple but only int, so you have to flatten your image before computing softmax, something like this should do the trick:
decoder_shape = decoder.shape
flatten_decoder = decoder.view(decoder_shape[0], decoder_shape[1], -1)
faltten_heat_map = torch.nn.Softmax… | 0 | 2021-11-26T13:47:23.385Z | https://discuss.pytorch.org/t/train-validation-loss-not-decreasing/137889/7 | I’ve checked another possibility and this is most likely the issue.
In your normalization, you have an additional zero for the third channel, which results in the inf values:
transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0,0.225])
Remove the zero and try it again. Looks good to me. To search for the problema... | 510 | {'text': ['Ah, sorry, softmax dim option cannot take tuple but only int, so you have to flatten your image before computing softmax, something like this should do the trick:\n\ndecoder_shape = decoder.shape\n\nflatten_decoder = decoder.view(decoder_shape[0], decoder_shape[1], -1)\n\nfaltten_heat_map = torch.nn.Softmax&... |
Batch must contain tensors, numpy arrays, numbers, dicts or lists; found <class 'PIL.Image.Image'> | Hi everyone, I don’t know how to handle this.
I did
valid_and_test_set = torchvision.datasets.MNIST("./mnist", train=False, download=True)
dataset_valid, dataset_test = torch.utils.data.random_split(valid_and_test_set,[5000, 5000])
class Convert(object):
def __call__(self, img):
retu… | 0 | 2020-06-16T17:13:39.057Z | Hi,
Here is the problem. MNIST object does not have transform and target_transform. You need to call dataset attribute of MNIST then call transform etc.
[image] patrick126:
dataset_valid.transform = transform
dataset_valid.target_transform = OneHot()
Solution:
dataset_valid.dataset.transfo… | 1 | 2020-06-16T18:23:46.437Z | https://discuss.pytorch.org/t/batch-must-contain-tensors-numpy-arrays-numbers-dicts-or-lists-found-class-pil-image-image/85669/3 | Hi,
Here is the problem. MNIST object does not have transform and target_transform. You need to call dataset attribute of MNIST then call transform etc.
[image] patrick126:
dataset_valid.transform = transform
dataset_valid.target_transform = OneHot()
Solution:
dataset_valid.dataset.transfo… Probably some l... | 1,640 | {'text': ['Hi,\n\nHere is the problem. MNIST object does not have transform and target_transform. You need to call dataset attribute of MNIST then call transform etc.\n\n[image] patrick126:\n\ndataset_valid.transform = transform\n\ndataset_valid.target_transform = OneHot()\n\nSolution:\n\ndataset_valid.dataset.transfo&... |
TypeError: ‘Conv2d’ object is not iterable | I want to use Xavier initialization scheme, for initializing weights, for Resnet in <a href="http://www.pabloruizruiz10.com/resources/CNNs/ResNet-PyTorch.html" rel="nofollow noopener">http://www.pabloruizruiz10.com/resources/CNNs/ResNet-PyTorch.html </a>
So I added this in the network:
def xavier_init(ms):
for m in ... | 1 | 2019-11-23T16:19:53.343Z | Probably some layers do not have a bias parameters, so you should add a condition to the weight init function. | 0 | 2019-11-26T02:42:30.847Z | https://discuss.pytorch.org/t/typeerror-conv2d-object-is-not-iterable/61958/9 | Hi,
Here is the problem. MNIST object does not have transform and target_transform. You need to call dataset attribute of MNIST then call transform etc.
[image] patrick126:
dataset_valid.transform = transform
dataset_valid.target_transform = OneHot()
Solution:
dataset_valid.dataset.transfo… Probably some l... | 1,125 | {'text': ['Probably some layers do not have a bias parameters, so you should add a condition to the weight init function.'], 'answer_start': [1125]} |
(Updated) NVIDIA RTX A6000 INCOMPATIBLE WITH PYTORCH | Hello!
Several days ago I posted a issue about pytorch with NVIDIA RTX A6000 GPU, here is the origianl link:
<a href="https://discuss.pytorch.org/t/nvidia-rtx-a6000-gpu-incompatible-with-pytorch/135450">Nvidia rtx a6000 gpu incompatible with pytorch - windows - PyTorch Forums</a>
Many thanks to ptrblck, and I have t... | 0 | 2021-11-05T06:02:20.469Z | Well, I think I figure out the reasons. The problem was caused by the conflict between nvidia driver and cuda 11.1. Install the nvidia driver with –no-opengl-files flag and cuda11.1 with runfile will make this A6000 GPU run smoothly on ubuntu 16.04LTS with desktop GUI and no error is reported.
If n… | 0 | 2021-12-06T16:22:35.113Z | https://discuss.pytorch.org/t/updated-nvidia-rtx-a6000-incompatible-with-pytorch/136046/27 | Hi,
Here is the problem. MNIST object does not have transform and target_transform. You need to call dataset attribute of MNIST then call transform etc.
[image] patrick126:
dataset_valid.transform = transform
dataset_valid.target_transform = OneHot()
Solution:
dataset_valid.dataset.transfo… Probably some l... | 416 | {'text': ['Well, I think I figure out the reasons. The problem was caused by the conflict between nvidia driver and cuda 11.1. Install the nvidia driver with –no-opengl-files flag and cuda11.1 with runfile will make this A6000 GPU run smoothly on ubuntu 16.04LTS with desktop GUI and no error is reported.\n\nIf n&hellip... |
Why my loss function's value doesn't going down? | my model is like below:
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(4909, 1500)
self.relu1 = nn.ReLU()
self.dout = nn.Dropout(0.2)
self.fc2 = nn.Linear(1500, 300)
self.prelu = nn.PReLU(1)
self.out… | 0 | 2018-10-15T13:31:48.518Z | nn.Sigmoid and nn.BCEWithLogitsLoss don’t fit together.
Either remove the nn.Simgoid or use nn.BCELoss. | 3 | 2018-10-15T13:46:27.320Z | https://discuss.pytorch.org/t/why-my-loss-functions-value-doesnt-going-down/27298/2 | nn.Sigmoid and nn.BCEWithLogitsLoss don’t fit together.
Either remove the nn.Simgoid or use nn.BCELoss. def forward(self, x):
batch_size, timesteps, C,H, W = x.size()
c_in = x.view(batch_size * timesteps, C, H, W)
c_out = self.cnn(c_in)
r_out, (h_n, h_c) = self.rnn(c_out.view(-1,batch_size,c_out.shape[-1]))
logit... | 1,448 | {'text': ['nn.Sigmoid and nn.BCEWithLogitsLoss don’t fit together.\n\nEither remove the nn.Simgoid or use nn.BCELoss.'], 'answer_start': [1448]} |
CNN LSTM implementation for video classification | I have implemented a Cnn connected with an lstm to classify multi label videos with CTC Loss
I have two implementations as followed and I don’t know which is better for the forward/bakward operations and if there is any impact in training the network.
class TimeDistributed_Subunet(nn.Module):
… | 1 | 2019-07-30T07:59:34.800Z | def forward(self, x):
batch_size, timesteps, C,H, W = x.size()
c_in = x.view(batch_size * timesteps, C, H, W)
c_out = self.cnn(c_in)
r_out, (h_n, h_c) = self.rnn(c_out.view(-1,batch_size,c_out.shape[-1]))
logits = self.classifier(r_out)
return logits | 0 | 2020-01-20T13:44:41.528Z | https://discuss.pytorch.org/t/cnn-lstm-implementation-for-video-classification/52018/7 | nn.Sigmoid and nn.BCEWithLogitsLoss don’t fit together.
Either remove the nn.Simgoid or use nn.BCELoss. def forward(self, x):
batch_size, timesteps, C,H, W = x.size()
c_in = x.view(batch_size * timesteps, C, H, W)
c_out = self.cnn(c_in)
r_out, (h_n, h_c) = self.rnn(c_out.view(-1,batch_size,c_out.shape[-1]))
logit... | 829 | {'text': ['def forward(self, x):\n\nbatch_size, timesteps, C,H, W = x.size()\n\nc_in = x.view(batch_size * timesteps, C, H, W)\n\nc_out = self.cnn(c_in)\n\nr_out, (h_n, h_c) = self.rnn(c_out.view(-1,batch_size,c_out.shape[-1]))\n\nlogits = self.classifier(r_out)\n\nreturn logits'], 'answer_start': [829]} |
Indexing with byte tensor into another tensor | So here I am wondering why i cannot write the following
labels = labels.byte() # shape [20]
pred = pred.byte() # shape [20]
print('labels', labels.shape)
print('pred', pred.shape)
true_positives = torch.zeros_lik… | 1 | 2019-02-27T21:08:47.741Z | Thanks for the detailed code and explanations!
Now I understand the problem and use case a bit better.
Yes, you are right in that the tp, fp, tn, fn tensors are treated as logical indices.
This advanced indexing behavior is different to the vanilla indexing and is explained a bit better in the <a href="https://docs.... | 1 | 2019-03-01T23:02:29.512Z | https://discuss.pytorch.org/t/indexing-with-byte-tensor-into-another-tensor/38457/17 | nn.Sigmoid and nn.BCEWithLogitsLoss don’t fit together.
Either remove the nn.Simgoid or use nn.BCELoss. def forward(self, x):
batch_size, timesteps, C,H, W = x.size()
c_in = x.view(batch_size * timesteps, C, H, W)
c_out = self.cnn(c_in)
r_out, (h_n, h_c) = self.rnn(c_out.view(-1,batch_size,c_out.shape[-1]))
logit... | 362 | {'text': ['Thanks for the detailed code and explanations!\n\nNow I understand the problem and use case a bit better.\n\nYes, you are right in that the tp, fp, tn, fn tensors are treated as logical indices.\n\nThis advanced indexing behavior is different to the vanilla indexing and is explained a bit better in the <a hr... |
Batched index_select / tf.gather_nd | I am trying to replicate tensorflow’s gather_nd().
torch.manual_seed(0)
images = torch.rand((2, 2, 2, 3))
indices = torch.randint(0, 2, size=(2, 2, 2, 3)).long()
These are the image values:
tensor([[[[0.4963, 0.7682, 0.0885],
[0.1320, 0.3074, 0.6341]],
[[0.4901, 0.8964, 0.455… | 1 | 2018-10-16T20:58:35.923Z | <a class="mention" href="/u/ptrblck">@ptrblck</a> thank you for your quick response, it works perfectly! However, for a single channel image I had to adapt it a little:
idx1, idx2, idx3 = indices.chunk(3, dim=3)
images[idx1, idx2, idx3].squeeze(3) | 1 | 2018-10-16T22:04:43.413Z | https://discuss.pytorch.org/t/batched-index-select-tf-gather-nd/27402/3 | <a class="mention" href="/u/ptrblck">@ptrblck</a> thank you for your quick response, it works perfectly! However, for a single channel image I had to adapt it a little:
idx1, idx2, idx3 = indices.chunk(3, dim=3)
images[idx1, idx2, idx3].squeeze(3) There seem to be a few minor mistakes in the code:
h and w should pro... | 1,604 | {'text': ['<a class="mention" href="/u/ptrblck">@ptrblck</a> thank you for your quick response, it works perfectly! However, for a single channel image I had to adapt it a little:\n\nidx1, idx2, idx3 = indices.chunk(3, dim=3)\n\nimages[idx1, idx2, idx3].squeeze(3)'], 'answer_start': [1604]} |
Custom nn.Conv2d | Hello, This is my first week as a PyTorch user.
How can we define a custom Conv2d function which works similar to nn.Conv2d but the multiplication and addition used inside nn.Conv2d are replaced with mymult(num1,num2) and myadd(num1,num2). It’s for some hdl simulation purpose. Even if it’s a slow i… | 0 | 2019-11-25T06:36:29.340Z | There seem to be a few minor mistakes in the code:
h and w should probably de defined as input.size(2) and input.size(3), respectively.
Currently you are assigning the same input value to both. However, since you are passing input directly, they can also be removed completely.
As already mention… | 1 | 2019-11-27T06:53:18.008Z | https://discuss.pytorch.org/t/custom-nn-conv2d/62068/12 | <a class="mention" href="/u/ptrblck">@ptrblck</a> thank you for your quick response, it works perfectly! However, for a single channel image I had to adapt it a little:
idx1, idx2, idx3 = indices.chunk(3, dim=3)
images[idx1, idx2, idx3].squeeze(3) There seem to be a few minor mistakes in the code:
h and w should pro... | 1,052 | {'text': ['There seem to be a few minor mistakes in the code:\n\nh and w should probably de defined as input.size(2) and input.size(3), respectively.\n\nCurrently you are assigning the same input value to both. However, since you are passing input directly, they can also be removed completely.\n\nAs already mention&hel... |
Segfault using cuda with openmpi | Hi there !
I am following the tutorial for writing distributed applications.
Here is the basic example code. Everything works well as long as I don’t try using cuda.
Is there a specific step to enable it that I missed ? I am getting a segfault…
It might also be linked with some kind of permissio… | 0 | 2017-12-14T03:00:46.707Z | Ok, solved it.
Since I was a bit lost due to lack of documentation for using pytorch + mpi + gpu, I will give here the steps I followed.
The main thing I was missing is that I needed a openmpi which is "cuda-aware".
Main steps to follow:
Install “cuda-aware” openMPI : Need to compile from source
… | 5 | 2017-12-14T15:52:08.829Z | https://discuss.pytorch.org/t/segfault-using-cuda-with-openmpi/11140/2 | <a class="mention" href="/u/ptrblck">@ptrblck</a> thank you for your quick response, it works perfectly! However, for a single channel image I had to adapt it a little:
idx1, idx2, idx3 = indices.chunk(3, dim=3)
images[idx1, idx2, idx3].squeeze(3) There seem to be a few minor mistakes in the code:
h and w should pro... | 558 | {'text': ['Ok, solved it.\n\nSince I was a bit lost due to lack of documentation for using pytorch + mpi + gpu, I will give here the steps I followed.\n\nThe main thing I was missing is that I needed a openmpi which is "cuda-aware".\n\nMain steps to follow:\n\nInstall “cuda-aware” openMPI : Need to compile fr... |
When training GAN why do we not need to zero_grad discriminator? | In the DCGAN example that can be found <a href="https://github.com/pytorch/examples/blob/master/dcgan/main.py" rel="nofollow noopener">here</a>, while training the generator network after training the discriminator network, we do not perform netG.zero_grad() again. However, doesn’t this accumulate the gradients with r... | 1 | 2018-06-28T21:48:51.935Z | In the update step of the discriminator (line 208), the generator does not get the data, so the backward step does not calculate any gradients for it.
In line 217 the input to the discriminator is detached as you already observed. Thus the backward call of errD_fake also does not calculate the grad… | 1 | 2018-06-28T22:13:06.179Z | https://discuss.pytorch.org/t/when-training-gan-why-do-we-not-need-to-zero-grad-discriminator/20439/2 | In the update step of the discriminator (line 208), the generator does not get the data, so the backward step does not calculate any gradients for it.
In line 217 the input to the discriminator is detached as you already observed. Thus the backward call of errD_fake also does not calculate the grad… Thanks - it... | 1,756 | {'text': ['In the update step of the discriminator (line 208), the generator does not get the data, so the backward step does not calculate any gradients for it.\n\nIn line 217 the input to the discriminator is detached as you already observed. Thus the backward call of errD_fake also does not calculate the grad&hellip... |
Finding the cause of RuntimeError: Expected to mark a variable ready only once | I’m extending a complex model (already with DistributedDataParallel with find_unused_parameters set to True) in PyTorch on detectron2.
I’ve added a new layer generating some additional output to the original network - initially, that layer was frozen (requires_grad = False) and everything was worki… | 0 | 2021-06-18T08:32:57.567Z | Thanks - it helped me to move forward. Turns out this feature is available in PyTorch 1.9.0 (was using 1.7.0), so no need to use nightly builds.
Now I have this error:
RuntimeError: Expected to mark a variable ready only once. This error is caused by one of the following reasons: 1) Use of a modul… | 1 | 2021-06-24T12:28:37.339Z | https://discuss.pytorch.org/t/finding-the-cause-of-runtimeerror-expected-to-mark-a-variable-ready-only-once/124428/5 | In the update step of the discriminator (line 208), the generator does not get the data, so the backward step does not calculate any gradients for it.
In line 217 the input to the discriminator is detached as you already observed. Thus the backward call of errD_fake also does not calculate the grad… Thanks - it... | 1,187 | {'text': ['Thanks - it helped me to move forward. Turns out this feature is available in PyTorch 1.9.0 (was using 1.7.0), so no need to use nightly builds.\n\nNow I have this error:\n\nRuntimeError: Expected to mark a variable ready only once. This error is caused by one of the following reasons: 1) Use of a modul&hell... |
Losses end up becoming NAN during training. how to debug and fix them? | Could you please help me figure why I am getting NAN loss value and how to debug and fix it?
P.S.: Why my losses are so large and how can I fix them?
After running this cell of code:
network = Network()
network.cuda()
criterion = nn.MSELoss()
optimizer = optim.Adam(network.parameters(), lr=0… | 0 | 2020-10-14T04:30:53.704Z | Firstly, a good idea might be to debug why you’re getting nans in your landmarks tensor.
Secondly, there might be an issue with the way normalizing is being done. Since landmarks are (x,y) pairs on an image, it might not be suitable to divide by the max landmark value to normalize.
As I mentioned … | 1 | 2020-10-16T02:55:01.263Z | https://discuss.pytorch.org/t/losses-end-up-becoming-nan-during-training-how-to-debug-and-fix-them/99291/11 | In the update step of the discriminator (line 208), the generator does not get the data, so the backward step does not calculate any gradients for it.
In line 217 the input to the discriminator is detached as you already observed. Thus the backward call of errD_fake also does not calculate the grad… Thanks - it... | 618 | {'text': ['Firstly, a good idea might be to debug why you’re getting nans in your landmarks tensor.\n\nSecondly, there might be an issue with the way normalizing is being done. Since landmarks are (x,y) pairs on an image, it might not be suitable to divide by the max landmark value to normalize.\n\nAs I mentioned &hell... |
Pre-built pytorch for CUDA [compute capability] 3.0 on windows? | Hi Forum!
Would anybody know of a pre-built pytorch windows / CUDA 3.0
version? (It’s windows 10, if that matters.)
I’m aware that pytorch no longer formally supports older CUDA
versions, but I have seen older pre-built packages floating
around on the internet – just not this configuration.
(… | 0 | 2019-07-22T11:39:04.203Z | Hi Frank,
I assume you are referring to the compute capability 3.0, which should work with CUDA6.0 - CUDA10.1.
If I’m not mistaken, the minimal compute capability for the current binaries is >=3.5, so you could build from source to support this older GPU.
However, if you would like to play around… | 0 | 2019-07-22T11:53:56.185Z | https://discuss.pytorch.org/t/pre-built-pytorch-for-cuda-compute-capability-3-0-on-windows/51263/2 | Hi Frank,
I assume you are referring to the compute capability 3.0, which should work with CUDA6.0 - CUDA10.1.
If I’m not mistaken, the minimal compute capability for the current binaries is >=3.5, so you could build from source to support this older GPU.
However, if you would like to play around… I google... | 1,852 | {'text': ['Hi Frank,\n\nI assume you are referring to the compute capability 3.0, which should work with CUDA6.0 - CUDA10.1.\n\nIf I’m not mistaken, the minimal compute capability for the current binaries is >=3.5, so you could build from source to support this older GPU.\n\nHowever, if you would like to play around... |
Loading a model + RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! | Hi everyone,
I want to load my previous saved model and continue training. This is the code for saving the model. The network is being trained on GPU (and works well there).
# Save model
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict… | 0 | 2022-02-11T10:04:18.447Z | I googled the idea of moving optimizer parameters from cpu to cuda:0 and found this bunch of code from <a href="https://github.com/pytorch/pytorch/issues/8741#issuecomment-402129385" rel="noopener nofollow ugc">here</a>:
def optimizer_to(optim, device):
# move optimizer to device
for param in optim.state.values():
... | 2 | 2022-02-11T17:45:32.242Z | https://discuss.pytorch.org/t/loading-a-model-runtimeerror-expected-all-tensors-to-be-on-the-same-device-but-found-at-least-two-devices-cuda-0-and-cpu/143897/7 | Hi Frank,
I assume you are referring to the compute capability 3.0, which should work with CUDA6.0 - CUDA10.1.
If I’m not mistaken, the minimal compute capability for the current binaries is >=3.5, so you could build from source to support this older GPU.
However, if you would like to play around… I google... | 1,238 | {'text': ['I googled the idea of moving optimizer parameters from cpu to cuda:0 and found this bunch of code from <a href="https://github.com/pytorch/pytorch/issues/8741#issuecomment-402129385" rel="noopener nofollow ugc">here</a>:\n\ndef optimizer_to(optim, device):\n\n# move optimizer to device\n\nfor param in optim.... |
How to copy a modified state_dict into a models state_dict | I am trying to copy a modified state_dict from a model that was pruned (e.g. reducing the 0 dimension of one of the tensors by 1). The models have the same keys, the only difference is the dimensions of the tensors. I made a wrapper class to handle pruned networks as seen below:
class PrunedNetwork… | 0 | 2019-12-23T15:18:56.108Z | Editing the dictionnary won’t help. As the dictionnary is created when you call .state_dict().
If you want to change them, the simplest solution I can think of right now is going to go through the network and for each parameter:
# mod is the current module that has a parameter weight that needs
# … | 0 | 2019-12-28T15:23:06.759Z | https://discuss.pytorch.org/t/how-to-copy-a-modified-state-dict-into-a-models-state-dict/64828/10 | Hi Frank,
I assume you are referring to the compute capability 3.0, which should work with CUDA6.0 - CUDA10.1.
If I’m not mistaken, the minimal compute capability for the current binaries is >=3.5, so you could build from source to support this older GPU.
However, if you would like to play around… I google... | 713 | {'text': ['Editing the dictionnary won’t help. As the dictionnary is created when you call .state_dict().\n\nIf you want to change them, the simplest solution I can think of right now is going to go through the network and for each parameter:\n\n# mod is the current module that has a parameter weight that needs\n\n# &h... |
How to Detach specific components in the loss? | I’m a little confused how to detach certain model from the loss computation graph.
If I have 3 models that generate an output: A, B and C, given an input.
And, 3 optimizers for those 3 models: Oa, Ob and Oc, for A, B and C resp.
Let’s assume I have an initial input x.
I also have 3 losses L1, L… | 0 | 2018-02-24T08:00:37.071Z | .detach() will return a detached version of your tensor. You can reuse the “attached” tensor for further computations as long as you don’t reassign it somehow:
modelA = nn.Linear(10, 10)
modelB = nn.Linear(10, 10)
modelC = nn.Linear(10, 10)
x = torch.randn(1, 10)
a = modelA(x)
b = modelB(a.detach(… | 4 | 2018-09-04T22:20:55.590Z | https://discuss.pytorch.org/t/how-to-detach-specific-components-in-the-loss/13983/8 | .detach() will return a detached version of your tensor. You can reuse the “attached” tensor for further computations as long as you don’t reassign it somehow:
modelA = nn.Linear(10, 10)
modelB = nn.Linear(10, 10)
modelC = nn.Linear(10, 10)
x = torch.randn(1, 10)
a = modelA(x)
b = modelB(a.detach(… You wou... | 2,044 | {'text': ['.detach() will return a detached version of your tensor. You can reuse the “attached” tensor for further computations as long as you don’t reassign it somehow:\n\nmodelA = nn.Linear(10, 10)\n\nmodelB = nn.Linear(10, 10)\n\nmodelC = nn.Linear(10, 10)\n\nx = torch.randn(1, 10)\n\na = modelA(x)\n\nb = modelB(a.... |
TypeError: new() received an invalid combination of arguments - got (Tensor, int) | Hi, I am defining a Custom Model for image classification. My code is as follows
class CustomNeuralNet(nn.Module):
def __init__(self,num_classes):
super(CustomNeuralNet,self).__init__()
self.conv_1 = nn.Conv2d(in_channels=3,out_channels=32,kernel_size=3,padding=1,stride=1)
… | 0 | 2020-03-12T04:52:19.721Z | You would have to create a model instance before passing in the inputs:
model = CustomNeuralNet(num_classes)
outputs = model(inputs)
Based on the error message it seems you are trying to pass the inputs directly to the initialization of the model. | 2 | 2020-03-12T05:01:26.757Z | https://discuss.pytorch.org/t/typeerror-new-received-an-invalid-combination-of-arguments-got-tensor-int/72948/2 | .detach() will return a detached version of your tensor. You can reuse the “attached” tensor for further computations as long as you don’t reassign it somehow:
modelA = nn.Linear(10, 10)
modelB = nn.Linear(10, 10)
modelC = nn.Linear(10, 10)
x = torch.randn(1, 10)
a = modelA(x)
b = modelB(a.detach(… You wou... | 1,335 | {'text': ['You would have to create a model instance before passing in the inputs:\n\nmodel = CustomNeuralNet(num_classes)\n\noutputs = model(inputs)\n\nBased on the error message it seems you are trying to pass the inputs directly to the initialization of the model.'], 'answer_start': [1335]} |
DistributedDataParallel barrier doesn't work as expected during evaluation | Hi, I am using the distributed data parallel as shown in the <a href="https://pytorch.org/tutorials/intermediate/ddp_tutorial.html" rel="noopener nofollow ugc">turtorial</a>. I have 2 GPUs in a single machine. I want to train the model on all the nodes but evaluate the model on the node with rank 0. I set up a barrier ... | 1 | 2020-10-19T12:47:16.122Z | <a class="mention" href="/u/euruson">@Euruson</a> I think I’ve figured out the problem here. You are still using DDP for the validation phase even though it runs only on one rank. Even though you might not run the backward pass for DDP during eval phase, the forward pass for DDP might still invoke some collective opera... | 7 | 2020-12-16T03:49:49.108Z | https://discuss.pytorch.org/t/distributeddataparallel-barrier-doesnt-work-as-expected-during-evaluation/99867/11 | .detach() will return a detached version of your tensor. You can reuse the “attached” tensor for further computations as long as you don’t reassign it somehow:
modelA = nn.Linear(10, 10)
modelB = nn.Linear(10, 10)
modelC = nn.Linear(10, 10)
x = torch.randn(1, 10)
a = modelA(x)
b = modelB(a.detach(… You wou... | 564 | {'text': ['<a class="mention" href="/u/euruson">@Euruson</a> I think I’ve figured out the problem here. You are still using DDP for the validation phase even though it runs only on one rank. Even though you might not run the backward pass for DDP during eval phase, the forward pass for DDP might still invoke some colle... |
How to implement skip-gram or CBOW in pytorch | I just learn about word embedding and I think the word vector can be learned by CBOW or Skip-gram procedure. And I have two questions about word embedding in Pytorch.
The first one–How to understand nn.Embedding in Pytorch
I think I don’t have a good understanding of Embedding in Pytorch. Is the nn… | 0 | 2019-06-11T13:46:12.109Z | in nn.Embeddings back propagation wouldnt happen on the entire matrix. Back propagation will be done only on the rows of the embedding matrix whose indices are passed. | 2 | 2019-06-12T10:37:57.262Z | https://discuss.pytorch.org/t/how-to-implement-skip-gram-or-cbow-in-pytorch/47625/7 | in nn.Embeddings back propagation wouldnt happen on the entire matrix. Back propagation will be done only on the rows of the embedding matrix whose indices are passed. Thanks for the info. I’ll try to debug your code.
In the meanwhile could you remove the recursion in __getitem__:
return self.__getitem__(np.random.ra... | 1,826 | {'text': ['in nn.Embeddings back propagation wouldnt happen on the entire matrix. Back propagation will be done only on the rows of the embedding matrix whose indices are passed.'], 'answer_start': [1826]} |
[SOLVED] Dataloader: runs out of RAM for a small dataset | I have a dataset with 100 images which occupy around 120 MB and their masks occupy around 4.2 MB. I have written a dataloader. When I try to plot some examples using the following code, the process is killed because of running out of memory.
import torchvision
import matplotlib.pyplot as plt
from a… | 0 | 2018-07-25T17:09:33.319Z | Thanks for the info. I’ll try to debug your code.
In the meanwhile could you remove the recursion in __getitem__:
return self.__getitem__(np.random.randint(0, self.__len__()))
and just return random data instead:
return torch.randn(YOUR_SIZE), torch.randn(YOUR_SIZE) | 0 | 2018-07-26T10:03:56.599Z | https://discuss.pytorch.org/t/solved-dataloader-runs-out-of-ram-for-a-small-dataset/21718/13 | in nn.Embeddings back propagation wouldnt happen on the entire matrix. Back propagation will be done only on the rows of the embedding matrix whose indices are passed. Thanks for the info. I’ll try to debug your code.
In the meanwhile could you remove the recursion in __getitem__:
return self.__getitem__(np.random.ra... | 1,081 | {'text': ['Thanks for the info. I’ll try to debug your code.\n\nIn the meanwhile could you remove the recursion in __getitem__:\n\nreturn self.__getitem__(np.random.randint(0, self.__len__()))\n\nand just return random data instead:\n\nreturn torch.randn(YOUR_SIZE), torch.randn(YOUR_SIZE)'], 'answer_start': [1081]} |
Size mismatch after loading saved model. Please explain! | Hey guys, I am trying to load a trained CNN classifier that I saved so I can modify the linear layers, but I get a size mismatch error when performing a forward pass (train or eval, doesn’t matter). Here is the output:
Exception NameError: “global name ‘FileNotFoundError’ is not defined” in <bound … | 0 | 2018-07-17T22:35:05.684Z | You could simply add a torch.nn.ReLU() layer to use relu inside your sequential model. | 1 | 2018-07-31T14:45:19.607Z | https://discuss.pytorch.org/t/size-mismatch-after-loading-saved-model-please-explain/21295/13 | in nn.Embeddings back propagation wouldnt happen on the entire matrix. Back propagation will be done only on the rows of the embedding matrix whose indices are passed. Thanks for the info. I’ll try to debug your code.
In the meanwhile could you remove the recursion in __getitem__:
return self.__getitem__(np.random.ra... | 439 | {'text': ['You could simply add a torch.nn.ReLU() layer to use relu inside your sequential model.'], 'answer_start': [439]} |
Model returning nan as output | I’m trying to implement a variant of capsule network where the matrix multiplication is replaced by element-wise multiplication with a vector. During training (mostly after the first backpropagation) the outputs become nan. I tried using gradient clipping, but it didn’ work. I’m working with MNIST d… | 0 | 2020-05-22T17:01:40.157Z | The values of squared_norm in PrimaryCaps explode and create the NaNs.
In the last iteration before the NaNs are raised PrimaryCaps creates tensors with these statistics:
print(squared_norm.min(), squared_norm.max())
> tensor(1.4527e+20, device='cuda:0', grad_fn=<MinBackward1>) tensor(5.3600e+26, &h... | 0 | 2020-05-24T02:37:44.561Z | https://discuss.pytorch.org/t/model-returning-nan-as-output/82510/8 | The values of squared_norm in PrimaryCaps explode and create the NaNs.
In the last iteration before the NaNs are raised PrimaryCaps creates tensors with these statistics:
print(squared_norm.min(), squared_norm.max())
> tensor(1.4527e+20, device='cuda:0', grad_fn=<MinBackward1>) tensor(5.3600e+26, &h... | 1,050 | {'text': ['The values of squared_norm in PrimaryCaps explode and create the NaNs.\n\nIn the last iteration before the NaNs are raised PrimaryCaps creates tensors with these statistics:\n\nprint(squared_norm.min(), squared_norm.max())\n\n> tensor(1.4527e+20, device='cuda:0', grad_fn=<MinBackward1>) tens... |
"binary_cross_entropy" not implemented for 'Long' | Hello, I am implementing a segmentation task with masks and images in input and one class in output. I am trying to use the binary cross entropy from pytorch but I have this error :
> RuntimeError: “binary_cross_entropy” not implemented for 'Long’
Indeed, I have formatted my mask as a long type, o… | 0 | 2020-09-29T08:55:43.051Z | You can
use a single output unit without any activation function at the end and lass this logit to nn.BCEWithLogitsLoss. For this the targets should have the same shape as the model output and be FloatTensors. To get the predicted label you can apply torch.sigmoid and use a threshold via preds = o… | 1 | 2020-09-30T09:49:23.167Z | https://discuss.pytorch.org/t/binary-cross-entropy-not-implemented-for-long/97712/8 | The values of squared_norm in PrimaryCaps explode and create the NaNs.
In the last iteration before the NaNs are raised PrimaryCaps creates tensors with these statistics:
print(squared_norm.min(), squared_norm.max())
> tensor(1.4527e+20, device='cuda:0', grad_fn=<MinBackward1>) tensor(5.3600e+26, &h... | 852 | {'text': ['You can\n\nuse a single output unit without any activation function at the end and lass this logit to nn.BCEWithLogitsLoss. For this the targets should have the same shape as the model output and be FloatTensors. To get the predicted label you can apply torch.sigmoid and use a threshold via preds = o…... |
Transformer Mask Doesn't Do Anything | I’m trying to train a Transformer Seq2Seq model using nn.Transformer class. I believe I am implementing it wrong, since when I train it, it seems to fit too fast, and during inference it repeats itself often. This seems like a masking issue in the decoder, and when I remove the target mask, the trai… | 2 | 2020-05-05T03:16:05.645Z | I figured out the problem, I was not properly inserting SOS and EOS tokens, so even with proper masking it was able to copy straight from the given target. | 3 | 2020-08-12T19:19:51.281Z | https://discuss.pytorch.org/t/transformer-mask-doesnt-do-anything/79765/3 | The values of squared_norm in PrimaryCaps explode and create the NaNs.
In the last iteration before the NaNs are raised PrimaryCaps creates tensors with these statistics:
print(squared_norm.min(), squared_norm.max())
> tensor(1.4527e+20, device='cuda:0', grad_fn=<MinBackward1>) tensor(5.3600e+26, &h... | 635 | {'text': ['I figured out the problem, I was not properly inserting SOS and EOS tokens, so even with proper masking it was able to copy straight from the given target.'], 'answer_start': [635]} |
How to apply a element wise cross_entropy/nll loss to a 3D matrix? | Hi guys, I’m working on a 3D Unet model. Currently I’m facing a trouble in implementing the loss function for 3D tensor. The output of my model is 1 x 2 x 64 x 64 x 64 (batchsize, class, H, W , Layer) and the groudntruth is
1 x 64 x 64 x 64. However, the nll_loss function does not allow me to inpu… | 0 | 2018-01-12T11:27:14.312Z | In 0.3.0, you’d have to do the following workaround. You can reshape your input into a 4D tensor and your target into a 3D tensor, and send them into the loss function, as so:
input_4d = input.view(1, 2, 64, -1)
target_3d = target.view(1, 64, -1)
loss = nn.NLLLoss(reduce=False)
out_3d = loss(input_… | 1 | 2018-01-14T17:26:41.891Z | https://discuss.pytorch.org/t/how-to-apply-a-element-wise-cross-entropy-nll-loss-to-a-3d-matrix/12213/4 | In 0.3.0, you’d have to do the following workaround. You can reshape your input into a 4D tensor and your target into a 3D tensor, and send them into the loss function, as so:
input_4d = input.view(1, 2, 64, -1)
target_3d = target.view(1, 64, -1)
loss = nn.NLLLoss(reduce=False)
out_3d = loss(input_… [image] ... | 1,580 | {'text': ['In 0.3.0, you’d have to do the following workaround. You can reshape your input into a 4D tensor and your target into a 3D tensor, and send them into the loss function, as so:\n\ninput_4d = input.view(1, 2, 64, -1)\n\ntarget_3d = target.view(1, 64, -1)\n\nloss = nn.NLLLoss(reduce=False)\n\nout_3d = loss(inpu... |
Compute gradient of determinant function or inverse function | I have a loss function defined like this
def Loss(U,G_metric,p,q):
''' U is a function takes a vector and return a scalar
G_metric is a function returns a matrix; it's a metric tensor
p ,q are two vectors
'''
D = p.size()[0] # get the dimension of p,q
G = G_metric(q) # … | 0 | 2018-08-26T02:46:37.280Z | [image] ElleryL:
x = Variable(x,requires_grad=True) G = torch.eye(2)*3 # compute matrix
Here G does not have requires_grad=True. I think, thats the reason for the error.
Probably, you wanted to do this:
x = torch.Tensor([3])
x = Variable(x,requires_grad=True)
G = torch.eye(2) * x # compute … | 0 | 2018-08-26T04:42:51.081Z | https://discuss.pytorch.org/t/compute-gradient-of-determinant-function-or-inverse-function/23892/11 | In 0.3.0, you’d have to do the following workaround. You can reshape your input into a 4D tensor and your target into a 3D tensor, and send them into the loss function, as so:
input_4d = input.view(1, 2, 64, -1)
target_3d = target.view(1, 64, -1)
loss = nn.NLLLoss(reduce=False)
out_3d = loss(input_… [image] ... | 1,102 | {'text': ['[image] ElleryL:\n\nx = Variable(x,requires_grad=True) G = torch.eye(2)*3 # compute matrix\n\nHere G does not have requires_grad=True. I think, thats the reason for the error.\n\nProbably, you wanted to do this:\n\nx = torch.Tensor([3])\n\nx = Variable(x,requires_grad=True)\n\nG = torch.eye(2) * x # compute ... |
Low GPU Usage during Training | Hi! I am training a Convnet to classify CIFAR10 images on RTX 3080 GPU. For some reason, when I look at the GPU usage in task manager, it shows 3% GPU usage as shown in the image.
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/3/7/37ca8508d13b9d63f7f5c2521666cad11f24a523.png" data-do... | 0 | 2021-05-18T04:44:05.943Z | Unfortunately I think I can’t help much. As the file in your github running successfully for me for different batch sizes and differ workers also. My gpu utilization is around 22%. But I am using linux machine and I do have 32 cpu’s in it.
But I did found one interesting article about num_wprkers>0… | 0 | 2021-05-18T15:57:55.241Z | https://discuss.pytorch.org/t/low-gpu-usage-during-training/121588/21 | In 0.3.0, you’d have to do the following workaround. You can reshape your input into a 4D tensor and your target into a 3D tensor, and send them into the loss function, as so:
input_4d = input.view(1, 2, 64, -1)
target_3d = target.view(1, 64, -1)
loss = nn.NLLLoss(reduce=False)
out_3d = loss(input_… [image] ... | 618 | {'text': ['Unfortunately I think I can’t help much. As the file in your github running successfully for me for different batch sizes and differ workers also. My gpu utilization is around 22%. But I am using linux machine and I do have 32 cpu’s in it.\n\nBut I did found one interesting article about num_wprkers>0&hel... |
Save checkpoints trained on multi GPUs for load on single GPU | I am training a GAN model right now on multi GPUs using DataParallel, and try to follow the official guidance <a href="https://pytorch.org/tutorials/beginner/saving_loading_models.html" rel="noopener nofollow ugc">here</a> for saving torch.nn.DataParallel Models, as I plan to do evaluation on single GPU later, which m... | 0 | 2020-10-01T02:46:18.155Z | Hi <a class="mention" href="/u/janine">@Janine</a>,
This is not related to PyTorch version but the DataParallel (also DistributedDataParallel) class wrapper of PyTorch nn class models.
DataParallel encloses the original model as it member variable, self.module.
In case you need both single-GPU and multi-GPU model tr... | 7 | 2020-10-03T16:09:08.463Z | https://discuss.pytorch.org/t/save-checkpoints-trained-on-multi-gpus-for-load-on-single-gpu/97881/9 | Hi <a class="mention" href="/u/janine">@Janine</a>,
This is not related to PyTorch version but the DataParallel (also DistributedDataParallel) class wrapper of PyTorch nn class models.
DataParallel encloses the original model as it member variable, self.module.
In case you need both single-GPU and multi-GPU model tr... | 1,858 | {'text': ['Hi <a class="mention" href="/u/janine">@Janine</a>,\n\nThis is not related to PyTorch version but the DataParallel (also DistributedDataParallel) class wrapper of PyTorch nn class models.\n\nDataParallel encloses the original model as it member variable, self.module.\n\nIn case you need both single-GPU and m... |
TypeError: 'Dataset' object does not support indexing | Hi,
I want to concatenate testing samples and training samples (CIFAR-10), and then using this dataset in the test. I used __getitem :
class MyTestDataset():
def __init__(self, transform_test=None, transform_train=None):
Train = datasets.CIFAR10(root='~/data', train=True,downl… | 0 | 2020-03-11T01:58:26.084Z | Is this what you need?
class MyTestDataset():
def __init__(self, transform_test=None, transform_train=None):
self.Train = datasets.CIFAR10(root='~/data', train=True,download=False,transform=transform_train)
self.Test = datasets.CIFAR10(root='~/data', train=False,down… | 1 | 2020-03-13T17:08:58.099Z | https://discuss.pytorch.org/t/typeerror-dataset-object-does-not-support-indexing/72799/16 | Hi <a class="mention" href="/u/janine">@Janine</a>,
This is not related to PyTorch version but the DataParallel (also DistributedDataParallel) class wrapper of PyTorch nn class models.
DataParallel encloses the original model as it member variable, self.module.
In case you need both single-GPU and multi-GPU model tr... | 1,278 | {'text': ['Is this what you need?\n\nclass MyTestDataset():\n\ndef __init__(self, transform_test=None, transform_train=None):\n\nself.Train = datasets.CIFAR10(root='~/data', train=True,download=False,transform=transform_train)\n\nself.Test = datasets.CIFAR10(root='~/data', train=False,down…'], 'a... |
How to sample images belonging to particular classes | I have an ImageFolder. I see that the __getitem__(index) method of ImageFolder can get both the tensor and the class of an index. But what if I want to use ImageFolder to sample the images from only a particular class of my choice.
How would this be done? | 0 | 2019-04-27T14:55:19.524Z | I just posted on another thread, but i think this one answers this question as well and may answer it best:
I would also consider going one level above the ImageFolder Class which inherits from DatasetFolder.
DatasetFolder uses a method to index the folder subdirectories for each class:
def find_… | 0 | 2021-10-13T22:02:47.080Z | https://discuss.pytorch.org/t/how-to-sample-images-belonging-to-particular-classes/43776/10 | Hi <a class="mention" href="/u/janine">@Janine</a>,
This is not related to PyTorch version but the DataParallel (also DistributedDataParallel) class wrapper of PyTorch nn class models.
DataParallel encloses the original model as it member variable, self.module.
In case you need both single-GPU and multi-GPU model tr... | 645 | {'text': ['I just posted on another thread, but i think this one answers this question as well and may answer it best:\n\nI would also consider going one level above the ImageFolder Class which inherits from DatasetFolder.\n\nDatasetFolder uses a method to index the folder subdirectories for each class:\n\ndef find_&he... |
Is there a way to quantize conv_transpose2d layer? | Following is my error message:
Traceback (most recent call last):
File “pose_estimation/test_on_single_image_quant_ver.py”, line 119, in
main()
File “pose_estimation/test_on_single_image_quant_ver.py”, line 92, in main
output = quantized_model(input)
File “/usr/lib/python3.8/site-packages/to… | 0 | 2020-09-17T07:32:45.932Z | At the moment there is no active work to implement the per channel observer for the convtranspose. The reason is that there is non-trivial task that requires observation of a proper channel, which is different for the conv and convtranspose. If you add a feature request on github, I will try to get … | 0 | 2021-03-25T17:34:28.019Z | https://discuss.pytorch.org/t/is-there-a-way-to-quantize-conv-transpose2d-layer/96590/32 | At the moment there is no active work to implement the per channel observer for the convtranspose. The reason is that there is non-trivial task that requires observation of a proper channel, which is different for the conv and convtranspose. If you add a feature request on github, I will try to get … This should... | 1,906 | {'text': ['At the moment there is no active work to implement the per channel observer for the convtranspose. The reason is that there is non-trivial task that requires observation of a proper channel, which is different for the conv and convtranspose. If you add a feature request on github, I will try to get …'... |
Rpn_box_reg loss is nan | Hi, I am trying to run a faster r-cnn model based on the torchvision <a href="https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html" rel="nofollow noopener">example</a> for a custom dataset.
However, I have noticed that when training, if xmax is smaller than xmin, the rpn_box_reg loss goes to nan. xmax... | 0 | 2019-07-12T22:36:15.393Z | This should be the solution to our issue: <a href="https://github.com/pytorch/vision/issues/1128" rel="nofollow noopener">https://github.com/pytorch/vision/issues/1128</a>
However, we will have to skip those images without annotations. So I have followed the solution given here: <a href="https://discuss.pytorch.org/t/... | 1 | 2019-07-17T12:26:07.369Z | https://discuss.pytorch.org/t/rpn-box-reg-loss-is-nan/50480/18 | At the moment there is no active work to implement the per channel observer for the convtranspose. The reason is that there is non-trivial task that requires observation of a proper channel, which is different for the conv and convtranspose. If you add a feature request on github, I will try to get … This should... | 1,262 | {'text': ['This should be the solution to our issue: <a href="https://github.com/pytorch/vision/issues/1128" rel="nofollow noopener">https://github.com/pytorch/vision/issues/1128</a>\n\nHowever, we will have to skip those images without annotations. So I have followed the solution given here: <a href="https://discuss.p... |
Import video in form of an numpy array in pytorch | I have an video in form of numpy array (Picture Number,x,y). And my mouse events corresponding to the pictures (Number,x,y,click). Now i tried the Approach in my code which oblivious doesn’t work. I couldn’t find anything specific in the internet either. Can someone help me how i import the dataset … | 0 | 2018-07-23T19:41:19.446Z | You could split the outputs into the regression problem (mouse coordinates) and the classification problem (click/no-click).
Both outputs should be passed to the appropriate loss function.
Here is a very simple example code you could use as a starter:
class MyModel(nn.Module):
def __init__(se… | 0 | 2018-07-25T14:15:03.728Z | https://discuss.pytorch.org/t/import-video-in-form-of-an-numpy-array-in-pytorch/21583/30 | At the moment there is no active work to implement the per channel observer for the convtranspose. The reason is that there is non-trivial task that requires observation of a proper channel, which is different for the conv and convtranspose. If you add a feature request on github, I will try to get … This should... | 744 | {'text': ['You could split the outputs into the regression problem (mouse coordinates) and the classification problem (click/no-click).\n\nBoth outputs should be passed to the appropriate loss function.\n\nHere is a very simple example code you could use as a starter:\n\nclass MyModel(nn.Module):\n\ndef __init__(se&hel... |
AttributeError: 'NoneType' object has no attribute 'in_channels' | I am trying to use <a href="https://github.com/Kuldeep-Attri/Pruning-CNN/blob/master/SqueezeNet-Pruning/prune.py#L146" rel="nofollow noopener">prune.py</a> in python 3.7.1 and pytorch 1.0, but I have the following error:
[phung@archlinux SqueezeNet-Pruning]$ python finetune.py --prune
/usr/lib/python3.7/site-packages... | 0 | 2018-11-29T15:38:13.192Z | That’s the issue.
i_2 is iterating over index mentioned below
model.classifier = Sequential(
(0): Dropout(p=0.5)
(1): Conv2d(512, 2, kernel_size=(1, 1), stride=(1, 1))
(2): ReLU(inplace)
(3): AvgPool2d(kernel_size=13, stride=1, padding=0)
)
Since, classifier has only one Conv2d, that too a… | 1 | 2018-12-01T16:23:57.532Z | https://discuss.pytorch.org/t/attributeerror-nonetype-object-has-no-attribute-in-channels/30882/9 | That’s the issue.
i_2 is iterating over index mentioned below
model.classifier = Sequential(
(0): Dropout(p=0.5)
(1): Conv2d(512, 2, kernel_size=(1, 1), stride=(1, 1))
(2): ReLU(inplace)
(3): AvgPool2d(kernel_size=13, stride=1, padding=0)
)
Since, classifier has only one Conv2d, that too a… Your script s... | 2,098 | {'text': ['That’s the issue.\n\ni_2 is iterating over index mentioned below\n\nmodel.classifier = Sequential(\n\n(0): Dropout(p=0.5)\n\n(1): Conv2d(512, 2, kernel_size=(1, 1), stride=(1, 1))\n\n(2): ReLU(inplace)\n\n(3): AvgPool2d(kernel_size=13, stride=1, padding=0)\n\n)\n\nSince, classifier has only one Conv2d, that ... |
Problem in Loading the Saved model | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import numpy as np
from torch.utils.data.dataset import Dataset
ckpt_path=’/home/students/soumyajit_po/hsd_cnn_code/SOUMYA/checkpoint/… | 0 | 2019-08-02T10:20:44.714Z | Your script should already thrown an error in from model import vgg, since model doesn’t seem to be a valid module.
I would recommend to look into <a href="https://docs.python.org/3/tutorial/modules.html" rel="nofollow noopener">Python modules</a> to get an idea how your model should be defined inside vgg.py.
That be... | 1 | 2019-08-03T23:39:27.733Z | https://discuss.pytorch.org/t/problem-in-loading-the-saved-model/52408/18 | That’s the issue.
i_2 is iterating over index mentioned below
model.classifier = Sequential(
(0): Dropout(p=0.5)
(1): Conv2d(512, 2, kernel_size=(1, 1), stride=(1, 1))
(2): ReLU(inplace)
(3): AvgPool2d(kernel_size=13, stride=1, padding=0)
)
Since, classifier has only one Conv2d, that too a… Your script s... | 1,356 | {'text': ['Your script should already thrown an error in from model import vgg, since model doesn’t seem to be a valid module.\n\nI would recommend to look into <a href="https://docs.python.org/3/tutorial/modules.html" rel="nofollow noopener">Python modules</a> to get an idea how your model should be defined inside vgg... |
AttributeError: 'DataParallel' object has no attribute 'copy' | While trying to load a checkpoint into a resnet model I get this error !
What is wrong here?
this is the snippet that causes this error :
def _init_model(self):
if self.device == 'cpu':
checkpoint = torch.load(self.model_checkpoint_path, map_location=torch.device('cpu'))
… | 0 | 2020-03-17T17:23:34.797Z | OK, here is the answer.
self.model.load_state_dict(checkpoint['model'].module.state_dict())
actually works and the reason it was failing earlier was that, I instantiated the models differently (assuming the use_se to be false as it was in the original training script) and thus the keys would diffe… | 2 | 2020-03-18T05:06:05.301Z | https://discuss.pytorch.org/t/attributeerror-dataparallel-object-has-no-attribute-copy/73545/12 | That’s the issue.
i_2 is iterating over index mentioned below
model.classifier = Sequential(
(0): Dropout(p=0.5)
(1): Conv2d(512, 2, kernel_size=(1, 1), stride=(1, 1))
(2): ReLU(inplace)
(3): AvgPool2d(kernel_size=13, stride=1, padding=0)
)
Since, classifier has only one Conv2d, that too a… Your script s... | 702 | {'text': ['OK, here is the answer.\n\nself.model.load_state_dict(checkpoint['model'].module.state_dict())\n\nactually works and the reason it was failing earlier was that, I instantiated the models differently (assuming the use_se to be false as it was in the original training script) and thus the keys would di... |
The input array must be have a shape == (.., ..,[ ..,] 3)), got (500, 333) | Hi everyone! Could you help me with this error?
ValueError: the input array must be have a shape == (.., ..,[ ..,] 3)), got (500, 333)
There are some values of batch size and number of images in the dataset that the training step works, but for other values I get this error…I don’t understand why … | 0 | 2020-05-17T04:19:56.598Z | Most likely caused by having grayscale images in the dataset. Add .convert('RGB') after loading your PIL image in the dataloader. | 1 | 2020-05-18T20:14:13.910Z | https://discuss.pytorch.org/t/the-input-array-must-be-have-a-shape-3-got-500-333/81597/12 | Most likely caused by having grayscale images in the dataset. Add .convert('RGB') after loading your PIL image in the dataloader. I see. It should be the problem of extension ‘code runner’, can you confirm you have this installed?
If is, check this link and setup your python path <a href="https://github.com/fo... | 2,036 | {'text': ['Most likely caused by having grayscale images in the dataset. Add .convert('RGB') after loading your PIL image in the dataloader.'], 'answer_start': [2036]} |
"No module named torch" in VSCode | Hi, everyone!
I know someone created a similar topic but it remained unsolved. I installed PyTorch last week through the ‘conda install pytorch torchvision -c pytorch’ command on the terminal in my Mac and it worked for a few days. This week it’s not working anymore, with the message “No module nam… | 0 | 2021-09-07T09:35:01.624Z | I see. It should be the problem of extension ‘code runner’, can you confirm you have this installed?
If is, check this link and setup your python path <a href="https://github.com/formulahendry/vscode-code-runner#configuration" class="inline-onebox" rel="noopener nofollow ugc">GitHub - formulahendry/vscode-code-runner:... | 0 | 2021-09-07T15:55:43.764Z | https://discuss.pytorch.org/t/no-module-named-torch-in-vscode/131327/8 | Most likely caused by having grayscale images in the dataset. Add .convert('RGB') after loading your PIL image in the dataloader. I see. It should be the problem of extension ‘code runner’, can you confirm you have this installed?
If is, check this link and setup your python path <a href="https://github.com/fo... | 1,156 | {'text': ['I see. It should be the problem of extension ‘code runner’, can you confirm you have this installed?\n\nIf is, check this link and setup your python path <a href="https://github.com/formulahendry/vscode-code-runner#configuration" class="inline-onebox" rel="noopener nofollow ugc">GitHub - formulahendry/vscode... |
Why Auxiliary logits set to false in train mode? | I’m trying to train a classifier on 15k images over five categories using googlenet architecture.
I followed the fine-tune tutorial (but used as pretrained=false just to train from scratch).
But the training is only possible if i set the ‘aux logits as false’
‘’’
model.aux.logits=False
‘’’
Can… | 0 | 2019-03-23T14:39:21.541Z | For GoogLeNet, there are 2 aux branches. So we have to do this way:
aux1, aux2, output = model(inputs)
loss1 = criterion(outputs, target)
loss2 = criterion(aux1, target)
loss3 = criterion(aux2, target)
loss = loss1 + 0.3*(loss2+loss3)
For Inception v3, it has only one aux branch.
outputs, au… | 2 | 2019-03-25T20:30:17.678Z | https://discuss.pytorch.org/t/why-auxiliary-logits-set-to-false-in-train-mode/40705/15 | Most likely caused by having grayscale images in the dataset. Add .convert('RGB') after loading your PIL image in the dataloader. I see. It should be the problem of extension ‘code runner’, can you confirm you have this installed?
If is, check this link and setup your python path <a href="https://github.com/fo... | 498 | {'text': ['For GoogLeNet, there are 2 aux branches. So we have to do this way:\n\naux1, aux2, output = model(inputs)\n\nloss1 = criterion(outputs, target)\n\nloss2 = criterion(aux1, target)\n\nloss3 = criterion(aux2, target)\n\nloss = loss1 + 0.3*(loss2+loss3)\n\nFor Inception v3, it has only one aux branch.\n\noutputs... |
Did any one know how to load the pth pre-trained model from fastai to pytorch? | Did any one know how to load the pth pre-trained model from fastai to pytorch? | 0 | 2020-02-11T03:10:00.029Z | You can see the source code for save here:
<a href="https://github.com/fastai/fastai/blob/master/fastai/basic_train.py#L246" target="_blank" rel="nofollow noopener">fastai/fastai/blob/master/fastai/basic_train.py#L246</a>
#layer_groups -> need to find a way
#TO SEE: do we save model structure and weights separate... | 3 | 2020-02-12T15:23:01.844Z | https://discuss.pytorch.org/t/did-any-one-know-how-to-load-the-pth-pre-trained-model-from-fastai-to-pytorch/69298/11 | You can see the source code for save here:
<a href="https://github.com/fastai/fastai/blob/master/fastai/basic_train.py#L246" target="_blank" rel="nofollow noopener">fastai/fastai/blob/master/fastai/basic_train.py#L246</a>
#layer_groups -> need to find a way
#TO SEE: do we save model structure and weights separate... | 1,610 | {'text': ['You can see the source code for save here:\n\n<a href="https://github.com/fastai/fastai/blob/master/fastai/basic_train.py#L246" target="_blank" rel="nofollow noopener">fastai/fastai/blob/master/fastai/basic_train.py#L246</a>\n\n#layer_groups -> need to find a way\n\n#TO SEE: do we save model structure and... |
RuntimeError: Could not run 'aten::thnn_conv2d_forward' with arguments from the 'QuantizedCPUTensorId' backend. 'aten::thnn_conv2d_forward' is only available for these backends: [CPUTensorId, VariableTensorId] | I am trying to do post quantization.
added QuantStub() and DeQuantStub() in the model
super(ConvTasNet, self).__init__()
# Hyper-parameter
self.N, self.L, self.B, self.Sk, self.H, self.P, self.X, self.R, self.C = N, L, B, Sk, H, P, X, R, C
self.norm_type = norm_type
self.causal … | 0 | 2020-05-11T13:56:31.029Z | I think this error typically means that QuantStub/DeQuantStub is not placed correctly, probably a missing DeQuantStub before conv2d. or conv2d is not quantized. | 1 | 2021-02-06T00:06:18.122Z | https://discuss.pytorch.org/t/runtimeerror-could-not-run-aten-thnn-conv2d-forward-with-arguments-from-the-quantizedcputensorid-backend-aten-thnn-conv2d-forward-is-only-available-for-these-backends-cputensorid-variabletensorid/80707/13 | You can see the source code for save here:
<a href="https://github.com/fastai/fastai/blob/master/fastai/basic_train.py#L246" target="_blank" rel="nofollow noopener">fastai/fastai/blob/master/fastai/basic_train.py#L246</a>
#layer_groups -> need to find a way
#TO SEE: do we save model structure and weights separate... | 1,219 | {'text': ['I think this error typically means that QuantStub/DeQuantStub is not placed correctly, probably a missing DeQuantStub before conv2d. or conv2d is not quantized.'], 'answer_start': [1219]} |
Loading pretrained weights into new model | Hello,
i have made modifications to a model, expanding it with multiple attention mechanisms. 80% of the model is the same as the previous version. Is it possible, to take the pretrained weights of the previous version, and insert them where applicable?
Ive trained the new model for 1 epoch, savin… | 1 | 2020-11-26T07:47:05.627Z | Manipulating the state_dict sounds like a valid approach, if you’ve changed some parameters (e.g. in their shape).
On the other hand, if you’ve added or removed parameters, you could try to use load_state_dict(sd, strict=False) to ignore missing or unexpected keys. | 1 | 2020-11-28T06:43:17.323Z | https://discuss.pytorch.org/t/loading-pretrained-weights-into-new-model/104159/2 | You can see the source code for save here:
<a href="https://github.com/fastai/fastai/blob/master/fastai/basic_train.py#L246" target="_blank" rel="nofollow noopener">fastai/fastai/blob/master/fastai/basic_train.py#L246</a>
#layer_groups -> need to find a way
#TO SEE: do we save model structure and weights separate... | 575 | {'text': ['Manipulating the state_dict sounds like a valid approach, if you’ve changed some parameters (e.g. in their shape).\n\nOn the other hand, if you’ve added or removed parameters, you could try to use load_state_dict(sd, strict=False) to ignore missing or unexpected keys.'], 'answer_start': [575]} |
Onnx export failed int8 model | Is quantize_per_tensor not supported by ONNX? Will more ops(like PReLU) be supported by nn.quantized? | 0 | 2019-11-01T08:30:51.477Z | How are you exporting the quantized model to ONNX? Like previously mentioned we only currently support a custom conversion flow through ONNX to Caffe2 for quantized models. The models aren’t represented in native ONNX format, but a format specific to Caffe2.
If you wish to export model to caffe2, y… | 1 | 2020-07-30T18:27:07.005Z | https://discuss.pytorch.org/t/onnx-export-failed-int8-model/59754/18 | How are you exporting the quantized model to ONNX? Like previously mentioned we only currently support a custom conversion flow through ONNX to Caffe2 for quantized models. The models aren’t represented in native ONNX format, but a format specific to Caffe2.
If you wish to export model to caffe2, y… That’s stra... | 1,682 | {'text': ['How are you exporting the quantized model to ONNX? Like previously mentioned we only currently support a custom conversion flow through ONNX to Caffe2 for quantized models. The models aren’t represented in native ONNX format, but a format specific to Caffe2.\n\nIf you wish to export model to caffe2, y&hellip... |
Error when building pytorch from source | When building from the source it throws up nvlink error. I have followed these <a href="https://github.com/pytorch/pytorch#from-source" rel="nofollow noopener">instructions</a>.
[386/3538] Performing build step for 'nccl_external'
FAILED: nccl_external-prefix/src/nccl_external-stamp/nccl_external-build nccl/l... | 0 | 2020-02-11T13:51:35.354Z | That’s strange. Somehow -gencode=arch=compute_53,code=sm_53 is generated.
Could you try to build it via:
TORCH_CUDA_ARCH_LIST="5.0" python setup.py install | 1 | 2020-02-12T09:09:45.920Z | https://discuss.pytorch.org/t/error-when-building-pytorch-from-source/69365/5 | How are you exporting the quantized model to ONNX? Like previously mentioned we only currently support a custom conversion flow through ONNX to Caffe2 for quantized models. The models aren’t represented in native ONNX format, but a format specific to Caffe2.
If you wish to export model to caffe2, y… That’s stra... | 1,150 | {'text': ['That’s strange. Somehow -gencode=arch=compute_53,code=sm_53 is generated.\n\nCould you try to build it via:\n\nTORCH_CUDA_ARCH_LIST="5.0" python setup.py install'], 'answer_start': [1150]} |
How to sum every k channels for a CNN feature map | Hey guys, I want to sum every k consecutive channels of a variable together. Assume that the input before summing is with the shape like NxCxWxH, and the output after the summation should be Nx(C/k)xWxH. I implemented the method using the code below. the function sum_up is called in the network’s fo… | 1 | 2018-04-01T14:58:45.389Z | You can split the channel dimension with a view/reshape and sum
n,c,h,w = input.size()
res = input.reshape(n, c//k, k, h, w).sum(2)
Best regards
Thomas | 4 | 2018-04-01T15:31:41.171Z | https://discuss.pytorch.org/t/how-to-sum-every-k-channels-for-a-cnn-feature-map/15795/2 | How are you exporting the quantized model to ONNX? Like previously mentioned we only currently support a custom conversion flow through ONNX to Caffe2 for quantized models. The models aren’t represented in native ONNX format, but a format specific to Caffe2.
If you wish to export model to caffe2, y… That’s stra... | 477 | {'text': ['You can split the channel dimension with a view/reshape and sum\n\nn,c,h,w = input.size()\n\nres = input.reshape(n, c//k, k, h, w).sum(2)\n\nBest regards\n\nThomas'], 'answer_start': [477]} |
How to freeze parts of the net? | Hi,
I need to freeze everything except the last layer.
I do this:
for param in model.parameters():
param.requires_grad = False
# Replace the last fully-connected layer
# Parameters of newly constructed modules have requires_grad=True by default
model.fc = nn.Linear(64, 10)
Bu… | 0 | 2020-06-08T13:17:14.971Z | I didn’t realize you are using your custom resnet implementation, which uses model.linear as the last linear layer, not fc.
Try to change the code to model.module.linear = ... and it should work. | 1 | 2020-06-13T23:51:41.227Z | https://discuss.pytorch.org/t/how-to-freeze-parts-of-the-net/84649/10 | I didn’t realize you are using your custom resnet implementation, which uses model.linear as the last linear layer, not fc.
Try to change the code to model.module.linear = ... and it should work. <a class="mention" href="/u/jpeg729">@jpeg729</a>: you have to run it with more epochs. It is normal that with a larger ba... | 1,264 | {'text': ['I didn’t realize you are using your custom resnet implementation, which uses model.linear as the last linear layer, not fc.\n\nTry to change the code to model.module.linear = ... and it should work.'], 'answer_start': [1264]} |
RNN and Adam: slower convergence than Keras | I’m training a Simple RNN on this dataset: <a href="https://ufile.io/gf7xo" rel="nofollow noopener">https://ufile.io/gf7xo</a>. I put the link so you can try my code on your machine. I use Adam as optimizer. I tried to build the same model (same weight initialization also) both on Pytorch and Keras (TF as backend) but... | 0 | 2017-12-18T02:32:19.628Z | <a class="mention" href="/u/jpeg729">@jpeg729</a>: you have to run it with more epochs. It is normal that with a larger batch (the entire sequence in this case) it converges slower. But it converges. Try with 500 epochs.
EDIT: I found the bug. It was just the reshape ordering that must be set to Fortran-like in PyTor... | 0 | 2018-01-06T12:52:58.002Z | https://discuss.pytorch.org/t/rnn-and-adam-slower-convergence-than-keras/11278/10 | I didn’t realize you are using your custom resnet implementation, which uses model.linear as the last linear layer, not fc.
Try to change the code to model.module.linear = ... and it should work. <a class="mention" href="/u/jpeg729">@jpeg729</a>: you have to run it with more epochs. It is normal that with a larger ba... | 829 | {'text': ['<a class="mention" href="/u/jpeg729">@jpeg729</a>: you have to run it with more epochs. It is normal that with a larger batch (the entire sequence in this case) it converges slower. But it converges. Try with 500 epochs.\n\nEDIT: I found the bug. It was just the reshape ordering that must be set to Fortran-... |
RuntimeError: cublas runtime error : the GPU program failed to execute at at /opt/conda/conda-bld/pytorch_1549635019666/work/aten/src/THC/THCBlas.cu:258 | Hi everyone, I tried to run the pointnet module on Pytorch but got the following error:
RuntimeError: cublas runtime error : the GPU program failed to execute at /opt/conda/conda-bld/pytorch_1549635019666/work/aten/src/THC/THCBlas.cu:258
It shows the error comes from F.linear(input, self.weight, s… | 0 | 2019-02-21T00:31:51.595Z | CUDA 9.2 doesn’t support turing gpus. | 0 | 2019-02-21T03:05:58.251Z | https://discuss.pytorch.org/t/runtimeerror-cublas-runtime-error-the-gpu-program-failed-to-execute-at-at-opt-conda-conda-bld-pytorch-1549635019666-work-aten-src-thc-thcblas-cu-258/37800/2 | I didn’t realize you are using your custom resnet implementation, which uses model.linear as the last linear layer, not fc.
Try to change the code to model.module.linear = ... and it should work. <a class="mention" href="/u/jpeg729">@jpeg729</a>: you have to run it with more epochs. It is normal that with a larger ba... | 547 | {'text': ['CUDA 9.2 doesn’t support turing gpus.'], 'answer_start': [547]} |
Couple of models in production | Hi everyone,
I’m trying to use couple of different models simultaneously in one big algorithm. Is it possible to run them on single GPU at the same time? And as I see, its kinda hard to deploy pytorch models in production pipeline. Should I turn to ONNX+Caffe2?
Thanks,
Anton | 1 | 2018-05-22T11:22:47.209Z | [image] ptrblck:
You could just create several different models, push them onto the GPU and feed your data.
So, as I understood:
I save a model this way
# ... some code here
torch.save(model.state_dict(), "{}.pt".format(output_name))
# NOTE: output_name is modelX_name in next steps
Then … | 0 | 2018-05-22T14:36:02.326Z | https://discuss.pytorch.org/t/couple-of-models-in-production/18501/5 | [image] ptrblck:
You could just create several different models, push them onto the GPU and feed your data.
So, as I understood:
I save a model this way
# ... some code here
torch.save(model.state_dict(), "{}.pt".format(output_name))
# NOTE: output_name is modelX_name in next steps
Then … Intere... | 1,168 | {'text': ['[image] ptrblck:\n\nYou could just create several different models, push them onto the GPU and feed your data.\n\nSo, as I understood:\n\nI save a model this way\n\n# ... some code here\n\ntorch.save(model.state_dict(), "{}.pt".format(output_name))\n\n# NOTE: output_name is modelX_name in next step... |
Attempted to read a PyTorch file with version 4, but the maximum supported version for reading is 3. Your PyTorch installation may be too old | I trained a model with Colab TPU using torch XLA, every time I load the saved weight I got this error.
My pytorch version is 1.5.0.
I can’t even install the XLA in my machine. And can’t find any way to install the 1.6.
How to solve this and what’s the reason behind this feature? | 0 | 2020-06-14T10:06:44.688Z | Interestingly, I can just open the file with Xarchiver and change the version to 3 and everything works.
Makes me really curious about the reason behind this. | 0 | 2020-06-14T10:25:48.978Z | https://discuss.pytorch.org/t/attempted-to-read-a-pytorch-file-with-version-4-but-the-maximum-supported-version-for-reading-is-3-your-pytorch-installation-may-be-too-old/85412/2 | [image] ptrblck:
You could just create several different models, push them onto the GPU and feed your data.
So, as I understood:
I save a model this way
# ... some code here
torch.save(model.state_dict(), "{}.pt".format(output_name))
# NOTE: output_name is modelX_name in next steps
Then … Intere... | 898 | {'text': ['Interestingly, I can just open the file with Xarchiver and change the version to 3 and everything works.\n\nMakes me really curious about the reason behind this.'], 'answer_start': [898]} |
RuntimeError: shape '[-1, 16384]' is invalid for input of size 789504 | my dataset have 32 x 32 images, what is the error in it?
class Genv2(nn.Module):
def __init__(self, *args, **kwargs):
super(Genv2, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=5)
self.conv2 = nn.Conv2d(in_channels=6, out_channels=16… | 0 | 2019-09-05T17:20:21.069Z | The conv and pooling layers in your model will change the shape of your activations depending on the kernel size, stride etc.
Have a look at <a href="http://cs231n.github.io/convolutional-networks/" rel="nofollow noopener">CS231n</a> for a detailed description.
The short version:
nn.Conv2d with kernel_size=5 and no ... | 1 | 2019-09-06T11:30:34.486Z | https://discuss.pytorch.org/t/runtimeerror-shape-1-16384-is-invalid-for-input-of-size-789504/55285/4 | [image] ptrblck:
You could just create several different models, push them onto the GPU and feed your data.
So, as I understood:
I save a model this way
# ... some code here
torch.save(model.state_dict(), "{}.pt".format(output_name))
# NOTE: output_name is modelX_name in next steps
Then … Intere... | 474 | {'text': ['The conv and pooling layers in your model will change the shape of your activations depending on the kernel size, stride etc.\n\nHave a look at <a href="http://cs231n.github.io/convolutional-networks/" rel="nofollow noopener">CS231n</a> for a detailed description.\n\nThe short version:\n\nnn.Conv2d with kern... |
How to set environment variables in torch.nn.parallel.DistributedDataParallel? | Hi, I am trying to train my code with distributed data parallelism, I already trained using torch.nn.DataParallel and now I am trying to see how much gain I can get in training speed if I train using torch.nn.parallel.DistributedDataParallel since I read on numerous pages that its better to use Dist… | 0 | 2020-07-31T01:53:41.472Z | Since the IP was an issue, I assume you will train the model using multiple machines? If yes, the --nnode and --node_rank also need to be configured, see: <a href="https://github.com/pytorch/examples/tree/master/distributed/ddp" rel="nofollow noopener">https://github.com/pytorch/examples/tree/master/distributed/ddp</a>... | 0 | 2020-08-03T14:38:22.399Z | https://discuss.pytorch.org/t/how-to-set-environment-variables-in-torch-nn-parallel-distributeddataparallel/91163/4 | Since the IP was an issue, I assume you will train the model using multiple machines? If yes, the --nnode and --node_rank also need to be configured, see: <a href="https://github.com/pytorch/examples/tree/master/distributed/ddp" rel="nofollow noopener">https://github.com/pytorch/examples/tree/master/distributed/ddp</a>... | 1,732 | {'text': ['Since the IP was an issue, I assume you will train the model using multiple machines? If yes, the --nnode and --node_rank also need to be configured, see: <a href="https://github.com/pytorch/examples/tree/master/distributed/ddp" rel="nofollow noopener">https://github.com/pytorch/examples/tree/master/distribu... |
How to replace a layer with own custom variant? | I am trying to replace a certain type of layer (e.g. nn.Conv2d) with my own custom variant in a way that I do not have to copy paste the model definition code and replace the relevant lines.
I tried to do this using the solution mentioned in: <a href="https://discuss.pytorch.org/t/replacing-convs-modules-with-custom-c... | 0 | 2019-04-25T13:41:23.332Z | I think this will work for you, just change it to your custom layer. Let us know if did work:
def replace_bn(module, name):
'''
Recursively put desired batch norm in nn.module module.
set module = net to start code.
'''
# go through all attributes of module nn.module (e.g. netw… | 0 | 2020-10-01T18:58:06.843Z | https://discuss.pytorch.org/t/how-to-replace-a-layer-with-own-custom-variant/43586/7 | Since the IP was an issue, I assume you will train the model using multiple machines? If yes, the --nnode and --node_rank also need to be configured, see: <a href="https://github.com/pytorch/examples/tree/master/distributed/ddp" rel="nofollow noopener">https://github.com/pytorch/examples/tree/master/distributed/ddp</a>... | 1,273 | {'text': ['I think this will work for you, just change it to your custom layer. Let us know if did work:\n\ndef replace_bn(module, name):\n\n'''\n\nRecursively put desired batch norm in nn.module module.\n\nset module = net to start code.\n\n'''\n\n# go through all attributes of module nn.module... |
Why conda installs old pytorch with by default with cudatoolkit=11.2 | I am trying to install conda for cudatoolkit=11.2 on google colab using:
conda install pytorch cudatoolkit=11.2 -c pytorch -c nvidia
But why does it install old pytorch=1.0.0 version not something >1.6?
If I try to force install pytorch=1.6, it gives the following error:
UnsatisfiableError: The … | 0 | 2021-09-04T21:20:09.116Z | No, you cannot install the PyTorch binaries built with CUDA11.2, since they are not available.
If you want to use this specific CUDA version, you could build from source.
Alternatively, you could install the nightly binaries with CUDA11.3 using:
pip install --pre torch -f https://download.pytorch… | 0 | 2021-09-04T21:52:30.098Z | https://discuss.pytorch.org/t/why-conda-installs-old-pytorch-with-by-default-with-cudatoolkit-11-2/131140/4 | Since the IP was an issue, I assume you will train the model using multiple machines? If yes, the --nnode and --node_rank also need to be configured, see: <a href="https://github.com/pytorch/examples/tree/master/distributed/ddp" rel="nofollow noopener">https://github.com/pytorch/examples/tree/master/distributed/ddp</a>... | 724 | {'text': ['No, you cannot install the PyTorch binaries built with CUDA11.2, since they are not available.\n\nIf you want to use this specific CUDA version, you could build from source.\n\nAlternatively, you could install the nightly binaries with CUDA11.3 using:\n\npip install --pre torch -f https://download.pytorch&he... |
Change the BN to GN in resnet | Hi everyone,
I have a question about how to change the Normlization methond in resnet. When I first look at the code of resnet, I found that there is a attribute named norm_layer, where we could create BN layer. So, I try to initializing the norm_layer with nn.GroupNorm. However, I notice in the co… | 0 | 2020-01-08T11:03:48.756Z | Rewriting the model definition would of course work.
However, using getattr and setattr might be the hacky but faster way:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = nn.Conv2d(3, 3, 3, 1, 1)
self.bn1 = nn.BatchNorm2d(3)
… | 1 | 2020-01-09T08:03:40.116Z | https://discuss.pytorch.org/t/change-the-bn-to-gn-in-resnet/66088/4 | Rewriting the model definition would of course work.
However, using getattr and setattr might be the hacky but faster way:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = nn.Conv2d(3, 3, 3, 1, 1)
self.bn1 = nn.BatchNorm2d(3)
… If I understand you correctly, you w... | 2,064 | {'text': ['Rewriting the model definition would of course work.\n\nHowever, using getattr and setattr might be the hacky but faster way:\n\nclass MyModel(nn.Module):\n\ndef __init__(self):\n\nsuper(MyModel, self).__init__()\n\nself.conv1 = nn.Conv2d(3, 3, 3, 1, 1)\n\nself.bn1 = nn.BatchNorm2d(3)\n\n…'], 'answer_... |
Replacing a for loop with indexing | I have a 3-dimensional tensor. 10_000 examples x 10 predicted labels x outputs from 3 models. (10_000, 10, 3)
I also have a tensor with ids of the model outputs I would like to use for each label. It has 10 values between 0 and 2.
Is there any way I could index into the 3d tensor picking an output… | 0 | 2018-05-08T11:22:29.843Z | If I understand you correctly, you would like to select from the last dimension using an index tensor with values in [0, 2].
The same operation should be performed for all examples?
If so, you could try the following code:
a = torch.randn(20, 10, 3)
idx = torch.zeros(10).random_(3).long()
idx = … | 1 | 2018-05-08T11:46:55.066Z | https://discuss.pytorch.org/t/replacing-a-for-loop-with-indexing/17730/2 | Rewriting the model definition would of course work.
However, using getattr and setattr might be the hacky but faster way:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = nn.Conv2d(3, 3, 3, 1, 1)
self.bn1 = nn.BatchNorm2d(3)
… If I understand you correctly, you w... | 1,316 | {'text': ['If I understand you correctly, you would like to select from the last dimension using an index tensor with values in [0, 2].\n\nThe same operation should be performed for all examples?\n\nIf so, you could try the following code:\n\na = torch.randn(20, 10, 3)\n\nidx = torch.zeros(10).random_(3).long()\n\nidx ... |
CUDA Invalid Configuration Error on GPU Only | Hi everyone, long-time reader, first-time poster!
I seem to be running into an odd bug when training my model. I am trying to train an embedding model using the Resnet18 architecture, which I have essentially cut off the last linear layer of (I can post the architecture if needed). I have written… | 0 | 2019-07-11T22:11:31.530Z | Thanks for replying <a class="mention" href="/u/ptrblck">@ptrblck</a>! While trying to reproduce the error at home (I was at work when I first got the error) I started with a smaller batch size (I was using 1024), and lo and behold it worked! I did some investigating, and apparently 1023 works, but any batch_size >... | 3 | 2019-07-12T02:11:21.227Z | https://discuss.pytorch.org/t/cuda-invalid-configuration-error-on-gpu-only/50399/3 | Rewriting the model definition would of course work.
However, using getattr and setattr might be the hacky but faster way:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = nn.Conv2d(3, 3, 3, 1, 1)
self.bn1 = nn.BatchNorm2d(3)
… If I understand you correctly, you w... | 594 | {'text': ['Thanks for replying <a class="mention" href="/u/ptrblck">@ptrblck</a>! While trying to reproduce the error at home (I was at work when I first got the error) I started with a smaller batch size (I was using 1024), and lo and behold it worked! I did some investigating, and apparently 1023 works, but any bat... |
CTC loss with variable input_lengths produces NaN values | Hello all,
I am working with Pytorch 1.0.1 and I am using the CTC loss of PyTorch.
The code looks like the following one (I am working on GPU):
criterion = torch.nn.CTCLoss()
outs, (h,c) = lstm(input) # input is padded with zeros
outs = torch.nn.functional.log_softmax(outs, dim=2)
loss = criterio… | 0 | 2019-04-24T15:52:46.421Z | No that is for CuDNN, you’ll be OK if you use the “native” (PyTorch) version.
Two caveats
If you feed “invalid” (targets to long for input length) samples, you probably want the zero_infinity option from PyTorch nightlies. This will very likely be the source of your difficulties.
GPU CTC doesn’t … | 1 | 2019-04-24T16:36:17.826Z | https://discuss.pytorch.org/t/ctc-loss-with-variable-input-lengths-produces-nan-values/43476/3 | No that is for CuDNN, you’ll be OK if you use the “native” (PyTorch) version.
Two caveats
If you feed “invalid” (targets to long for input length) samples, you probably want the zero_infinity option from PyTorch nightlies. This will very likely be the source of your difficulties.
GPU CTC doesn’t … Yes, the or... | 1,892 | {'text': ['No that is for CuDNN, you’ll be OK if you use the “native” (PyTorch) version.\n\nTwo caveats\n\nIf you feed “invalid” (targets to long for input length) samples, you probably want the zero_infinity option from PyTorch nightlies. This will very likely be the source of your difficulties.\n\nGPU CTC doesn’t &he... |
Transform and Image Data Augmentation | The documentation for torchvision.transform seems to be not clear enough. There are several questions I have.
Does Compose apply each transform to every image sequentially. If order matters, what if I want to don’t want to apply transform in a composite way? (i.e. if I want to apply either flippin… | 0 | 2020-03-04T05:30:45.231Z | Yes, the order of transformations will stay the same, if you don’t use <a href="https://pytorch.org/docs/stable/torchvision/transforms.html#torchvision.transforms.RandomOrder">transforms.RandomOrder</a> or manipulate the list in another way. You could use <a href="https://pytorch.org/docs/stable/torchvision/transforms.... | 2 | 2020-03-04T05:43:29.683Z | https://discuss.pytorch.org/t/transform-and-image-data-augmentation/71942/2 | No that is for CuDNN, you’ll be OK if you use the “native” (PyTorch) version.
Two caveats
If you feed “invalid” (targets to long for input length) samples, you probably want the zero_infinity option from PyTorch nightlies. This will very likely be the source of your difficulties.
GPU CTC doesn’t … Yes, the or... | 1,255 | {'text': ['Yes, the order of transformations will stay the same, if you don’t use <a href="https://pytorch.org/docs/stable/torchvision/transforms.html#torchvision.transforms.RandomOrder">transforms.RandomOrder</a> or manipulate the list in another way. You could use <a href="https://pytorch.org/docs/stable/torchvision/... |
How can I crop half? | I want to crop each cifar10 images half(0-15) and half(16-31) height.
32x32 -> 2x16x32
I can’t solve this with my code…
Because after crop like that, when I put the data in model, dataloder makes problem…
Thank you for your help. | 0 | 2019-04-05T14:05:52.865Z | Try to use __setattr__ and __getattribute__:
class MyDataset(Dataset):
def __init__(self):
for i in range(32):
self.__setattr__('data_{}'.format(i), torch.tensor(i))
def __getitem__(self, index):
return [self.__getattribute__('data_{}'.format(i)) for i … | 0 | 2019-05-01T18:34:58.648Z | https://discuss.pytorch.org/t/how-can-i-crop-half/41767/35 | No that is for CuDNN, you’ll be OK if you use the “native” (PyTorch) version.
Two caveats
If you feed “invalid” (targets to long for input length) samples, you probably want the zero_infinity option from PyTorch nightlies. This will very likely be the source of your difficulties.
GPU CTC doesn’t … Yes, the or... | 835 | {'text': ['Try to use __setattr__ and __getattribute__:\n\nclass MyDataset(Dataset):\n\ndef __init__(self):\n\nfor i in range(32):\n\nself.__setattr__('data_{}'.format(i), torch.tensor(i))\n\ndef __getitem__(self, index):\n\nreturn [self.__getattribute__('data_{}'.format(i)) for i …'], 'answer_st... |
Pytorch RuntimeError: CUDA out of memory. Tried to allocate 256.00 GiB | I tried to run a model on colab and I have this error which seems to be really weird(256.00 GiB !!) same error occurred if I change the data size, the batch size, or clear the GPU memory.
the main model is a self-attention module (data is images)
here is the Traceback error :
Traceback (most rece… | 1 | 2021-08-26T13:40:49.538Z | Hi again , Just want to share with you the solution of this problem , actually I had a problem on the size of the images wut made the training impossible , the image size was 1024*1024 on the validation file , although I resized data images on the training folder
that was the main problem so I hade… | 0 | 2021-09-03T20:26:05.443Z | https://discuss.pytorch.org/t/pytorch-runtimeerror-cuda-out-of-memory-tried-to-allocate-256-00-gib/130360/10 | Hi again , Just want to share with you the solution of this problem , actually I had a problem on the size of the images wut made the training impossible , the image size was 1024*1024 on the validation file , although I resized data images on the training folder
that was the main problem so I hade… That’s good... | 2,236 | {'text': ['Hi again , Just want to share with you the solution of this problem , actually I had a problem on the size of the images wut made the training impossible , the image size was 1024*1024 on the validation file , although I resized data images on the training folder\n\nthat was the main problem so I hade&hellip... |
Given groups=1, weight of size [6, 1, 3, 3], expected input[13, 3, 100, 100] to have 1 channels, but got 3 channels instead | I am new to pytorch and I am trying to build a cnn model using the following code. My issue is I dont know how to calculate input and output parameters. my images are of 100x 100 and grayscale. more my dataset is of 1690 images and I want to batch them in 13 images. there two output sets pos or neg.… | 0 | 2019-02-08T05:20:07.877Z | That’s good to hear!
Is the initialization working now?
This code runs perfectly on my machine:
import torch
import torch.nn as nn
class CNN(nn.Module):
def __init__(self, out_1=13, out_2=32):
super(CNN, self).__init__()
self.cnn1 = nn.Conv2d(in_channels=3, out_channels=… | 1 | 2019-02-16T10:08:53.844Z | https://discuss.pytorch.org/t/given-groups-1-weight-of-size-6-1-3-3-expected-input-13-3-100-100-to-have-1-channels-but-got-3-channels-instead/36666/28 | Hi again , Just want to share with you the solution of this problem , actually I had a problem on the size of the images wut made the training impossible , the image size was 1024*1024 on the validation file , although I resized data images on the training folder
that was the main problem so I hade… That’s good... | 1,427 | {'text': ['That’s good to hear!\n\nIs the initialization working now?\n\nThis code runs perfectly on my machine:\n\nimport torch\n\nimport torch.nn as nn\n\nclass CNN(nn.Module):\n\ndef __init__(self, out_1=13, out_2=32):\n\nsuper(CNN, self).__init__()\n\nself.cnn1 = nn.Conv2d(in_channels=3, out_channels=…'], 'a... |
Random seed with external GPU | Hi all,
I bought a new Palit GeForce RTX 3070 GPU, to speed up my deep learning projects. My laptop is a Dell Latitude 5491 with an Nvidia GeForce MX130 and Intel UHD Graphics 630. I am using the GeForce RTX 3070 in a Razer Core X via Thunderbolt 3.0.
I would like to make my pytorch training repro… | 0 | 2020-11-10T09:11:27.490Z | Thank you for the tip it solved my problem! Yes with torch.set_deterministic(True) I’ve got the following error:
RuntimeError: Deterministic behavior was enabled with either torch.set_deterministic(True) or at::Context::setDeterministic(true), but this operation is not deterministic because it use… | 2 | 2020-11-11T12:43:42.435Z | https://discuss.pytorch.org/t/random-seed-with-external-gpu/102260/3 | Hi again , Just want to share with you the solution of this problem , actually I had a problem on the size of the images wut made the training impossible , the image size was 1024*1024 on the validation file , although I resized data images on the training folder
that was the main problem so I hade… That’s good... | 597 | {'text': ['Thank you for the tip it solved my problem! Yes with torch.set_deterministic(True) I’ve got the following error:\n\nRuntimeError: Deterministic behavior was enabled with either torch.set_deterministic(True) or at::Context::setDeterministic(true), but this operation is not deterministic because it use&hellip... |
Expected stride to be a single integer value or a list of N values to match the convolution dimensions, but got stride=[2,2] | I’m converting a list of 3d numpy arrays (from an .npz file) into a tensor like so:
data = np.load("path.npz",encoding='bytes')
data = torch.from_numpy(data['arr_0'].unsqueeze(1).float()
train_kwargs = {'data_tensor':data}
The images are 8 channel 96X96 pixels, and currently I’m us... | 0 | 2018-06-07T23:49:51.376Z | Ah sorry, my bad! I just added my batch size of 1 to the View() layer.
You should change it to:
encoder:
View((batch_size, -1))
decoder:
View((batch_size, -1, 3, 3))
Unfortunately, you cannot use x.size(0), since the layer is defined in a Sequential, so you have to know your batch size beforehan… | 0 | 2018-06-11T21:56:18.609Z | https://discuss.pytorch.org/t/expected-stride-to-be-a-single-integer-value-or-a-list-of-n-values-to-match-the-convolution-dimensions-but-got-stride-2-2/19364/23 | Ah sorry, my bad! I just added my batch size of 1 to the View() layer.
You should change it to:
encoder:
View((batch_size, -1))
decoder:
View((batch_size, -1, 3, 3))
Unfortunately, you cannot use x.size(0), since the layer is defined in a Sequential, so you have to know your batch size beforehan… Thank you... | 1,810 | {'text': ['Ah sorry, my bad! I just added my batch size of 1 to the View() layer.\n\nYou should change it to:\n\nencoder:\n\nView((batch_size, -1))\n\ndecoder:\n\nView((batch_size, -1, 3, 3))\n\nUnfortunately, you cannot use x.size(0), since the layer is defined in a Sequential, so you have to know your batch size befo... |
Automatic gradient and torch.sum | Hi,
I use PyTorch’s automatic gradient function to compute the Jacobian and supply it to IPOPT to solve an NLP problem.
Now I want to take the Jacobian of the following equation:
def eval_g(x):
""" The system of non-linear equilibrium conditions
x[0]: Capital stock in the next per… | 0 | 2020-02-06T12:54:31.027Z | Thank you for your comments. After some trials, I finally figured out the way and pass torch.autograd.gradcheck. Just in case, I attach the code below. I appreciate your continuous help.
import numpy as np
import torch
print(r"PyTorch version is {}".format(torch.__version__))
# ------------------… | 0 | 2020-02-12T12:02:39.509Z | https://discuss.pytorch.org/t/automatic-gradient-and-torch-sum/68861/18 | Ah sorry, my bad! I just added my batch size of 1 to the View() layer.
You should change it to:
encoder:
View((batch_size, -1))
decoder:
View((batch_size, -1, 3, 3))
Unfortunately, you cannot use x.size(0), since the layer is defined in a Sequential, so you have to know your batch size beforehan… Thank you... | 1,216 | {'text': ['Thank you for your comments. After some trials, I finally figured out the way and pass torch.autograd.gradcheck. Just in case, I attach the code below. I appreciate your continuous help.\n\nimport numpy as np\n\nimport torch\n\nprint(r"PyTorch version is {}".format(torch.__version__))\n\n# --------... |
Saving a Variable with requires_grad=True in a dictionary is not being updated | Hi, I am still very new to PyTorch and after searching google for this doubt I could not find anything. Hopefully, someone could help me.
I have a forward() method that looks as follows:
def forward(self, feature_vector):
activation_function = {'tanh': torch.tanh, 'relu': F.relu}
s… | 0 | 2019-01-17T19:33:14.914Z | The core reason of “those variables not updated” is because they are not registed in the optimizer. If you look at any optimizer’s constructor, there will be a parameter named params, which is expected to hold the parameters you want to automatically updated by grad.
I’m not sure how you initialize… | 2 | 2019-01-18T05:14:13.169Z | https://discuss.pytorch.org/t/saving-a-variable-with-requires-grad-true-in-a-dictionary-is-not-being-updated/34947/3 | Ah sorry, my bad! I just added my batch size of 1 to the View() layer.
You should change it to:
encoder:
View((batch_size, -1))
decoder:
View((batch_size, -1, 3, 3))
Unfortunately, you cannot use x.size(0), since the layer is defined in a Sequential, so you have to know your batch size beforehan… Thank you... | 631 | {'text': ['The core reason of “those variables not updated” is because they are not registed in the optimizer. If you look at any optimizer’s constructor, there will be a parameter named params, which is expected to hold the parameters you want to automatically updated by grad.\n\nI’m not sure how you initialize&hellip... |
Approximating sine function using neural network | Problem
I am trying to build a function approximator using PyTorch. But my neural network does not seem to learn anything.
[image]
The full executable code is as follows. I am not sure what mistakes I have made. Could someone help me? Thank you in advance.
import torch
import numpy as np
from to… | 0 | 2020-01-06T06:11:36.992Z | This is a dumb mistake. I wrongly return x instead of output in the forward function. The resulting model could successfully approximate the sine function. As could be seen below, the prediction could perfectly match the sine curve in validation data.
[image] | 1 | 2020-01-06T09:06:48.304Z | https://discuss.pytorch.org/t/approximating-sine-function-using-neural-network/65875/2 | This is a dumb mistake. I wrongly return x instead of output in the forward function. The resulting model could successfully approximate the sine function. As could be seen below, the prediction could perfectly match the sine curve in validation data.
[image] On the latest version of PyTorch you can use Tensor.put_ wi... | 1,878 | {'text': ['This is a dumb mistake. I wrongly return x instead of output in the forward function. The resulting model could successfully approximate the sine function. As could be seen below, the prediction could perfectly match the sine curve in validation data.\n\n[image]'], 'answer_start': [1878]} |
Indexing with repeating indices (numpy.add.at) | Hi,
Simple problem, which is already solved in numpy with add.at operator. I want to index with repeating indices over two dimensions. A simple 1D example :
l=torch.ones(5)
i = torch.LongTensor([1, 2, 2, 3])
l[i] += 1
print(l)
Out[52]:
1
2
2 # should be 3
2
1
[torch.FloatTensor of size 5]
I… | 0 | 2017-11-21T16:54:20.951Z | On the latest version of PyTorch you can use Tensor.put_ with accumulate=True:
<a href="http://pytorch.org/docs/master/tensors.html#torch.Tensor.put_" class="onebox" target="_blank">http://pytorch.org/docs/master/tensors.html#torch.Tensor.put_</a>
You will need to translate your indices into linear indexes though. Mo... | 0 | 2017-11-23T06:18:06.910Z | https://discuss.pytorch.org/t/indexing-with-repeating-indices-numpy-add-at/10223/12 | This is a dumb mistake. I wrongly return x instead of output in the forward function. The resulting model could successfully approximate the sine function. As could be seen below, the prediction could perfectly match the sine curve in validation data.
[image] On the latest version of PyTorch you can use Tensor.put_ wi... | 1,200 | {'text': ['On the latest version of PyTorch you can use Tensor.put_ with accumulate=True:\n\n<a href="http://pytorch.org/docs/master/tensors.html#torch.Tensor.put_" class="onebox" target="_blank">http://pytorch.org/docs/master/tensors.html#torch.Tensor.put_</a>\n\nYou will need to translate your indices into linear ind... |
Image lost its pixels(color) after reading from PIL and converting back | Data Fatching
import PIL.Image as Image
import os
import torch
images=torch.zeros(len(df),3,128,128)
for i in range(len(df)):
ak=Image.open(("/content/VOC2012/SegmentationObject")+"/"+df['a'][i]+".png")
ak=transform(ak)
images[i]=ak
Transform–
from torchvision import tran... | 0 | 2019-03-12T06:27:37.814Z | Yes that info is lost in the tensor. If you want the original colors used you have to save the palette.
If you are ok with the red being for example green and the yellow being blue, you can use a new palette. | 1 | 2019-03-14T12:24:34.831Z | https://discuss.pytorch.org/t/image-lost-its-pixels-color-after-reading-from-pil-and-converting-back/39586/14 | This is a dumb mistake. I wrongly return x instead of output in the forward function. The resulting model could successfully approximate the sine function. As could be seen below, the prediction could perfectly match the sine curve in validation data.
[image] On the latest version of PyTorch you can use Tensor.put_ wi... | 677 | {'text': ['Yes that info is lost in the tensor. If you want the original colors used you have to save the palette.\n\nIf you are ok with the red being for example green and the yellow being blue, you can use a new palette.'], 'answer_start': [677]} |
Why amI getting RuntimeError: CUDA error: device-side assert triggered | Hello everyone, hope you are having a great time. I tried to implement a simple VAE! but I’m getting this error out of no where!
The code I’m using is this :
class VAE(nn.Module):
def __init__(self, embedding=100):
super().__init__()
self.fc1 = nn.Linear(28*28, 400)
se… | 0 | 2019-09-11T09:40:47.222Z | Thanks to dear God, I finally found the culprit! it was/is the BCE!
For some weird reason the former versions of Pytorch worked perfectly fine with reduction='mean', however, in the newer Pytorch versions that I tested myself , including (1.1.0 and ultimately 1.2.0+cu92) only reduction='sum' will w&hel... | 1 | 2019-09-12T03:11:58.215Z | https://discuss.pytorch.org/t/why-ami-getting-runtimeerror-cuda-error-device-side-assert-triggered/55686/20 | Thanks to dear God, I finally found the culprit! it was/is the BCE!
For some weird reason the former versions of Pytorch worked perfectly fine with reduction='mean', however, in the newer Pytorch versions that I tested myself , including (1.1.0 and ultimately 1.2.0+cu92) only reduction='sum' will w&hel... | 1,772 | {'text': ['Thanks to dear God, I finally found the culprit! it was/is the BCE!\n\nFor some weird reason the former versions of Pytorch worked perfectly fine with reduction='mean', however, in the newer Pytorch versions that I tested myself , including (1.1.0 and ultimately 1.2.0+cu92) only reduction='sum... |
CTCLoss predicts blanks after a few batches | Hello,
I’m trying to port over a CTC network from Keras. I’ve based the model off of <a href="https://github.com/meijieru/crnn.pytorch/blob/master/models/crnn.py" rel="nofollow noopener">https://github.com/meijieru/crnn.pytorch/blob/master/models/crnn.py</a> (basically replacing the warp_ctc.CTCLoss with the pytorch ... | 0 | 2019-03-18T15:53:58.055Z | Just a note that I’ve managed to solve the issue I was having. Using <a href="https://github.com/Holmeyoung/crnn-pytorch" rel="nofollow noopener">https://github.com/Holmeyoung/crnn-pytorch</a> as a working version compared to mine, the issue was that when I was porting over the dataset from the Keras implementation, t... | 1 | 2019-07-25T17:30:47.699Z | https://discuss.pytorch.org/t/ctcloss-predicts-blanks-after-a-few-batches/40190/16 | Thanks to dear God, I finally found the culprit! it was/is the BCE!
For some weird reason the former versions of Pytorch worked perfectly fine with reduction='mean', however, in the newer Pytorch versions that I tested myself , including (1.1.0 and ultimately 1.2.0+cu92) only reduction='sum' will w&hel... | 1,211 | {'text': ['Just a note that I’ve managed to solve the issue I was having. Using <a href="https://github.com/Holmeyoung/crnn-pytorch" rel="nofollow noopener">https://github.com/Holmeyoung/crnn-pytorch</a> as a working version compared to mine, the issue was that when I was porting over the dataset from the Keras implem... |
Speed benchmarking on android? | I am interested to know how fast some of my models run on the CPUs of a Pixel 3 phone. I am a moderately experienced pytorch programmer and linux user, but I have zero experience with android. I am not looking to build an app right now; I just want to know how fast my model runs on this particular p… | 1 | 2020-01-22T06:55:24.756Z | We have a binary to do this that can run on your android phone using adb.
To build,
./scripts/build_android.sh \
-DBUILD_BINARY=ON \
-DBUILD_CAFFE2_MOBILE=OFF \
-DCMAKE_PREFIX_PAT… | 0 | 2020-01-22T22:53:23.880Z | https://discuss.pytorch.org/t/speed-benchmarking-on-android/67340/2 | Thanks to dear God, I finally found the culprit! it was/is the BCE!
For some weird reason the former versions of Pytorch worked perfectly fine with reduction='mean', however, in the newer Pytorch versions that I tested myself , including (1.1.0 and ultimately 1.2.0+cu92) only reduction='sum' will w&hel... | 715 | {'text': ['We have a binary to do this that can run on your android phone using adb.\n\nTo build,\n\n./scripts/build_android.sh \\\n\n-DBUILD_BINARY=ON \\\n\n-DBUILD_CAFFE2_MOBILE=OFF \\\n\n-DCMAKE_PREFIX_PAT…'], 'answer_start': [715]} |
Getting this warning; Output 0 of BackwardHookFunctionBackward is a view and is being modified inplace | I have checked the post here , trying to fix the warning but I am still getting the warning.
<a href="https://discuss.pytorch.org/t/custom-autograd-function-backward-pass-not-called/71065">Custom Autograd Function Backward pass not Called</a>
/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:1204: UserWar... | 0 | 2021-05-30T07:59:00.760Z | problem is with the inplace in the activation function of your model. You need to disable it. | 1 | 2021-12-10T13:14:09.749Z | https://discuss.pytorch.org/t/getting-this-warning-output-0-of-backwardhookfunctionbackward-is-a-view-and-is-being-modified-inplace/122766/8 | problem is with the inplace in the activation function of your model. You need to disable it. Right.
That should be significantly faster already.
Using fancier function and playing with views, you might be able to narrow it down to a single call. But that shouldn’t be necessary :slight_smile:
import torch
from torc... | 1,814 | {'text': ['problem is with the inplace in the activation function of your model. You need to disable it.'], 'answer_start': [1814]} |
How to preserve autograd of tensor after .detach() and processing it? | Hello!
In the work that I’m doing, after the first conv2d() layer, the output is converted to numpy array to do some processing using .detach(). During this process, the new output will be 3 times bigger and then it is converted back to the tensor to be used as a input for the next conv2d() layer.
… | 0 | 2020-02-03T08:29:40.247Z | Right.
That should be significantly faster already.
Using fancier function and playing with views, you might be able to narrow it down to a single call. But that shouldn’t be necessary :slight_smile:
import torch
from torch.nn import functional as F
import numpy as np
image = torch.randn(1, 1, 6… | 1 | 2020-02-06T17:41:33.743Z | https://discuss.pytorch.org/t/how-to-preserve-autograd-of-tensor-after-detach-and-processing-it/68483/16 | problem is with the inplace in the activation function of your model. You need to disable it. Right.
That should be significantly faster already.
Using fancier function and playing with views, you might be able to narrow it down to a single call. But that shouldn’t be necessary :slight_smile:
import torch
from torc... | 1,001 | {'text': ['Right.\n\nThat should be significantly faster already.\n\nUsing fancier function and playing with views, you might be able to narrow it down to a single call. But that shouldn’t be necessary :slight_smile:\n\nimport torch\n\nfrom torch.nn import functional as F\n\nimport numpy as np\n\nimage = torch.randn(1,... |
Concat image datasets with different size and number of channels | Good evening everyone,
I got a problem with loading multiple datasets and did not find a solution so far.
For loading multiple datasets into one dataloader I can use the ConcatDataset class, but how do I concatenate e.g. CIFAR10 and MNIST. For this I would have CIFAR10 to resize and convert to gra… | 2 | 2019-02-04T15:30:33.973Z | You could specify the transformations for each dataset.
This code should work:
mnist = datasets.MNIST(
root='/home/ptrblck/python/data',
download=False,
transform=transforms.Compose([
transforms.ToTensor()
])
)
cifar = datasets.CIFAR10(
root='/home/ptrblck/python/data'… | 1 | 2019-02-04T17:30:00.950Z | https://discuss.pytorch.org/t/concat-image-datasets-with-different-size-and-number-of-channels/36362/2 | problem is with the inplace in the activation function of your model. You need to disable it. Right.
That should be significantly faster already.
Using fancier function and playing with views, you might be able to narrow it down to a single call. But that shouldn’t be necessary :slight_smile:
import torch
from torc... | 405 | {'text': ['You could specify the transformations for each dataset.\n\nThis code should work:\n\nmnist = datasets.MNIST(\n\nroot='/home/ptrblck/python/data',\n\ndownload=False,\n\ntransform=transforms.Compose([\n\ntransforms.ToTensor()\n\n])\n\n)\n\ncifar = datasets.CIFAR10(\n\nroot='/home/ptrblck/python/dat... |
TypeError: 'DataLoader' object is not callable | train_loader = DataLoader(dataset=dataset, batch_size=40, shuffle=False)
" This is my train loader variable."
for epoch in range(num_epochs):
for i in enumerate(train_loader):
t = train_loader(-1,1).to(device)
outputs = model(t)
loss = criterion(outputs)
optimizer.zero_grad()
loss.backward() … | 0 | 2020-04-01T07:29:11.596Z | I tried your solution and I’m getting this error
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/4/e/4e8efea2dc390fa410092521330ee3162019af63.png" data-download-href="https://discuss.pytorch.org/uploads/default/4e8efea2dc390fa410092521330ee3162019af63" title="Screenshot 2020-04-01 at ... | 0 | 2020-04-01T09:37:19.451Z | https://discuss.pytorch.org/t/typeerror-dataloader-object-is-not-callable/74979/7 | I tried your solution and I’m getting this error
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/4/e/4e8efea2dc390fa410092521330ee3162019af63.png" data-download-href="https://discuss.pytorch.org/uploads/default/4e8efea2dc390fa410092521330ee3162019af63" title="Screenshot 2020-04-01 at ... | 1,416 | {'text': ['I tried your solution and I’m getting this error\n\n<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/4/e/4e8efea2dc390fa410092521330ee3162019af63.png" data-download-href="https://discuss.pytorch.org/uploads/default/4e8efea2dc390fa410092521330ee3162019af63" title="Screenshot 2... |
Loading a few layers from a pretrained MDNet | Hi,
I’m using MDNet, which is a network with 3 conv layers,2 fc layers, plus branches in offline mode or fc layer in online mode (not pretrained, this layer is learned in the offline/online learning).
Thing is, I changed fc5 to add another feature thus I want to load only the weights from the 3 co… | 0 | 2019-05-14T16:51:13.697Z | [image] Nimrod_Daniel:
Plus, what exactly this line mean (‘shared_weights’ is not defined anywhere)?
shared_layers = states[‘shared_layers’]
I guess you are using <a href="https://github.com/HyeonseobNam/py-MDNet" rel="nofollow noopener">this repo</a>. So, in this case, when you load a pth file, say mdnet_vot-otb.pt... | 2 | 2019-05-14T21:11:59.973Z | https://discuss.pytorch.org/t/loading-a-few-layers-from-a-pretrained-mdnet/45221/2 | I tried your solution and I’m getting this error
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/4/e/4e8efea2dc390fa410092521330ee3162019af63.png" data-download-href="https://discuss.pytorch.org/uploads/default/4e8efea2dc390fa410092521330ee3162019af63" title="Screenshot 2020-04-01 at ... | 1,082 | {'text': ['[image] Nimrod_Daniel:\n\nPlus, what exactly this line mean (‘shared_weights’ is not defined anywhere)?\n\nshared_layers = states[‘shared_layers’]\n\nI guess you are using <a href="https://github.com/HyeonseobNam/py-MDNet" rel="nofollow noopener">this repo</a>. So, in this case, when you load a pth file, say... |
New custom convolution | Hi. I am a beginner in Pytorch. I would like to add a new convolutional layer. The new layer will have an extra input called attention layer (Same size as that of the input). Before doing the convolution, the kernels values will be modified using this attention layer and only then the convolution wi… | 0 | 2020-06-11T12:34:53.699Z | class MyConv(nn.Conv2d):
# Assuming you don't want to change the init
def forward(self, input, mask):
bs = input.shape[0]
ch = input.shape[1]
cols = nd2col(input,self.kernel_size, self.dilation, 1, self.stride)
cols_att = nd2col(mask, se… | 1 | 2020-06-11T18:50:43.254Z | https://discuss.pytorch.org/t/new-custom-convolution/85051/9 | I tried your solution and I’m getting this error
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/4/e/4e8efea2dc390fa410092521330ee3162019af63.png" data-download-href="https://discuss.pytorch.org/uploads/default/4e8efea2dc390fa410092521330ee3162019af63" title="Screenshot 2020-04-01 at ... | 761 | {'text': ['class MyConv(nn.Conv2d):\n\n# Assuming you don't want to change the init\n\ndef forward(self, input, mask):\n\nbs = input.shape[0]\n\nch = input.shape[1]\n\ncols = nd2col(input,self.kernel_size, self.dilation, 1, self.stride)\n\ncols_att = nd2col(mask, se…'], 'answer_start': [761]} |
Synchronization slow down caused by .item() which is not caused by .data[0] | I noticed that there is a weird slow down of the training phase when I accumulate the losses using .item() instead of .data[0] (note I am testing this code on google colab GPU). The network is a relatively simple CNN:
import torch
import time
from torch.autograd import Variable
import torchvision
f… | 0 | 2018-06-08T10:47:25.560Z | I think your timing might give weird results, because your synchronization points are different in both implementations.
Calling .item() on a tensor gives you a standard Python number, which is pushed to the CPU.
This line of code would add a synchronization to wait for the GPU to finish calculati… | 1 | 2018-06-08T12:24:24.330Z | https://discuss.pytorch.org/t/synchronization-slow-down-caused-by-item-which-is-not-caused-by-data-0/19394/3 | I think your timing might give weird results, because your synchronization points are different in both implementations.
Calling .item() on a tensor gives you a standard Python number, which is pushed to the CPU.
This line of code would add a synchronization to wait for the GPU to finish calculati… Hey Yin, sp... | 2,032 | {'text': ['I think your timing might give weird results, because your synchronization points are different in both implementations.\n\nCalling .item() on a tensor gives you a standard Python number, which is pushed to the CPU.\n\nThis line of code would add a synchronization to wait for the GPU to finish calculati&hell... |
Dataloader for a folder with multiple files. PyTorch solutions that is equivalent to TFRecordDataset in TF2.0 | Hi,
Suppose I have a folder which contain multiple files, Is there some way for create a dataloader to read the files? For example, after a spark or a mapreduce job, the outputs in a folder is like
part-00000
part-00001
...
part-00999
Usually the files in the folder is very large and cannot fit t… | 0 | 2020-02-20T16:19:44.813Z | Hey Yin, spark to torch dataloader does require some custom work but is fairly easy to build. How I do it is I use torch.utils.data.IterableDataset. Firstly I load all the avro/parquet (as you are working with spark) to a DataReader object which is a generator (where I do some of my custom processin… | 0 | 2020-02-26T14:04:38.875Z | https://discuss.pytorch.org/t/dataloader-for-a-folder-with-multiple-files-pytorch-solutions-that-is-equivalent-to-tfrecorddataset-in-tf2-0/70512/5 | I think your timing might give weird results, because your synchronization points are different in both implementations.
Calling .item() on a tensor gives you a standard Python number, which is pushed to the CPU.
This line of code would add a synchronization to wait for the GPU to finish calculati… Hey Yin, sp... | 1,325 | {'text': ['Hey Yin, spark to torch dataloader does require some custom work but is fairly easy to build. How I do it is I use torch.utils.data.IterableDataset. Firstly I load all the avro/parquet (as you are working with spark) to a DataReader object which is a generator (where I do some of my custom processin…'... |
Model parameters are not being updated? | I made a simple example of a cnn layer where convolutional weights are defined as linear combination of predefined filters. The goal is to train the coefficients of linear combination while keeping predefined filters fixed. This can be easily achieved in tensorflow using tf.nn.conv2d. However here m… | 0 | 2019-02-15T01:40:42.691Z | <a href="https://gist.github.com/InnovArul/ca0db578769186bbaf094c5f8416a8bc" target="_blank" rel="nofollow noopener">https://gist.github.com/InnovArul/ca0db578769186bbaf094c5f8416a8bc</a>
filter_learning.py
from __future__ import print_function
import torch.nn.functional as F
# from torch.autograd import Variable
... | 1 | 2019-02-16T08:15:24.903Z | https://discuss.pytorch.org/t/model-parameters-are-not-being-updated/37233/8 | I think your timing might give weird results, because your synchronization points are different in both implementations.
Calling .item() on a tensor gives you a standard Python number, which is pushed to the CPU.
This line of code would add a synchronization to wait for the GPU to finish calculati… Hey Yin, sp... | 618 | {'text': ['<a href="https://gist.github.com/InnovArul/ca0db578769186bbaf094c5f8416a8bc" target="_blank" rel="nofollow noopener">https://gist.github.com/InnovArul/ca0db578769186bbaf094c5f8416a8bc</a>\n\nfilter_learning.py\n\nfrom __future__ import print_function\n\nimport torch.nn.functional as F\n\n# from torch.autogra... |
Libtorch_cuda.so is too large (>2GB) | We use <a href="https://bazel.build/" rel="noopener nofollow ugc">bazel</a> as part of large monorepo to integrate with torch. In order to support large amounts of concurrent builds, we must execute our build actions remotely and this entails serializing the files needed for the build action. However, protobuf serial... | 0 | 2020-11-17T19:18:29.313Z | The additional compute capabilities might be displayed, since I assume you are linking the CUDA runtime as well as cudnn statically into the wheel. Without removing these architectures in e.g. libcudnn.a via nvprune, these archs should be displayed in the wheel.
Note that I posted the command to bu… | 0 | 2020-11-20T22:02:15.816Z | https://discuss.pytorch.org/t/libtorch-cuda-so-is-too-large-2gb/103155/21 | The additional compute capabilities might be displayed, since I assume you are linking the CUDA runtime as well as cudnn statically into the wheel. Without removing these architectures in e.g. libcudnn.a via nvprune, these archs should be displayed in the wheel.
Note that I posted the command to bu… [image] aau... | 2,096 | {'text': ['The additional compute capabilities might be displayed, since I assume you are linking the CUDA runtime as well as cudnn statically into the wheel. Without removing these architectures in e.g. libcudnn.a via nvprune, these archs should be displayed in the wheel.\n\nNote that I posted the command to bu&hellip... |
Faster Transforms (Precompiled) | Hi all,
I spent some time tracking down the biggest bottleneck in the training phase, which turned out to be the transforms on the input images. 500-3000 tiles need to be interactively transformed using the below Composition, which takes 5-20 seconds. I tried a variety of python tricks to speed t… | 1 | 2020-02-03T15:18:57.029Z | [image] aauker:
Everything is fine technically. I was mostly curious if a pure C++ implementation would actually be faster/possible.
The transforms are all implemented in C under the hood. The PyTorch vision transform functions are just wrappers around the PIL (pillow) library and the PIL ope… | 1 | 2020-02-05T22:32:25.662Z | https://discuss.pytorch.org/t/faster-transforms-precompiled/68527/7 | The additional compute capabilities might be displayed, since I assume you are linking the CUDA runtime as well as cudnn statically into the wheel. Without removing these architectures in e.g. libcudnn.a via nvprune, these archs should be displayed in the wheel.
Note that I posted the command to bu… [image] aau... | 1,357 | {'text': ['[image] aauker:\n\nEverything is fine technically. I was mostly curious if a pure C++ implementation would actually be faster/possible.\n\nThe transforms are all implemented in C under the hood. The PyTorch vision transform functions are just wrappers around the PIL (pillow) library and the PIL ope…']... |
How to apply weighted loss to a binary segmentation problem? | Hi ,
I have a binary segmentation problem. Where the label/target tensor is a simple binary mask where the background is represented by 0 and the foreground (object I want to segment) by 1.
I read that for such problems people have gotten great results using a single channel output, so the output … | 0 | 2019-01-22T16:29:59.580Z | You could just pass a torch.FloatTensor for the positive weight:
output = torch.randn(1, 1, 10, 10, requires_grad=True)
target = torch.randint(0, 2, (1, 1, 10, 10)).float()
criterion = nn.BCEWithLogitsLoss(pos_weight=torch.tensor(10.))
loss = criterion(output, target)
Let me know, if that works fo… | 4 | 2019-01-23T18:36:21.278Z | https://discuss.pytorch.org/t/how-to-apply-weighted-loss-to-a-binary-segmentation-problem/35317/4 | The additional compute capabilities might be displayed, since I assume you are linking the CUDA runtime as well as cudnn statically into the wheel. Without removing these architectures in e.g. libcudnn.a via nvprune, these archs should be displayed in the wheel.
Note that I posted the command to bu… [image] aau... | 613 | {'text': ['You could just pass a torch.FloatTensor for the positive weight:\n\noutput = torch.randn(1, 1, 10, 10, requires_grad=True)\n\ntarget = torch.randint(0, 2, (1, 1, 10, 10)).float()\n\ncriterion = nn.BCEWithLogitsLoss(pos_weight=torch.tensor(10.))\n\nloss = criterion(output, target)\n\nLet me know, if that work... |
Importing and concatenating images along given dimension | UPDATED: Clarifying the question and providing my code.
I have a dataset of RGB images as well as the corresponding Alpha map images (image mode=P). I would like to import and concatenate the alpha maps with the RGB images to create a 4-channel RGBA input for the network. Currently, my code is crea… | 0 | 2017-12-13T21:05:57.403Z | I assume you could simply add a <a href="http://pytorch.org/docs/master/torchvision/transforms.html#torchvision.transforms.Grayscale" rel="nofollow noopener">grayscale transform</a> to the list of transforms. | 1 | 2017-12-29T10:07:18.942Z | https://discuss.pytorch.org/t/importing-and-concatenating-images-along-given-dimension/11130/11 | I assume you could simply add a <a href="http://pytorch.org/docs/master/torchvision/transforms.html#torchvision.transforms.Grayscale" rel="nofollow noopener">grayscale transform</a> to the list of transforms. Different processes do not share memory. So after the loader is running, they are different objects. Your train... | 1,848 | {'text': ['I assume you could simply add a <a href="http://pytorch.org/docs/master/torchvision/transforms.html#torchvision.transforms.Grayscale" rel="nofollow noopener">grayscale transform</a> to the list of transforms.'], 'answer_start': [1848]} |
Do multiple Dataloader processes share resource reader instances? | I’m running into a problem with my data file reader, and I believe it may be because this specific file reader can’t be used by multiple processes at the same time. Does the Dataloader’s processes share the file readers? That is, if my custom Dataset has a self.my_file_reader = MyFileReader(file_pat… | 1 | 2017-11-08T02:28:02.155Z | Different processes do not share memory. So after the loader is running, they are different objects. | 0 | 2017-11-08T02:36:52.707Z | https://discuss.pytorch.org/t/do-multiple-dataloader-processes-share-resource-reader-instances/9629/2 | I assume you could simply add a <a href="http://pytorch.org/docs/master/torchvision/transforms.html#torchvision.transforms.Grayscale" rel="nofollow noopener">grayscale transform</a> to the list of transforms. Different processes do not share memory. So after the loader is running, they are different objects. Your train... | 1,133 | {'text': ['Different processes do not share memory. So after the loader is running, they are different objects.'], 'answer_start': [1133]} |
Dataset is not callable | Hy guys, I have a strange error and I don’t know why.
This is my code:
from torch.utils.data.dataset import Dataset
import pandas as pd
from PIL import Image
from os import path
import numpy as np
from torchvision import transforms
class Dataset(Dataset):
def __init__(self, base_path, Inten… | 1 | 2020-08-19T09:51:25.864Z | Your train dataset name is same as that of train function…, so in effect you are calling the dataset (which is rightly not callable) instead of the train function. | 3 | 2020-08-19T15:27:50.578Z | https://discuss.pytorch.org/t/dataset-is-not-callable/93350/15 | I assume you could simply add a <a href="http://pytorch.org/docs/master/torchvision/transforms.html#torchvision.transforms.Grayscale" rel="nofollow noopener">grayscale transform</a> to the list of transforms. Different processes do not share memory. So after the loader is running, they are different objects. Your train... | 310 | {'text': ['Your train dataset name is same as that of train function…, so in effect you are calling the dataset (which is rightly not callable) instead of the train function.'], 'answer_start': [310]} |
Changing transforms after creating a dataset | i’m using torchvision.datasets.ImageFolder (which takes transform as input) to read my data, then i split it to train and test sets using torch.utils.data.Subset. until now i applied the same transforms to all images, doesn’t matter whether they’re train or test, but now i want to change it.
is it … | 1 | 2019-12-24T22:33:43.041Z | I think you meant:
train_dataset = MyDataset(train_transform)
val_dataset = MyDataset(val_transform)
train_indices, val_indices = sklearn.model_selection.train_test_split(indices)
train_dataset = torch.utils.data.Subset(train_dataset, train_indices)
val_dataset = torch.utils.data.Subset(val_dataset… | 1 | 2021-12-17T21:47:55.364Z | https://discuss.pytorch.org/t/changing-transforms-after-creating-a-dataset/64929/7 | I think you meant:
train_dataset = MyDataset(train_transform)
val_dataset = MyDataset(val_transform)
train_indices, val_indices = sklearn.model_selection.train_test_split(indices)
train_dataset = torch.utils.data.Subset(train_dataset, train_indices)
val_dataset = torch.utils.data.Subset(val_dataset… I think... | 946 | {'text': ['I think you meant:\n\ntrain_dataset = MyDataset(train_transform)\n\nval_dataset = MyDataset(val_transform)\n\ntrain_indices, val_indices = sklearn.model_selection.train_test_split(indices)\n\ntrain_dataset = torch.utils.data.Subset(train_dataset, train_indices)\n\nval_dataset = torch.utils.data.Subset(val_da... |
Creating a DataLoader for unsupervised learning (MNIST, SVHN) | I need to solve an unsupervised problem with images from MNIST and SVHN, in which I have 100 images from MNIST and 10 images from SVHN). I need a pre-trained net to learn how to classify if a given image is from MNIST or SVHN (the anomaly). Basically, it’s an anomaly detection problem.
I know I’ll… | 0 | 2019-05-29T09:57:16.638Z | I think the easiest approach would be to write a custom Dataset, and load the desired samples inside of __init__.
Since the data format is different for MNIST and CIFAR (size and number of channels), you would also need to specify some dataset-specific transformations.
Here is a small sample code,… | 1 | 2019-05-29T11:38:55.324Z | https://discuss.pytorch.org/t/creating-a-dataloader-for-unsupervised-learning-mnist-svhn/46523/2 | I think you meant:
train_dataset = MyDataset(train_transform)
val_dataset = MyDataset(val_transform)
train_indices, val_indices = sklearn.model_selection.train_test_split(indices)
train_dataset = torch.utils.data.Subset(train_dataset, train_indices)
val_dataset = torch.utils.data.Subset(val_dataset… I think... | 786 | {'text': ['I think the easiest approach would be to write a custom Dataset, and load the desired samples inside of __init__.\n\nSince the data format is different for MNIST and CIFAR (size and number of channels), you would also need to specify some dataset-specific transformations.\n\nHere is a small sample code,&hell... |
How do I get my older GPU that supports CUDA to work with PyTorch 1.4? | I’m using anaconda for python 3.7, and have CUDA 10.1 installed. My GPU is a GTX 760, with 3.0 CUDA capability. I’m getting true values for torch.cuda.is_available , but I keep getting this error whenever I try to use CUDA for anything.
Here’s the error:
RuntimeError: CUDA error: no kernel image i… | 0 | 2020-02-07T19:12:36.276Z | Thanks for the error message.
Could you refer to <a href="https://github.com/pytorch/pytorch/issues/25393#issuecomment-566286374">this post</a>, install the latest VS 2019, and try to rebuild it?
Please let us know, if you are continuously running into this error, as it seems to be hard to reproduce on the Windows CI... | 1 | 2020-02-10T02:42:42.523Z | https://discuss.pytorch.org/t/how-do-i-get-my-older-gpu-that-supports-cuda-to-work-with-pytorch-1-4/69005/6 | I think you meant:
train_dataset = MyDataset(train_transform)
val_dataset = MyDataset(val_transform)
train_indices, val_indices = sklearn.model_selection.train_test_split(indices)
train_dataset = torch.utils.data.Subset(train_dataset, train_indices)
val_dataset = torch.utils.data.Subset(val_dataset… I think... | 622 | {'text': ['Thanks for the error message.\n\nCould you refer to <a href="https://github.com/pytorch/pytorch/issues/25393#issuecomment-566286374">this post</a>, install the latest VS 2019, and try to rebuild it?\n\nPlease let us know, if you are continuously running into this error, as it seems to be hard to reproduce on... |
Torch.cat and backpropagation | Does torch.cat work with backpropagation? | 0 | 2020-03-30T14:21:55.518Z | And if I wanted to concatenate a list of tensors, how would I do it with cat? | 0 | 2020-03-30T18:41:27.973Z | https://discuss.pytorch.org/t/torch-cat-and-backpropagation/74802/13 | And if I wanted to concatenate a list of tensors, how would I do it with cat? Have you used with torch.no_grad() during your test phase? This will avoid storing the intermediate variables needed for the backward pass, which is not necessary for testing. You can use something like this <a href="https://github.com/ngimel... | 1,886 | {'text': ['And if I wanted to concatenate a list of tensors, how would I do it with cat?'], 'answer_start': [1886]} |
Is it possible to Free-up a Dataloader? | I am using different Dataloaders for train set and test set, so in all, I have 2 Dataloaders.
I do training and testing in every epoch.
Is there a way I can free up the Dataloader not being used (for eg. free-up the train dataloader while testing; and free-up test dataloader while training) so as … | 0 | 2018-07-21T21:49:41.693Z | Have you used with torch.no_grad() during your test phase? This will avoid storing the intermediate variables needed for the backward pass, which is not necessary for testing. | 1 | 2018-07-22T21:19:07.458Z | https://discuss.pytorch.org/t/is-it-possible-to-free-up-a-dataloader/21498/6 | And if I wanted to concatenate a list of tensors, how would I do it with cat? Have you used with torch.no_grad() during your test phase? This will avoid storing the intermediate variables needed for the backward pass, which is not necessary for testing. You can use something like this <a href="https://github.com/ngimel... | 1,021 | {'text': ['Have you used with torch.no_grad() during your test phase? This will avoid storing the intermediate variables needed for the backward pass, which is not necessary for testing.'], 'answer_start': [1021]} |
Tensor Cores and mixed precision *matrix multiplication* - output in float32 | <a href="https://devblogs.nvidia.com/programming-tensor-cores-cuda-9/" rel="nofollow noopener">https://devblogs.nvidia.com/programming-tensor-cores-cuda-9/</a> states that “Each Tensor Core performs 64 floating point FMA mixed-precision operations per clock (FP16 input multiply with full-precision product and FP32 accu... | 1 | 2019-04-17T11:15:39.121Z | You can use something like this <a href="https://github.com/ngimel/rnn_ext" rel="nofollow noopener">https://github.com/ngimel/rnn_ext</a>, it’s more complicated than you need but it shows how to call cublas directly from extension. | 1 | 2019-04-18T16:01:06.846Z | https://discuss.pytorch.org/t/tensor-cores-and-mixed-precision-matrix-multiplication-output-in-float32/42831/8 | And if I wanted to concatenate a list of tensors, how would I do it with cat? Have you used with torch.no_grad() during your test phase? This will avoid storing the intermediate variables needed for the backward pass, which is not necessary for testing. You can use something like this <a href="https://github.com/ngimel... | 254 | {'text': ['You can use something like this <a href="https://github.com/ngimel/rnn_ext" rel="nofollow noopener">https://github.com/ngimel/rnn_ext</a>, it’s more complicated than you need but it shows how to call cublas directly from extension.'], 'answer_start': [254]} |
Access to grad_output (the input to the backward) | Hi,
In this <a href="https://pytorch.org/tutorials/beginner/examples_autograd/two_layer_net_custom_function.html" rel="nofollow noopener">tutorial</a>, it is mentioned that backward receives a tensor (grad_output) but when we run loss.backward(), loss is a scalar. I see scalar is also a tensor but if grad_output is s... | 0 | 2019-10-02T18:46:29.255Z | I could successfully bypass loss.backward() in a simple network for both MSE loss and CrossEntropy loss and I replaced it with a backward network. For future reference, I am sharing the code. Thanks albanD!
import torch.nn as nn
import torch.optim as optim
import torchvision
import numpy as np
imp… | 4 | 2019-10-04T14:27:07.692Z | https://discuss.pytorch.org/t/access-to-grad-output-the-input-to-the-backward/57349/11 | I could successfully bypass loss.backward() in a simple network for both MSE loss and CrossEntropy loss and I replaced it with a backward network. For future reference, I am sharing the code. Thanks albanD!
import torch.nn as nn
import torch.optim as optim
import torchvision
import numpy as np
imp… Save you... | 970 | {'text': ['I could successfully bypass loss.backward() in a simple network for both MSE loss and CrossEntropy loss and I replaced it with a backward network. For future reference, I am sharing the code. Thanks albanD!\n\nimport torch.nn as nn\n\nimport torch.optim as optim\n\nimport torchvision\n\nimport numpy as np\n\... |
Right ways to serialize and load DDP model checkpoints | I have trained a model using DistributedDataParallel. After training, I serialized the model like so where the model is wrapped using DistributedDataParallel:
torch.save(model.state_dict(), 'model.pt')
Note that this serialization was performed in the launcher function which is typically passed to… | 1 | 2021-05-29T16:51:23.232Z | Save your DDP model after unwrapping DataParallel, such as,
torch.save(model.module.state_dict(), 'model.pt')
Here, model.module is where your original model (before DDP wrapping) is placed. | 1 | 2021-05-29T18:13:45.609Z | https://discuss.pytorch.org/t/right-ways-to-serialize-and-load-ddp-model-checkpoints/122719/2 | I could successfully bypass loss.backward() in a simple network for both MSE loss and CrossEntropy loss and I replaced it with a backward network. For future reference, I am sharing the code. Thanks albanD!
import torch.nn as nn
import torch.optim as optim
import torchvision
import numpy as np
imp… Save you... | 797 | {'text': ['Save your DDP model after unwrapping DataParallel, such as,\n\ntorch.save(model.module.state_dict(), 'model.pt')\n\nHere, model.module is where your original model (before DDP wrapping) is placed.'], 'answer_start': [797]} |
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation when using distributed training | Hi. I’m using the following 1D resnet. I can train it in the non-distributed mode without any error but when switching to data distributed parallel mode I get the gradient computation has been modified by an in-place operation which usually occurs for in-place operations.
class MyConv1dPadSame(… | 1 | 2020-12-23T12:31:50.972Z | <a class="mention" href="/u/shaoming20798">@shaoming20798</a>
Yes. my problem was the normal batch norm is not working with DDP so I replaced it with <a href="https://pytorch.org/docs/stable/generated/torch.nn.SyncBatchNorm.html" rel="noopener nofollow ugc">syncedbatchnorm</a>
the way I used the synced batch norm
de... | 1 | 2021-01-14T10:11:52.356Z | https://discuss.pytorch.org/t/runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation-when-using-distributed-training/106969/10 | I could successfully bypass loss.backward() in a simple network for both MSE loss and CrossEntropy loss and I replaced it with a backward network. For future reference, I am sharing the code. Thanks albanD!
import torch.nn as nn
import torch.optim as optim
import torchvision
import numpy as np
imp… Save you... | 513 | {'text': ['<a class="mention" href="/u/shaoming20798">@shaoming20798</a>\n\nYes. my problem was the normal batch norm is not working with DDP so I replaced it with <a href="https://pytorch.org/docs/stable/generated/torch.nn.SyncBatchNorm.html" rel="noopener nofollow ugc">syncedbatchnorm</a>\n\nthe way I used the synced... |
Different ouputs for the same network | Hi again,
This may seems as a stupid question but I have different outputs for the same network every time I train just for the forward pass.
the shape of the network looks like this :
self.features = torch.nn.Sequential(
# conv1
torch.nn.Conv2d(3,64,3,padding=35),
… | 0 | 2018-02-14T08:52:11.373Z | Yes, weight initialization is one crucial step in training a network from scratch.
PyTorch has a lot of different <a href="http://pytorch.org/docs/master/nn.html#torch-nn-init" rel="nofollow noopener">init functions</a>.
E.g. one popular method for conv layers is xavier_uniform. Depending on your architecture, differ... | 0 | 2018-02-14T14:31:55.781Z | https://discuss.pytorch.org/t/different-ouputs-for-the-same-network/13641/20 | Yes, weight initialization is one crucial step in training a network from scratch.
PyTorch has a lot of different <a href="http://pytorch.org/docs/master/nn.html#torch-nn-init" rel="nofollow noopener">init functions</a>.
E.g. one popular method for conv layers is xavier_uniform. Depending on your architecture, differ... | 2,006 | {'text': ['Yes, weight initialization is one crucial step in training a network from scratch.\n\nPyTorch has a lot of different <a href="http://pytorch.org/docs/master/nn.html#torch-nn-init" rel="nofollow noopener">init functions</a>.\n\nE.g. one popular method for conv layers is xavier_uniform. Depending on your archi... |
How to visualize Backward (and perhaps DoubleBackward) pass of variable? | Hi All,
I was just wondering if it’s possible to visualize the backward pass (including the shape of the Tensors in the computation). This is because I’ve been writing my own custom Autograd function with a custom Backward and custom DoubleBackward and when I run my network, I get a mismatch error … | 1 | 2021-01-10T21:09:46.321Z | Ho if one has 1 as batch and the other B, then it will broadcast which is not what you want to do here for sure. This is most likely the issue indeed. | 1 | 2021-01-12T20:16:45.520Z | https://discuss.pytorch.org/t/how-to-visualize-backward-and-perhaps-doublebackward-pass-of-variable/108456/19 | Yes, weight initialization is one crucial step in training a network from scratch.
PyTorch has a lot of different <a href="http://pytorch.org/docs/master/nn.html#torch-nn-init" rel="nofollow noopener">init functions</a>.
E.g. one popular method for conv layers is xavier_uniform. Depending on your architecture, differ... | 1,403 | {'text': ['Ho if one has 1 as batch and the other B, then it will broadcast which is not what you want to do here for sure. This is most likely the issue indeed.'], 'answer_start': [1403]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.