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 |
|---|---|---|---|---|---|---|---|---|---|---|
Unused model parameters affect optimization for Adam | I recently encounter a situation where some of the model parameters will not be updated during certain iterations. The unused parameters are those are not in computation graph (after backward(), the gradients of those unused parameters is None)
I find the training result is different when I do not … | 3 | 2018-10-19T06:17:55.101Z | No, the manual seed is not the issue. I’ve just used it in my first example to show, that the optimizer does not have any problems optimizing a model with unused parameters.
Even if we copy all parameters between models, the optimizer works identically.
So back to your original question. The discr… | 2 | 2018-10-26T12:11:33.163Z | https://discuss.pytorch.org/t/unused-model-parameters-affect-optimization-for-adam/27563/20 | In your current code snippet you are assigning x to your complete dataset, i.e. you are performing batch gradient descent.
In the former code your DataLoader provided batches of size 5, so you used mini-batch gradient descent.
If you use a dataloader with batch_size=1 or slice each sample one by o… When it say... | 618 | {'text': ['No, the manual seed is not the issue. I’ve just used it in my first example to show, that the optimizer does not have any problems optimizing a model with unused parameters.\n\nEven if we copy all parameters between models, the optimizer works identically.\n\nSo back to your original question. The discr&hell... |
Adam+Half Precision = NaNs? | Hi guys,
I’ve been running into the sudden appearance of NaNs when I attempt to train using Adam and Half (float16) precision; my nets train just fine on half precision with SGD+nesterov momentum, and they train just fine with single precision (float32) and Adam, but switching them over to half see… | 0 | 2017-04-09T20:37:22.516Z | It’s probably a 0 division somewhere. Have you tried using a much larger eps (say 1e-4)? The default 1e-8 is rounded to 0 in half precision. | 12 | 2017-04-29T14:38:26.901Z | https://discuss.pytorch.org/t/adam-half-precision-nans/1765/5 | It’s probably a 0 division somewhere. Have you tried using a much larger eps (say 1e-4)? The default 1e-8 is rounded to 0 in half precision. You can use the scripts provided in the transformers library. These are well-tested and provide many useful options. For BERT in particular, you can have a look <a href="https://g... | 1,852 | {'text': ['It’s probably a 0 division somewhere. Have you tried using a much larger eps (say 1e-4)? The default 1e-8 is rounded to 0 in half precision.'], 'answer_start': [1852]} |
Bert additional pre-training | I would like to use transformers/hugging face library to further pretrain BERT. I found the masked LM/ pretrain model, and a usage <a href="https://huggingface.co/transformers/model_doc/bert.html#bertforpretraining" rel="nofollow noopener">example</a>, but not a training example.
In the original BERT repo I have this ... | 3 | 2020-02-20T20:26:35.463Z | You can use the scripts provided in the transformers library. These are well-tested and provide many useful options. For BERT in particular, you can have a look <a href="https://github.com/huggingface/transformers/tree/master/examples/language-modeling#robertabertdistilbert-and-masked-language-modeling" rel="noopener n... | 0 | 2020-11-18T12:38:30.920Z | https://discuss.pytorch.org/t/bert-additional-pre-training/70539/18 | It’s probably a 0 division somewhere. Have you tried using a much larger eps (say 1e-4)? The default 1e-8 is rounded to 0 in half precision. You can use the scripts provided in the transformers library. These are well-tested and provide many useful options. For BERT in particular, you can have a look <a href="https://g... | 1,067 | {'text': ['You can use the scripts provided in the transformers library. These are well-tested and provide many useful options. For BERT in particular, you can have a look <a href="https://github.com/huggingface/transformers/tree/master/examples/language-modeling#robertabertdistilbert-and-masked-language-modeling" rel=... |
Legacy autograd function with non-static forward method is deprecated and will be removed in 1.3 | Hi,
Do you know why a have this warning, and what I need to modify so that it doesn’t appear:
/pytorch/torch/csrc/autograd/python_function.cpp:622: UserWarning: Legacy autograd function with non-static forward method is deprecated and will be removed in 1.3. Please use new-style autograd function … | 0 | 2020-02-15T23:42:32.212Z | Try to use:
x, mean = BinActive.apply(x) | 2 | 2020-02-16T21:49:39.149Z | https://discuss.pytorch.org/t/legacy-autograd-function-with-non-static-forward-method-is-deprecated-and-will-be-removed-in-1-3/69869/4 | It’s probably a 0 division somewhere. Have you tried using a much larger eps (say 1e-4)? The default 1e-8 is rounded to 0 in half precision. You can use the scripts provided in the transformers library. These are well-tested and provide many useful options. For BERT in particular, you can have a look <a href="https://g... | 627 | {'text': ['Try to use:\n\nx, mean = BinActive.apply(x)'], 'answer_start': [627]} |
Test accuracy with different batch sizes | this is a newby question I am asking here but for some reason, when I change the batch size at test time, the accuracy of my model changes. Decreasing the batch size reduces the accuracy until a batch size of 1 leads to 11% accuracy although the same model gives me 97% accuracy with a test batch siz… | 1 | 2018-08-11T18:01:48.064Z | Thank you so much everyone for your help. <a href="https://discuss.pytorch.org/t/test-accuracy-with-different-batch-sizes/23049/4">Steve_cruz</a> helped me solve my error. I retrained my model be removing the last softmax layer since cross entropy loss applies softmax itself. Also I decorated my evaluation function wit... | 1 | 2018-08-16T23:48:20.983Z | https://discuss.pytorch.org/t/test-accuracy-with-different-batch-sizes/22930/18 | Thank you so much everyone for your help. <a href="https://discuss.pytorch.org/t/test-accuracy-with-different-batch-sizes/23049/4">Steve_cruz</a> helped me solve my error. I retrained my model be removing the last softmax layer since cross entropy loss applies softmax itself. Also I decorated my evaluation function wit... | 1,336 | {'text': ['Thank you so much everyone for your help. <a href="https://discuss.pytorch.org/t/test-accuracy-with-different-batch-sizes/23049/4">Steve_cruz</a> helped me solve my error. I retrained my model be removing the last softmax layer since cross entropy loss applies softmax itself. Also I decorated my evaluation f... |
Batchnorm.eval() cause worst result | I have sequential model with several convolutions and batchnorms. After training I save it and load in other place. Now if I load and feed my model I get good results (same loss that I have after training), but if after loading I call model.eval() I get much worse losses. Before that I think eval() … | 3 | 2018-04-04T16:03:19.701Z | Generally, BatchNorm sizes shouldn’t be smaller than 32 to get good results. Maybe see the recent GroupNorm paper by Wu & He which references this issue. In the paper itself, I think they got also good results with batchsize 16 in batchnorm, but 32 would be the rule-of-thumb recommended minimum.
<a href="https://a... | 4 | 2018-04-06T20:00:56.284Z | https://discuss.pytorch.org/t/batchnorm-eval-cause-worst-result/15948/12 | Thank you so much everyone for your help. <a href="https://discuss.pytorch.org/t/test-accuracy-with-different-batch-sizes/23049/4">Steve_cruz</a> helped me solve my error. I retrained my model be removing the last softmax layer since cross entropy loss applies softmax itself. Also I decorated my evaluation function wit... | 1,070 | {'text': ['Generally, BatchNorm sizes shouldn’t be smaller than 32 to get good results. Maybe see the recent GroupNorm paper by Wu & He which references this issue. In the paper itself, I think they got also good results with batchsize 16 in batchnorm, but 32 would be the rule-of-thumb recommended minimum.\n\n<a hr... |
PyTorch 1.6 - "Tesla T4 with CUDA capability sm_75 is not compatible" | I installed PyTorch 1.6 with pip as follows.
pip install --no-cache-dir torch==1.6.0+cu101 torchvision==0.7.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html
However, PyTorch prints the following now.
Tesla T4 with CUDA capability sm_75 is not compatible with the current PyTorch insta… | 2 | 2020-07-29T20:49:23.398Z | okay, I got an update. <a class="mention" href="/u/seemethere">@seemethere</a> is fixing the issue and re-uploading the cuda 10.1 binaries asap, like in ~3 hours or so | 6 | 2020-07-30T19:49:38.332Z | https://discuss.pytorch.org/t/pytorch-1-6-tesla-t4-with-cuda-capability-sm-75-is-not-compatible/91003/11 | Thank you so much everyone for your help. <a href="https://discuss.pytorch.org/t/test-accuracy-with-different-batch-sizes/23049/4">Steve_cruz</a> helped me solve my error. I retrained my model be removing the last softmax layer since cross entropy loss applies softmax itself. Also I decorated my evaluation function wit... | 819 | {'text': ['okay, I got an update. <a class="mention" href="/u/seemethere">@seemethere</a> is fixing the issue and re-uploading the cuda 10.1 binaries asap, like in ~3 hours or so'], 'answer_start': [819]} |
Dataloader on two datasets | We are writing some code to read two different datasets <a href="https://pytorch.org/tutorials/beginner/data_loading_tutorial.html#data-loading-and-processing-tutorial" rel="nofollow noopener">based on the tutorial</a>, and thus, we will have:
train_set1, test_set1,
train_set2, test_set2
We want to investigate each ... | 1 | 2018-05-22T11:39:10.685Z | FYI, just to update this topic in case someone else is looking for a good answer, there is now a <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.ConcatDataset" rel="nofollow noopener">ConcatDataset</a> in Pytorch that does pretty much what the author was looking for. | 3 | 2019-03-14T19:36:18.395Z | https://discuss.pytorch.org/t/dataloader-on-two-datasets/18504/7 | FYI, just to update this topic in case someone else is looking for a good answer, there is now a <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.ConcatDataset" rel="nofollow noopener">ConcatDataset</a> in Pytorch that does pretty much what the author was looking for. Make sure to use <a href="https:... | 1,972 | {'text': ['FYI, just to update this topic in case someone else is looking for a good answer, there is now a <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.ConcatDataset" rel="nofollow noopener">ConcatDataset</a> in Pytorch that does pretty much what the author was looking for.'], 'answer_start': [1... |
How to get gradients of each node in the network (not weights) | .grad() method returns gradient values for each weight in the network. However, how can I get gradient values for each node in the network? Or is it safe to simply add gradients for each weight that corresponds to a specific node? | 4 | 2022-03-10T08:00:20.877Z | Make sure to use <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html?highlight=full_backward#torch.nn.Module.register_full_backward_hook" rel="noopener nofollow ugc">register_full_backward_hook</a> and not <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.regist... | 2 | 2022-03-10T23:14:58.677Z | https://discuss.pytorch.org/t/how-to-get-gradients-of-each-node-in-the-network-not-weights/146024/8 | FYI, just to update this topic in case someone else is looking for a good answer, there is now a <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.ConcatDataset" rel="nofollow noopener">ConcatDataset</a> in Pytorch that does pretty much what the author was looking for. Make sure to use <a href="https:... | 1,274 | {'text': ['Make sure to use <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html?highlight=full_backward#torch.nn.Module.register_full_backward_hook" rel="noopener nofollow ugc">register_full_backward_hook</a> and not <a href="https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Mo... |
How do you determine the layer type? | I want to iterate through the children() of a module,
and identify all the convolutional layers (for instance), or maybe all the maxpool layers, to do something with them.
How can I determine the type of layer?
My code would be something like this:
for layer in net.children():
if layer is a … | 1 | 2018-06-07T01:09:28.868Z | Do you plan to treat Conv1d, Conv2d and so far as different? If you were only looking for Conv2d layers you can do something like:
for layer in net.children():
if isinstance(layer, nn.Conv2d):
do something with the layer
isinstance is a Python built-in <a href="https://docs.python.org/3/library/functions.html#isins... | 8 | 2018-06-07T04:42:23.638Z | https://discuss.pytorch.org/t/how-do-you-determine-the-layer-type/19309/2 | FYI, just to update this topic in case someone else is looking for a good answer, there is now a <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.ConcatDataset" rel="nofollow noopener">ConcatDataset</a> in Pytorch that does pretty much what the author was looking for. Make sure to use <a href="https:... | 753 | {'text': ['Do you plan to treat Conv1d, Conv2d and so far as different? If you were only looking for Conv2d layers you can do something like:\n\nfor layer in net.children():\n\nif isinstance(layer, nn.Conv2d):\n\ndo something with the layer\n\nisinstance is a Python built-in <a href="https://docs.python.org/3/library/f... |
Is there anybody happen this error? | /opt/conda/conda-bld/pytorch_1512386481460/work/torch/lib/THCUNN/SpatialClassNLLCriterion.cu:99: void cunn_SpatialClassNLLCriterion_updateOutput_kernel(T *, T *, T *, long *, T *, int, int, int, int, int, long) [with T = float, AccumT = float]: block: [0,0,0], thread: [1017,0,0] Assertion t >= 0 && … | 1 | 2018-05-03T07:46:24.489Z | Most likely since cv2.resize uses some interpolation method (default is linear interpolation if I’m not mistaken) other than “nearest neighbors”.
Try to pass cv2.INTER_NEAREST as the method to this function. | 1 | 2019-07-16T15:02:50.841Z | https://discuss.pytorch.org/t/is-there-anybody-happen-this-error/17416/16 | Most likely since cv2.resize uses some interpolation method (default is linear interpolation if I’m not mistaken) other than “nearest neighbors”.
Try to pass cv2.INTER_NEAREST as the method to this function. Could you try to uninstall PyTorch and run the following command instead:
from os import path
from wheel.pep4... | 2,298 | {'text': ['Most likely since cv2.resize uses some interpolation method (default is linear interpolation if I’m not mistaken) other than “nearest neighbors”.\n\nTry to pass cv2.INTER_NEAREST as the method to this function.'], 'answer_start': [2298]} |
Pytorch 0.4.0 on Google colab | It looks like I have installed the version 0.4.0 successfully as the attached screenshot.
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/c/cf9f98dcada39c0f408de88e0fa2fd5c1690e66f.png" data-download-href="https://discuss.pytorch.org/uploads/default/cf9f98dcada39c0f408de88e0fa2fd5c169... | 1 | 2018-05-02T03:06:35.978Z | Could you try to uninstall PyTorch and run the following command instead:
from os import path
from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag
platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())
accelerator = 'cu80' if path.exists('/opt/bin/nvidia-smi... | 12 | 2018-05-02T11:47:44.004Z | https://discuss.pytorch.org/t/pytorch-0-4-0-on-google-colab/17329/2 | Most likely since cv2.resize uses some interpolation method (default is linear interpolation if I’m not mistaken) other than “nearest neighbors”.
Try to pass cv2.INTER_NEAREST as the method to this function. Could you try to uninstall PyTorch and run the following command instead:
from os import path
from wheel.pep4... | 1,358 | {'text': ['Could you try to uninstall PyTorch and run the following command instead:\n\nfrom os import path\n\nfrom wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag\n\nplatform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())\n\naccelerator = 'cu80' if path.exists('... |
Cuda runtime error (999) | Just getting started with PyTorch (very nice system, btw). Unfortunately, The last couple days I’ve been trying to run unmodified tutorial code in PyCharm (mostly transformer_tutorial.py). Sometimes I get the following error in PyCharm:
THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_157902206… | 1 | 2020-02-13T21:33:38.316Z | Hello, I ended up with this solution, no reboot requires:
sudo rmmod nvidia_uvm
sudo modprobe nvidia_uvm
After executing such commands, I can use PyTorch again. | 5 | 2020-07-01T10:30:45.160Z | https://discuss.pytorch.org/t/cuda-runtime-error-999/69658/21 | Most likely since cv2.resize uses some interpolation method (default is linear interpolation if I’m not mistaken) other than “nearest neighbors”.
Try to pass cv2.INTER_NEAREST as the method to this function. Could you try to uninstall PyTorch and run the following command instead:
from os import path
from wheel.pep4... | 544 | {'text': ['Hello, I ended up with this solution, no reboot requires:\n\nsudo rmmod nvidia_uvm\n\nsudo modprobe nvidia_uvm\n\nAfter executing such commands, I can use PyTorch again.'], 'answer_start': [544]} |
How to modify a pretrained model | Hey there,
I am working on Bilinear CNN for Image Classification. I am trying to modify the pretrained VGG-Net Classifier and modify the final layers for fine-grained classification. I have designed the code snipper that I want to attach after the final layers of VGG-Net but I don’t know-how. Can a… | 0 | 2019-11-10T04:57:34.433Z | I got it working! This works:
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. network or layer) and put batch norms if present
for attr_str in… | 0 | 2020-10-01T18:53:41.807Z | https://discuss.pytorch.org/t/how-to-modify-a-pretrained-model/60509/10 | I got it working! This works:
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. network or layer) and put batch norms if present
for attr_str in… The c+... | 1,414 | {'text': ['I got it working! This works:\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 (e.g. network or layer) and put batch norms if present\n\nfor a... |
Memory leak in LibTorch, extremely simple code | I have the following tiny code snippet, which allocates a new chunk of CUDA memory every time I call model.forward():
auto model = torch::jit::load("model.tm");
auto out = torch::empty({1, 512, 512});
for (int i = 0; i < 20; i++) {
auto in = torch::empty({1, 3, 512, 512}, torch::kCUDA);
auto r&hell... | 1 | 2019-02-25T06:20:54.309Z | The c++ equivalent of torch.no_grad() would be NoGradGuard from
<a href="https://github.com/pytorch/pytorch/blob/master/torch/csrc/api/include/torch/utils.h" rel="nofollow noopener">torch/csrc/api/include/torch/utils.h</a>. From the current comments you can see that it is a thread-local guard to disable gradients.
to... | 5 | 2019-02-27T02:53:57.428Z | https://discuss.pytorch.org/t/memory-leak-in-libtorch-extremely-simple-code/38149/4 | I got it working! This works:
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. network or layer) and put batch norms if present
for attr_str in… The c+... | 1,021 | {'text': ['The c++ equivalent of torch.no_grad() would be NoGradGuard from\n\n<a href="https://github.com/pytorch/pytorch/blob/master/torch/csrc/api/include/torch/utils.h" rel="nofollow noopener">torch/csrc/api/include/torch/utils.h</a>. From the current comments you can see that it is a thread-local guard to disable g... |
How to process variable length sequence of images with CNN | Hi -
I have images in sequences of variable length. I am trying to first process each image with a CNN to get a feature representation. Once I have variable-length sequences of features, I will process each sequence through an LSTM. I know that I can pad the variable-length sequence of feature vect… | 4 | 2020-05-22T04:56:47.596Z | Sure, each data sequence is of format [image_0, action_1, image_1, action_2, image_2, action_3, image_3…], and the task is to predict action sequence [action_1, action_,…, action_k] given image sequence [image_0, image_1,…, image_k]. The image sequence of a variable length k+1 in a batch, so I pad e… | 1 | 2020-05-24T13:15:57.118Z | https://discuss.pytorch.org/t/how-to-process-variable-length-sequence-of-images-with-cnn/82422/3 | I got it working! This works:
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. network or layer) and put batch norms if present
for attr_str in… The c+... | 700 | {'text': ['Sure, each data sequence is of format [image_0, action_1, image_1, action_2, image_2, action_3, image_3…], and the task is to predict action sequence [action_1, action_,…, action_k] given image sequence [image_0, image_1,…, image_k]. The image sequence of a variable length k+1 in a batch, so I pad e…'... |
Layers are not initialized with same weights with manual seed | When setting all seeds manually, I would expect that all new layers of a given type have the same initial weights. However, that is not the case.
import torch
from torch import nn
import os
import numpy as np
import random
torch.manual_seed(3)
torch.cuda.manual_seed_all(3)
torch.backends.cudnn.det… | 3 | 2019-09-25T15:35:20.029Z | The reason is because generating some numbers change the state of the random number generator.
If you set the seed back and the create the layer again, you will get the same weights:
import torch
from torch import nn
torch.manual_seed(3)
linear = nn.Linear(5, 2)
torch.manual_seed(3)
linear2 = nn… | 7 | 2019-09-25T15:42:31.572Z | https://discuss.pytorch.org/t/layers-are-not-initialized-with-same-weights-with-manual-seed/56804/2 | The reason is because generating some numbers change the state of the random number generator.
If you set the seed back and the create the layer again, you will get the same weights:
import torch
from torch import nn
torch.manual_seed(3)
linear = nn.Linear(5, 2)
torch.manual_seed(3)
linear2 = nn… Just for... | 2,016 | {'text': ['The reason is because generating some numbers change the state of the random number generator.\n\nIf you set the seed back and the create the layer again, you will get the same weights:\n\nimport torch\n\nfrom torch import nn\n\ntorch.manual_seed(3)\n\nlinear = nn.Linear(5, 2)\n\ntorch.manual_seed(3)\n\nline... |
How do I know the current version of pytorch? | How do I know the current version of pytorch? | 10 | 2017-08-26T15:32:50.875Z | Just for the record:
to check it from terminal in linux:
python -c "import torch; print(torch.__version__)" | 26 | 2018-07-25T19:45:19.141Z | https://discuss.pytorch.org/t/how-do-i-know-the-current-version-of-pytorch/6754/3 | The reason is because generating some numbers change the state of the random number generator.
If you set the seed back and the create the layer again, you will get the same weights:
import torch
from torch import nn
torch.manual_seed(3)
linear = nn.Linear(5, 2)
torch.manual_seed(3)
linear2 = nn… Just for... | 1,320 | {'text': ['Just for the record:\n\nto check it from terminal in linux:\n\npython -c "import torch; print(torch.__version__)"'], 'answer_start': [1320]} |
Onv2d(): argument 'input' (position 1) must be Tensor, not tuple | I am making an encoder decoder model but this error occur in my encoder.
<ipython-input-2-2b8ee621aeff> in forward(self, x)
29
30 def forward(self,x):
---> 31 output=self.encoder(x)
32 ok=self.decoder(output)
33
/usr/local/lib/python3.6/dist-packages/torch/nn/module… | 0 | 2019-02-22T12:24:28.046Z | You would have to pass the indices as the second argument to nn.MaxUnpool2d. The <a href="https://pytorch.org/docs/stable/nn.html#maxunpool2d" rel="nofollow noopener">docs</a> have an example using it. | 1 | 2019-02-27T18:21:58.158Z | https://discuss.pytorch.org/t/onv2d-argument-input-position-1-must-be-tensor-not-tuple/37957/7 | The reason is because generating some numbers change the state of the random number generator.
If you set the seed back and the create the layer again, you will get the same weights:
import torch
from torch import nn
torch.manual_seed(3)
linear = nn.Linear(5, 2)
torch.manual_seed(3)
linear2 = nn… Just for... | 432 | {'text': ['You would have to pass the indices as the second argument to nn.MaxUnpool2d. The <a href="https://pytorch.org/docs/stable/nn.html#maxunpool2d" rel="nofollow noopener">docs</a> have an example using it.'], 'answer_start': [432]} |
Calculating loss with numpy function | Is it okey to convert tensor to numpy and calculate the loss value, and convert that value to tensor and backpropagate? | 3 | 2018-11-05T08:58:25.306Z | That won’t work as you are detaching the computation graph by calling numpy operations.
Autograd won’t be able to keep record of these operations, so that you won’t be able to simply backpropagate.
If you need the numpy functions, you would need to implement your own backward function and it shoul… | 4 | 2018-11-05T11:16:59.481Z | https://discuss.pytorch.org/t/calculating-loss-with-numpy-function/28796/2 | That won’t work as you are detaching the computation graph by calling numpy operations.
Autograd won’t be able to keep record of these operations, so that you won’t be able to simply backpropagate.
If you need the numpy functions, you would need to implement your own backward function and it shoul… I think the... | 1,266 | {'text': ['That won’t work as you are detaching the computation graph by calling numpy operations.\n\nAutograd won’t be able to keep record of these operations, so that you won’t be able to simply backpropagate.\n\nIf you need the numpy functions, you would need to implement your own backward function and it shoul&hell... |
Calculating accuracy of the current minibatch? | How can I calculate the acuracy for the current mini batch in my training? My trainining code is just:
for epoch in range(args.epochs):
for i, (images, captions, lengths) in enumerate(train_loader):
targets = pack_padded_sequence(captions, lengths, batch_first=True)[0]
features = encoder… | 0 | 2017-06-26T00:39:39.317Z | I think the simplest answer is the one from <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html" rel="nofollow noopener">the cifar10 tutorial</a>:
total = 0
with torch.no_grad():
net.eval()
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(output... | 1 | 2020-08-04T18:23:15.421Z | https://discuss.pytorch.org/t/calculating-accuracy-of-the-current-minibatch/4308/11 | That won’t work as you are detaching the computation graph by calling numpy operations.
Autograd won’t be able to keep record of these operations, so that you won’t be able to simply backpropagate.
If you need the numpy functions, you would need to implement your own backward function and it shoul… I think the... | 942 | {'text': ['I think the simplest answer is the one from <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html" rel="nofollow noopener">the cifar10 tutorial</a>:\n\ntotal = 0\n\nwith torch.no_grad():\n\nnet.eval()\n\nfor data in testloader:\n\nimages, labels = data\n\noutputs = net(images)\n\n_, pre... |
Is it okay to reuse activation function modules in the network architecture? | Does it make any discernible difference to a model whether activation function modules are reused within a neural network model?
Specifically, is it expected that training results differ depending on whether you reuse such modules or not?
Example model without reusing ReLU’s:
class NormalModel(nn… | 3 | 2020-03-25T14:20:07.221Z | I continually tweaked my network until I was finally able to get deterministic results. I removed the MaxPools first (even though I don’t think this uses atomicAdd), and as expected it changed nothing, but when I then also removed the convTranspose2d’s (being left with only conv2d, BN, ReLU for the … | 7 | 2020-04-02T13:58:17.622Z | https://discuss.pytorch.org/t/is-it-okay-to-reuse-activation-function-modules-in-the-network-architecture/74351/16 | That won’t work as you are detaching the computation graph by calling numpy operations.
Autograd won’t be able to keep record of these operations, so that you won’t be able to simply backpropagate.
If you need the numpy functions, you would need to implement your own backward function and it shoul… I think the... | 683 | {'text': ['I continually tweaked my network until I was finally able to get deterministic results. I removed the MaxPools first (even though I don’t think this uses atomicAdd), and as expected it changed nothing, but when I then also removed the convTranspose2d’s (being left with only conv2d, BN, ReLU for the …'... |
Load mnist how to get the labels? | Strange but I would like to load mnist labels using torchvision.datasets.MNIST. I loaded images like this:
train_loader = torch.utils.data.DataLoader(
torchvision.datasets.MNIST('/data/mnist', train=True, download=True,
transform=torchvision.transforms.Compose([
… | 1 | 2019-06-19T14:40:00.288Z | You can print the labels using dataset.targets. | 1 | 2019-06-19T14:48:38.733Z | https://discuss.pytorch.org/t/load-mnist-how-to-get-the-labels/48410/2 | You can print the labels using dataset.targets. [image] Ahmed_Abdelaziz:
I assumed that anomaly detection find the first occurrence of NaN and reports it
It does, but it can only look at the backward pass. So if nans happen in the forward, they won’t be reported.
You will need to add prints directly in your code to ... | 1,982 | {'text': ['You can print the labels using dataset.targets.'], 'answer_start': [1982]} |
LogBackward returned nan values in its 0th output | Hi,
While training my model I got NaNs as the result of loss function after many iterations. I used anaomly_detection to see what is causing that issue and I got that error.
Function 'LogBackward' returned nan values in its 0th output
This is the only log funtion I used in my forward path
retur… | 0 | 2020-08-14T15:14:13.860Z | [image] Ahmed_Abdelaziz:
I assumed that anomaly detection find the first occurrence of NaN and reports it
It does, but it can only look at the backward pass. So if nans happen in the forward, they won’t be reported.
You will need to add prints directly in your code to check where the nan app… | 4 | 2020-08-14T16:18:42.588Z | https://discuss.pytorch.org/t/logbackward-returned-nan-values-in-its-0th-output/92820/8 | You can print the labels using dataset.targets. [image] Ahmed_Abdelaziz:
I assumed that anomaly detection find the first occurrence of NaN and reports it
It does, but it can only look at the backward pass. So if nans happen in the forward, they won’t be reported.
You will need to add prints directly in your code to ... | 1,039 | {'text': ['[image] Ahmed_Abdelaziz:\n\nI assumed that anomaly detection find the first occurrence of NaN and reports it\n\nIt does, but it can only look at the backward pass. So if nans happen in the forward, they won’t be reported.\n\nYou will need to add prints directly in your code to check where the nan app…... |
RuntimeError: only batches of spatial targets supported (3D tensors) but got targets of dimension: 4 | Issue: RuntimeError: only batches of spatial targets supported (3D tensors) but got targets of dimension: 4
Problem Statement: I have an image and a pixel of the image can belong to only(either) one of Band5','Band6', 'Band7' (see below for details). Hence, I have a pytorch multi-class problem but ... | 0 | 2020-05-20T04:19:12.002Z | Assuming that you are working with 3 classes (based on the last edit of the post with the shape information), your model output should have the shape [batch_size, nb_classes=3, height, width].
To get the predicted class indices, you can use the same method:
preds = torch.argmax(output, dim=1) | 1 | 2020-05-20T06:34:31.718Z | https://discuss.pytorch.org/t/runtimeerror-only-batches-of-spatial-targets-supported-3d-tensors-but-got-targets-of-dimension-4/82098/11 | You can print the labels using dataset.targets. [image] Ahmed_Abdelaziz:
I assumed that anomaly detection find the first occurrence of NaN and reports it
It does, but it can only look at the backward pass. So if nans happen in the forward, they won’t be reported.
You will need to add prints directly in your code to ... | 352 | {'text': ['Assuming that you are working with 3 classes (based on the last edit of the post with the shape information), your model output should have the shape [batch_size, nb_classes=3, height, width].\n\nTo get the predicted class indices, you can use the same method:\n\npreds = torch.argmax(output, dim=1)'], 'answe... |
Converting model into 16 points precisoin (float16) instead of 32 | Hi,
I am trying to train the model on mixed precision, so for the same I am using the command:
model.half()
But I am getting the following error:
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/7/7/7724e9c9cf344b99aafad73e478166e81375b25c.png" data-download-href="https://discuss.py... | 1 | 2020-11-13T03:42:20.277Z | This code is working fine for me:
temp = nn.Sequential(
nn.Dropout(p=0.5),
nn.Linear(in_features=512, out_features=128),
nn.ReLU(),
nn.Linear(in_features=128, out_features=17, bias=True),
)
classifier = models.resnet34(pretrained=True)
classifier.fc … | 1 | 2020-11-16T05:59:20.500Z | https://discuss.pytorch.org/t/converting-model-into-16-points-precisoin-float16-instead-of-32/102622/16 | This code is working fine for me:
temp = nn.Sequential(
nn.Dropout(p=0.5),
nn.Linear(in_features=512, out_features=128),
nn.ReLU(),
nn.Linear(in_features=128, out_features=17, bias=True),
)
classifier = models.resnet34(pretrained=True)
classifier.fc … I manage to solve the problem with following link <a ... | 1,294 | {'text': ['This code is working fine for me:\n\ntemp = nn.Sequential(\n\nnn.Dropout(p=0.5),\n\nnn.Linear(in_features=512, out_features=128),\n\nnn.ReLU(),\n\nnn.Linear(in_features=128, out_features=17, bias=True),\n\n)\n\nclassifier = models.resnet34(pretrained=True)\n\nclassifier.fc …'], 'answer_start': [1294]} |
Unexpected key in state_dict: "bn1.num_batches_tracked" | Hello to all!
I read forum and the only solution is to update PyTorch. How can I solve this if I can’t update PyTorch version on the server? I saved the model and then I loaded model on the server and I got this:
RuntimeError: Error(s) in loading state_dict for ResNet:
Unexpected key(s) in state_… | 1 | 2018-11-13T07:01:33.170Z | I manage to solve the problem with following link <a href="https://discuss.pytorch.org/t/how-to-load-part-of-pre-trained-model/1113/2">How to load part of pre trained model?</a> <a class="mention" href="/u/apaszke">@apaszke</a> post. | 0 | 2018-11-13T16:06:16.081Z | https://discuss.pytorch.org/t/unexpected-key-in-state-dict-bn1-num-batches-tracked/29454/3 | This code is working fine for me:
temp = nn.Sequential(
nn.Dropout(p=0.5),
nn.Linear(in_features=512, out_features=128),
nn.ReLU(),
nn.Linear(in_features=128, out_features=17, bias=True),
)
classifier = models.resnet34(pretrained=True)
classifier.fc … I manage to solve the problem with following link <a ... | 914 | {'text': ['I manage to solve the problem with following link <a href="https://discuss.pytorch.org/t/how-to-load-part-of-pre-trained-model/1113/2">How to load part of pre trained model?</a> <a class="mention" href="/u/apaszke">@apaszke</a> post.'], 'answer_start': [914]} |
How can I replace the forward method of a predefined torchvision model with my customized forward function? | How can I replace the forward method of a predefined torchvision model with my customized forward function?
I tried the following: <a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/7/7cc8e2f46ecec9bed9a374b2db84c6452c5809c6.png" data-download-href="https://discuss.pytorch.org/uploads/de... | 0 | 2019-08-24T21:19:03.940Z | You could derive a custom class using the resnet class as its parent:
import torchvision.models as models
from torchvision.models.resnet import ResNet, BasicBlock
class MyResNet18(ResNet):
def __init__(self):
super(MyResNet18, self).__init__(BasicBlock, [2, 2, 2, 2])
def f… | 7 | 2019-08-25T13:16:00.513Z | https://discuss.pytorch.org/t/how-can-i-replace-the-forward-method-of-a-predefined-torchvision-model-with-my-customized-forward-function/54224/7 | This code is working fine for me:
temp = nn.Sequential(
nn.Dropout(p=0.5),
nn.Linear(in_features=512, out_features=128),
nn.ReLU(),
nn.Linear(in_features=128, out_features=17, bias=True),
)
classifier = models.resnet34(pretrained=True)
classifier.fc … I manage to solve the problem with following link <a ... | 501 | {'text': ['You could derive a custom class using the resnet class as its parent:\n\nimport torchvision.models as models\n\nfrom torchvision.models.resnet import ResNet, BasicBlock\n\nclass MyResNet18(ResNet):\n\ndef __init__(self):\n\nsuper(MyResNet18, self).__init__(BasicBlock, [2, 2, 2, 2])\n\ndef f…'], 'answe... |
Custom a new convolution layer in cnn | Hi,
I am a beginner in pytorch. I want to define my proposed kernel and add it to a CNN. I am searching about 2 or 3 days. I am so confused! Because I do not know, I should implement CNN by C++ from scratch and build it and add it to pytorch or it is enough to implement a new convolution layer by m… | 1 | 2019-04-26T09:46:52.138Z | There seem to be some issues regarding the shape in the forward method.
Currently, input[j][0][:, start_col_indx:end_col_indx] will have the shapes:
torch.Size([2, 2])
torch.Size([2, 1])
torch.Size([2, 0])
which will create an error.
Did you forget to increase the end_col_index?
Also, I might h… | 2 | 2019-04-29T20:40:57.122Z | https://discuss.pytorch.org/t/custom-a-new-convolution-layer-in-cnn/43682/20 | There seem to be some issues regarding the shape in the forward method.
Currently, input[j][0][:, start_col_indx:end_col_indx] will have the shapes:
torch.Size([2, 2])
torch.Size([2, 1])
torch.Size([2, 0])
which will create an error.
Did you forget to increase the end_col_index?
Also, I might h… Hi,
The ... | 1,576 | {'text': ['There seem to be some issues regarding the shape in the forward method.\n\nCurrently, input[j][0][:, start_col_indx:end_col_indx] will have the shapes:\n\ntorch.Size([2, 2])\n\ntorch.Size([2, 1])\n\ntorch.Size([2, 0])\n\nwhich will create an error.\n\nDid you forget to increase the end_col_index?\n\nAlso, I ... |
Accessing PyTorch documentation offline | Is there a way for me to access PyTorch documentation offline? I checked the github repo and there seems to be a doc folder but I am not clear on how to generate the documentation so that I can use it offline.
I am looking for documentation for stable 0.4.0. | 3 | 2018-06-29T06:38:41.059Z | Hi,
The doc needs to be generated from the source code.
To get it you will need to go into the docs folder and then run make (or the bat file if you’re on windows). You might need to install the dependencies in the requirements.txt file before.
Once make run, you will have a local html file that … | 5 | 2018-06-29T09:07:19.783Z | https://discuss.pytorch.org/t/accessing-pytorch-documentation-offline/20453/2 | There seem to be some issues regarding the shape in the forward method.
Currently, input[j][0][:, start_col_indx:end_col_indx] will have the shapes:
torch.Size([2, 2])
torch.Size([2, 1])
torch.Size([2, 0])
which will create an error.
Did you forget to increase the end_col_index?
Also, I might h… Hi,
The ... | 1,099 | {'text': ['Hi,\n\nThe doc needs to be generated from the source code.\n\nTo get it you will need to go into the docs folder and then run make (or the bat file if you’re on windows). You might need to install the dependencies in the requirements.txt file before.\n\nOnce make run, you will have a local html file that &he... |
Is it required to set-up CUDA on PC before installing CUDA enabled pytorch? | Can I simply go to pytorch website and use the following link to download a CUDA enabled pytorch library ? Or do i have to set up the CUDA on my device first, before installing the CUDA enabled pytorch ?
pip3 install torch===1.3.0 torchvision===0.4.1 -f https://download.pytorch.org/whl/torch_stabl… | 0 | 2019-11-06T14:03:54.624Z | i solved it. and yes you were right <a class="mention" href="/u/alband">@albanD</a> ! :smiley:
my nvidia drivers were old. i just updated the nvidia drivers by going to Start>Device Manager>Display adapters> select_ur_gpu >Right Click>Update Driver
Thanks a lot :slight_smile: | 1 | 2019-11-07T20:14:32.565Z | https://discuss.pytorch.org/t/is-it-required-to-set-up-cuda-on-pc-before-installing-cuda-enabled-pytorch/60181/10 | There seem to be some issues regarding the shape in the forward method.
Currently, input[j][0][:, start_col_indx:end_col_indx] will have the shapes:
torch.Size([2, 2])
torch.Size([2, 1])
torch.Size([2, 0])
which will create an error.
Did you forget to increase the end_col_index?
Also, I might h… Hi,
The ... | 620 | {'text': ['i solved it. and yes you were right <a class="mention" href="/u/alband">@albanD</a> ! :smiley:\n\nmy nvidia drivers were old. i just updated the nvidia drivers by going to Start>Device Manager>Display adapters> select_ur_gpu >Right Click>Update Driver\n\nThanks a lot :slight_smile:'], 'answer_... |
Changing transformation applied to data during training | I would like to change the transformation I am applying to data during training. For example, I might want to change the size of the random crop I am taking of images from 32 to 28 or change the amount of jitter applied to an image. Is there a way of doing this that works with the DataLoader class w… | 1 | 2018-03-29T16:53:58.199Z | Thanks!
I think a good solution can be found here: <a href="https://discuss.pytorch.org/t/changing-transforms-after-creating-a-dataset/64929/7" class="inline-onebox">Changing transforms after creating a dataset - #7 by Brando_Miranda</a>
train_dataset = MyDataset(train_transform)
val_dataset = MyDataset(val_transfor... | 0 | 2021-12-17T21:51:37.360Z | https://discuss.pytorch.org/t/changing-transformation-applied-to-data-during-training/15671/14 | Thanks!
I think a good solution can be found here: <a href="https://discuss.pytorch.org/t/changing-transforms-after-creating-a-dataset/64929/7" class="inline-onebox">Changing transforms after creating a dataset - #7 by Brando_Miranda</a>
train_dataset = MyDataset(train_transform)
val_dataset = MyDataset(val_transfor... | 1,826 | {'text': ['Thanks!\n\nI think a good solution can be found here: <a href="https://discuss.pytorch.org/t/changing-transforms-after-creating-a-dataset/64929/7" class="inline-onebox">Changing transforms after creating a dataset - #7 by Brando_Miranda</a>\n\ntrain_dataset = MyDataset(train_transform)\n\nval_dataset = MyDat... |
Implementing a custom convolution using conv2d_input and conv2d_weight | Hi,
I have been trying to implement a custom convolutional layer.
In order to do that, I’m using torch.nn.functional.conv2d in the forward pass, and both torch.nn.grad.conv2d_weight and torch.nn.grad.conv2d_input in the backward pass.
I started getting OOM exceptions when entering torch.nn.grad.c… | 1 | 2018-05-23T08:27:36.110Z | Hi, This OOM exception comes from the python api implement of conv2d_weight actually.
In backprop weight calculation, the output gradients need to be expanded with output channel times. When default cudnn implement this with data prefetch block and block (not allocate more memory), python api uses … | 3 | 2019-08-10T13:07:31.978Z | https://discuss.pytorch.org/t/implementing-a-custom-convolution-using-conv2d-input-and-conv2d-weight/18556/12 | Thanks!
I think a good solution can be found here: <a href="https://discuss.pytorch.org/t/changing-transforms-after-creating-a-dataset/64929/7" class="inline-onebox">Changing transforms after creating a dataset - #7 by Brando_Miranda</a>
train_dataset = MyDataset(train_transform)
val_dataset = MyDataset(val_transfor... | 1,344 | {'text': ['Hi, This OOM exception comes from the python api implement of conv2d_weight actually.\n\nIn backprop weight calculation, the output gradients need to be expanded with output channel times. When default cudnn implement this with data prefetch block and block (not allocate more memory), python api uses &hellip... |
How to change the name of the weights to a new name when saving the model | How I can change the name of the weights in a models when i want to save them?
Here is what i want to do:
I do torch.load to load the pretrained model and update the weights forself.Conv1 (where
self.Conv1 = nn.Conv2d(3,3,kernel_size=1, stride=1, padding=0, bias=False))
after training my model… | 1 | 2018-12-14T18:45:16.704Z | You code should rename the self.conv1 layers:
class ModelA(nn.Module):
def __init__(self):
super(ModelA, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 3, 1, 1)
self.fc1 = nn.Linear(6*4*4, 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x =… | 5 | 2018-12-15T23:00:47.843Z | https://discuss.pytorch.org/t/how-to-change-the-name-of-the-weights-to-a-new-name-when-saving-the-model/32166/5 | Thanks!
I think a good solution can be found here: <a href="https://discuss.pytorch.org/t/changing-transforms-after-creating-a-dataset/64929/7" class="inline-onebox">Changing transforms after creating a dataset - #7 by Brando_Miranda</a>
train_dataset = MyDataset(train_transform)
val_dataset = MyDataset(val_transfor... | 740 | {'text': ['You code should rename the self.conv1 layers:\n\nclass ModelA(nn.Module):\n\ndef __init__(self):\n\nsuper(ModelA, self).__init__()\n\nself.conv1 = nn.Conv2d(1, 6, 3, 1, 1)\n\nself.fc1 = nn.Linear(6*4*4, 2)\n\ndef forward(self, x):\n\nx = F.relu(self.conv1(x))\n\nx =…'], 'answer_start': [740]} |
Error: grad can be implicitly created only for scalar outputs | So i am trying to train a Variational Auto Encoder, and i have created a custom loss function to train the network, the network throws the error
RuntimeError: grad can be implicitly created only for scalar outputs
heres the Loss function
def loss_function(recon_x, x, mu, logvar):
BCE = F.bina… | 0 | 2019-02-24T14:26:35.319Z | As <a class="mention" href="/u/bharat0to">@bharat0to</a> said, your loss is most likely a multi-dimensional tensor, which will thus throw this error.
You could add some reduction or pass a gradient with the same shape as loss. | 2 | 2019-02-24T21:02:09.953Z | https://discuss.pytorch.org/t/error-grad-can-be-implicitly-created-only-for-scalar-outputs/38102/4 | As <a class="mention" href="/u/bharat0to">@bharat0to</a> said, your loss is most likely a multi-dimensional tensor, which will thus throw this error.
You could add some reduction or pass a gradient with the same shape as loss. Maybe something like this:
cifar_dataset = torchvision.datasets.CIFAR10(root='./data... | 1,996 | {'text': ['As <a class="mention" href="/u/bharat0to">@bharat0to</a> said, your loss is most likely a multi-dimensional tensor, which will thus throw this error.\n\nYou could add some reduction or pass a gradient with the same shape as loss.'], 'answer_start': [1996]} |
Train on a fraction of the data set | I want to train with SGD on say 10% of cifar10. However, I want that 10% to be the same fraction of cifar10 and not change once training has started. How does one do this?
The only way I’ve thought of doing this was loop through all the data of cifar10 and once I’ve extracted the first 10% of the d… | 1 | 2018-04-21T01:40:04.195Z | Maybe something like this:
cifar_dataset = torchvision.datasets.CIFAR10(root='./data', transform=transform)
train_indices = # select train indices according to your rule
test_indices = # select test indices according to your rule
train_loader = torch.utils.data.DataLoader(cifar_dataset, batch_size=… | 1 | 2018-04-22T04:13:46.740Z | https://discuss.pytorch.org/t/train-on-a-fraction-of-the-data-set/16743/8 | As <a class="mention" href="/u/bharat0to">@bharat0to</a> said, your loss is most likely a multi-dimensional tensor, which will thus throw this error.
You could add some reduction or pass a gradient with the same shape as loss. Maybe something like this:
cifar_dataset = torchvision.datasets.CIFAR10(root='./data... | 1,226 | {'text': ['Maybe something like this:\n\ncifar_dataset = torchvision.datasets.CIFAR10(root='./data', transform=transform)\n\ntrain_indices = # select train indices according to your rule\n\ntest_indices = # select test indices according to your rule\n\ntrain_loader = torch.utils.data.DataLoader(cifar_dataset, b... |
Optimizing based on another model's output | Hi sorry I’m new to Pytorch: if I have Model1 producing some output, which is fed into Model2 (which is pre-trained), is there a simple way to optimize Model1’s weights based on Model2’s outputs? I could of course just backprop through Model2 into Model1, but I want to assume Model2 is not accessibl… | 2 | 2017-08-31T14:58:51.024Z | Hi,
If I understand properly, you have this:
input = # ...
out1 = Model1(input)
out2 = Model2(out1)
loss = LossFunc(out2)
If you want to optimize the parameters of Model1, you can just use loss.backward() and create your optimizer to only update the first model with optimizer = torch.optim.SGD(Mo… | 4 | 2017-08-31T15:06:43.098Z | https://discuss.pytorch.org/t/optimizing-based-on-another-models-output/6935/2 | As <a class="mention" href="/u/bharat0to">@bharat0to</a> said, your loss is most likely a multi-dimensional tensor, which will thus throw this error.
You could add some reduction or pass a gradient with the same shape as loss. Maybe something like this:
cifar_dataset = torchvision.datasets.CIFAR10(root='./data... | 548 | {'text': ['Hi,\n\nIf I understand properly, you have this:\n\ninput = # ...\n\nout1 = Model1(input)\n\nout2 = Model2(out1)\n\nloss = LossFunc(out2)\n\nIf you want to optimize the parameters of Model1, you can just use loss.backward() and create your optimizer to only update the first model with optimizer = torch.optim.... |
Multiprocessing CUDA memory | Hi !
I’m currently using multiprocessing in a project, and I was wondering if I had a way not to reinitialize CUDA on every process (which takes approximately ~300Mo of VRAM from what I saw).
I send models to the processes and dont expect to get anything back that is related to PyTorch.
I already… | 3 | 2018-05-31T07:15:41.276Z | I guess there are three possible ways of answering this:
is it possible to avoid initialization? Possibly out of my own expertise to give a definitive answer. Simon Wang states that it’s not. That correlates with my own experience.
is it theoretically possible to reduce the footprint of initia… | 4 | 2018-06-04T04:17:19.107Z | https://discuss.pytorch.org/t/multiprocessing-cuda-memory/18951/11 | I guess there are three possible ways of answering this:
is it possible to avoid initialization? Possibly out of my own expertise to give a definitive answer. Simon Wang states that it’s not. That correlates with my own experience.
is it theoretically possible to reduce the footprint of initia… hello there,
u... | 1,718 | {'text': ['I guess there are three possible ways of answering this:\n\nis it possible to avoid initialization? Possibly out of my own expertise to give a definitive answer. Simon Wang states that it’s not. That correlates with my own experience.\n\nis it theoretically possible to reduce the footprint of initia…'... |
Batch non-maximum suppression on the GPU | I am trying to speed up SSD family of object detectors in PyTorch. Most implementations use a CUDA-based non-maximum suppression (NMS) for efficiency, but the implementation (from Fast/er R-CNN) is image-based. If we have batch size larger than 1, the post processing & NMS becomes the bottleneck, as… | 2 | 2019-01-09T04:01:42.482Z | hello there,
using the awesome idea from torchvision “batched_nms”, this following code can decode for several images / several classes at once, it works because batched_nms offsets boxes according to their category, so you never perform a wrong suppression.
I also tried to accelerate box encoding… | 2 | 2019-10-21T17:30:27.668Z | https://discuss.pytorch.org/t/batch-non-maximum-suppression-on-the-gpu/34210/8 | I guess there are three possible ways of answering this:
is it possible to avoid initialization? Possibly out of my own expertise to give a definitive answer. Simon Wang states that it’s not. That correlates with my own experience.
is it theoretically possible to reduce the footprint of initia… hello there,
u... | 1,164 | {'text': ['hello there,\n\nusing the awesome idea from torchvision “batched_nms”, this following code can decode for several images / several classes at once, it works because batched_nms offsets boxes according to their category, so you never perform a wrong suppression.\n\nI also tried to accelerate box encoding&hell... |
A question concerning batchsize and multiple GPUs in Pytorch | If I set batch-size to 256 and use all of the GPUs on my system (lets say I have 8), will each GPU get a batch of 256 or will it get 256//8 ?
If my memory serves me correctly, in Caffe, all GPUs would get the same batch-size , i.e 256 and the effective batch-size would be 8*256 , 8 being the number… | 2 | 2019-01-04T10:08:54.617Z | nn.DataParallel splits the data along the batch dimension so that each specified GPU will get a chunk of the batch. If you just call .cuda() (or the equivalent .to() call), you will push the tensor or parameters onto the specified single device. | 2 | 2019-01-04T21:18:50.972Z | https://discuss.pytorch.org/t/a-question-concerning-batchsize-and-multiple-gpus-in-pytorch/33767/2 | I guess there are three possible ways of answering this:
is it possible to avoid initialization? Possibly out of my own expertise to give a definitive answer. Simon Wang states that it’s not. That correlates with my own experience.
is it theoretically possible to reduce the footprint of initia… hello there,
u... | 614 | {'text': ['nn.DataParallel splits the data along the batch dimension so that each specified GPU will get a chunk of the batch. If you just call .cuda() (or the equivalent .to() call), you will push the tensor or parameters onto the specified single device.'], 'answer_start': [614]} |
Loss problem in net finetuning | I’m obviously doing something wrong trying to finetune <a href="https://github.com/delta-onera/segnet_pytorch" rel="nofollow noopener">this</a> implementation of Segnet. This is my results with accuracy and loss in TensorBoard.
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/b/bed4cca... | 2 | 2018-05-18T13:02:04.903Z | Add the following line:
elif mask.mode == '1':
img2 = torch.from_numpy(np.array(mask, np.uint8, copy=False)) | 0 | 2018-05-23T09:36:21.713Z | https://discuss.pytorch.org/t/loss-problem-in-net-finetuning/18311/30 | Add the following line:
elif mask.mode == '1':
img2 = torch.from_numpy(np.array(mask, np.uint8, copy=False)) Solved the problem of path with
export PYTHONNOUSERSITE=True Took a closer look at my dataset. It had audio files which produced very long inputs which were the cause of OOM.
Lessons learned:
Check ... | 1,718 | {'text': ['Add the following line:\n\nelif mask.mode == '1':\n\nimg2 = torch.from_numpy(np.array(mask, np.uint8, copy=False))'], 'answer_start': [1718]} |
ImportError: cannot import name 'Optional' | Hello,
I’m facing a strange issue given that suddenly, i can not anymore import torchvision.
I removed and installed pytorch + torchvision but it did not help.
>>> import torchvision
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/renaud/anaco... | 2 | 2020-05-06T13:26:20.120Z | Solved the problem of path with
export PYTHONNOUSERSITE=True | 2 | 2020-05-07T19:14:16.224Z | https://discuss.pytorch.org/t/importerror-cannot-import-name-optional/80007/18 | Add the following line:
elif mask.mode == '1':
img2 = torch.from_numpy(np.array(mask, np.uint8, copy=False)) Solved the problem of path with
export PYTHONNOUSERSITE=True Took a closer look at my dataset. It had audio files which produced very long inputs which were the cause of OOM.
Lessons learned:
Check ... | 978 | {'text': ['Solved the problem of path with\n\nexport PYTHONNOUSERSITE=True'], 'answer_start': [978]} |
CUDA memory leak while training | Hi,
I ran into a problem with CUDA memory leak. I’m training on a single GPU with 16GB of RAM and I keep running out of memory after some number of steps. Around 500 out of 4000.
My dataset is quite big, and it crashes during the first epoch.
I noticed that memory usage is growing steadily, but I… | 2 | 2020-05-25T19:18:42.877Z | Took a closer look at my dataset. It had audio files which produced very long inputs which were the cause of OOM.
Lessons learned:
Check your data. Even if dataset description says, that it’s clean, prepared for training.
Audio sample rate matters - it should 8000 or 16000 (in my case). I had var… | 0 | 2020-05-31T16:07:34.254Z | https://discuss.pytorch.org/t/cuda-memory-leak-while-training/82855/16 | Add the following line:
elif mask.mode == '1':
img2 = torch.from_numpy(np.array(mask, np.uint8, copy=False)) Solved the problem of path with
export PYTHONNOUSERSITE=True Took a closer look at my dataset. It had audio files which produced very long inputs which were the cause of OOM.
Lessons learned:
Check ... | 181 | {'text': ['Took a closer look at my dataset. It had audio files which produced very long inputs which were the cause of OOM.\n\nLessons learned:\n\nCheck your data. Even if dataset description says, that it’s clean, prepared for training.\n\nAudio sample rate matters - it should 8000 or 16000 (in my case). I had var&he... |
CNN-LSTM problem | Hi,
I have implemented a hybdrid model with CNN & LSTM in both Keras and PyTorch, the network is composed by 4 layers of convolution with an output size of 64 and a kernel size of 5, followed by 2 LSTM layer with 128 hidden states, and then a Dense layer of 6 outputs for the classification.
In fac… | 2 | 2020-02-11T11:06:04.358Z | Alright, I believe here’s the problem. In ur model, if I assume the input to CNN is of shape [B, 1, L], then the CNN outputs a tensor of shape [B, C, L] where B is the batch size, L is the sequence length, C is the channel. You then fed it into LSTM hoping it would learn the temporal information of … | 6 | 2020-02-12T13:02:39.423Z | https://discuss.pytorch.org/t/cnn-lstm-problem/69344/6 | Alright, I believe here’s the problem. In ur model, if I assume the input to CNN is of shape [B, 1, L], then the CNN outputs a tensor of shape [B, C, L] where B is the batch size, L is the sequence length, C is the channel. You then fed it into LSTM hoping it would learn the temporal information of … it’s the pr... | 978 | {'text': ['Alright, I believe here’s the problem. In ur model, if I assume the input to CNN is of shape [B, 1, L], then the CNN outputs a tensor of shape [B, C, L] where B is the batch size, L is the sequence length, C is the channel. You then fed it into LSTM hoping it would learn the temporal information of …'... |
Assertion `input_val >= zero && input_val <= one` failed | Hi, all
Recently, I changed the cpu and motherboard of my PC. But when I tried to run the training code, I encountered this problem. I haven’t changed any codes on my scripts. So I’m wondering whether it’s caused by the CPU(Ryzen 7 3800xt)
The “Traceback (most recent call last):” showed below chan… | 0 | 2020-12-31T00:45:05.284Z | it’s the problem of the cpu. I have already claimed an return | 0 | 2021-01-19T16:12:52.339Z | https://discuss.pytorch.org/t/assertion-input-val-zero-input-val-one-failed/107554/18 | Alright, I believe here’s the problem. In ur model, if I assume the input to CNN is of shape [B, 1, L], then the CNN outputs a tensor of shape [B, C, L] where B is the batch size, L is the sequence length, C is the channel. You then fed it into LSTM hoping it would learn the temporal information of … it’s the pr... | 798 | {'text': ['it’s the problem of the cpu. I have already claimed an return'], 'answer_start': [798]} |
Correctly feeding LSTM with minibatch time sequence data | Hi,
I’m having trouble with setting the correct tensor sizes for my research. I have about 400000 data points in the form: time, value. They are in a csv file. I would like to feed my LSTM in mini batches of 20 sequences of length 100 for each batch. I’m not sure how to that properly. Any advise ap… | 1 | 2019-07-30T21:00:43.659Z | The batch index 19 would get the last part of the dataset wouldn’t it?
Using 400 samples, a sequence length of 100 and a batch size of 2 seems to work:
class OUDataset(Dataset):
def __init__(self, window_size=100):
self.oudataframe = pd.DataFrame(np.random.randn(400, 2))
self.window_size… | 2 | 2019-08-07T22:29:23.818Z | https://discuss.pytorch.org/t/correctly-feeding-lstm-with-minibatch-time-sequence-data/52101/27 | Alright, I believe here’s the problem. In ur model, if I assume the input to CNN is of shape [B, 1, L], then the CNN outputs a tensor of shape [B, C, L] where B is the batch size, L is the sequence length, C is the channel. You then fed it into LSTM hoping it would learn the temporal information of … it’s the pr... | 371 | {'text': ['The batch index 19 would get the last part of the dataset wouldn’t it?\n\nUsing 400 samples, a sequence length of 100 and a batch size of 2 seems to work:\n\nclass OUDataset(Dataset):\n\ndef __init__(self, window_size=100):\n\nself.oudataframe = pd.DataFrame(np.random.randn(400, 2))\n\nself.window_size&helli... |
Measuring peak memory usage: tracemalloc for pytorch? | I’ve been working on tools for memory usage diagnostics and management (<a href="https://github.com/stas00/ipyexperiments/" rel="nofollow noopener">ipyexperiments </a>) to help to get more out of the limited GPU RAM. The features include tracking real used and peaked used memory (GPU and general RAM). The peak memory u... | 1 | 2019-01-07T23:26:00.274Z | [image] stas:
But I suppose there is no way pytorch could even try to estimate the extras that it can’t account for.
You are right. Unfortunately we can’t know the exact size of the cuda context. The memory_allocated/cached methods report all memory allocated by pytorch. But if cuda context i… | 1 | 2019-01-12T06:45:49.242Z | https://discuss.pytorch.org/t/measuring-peak-memory-usage-tracemalloc-for-pytorch/34067/9 | [image] stas:
But I suppose there is no way pytorch could even try to estimate the extras that it can’t account for.
You are right. Unfortunately we can’t know the exact size of the cuda context. The memory_allocated/cached methods report all memory allocated by pytorch. But if cuda context i… I think the stan... | 1,344 | {'text': ['[image] stas:\n\nBut I suppose there is no way pytorch could even try to estimate the extras that it can’t account for.\n\nYou are right. Unfortunately we can’t know the exact size of the cuda context. The memory_allocated/cached methods report all memory allocated by pytorch. But if cuda context i…']... |
How to shuffle an iterable dataset | Hi,
I am using the IterableDataset class in order to avoid loading the whole data to memory. However, I cannot shuffle the dataset in that case. Is there any trick for shuffling an iterable dataset?
Thanks in advance! | 0 | 2019-12-15T18:54:54.344Z | I think the standard approach to shuffling an iterable dataset is to introduce a shuffle buffer into your pipeline. Here’s the class I use to shuffle an iterable dataset:
class ShuffleDataset(torch.utils.data.IterableDataset):
def __init__(self, dataset, buffer_size):
super().__init__()
s… | 8 | 2020-04-30T20:30:23.710Z | https://discuss.pytorch.org/t/how-to-shuffle-an-iterable-dataset/64130/6 | [image] stas:
But I suppose there is no way pytorch could even try to estimate the extras that it can’t account for.
You are right. Unfortunately we can’t know the exact size of the cuda context. The memory_allocated/cached methods report all memory allocated by pytorch. But if cuda context i… I think the stan... | 976 | {'text': ['I think the standard approach to shuffling an iterable dataset is to introduce a shuffle buffer into your pipeline. Here’s the class I use to shuffle an iterable dataset:\n\nclass ShuffleDataset(torch.utils.data.IterableDataset):\n\ndef __init__(self, dataset, buffer_size):\n\nsuper().__init__()\n\ns…... |
F.interpolate weird behaviour | Hi !
So I might be missing something basic but I’m getting a weird behavior with F.interpolate :
I created a 3D-tensor using :
t = torch.randn(4,4,4)
Or a least I thought it was 3D, but F.interpolate doesn’t seem to agree. The following code :
F.interpolate(t, scale_factor=(1,2,1))
gives the … | 2 | 2019-01-31T20:21:10.062Z | The error message might be a bit weird, but it refers to an input of shape [batch_size, channels, *addidional_dims].
Given that you provide a “1D” input with a length of 4.
Here would be an example using an image tensor:
batch_size, c, h, w = 1, 3, 4, 4
x = torch.randn(batch_size, c, h, w)
x = F… | 6 | 2019-01-31T22:43:03.385Z | https://discuss.pytorch.org/t/f-interpolate-weird-behaviour/36088/2 | [image] stas:
But I suppose there is no way pytorch could even try to estimate the extras that it can’t account for.
You are right. Unfortunately we can’t know the exact size of the cuda context. The memory_allocated/cached methods report all memory allocated by pytorch. But if cuda context i… I think the stan... | 606 | {'text': ['The error message might be a bit weird, but it refers to an input of shape [batch_size, channels, *addidional_dims].\n\nGiven that you provide a “1D” input with a length of 4.\n\nHere would be an example using an image tensor:\n\nbatch_size, c, h, w = 1, 3, 4, 4\n\nx = torch.randn(batch_size, c, h, w)\n\nx ... |
Is there will have total 48g memory if I use nvlink to connect two 3090? | Now, we bought a 4 way rtx3090 24g GPU server, and I want to confirm there will be total 48g memory while I use nvlink to connect two 3090.
If rtx3090 supports this feature, how should I change my pytorch code?
Thanks. | 2 | 2020-10-23T09:37:50.718Z | [image] prophet_zhan:
and I want to confirm there will be total 48g memory while I use nvlink to connect two 3090.
No, the devices should not show up as a single GPU with 48GB.
You can connect them via nvlink and use a data or model parallel approach. | 1 | 2020-10-23T23:58:46.993Z | https://discuss.pytorch.org/t/is-there-will-have-total-48g-memory-if-i-use-nvlink-to-connect-two-3090/100378/4 | [image] prophet_zhan:
and I want to confirm there will be total 48g memory while I use nvlink to connect two 3090.
No, the devices should not show up as a single GPU with 48GB.
You can connect them via nvlink and use a data or model parallel approach. Hi ptrblck,
I solve the question posted here by using:
<a class... | 1,832 | {'text': ['[image] prophet_zhan:\n\nand I want to confirm there will be total 48g memory while I use nvlink to connect two 3090.\n\nNo, the devices should not show up as a single GPU with 48GB.\n\nYou can connect them via nvlink and use a data or model parallel approach.'], 'answer_start': [1832]} |
How to reduce the memory requirement for a GPU pytorch training process? (finally solved by using multiple GPUs) | Hi,
I’m new to torch 0.4 and implement a Encoder-Decoder model for image segmentation.
during training to my lab server with 2 GPU cards only, I face the following problem say “out of memory”:
[image]
<a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/d/dadc088ad19835a33c6996a84f2c5e2... | 0 | 2018-06-12T01:33:53.266Z | Hi ptrblck,
I solve the question posted here by using:
<a class="mention" href="/u/voxmenthe">@voxmenthe</a> ‘s answer from a multiple GPUs’ solution:
model = <specify model here>
model = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count()))
I notice you mentioned “it splits the data/batch ... | 0 | 2018-06-23T07:15:26.601Z | https://discuss.pytorch.org/t/how-to-reduce-the-memory-requirement-for-a-gpu-pytorch-training-process-finally-solved-by-using-multiple-gpus/19535/20 | [image] prophet_zhan:
and I want to confirm there will be total 48g memory while I use nvlink to connect two 3090.
No, the devices should not show up as a single GPU with 48GB.
You can connect them via nvlink and use a data or model parallel approach. Hi ptrblck,
I solve the question posted here by using:
<a class... | 1,171 | {'text': ['Hi ptrblck,\n\nI solve the question posted here by using:\n\n<a class="mention" href="/u/voxmenthe">@voxmenthe</a> ‘s answer from a multiple GPUs’ solution:\n\nmodel = <specify model here>\n\nmodel = torch.nn.DataParallel(net, device_ids=range(torch.cuda.device_count()))\n\nI notice you mentioned “it s... |
How to allocate more GPU memory to be reserved by PyTorch to avoid "RuntimeError: CUDA out of memory"? | Hello,
I’m not experienced in PyTorch very well and perhaps asking a weird question.
I’m running my PyTorch script in a docker container and I’m using GPU that has 48 GB.
Although it has a larger capacity, somehow PyTorch is only using smaller than 10GiB and causing the “CUDA out of memory” error… | 2 | 2022-04-13T12:37:43.057Z | No, docker containers are not limiting the GPU resources (there might be options to do so, but I’m unaware of these).
As you can see in the output of nvidia-smi 4 processes are using the device where the Python scripts are taking the majority of the GPU memory so the OOM error would be expected.
… | 2 | 2022-04-14T05:37:52.392Z | https://discuss.pytorch.org/t/how-to-allocate-more-gpu-memory-to-be-reserved-by-pytorch-to-avoid-runtimeerror-cuda-out-of-memory/149037/7 | [image] prophet_zhan:
and I want to confirm there will be total 48g memory while I use nvlink to connect two 3090.
No, the devices should not show up as a single GPU with 48GB.
You can connect them via nvlink and use a data or model parallel approach. Hi ptrblck,
I solve the question posted here by using:
<a class... | 614 | {'text': ['No, docker containers are not limiting the GPU resources (there might be options to do so, but I’m unaware of these).\n\nAs you can see in the output of nvidia-smi 4 processes are using the device where the Python scripts are taking the majority of the GPU memory so the OOM error would be expected.\n\n&helli... |
V0.4 - PyCharm "unknown" inspections: `unexpected argument`, `not callable`, etc | After installing PyTorch via pip on Mac, my PyCharm seems to not be recognizing many of the v0.4 commands. For example, for torch.rand the device argument is an unexpected argument, and torch.tensor is considered not callable. Of course, it’s possible to disable these inspections, but I would prefer… | 2 | 2018-05-09T15:53:47.918Z | We will fix this in the next release. It’s being tracked at:
<a href="https://github.com/kimdwkimdw">
[image]
</a>
<a href="https://github.com/pytorch/pytorch/issues/7318" target="_blank">Issue: Broken `Type Hints` in PyTorch 0.4.0, related to IDEs(eq. PyCharm)</a>
opened by <a href="https://github.com/kimdwkimdw"... | 3 | 2018-05-09T20:05:03.326Z | https://discuss.pytorch.org/t/v0-4-pycharm-unknown-inspections-unexpected-argument-not-callable-etc/17810/2 | We will fix this in the next release. It’s being tracked at:
<a href="https://github.com/kimdwkimdw">
[image]
</a>
<a href="https://github.com/pytorch/pytorch/issues/7318" target="_blank">Issue: Broken `Type Hints` in PyTorch 0.4.0, related to IDEs(eq. PyCharm)</a>
opened by <a href="https://github.com/kimdwkimdw"... | 1,842 | {'text': ['We will fix this in the next release. It’s being tracked at:\n\n<a href="https://github.com/kimdwkimdw">\n\n[image]\n\n</a>\n\n<a href="https://github.com/pytorch/pytorch/issues/7318" target="_blank">Issue: Broken `Type Hints` in PyTorch 0.4.0, related to IDEs(eq. PyCharm)</a>\n\nopened by <a href="https://g... |
AttributeError: module 'torchvision.transforms' has no attribute 'RandomResizedCrop' | I am running pytorch 0.3.0.post4 on Ubuntu 14.04 (conda 4.3.25, python 3.6.2, cuda 8.0).
Here is what I get when importing torchvision.transforms
>>> from torchvision import transforms
>>> dir(transforms)
['CenterCrop',
'Compose',
'Image',
'ImageOps',
'Lambd... | 0 | 2017-12-23T10:55:08.438Z | My bad. Newest torchvision apparently is 0.2.
With conda, you should be looking at the new pytorch channel. Here’s the new install command: conda install pytorch torchvision -c pytorch | 1 | 2017-12-26T00:11:31.231Z | https://discuss.pytorch.org/t/attributeerror-module-torchvision-transforms-has-no-attribute-randomresizedcrop/11489/5 | We will fix this in the next release. It’s being tracked at:
<a href="https://github.com/kimdwkimdw">
[image]
</a>
<a href="https://github.com/pytorch/pytorch/issues/7318" target="_blank">Issue: Broken `Type Hints` in PyTorch 0.4.0, related to IDEs(eq. PyCharm)</a>
opened by <a href="https://github.com/kimdwkimdw"... | 1,473 | {'text': ['My bad. Newest torchvision apparently is 0.2.\n\nWith conda, you should be looking at the new pytorch channel. Here’s the new install command: conda install pytorch torchvision -c pytorch'], 'answer_start': [1473]} |
How to apply different kernels to each example in a batch when using convolution? | F.conv2d only supports applying the same kernel to all examples in a batch.
However, I want to apply different kernels to each example. How can I do this?
The most naive approach seems the code below:
def parallel_conv2d(inputs, filters, stride=1, padding=1):
batch_size = inputs.size(0)
outp… | 1 | 2020-06-10T06:39:58.416Z | Thanks for the update and I clearly misunderstood the use case.
I think if the kernel shapes are different, you would need to use a loop and concatenate the output afterwards, as the filters cannot be stored directly in a single tensor.
However, if the kernels have all the same shape, the grouped … | 10 | 2020-06-11T00:30:54.046Z | https://discuss.pytorch.org/t/how-to-apply-different-kernels-to-each-example-in-a-batch-when-using-convolution/84848/4 | We will fix this in the next release. It’s being tracked at:
<a href="https://github.com/kimdwkimdw">
[image]
</a>
<a href="https://github.com/pytorch/pytorch/issues/7318" target="_blank">Issue: Broken `Type Hints` in PyTorch 0.4.0, related to IDEs(eq. PyCharm)</a>
opened by <a href="https://github.com/kimdwkimdw"... | 738 | {'text': ['Thanks for the update and I clearly misunderstood the use case.\n\nI think if the kernel shapes are different, you would need to use a loop and concatenate the output afterwards, as the filters cannot be stored directly in a single tensor.\n\nHowever, if the kernels have all the same shape, the grouped &hell... |
TypeError: cannot unpack non-iterable int object | Hi,
Im trying to make my first CNN using pyTorch and am following online help and code already people wrote. i am trying to reproduce their results. I’m using the Kaggle Dogs Breed Dataset for this and below is the error I get. The trainloader does not return my images and labels and any attempt to… | 0 | 2018-10-15T10:38:25.413Z | I guess your self.transform contains some image transformations other than ToTensor(), e.g. RandomCrop().
These transformations currently work on PIL.Images, so if you load your image with img = Image.open(this_img) it should work. | 2 | 2018-10-15T11:56:56.890Z | https://discuss.pytorch.org/t/typeerror-cannot-unpack-non-iterable-int-object/27286/2 | I guess your self.transform contains some image transformations other than ToTensor(), e.g. RandomCrop().
These transformations currently work on PIL.Images, so if you load your image with img = Image.open(this_img) it should work. Or you could do
img = LOAD_YOUR_IMAGE
img += img.min()
img *= 255/img.max()
img = n... | 2,092 | {'text': ['I guess your self.transform contains some image transformations other than ToTensor(), e.g. RandomCrop().\n\nThese transformations currently work on PIL.Images, so if you load your image with img = Image.open(this_img) it should work.'], 'answer_start': [2092]} |
torchvision.Transforms.ToTensor changing scale | I am using torchvision.Transforms to prepare images for a network but when I perform the operation I get strange scaling of the image.
Here is an image before transforming which is just a numpy array:
[before]
and now performing the transform…
transform = transforms.Compose([transforms.ToTensor(… | 1 | 2018-08-22T11:09:27.743Z | Or you could do
img = LOAD_YOUR_IMAGE
img += img.min()
img *= 255/img.max()
img = np.astype(np.uint8)
If your image is a numpy array (which I assume from your plotting code). This would work for all image ranges and would always use the full range of [0,255]. The disadvantage however would be that… | 1 | 2018-08-22T11:34:51.964Z | https://discuss.pytorch.org/t/torchvision-transforms-totensor-changing-scale/23663/6 | I guess your self.transform contains some image transformations other than ToTensor(), e.g. RandomCrop().
These transformations currently work on PIL.Images, so if you load your image with img = Image.open(this_img) it should work. Or you could do
img = LOAD_YOUR_IMAGE
img += img.min()
img *= 255/img.max()
img = n... | 1,279 | {'text': ['Or you could do\n\nimg = LOAD_YOUR_IMAGE\n\nimg += img.min()\n\nimg *= 255/img.max()\n\nimg = np.astype(np.uint8)\n\nIf your image is a numpy array (which I assume from your plotting code). This would work for all image ranges and would always use the full range of [0,255]. The disadvantage however would be ... |
Sampling with replacement | I’m trying to work out whether the torch.utils.data.WeightedRandomSampler class will still cover all available data inputs provided a long enough training period when choosing sampling with replacement.
Given that WeightedRandomSampler requires shuffle=False in the DataLoader, does that mean that W… | 1 | 2018-10-03T16:06:33.900Z | I think it will still work. If I’m not misunderstanding your concern, that should be exactly how the WeightedRandomSampler works.
I’ve adapted an old example using two highly imbalanced classes:
numDataPoints = 1000
data_dim = 5
bs = 100
# Create dummy data with class imbalance 99 to 1
data = tor… | 1 | 2018-11-07T17:13:39.434Z | https://discuss.pytorch.org/t/sampling-with-replacement/26474/15 | I guess your self.transform contains some image transformations other than ToTensor(), e.g. RandomCrop().
These transformations currently work on PIL.Images, so if you load your image with img = Image.open(this_img) it should work. Or you could do
img = LOAD_YOUR_IMAGE
img += img.min()
img *= 255/img.max()
img = n... | 545 | {'text': ['I think it will still work. If I’m not misunderstanding your concern, that should be exactly how the WeightedRandomSampler works.\n\nI’ve adapted an old example using two highly imbalanced classes:\n\nnumDataPoints = 1000\n\ndata_dim = 5\n\nbs = 100\n\n# Create dummy data with class imbalance 99 to 1\n\ndata... |
Fast way to use `map` in PyTorch? | So I am using PyTorch for some numerical calculation, and my problem can’t be vectorized because NestedTensor has yet to function in stable PyTorch release… Currently, I am using map function to do some tensor calculation. Here are two questions:
Is there a more efficient way to do the parallel co… | 0 | 2020-02-24T03:25:36.709Z | Hi,
I’m afraid there is no map in pytorch.
If all the operations are very small, single threaded CPU will be the fastest I’m afraid.
If you can share your problem, maybe we can help you achieve some parallelization using the existing functions though. | 1 | 2020-02-24T15:11:08.215Z | https://discuss.pytorch.org/t/fast-way-to-use-map-in-pytorch/70814/2 | Hi,
I’m afraid there is no map in pytorch.
If all the operations are very small, single threaded CPU will be the fastest I’m afraid.
If you can share your problem, maybe we can help you achieve some parallelization using the existing functions though. The easiest way would be to use <a href="http://pytorch.org/docs/... | 1,712 | {'text': ['Hi,\n\nI’m afraid there is no map in pytorch.\n\nIf all the operations are very small, single threaded CPU will be the fastest I’m afraid.\n\nIf you can share your problem, maybe we can help you achieve some parallelization using the existing functions though.'], 'answer_start': [1712]} |
How to load png using dataloader | Could someone provide me some starter code for dataloader to load the following into pytorch
Folder - Data
Folder - train
Folder - 0
3.png
10.png
13.png
…
Folder - 1
2.png
9.png
16.png
…
…
…
The folder name is the label for the data, each file is a 28x28 size png. | 1 | 2018-04-26T21:40:11.906Z | The easiest way would be to use <a href="http://pytorch.org/docs/master/torchvision/datasets.html#imagefolder">torchvision.ImageFolder</a>. This class uses assigns different classes to your folders.
The <a href="http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader">DataLoder</a> class wraps the Dataset... | 1 | 2018-04-26T22:50:39.238Z | https://discuss.pytorch.org/t/how-to-load-png-using-dataloader/17079/2 | Hi,
I’m afraid there is no map in pytorch.
If all the operations are very small, single threaded CPU will be the fastest I’m afraid.
If you can share your problem, maybe we can help you achieve some parallelization using the existing functions though. The easiest way would be to use <a href="http://pytorch.org/docs/... | 1,111 | {'text': ['The easiest way would be to use <a href="http://pytorch.org/docs/master/torchvision/datasets.html#imagefolder">torchvision.ImageFolder</a>. This class uses assigns different classes to your folders.\n\nThe <a href="http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader">DataLoder</a> class wrap... |
Batch prediction for a model | I have a LSTM model trained for a batch size = 512. This means that 512 hidden states are initialized for each sample in the batch. Now during prediction if I give a batch_size=100 it throws an inconsistent size error probably because it cannot initialize the hidden states for the 100 samples since … | 1 | 2018-01-11T12:05:51.883Z | My mistake, you also have to set the correct new batch size.
model.batch_size = test_batch_size
model.hidden_state = model.init_hidden()
If you don’t know why you need to do that then you know little about how an LSTM works.
[image] kaushalshetty:
I have a LSTM model trained for a batch size … | 2 | 2018-01-11T17:12:06.954Z | https://discuss.pytorch.org/t/batch-prediction-for-a-model/12156/7 | Hi,
I’m afraid there is no map in pytorch.
If all the operations are very small, single threaded CPU will be the fastest I’m afraid.
If you can share your problem, maybe we can help you achieve some parallelization using the existing functions though. The easiest way would be to use <a href="http://pytorch.org/docs/... | 730 | {'text': ['My mistake, you also have to set the correct new batch size.\n\nmodel.batch_size = test_batch_size\n\nmodel.hidden_state = model.init_hidden()\n\nIf you don’t know why you need to do that then you know little about how an LSTM works.\n\n[image] kaushalshetty:\n\nI have a LSTM model trained for a batch size &... |
Transferring weights from Keras to PyTorch | Hi,
I have a trained model in Keras (tensorflow backend) and want to transfer those weights to a pytorch model. As I do it, the model in pytorch performance not as good as the keras model does. Even the forward propagation has differences. To nail the problem down I created a small toy example to s… | 0 | 2017-11-13T20:06:33.021Z | Hi soumith,
Thank you for your prompt responses. I have identified the problem to how the input was being pre-processed before feeding into the model. there were subtle differences which were not easily identifiable by the naked eye.
Currently the results are exactly the same, even till the order … | 3 | 2017-11-17T20:51:07.712Z | https://discuss.pytorch.org/t/transferring-weights-from-keras-to-pytorch/9889/11 | Hi soumith,
Thank you for your prompt responses. I have identified the problem to how the input was being pre-processed before feeding into the model. there were subtle differences which were not easily identifiable by the naked eye.
Currently the results are exactly the same, even till the order … You can rea... | 2,072 | {'text': ['Hi soumith,\n\nThank you for your prompt responses. I have identified the problem to how the input was being pre-processed before feeding into the model. there were subtle differences which were not easily identifiable by the naked eye.\n\nCurrently the results are exactly the same, even till the order &hell... |
Leaf variable has been moved into the graph interior | I am using PyTorch 0.4
import torch
X=torch.randn((100,3))
Y=torch.randn((100))
w1=torch.tensor(0.1, requires_grad=True)
w2=torch.tensor(0.1, requires_grad=True)
w3=torch.tensor(0.1, requires_grad=True)
W=torch.tensor([0.1, 0.1, 0.1], requires_grad=True)
W[0]=w1 * w2; W[1]=w2 * w3; W[2]=w3… | 0 | 2018-05-25T14:36:34.169Z | You can read a nice explanation of leaf variables in <a href="https://discuss.pytorch.org/t/leaf-variable-was-used-in-an-inplace-operation/308/2?u=ptrblck">this post</a>.
Usually you have to avoid modifying a leaf variable with an in-place operation.
I haven’t seen your error message yet, but it seems it related to a... | 2 | 2018-05-25T16:24:28.571Z | https://discuss.pytorch.org/t/leaf-variable-has-been-moved-into-the-graph-interior/18679/6 | Hi soumith,
Thank you for your prompt responses. I have identified the problem to how the input was being pre-processed before feeding into the model. there were subtle differences which were not easily identifiable by the naked eye.
Currently the results are exactly the same, even till the order … You can rea... | 1,345 | {'text': ['You can read a nice explanation of leaf variables in <a href="https://discuss.pytorch.org/t/leaf-variable-was-used-in-an-inplace-operation/308/2?u=ptrblck">this post</a>.\n\nUsually you have to avoid modifying a leaf variable with an in-place operation.\n\nI haven’t seen your error message yet, but it seems ... |
Mask selection with expand | Hi,
I have a target tensor that I want to one hot encode and finally filter with a binary mask originally based on the target tensor.
# target tensor
t = torch.Tensor(4, 5, 5).random_(0, 10).long()
# binary mask
m = t == 3
# one hot encoded tensor
et = torch.Tensor(4, 10, 5, 5).zero_()
# one hot e… | 1 | 2017-11-13T13:23:37.904Z | You will have problems regarding one of the inner dimensions, as you won’t have always the same number of elements
here’s a little over-simplified example :
t = torch.Tensor(2, 2).random_(0, 2).long()
# t = [ 0, 0,
# 1, 0] (long tensor)
m = t == 1
# m = [[0, 0],
# [1, 0]] (byte tensor … | 2 | 2017-11-13T15:18:10.670Z | https://discuss.pytorch.org/t/mask-selection-with-expand/9873/2 | Hi soumith,
Thank you for your prompt responses. I have identified the problem to how the input was being pre-processed before feeding into the model. there were subtle differences which were not easily identifiable by the naked eye.
Currently the results are exactly the same, even till the order … You can rea... | 725 | {'text': ['You will have problems regarding one of the inner dimensions, as you won’t have always the same number of elements\n\nhere’s a little over-simplified example :\n\nt = torch.Tensor(2, 2).random_(0, 2).long()\n\n# t = [ 0, 0,\n\n# 1, 0] (long tensor)\n\nm = t == 1\n\n# m = [[0, 0],\n\n# [1, 0]] (by... |
Installing Pytorch on M1 Macbook? | I haven’t been able to install Pytorch. When I try using pip3, I get this error due to building wheel for Numpy:
ERROR: Could not build wheels for numpy which use PEP 517 and cannot be installed directly
When I use the Apple version of NumPy that Tensorflow released, I need to use a virtual env. S… | 1 | 2020-12-12T21:52:38.206Z | Since there is no binary, I guess you can also install it from source the same way.
If you encounter any issues with that, do report an issue on the torchvision repo! | 0 | 2020-12-14T20:59:34.247Z | https://discuss.pytorch.org/t/installing-pytorch-on-m1-macbook/105961/4 | Since there is no binary, I guess you can also install it from source the same way.
If you encounter any issues with that, do report an issue on the torchvision repo! import torch
import torch.nn.functional as F
src = torch.arange(25, dtype=torch.float).reshape(1, 1, 5, 5).requires_grad_() # 1 x 1 x 5 x 5 with 0 ..... | 2,076 | {'text': ['Since there is no binary, I guess you can also install it from source the same way.\n\nIf you encounter any issues with that, do report an issue on the torchvision repo!'], 'answer_start': [2076]} |
Differentiable Indexing | I want to do something like this, but I need it be be differentiable w.r.t the index-tensors. is there any possibility to achieve this?
import torch
# initialize tensor
tensor = torch.zeros((1, 400, 400)).double()
tensor.requires_grad_(True)
# create index ranges
x_range = torch.arange(150, 250).… | 1 | 2018-05-07T07:54:28.410Z | import torch
import torch.nn.functional as F
src = torch.arange(25, dtype=torch.float).reshape(1, 1, 5, 5).requires_grad_() # 1 x 1 x 5 x 5 with 0 ... 25
indices = torch.tensor([[-1, -1], [0, 0]], dtype=torch.float).reshape(1, 1, -1, 2) # 1 x 1 x 2 x 2
output = F.grid_sample(src, indices)
print(o… | 6 | 2018-05-08T19:40:50.375Z | https://discuss.pytorch.org/t/differentiable-indexing/17647/6 | Since there is no binary, I guess you can also install it from source the same way.
If you encounter any issues with that, do report an issue on the torchvision repo! import torch
import torch.nn.functional as F
src = torch.arange(25, dtype=torch.float).reshape(1, 1, 5, 5).requires_grad_() # 1 x 1 x 5 x 5 with 0 ..... | 1,206 | {'text': ['import torch\n\nimport torch.nn.functional as F\n\nsrc = torch.arange(25, dtype=torch.float).reshape(1, 1, 5, 5).requires_grad_() # 1 x 1 x 5 x 5 with 0 ... 25\n\nindices = torch.tensor([[-1, -1], [0, 0]], dtype=torch.float).reshape(1, 1, -1, 2) # 1 x 1 x 2 x 2\n\noutput = F.grid_sample(src, indices)\n\npr... |
Affine transformation matrix paramters conversion | Hi all,
I want to rotate an image about a specific point. First I create the Transformation matrices for moving the center point to the origin, rotating and then moving back to the first point, then apply the transform using affine_grid and grid_sample functions. But the resulting image is not what… | 0 | 2018-06-11T14:26:17.544Z | Demo code can be found,<a href="https://github.com/wuneng/WarpAffine2GridSample" rel="nofollow noopener">https://github.com/wuneng/WarpAffine2GridSample</a>. | 2 | 2019-07-26T03:36:48.331Z | https://discuss.pytorch.org/t/affine-transformation-matrix-paramters-conversion/19522/15 | Since there is no binary, I guess you can also install it from source the same way.
If you encounter any issues with that, do report an issue on the torchvision repo! import torch
import torch.nn.functional as F
src = torch.arange(25, dtype=torch.float).reshape(1, 1, 5, 5).requires_grad_() # 1 x 1 x 5 x 5 with 0 ..... | 481 | {'text': ['Demo code can be found,<a href="https://github.com/wuneng/WarpAffine2GridSample" rel="nofollow noopener">https://github.com/wuneng/WarpAffine2GridSample</a>.'], 'answer_start': [481]} |
DataLoader Multiprocessing error: can't pickle odict_keys objects when num_workers > 0 | I’m using windows10 64-bit, python 3.7.3 in Jupyter Notebook(anaconda) environment, intel i9-7980XE:
When I try to enumerate over the DataLoader() object with num_workers > 0 like:
> if __name__=='__main__':
> ...
> DL = DataLoader(data, batch_size=8, shuffle=True, num_workers=8)
> ... | 0 | 2019-04-29T17:16:21.633Z | I eventually solved my problem and i’ll leave the solution here so hopefully someone else will be spared the pain.
It had nothing to do with python version or interactive shells. I tried different environments, none made it work. The error was related to pickling/dictionaries/windows/python.
My py… | 5 | 2019-04-30T14:19:59.915Z | https://discuss.pytorch.org/t/dataloader-multiprocessing-error-cant-pickle-odict-keys-objects-when-num-workers-0/43951/4 | I eventually solved my problem and i’ll leave the solution here so hopefully someone else will be spared the pain.
It had nothing to do with python version or interactive shells. I tried different environments, none made it work. The error was related to pickling/dictionaries/windows/python.
My py… In
self.Bi... | 1,276 | {'text': ['I eventually solved my problem and i’ll leave the solution here so hopefully someone else will be spared the pain.\n\nIt had nothing to do with python version or interactive shells. I tried different environments, none made it work. The error was related to pickling/dictionaries/windows/python.\n\nMy py&hell... |
Why "loss.backward()" didn't update parameters' gradient? | Hi, I came across some problems about gradient update when training my network. I built a CNN network with “two” weights, the original float weight “self.weight” and a binarized one “self.Bi_weight”, I created them as the same:
if transposed:
# If transposed, [in, out, [kernal size]]
… | 0 | 2018-06-11T12:36:51.002Z | In
self.Bi_weight = Parameter(torch.Tensor(self.weight.shape)).cuda()
the .cuda() is computation and you don’t have a Parameter in self.Bi_weight.
Use self.Bi_weight = Parameter(torch.Tensor(self.weight.shape).cuda()) or better yet just leave the .cuda() alone and do model.cuda() at the end.
Bes… | 0 | 2018-06-11T12:44:46.636Z | https://discuss.pytorch.org/t/why-loss-backward-didnt-update-parameters-gradient/19515/2 | I eventually solved my problem and i’ll leave the solution here so hopefully someone else will be spared the pain.
It had nothing to do with python version or interactive shells. I tried different environments, none made it work. The error was related to pickling/dictionaries/windows/python.
My py… In
self.Bi... | 947 | {'text': ['In\n\nself.Bi_weight = Parameter(torch.Tensor(self.weight.shape)).cuda()\n\nthe .cuda() is computation and you don’t have a Parameter in self.Bi_weight.\n\nUse self.Bi_weight = Parameter(torch.Tensor(self.weight.shape).cuda()) or better yet just leave the .cuda() alone and do model.cuda() at the end.\n\nBes&... |
How to print the computational graph of a Variable? | <a href="http://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html" rel="nofollow noopener">http://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html</a> says:
Now, if you follow loss in the backward direction, using it’s .creator attribute, you will see a graph of computations that loo... | 1 | 2017-05-22T09:30:33.723Z | Hi,
You can use this script to create a graph <a href="https://github.com/szagoruyko/functional-zoo/blob/master/visualize.py">https://github.com/szagoruyko/functional-zoo/blob/master/visualize.py</a>
To open it with a regular pdf viewer you can do make_dot(your_var).view(). | 2 | 2017-05-22T09:31:49.887Z | https://discuss.pytorch.org/t/how-to-print-the-computational-graph-of-a-variable/3325/2 | I eventually solved my problem and i’ll leave the solution here so hopefully someone else will be spared the pain.
It had nothing to do with python version or interactive shells. I tried different environments, none made it work. The error was related to pickling/dictionaries/windows/python.
My py… In
self.Bi... | 618 | {'text': ['Hi,\n\nYou can use this script to create a graph <a href="https://github.com/szagoruyko/functional-zoo/blob/master/visualize.py">https://github.com/szagoruyko/functional-zoo/blob/master/visualize.py</a>\n\nTo open it with a regular pdf viewer you can do make_dot(your_var).view().'], 'answer_start': [618]} |
Backward() on parameter that requires_grad=True; but still get does not have a grad_fn | Following is a simple version of my original code.
Basically; the code does two things
(1) optimize the objective function use the gradient descent
(2) control the gradients computed from (1) by through a neural network
a = Variable(torch.Tensor([-2.]),requires_grad=True)
b = Variable(torch.Tens… | 0 | 2018-05-22T03:11:50.510Z | The problem is that you created 2 tensors that have no grad function by calling the clone operation on the .data.grad tensor.
Below is a simplified, working example:
a = torch.tensor([-2.], requires_grad=True)
b = torch.tensor([-2.], requires_grad=True)
for i in range(1):
var_loss = torch.t… | 2 | 2018-05-22T03:55:18.085Z | https://discuss.pytorch.org/t/backward-on-parameter-that-requires-grad-true-but-still-get-does-not-have-a-grad-fn/18475/2 | The problem is that you created 2 tensors that have no grad function by calling the clone operation on the .data.grad tensor.
Below is a simplified, working example:
a = torch.tensor([-2.], requires_grad=True)
b = torch.tensor([-2.], requires_grad=True)
for i in range(1):
var_loss = torch.t… <a href="https:... | 1,788 | {'text': ['The problem is that you created 2 tensors that have no grad function by calling the clone operation on the .data.grad tensor.\n\nBelow is a simplified, working example:\n\na = torch.tensor([-2.], requires_grad=True)\n\nb = torch.tensor([-2.], requires_grad=True)\n\nfor i in range(1):\n\nvar_loss = torch.t&he... |
Converting list to tensor | There is a variable ‘tmp’ (3 dimension).
type(tmp) -> <class 'list'>
type(tmp[0]) -> <class 'torch.Tensor'>
type(tmp[0][0]) -> <class 'torch.Tensor'>
I want to convert ‘tmp’ into torch.Tensor type.
But, when I run this code below, an error occurs.
torch.Tensor(tm... | 0 | 2020-02-18T06:03:43.173Z | <a href="https://github.com/pytorch/pytorch/issues/22169">Nested tensors</a> (WIP) might be usable.
Since this feature is not implemented yet, you might need to keep the list.
Depending on your use case, you might be able to create tensors using padding or slicing. | 1 | 2020-02-18T07:06:55.927Z | https://discuss.pytorch.org/t/converting-list-to-tensor/70120/5 | The problem is that you created 2 tensors that have no grad function by calling the clone operation on the .data.grad tensor.
Below is a simplified, working example:
a = torch.tensor([-2.], requires_grad=True)
b = torch.tensor([-2.], requires_grad=True)
for i in range(1):
var_loss = torch.t… <a href="https:... | 1,199 | {'text': ['<a href="https://github.com/pytorch/pytorch/issues/22169">Nested tensors</a> (WIP) might be usable.\n\nSince this feature is not implemented yet, you might need to keep the list.\n\nDepending on your use case, you might be able to create tensors using padding or slicing.'], 'answer_start': [1199]} |
How to Implement a convolutional layer | Hello all,
For my research, I’m required to implement a convolution-like layer i.e something that slides over some input (assume 1D for simplicity), performs some operation and generates basically an output feature map. While this is perfectly similar to regular convolution, the difference here is … | 2 | 2020-01-31T08:33:32.940Z | You could use unfold as descibed <a href="https://discuss.pytorch.org/t/efficiently-slicing-tensor-like-a-convolution/44840/2">here</a> to create the patches, which would be used in the convolution.
Instead of a multiplication and summation you could apply your custom operation on each patch and reshape the output to ... | 1 | 2020-02-01T07:44:25.779Z | https://discuss.pytorch.org/t/how-to-implement-a-convolutional-layer/68211/2 | The problem is that you created 2 tensors that have no grad function by calling the clone operation on the .data.grad tensor.
Below is a simplified, working example:
a = torch.tensor([-2.], requires_grad=True)
b = torch.tensor([-2.], requires_grad=True)
for i in range(1):
var_loss = torch.t… <a href="https:... | 573 | {'text': ['You could use unfold as descibed <a href="https://discuss.pytorch.org/t/efficiently-slicing-tensor-like-a-convolution/44840/2">here</a> to create the patches, which would be used in the convolution.\n\nInstead of a multiplication and summation you could apply your custom operation on each patch and reshape t... |
Input numpy ndarray instead of images in a CNN | Hello,
I am kind of new with Pytorch.
I would like to run my CNN with some ordered datasets that I have.
I have n-dimensional arrays, and I would like to pass them like the input dataset.
Is there any way to pass it with torch.utils.data.DataLoader?
Or how can I transform the n-dimensional arra… | 0 | 2018-05-28T16:47:41.357Z | You could create a Dataset, and load and transform your arrays there.
Here is a small example:
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
class MyDataset(Dataset):
def __init__(self, data, target, transform=None):
self.data = torch.from_numpy(da… | 12 | 2018-05-28T17:16:09.032Z | https://discuss.pytorch.org/t/input-numpy-ndarray-instead-of-images-in-a-cnn/18797/2 | You could create a Dataset, and load and transform your arrays there.
Here is a small example:
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
class MyDataset(Dataset):
def __init__(self, data, target, transform=None):
self.data = torch.from_numpy(da… Thanks for the code.
... | 1,822 | {'text': ['You could create a Dataset, and load and transform your arrays there.\n\nHere is a small example:\n\nimport torch\n\nfrom torch.utils.data import Dataset, DataLoader\n\nimport numpy as np\n\nclass MyDataset(Dataset):\n\ndef __init__(self, data, target, transform=None):\n\nself.data = torch.from_numpy(da&hell... |
Extract features from layer of submodule of a model | My model looks like this:
from __future__ import absolute_import
import torch
from torch import nn
from torch.nn import functional as F
import torchvision
class hybrid_cnn(nn.Module):
def __init__(self,**kwargs):
super(hybrid_cnn,self).__init__()
resnet = torchvision.model… | 0 | 2018-06-24T16:47:17.023Z | Thanks for the code.
Your return statement is at the wrong place.
get_activation should return hook, not hook itself:
Right way:
def get_activation(name):
def hook(model, input, output):
activation[name] = output.detach()
return hook
Your current implementation:
def get_activat… | 0 | 2018-06-25T08:17:59.436Z | https://discuss.pytorch.org/t/extract-features-from-layer-of-submodule-of-a-model/20181/14 | You could create a Dataset, and load and transform your arrays there.
Here is a small example:
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
class MyDataset(Dataset):
def __init__(self, data, target, transform=None):
self.data = torch.from_numpy(da… Thanks for the code.
... | 1,210 | {'text': ['Thanks for the code.\n\nYour return statement is at the wrong place.\n\nget_activation should return hook, not hook itself:\n\nRight way:\n\ndef get_activation(name):\n\ndef hook(model, input, output):\n\nactivation[name] = output.detach()\n\nreturn hook\n\nYour current implementation:\n\ndef get_activat&hel... |
Input size of fc layer in tutorial? | class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2,2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear(120, 84)
self.f… | 0 | 2018-03-09T06:44:43.354Z | The input of a Pytorch Neural Network is of type [BATCH_SIZE] * [CHANNEL_NUMBER] * [HEIGHT] * [WIDTH].
Example : So lets assume you image is of dimension 1×3×32×32 meaning that you have 1 image with 3 channels (RGB) with height 32 and width 32. So using the formular of convolution which is ((W -… | 2 | 2019-02-21T22:39:16.313Z | https://discuss.pytorch.org/t/input-size-of-fc-layer-in-tutorial/14644/10 | You could create a Dataset, and load and transform your arrays there.
Here is a small example:
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
class MyDataset(Dataset):
def __init__(self, data, target, transform=None):
self.data = torch.from_numpy(da… Thanks for the code.
... | 595 | {'text': ['The input of a Pytorch Neural Network is of type [BATCH_SIZE] * [CHANNEL_NUMBER] * [HEIGHT] * [WIDTH].\n\nExample : So lets assume you image is of dimension 1×3×32×32 meaning that you have 1 image with 3 channels (RGB) with height 32 and width 32. So using the formular of convolution which is ((W -&hellip... |
Saving model AND optimiser AND scheduler | Hi,
I want to able to have a model/optimiser/scheduler object - which I can hot plug and play.
So for example, have a list of such objects, load to gpu in turn, do some training, switch objects.
Maybe then load some earlier ones and pick up training where we left off last time.
I’d like to be ab… | 1 | 2019-07-30T09:27:00.059Z | If I store them in the same file - it only stores the state_dicts for each. It will not pickle the object.
This is not true. As long as you do not call state_dict(), it will save the whole variable. Please try the following.
For saving:
checkpoint = {
'epoch': epoch,
'model': model,
… | 5 | 2019-07-30T10:17:18.128Z | https://discuss.pytorch.org/t/saving-model-and-optimiser-and-scheduler/52030/8 | If I store them in the same file - it only stores the state_dicts for each. It will not pickle the object.
This is not true. As long as you do not call state_dict(), it will save the whole variable. Please try the following.
For saving:
checkpoint = {
'epoch': epoch,
'model': model,
… I hav... | 1,806 | {'text': ['If I store them in the same file - it only stores the state_dicts for each. It will not pickle the object.\n\nThis is not true. As long as you do not call state_dict(), it will save the whole variable. Please try the following.\n\nFor saving:\n\ncheckpoint = {\n\n'epoch': epoch,\n\n'model': m... |
Loading saved models gives inconsistent results each time | I have multiple trained LSTM models on different data. I save them as below.
save_checkpoints({
'num_epochs': epoch,
'num_hidden': number_hidden,
'num_cells': number_cells,
'device': device,
'state_dict': model.state_di… | 0 | 2019-02-03T18:17:48.503Z | I have corrected the code to save dict of multiple LSTM Cells and load them individually like below,
# Save the checkpoint
save_checkpoints({
'num_epochs': epoch,
'num_hidden': number_hidden,
'num_cells': number_cells,
… | 0 | 2019-02-17T09:49:48.300Z | https://discuss.pytorch.org/t/loading-saved-models-gives-inconsistent-results-each-time/36312/24 | If I store them in the same file - it only stores the state_dicts for each. It will not pickle the object.
This is not true. As long as you do not call state_dict(), it will save the whole variable. Please try the following.
For saving:
checkpoint = {
'epoch': epoch,
'model': model,
… I hav... | 1,218 | {'text': ['I have corrected the code to save dict of multiple LSTM Cells and load them individually like below,\n\n# Save the checkpoint\n\nsave_checkpoints({\n\n'num_epochs': epoch,\n\n'num_hidden': number_hidden,\n\n'num_cells': number_cells,\n\n…'], 'answer_start': [1218]} |
Comparison Data Parallel Distributed data parallel | Hello. I hope you are very well.
I am finalizing my experiment with pytorch. When I finish my paper, I hope I can share my paper in here.
Anyway, is there any detailed documentation about data parallel(dp) and distributed data parallel(ddp)
During my experiment, DP and DDP have big accuracy diffe… | 2 | 2020-08-18T19:37:34.018Z | [image] henry_Kang:
So Basically DP and DDP do not directly change the weight “but it is a different way to calculate the gradient in multi GPU conditions”.
correct.
The input data goes through the network, and loss calculate based on output and ground truth.
During this loss calculation, … | 2 | 2020-08-19T02:14:00.182Z | https://discuss.pytorch.org/t/comparison-data-parallel-distributed-data-parallel/93271/6 | If I store them in the same file - it only stores the state_dicts for each. It will not pickle the object.
This is not true. As long as you do not call state_dict(), it will save the whole variable. Please try the following.
For saving:
checkpoint = {
'epoch': epoch,
'model': model,
… I hav... | 573 | {'text': ['[image] henry_Kang:\n\nSo Basically DP and DDP do not directly change the weight “but it is a different way to calculate the gradient in multi GPU conditions”.\n\ncorrect.\n\nThe input data goes through the network, and loss calculate based on output and ground truth.\n\nDuring this loss calculation, &hellip... |
Where to find <torch/torch.h>? | I succeed in compiling the code with cmake directly, but when I use vscode for editing, it always get error message with <torch/torch.h> not found. How can I get it? | 1 | 2019-11-04T01:20:39.662Z | Hi,
you need to add the somewhat hidden <installation dir>/include/torch/csrc/api/include to the includes.
If you create the CMakeLists.txt as in <a href="https://pytorch.org/cppdocs/installing.html" rel="nofollow noopener">the example</a>, the TorchConfig.cmake should set it up for you up when running find_pac... | 5 | 2019-11-04T06:52:58.936Z | https://discuss.pytorch.org/t/where-to-find-torch-torch-h/59908/2 | Hi,
you need to add the somewhat hidden <installation dir>/include/torch/csrc/api/include to the includes.
If you create the CMakeLists.txt as in <a href="https://pytorch.org/cppdocs/installing.html" rel="nofollow noopener">the example</a>, the TorchConfig.cmake should set it up for you up when running find_pac... | 1,750 | {'text': ['Hi,\n\nyou need to add the somewhat hidden <installation dir>/include/torch/csrc/api/include to the includes.\n\nIf you create the CMakeLists.txt as in <a href="https://pytorch.org/cppdocs/installing.html" rel="nofollow noopener">the example</a>, the TorchConfig.cmake should set it up for you up when r... |
RuntimeError: Unexpected error from cudaGetDeviceCount() | I was training GCN model on my Linux server and I suddenly got this error.
RuntimeError: Unexpected error from cudaGetDeviceCount(). Did you run some cuda functions before calling NumCudaDevices() that might have already set an error? Error 804: forward compatibility was attempted on non supported… | 0 | 2021-12-22T10:10:12.523Z | Based on <a href="https://github.com/pytorch/pytorch/issues/40671">this issue</a> other users were running into the same error message if
their setup was broken due to a driver/library mismatch (rebooting seemed to solve the issue)
their installed drivers didn’t match the user-mode driver inside a docker container (a... | 1 | 2021-12-22T19:25:02.249Z | https://discuss.pytorch.org/t/runtimeerror-unexpected-error-from-cudagetdevicecount/139977/5 | Hi,
you need to add the somewhat hidden <installation dir>/include/torch/csrc/api/include to the includes.
If you create the CMakeLists.txt as in <a href="https://pytorch.org/cppdocs/installing.html" rel="nofollow noopener">the example</a>, the TorchConfig.cmake should set it up for you up when running find_pac... | 1,239 | {'text': ['Based on <a href="https://github.com/pytorch/pytorch/issues/40671">this issue</a> other users were running into the same error message if\n\ntheir setup was broken due to a driver/library mismatch (rebooting seemed to solve the issue)\n\ntheir installed drivers didn’t match the user-mode driver inside a dock... |
AttributeError: 'tuple' object has no attribute 'size' | Hi, I am working on omniglot images and I am struggling with this error. I believe the problem is with my dataset generation. Please help me figure it out. Here is the dataset code:
import os
from PIL import Image
import numpy as np
from torch.utils.data import Dataset
import torch
from torchvision… | 0 | 2019-12-03T00:34:00.185Z | Could you check the type of outputs and labels?
I guess labels is passed as a tuple instead of a tensor.
If so, you could return labels in your __getitem__ as:
torch.tensor(self.labels[idx]) | 1 | 2019-12-03T00:46:35.655Z | https://discuss.pytorch.org/t/attributeerror-tuple-object-has-no-attribute-size/62801/4 | Hi,
you need to add the somewhat hidden <installation dir>/include/torch/csrc/api/include to the includes.
If you create the CMakeLists.txt as in <a href="https://pytorch.org/cppdocs/installing.html" rel="nofollow noopener">the example</a>, the TorchConfig.cmake should set it up for you up when running find_pac... | 735 | {'text': ['Could you check the type of outputs and labels?\n\nI guess labels is passed as a tuple instead of a tensor.\n\nIf so, you could return labels in your __getitem__ as:\n\ntorch.tensor(self.labels[idx])'], 'answer_start': [735]} |
Loading pytorch model without a code | Hello, everyone!
I have a question about PyTorch load mechanics, when we are using torch.save and torch.load. Let’s look at examples:
Suppose, I have a network:
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
class ReallySimpleModel(nn.Mod… | 1 | 2018-01-18T07:16:45.146Z | There are limitations to loading pytorch model without code.
First limitation:
We only save the source code of the class definition. We do not save beyond that (like the package sources that the class is referring to).
For example:
import foo
class MyModel(...):
def forward(input):
… | 5 | 2018-01-18T18:21:00.626Z | https://discuss.pytorch.org/t/loading-pytorch-model-without-a-code/12469/2 | There are limitations to loading pytorch model without code.
First limitation:
We only save the source code of the class definition. We do not save beyond that (like the package sources that the class is referring to).
For example:
import foo
class MyModel(...):
def forward(input):
… Thank you for your re... | 1,856 | {'text': ['There are limitations to loading pytorch model without code.\n\nFirst limitation:\n\nWe only save the source code of the class definition. We do not save beyond that (like the package sources that the class is referring to).\n\nFor example:\n\nimport foo\n\nclass MyModel(...):\n\ndef forward(input):\n\n&hell... |
Tensor stack or concatenate | Here is the question:
suppose:
tensor a is a 3x3 tensor
tensor b is a 4x3 tensor
tensor c is a 5x3 tensor
I want to build a tensor which contains all the unique row tensor of these three tensors
example:
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[1,3,7],[2,4,8],[3,7,9],[4,5,6]]
c = [[1,2,3],[2,4,8… | 0 | 2019-01-10T07:16:41.496Z | Thank you for your reply, your solution give my a hint, I find another solution:
a = torch.Tensor([[1,2,3],[4,5,6],[7,8,9]])
b = torch.Tensor([[1,3,7],[2,4,8],[3,7,9],[4,5,6]])
c = torch.Tensor([[1,2,3],[2,4,8],[3,7,9],[3,5,6],[7,8,9]])
d = torch.cat((a,b,c))
print(d.shape)
d_unique = torch.unique(… | 1 | 2019-01-10T10:27:06.802Z | https://discuss.pytorch.org/t/tensor-stack-or-concatenate/34331/7 | There are limitations to loading pytorch model without code.
First limitation:
We only save the source code of the class definition. We do not save beyond that (like the package sources that the class is referring to).
For example:
import foo
class MyModel(...):
def forward(input):
… Thank you for your re... | 1,227 | {'text': ['Thank you for your reply, your solution give my a hint, I find another solution:\n\na = torch.Tensor([[1,2,3],[4,5,6],[7,8,9]])\n\nb = torch.Tensor([[1,3,7],[2,4,8],[3,7,9],[4,5,6]])\n\nc = torch.Tensor([[1,2,3],[2,4,8],[3,7,9],[3,5,6],[7,8,9]])\n\nd = torch.cat((a,b,c))\n\nprint(d.shape)\n\nd_unique = torch... |
How to transfer learned weight in the same model without last layer? | Hello all, I have my own network, it trained for the binary classifier (2 classes). After 10k epochs, I obtained the trained weight as 10000_model.pth. Now, I want to use the model for 4 classes classifier problem using the same network. Thus, I want to copy all trained weight in the binary classifi… | 1 | 2018-12-22T15:35:53.769Z | The error message sounds like you already changed the conv_class layer.
Could you check, if you are using two different layers as the output, since the error points to conv_class, while you are manipulating conv_classify.
Here is a small code snippet of what I was thinking about:
class MyModel(nn… | 2 | 2018-12-23T23:46:32.185Z | https://discuss.pytorch.org/t/how-to-transfer-learned-weight-in-the-same-model-without-last-layer/32824/6 | There are limitations to loading pytorch model without code.
First limitation:
We only save the source code of the class definition. We do not save beyond that (like the package sources that the class is referring to).
For example:
import foo
class MyModel(...):
def forward(input):
… Thank you for your re... | 613 | {'text': ['The error message sounds like you already changed the conv_class layer.\n\nCould you check, if you are using two different layers as the output, since the error points to conv_class, while you are manipulating conv_classify.\n\nHere is a small code snippet of what I was thinking about:\n\nclass MyModel(nn&he... |
How to Save DataLoader? | Hi,
I am new to PyTorch and currently experimenting on PyTorch’s DataLoader on Google Colab. My experiment often requires training time over 12 hours, which is more than what Google Colab offers. Due to this reason, I need to be able to save my optimizer, learning rate scheduler, and the state per … | 0 | 2019-12-03T02:16:33.161Z | Thank you for the answers. After trying some codes of my own yesterday, I figured out that DataLoader can be saved directly using PyTorch’s torch.save(dataloader_obj, 'dataloader.pth'). The order of data is maintained so far, and the batches as well. | 6 | 2019-12-04T00:55:54.134Z | https://discuss.pytorch.org/t/how-to-save-dataloader/62813/4 | Thank you for the answers. After trying some codes of my own yesterday, I figured out that DataLoader can be saved directly using PyTorch’s torch.save(dataloader_obj, 'dataloader.pth'). The order of data is maintained so far, and the batches as well. Could you update to the latest stable release or the nightly ... | 1,842 | {'text': ['Thank you for the answers. After trying some codes of my own yesterday, I figured out that DataLoader can be saved directly using PyTorch’s torch.save(dataloader_obj, 'dataloader.pth'). The order of data is maintained so far, and the batches as well.'], 'answer_start': [1842]} |
Validation hangs up when using DDP and syncbatchnorm | I’m using DDP(one process per GPU) to training a 3D UNet. I transfered all batchnorm layer inside network to syncbatchnorm with nn.SyncBatchNorm.convert_sync_batchnorm.
When doing validation at the end of every training epoch on rank 0, it always freeze at same validation steps. I think it is becau… | 3 | 2020-12-02T07:04:55.901Z | Could you update to the latest stable release or the nightly binary and check, if you are still facing the error? 1.1.0 is quite old by now and this issue might have been already fixed. | 1 | 2020-12-04T06:25:00.531Z | https://discuss.pytorch.org/t/validation-hangs-up-when-using-ddp-and-syncbatchnorm/104831/2 | Thank you for the answers. After trying some codes of my own yesterday, I figured out that DataLoader can be saved directly using PyTorch’s torch.save(dataloader_obj, 'dataloader.pth'). The order of data is maintained so far, and the batches as well. Could you update to the latest stable release or the nightly ... | 1,180 | {'text': ['Could you update to the latest stable release or the nightly binary and check, if you are still facing the error? 1.1.0 is quite old by now and this issue might have been already fixed.'], 'answer_start': [1180]} |
Implement Selected Sparse connected neural network | I am trying to implement the following general NN model (Not CNN) using Pytorch.
<a class="lightbox" href="https://lh6.googleusercontent.com/Boki3HCcAbmFrCHLfyLEOUaQOQlTffYSGi5iAzGyne_dG3YUbonkl5O8n0iUcWSDQQHdxiZON-l2SYksF8L2RI5hjO4MQTRGQPdbtJqn0Z1EIQAf8YnhSvVNnqNwJXLUGpoQRMvowvQ" title="Boki3HCcAbmFrCHLfyLEOUaQOQlTff... | 1 | 2019-05-17T15:30:38.668Z | The parameters of MySmallModels are most likely missing in model.parameters(), since you are storing them in a plain Python list, thus the optimizer is ignoring them.
Try to use self.networks = nn.ModuleList instead. | 0 | 2019-05-19T20:07:43.667Z | https://discuss.pytorch.org/t/implement-selected-sparse-connected-neural-network/45517/4 | Thank you for the answers. After trying some codes of my own yesterday, I figured out that DataLoader can be saved directly using PyTorch’s torch.save(dataloader_obj, 'dataloader.pth'). The order of data is maintained so far, and the batches as well. Could you update to the latest stable release or the nightly ... | 445 | {'text': ['The parameters of MySmallModels are most likely missing in model.parameters(), since you are storing them in a plain Python list, thus the optimizer is ignoring them.\n\nTry to use self.networks = nn.ModuleList instead.'], 'answer_start': [445]} |
RuntimeError: cuda runtime error (710) | error:
RuntimeError: cuda runtime error (710) : device-side assert triggered at /pytorch/aten/src/THC/THCCachingHostAllocator.cpp:278
How to trigger it:
print (logits)
about this tensor:
print (logits.shape)
torch.Size([32, 80, 7])
type (logits)
torch.Tensor
Full stack trace:
RuntimeError … | 1 | 2019-11-21T15:11:19.091Z | In else I use label1_embedding ! There should be self.label2_embedding. | 1 | 2019-11-24T11:07:29.436Z | https://discuss.pytorch.org/t/runtimeerror-cuda-runtime-error-710/61751/7 | In else I use label1_embedding ! There should be self.label2_embedding. It’s probably user’s preference, but I would remove the keepdims=True ans .view_as, like in my code. :wink:
Ah ok, I understand.
You could just store them in a list.
preds = []
targets = []
for i in range(10):
output = F.log_softmax(Variable(... | 1,324 | {'text': ['In else I use label1_embedding ! There should be self.label2_embedding.'], 'answer_start': [1324]} |
Getting the proper prediction and comparing it to the true value | Hello,
I am making a neural network to make a binary classification and I would like to check the predictions made in the testing phase of my network, but I don’t seem to be getting the proper values.
What I want is not the loss over the whole batch but each prediction over every test sample to co… | 1 | 2018-04-16T09:07:40.267Z | It’s probably user’s preference, but I would remove the keepdims=True ans .view_as, like in my code. :wink:
Ah ok, I understand.
You could just store them in a list.
preds = []
targets = []
for i in range(10):
output = F.log_softmax(Variable(torch.randn(batch_size, n_classes)), dim=1)
tar… | 2 | 2018-04-16T09:32:30.260Z | https://discuss.pytorch.org/t/getting-the-proper-prediction-and-comparing-it-to-the-true-value/16468/4 | In else I use label1_embedding ! There should be self.label2_embedding. It’s probably user’s preference, but I would remove the keepdims=True ans .view_as, like in my code. :wink:
Ah ok, I understand.
You could just store them in a list.
preds = []
targets = []
for i in range(10):
output = F.log_softmax(Variable(... | 734 | {'text': ['It’s probably user’s preference, but I would remove the keepdims=True ans .view_as, like in my code. :wink:\n\nAh ok, I understand.\n\nYou could just store them in a list.\n\npreds = []\n\ntargets = []\n\nfor i in range(10):\n\noutput = F.log_softmax(Variable(torch.randn(batch_size, n_classes)), dim=1)\n\nta... |
I get a much better result with batch size 1 than when I use a higher batch size | I am doing regression on an image, I have a fully CNN (no fully connected layers) and Adam optimizer. For some reason unknown to me when I use batch size 1, my result is much better (In testing is almost 10 times better, in training more than 10 times) in training and testing as oposed to using high… | 0 | 2018-06-29T14:56:28.083Z | The batch size is independent from the data loading and is usually chosen as
what works well for your model and training procedure (too small or too large might degrade the final accuracy)
which GPUs you are using and what fits into your device memory. Generally you can increase the device utiliza… | 1 | 2020-06-08T09:11:10.383Z | https://discuss.pytorch.org/t/i-get-a-much-better-result-with-batch-size-1-than-when-i-use-a-higher-batch-size/20477/11 | In else I use label1_embedding ! There should be self.label2_embedding. It’s probably user’s preference, but I would remove the keepdims=True ans .view_as, like in my code. :wink:
Ah ok, I understand.
You could just store them in a list.
preds = []
targets = []
for i in range(10):
output = F.log_softmax(Variable(... | 377 | {'text': ['The batch size is independent from the data loading and is usually chosen as\n\nwhat works well for your model and training procedure (too small or too large might degrade the final accuracy)\n\nwhich GPUs you are using and what fits into your device memory. Generally you can increase the device utiliza&hell... |
How upload sequence of image on video-classification | Hi I’m new with Pytorch and I want to know how create class dataset that load a sequence of image take on a folder
I need to do this because then I will use LSTM to train my sequence of frame and classificate my video
Thanks to answer | 1 | 2018-09-11T01:42:05.506Z | Assuming your folder structure looks like this:
root/
- boxing/
-person0/
-image00.png
-image01.png
- ...
-person1
- image00.png
- image01.png
- ...
- jogging
-person0/
-image00.png
… | 11 | 2018-09-12T14:24:13.120Z | https://discuss.pytorch.org/t/how-upload-sequence-of-image-on-video-classification/24865/9 | Assuming your folder structure looks like this:
root/
- boxing/
-person0/
-image00.png
-image01.png
- ...
-person1
- image00.png
- image01.png
- ...
- jogging
-person0/
-image00.png
… You said you can’t obtain covariance matrix. In VAE paper, the author assume the true (but intractable) posterior ... | 1,370 | {'text': ['Assuming your folder structure looks like this:\n\nroot/\n\n- boxing/\n\n-person0/\n\n-image00.png\n\n-image01.png\n\n- ...\n\n-person1\n\n- image00.png\n\n- image01.png\n\n- ...\n\n- jogging\n\n-person0/\n\n-image00.png\n\n…'], 'answer_start': [1370]} |
KL-divergence between two multivariate gaussian | I have two multivariate Gaussian distributions that I would like to calculate the kl divergence between them. each is defined with a vector of mu and a vector of variance (similar to VAE mu and sigma layer). What is the best way to calculate the KL between the two? Is this even doable? because I … | 0 | 2019-08-09T19:11:29.033Z | You said you can’t obtain covariance matrix. In VAE paper, the author assume the true (but intractable) posterior takes on a approximate Gaussian form with an approximately diagonal covariance. So just place the std on diagonal of convariance matrix, and other elements of matrix are zeros. | 2 | 2019-08-16T07:07:17.512Z | https://discuss.pytorch.org/t/kl-divergence-between-two-multivariate-gaussian/53024/9 | Assuming your folder structure looks like this:
root/
- boxing/
-person0/
-image00.png
-image01.png
- ...
-person1
- image00.png
- image01.png
- ...
- jogging
-person0/
-image00.png
… You said you can’t obtain covariance matrix. In VAE paper, the author assume the true (but intractable) posterior ... | 890 | {'text': ['You said you can’t obtain covariance matrix. In VAE paper, the author assume the true (but intractable) posterior takes on a approximate Gaussian form with an approximately diagonal covariance. So just place the std on diagonal of convariance matrix, and other elements of matrix are zeros.'], 'answer_star... |
Example for One of the differentiated Tensors appears to not have been used in the graph | Can anyone please give an example of this scenario, I am struggling to understand why this could even happen | 0 | 2019-10-16T14:15:12.256Z | Hi,
Here is an example:
a = torch.rand(10, requires_grad=True)
b = torch.rand(10, requires_grad=True)
output = (2 * a).sum()
torch.autograd.grad(output, (a, b)) | 3 | 2019-10-16T15:28:16.997Z | https://discuss.pytorch.org/t/example-for-one-of-the-differentiated-tensors-appears-to-not-have-been-used-in-the-graph/58396/2 | Assuming your folder structure looks like this:
root/
- boxing/
-person0/
-image00.png
-image01.png
- ...
-person1
- image00.png
- image01.png
- ...
- jogging
-person0/
-image00.png
… You said you can’t obtain covariance matrix. In VAE paper, the author assume the true (but intractable) posterior ... | 499 | {'text': ['Hi,\n\nHere is an example:\n\na = torch.rand(10, requires_grad=True)\n\nb = torch.rand(10, requires_grad=True)\n\noutput = (2 * a).sum()\n\ntorch.autograd.grad(output, (a, b))'], 'answer_start': [499]} |
Call backward on function inside a backpropagation step | Hi everyone!
I’m trying to build a custom module layer which itself uses a custom function. Then, inside this function it would be nice, if I could use existing functions. As a simplified example I wrapped a Linear Layer inside my function and try to pass its weights as a parameter from the “surrou… | 1 | 2017-06-07T06:50:34.975Z | It seems this issue has been solved in more recent releases. Check out the Github issue opened by the OP: (<a href="https://github.com/pytorch/pytorch/issues/1776" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/1776 </a>) | 0 | 2019-03-01T20:24:00.108Z | https://discuss.pytorch.org/t/call-backward-on-function-inside-a-backpropagation-step/3793/13 | It seems this issue has been solved in more recent releases. Check out the Github issue opened by the OP: (<a href="https://github.com/pytorch/pytorch/issues/1776" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/1776 </a>) Another good way to know the input dimensions of the image is to use torchsumma... | 1,328 | {'text': ['It seems this issue has been solved in more recent releases. Check out the Github issue opened by the OP: (<a href="https://github.com/pytorch/pytorch/issues/1776" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/1776 </a>)'], 'answer_start': [1328]} |
Calculation for the input to the Fully Connected Layer | <a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/b/1/b17d29dac866154ccf5825481c991eefba8f864e.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/b17d29dac866154ccf5825481c991eefba8f864e" title="doubt">[doubt]</a>
Do we always need to calculate this 6444 manually usin... | 1 | 2020-05-25T06:10:09.225Z | Another good way to know the input dimensions of the image is to use torchsummary module for summary library.
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary
# define the CNN architecture
class Net(nn.Module):
def __init__(self):
super(Net, self).… | 1 | 2020-05-31T04:34:33.605Z | https://discuss.pytorch.org/t/calculation-for-the-input-to-the-fully-connected-layer/82774/16 | It seems this issue has been solved in more recent releases. Check out the Github issue opened by the OP: (<a href="https://github.com/pytorch/pytorch/issues/1776" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/1776 </a>) Another good way to know the input dimensions of the image is to use torchsumma... | 905 | {'text': ['Another good way to know the input dimensions of the image is to use torchsummary module for summary library.\n\nimport torch.nn as nn\n\nimport torch.nn.functional as F\n\nfrom torchsummary import summary\n\n# define the CNN architecture\n\nclass Net(nn.Module):\n\ndef __init__(self):\n\nsuper(Net, self).&h... |
Dynamic Dataloaders for on the fly modifications | Hello,
I am working on a project where we are trying to modify the data every n epochs. I have two questions related to this:
Can we use a single dataloader and dataset to do this?
ie every 5 epochs jitter the images in the trainset
Would it be better from a computational standpoint to perfo… | 3 | 2020-04-28T19:50:40.788Z | If your use case allows to manipulate the dataset after a full epoch, I would recommend to perform the manipulations directly on the data inside the Dataset and just recreate the DataLoader.
Instantiation of DataLoaders should be cheap, so you shouldn’t see any slow down.
Also, manipulating the da… | 1 | 2020-04-29T03:26:12.509Z | https://discuss.pytorch.org/t/dynamic-dataloaders-for-on-the-fly-modifications/78870/2 | It seems this issue has been solved in more recent releases. Check out the Github issue opened by the OP: (<a href="https://github.com/pytorch/pytorch/issues/1776" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/1776 </a>) Another good way to know the input dimensions of the image is to use torchsumma... | 543 | {'text': ['If your use case allows to manipulate the dataset after a full epoch, I would recommend to perform the manipulations directly on the data inside the Dataset and just recreate the DataLoader.\n\nInstantiation of DataLoaders should be cheap, so you shouldn’t see any slow down.\n\nAlso, manipulating the da&hell... |
Input data normalization | When is it best to use normalization:
# consist positive numbers
normalized_data = (data / data.max()) * 2 - 1
instead of standardization:
nomalized_data = (data - data.mean()) / sqrt(data.var()) | 1 | 2019-11-25T08:07:50.357Z | In standarization, technically, there is no limit as to what value can the extremes of output have. In case of normalization, however, the most extreme values will be equal to 1 and -1.
This will suppress the effect of outliers. Why?
For example lets consider a situation when in dataset feature A … | 0 | 2019-11-27T22:49:58.470Z | https://discuss.pytorch.org/t/input-data-normalization/62081/11 | In standarization, technically, there is no limit as to what value can the extremes of output have. In case of normalization, however, the most extreme values will be equal to 1 and -1.
This will suppress the effect of outliers. Why?
For example lets consider a situation when in dataset feature A … You could m... | 1,702 | {'text': ['In standarization, technically, there is no limit as to what value can the extremes of output have. In case of normalization, however, the most extreme values will be equal to 1 and -1.\n\nThis will suppress the effect of outliers. Why?\n\nFor example lets consider a situation when in dataset feature A &hell... |
How to get a part of datasets? | Sorry for my poor English.
This is my code:
trainset = datasets.MNIST(‘data’, train=True, download=False, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset,batch_size=32, shuffle=True)
Now I want to choose a part of train sets(like 3000 images and labels) from shuffled data… | 0 | 2020-05-20T10:45:19.368Z | You could manually shuffle the indices using:
indices = torch.randperm(len(train_dataset))[:3000]
and pass these indices to a RandomSubsetSampler, which can then be passed to the DataLoader. | 2 | 2020-05-21T08:54:22.958Z | https://discuss.pytorch.org/t/how-to-get-a-part-of-datasets/82161/2 | In standarization, technically, there is no limit as to what value can the extremes of output have. In case of normalization, however, the most extreme values will be equal to 1 and -1.
This will suppress the effect of outliers. Why?
For example lets consider a situation when in dataset feature A … You could m... | 1,160 | {'text': ['You could manually shuffle the indices using:\n\nindices = torch.randperm(len(train_dataset))[:3000]\n\nand pass these indices to a RandomSubsetSampler, which can then be passed to the DataLoader.'], 'answer_start': [1160]} |
Why does nn.Embedding layers expect LongTensor type input Tensors? | I’m a bit confused about the types that different layers are expecting.
I discovered that a nn.Embedding layer expects its input to be of type LongTensor aka torch.int64. Then it outputs a tensor of type torch.float64.
But then if I want to use a nn.LSTM layer next, I need to change the type since… | 1 | 2018-07-19T08:05:15.914Z | Hi,
The embedding layer takes as input the index of the element in the embedding you want to select and return the corresponding embedding. The input is expected to be a LongTensor because it is an index and so must be an integer. The output is a float type, you can call .float() or .double() on th… | 2 | 2018-07-19T08:32:51.562Z | https://discuss.pytorch.org/t/why-does-nn-embedding-layers-expect-longtensor-type-input-tensors/21376/2 | In standarization, technically, there is no limit as to what value can the extremes of output have. In case of normalization, however, the most extreme values will be equal to 1 and -1.
This will suppress the effect of outliers. Why?
For example lets consider a situation when in dataset feature A … You could m... | 502 | {'text': ['Hi,\n\nThe embedding layer takes as input the index of the element in the embedding you want to select and return the corresponding embedding. The input is expected to be a LongTensor because it is an index and so must be an integer. The output is a float type, you can call .float() or .double() on th&hellip... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.