id
stringlengths
3
8
text
stringlengths
1
115k
st99268
ok, thanks for that, but then what about the fact that I would like the user not to care about this but have this encapsulated within the module ? best
st99269
ok, I see, this wouldn’t help me since it would require any user of this custom module to only use my custom optimizer. I guess I’ll have to go with it and tell ppl to just run some code of mine after the step() (a feature like monitoring if some attribute from a module was changed to run some code in that case would be nice here for me) thanks
st99270
Hi, I don’t know if I’m doing something wrong but I checked the tutorial https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html#sphx-glr-intermediate-seq2seq-translation-tutorial-py 2 to keep me up to date with the version 1.0 of PyTorch and did the same to my code. I have remarked that during inference, Dropout still randomly puts zero because self.training=True even with torch.no_grad(). Is this expected ? If yes, how does the tutorial ? Before we were supposed to do something like model.eval(True) Here a sample code In [1]: import torch In [2]: a = torch.Tensor([1,2,3,4,5]) In [3]: d = torch.nn.Dropout() In [4]: d = torch.nn.Dropout(0.2) In [5]: d(a) Out[5]: tensor([0.0000, 0.0000, 0.0000, 0.0000, 6.2500]) In [6]: d(a) Out[6]: tensor([1.2500, 2.5000, 3.7500, 0.0000, 6.2500]) In [7]: d(a) Out[7]: tensor([1.2500, 0.0000, 3.7500, 5.0000, 6.2500]) In [8]: with torch.no_grad(): ...: d(a) ...: In [9]: with torch.no_grad(): ...: print(d(a)) ...: ...: tensor([1.2500, 2.5000, 3.7500, 5.0000, 6.2500]) In [10]: with torch.no_grad(): ...: print(d(a)) ...: ...: tensor([1.2500, 2.5000, 3.7500, 0.0000, 6.2500]) In [11]: with torch.no_grad(): ...: print(d(a)) ...: ...: tensor([1.2500, 2.5000, 3.7500, 5.0000, 0.0000]) In [12]: with torch.no_grad(): ...: print(d(a)) ...: ...: tensor([1.2500, 2.5000, 3.7500, 5.0000, 6.2500]) In [13]: with torch.no_grad(): ...: print(d(a)) ...: ...: tensor([1.2500, 2.5000, 3.7500, 0.0000, 6.2500]) In [14]: with torch.no_grad(): ...: print(d(a)) ...: ...: tensor([1.2500, 2.5000, 3.7500, 5.0000, 0.0000]) In [15]: with torch.no_grad(): ...: print(d(a)) ...: print(d.training) ...: ...: tensor([1.2500, 2.5000, 0.0000, 5.0000, 6.2500]) True In [16]: with torch.no_grad(): ...: print(d(a)) ...: print(d.training) ...: ...: tensor([1.2500, 0.0000, 0.0000, 5.0000, 6.2500]) True In [17]: print(d.training) True
st99271
Yeah this is expected, precisely due to that d.training is still True. And yes you should call model.eval() before testing. Could you tell me where in that tutorial suggests otherwise? I took a quick glance but didn’t see anything obvious.
st99272
Thank you for your quick answer ! I’m also checking the following thread ‘model.eval()’ vs ‘with torch.no_grad()’ 3 where they say that the recommended way should be torch.no_grad() (and should be faster). At the end, It’s not very clear. What should we do ? I didn’t read the tutorial but in the code, you can see at line 451 self.dropout = nn.Dropout(self.dropout_p) and at line 699 with torch.no_grad(): and not an encoder.eval() or decoder.eval(). I could also find similarities with other tutorials.
st99273
I have long faced this problem, but never investigated it until now. It seems that there are processes with sequential IDs spawned which persist. They don’t show up in nvidia-smi, and neither in top, but if I do a fuser /dev/nvidia* processes with sequential IDs show up. The number of processes is equal to num_workers in the PyTorch data loader. It becomes a big problem because every once in a while, these processes end up in an S state, that is ‘interruptible sleep’, or ‘uninterruptible sleep’, at which point we have to reboot our system. Which is a BIG problem for research clusters. Any leads?
st99274
https://github.com/pytorch/pytorch/pull/11985 28 should fix this. However, you can always kill -9 those without needing to reboot.
st99275
The patch is merged! If you download the nighly later today, it should have the patch.
st99276
kill -9 doesn’t kill if they’ve gone into the interrupted sleep state. It can only kill processes if they’re not in S,D,Z states (look up linux process states). I’ll update though and see if it happens again!
st99277
You are absolutely right. Although I am curious, why are your dataloader workers using CUDA>
st99278
While in training procedure, I want to get and set the parameters of BN layer. The following code works on single GPU, but failed with multi. How could I fixe the code? def get_adabn_params(model): new_dict = OrderedDict() for name, value in model.state_dict().items(): if 'running_mean' in name or 'running_var' in name: new_dict[name] = value return new_dict def reset_adabn_params(model): new_dict = OrderedDict() for name, value in model.state_dict().items(): if 'running_mean' in name: new_dict[name] = 0 if 'running_var' in name: new_dict[name] = 1 for key,value in new_dict.items(): model.state_dict()[key].copy_(torch.from_numpy(np.array(value)))
st99279
Most of Pyro’s models and unit tests, e.g. in test_jit.py 1 are now working with the PyTorch JIT tracer. However, when we run these tests with the default tensor type set to torch.cuda.DoubleTensor, the tests fail with a cryptic error message, pasted below. Note that these errors are only triggered on CUDA with JIT enabled (they run fine as CUDA tests or on the CPU with JIT). File "/home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/nn/modules/module.py", line 477, in __call__ result = self.forward(*input, **kwargs) File "/home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/jit/__init__.py", line 1172, in forward return self._get_method('forward')(*args, **kwargs) RuntimeError: TensorIterator expected type CPUDoubleType but got CUDADoubleType[2] (check_type_conversions at /home/npradhan/workspace/pyro_dev/pytorch/aten/src/ATen/native/TensorIterator.cpp:426) frame #0: at::TensorIterator::Builder::build() + 0x21b (0x7fd85785f87b in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libcaffe2.so) frame #1: at::TensorIterator::binary_op(at::Tensor&, at::Tensor const&, at::Tensor const&) + 0x80 (0x7fd85785e73a in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libcaffe2.so) frame #2: at::native::mul_out(at::Tensor&, at::Tensor const&, at::Tensor const&) + 0x114 (0x7fd857762b71 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libcaffe2.so) frame #3: at::native::mul(at::Tensor const&, at::Tensor const&) + 0x47 (0x7fd857762c3e in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libcaffe2.so) frame #4: at::TypeDefault::mul(at::Tensor const&, at::Tensor const&) const + 0x52 (0x7fd857a9baf8 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libcaffe2.so) frame #5: torch::autograd::VariableType::mul(at::Tensor const&, at::Tensor const&) const + 0x3e2 (0x7fd84443749e in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #6: <unknown function> + 0xcd94d0 (0x7fd8445e54d0 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #7: <unknown function> + 0xd17fdc (0x7fd844623fdc in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #8: <unknown function> + 0xd7edd7 (0x7fd84468add7 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #9: std::function<int (std::vector<torch::jit::IValue, std::allocator<torch::jit::IValue> >&)>::operator()(std::vector<torch::jit::IValue, std::allocator<torch::jit::IValue> >&) const + 0x49 (0x7fd85b7ff415 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so) frame #10: <unknown function> + 0xe88ee5 (0x7fd844794ee5 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #11: <unknown function> + 0xe88fb6 (0x7fd844794fb6 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #12: torch::jit::ConstantPropagation(torch::jit::Node*, bool) + 0x163 (0x7fd844795b3d in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #13: torch::jit::ConstantPropagation(torch::jit::Block*, bool) + 0xd2 (0x7fd844795c48 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #14: torch::jit::ConstantPropagation(std::shared_ptr<torch::jit::Graph>&) + 0x2d (0x7fd844795c91 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #15: <unknown function> + 0xdff336 (0x7fd84470b336 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #16: <unknown function> + 0xdff1c3 (0x7fd84470b1c3 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #17: <unknown function> + 0xe06272 (0x7fd844712272 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #18: torch::jit::GraphExecutor::run(std::vector<torch::jit::IValue, std::allocator<torch::jit::IValue> >&) + 0x2e (0x7fd84470b7b2 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/lib/libtorch.so.1) frame #19: torch::jit::script::Method::run(std::vector<torch::jit::IValue, std::allocator<torch::jit::IValue> >&) + 0xf6 (0x7fd85b8e4744 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so) frame #20: <unknown function> + 0xd146ba (0x7fd85b8e66ba in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so) frame #21: <unknown function> + 0xd44bab (0x7fd85b916bab in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so) frame #22: <unknown function> + 0xd3c8f0 (0x7fd85b90e8f0 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so) frame #23: <unknown function> + 0xd35f52 (0x7fd85b907f52 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so) frame #24: <unknown function> + 0xd360e5 (0x7fd85b9080e5 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so) frame #25: <unknown function> + 0x92d0d6 (0x7fd85b4ff0d6 in /home/npradhan/miniconda3/envs/pytorch-master/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so) <omitting python frames> I have found it very hard to debug this, and reduce it to a more minimal example, but given that so many of our models (e.g. the VAE), and tests are failing when JIT traced using CUDA tensors, I think there is something more fundamental on our end that is breaking the JIT tracer, or it might point to a bug somewhere in torch/aten. Any help / tips in debugging this is appreciated. Is it possible to look at the trace graph to see why/where the JIT expects a CPU tensor in the first place?
st99280
Is there any known issues related to cuda version 10.0 with respect to cuda-cpp-extension for pytorch? I am noticing a strange behavior in an own cpp-cuda extension that in cuda version 10.0, the kernel code is unable to modify the output variable’s values. (i.e., all the values are 0), but the same code works with cuda 9.0. To reproduce this behavior, I did the following: I took the standard cpp-cuda-extension (LLTM) of pytorch tutorial and added a print statement at line 60 of benchmark.py 2 as below: print(new_h.sum() + new_C.sum()) Then I compiled the cuda extension in two configurations and tested it. Configuration-1: gcc 6.4.0 + cuda 10.0 + pytorch 1.0.0.dev20181008 output printed: tensor(0., device='cuda:0', grad_fn=<AddBackward0>) Configuration-2: gcc 4.9.0 + cuda 9.0 + pytorch 1.0.0.dev20181008 output printed: tensor(57.2220, device='cuda:0', grad_fn=<AddBackward0>) This shows that there is some issue with either the cuda version or gcc. I am unable to point out which one it is. Can anyone confirm this behavior if you have cuda-10.0 and cuda-9.0? Thanks!
st99281
Itseems pytorch is not supported yet for cuda 10.0. My bad! reddit r/pytorch - How do I install pytorch with cuda 10? 88 1 vote and 7 comments so far on Reddit
st99282
I’m trying to train a network. I have set the device to “cuda”, and I run net.to(device) However, when I run inputs = data["input"].float().to(device) outputs = net(inputs) I get an error at the outputs assignment. “RuntimeError: Expected object of type torch.FloatTensor but found type torch.cuda.FloatTensor for argument #4 ‘mat1’” Puzzlingly enough, with inputs = data["input"].float() outputs = net(inputs) I get, erring on the same last line of code, the “opposite error”: “RuntimeError: Expected object of type torch.cuda.FloatTensor but found type torch.FloatTensor for argument #4 ‘mat1’” However, if I remove all “to(device)” then the code runs fine. What might be going on here? Thank you.
st99283
Which version of pytorch are you using? It will be great if you could give a short reproducible script. This works for me. Does it work for you? import torch device = 'cuda' x = torch.rand(5,5) y = x.to(device) import torch.nn as nn net = nn.Linear(5,5) net.to(device) out = net(y)
st99284
Thank you. I’m using version 0.4.1. Your example did work for me. I’ll try to create a minimal reproducible script as soon as I can. However, I also wonder in generally what dictates the kind of input that a custom defined net is expecting. In your case, while you saved a layer in a variable called “net”, it’s not of the Module class, which I suspect might be relevant. Is sending a net “to(device)” which is cuda an if and only if condition for it to expect cuda input?
st99285
Just for the sake of archival conclusion I’ll say that I went back to the same code, and I managed to run it with Cuda. Apparently I just didn’t append".to(device)" to all necessary variables. I’d say the error messages were not so informative, but I think that’s a known issue already (I remember reading people mentioning it, probably on this here forum). Perhaps it was solved on the 1.0 version which I had not the pleasure yet to try. Thank you for the help!
st99286
@Konotori About Arul’s answer, layer is actually a subclass of Module, so it is relevant. May I ask what variable you missed to append .to(device) to? It seems you already get the input and model on cuda.
st99287
Yes, I noticed that what he defined as a net was really only a layer. As for your question, the extra .to(device) I added was to the labels.
st99288
If you’ve two models net1 and net2 sitting on different GPUs and two optimizers optim1 and optim2 taking care of net1 and net2 respectively - how would you execute optim1.step() and optim2.step() in parallel? any help/pointers to tutorials to do this are appreciated! thanks!
st99289
Hi, I did as follow: Install 0.4.1 then torchvision then torch_nightly I open a python console import torch.distributed.c10d get_rank() => NameError: name ‘get_rank’ is not defined What am I missing ?
st99290
my code is mobilenet code on github I found:https://github.com/marvis/pytorch-mobilenet/blob/master/main.py 5
st99291
I have met the same problem when I use multi-gpus to inference and train with torch.nn.DataParallel. You can use this code to reproduce the problem. GitHub pytorch/examples 4 A set of examples around pytorch in Vision, Text, Reinforcement Learning, etc. - pytorch/examples
st99292
Finally I solve the problem when inference by multiprocessing module, but i don’t know how to change my code in train mode. If someone know something about this, If anyone knows about it , please tell me
st99293
Hi. I have wrote a detection algorithm. Does any one know how to calculate the mAP criterion? Is there any module in python to calculate the mAP? Thanks.
st99294
see https://github.com/pytorch/tnt/pull/21 2.6k they have recently merged mAP meter. You cannot make mAP a criterion (i.e. differentiable) as it’s not a differentiable cost.
st99295
Oh Sorry I did not want to mean mAP as a Criterion (differentiable Layer). I just wanted to find an exact implementation of that as metric. On the other hand, I want to say that we can find an exact implementation of mAP specifically for each dataset. Since I benefited from MSCOCO Detection Dataset, the author of MSCOCO present a good module in python to measure this metric. By the way thanks for your response!
st99296
@mderakhshani Check this one: GitHub rafaelpadilla/Object-Detection-Metrics 1.3k Most popular metrics used to evaluate object detection algorithms - rafaelpadilla/Object-Detection-Metrics Very useful
st99297
I am facing some compilation errors when I compile the given cuda-extension tutorial code from here: GitHub pytorch/extension-cpp 4 C++ extensions in PyTorch. Contribute to pytorch/extension-cpp development by creating an account on GitHub. CUDA version : 9.0 gcc version : 6.4.0 Pytorch version : 1.0.0.dev20181008 / 0.5.0a0+ab6afc2 Compilation log: gist.github.com https://gist.github.com/InnovArul/db9ac86f8c5f7bc97fea348d3542a105 12 cuda-extension-pytorch1.0-compile.sh running install running bdist_egg running egg_info creating lltm_cuda.egg-info writing lltm_cuda.egg-info/PKG-INFO writing dependency_links to lltm_cuda.egg-info/dependency_links.txt writing top-level names to lltm_cuda.egg-info/top_level.txt writing manifest file 'lltm_cuda.egg-info/SOURCES.txt' reading manifest file 'lltm_cuda.egg-info/SOURCES.txt' writing manifest file 'lltm_cuda.egg-info/SOURCES.txt' This file has been truncated. show original The notable errors are: /usr/local/cuda-9.0/bin/nvcc -I/home/arul/anaconda3/envs/pytorch-nightly/lib/python3.6/site-packages/torch/lib/include -I/home/arul/anaconda3/envs/pytorch-nightly/lib/python3.6/site-packages/torch/lib/include/torch/csrc/api/include -I/home/arul/anaconda3/envs/pytorch-nightly/lib/python3.6/site-packages/torch/lib/include/TH -I/home/arul/anaconda3/envs/pytorch-nightly/lib/python3.6/site-packages/torch/lib/include/THC -I/usr/local/cuda-9.0/include -I/home/arul/cuda/include -I/home/arul/anaconda3/envs/pytorch-nightly/include/python3.6m -c lltm_cuda_kernel.cu -o build/temp.linux-x86_64-3.6/lltm_cuda_kernel.o -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --compiler-options '-fPIC' -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=lltm_cuda -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++11 /usr/include/c++/6/tuple: In instantiation of ‘static constexpr bool std::_TC<<anonymous>, _Elements>::_MoveConstructibleTuple() [with _UElements = {std::tuple<at::Tensor, at::Tensor, at::Tensor>}; bool <anonymous> = true; _Elements = {at::Tensor, at::Tensor, at::Tensor}]’: /usr/include/c++/6/tuple:626:248: required by substitution of ‘template<class ... _UElements, typename std::enable_if<(((std::_TC<(sizeof... (_UElements) == 1), at::Tensor, at::Tensor, at::Tensor>::_NotSameTuple<_UElements ...>() && std::_TC<(1ul == sizeof... (_UElements)), at::Tensor, at::Tensor, at::Tensor>::_MoveConstructibleTuple<_UElements ...>()) && std::_TC<(1ul == sizeof... (_UElements)), at::Tensor, at::Tensor, at::Tensor>::_ImplicitlyMoveConvertibleTuple<_UElements ...>()) && (3ul >= 1)), bool>::type <anonymous> > constexpr std::tuple< <template-parameter-1-1> >::tuple(_UElements&& ...) [with _UElements = {std::tuple<at::Tensor, at::Tensor, at::Tensor>}; typename std::enable_if<(((std::_TC<(sizeof... (_UElements) == 1), at::Tensor, at::Tensor, at::Tensor>::_NotSameTuple<_UElements ...>() && std::_TC<(1ul == sizeof... (_UElements)), at::Tensor, at::Tensor, at::Tensor>::_MoveConstructibleTuple<_UElements ...>()) && std::_TC<(1ul == sizeof... (_UElements)), at::Tensor, at::Tensor, at::Tensor>::_ImplicitlyMoveConvertibleTuple<_UElements ...>()) && (3ul >= 1)), bool>::type <anonymous> = <missing>]’ /home/arul/anaconda3/envs/pytorch-nightly/lib/python3.6/site-packages/torch/lib/include/ATen/core/TensorMethods.h:456:36: required from here /usr/include/c++/6/tuple:483:67: error: mismatched argument pack lengths while expanding ‘std::is_constructible<_Elements, _UElements&&>’ return __and_<is_constructible<_Elements, _UElements&&>...>::value; ^~~~~ /usr/include/c++/6/tuple:484:1: error: body of constexpr function ‘static constexpr bool std::_TC<<anonymous>, _Elements>::_MoveConstructibleTuple() [with _UElements = {std::tuple<at::Tensor, at::Tensor, at::Tensor>}; bool <anonymous> = true; _Elements = {at::Tensor, at::Tensor, at::Tensor}]’ not a return-statement } /usr/include/c++/6/tuple: In instantiation of ‘static constexpr bool std::_TC<<anonymous>, _Elements>::_NonNestedTuple() [with _SrcTuple = const std::tuple<at::Tensor, at::Tensor, at::Tensor>&; bool <anonymous> = true; _Elements = {at::Tensor, at::Tensor, at::Tensor}]’: /usr/include/c++/6/tuple:662:419: required by substitution of ‘template<class ... _UElements, class _Dummy, typename std::enable_if<((std::_TC<(1ul == sizeof... (_UElements)), at::Tensor, at::Tensor, at::Tensor>::_ConstructibleTuple<_UElements ...>() && std::_TC<(1ul == sizeof... (_UElements)), at::Tensor, at::Tensor, at::Tensor>::_ImplicitlyConvertibleTuple<_UElements ...>()) && std::_TC<(std::is_same<_Dummy, void>::value && (1ul == 1)), at::Tensor, at::Tensor, at::Tensor>::_NonNestedTuple<const tuple<_Elements ...>&>()), bool>::type <anonymous> > constexpr std::tuple< <template-parameter-1-1> >::tuple(const std::tuple<_Args1 ...>&) [with _UElements = {at::Tensor, at::Tensor, at::Tensor}; _Dummy = void; typename std::enable_if<((std::_TC<(1ul == sizeof... (_UElements)), at::Tensor, at::Tensor, at::Tensor>::_ConstructibleTuple<_UElements ...>() && std::_TC<(1ul == sizeof... (_UElements)), at::Tensor, at::Tensor, at::Tensor>::_ImplicitlyConvertibleTuple<_UElements ...>()) && std::_TC<(std::is_same<_Dummy, void>::value && (1ul == 1)), at::Tensor, at::Tensor, at::Tensor>::_NonNestedTuple<const tuple<_Elements ...>&>()), bool>::type <anonymous> = <missing>]’ /home/arul/anaconda3/envs/pytorch-nightly/lib/python3.6/site-packages/torch/lib/include/ATen/core/TensorMethods.h:456:36: required from here /usr/include/c++/6/tuple:495:244: error: wrong number of template arguments (4, should be 2) return __and_<__not_<is_same<tuple<_Elements...>, ^ /usr/include/c++/6/type_traits:1558:8: note: provided for ‘template<class _From, class _To> struct std::is_convertible’ struct is_convertible ^~~~~~~~~~~~~~ /usr/include/c++/6/tuple:502:1: error: body of constexpr function ‘static constexpr bool std::_TC<<anonymous>, _Elements>::_NonNestedTuple() [with _SrcTuple = const std::tuple<at::Tensor, at::Tensor, at::Tensor>&; bool <anonymous> = true; _Elements = {at::Tensor, at::Tensor, at::Tensor}]’ not a return-statement } ^ The code is taken from the given pytorch cpp extension github repo as it is. I had to make a change to replace fmax() to fmaxf() (in this line 11) for the code to compile though.
st99298
Solved by InnovArul in post #2 Itseems the gcc version 6.4.0 is incompatible with cuda version 9.0. After updating to cuda version 10.0, I am able to compile. Reference: https://devtalk.nvidia.com/default/topic/1028112/cuda-setup-and-installation/nvcc-bug-related-to-gcc-6-lt-tuple-gt-header-/
st99299
Itseems the gcc version 6.4.0 is incompatible with cuda version 9.0. After updating to cuda version 10.0, I am able to compile. Reference: https://devtalk.nvidia.com/default/topic/1028112/cuda-setup-and-installation/nvcc-bug-related-to-gcc-6-lt-tuple-gt-header-/ 268
st99300
Hi everyone, I know that in order to load weights for CPU model which was saved during training by 1 GPU, we can use 2 lines below: net = Model() # My own architecture I define model_path = "path/to/model.pkl" state_dict = torch.load(model_path, map_location={"cuda:0" : "cpu"} net.load_state_dict(state_dict) However, when I train model on 2 GPUs using DataParallel to wrap my net model, then saving with net = Model() net = torch.nn.DataParallel(net) net.cuda() # Training training() # Saving model_path = "path/to/model.pkl" torch.save(net.state_dict(), model_path" I load it back for later use like below: net = Model() net.load_state(torch.load(model_path, map_location={"cuda" : "cpu"}) It doesn’t map correctly the weights and keys in the state_dict. So what is the solution for it? Should I change the value for map_location to different one? Thank you.
st99301
For later use, if I define the model in in DataParallel and move it to 2 GPUs, there is no problem: net = Model() net = DataParallel(net) net.cuda() model = "path/to/model.pkl" state_dict = torch.load(model_path) net.load_state_dict(state_dict) It works well in this case even I don’t need to pass a value for map_location. But my concern is how to load weights on CPU-only machine, or 1-GPU only machine. I have a temporary solution which I don’t think, is the best one. class WrappedModel(nn.Module): def __init__(self): super(WrappedModel, self).__init__() self.module = Model() # that I actually define. def forward(self, x): return self.module(x) # then I load the weights I save from previous code: net = WrappedModel() net.load_state_dict(torch.load(model_path, map_location={"cuda" : "cpu"}) The keys in state_dict map perfectly and works but it is kind of lengthy
st99302
I change the code, and it works, thankyou. class WrappedModel(nn.Module): def __init__(self, module): super(WrappedModel, self).__init__() self.module = module # that I actually define. def forward(self, x): return self.module(x) model = getattr(models, args.model)(args) model = WrappedModel(model) state_dict = torch.load(modelname)['state_dict'] model.load_state_dict(state_dict)
st99303
Referring to https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/core/Tensor.h 7, I could not find an API equivalent to tensor.nelement() to get total number of elements in the tensor regardless of its dimension. Does anyone know about it?
st99304
Solved by colesbury in post #2 The equivalent function is Tensor::numel()
st99305
is there a documentation or list of APIs that I could refer to? Maybe I missed to look into it.
st99306
Great. I think I overlooked the same page. The page I was looking for, is this : https://pytorch.org/cppdocs/genindex.html 24
st99307
Observed the following error while executing the example at - https://pytorch.org/docs/master/onnx.html 4 RuntimeError: [enforce fail at reshape_op.h:110] total_size == size. 92160 vs -1613423362598410240. Argument `shape` does not agree with the input data. (92160 != -1613423362598410240)Error from operator: input: "29" input: "36" output: "37" output: "OC2_DUMMY_1" name: "" type: "Reshape" device_option { device_type: 1 cuda_gpu_id: 0 } [F context_gpu.h:118] Check failed: error == cudaSuccess driver shutting down.
st99308
Hi, If I need to modify the scheme of my optimizer in an irregular way, how could I do it ? For example, I have an adam optimizer, and I need it to keep working with its default parameters before the 1000th iteration, then I need to change beta1 to 0.3 and in the following training process, I need its learning rate to decay with the ratio of 0.9999. How could I do it with pytorch ?
st99309
You can custom a function to change the parameters of optimizer as the training goes. def adjust_optim(optimizer, n_iter): if n_iter == 1000: optimizer.param_groups[0]['betas'] = (0.3, optimizer.param_groups[0]['betas'][1]) if n_iter > 1000: optimizer.param_groups[0]['lr'] *= 0.9999 If you are using multiple params groups, change 0 to i for ith group. Best,
st99310
Many thanks, BTW, how could I tell I am using param_groups or defaults. It appears that I can print out both optim.defaults and optim.paarm_groups, they are both exist in my optimizer.
st99311
It depends how you construct the optimizer. If you do optimizer = optim.SGD(model.parameters(), lr = 0.01, momentum=0.9) that means you only have one param group. If you do optim.SGD([ {'params': model.base.parameters()}, {'params': model.classifier.parameters(), 'lr': 1e-3} ], lr=1e-2, momentum=0.9) that means you have two param groups. Sorry, I edited the first post. It seems that changing .defaults won’t change the optimizer setup for param group 0 (when there is only one group). Sorry, I should have searched enough before answering the question.
st99312
Check out the function exp_lr_scheduler in my fine tuning tutorial linked below. That lets you decay the LR. I just multiply it by a constant but you can do anything fancy you want using the same code structure. github.com Spandan-Madan/Pytorch_fine_tuning_Tutorial/blob/master/main_fine_tuning.py 299 ### Section 1 - First, let's import everything we will be needing. from __future__ import print_function, division import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import numpy as np import torchvision from torchvision import datasets, models, transforms import matplotlib.pyplot as plt import time import copy import os from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True from fine_tuning_config_file import * ## If you want to keep a track of your network on tensorboard, set USE_TENSORBOARD TO 1 in config file. This file has been truncated. show original
st99313
Thanks for your helpful tutorial!! However, I have a question that may not be so relevant to this. I noticed that caffe allows to set different learning rates for weight and bias tensor of a conv layer(usually lr for weight and 2*lr for bias). Could I do this with pytorch without too much tedious work to construct the param_groups for the optimizer ?
st99314
I’m looking at a seq2seq model as described in this sample project: https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/seq2seq-translation.ipynb 31 To train this network, two SGD optimizers are being initialized (one for decode, one for encode). In the train function (c.f. prompt 16), the loss function is calculated at the bottom of the full stack (i.e. after encode + decode) and then the optimizer is being steped for both. Is this simply because there’s no way to initialize an optimizer with a union of different modules, or is there something more going on here that I’m not aware of? Namely: if the encoder and decoder networks were in a ModuleList() property (i.e. both were inside a single model object), would it be sufficient/equivalent to have a single optimizer? Thanks.
st99315
I did that to make it clear what is happening in the model (two separate networks being optimized) - it also makes it easy to use different optimizers per network. No technical reason though.
st99316
I am applying seq2seq models to generate conversation responses, and I am noticing that the NLL criterion is lesser when optimizers are separate for encoder and decoder. Would you suggest any ways to debug this scenario?
st99317
I am trying to convert PyTorch model to Onnx model. I keep ending up with the following error: Traceback (most recent call last): File "/tmp/pycharm_project_896/utils/pytorch2onnx.py", line 15, in <module> for k, v in state_dict.items(): File "/usr/local/lib/python2.7/dist-packages/torch/nn/modules/module.py", line 398, in __getattr__ type(self).__name__, name)) AttributeError: 'DataParallel' object has no attribute 'items' I have been using the following code: import torch from torch.autograd import Variable # Load the trained model from file path = "model.pth" #pytorch_network = torch.load(path) state_dict = torch.load("model.pth") #pytorch_network.state_dict() # Create new OrderedDict that does not contain the module from collections import OrderedDict new_state_dict = OrderedDict() for k, v in state_dict.items(): name = k[7:] # remove module new_state_dict[name] = v pytorch_network.load_state_dict(new_state_dict) # Export the trained model to ONNX #pytorch_network = torch.nn.DataParallel(pytorch_network, device_ids=range(torch.cuda.device_count())) dummy_input = Variable(torch.randn(1, 3, 224, 224)) torch.onnx.export(pytorch_network, dummy_input, "model.onnx") Can anyone tell me where I might be going wrong. I keep ended up with the same error. I have referred this Issue 3 too but I don’t seem to end with a solution. Thanks
st99318
I guess it is similar with the problem you posted before 68. The .pth file saves the entire model rather than the weights. Your state_dict is actually not an OrderedDict but a DataParallel object. That is why you get the error.
st99319
Hello, I would like to get a gradient of certain module, so I did some experiment, and I found something that I cannot understand. I made a model that has only one layer and one weight, and then put a single number into a layer then I tried to get a gradient of this number. so I coded like following class fcl(nn.Module): def __init__(self): super(fcl, self).__init__() self.model = nn.Sequential( nn.Linear(1, 1) ) self.model.register_backward_hook(self.hookfunc) def forward(self, x): out = self.model(x) return out def hookfunc(self, module, gradInput, gradoutput): for i in gradInput: print('gradInput :', i) for i in gradoutput: print('gradoutput :', i) cpu_dtype = tc.FloatTensor gpu_dtype = tc.cuda.FloatTensor model_test = fcl() loss_fn = nn.MSELoss() optimizer = tc.optim.Adam(model_test.parameters(), lr=0.00001) a = tc.Tensor([5]) b = tc.Tensor([2, 3]) print(a) out = model_test(a) print('out :', out) print('\nweight :\n', model_test.model[0].weight) print('\nbias :\n', model_test.model[0].bias) optimizer.zero_grad() out.backward() and the result is this tensor([5.]) out : tensor([-5.0639], grad_fn=<ThAddBackward>) weight : Parameter containing: tensor([[-0.9929]], requires_grad=True) bias : Parameter containing: tensor([-0.0993], requires_grad=True) gradInput : tensor([1.]) gradInput : tensor([1.]) gradoutput : tensor([1.]) But why the gradInput and the gradoutput are 1? I expected the gradInput would be same as weight which is -0.9929. and I can’t understand why gradInput has 2 elements unlike gradoutput.
st99320
Solved by albanD in post #2 Hi, The backward hooks for nn.Modules are not working properly at the moment (should be fixed soon). The gradients that you see here are not the ones you expect. To check gradients, I would add hooks inside the forward function like: def get_hook_fn(name) def hook(grad): print("grad …
st99321
Hi, The backward hooks for nn.Modules are not working properly at the moment (should be fixed soon). The gradients that you see here are not the ones you expect. To check gradients, I would add hooks inside the forward function like: def get_hook_fn(name) def hook(grad): print("grad for {}".format(name)) print(grad) return hook class fcl(nn.Module): def forward(self, x): x.register_hook(get_hook_fn("x")) out = self.model(x) out.register_hook(get_hook_fn("out")) return out For your forward value, don’t forget that a Linear layer has bias
st99322
I would like to know if there is a dependency between gcc-version and cpp-extension compilation. I have tried compiling the standard cpp-extension (LLTM from here 1) example under two gcc version (5.2.0, 6.1.0 with conda), both of them are unable to compile the extension. The details are given below: Ubuntu : 14.04 Python version: 3.6.5 Pytorch installation: conda install pytorch-nightly -c pytorch (version 1.0.0.dev20181008) gcc installation: conda install -c omgarcia gcc-6 or conda install -c cqwz gcc-5 Error in gcc 5.2.0: g++: error: -fuse-linker-plugin is not supported in this configuration Error in gcc 6.1.0: creating build/lib.linux-x86_64-3.6 g++ -pthread -shared -L/home/arul/anaconda3/envs/pytorch-nightly/lib -Wl,-rpath=/home/arul/anaconda3/envs/pytorch-nightly/lib,--no-as-needed -L/home/arul/anaconda3/envs/pytorch-nightly/lib -Wl,-rpath=/home/arul/anaconda3/envs/pytorch-nightly/lib,--no-as-needed build/temp.linux-x86_64-3.6/lltm.o -L/home/arul/anaconda3/envs/pytorch-nightly/lib -lpython3.6m -o build/lib.linux-x86_64-3.6/lltm_cpp.cpython-36m-x86_64-linux-gnu.so /usr/bin/ld: /home/arul/anaconda3/envs/pytorch-nightly/bin/../lib/gcc/x86_64-pc-linux-gnu/6.1.0/crtbeginS.o: unrecognized relocation (0x2a) in section `.text' /usr/bin/ld: final link failed: Bad value collect2: error: ld returned 1 exit status error: command 'g++' failed with exit status 1
st99323
It seems the gcc installed using conda is not compatible with the other libraries native in the OS (Ubuntu). After updating the system gcc to 6.4.0 (by following this 82), the compilation works.
st99324
Sparse dropout could be implemented efficiently in TensorFlow by tf.sparse_retain. But it seems that in PyTorch, such kind of sparse retain function does not exist. How could we implement a sparse dropout?
st99325
Hi, did you figure out how to do it? I am also trying to implement sparse dropout in pytorch.
st99326
I’m playing around with the LSTM architecture and I added another set of weights, the same dimension as the original set. def LSTMCell(input, hidden, w_ih, w_ih2, w_hh, w_hh2, b_ih=None, b_hh=None): hx, cx = hidden w_ih = torch.mul(w_ih2, w_ih) w_hh = torch.mul(w_hh2, w_hh) I get a RuntimeError: cuda runtime error (2) : out of memory at c:\programdata\miniconda3\conda-bld\pytorch_1524543037166\work\aten\src\thc\generic/THCStorage.cu:58 at line: w_hh = (w_hh2 * w_hh) Anybody have any idea why this is happening? Does element wise multiplication of Tensors (correction: Matrices) create an unnecessary gradient build up? (I need to use element wise multiplication to keep the original Tensor (correction: Matrix) size) Any help would be appreciated. Thanks!!
st99327
I’d recommend you printing the sizes of the tensors that you are multiplying. There might be some broadcasting happening under the hood (for example, a 10000 tensor multiplied by a 10000 x 1 tensor, which would generate a 10000 x 10000 tensor as result)
st99328
Forgive me, but I don’t understand what broadcasting means in this context. The sizes are [4600 , 400] for both matrices (I think I may have made a mistake by calling them Tensors), and the output is the same size. (Worth noting, is that the network runs for a couple seconds before giving the memory error.)
st99329
Hello together, I’am trying around with the newly released c++ api of pytorch. It sounds pretty promising and I think it’s definitely going in the right direction. However as you can imagine I encountered some problems I couldn’t solve so far. First things first: I used pytorch (python) to train an MNIST model. Nothing special here 2xconv2d + dropout + 2xlinear. I used the concept of Torch Script to save my model and to be able to load it later in c++. use_cuda = torch.cuda.is_available() mnist_testset = datasets.MNIST(root='./data', train=False, download=True, transform=None) train_image, train_target= mnist_testset[24] print (type(train_image)) train_image.show() device = torch.device("cuda" if use_cuda else "cpu") model = torch.load("model.pth").to(device) loader = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ]) tensor_image = loader(train_image).unsqueeze(0).to(device) output = model(tensor_image) pred = output.max(1, keepdim=True)[1] pred = torch.squeeze(pred) print("Success - Train target: " + str(train_target.cpu().numpy()) + " Prediction: " + str(pred.cpu().numpy())) # TRACING THE MODEL traced_net = torch.jit.trace(model,tensor_image) traced_net.save("model_trace.pt") where model is my pytorch model and tensor_image is an example input which is necessary for tracing. The result of this is a model_trace.pt file that can be loaded from c++. Alright so far so good! Next thing I wanted to do is to run the model in C++ so I can do the forward of a sample MNIST image in C++. Most importantly include torch! #include <torch/script.h> // One-stop header. Now I was able to load the model in c++ using: std::shared_ptr<torch::jit::script::Module> module = torch::jit::load("/home/Dev/testtorch/model_trace.pt"); After the model was loaded succesfully I needed some input to try it out! So I created a random Tensor as Input. Later I will have to change it so I can read an Image from OpenCV, access the data and convert it to a Tensor but for now I just wanted to try out If my Model accepts any Input. at::Tensor randomInput = at::rand({1,28,28}); I used the newly created “randomInput” to call the forward function of my model. module->forward({randomInput}) but here comes the problem. The Building works but I get some runtime errors. terminate called after throwing an instance of 'at::Error' what(): Tensor that was converted to Variable was not actually a Variable (Variable at /pytorch/torch/csrc/autograd/variable.h:120) frame #0: <unknown function> + 0x483fef (0x7fb619733fef in /home/narvis/Lib/libtorch/lib/libtorch.so.1) frame #1: <unknown function> + 0x4842a1 (0x7fb6197342a1 in /home/narvis/Lib/libtorch/lib/libtorch.so.1) frame #2: <unknown function> + 0x4886aa (0x7fb6197386aa in /home/narvis/Lib/libtorch/lib/libtorch.so.1) frame #3: torch::jit::script::Method::run(std::vector<torch::jit::IValue, std::allocator<torch::jit::IValue> >&) + 0xf6 (0x42fbf8 in /home/narvis/Dev/testtorch/cmake-build-debug/example-app) frame #4: torch::jit::script::Method::operator()(std::vector<torch::jit::IValue, std::allocator<torch::jit::IValue> >) + 0x4a (0x42fc86 in /home/narvis/Dev/testtorch/cmake-build-debug/example-app) frame #5: torch::jit::script::Module::forward(std::vector<torch::jit::IValue, std::allocator<torch::jit::IValue> >) + 0x81 (0x430495 in /home/narvis/Dev/testtorch/cmake-build-debug/example-app) frame #6: main + 0x548 (0x42c1a0 in /home/narvis/Dev/testtorch/cmake-build-debug/example-app) frame #7: __libc_start_main + 0xf0 (0x7fb60eae6830 in /lib/x86_64-linux-gnu/libc.so.6) frame #8: _start + 0x29 (0x42b209 in /home/narvis/Dev/testtorch/cmake-build-debug/example-app) I guess that this error has something to do with the ATen Tensor library but I couldn’t figure out what the problem was. If you have any thoughts on this please share them with me!
st99330
Hi, I’m not sure but I think it expects torch::Tensor as input no? Be careful as at::Tensor and torch::Tensor are not the same
st99331
You are absolutely right! Christian S. Perone wrote a nice article about it: http://blog.christianperone.com/2018/10/pytorch-1-0-tracing-jit-and-libtorch-c-api-to-integrate-pytorch-into-nodejs/ 56 A word of caution for those who are starting now is to be careful with the use of the tensors that can be created both from ATen and autograd, do not mix them , the ATen will return the plain tensors (when you create them using the at namespace) while the autograd functions (from the torch namespace) will return Variable , by adding its automatic differentiation mechanism. So if you use: at::Tensor test = at::rand({1,28,28}) gives you a at::Tensor without autograd functionality. at::Tensor test = tensor::rand({1,28,28}) gives you a at::Tensor with autograd functionality. Thanks again!
st99332
I wrote a minimal example on how to train a model in pytorch using python and use c++ to load the model and use it. I hope this helps! GitHub tobiascz/MNIST_Pytorch_python_and_capi 156 This is an example of how to train a MNIST network in Python and run it in c++ with pytorch 1.0 - tobiascz/MNIST_Pytorch_python_and_capi
st99333
Hello If i have a network of input 13 and output dim 4. I would like to pass the output of dim 4 back into another network with input dim of 6. If I pad the output of 4 dim with 2 extra dim of 0s, use the output of the 2nd Net to construct a loss, but back prop only on the parameters of the 1st network, would the zero padding cause any problems with the back-prop? If no problems there, what’s a good way of padding the output of the 1st network? Thank you.
st99334
Hello guys, i am new to PyTorch and i have some questions related to the installation process. So far, i have done these: Installed Ubuntu 18.04, 2. Updated python to 3.7, 3. Installed Anaconda, 4. Made Ubuntu use my GPU instead of Intel Graphics Now, correct me if i am wrong, i need to install Cuda before proceeding to the installation of PyTorch. PyTorch doesn’t work with Cuda 10 yet, but i can’t download Cuda 9.2 or 8 for the Ubuntu 18.04. What should i do? Also, my GPU is kinda bad (nVidia GEFORCE GT630M). Is it compatible with PyTorch? If not, what can i do? Thanks in advance
st99335
Hi, Your GPU, GT630M has compute capability of 2.1. Unfortunately, this is quite old (6years) and not supported by pytorch. Anyway, any recent CPU will actually be faster than such and old GPU, so you can just use your CPU. To do so, forget about cuda versions and just install pytorch with no cuda support
st99336
Ok, thank you for the answer! However, i will be able to train models on the cloud if i want, regardless of the installation setup i choose, right?
st99337
Yes, you will need to setup your cloud machine with cuda support if you have gpus there. The change to the code to support GPU is minimal as it’s just a few .cuda() calls, also you can use torch.cuda.is_available() to check if it is available on the current machine.
st99338
Thank you very much! One last question Do you know which cloud service (like AWS, Azure etc) is the best regarding the ease of use?
st99339
I don’t use them so I couldn’t tell you what I personally prefer. They all provide pre-built VM iirc so pick the one your prefer/already use !
st99340
I’m converting a numpy.array to a torch tensor: a = torch.from_numpy(np.random.rand(1,5)) And I want to it to have this type torch.get_default_dtype() How do you do that? thanks
st99341
Solved by saan77 in post #2 You can use .type() function to specify the type. a = torch.from_numpy(np.random.rand(1.5)).type(torch.get_default_dtype())
st99342
You can use .type() function to specify the type. a = torch.from_numpy(np.random.rand(1.5)).type(torch.get_default_dtype())
st99343
Hi, I would like to add a parameter to the function SpatialConvolutionMM_updateOutput(…, int newParam) from “aten/src/THCUNN/generic/SpatialConvolutionMM.cu”. Things I changed so far: I added the new parameter to the thnn_conv2d():in “aten/src/ATen/nn.yaml” also added the new parameter to conv2d: in " /ATen/native/native_functions.yaml" Compile errors I obtain: aten/src/ATen/TypeDefault.h:782: “candidate expects 9 arguments, 10 provided” aten/src/ATen/TypeDefault.h:783: “candidate expects 6 arguments, 7 provided”
st99344
Hi, I guess you will need to change the implementation in THNN as well. Also keep in mind that this might break some python part of pytorch that expects the convolution to take less arguments. If you don’t need all the utilities from THCUNN, it might be simpler to create a cpp extension with your modified function.
st99345
Unfortunately updating SpatialConvolutionMM.c in THNN does not resolve the error. Do you know how to change the declaration of thnn_conv2d_forward_out() and thnn_conv2d_forward() in the autogenerated Declarations.yaml file “build/aten/src/ATen/Declarations.yaml”? Changing them in derivatives.yaml “/tools/autograd/derivatives.yaml” does not yield a result.
st99346
Hi, As stated above this is very dangerous to do and will require quite significant changes to the whole backend as many functions assume the current interface for conv and will need to be modified. I would advice doing a cpp extension 9 containing your modified convolution.
st99347
For any reader who stumbles upon this - here you can find out how to solve it: https://github.com/pytorch/pytorch/issues/12320 21.
st99348
Hello. I am experimenting an issue that on previous versions I did not have. When computing the cross entropy error with the parameter reduce=False I got this error: RuntimeError: expand(torch.cuda.FloatTensor{[100]}, size=[]): the number of sizes provided (0) must be greater or equal to the number of dimensions in the tensor (1) I am evaluating torch.nn.functional.cross_entropy(out,y,reduce=False) where y has shape (100,) and out has shape (100,10) Can anyone give me some feedback? I have seen on other posts that people experimented this issue when calling backward on a Loss. Thanks.
st99349
Upon iterating over the dataloader I receive RuntimeError: received 0 items of ancdata. I tried by increasing number of open file descriptors as shown in https://github.com/pytorch/pytorch/issues/973 15 but to no avail. Can someone please guide how this error could be prevented. x, (y_l, y_ab) = next(loader) where loader is defined as following loader = cycle(train_dataloader) The complete error traceback is given below. Traceback (most recent call last): File "main_mse.py", line 267, in <module> main() File "main_mse.py", line 263, in main train(g_model, d_model, learning_rate_ae, learning_rate_color, train_dataloader, test_dataloader, now) File "main_mse.py", line 111, in train x, (y_l, y_ab) = next(loader) File "/home/thor/anaconda3/envs/torch3env/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 280, in __next__ idx, batch = self._get_batch() File "/home/thor/anaconda3/envs/torch3env/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 259, in _get_batch return self.data_queue.get() File "/home/thor/anaconda3/envs/torch3env/lib/python3.6/multiprocessing/queues.py", line 337, in get return _ForkingPickler.loads(res) File "/home/thor/anaconda3/envs/torch3env/lib/python3.6/site-packages/torch/multiprocessing/reductions.py", line 70, in rebuild_storage_fd fd = df.detach() File "/home/thor/anaconda3/envs/torch3env/lib/python3.6/multiprocessing/resource_sharer.py", line 58, in detach return reduction.recv_handle(conn) File "/home/thor/anaconda3/envs/torch3env/lib/python3.6/multiprocessing/reduction.py", line 182, in recv_handle return recvfds(s, 1)[0] File "/home/thor/anaconda3/envs/torch3env/lib/python3.6/multiprocessing/reduction.py", line 161, in recvfds len(ancdata)) RuntimeError: received 0 items of ancdata
st99350
torch.multiprocessing.set_sharing_strategy('file_system') solved the problem for me. or echo "ulimit -n 4096" >> .bashrc echo "ulimit -n 4096" >> .bash_profile source ~/.bashrc
st99351
Is there a way to provide arguments to a collate_fn() or in some other way get that function access to information other than ‘batch’? The use case is this: I have a fairly large, custom data set in need of some sort of normalization. Exactly what normalization will be most effective is not obvious. It would therefore be convenient to use sklearn to construct a bunch of pre-populated scaler objects (say, a maxabs scaler, and a standardization scaler, just for starters) and use a collate_fn to perform the scaling on the fly. But in order to do this, the collate_fn needs some way to get the file location of those scaler files. But how to do this eludes me. (The brute force alternative of simply replicating the dataset multiple times, normalizing each one separately, is unpalatable do to the sheer size of the database.)
st99352
Solved by fmassa in post #3 I’m not sure I understand everything, but one possibility is to create a class that contains a __call__ method which will be passed to your DataLoader class MyCollator(object): def __init__(self. *params): self.params = params def __call__(self, batch): # do something with b…
st99353
I’m not sure I understand everything, but one possibility is to create a class that contains a __call__ method which will be passed to your DataLoader class MyCollator(object): def __init__(self. *params): self.params = params def __call__(self, batch): # do something with batch and self.params my_collator = MyCollator(param1, param2, ...) data_loader = torch.utils.data.DataLoader(..., collate_fn=my_collator)
st99354
Depending on what you want, I’d probably try one of the following: If the normalization is per example, add it to the dataset and keeping track of it in the dataset is the preferred way. There are various other ways to achieve something similar to what @fmassa suggested (and even more variants when you search for “currying in python”). The lazy person’s way would be using default arguments: dl = torch.utils.data.DataLoader(..., collate_fn = lambda b: my_collator_with_param(b, 3)) or, using the params argument in the lambda to fix the argument rather than having the lookup during execution dl = torch.utils.data.DataLoader(..., collate_fn = lambda b, params=params: my_collator_with_param(b, params)) Between doing things in the dataset and having one of the collator variants from this thread, you should be able to do most things. Best regards Thomas
st99355
Almost same as the above answers though, functools.partial enabeles you to specify arguments other than batch like this from functools import partial def my_collate_fn(batch, a, b): ... DataLoader(..., collate_fn=partial(my_collate_fn, a=foo, b=bar))
st99356
Hey, I am considering to run my model on multiple GPU in one machine. And I found these two DataParallel methods in Pytorch Documentation. https://pytorch.org/tutorials/beginner/blitz/data_parallel_tutorial.html 4 Seems easier but somewhat vague. https://pytorch.org/tutorials/beginner/former_torchies/parallelism_tutorial.html 8 Seems more specific What’s the difference between these two pipelines? Which should I choose? (BTW, I am training a Generative Adversarial Network. Are there some fantastic public Multi-GPUs codes I can refer to? Thanks in advance~
st99357
I would use the first pipeline if I don’t need the precise control offered by the second pipeline. Besides, using the second pipeline means modifying the code of your model. I personally prefer the model code fixed and separated from training settings (to me using Multi-GPU is more of a training config rather than a model design). Best
st99358
Hi, I have a model as such: model = MyNetwork() if self.hparams.nb_gpus > 1: model = nn.DataParallel(model, device_ids=[0, 1, 2, 3]) device = torch.device("cuda:0") model.to(device) for data in loader(): gpu_data = data.to(device) # ------------> HANGS IN THE MODEL CALL... out = model(gpu_data) Q1: If I don’t add the nn.DataParallel call, this works just fine on 1 GPU. Any ideas? I’m also running this on a compute cluster (HPC) managed by SLURM. I’m reserving a full node which has 4 gpus on it (1080tis)… Q2: do i need multiple device calls for multiple gpus? ie: device_a = torch.device("cuda:0") device_b = torch.device("cuda:1") device_c = torch.device("cuda:2") device_d = torch.device("cuda:3")
st99359
After a lot of debugging, I’ve found that my worker processes end up using no CPU and only the main process seems to be using CPU to preprocess the batch data. As far as I understand, each of the worker processes should use the __getitem__ function of the DataLoader independently (during which I just load NumPy files and perform transformations on them). Perhaps all the workers are relying on the main process to perform the transforms for some reason? Any suggestions on to why this might be? Original post: I’m having trouble finding the bottleneck in training time for my code. For some reason, it appears setting num_workers=0 results in the fastest training. I ran a series of experiments comparing training speeds under various conditions, and I can’t seem to figure out why num_workers=0 would produce the fastest speed. During my experiments, I’ve been monitoring the CPU and memory (using glances) and neither seems to come anywhere near being maximally used. Except, in the case where I’m using num_workers=0, then the CPU the main process is running on is almost always at 100% usage. Again though, for some reason, this is when training seems to run the fastest. The GPU processing only spikes occasionally (when a batch is being run), but most of the time it just seems to be idling. Turning pin_memory off and on for the DataLoaders results in no speed difference. Reading data from the SSD does not seem to be the limiting factor (I tried setting the DataLoader to just remember the examples it already loaded and not load another file to test if disk read speed was limiting, but even with this setup, num_workers=0 was still fastest). The only factor I can think of that I’m not directly monitoring is the transfer speed from memory to GPU memory, but I wouldn’t expect this to be the limiting factor, and I would expect pin_memory to result in a change here. Just in case some more details are helpful, my speed experiments consisted of the following. Each batch consists of 100 images. The images and their corresponding labels have significant transforms applied to them in the DataLoader. A patch of the image is extracted and the remainder of the transforms depends on what’s in that patch, so these transforms can only be preformed after the patch is extracted. Trying to save every permutation of this preprocessed data would require too much storage, which is why the transforms are applied during training. Timing 10 batches of processing with num_workers=0 takes ~5.5s. With num_workers=1 it takes ~7s and num_workers=4 takes ~10s (again noting that each of these trials with pin_memory seemed to have no impact on speed). Given that with num_workers=0, I can clearly see the individual CPU core the main process is running on is nearly always at 100%, it seems strange that adding more workers would decrease the speed. And when running multiple workers it’s slower despite no obvious bottleneck seems strange to me. Can anyone suggest what I might be doing wrong? Thank you for your time. Original post update (GAN): After writing the above, I considered one additional factor that may be worth noting. I’m working with a GAN, where both labeled and unlabeled data is being passed to the network. Because of this, I have two DataLoaders passing batches to the network. Does having two separate DataLoaders trying to access the same input to the network cause trouble (especially in regards to pinning memory)? And if so, is there a way to avoid this problem? Original post update 2 (Workers don’t seem to be using CPU): Strangely, it doesn’t seem any of my worker processes end up using any CPU. As far as I understand, each of the worker processes should use the __getitem__ function of the DataLoader independently (during which I just load NumPy files and perform transformations on them). Perhaps all the workers are relying on the main process to perform the transforms for some reason? Any suggestions on to why this might be?
st99360
Solved by mattrobin in post #2 I solved the problem. The problem was because the dataset was listed as only having a length of the same size as the batch size. And it seems the DataLoader will “hand out” remaining dataset indexes left to be processed to its workers. When the batch size is the dataset length, then only 1 process w…
st99361
I solved the problem. The problem was because the dataset was listed as only having a length of the same size as the batch size. And it seems the DataLoader will “hand out” remaining dataset indexes left to be processed to its workers. When the batch size is the dataset length, then only 1 process will be given indexes to preprocess. I had done this because only a small patch of each full image was used during processing, and this patch was randomly chosen from each image during the transform part of the preprocessing. Since only a tiny part of each image was used (and the total number of full size images were less than the desired batch size), it didn’t make sense to use the actual length of the dataset as the length listed as the length attribute of the dataset. In the end, to utilize each worker of the DataLoader, I need to set the dataset length to be num_workers * batch_size. This way, the DataLoader can give each worker batch_size number of indexes to work on.
st99362
let’s say I have 1/14 sample in class 0 and 13/14 in class 1. how to choose the properly the alpha or the weight in BCE and focal loss ? is it .92 for class zero and .07 for class one or 1 for class zero and 0.07 for class one or else ?
st99363
I’m using BCEWithLogitsLoss while my batch size is 24 and one single node output. I’m defining the loss as weight = torch.FloatTensor([1.0, .25]) criterion =nn.BCEWithLogitsLoss(weight=weight ) So I’m having this error RuntimeError: The size of tensor a (24) must match the size of tensor b (2) at non-singleton dimension 0 Do I need to re-initiate the weight in each call for the loss with an arranged weight of the batch size?
st99364
Hi, equation (1) in this paper 40 computes binary cross entropy as you said. Also, I found this: How to Prevent Overfitting oh if you have class imbalance, use a weighted sampler, so that you see all classes with equal probability. That should help a lot (depending on the severity of your imbalance): http://pytorch.org/docs/data.html#torch.utils.data.sampler.WeightedRandomSampler You can give this to your DataLoader
st99365
Hello, My data has [Nx2x10] shape and i want the model to take 2 inputs (xi and xj) at every time. when i stack the inputs xi and xj as (20,) the output probability is different from stacking xj and xi. How can i make sure that the probability is same for (xi,xj) and (xj,xi) ?
st99366
Can you share a code snippet on what you are trying to do? It depends on your model and use case. Probably you have to train the network with both the variants of your data, if you want the behaviour to be same. .
st99367
I’m trying to convert CNN model code from Keras with a Tensorflow backend to Pytorch. Problem is that I can’t seem to find the equivalent of Keras’ ‘categorical crossentrophy’ function: model.compile(loss=‘categorical_crossentropy’, optimizer=‘adam’, metrics=[‘accuracy’]) The closest I can find is this: self._criterion = nn.CrossEntropyLoss() self._optimizer = optim.Adam(self._model.parameters(), eps=1e-07) … loss = self._criterion(outputs, primary_indexes) loss.backward() But it doesn’t function similarly and as well as the original Keras code. It takes twice as many epochs to end on the original dataset and doesn’t work as well, and in my larger datasets the loss and accuracy goes from around ~15-20% at the first epoch to around 4% when training ends. Whereas the Keras version goes from ~15-20% to around ~40-55% when training ends. Here’s the original Keras model: model = models.Sequential() model.add(Reshape(in_shp+[1], input_shape=in_shp)) model.add(ZeroPadding2D((0,2))) model.add(Conv2D(64, (1,4), activation=“relu”)) model.add(Dropout(dr)) model.add(ZeroPadding2D((0,2))) model.add(Conv2D(64, (2,4), activation=“relu”)) model.add(Dropout(dr)) model.add(Conv2D(128, (1,8), activation=“relu”)) model.add(Dropout(dr)) model.add(Conv2D(128, (1,8), activation=“relu”)) model.add(Dropout(dr)) model.add(Flatten()) model.add(Dense(256, activation=‘relu’)) model.add(Dropout(dr)) model.add(Dense(len(classes), activation=‘softmax’)) model.add(Reshape([len(classes)])) model.compile(loss=‘categorical_crossentropy’, optimizer=‘adam’, metrics=[‘accuracy’]) model.summary() Layer (type) Output Shape Param # reshape_1 (Reshape) (None, 2, 128, 1) 0 zero_padding2d_1 (ZeroPadding) (None, 2, 132, 1) 0 conv2d_1 (Conv2D) (None, 2, 129, 64) 320 dropout_1 (Dropout) (None, 2, 129, 64) 0 zero_padding2d_2 (ZeroPadding) (None, 2, 133, 64) 0 conv2d_2 (Conv2D) (None, 1, 130, 64) 32832 dropout_2 (Dropout) (None, 1, 130, 64) 0 conv2d_3 (Conv2D) (None, 1, 123, 128) 65664 dropout_3 (Dropout) (None, 1, 123, 128) 0 conv2d_4 (Conv2D) (None, 1, 116, 128) 131200 dropout_4 (Dropout) (None, 1, 116, 128) 0 flatten_1 (Flatten) (None, 14848) 0 dense1 (Dense) (None, 256) 3801344 dropout_5 (Dropout) (None, 256) 0 dense2 (Dense) (None, 11) 2827 reshape_2 (Reshape) (None, 11) 0 My Pytorch model code looks like this: def __init__(self, classes, dr=0.5, bias=False): super(My_Model, self).__init__() self.pad = nn.ConstantPad2d((2, 2, 0, 0), 0) self.dropout = nn.Dropout(dr) self.conv1 = nn.Conv2d( 1, 64, (1,4), bias=bias) self.conv2 = nn.Conv2d( 64, 64, (2,4), bias=bias) self.conv3 = nn.Conv2d( 64, 128, (1,8), bias=bias) self.conv4 = nn.Conv2d(128, 128, (1,8), bias=bias) self.linear1 = nn.Linear(self.linear1_input_size,256, bias=bias) self.linear2 = nn.Linear(256,classes, bias=bias) def forward(self, x): x = self.pad(x) x = F.relu(self.conv1(x)) x = self.dropout(x) x = self.pad(x) x = F.relu(self.conv2(x)) x = self.dropout(x) x = F.relu(self.conv3(x)) x = self.dropout(x) x = F.relu(self.conv4(x)) x = self.dropout(x) x = x.view(-1, 14848) x = F.relu(self.linear1(x)) x = self.dropout(x) x = F.softmax(self.linear2(x), 1) return x