user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
Cuistiano
Can I use ‘torch.cuda.amp.autocast’ with ‘torch.einsum’ ? Will this work ?
smth
since einsum is a fairly dynamic op, i think amp.autocast might keep it in the “safe” region and do the computation in fp32. It should be quick to try and find out.
cakeeatingpolarbear
I was wondering how I would re-initialize the weights of my model without having to re-instantiate the model?
smth
This is not a robust solution and wont work for anything except core torch.nn layers, but this works: for layer in model.children(): if hasattr(layer, 'reset_parameters'): layer.reset_parameters()
dipanp
So pytorch’s main strength is the ability to have dynamic computation graphs. I was wondering if there is a simple way of initializing or inserting new layers into the network as well while the network is training? For example, epoch 0 to 10 trains a single linear layer (input -> 100) and then epoch 10 to 20 adds in an...
smth
just create new layers on the fly behind python conditionals etc. pytorch’s models are python code, so it’s upto you how you want to do these things. your forward function gives you full freedom to do arbitrary things.
amandeep1991
Hi PyTorch Team,Thanks for building this wonderful library.I have been using many open-source libraries for quite some time now; however, I am a newbie contributor in the same space, so doubtful about licensing.I have a vision that I would be building at least my domain-specific 5-10 models using pytorch library, whic...
smth
PyTorch is BSD licensed. If you write New Code in your own repository, you can license it under whatever license you want. If you are distributing PyTorch code as-is, you have to preserve PyTorch code license in the distribution.
AmirAlavi
The tutorials (such asthis one) show how to usetorch.utils.data.Datasetto efficiently load largeimagedatasets (lazy loading or data streaming). This is easily applied to images because they usually exist as a folder containing separate files (each sample exists as its own file), and so it’s easy to load just a single i...
smth
you can use a memory-mapped numpy array from your .npy file:https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.memmap.htmlThat way it still stays on disk and loads the rows you ask on the fly.
ironv
I was downloading the latest versions of pytorch to install offline on a Windows VDI with CPUs. I ran the followingpip3 download -d torch torch==1.4.0+cpu -f https://download.pytorch.org/whl/torch_stable.html pip3 download -d torchvision torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stab...
smth
This worked for me perfectly, it downloaded torch 1.4.0+cpu torchvision 0.5.0+cpu and torchtext 0.5.0 pip download torch==1.4.0+cpu torchvision==0.5.0+cpu torchtext==0.5.0 -f https://download.pytorch.org/whl/torch_stable.html Files: certifi-2019.11.28-py2.py3-none-any.whl chardet-3.0.4-py2.py3-no…
pvskand
I have trained my model and now want to test it but I was getting this error while testingAttributeError: 'OrderedDict' object has no attribute 'cuda'The error comes after this:model = torch.load(snapshot_path) model.cuda()Is there any mistake in my training that it is not able to find the cuda parameter, since I had d...
smth
if you saved the state dict, you have to load the model via load_state_dict. Either read the documentation or look at our examples.
ihexx
I’m trying to implement meta-gradient learning similarly to [https://arxiv.org/pdf/1805.09801.pdf].I need to backpropagate through a parameter update.The following is a minimum example that highlights the problem:meta_param = torch.tensor(5.0,requires_grad=True) # this is the variable i want to learn pa...
smth
you could look at something likehttps://github.com/facebookresearch/higherfor this purpose. It functionalizes the model, where it’s parameters can be detached and backproped through
junhocho
I wanted to install Pytorch1.1.0 along with cuda9.0Referringhttps://pytorch.org/get-started/previous-versions/, Used following command.Following command fails, attempting to install pytorch1.1.0 of cuda10conda install pytorch=1.1.0 cuda90 -c pytorchCollecting package metadata (current_repodata.json): done Solving envir...
smth
for 1.1.0 it was conda install pytorch=1.1.0 cudatoolkit=9.0 -c pytorch as far as I can remember.
lmoss
Hi all,Is there an elegant way to apply a network to a tensor that is larger than GPU memory?Tensorflow has tensorflow-mesh, maybe there’s something similar for pytorch?I am aware of a sliding window approach, but that can lead to artifacts at edges of outputs.Thanks!
smth
have you looked at something likehttps://pytorch.org/docs/stable/checkpoint.html
tsterin
Hi all,I was wondering, when using the pretrained networks of torchvision.models module, what preprocessing should be done on the input images we give them ?For instance I remember that if you use VGG 19 layers you should substract the following means [103.939, 116.779, 123.68].Where can I find these numbers (and even ...
smth
All pretrained torchvision models have the same preprocessing, which is to normalize using the following mean/std values:https://github.com/pytorch/examples/blob/97304e232807082c2e7b54c597615dc0ad8f6173/imagenet/main.py#L197-L198(input is RGB format)
mbp28
Hi,this should be a quick one, but I wasn’t able to figure it out myself.When I use a pre-defined module in PyTorch, I can typically access its weights fairly easily.However, how do I access them if I wrapped the module in nn.Sequential() first?Please see toy example below.class My_Model_1(nn.Module): def __init__(...
smth
model_2.layer[0].weight
ChangGao
Hi guys, I’m asking a question about using multipleprocessing module to print random numbers.When I was using the “numpy.random.rand” produce random numbers, I found that some of the produced values from different cores are the same. But the random.uniform can work just ok.Here is the code.import multiprocessing import...
smth
See this comment:Does __getitem__ of dataloader reset random seed?
handesy
Hi, I encountered the following assertion error when running my code on GPU (things are fine on CPU):/b/wheel/pytorch-src/torch/lib/THC/THCTensorIndex.cu:321: void indexSelectLargeIndex(TensorInfo<T, IndexType>, TensorInfo<T, IndexType>, TensorInfo<long, IndexType>, int, int, IndexType, IndexType, long) [with T = float...
smth
you are giving an out of bounds index somewhere. Can you reproduce this error with a small snippet? Usually these device-side asserts are easier to debug if you run the same code on CPU (i.e. without .cuda()) and you know right away what the out of bounds indices are and where they’re coming from. …
hdkgr
I noticeddeepcopying a module causes itsparameters()to betensors rather thannn.Parameters.import torch.nn import copy l = torch.nn.Linear(3,1) c = copy.deepcopy(l) print([type(p) for p in l.parameters()]) print([type(p) for p in c.parameters()])[<class 'torch.nn.parameter.Parameter'>, <class 'torch.nn.parameter.Parame...
smth
This looks like a regression in 0.4.0 / 0.4.1, We reopened the issue and an engineer is working on issuing a fix.
jmaronas
It seems there is a problem with the conda installation of the 1.0.0 version for cuda 10. If I execute:/usr/local/anaconda3/bin/conda install -y pytorch=1.0.0 torchvision cudatoolkit=10.0 -c pytorchThen If executing. I get cuda version 9:(/tmp/cuda10.0_pytorch_1.0.0/) user@usermachine1:/tmp$ python -c "import torch; pr...
smth
the cudatoolkit version should be the final version with no planned changes. It’s what the Anaconda team recommended, and we worked with them to move to this.
WERush
There is an example.class mm(nn.Module): def __init__(self): super(mm, self).__init__() self.n = nn.Linear(4,3) self.m = nn.Linear(3,2) self.m2 = nn.Linear(3,4) def forward(self, input, input2): input_ = self.n(input) input2_ = self.n(input2) o1 = self.m(i...
smth
opt1 = optim.Adam(branch_1.parameters(), ...) opt2 = optim.SGD(branch_2.parameters(), ...) ... ... loss = 2*loss_1 + 3 *loss_2 loss.backward() opt1.step() opt2.step()
wangg12
When I runtorch.svd(torch.rand(3,3).cuda())I encountered an error:--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-6-9c860559505b> in <module>() ----> 1 torch.svd(torch.rand(3,3).cuda()) RuntimeError: ...
smth
cmake prefix path is not which conda, it is "$(dirname $(which conda))/../" export CMAKE_PREFIX_PATH="$(dirname $(which conda))/../"
christianperone
I’m using clang 6.0 and I’m getting a lot of issues while linking toc10library:undefined reference to `c10::Error::Error(c10::SourceLocation, std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;)'All undefined references seems to be related with thestd::__cxx11::b...
smth
we have that flag set because we build with gcc 4.9.x, which only has the old ABI. In GCC 5.1, the ABI for std::string was changed, and binaries compiling with gcc >= 5.1 are not ABI-compatible with binaries build with gcc < 5.1 (like pytorch) unless you set that flag.
hhsecond
Hi Team,I have a very simple fizbuz model made using pytorch python APIs which I have exported as ScriptModule. I am loading the same module from python and CPP and passing same input but getting wrong output in CPP.In fact, regardless of what ever input I pass, I get the exactly same values in the output from CPPHere ...
smth
As Thomas said, you probably have to make array a float, you have it as int array[10]. If you have int array[10] and re-interpret it as a float, it’s probably going to have weird floats come out on the other side.
kealexanderwang
I’m trying to take advantage of Pytorch’s autograd feature and perform matrix-matrix multiplication$A \times B$where matrix A is represented as a list ofTensorseach on a separate GPU.What is the best way of distributing this task across multiple GPUs and then collecting the results from each GPU onto one? It doesn’t se...
smth
There isn’t an automatic way to do this. If A is a list of Tensors, each on a separate GPU, I presume A is a large matrix, with rows 0 to i on GPU0, i to j on GPU1, etc. Let’s assume B is only on GPU 0, because you didn’t mention anything about B. Here’s a sample snippet showing how to parallelize…
dragen
Hi, all:I found the built-in python sum function can deal with Tensor data type. That’s weird!Moreover, the result ofsum(a, b)is distinct fromsum([a, b]), Could anyone give some insight?In [8]: a Out[8]: tensor([[1., 1., 1.], [1., 1., 1.]], device='cuda:0') In [9]: b Out[9]: tensor([[1., 1., 1.], [1....
smth
PyTorch Tensors are iterables, so Python will iterate over Tensor and sum each element. This will be done by Python getting each pair of elements in the left-most dimension of the Tensor, from left to right, and calling __add__ on them. It’s going to be slower, because it’s equivalent to: x = torch…
catphive
I’m trying to get a handle of the organization the pytorch code base.I see in an earlier version where matrix inverse and the backward operation for matrix inverse are implemented:github.comfmassa/pytorch/blob/359356776dbd66cf2208d9f791ea2da682ae9405/torch/autograd/_functions/linalg.pyimport torch from ..function impo...
smth
I took you down the wrong rabbit-hole and its ENTIRELY my fault, sorry about that. We do have functions in C+±land whose derivatives are entirely defined by tracing, but this is not such a function. inverse's derivate is speficied in derivatives.yaml here:https://github.com/pytorch/pytorch/blob/e…
hassan_hamdy
hi guys,i train my model for image classifier of flower dataset on colab -because it will take long time on my local machine- using pretrained model vgg19 and after train i want to save my model weights on my local machine how can i do that ?stackoverflow.comgoogle colaboratory, weight download (export saved models)goo...
smth
replace that entire snippet with: torch.save(model.state_dict(), 'drive/app/model.pth')
chenglu
If I want to write a operation by C++ extension, is it necessary to write a corresponding backward function for that operation even if there’re no trainable weights in that operation?I have dug into the source and found that every built-in loss function comes with a backward function. i.e. thebinary_crosss_entropy_with...
smth
yes, but make sure you are using an input of torch::Tensor, and not at::Tensor. torch::Tensor is autograd-ready
kuzand
I am training a model on Google Colab and would like to save a checkpoint.pth file to the github repository from which I opened the notebook.Is it possible?
smth
in colab, I ran !git status and I see that git is available. So technically, you can re-clone the repo inside your colab environment, using ! git clone [your repo URL], save your model to that repo, and then do your usual git add, git commit, git push etc. I haven’t seen any automated way to do th…
NadimKawwa
I’m running an instance on AWS of the type p2.xlarge.Once I have the instance running I connect to it from the command line as follows:ssh -i YourKeyName.pem ubuntu@X.X.X.XI configure Jupyter with this:jupyter notebook --generate-configChange the IP address config setting for notebooks:sed -ie "s/#c.NotebookApp.ip = 'l...
smth
About the numpy issue, check what pip --version says. It has to match to the root of where your which python or python --version is pointing. On some machines pip3 will correspond to the python you are using, rather than pip. About the 2nd issue, i.e. AttributeError: ‘FloatTensor’ object has no att…
simenthys
I am trying to backpropagate the loss of my model towards the input, for the purpose of calculating adversarial examples. The idea is to train an adversarial sticker that can be added to an input image to cause an object detection system to fail. However, when trying to backpropagate my loss towards the input of my mod...
smth
did you use .detach() or .data or .numpy() somewhere in the chain? those are the main suspects for a disconnected graph
csharp3x7
Hi,I was wondering if anyone knows or has tested on Linux/Ubuntu whether running 2x Nvidia 2080 Ti with the NVLink will allow you to pool the GPU memory such that it appears as 22gb (2x11gb/GPU)? Someone on Reddit posted, “Linux users report NVLink merges two 2080Tis into 1 logical GPU, though their communication is go...
smth
From my fairly up-to-date knowledge, NVLink doesn’t merge the GPUs into 1 logical GPU, I’ve never heard of this happen. Even for GPUs such as K80 where it’s 1 physical GPU, they split it into 2 logical GPUs in nvidia-smi / software. Maybe it merges the 2 GPUs into 1 logical GPU for gaming, such as …
vivivo
Hi, guys. I faced some problem in pytorch. My code like this:class Net(nn.Module): __init__(self, n_inputs, n_outputs, kernel_size, stride, dilation, padding, dropout=0.2): self.conv1 = weight_norm(nn.Conv1d(n_inputs, n_outputs, kernel_size, stride=stride, padding=padding, dilation=dilation, bias=False)) ...
smth
did your training accuracy drop / fail a lot after you removed the Sequential? I looked at your code and didn’t see anything obvious. Some things to look for are to see if the number of parameters in your model is the same before and after. You can do this with: num_params = 0 for p in model.para…
Isaac009
----> 1 import torch2 import torch.nn as nn3 import torch.nn.functional as F45 # define a neural network with a single convolutional layer with four filtersC:\ProgramData\Anaconda3\lib\site-packages\torch_init_.py in74 pass75—> 76 from torch._C import *7778all+= [name for name in dir(_C)ImportError: DLL load failed...
smth
Hi Isaac, How did you install PyTorch? Was it via Pip or Conda? In your current working directory, is there a folder called torch? Can you try changing your directory if so?
Lemling
Hello there, complete pytoch beginner here (started 5 months ago).I got the following task:I have to build an Autoencoder that hast 3 different parts. 2 of those are the encoder that are fed with the same Image. The third part is the decoder.Now I am really confused about summing up the losses when I have 3 losses wher...
smth
First issue in your question: # WRONG! (reconstLoss +outLoss.item()).backward() # Correct (reconstLoss +outLoss).backward() x.item() returns it as a Python number, which means, your operations on the return of x.item() no longer come under the visibility of PyTorch. It’s pretty much like doing (r…
Lemling
Hello there,for evaluation purposes I ran 2 extra losses alongside the first main loss.I only called backward on the main loss.Do the other 2 loss calculations change anything for back propagation or any other update?GreetingsLemling
smth
unless you call .backward() on the two extra losses, or add them to the main loss before calling backward (for eg. `(main_loss + loss_extra1 + loss_extra2).backward()), they wont affect the gradients you computed.
crcrpar
Hi,Now Pytorch repository amazingly hosts Caffe2 and PyTorch.So, what is the recommended way to install all of them at once including CUDA compat and C++ interface (libtorch, and caffe2 cpp) on Ubuntu 16.04 with CUDA 9.0?
smth
install them as listed in commands onhttps://pytorch.orgThe commands install PyTorch, which includes caffe2 as well.
Yuerno
If my model gives outputs in the shape of [N, C, H, W], where N is the batch size, and C are the number of channels based on the number of output classes, and I have corresponding masks in the shape of [N, H, W], am I okay to just plug these as-is into a CrossEntropyLoss function? Or do I need to do some sort of arg-ma...
smth
you can just use CrossEntropyLoss in this case, and it will treat C as the slicing dimension for softmax, i.e. each [N, H, W] slice will have a softmax be taken over it
Zichun_Zhang
Hello! Why there is no global pooling in Pytorch Framework.I just notice there are normal pooling method like Maxpool or Avgpoolbut no Global pool there, why?~And if you may, how does global pooling works actually, I just saw it in the paper about CNN, but a little bit confuse about its backend mechanism:hushed:
smth
use torch.mean or torch.max operator
soumyarooproy
This example:github.compytorch/pytorch/blob/master/test/cpp_extensions/complex_registration_extension.cpp#include <torch/extension.h> #include <ATen/CPUFloatType.h> #include <ATen/Type.h> #include <ATen/core/VariableHooksInterface.h> #include <ATen/detail/ComplexHooksInterface.h> #include "ATen/Allocator.h" #include ...
smth
some fundamental parts need to be added to aten/C10, similar to how we added ComplexFloat. The rest can be done out-of-source. If it’s bfloat16, we are interested in adding it into aten/c10 for some accelerators.
aplusm
I’m aware that PyTorch 1.0 now supports deployment to C++ using tracing, etc. and there’s also ONNX for cross-framework deployments. I’m wondering if there’s any recommendation about running models in a production Golang API?The only option I could think of would be PyTorch->ONNX->TensorFlow to use TF’s Go bindings, wh...
smth
at the moment that’s your best bet. Alternatively writing Go -> PyTorch C++ bindings for the functions you want, but that seems like it’ll be maintenance overhead for you.
John1231983
Hello all, I am working on a project using pytorch. However, the speed is not so good enough in inference. Do you think the inference time will reduce if I use caffe 2? Thanks so much
smth
if you are using GPU, for Densenet, both frameworks should be same speed.
acgtyrant
I want to understand how does ReLU backward, I find it is implemented bytorch._C._nn.threshold, notautograd.Functionobject.I think all object fromtorch._C._nnis defined byaten/src/Aten/nn.yaml, and a backward implementation oftorch._C._nn.thresholdisTHNN_(Threshold_updateGradInput), however, I finds it acceptTHTensor *...
smth
an autograd.Function (sort of, but in C++) is generated from nn.yaml and other metadata, which saves the input and passes it to the Threshold_updateGradInput function. If you have a local source build of PyTorch, looking at the file build/aten/src/ATen/CPUFloatType.cpp would help
shagunsodhani
I was looking at thehogwild example. Here the model is evaluated on the test data within each process. Shouldn’t the right way be to first train the model in different processes, wait for the processes to terminate and then do an evaluation over test data? Or the asynchronous updates (to the model from different proces...
smth
I could not figure out when the updates are shared between the different processes. The updates aren’t shared between processes at all. All processes are seeing the same memory for the weights, so regardless of who updates the weights, all of them see updated weights. On (1), yes you need valida…
RogerXT
Let’s say, I have a tensor, torch.tensor([1, 2, 3]) and a set {2, 3}. I want to check whether an element in the tensor is in the set. And return a tensor like this: torch.tensor([0, 1, 1]) because 2 and 3 are in the set.Is there a fast way to do this? Or I have to right a for loop?
smth
if you dont have a constraint of memory, then you can use a broadcasting trick: x = torch.tensor([1, 2, 3]) y = torch.tensor([2, 3]) x.view(1, -1).eq(y.view(-1, 1)).sum(0)
ydawei
Hi,I would like to install pytorch version 0.4.1 with cuda 8.0 with python 3.6.When I runconda info pytorch, there is one block as follows:pytorch 0.4.1 py36_cuda8.0.61_cudnn7.1.2_1 ------------------------------------------ file name : pytorch-0.4.1-py36_cuda8.0.61_cudnn7.1.2_1.tar.bz2 name : pytorch version ...
smth
as mentioned on the pytorch website, if you want to install with cudatoolkit 8.0, use conda install pytorch cuda80 -c pytorch
jmandivarapu1
Need confirmation for the method I am following to implement the permutated MNISTprint("Applying permutation to MNIST pixels") rng_permute = np.random.RandomState(92916) idx_permute = rng_permute.permutation(784) transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor(), torchvision.tr...
smth
it should be: idx_permute = torch.from_numpy(rng_permute.permutation(784), dtype=torch.int64) transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor(), torchvision.transforms.Lambda(lambda x: x.view(-1)[idx_permute].view(1, 28, 28) )])
youkaichao
import torch from torch import nn from torch.autograd import Variable torch.manual_seed(1) net = nn.Sequential( nn.Linear(100, 100), nn.BatchNorm1d(100), nn.Linear(100, 1) ) im = Variable(torch.ones(10, 100)) for _ in range(10): net.train(True) print(net(im)) for _ in range(10): net.train(Fal...
smth
On 1: in training mode, BatchNorm DOES NOT use running_mean and running_std to compute the output. It only updates running_mean and running_std values internally. Hence, what you see is exactly what’s expected. On 2: At test time, the output is not the same as the last training output. The output u…
mpagli
At inference time, or when doing hyper-parameter search, I would like to have multiple processes running one pytorch model each (independently from each others). I’m trying to achieve this on CPU. In the case of hyperparameter search for instance, I wrote some code to have a pool of processes trying different hyperpara...
smth
if you want to have pytorch CPU models run in multiple processes, and see speedups, set the environment variables export MKL_NUM_THREADS=1; export OMP_NUM_THREADS=1 in your shell, before starting python. This will make sure that the multithreading pools in multiple process are disabled and hence don…
lmnt
Hi I’m very new to using PyTorch and am still wrapping my head around it all, but I was wondering given the dynamic nature of pytorch how it might be possible to add new neurons (with different parameters than the other nodes potentially) to the hidden layer partway through training. Or if I train first, add new neuron...
smth
you can keep your “neurons” in a ParameterList, and keep adding new Variable or nn.Parameter of neurons to that list, whether that be each individual neurons (not super efficient), or say a block of 4096 neurons whenever you want a new set. You can also take the “some are silenced” approach, and th…
jsn
Sorry for throwing in multiple questions:Does pytorch support setting same seed across all devices (CPUs/GPUs)? Do these devices all use the same PRNG? If not, are there any other ways to make layers like dropouts deterministic?
smth
torch.manual_seed(seed) will set the same seed on all devices. However, setting the same seed on CPU and on GPU doesn’t mean they spew the same random number sequences – they both have fairly different PRNGs (for efficiency reasons). As guidance, treat the PyTorch PRNGs as determinism helpers, but…
iandanforth
Hello all! I’ve recently started learning Pytorch and as a learning exercise I am trying to create a RNN + fully connected module. Unfortunately when I try to use the module I find that my network is not learning. In fact when I do a trace I find that my parameter gradients are all remaining None. I’d appreciate any de...
smth
so, i think i know the problem. let’s see. you are doing this, to signal that your model requires gradients: outputs = torch.tensor(outputs, requires_grad=True) A tensor constructor torch.tensor(outputs, requires_grad=True) has taken outputs here which are lists of Tensors. The constructor doesn’…
araffin
Hello,When building pytorch from source (no cuda, no distributed, cpu only), i noticed a big difference in performance from the version i installed via pip (http://download.pytorch.org/whl/cpu/torch-0.4.0-cp27-cp27mu-linux_x86_64.whl).After some trials, i managed to get similar performances by linking against mkl lib (...
smth
here’s a link to the build script that is used to build the cpu-only wheel:https://github.com/pytorch/builder/tree/master/manywheel(linux)https://github.com/pytorch/builder/tree/master/wheel(osx)
YK11
Hello!I am trying to implement one dimensional CNN (nn.Conv1D()). The input shape is (N,C,L), but my audio file’s shape is (L, C). How can I transform it to tensor?When I worked with image I used ToTensor() built-in transform.Thank you!
smth
you can simply do input.transpose(0, 1).unsqueeze(0) which will make it (1, C, L)
jeff
I have a tensor namedinputwith dimensions 64x21x21. It is a minibatch of 64 images, each 21x21 pixels. I’d like to crop each image down to 11x11 pixels. So the output tensor I want would have dimensions 64x11x11.I’d like to crop each image around a different “center pixel.” The center pixels are given by a 2-dimensiona...
smth
it’s a bit more advanced usage, but you can do this efficiently on the GPU using the grid_sample method. It implements warping, given a 2D flow-field.http://pytorch.org/docs/0.3.0/nn.html?highlight=grid_sample#torch.nn.functional.grid_sample
jeff
Sorry to ask. I know, it’ll be ready when it’s ready. For reasons documented in parthere, my team of developers and I are thinking of delaying the release our Python library until PyTorch 0.4 binaries are available through pip and conda. There’s no rush, it would just help us planning to have some idea of the release d...
smth
we are planning to release within the next 2 weeks
MatthewInkawhich
To my knowledge, theautograd.backward()function is used to determine the gradient of the loss with respect to the output of the network, which ultimately gets propagated back through the network via chain rule.Is it possible to manually set the initial gradient (gradient of loss w.r.t. output), and use thebackward()fun...
smth
I apologize, it should be output.backward(). What you want to do is: output.backward(custom_grad)
GarrisonD
Is there any reason why we should prefer compiling PyTorch from source to installing it with pip?
smth
no reason to compile from source. installing with pip will give you stable branch. compiling from source will give you latest features, but more unstable branch
username1
Is there any difference between CUDNN_LIB_DIR and CUDNN_LIBRARY enviroment variables fed to the setup.py script ?The fillowinglinesuggests that they should be the same, is this true ? If so, why do both of them exist ?
smth
just set CUDNN_LIBRARY OR CUDNN_LIB_DIR as environment variable. CUDNN_LIBRARY takes precedence if specified.
vadimkantorov
A little confusing that both exist. Is any of these deprecated?
smth
we should now deprecate torch.nn.functional.tanh on master, as tensors and variables are now merged.
acgtyrant
2017-06-08-144235_701x297_scrot.png701×297 47.8 KBYou need a striking favicon!
smth
Added now, thanks for the suggestion
acgtyrant
I read the paper about batch normalization, but I do not find how does it initialize the weight. So I find the code in PyTorch as below:nn/modules/batchnorm.py line31,32:self.weight.data.uniform_() self.bias.data.zero_()So why do the wights of batch normalization initialize like this? Is there any theory that this inia...
smth
there is no theory around this specifically.
luckynoob
Looking into the tensor library used by pytorch, wondering which linear algebra package was used for some of the tensor operations.TensorFlow seems using Eigen from their code.
smth
On the CPU, we use Intel MKL to ship with our binaries. ATen can use other Linear Algebra libraries as well, that expose a LAPACK interface, such as OpenBLAS, Eigen. On the GPU, we use cuBLAS, cuSolver andMAGMA
Gullal
I have a network (can be VGG, Resnet, Densenet) with its head/final layer split into two sibling layers. Both the layers are of size equal to number of classes. One layer outputs logits (before softmax) while the other one outputs noise for each class. In simple terms, my loss function is a cross entropy over element-w...
smth
just write your loss in terms of autograd operations, and call backward. you dont need to do anything special like writing your own autograd.Function with a custom backward.
Gullal
I have fine-tuned the pre-trained densenet121 pytorch model with dropout rate of 0.2.Now, is there any way I can use dropout while testing an individual image?The purpose is to pass a single image multiple times through the learned network (with dropout) and calculate mean/variance on the outputs and do further analysi...
smth
you can set your whole network to .eval() mode, but then set your dropout layers to .train() mode. You can use the apply function to achieve this for example:http://pytorch.org/docs/master/nn.html#torch.nn.Module.apply
magnus_w
Hey everyone,very simple question.I have an input [Batch, C_1, H, W],and want an output [Batch, C_1, H, 1],and I am going to use a Conv2D with kernel shape (1, W).However, I only want to use W parameters for this.If I use the group option I can decrease my weights, and minimally I will have for every channel a set of o...
smth
the right thing to do here is to have a nn.Conv2d(1, 1, (1, W)) and then fold the channels dim into batch: input = Variable(torch.randn(Batch, C_1, H, W)) m = nn.Conv2d(1, 1, (1, W)) output = m(input.view(Batch * C_1, 1, H, W)).view(Batch, C_1, H, 1)
squirrel
It’s weight initialization code below:import torch.nn.init as init def xavier(param): init.xavier_uniform(param) def weights_init(m): if isinstance(m, nn.Conv2d): xavier(m.weight.data) m.bias.data.zero_()if VGG is a nn.ModuleList, and:VGG.apply(weights_init)dosen’t throw an error.But I just can...
smth
just for closure of this thread, documentation is here:http://pytorch.org/docs/master/nn.html?highlight=modulelist#torch.nn.Module.apply
JiamingSun
Hi there, I’m testing with fp16 features of pytorch with a benchmark script providedhere, getting these result(all with CUDA8 and cuDNN6):➜ ~ python test_pytorch_vgg19_fp16.py Titan X Pascal(Dell T630, anaconda2, pytorch 0.3.0): FP32 Iterations per second: 1.7890313980917067 FP16 Iterations per second: 1.83457665662...
smth
on P100 we dont expect FP16 to be any faster, because we disabled FP16 math on P100 (it is numerically unstable). We use simulated FP16, where storage is FP16, but compute is in FP32 (so it upconverts to FP32 before doing operations).
Nicholas_Wickman
My network outputs a 3D tensor with shape (B x C x H x W), I understand that torchvision’s make_grid utility takes a 4D tensor.If I understand right, I want each layer of B(atch) to extend into the 4th dim for make_grid. How can I do this?
smth
My network outputs a 3D tensor with shape (B x C x H x W) B,C,H,W is a 4D Tensor, that’s what make_grid wants, a batch of 3d images.
ejoebstl
Is there any way to calculate a partial derivative (for instance for the slice of a tensor) in pytorch using autograd?Background:I am attempting to compute the hessian of convolutional layer weights wrt the loss. However, computing the hessian for the complete tensor holding the weights for all convolution kernels is n...
smth
I would therefore like to calculate the hessian for each convolution kernel, which is significantly less complex. While this is mathematically less complex, the way that convolution layers are implemented in every framework is that the compute the full forward (or backward-grad / backward-weight)…
marcman411
I downloaded the PyTorch VGG16 model with batchnorm (vgg16_bn) model and inspected the state dictionary. Instead of the one extra layer after each conv layer (for the batch normalization), I see 4 extra layers. Here is the output:> sd = torch.load('vgg16_bn-6c64b313.pth') > for k in sd: > ... print sd[k].shape > ... ...
smth
batchnorm weight, batchnorm bias, batchnorm running_mean, batchnorm running_std (batchnorm has an affine transform by default)
gtm2122
Hi Pytorch community.I wanted to implement sequence classification of videos, so far I have been using a pretrained feature extractor to get a d-dimensional vector representation of a frame for all frames and pass this to an LSTM.All this while I have been using sequence length = number of frames in the video and batch...
smth
@gtm2122padding with zero is fine. The padded regions are not actually used in computation if you use pack_padded_sequence() and give the packed sequence to nn.LSTM
jpeg729
It seems really hard for people to post code that is correctly indented.Some people post screenshots of code from their editor.Some people post code where the first line(s) are not indented and so aren’t formatted.Some people add > to the first line so the whole thing looks like a quote, but then indentation doesn’t re...
smth
Fixed now. The code editor will suggest code-fences instead of indentation now. Thanks for asking to look into it
kkjh0723
I’m trying to modify my image classifier by adding decoder and reconstruction loss as autoencoder.I want to use the BCELoss which requires targets range from 0 to 1.But my classifier has input normalization at the data loader as in usual so the input range is not fitted.So I want to get it back to the original range by...
smth
y = (x - mean) / std x = (y * std) + mean Just do such an operation per-channel on your output: # assuming x and y are Batch x 3 x H x W and mean = (0.4914, 0.4822, 0.4465), std = (0.2023, 0.1994, 0.2010) x = y.new(*y.size()) x[:, 0, :, :] = y[:, 0, :, :] * std[0] + mean[0] x[:, 1, :, :] = y[:, 1…
Ujan_Deb
It seems like torchtext is a wonderful library. But its tedious to go through the code to understand how everything works. There are a few short introductions to the library on the web, but I couldn’t find an official documentation. Does a documentation exist? If not are there any plans to make one in the near future?
smth
here you go:http://torchtext.readthedocs.io/en/latest/
scitator
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.Module): def __init__(sel...
smth
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): …
antspy
Assume you have model 1 and model 2. We are in a transfer learning setting, so I want to evaluate model1 and then model2. This looks like the perfect application for nn.Sequential!Except that we want to train model1 and model2 differently (Say, we want to freeze the weights of model1). To do this we need an easy way to...
smth
this is exactly what you are supposed to be doing. shoehorning it into nn.Sequential is not a great idea, Sequential is meant to be a very simple container that’s dumb.
Eliot_Brenner
after updating using the commandconda update pytorchor uninstalling pytorch and reinstalling withconda install pytorch torchvision -c pytorchCosineSimilarity disappears from distance.py.however it appears that CosineSimilarity remains in the master branch of the source code. Anyone else experiencing this issue?torch.ut...
smth
weird. can you try: conda update -y conda conda install mkl=2018 conda install pytorch=0.3.0 -c pytorch
cphb
I have a binary classification problem with highly imbalanced data (250 negatives for every 1 positive). If I use NLLLoss (or CrossEntropyLoss), what should the class weights be?I’m also testing the custom BCE Loss function at[SOLVED] Class Weight for BCELoss.Thanks so much!
smth
they should be [1 / 250, 1] i think.
SimonW
Why are there two bias terms in RNNCell when they are pointwise added together? Wouldn’t this be equivalent to using one bias and doubling its gradient? Although I’m not sure if doubling the gradient is the desired behavior…
smth
Yes, it’d be equivalent to just learn 1 bias term. I guess it’s just convention to learn two bias terms for an Elman cell (or we just implemented it exactly as the formula says, rather than thinking this through). Here’s the relevant code that I double-checkedhttps://github.com/pytorch/pytorch/blo…
brightnesss
I’m going to installhttp://download.pytorch.org/whl/cu80/torch-0.3.0.post4-cp27-cp27mu-linux_x86_64.whlusing pip install in python2, CUDA8.0, linux, but some wrong occurs. And i’m sure my python2 is UCS4Exception:Traceback (most recent call last):File “/usr/local/lib/python2.7/dist-packages/pip/basecommand.py”, line 21...
smth
your download was incomplete. hence this error
abandon_tf
In my model’s init function, I create a GRU layer.self.gru = nn.GRU(self.global_dim, self.global_dim, 1) for param in self.gru.parameters(): if param.dim() == 2: nn.init.xavier_normal(param)When I want to use this gru in another function, like this:state = torch.zeros(1, 1, 100) ou...
smth
state has to be a Variable: state = Variable(torch.zeros(1, 1, 100))
Nicholas_Wickman
Hey all, I saw it recommended to reserve Sequential for only the most trivial networks, but I’m a big fan of the readability/simplicity and I’m trying to keep as much of my network in nn.Sequential as possible.Is there a simple way to use MaxUnpool2d layers in one Sequential block with respect to the indices from MaxPo...
smth
there isn’t at the moment
munkiti
This is in continuation of my previous postImagenet 10-crop testing examplevisionI am trying to use 10-crop testing feature of Pytorch. However, i want to store the dataloader to a pickle file for efficiency. Ten crop testing requires a lambda function and i get a traceback as follows AttributeError: Can't pickle lo...
smth
Before transforms.TenCrop(224), you have to add transforms.Scale(256), some of your images are too small to be cropped to 224
tedli
Hi there,I was trying to do an un-pooling operation on a feature map that was NOT produced by an pooling layer (say it might be a shrunken map after a ‘VALID’ convolution layer), thus I cannot pass the indices argument (which in normal is one of the outputs of pooling layer if you setreturn_indicesoption toTrue) to a ...
smth
generating the indices Tensor to your convenience (i.e. solution 1) seems like the easier path forward.
myc
Is there a way to convert the parameter nan to 0?at the same time,do not damage the backward.
smth
yes you can do: weight[weight.ne(weight)] = 0 where weight is your parameter Tensor from which you want to get rid of nans.
antspy
What is the best way to apply softmax to a tensor?Before pytorch 0.3 I used to dotorch.nn.functional.softmax(tensor).dataBut now it complains that “tensor” has to be a variable. Of course I could dotorch.nn.functional.softmax(Variable(tensor), dim=1).databut it’s pretty ugly.Is there a particular reason why softmax doe...
smth
in 0.4 there will be no difference between Variable and Tensor. Until then, sorr for the ugliness.
MichaelXin
Hi all,I try to write a C extension according to this:http://pytorch.org/tutorials/advanced/c_extension.html.Everything is OK when I do the step 1. I can generate the _ext source folder and the .so file.However, when I do the second step, something wrong happens.My code is:import torch from _ext import my_lib from torc...
smth
this seems wrong super(MyNetwork, self).__init__( add = MyAddModule(), ) Instead do: super(MyNetwork, self).__init__(): self.add = MyAddModule()
nick_debu
I wan to copy the discriminator model of DCGAN to Classification model.GitHubmartinarjovsky/WassersteinGANContribute to WassersteinGAN development by creating an account on GitHub.
smth
get the state_dict with model.state_dict(). It is a dictionary of parameters with names. Now filter the weights that you want to copy from the dictionary and you can call model.load_state_dict(my_modified_dict) on your newly constructed classification model.
Paralysis
I’m transferring a Caffe network into PyTorch. However, when I’m training the network with exactly same protocol, the training loss behaves like this:untitled987×634 20 KBThe loss increasing within each epoch and decreases when starting a new epoch. Thus forms this sawtooth-shaped loss.Two problems:The increasing of lo...
smth
i dont think this is because of momentum. It is probably because of the way new samples are selected in the dataset. PyTorch selects samples from dataset without replacement. Which means, at the beginning of a new epoch, it is likely that you saw a sample in training set that you saw at the end of…
Paralysis
I want to check the gradient in a fully-connected layer (which is a feature map) w.r.t every image in a batch. Specifically, I want to print the norm of gradient of every image at a specific layer. So I used register_hook in my code:class Net(nn.Module): def __init__(self): ... def forward(self...
smth
self.grad_norm is a list. I dont know why you are giving it to feat.register_hook(self.grad_norm). register_hook takes functions / closures / lambdas.http://pytorch.org/docs/master/autograd.html?highlight=register_hook#torch.autograd.Variable.register_hook
zazzyy
Hi everyone,I’m working on a project that requires me to have access to each step of backward propagation during the training process. Say I have a 10 layer fully connected neural net (input->fc1->fc2->…->fc10->output), and during the backward process I want something like output.backward()->fc10.backward()->fc9->backw...
smth
here’s a more precise and fuller example. What you are doing in my example is to completely avoid autograd’s automatic backward computation and manually reverse-computing the backward graph. For anyone coming here with a search, my solution is a hack, it is not good practice. it is given as an ill…
SKYHOWIE25
HiDo I need to set the batch size a factor of the total training data size? i.e. something like training_size = batch_size * n
smth
you can add drop_last=True to your DataLoader constructor, that should fix the problem. Look at documentation on what that option does.
marcman411
The question kind of speaks for itself, but I’ll try to explain a bit further…As far as I understand, generally you want a Variable to have gradient if it contains some learnable parameters. However, it is possible (and can be found in some PyTorch docs code segments) that you might want the input Variables to track th...
smth
As a very quick answer, you might want to do something likeNeural Style Transferwhere you are optimizing your input image. There are many many many other settings that you’d want to do this too.
marcman411
There ought to be a way to mark an answer as “accepted.” This is a really handy feature on the StackExchange family of sites to help quickly determine what the correct/working answer is. The discussion can still be there, but it gives the user a location to jump to for quick resolution.
smth
Looks like there’s a plugin for this nowhttps://meta.discourse.org/t/discourse-solved-accepted-answer-plugin/30155I’m adding it.