user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
JiaRu2016
eg. I have andnn.Linearwhosein_features = 500e4andout_features = 3000, so number of trainable parameters consume 55 GB (500e4 * 3000 * 4 / 1024 ** 2) memory. My single GPU has 12 GB and I have 8 GPU on one machine. How can I parallel this “atomic” built-in module on multiple gpu?
albanD
Hi, I’m afraid we don’t provide any construct to do this automatically. But you can simply create 8 different Linear that each take a subset of the input and split the input yourself and call each of these Linears and then add all the results (assuming your split on the input size here given that …
antgr
I was just watching a lecture of a great researcher and engineer who is also trax’s author.He claimed that the implementation of adam optimizer is complicated in tensorflow and keras but it is complicated also even in pytorch. He demonstrated the implementation in trax and seemed indeed quite simple.Can you point me o...
albanD
Hi, You can find the implementation inthis file. The implementation is not as simple as it could be mainly for performance reasons: it uses inplace operations and re-uses buffers as much as possible to be able to get very good speed even though it is implemented in python. But even beyond that, …
Carsten_Ditzel
Given a 4-dim tensor XX = torch.tensor([[[[0, 2]], [[1, 3]]]])of shapetorch.Size([1, 2, 1, 2])and stack, which stacks along a new dimension (here the last)Y = torch.stack((X[:, :1], X[:, 1:]), dim= -1)results in a shapeY.shape torch.Size([1, 1, 1, 2, 2])but why are the elements arranged in this way?Y tensor([[[[[0, 1],...
albanD
This is because usually, the concept of row/column correspond to the last two dimensions of a Tensor. And when you add a new dimension, what used to be rows become columns. And if you stack stuff on that new dimension, they are columns.
ttoosi
Hi,I want to change the saved input to a module that is used to calculate the gradients in the backward call.To be clear, let’s say I wantAdaptiveAveragePool2dcomputes the gradients given aninput2rather than theinputthat passed through it duringforwardcall.One would write a custom autograd function whereinput2is saved ...
albanD
Hi, I am afraid this is not really possible. This would compute the “wrong” gradients and so autograd will raise an error if you try to change the input inplace before computing the backward. For the particular case of AdaptiveAveragePool, the input value is not actually needed when you compute th…
gakadam
I want to confirm my understanding ofHooksin PyTorch.Objective: Changing incoming Neurons to the Convolution layers during inference. For simplicity, assume the neuron values will be halved.Code (showing hook only):# Define hooks class SaveOutput: def __init__(self): self.outputs = [] def __call__(self...
albanD
Hi, If you want to be able to modify the input before it is processed by your module, you need to use a forward pre hook and return the new value for the input. If you want to change the output, you can use the forward hook and return the new value that should be used from now on.
Pravesh_Koirala
Hello,I am trying to calculate loss on a function which looks like this:W is a vector of shape (314287, 300), whereas V is a vector of shape (314287, 3000)… (I am trying to learn a sparse representation).The relevant portion of my code is as follows:model = torch.optim.Adam([sparse_embeds], lr=1e-4) embeds = embeds.cud...
albanD
Hi, Have you tried to reduce the embedding size or replace Adam with SGD? The Adam optimizers will allocate a couple buffers with the same size as the weights to store all the statistics it needs. So that might be too much for your machine?
Capo_Mestre
I am trying to create a CNN-network and I follow the articlehereand I use batchnorm-layers here and there.When training my network with the batch sizes equal to 1, I get this error:Traceback (most recent call last): File "D:\Jupiter_playground\fashion_mnist_tidied.py", line 1387, in <module> main() File "D:\J...
albanD
Hi, This happens because you use a batchnorm on an input with no spacial size: An input of size (1, 40) has 40 channels only. And batchnorm compute normalization for each channel. In this case, since there is a single element, then the renormalization by the standard deviation will divide by 0 and…
Scott_Hoang
Given x, and y are one-hot vectors matrixes obtaining from Gumbel-softmax, and z = torch.max(x,y), Is z still differentiable?
albanD
Hi, Assuming that x and y are floating point gradients, then the element-wise max is differentiable yes. The gradient will flow back, for each value, to the element that was used.
SungmanHong
In python3.7 and windows10, pytorch 1.5, I saved my modeland…I loadedimport torchmodel = torch.load(‘D:\CR_DOWN\CRAFT-pytorch-master\CRAFT-pytorch-master\model_OCR.pt’)but… I got a error ofNo module named ‘torch’why I got this error??ModuleNotFoundError Traceback (most recent call last)in----> 1 m...
albanD
Hi, Did you saved that file with a different version of pytorch by any chance? Especially a more recent version than the one you use for loading?
pytorcher
I have a member tensor that is created/saved during a backward hook. Hook looks like:def saveGrad(self, grad_input, grad_output): self.currentGrad = grad_output[0].detach()This works fine on one GPU but when running on multiple it tells me 'AttributeError: (module) object has no attribute ‘currentGrad’ '. I ima...
albanD
Is it possible to resize a buffer after it has been declared? Yes, you can do .resize_(). Note that the content of the Tensor will be un-initialized though. So you need to make sure that you either zero it or write some value before using it. And additionally is it possible to add a buffer afte…
ndronen
I see inthis postwhere_VF.lstmis defined (presumably asLSTMImpl). Since it callstorch::lstm(this line), I’m trying to track downtorch::lstm. Any pointers would be much appreciated!
albanD
Hi, The torch::XXX binding is generated based on the info fromherewhich then hits the native codehere. Hope this helps.
rGure
Hey everyone,I am in the process of extending captum’s lrp implementation by some of the rules that are not in the current pull request as I need those for a project at work. Due to that I have some questions on tensor hooks:1.) It seems the invocation order of hooks on tensors is determined by the order of calling reg...
albanD
It seems the invocation order of hooks on tensors is determined by the order of calling regsiter_hook() Yes they are called in the order they were installed. Is there a way to alter the invocation order after registration? There is no official way to do this no, you will need to uninstall and…
Pepi
I am building an LSTM model for time series prediction. We start with a pandas DataFrame and load that into a TensorDataset and train the model.I have received this error a few times and have managed to fix it in the past, however this time I just cannot find the in-place operation in question so I would really appreci...
albanD
Ho I just noticed that you update self.hidden in your forward function. That means that the next iteration will depend on the previous one. I am not sure how you want to handle this. But you should either .detach() if you want to keep the updated value without having gradients flow back all the wa…
yzz
I saw torch vision use nn.ReLU(inplace=True) after a CONV layer (https://github.com/pytorch/vision/blob/1aef87d01eec2c0989458387fa04baebcc86ea7b/torchvision/models/vgg.py#L74). However, based on the description for here (Why relu(inplace=True) does not give error in official resnet.py but it gives error in my code?). I...
albanD
Convolution is a linear operation. So you can see it as (ignoring conv parameters): y = conv(x ,w). Then dL/dx = dL/dy dy/dx = conv_transpose(dL/dy, w) and dL/dw = dL/dy dy/dw = conv(x, dL/dy). These new conv with modified parameters. The way I check if the output is needed is by checkingthis fil…
udo
Could someone kindly explain the logic behind the tensor reshape below? According to what kind of rule is theb.view(3*2, 2)tensor being re-organized?import torch¬ a = torch.eye(2)¬ ...
albanD
Hi, The view operation will just change the view you look at the memory. A contiguous Tensor is stored in a row major way, meaning that the rows contain elements that are next to each other in memory. When you do view, you just read these with different size, still with rows containing elements t…
Hung_Yu_Heng
I have some problem when I implement my loss function.(In actually, I want to implement the Maximum likelihood estimation. Thus I have to maintain the forward graph and add the new forward data every time.)There is a RuntimeError about the inplace operation which may be the assign operation.Does anyone encounter the sa...
albanD
Hi, The problem I see here is that the first optimizer.step() is modifying the parameters of your network inplace. But the original values of these parameters are needed to compute the second backward. Hence the error that you see. You will have to either delay the optimizer step or redo the forw…
wangps
I follow the officialtutorialto build custom CUDA extensions. And I would like to use the functionat::cuda::blas::gemm<float>()to do the matrix product, which is defined in#include <ATen/cuda/CUDABlas.h>. But the g++ compiler seems to fail to link this function according to current configurations. Could anyone give me ...
albanD
Hi, In the extensions, you should not try to access low level functions like this one directly. You can use at::mm() or at::bmm() directly with Tensor arguments to get that result (also these function will have all the nice autograd support while low level ones won’t).
Aryan_Asadian
Hi everyone. I have created a modular model via this class:class VGG8StepBySTepModelModular(nn.Module): def __init__(self): super(VGG8StepBySTepModelModular, self).__init__() #empty_model.add_module("stage_1", vgg_8_sub_student) #empty_model.add_module("stage_2", nn.Sequential(*list(vgg_8_m...
albanD
Hi, The two are not related. The mod.train() and mod.eval() change the mod.training flag on the module (and its children). This is used to know how modules like batchnorm or dropout should behave. The requires_grad field on the Parameters tells the autograd if it should track gradients for these …
pomonam
Using functional.jvp (https://pytorch.org/docs/stable/autograd.html) and taking gradient with respect to it is 2 times slow in general and for larger networks (ResNet-20), it is 4 times slower. Are there any known issues on using JVP? Are there any methods to make it more efficient (maybe using other packages)?
albanD
Hi, As mentioned in the note on the function definition, the function uses the “double backward trick” to compute the jvp and is thus expected to be slower. We are working on changing that for 1.7.
pomonam
I have a neural network $f: \mathbb{R}^n \times \mathbb{R}^c \to \mathbb{R}^m$ and in each layer, I have $W_1 b + W_2$, where $b \in \mathbb{R}^c$ is some parameter. I would like to compute a derivative (jacobian) with respect to $b$ (e.g. $d/db f(x)$).When I try to use autograd.grad (e.g. autograd.grad(output which is...
albanD
Hi, Yes this is a limitation of AD that it only does “vector times Jacobian” product. If you want to get the full jacobian you will need to use special code. Note that if you use nightly builds of pytorch, we added thishere.
iffiX
cc@ptrblckI have a question regarding pytorch tensor memory usage, it seems that what should be functionally similar designs consumes drastically different amount ofCPUmemory, I have not tried GPU memory yet.Below are two implementations of replay buffer used in RL:Implementation 1, uses 4.094GiB memory, creates 20003 ...
albanD
Hi, The allocator I mention here is not from pytorch but from your libc (we have no control over it). These are classic CPU allocators. Famous alternatives include jemalloc or tmalloc. But I haven’t tested them myself.
jwillette
I am having trouble understanding exactly what this line means in thedocs…grad_outputs (sequence of Tensor) – The “vector” in the Jacobian-vector product. Usually gradients w.r.t. each output. None values can be specified for scalar Tensors or ones that don’t require grad. If a None value would be acceptable for all gr...
albanD
In most cases, you can do without it, but for example, you can replace: loss = l1 + 2 * l2 autograd.grad(loss, inp) by autograd.grad((l1, l2), inp, grad_outputs=(torch.ones_like(l1), 2 * torch.ones_like(l2)) Which is going to be slightly faster. Also some algorithms require you to compute x * J …
Ettore_Celozzi
Hello, I’m new to Pytorch. I’m tring to convert a code that use functions from scipy and numpy library in Pytorch in order to build a NN and execute it on the GPU.I have some convolution layers that perform the convolution between a gaussian filter and an image. Exploiting the separability of the gaussian filters I per...
albanD
I simplified your code below: import torch import torch.nn.functional as F import numpy as np img = torch.rand(1, 1, 512, 512) kx, ky = 5, 5 # Goes from 1 channel to 1 channel weight_h = torch.rand(1, 1, ky, 1) weight_w = torch.rand(1, 1, 1, kx) padx = kx // 2 pady = ky // 2 convY = F.conv2d(i…
Stihl
Can’t find the problem place.I cant find inplace problem operations. RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [1, 5]], which is output 0 of UnsqueezeBackward0, is at version 321; expected version 316 insteadhere is the forward ...
albanD
I guess each of these calls are actually modifying out inplace. But it’s value is needed by the dense(out) call? Can you try not to change out inplace and just torch.cat() your hidden layers together?
AghaRezaey
Hello allWe have developed a multilingual TTS service, and we have got several DL models to run at test time , and those models can be run in parallel because they don’t have any dependencies to each other (trying to get lower runtime, better performance)We do that on a GPUbut I ran into several problemsA simpler vers...
albanD
Note that if you spawn the processes before doing anything cuda related, you won’t see “RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the ‘spawn’ start method” even if you use fork. I am not sure why you have this behavior with spawn. B…
Valerio_Biscione
As far as I understand, PyTorch is pretty conservative in terms of what goes executed on the GPU: you need to explicitly call cuda(), otherwise they will be executed on the CPU.Is this true from the images loaded and transformed by thetorchvision.datasets? Let’s say that after having transformed the PIL image to tensor...
albanD
Hi, They will run on the CPU, unless you send them on the GPU explicitly yes. Note that in this case, you most likely don’t want to do that. Indeed the main purpose of the dataloader (with multiple workers) is to use many cpu cores to load and pre-process data on the CPU so that the GPU can be ful…
KAISER1997
Assume an image classification task using a neural net where loss function is defined as L .Consider an image x ,while performing gradient descent on the loss, the gradient of L with respect to x is dL/dx . Now about my doubt. After this I want to calculate the gradient of norm of dL/dx wrt to weights of neural net. ho...
albanD
Hi, You can do the following: x = torch.rand() output = net(x) L = crit(output, label) dLdx = autograd.grad(L, x, create_graph=True)[0] dLdx.backward() # Now you have the grads as usual in the .grad fields
nickthoukas
I’m trying to rewrite some legacy code and switch from scipy to pytorch and I’m having difficulties re-writing the spdiags and spsolve.How could I perform these operations on GPUs?A = spdiags(B.T,d,k,k) A = A + A.T + spdiags(D.T, 0, k, k) return spsolve(A, input)
albanD
Hi, I’m afraid we don’t have support for these functions on sparse Tensors. You can check thesparse docto see what is available. You can use the Dense version of these methods though if this is not too memory intensive. Also sparse operations will most likely be slower than dense ones on GPU (…
someAdjectiveNoun
I require to update grads of an intermediate tensor variable using theregister_hookmethod. Since the variable isn’t a leaf-variable, I require to add theretain_grad()method to it after which, I can use theregister_hookmethod to alter the grads.score.retain_grad() h = score.register_hook(lambda grad: grad * torch.FloatT...
albanD
Hi, I think the simplest thing to do here is to guard the register_hook() call with if score.requires_grad:. Also side note: you don’t need to call retain_grad() for the hook to work. Only if you want to be able to read the value in the .grad field on the Tensor.
Chuong_Vo
Hello!In the work that I’m doing, after the firstconv2d()layer, the output is converted to numpy array to do some processing using.detach(). During this process, the new output will be 3 times bigger and then it is converted back to the tensor to be used as a input for the nextconv2d()layer.Is there anyway of getting t...
albanD
Right. That should be significantly faster already. Using fancier function and playing with views, you might be able to narrow it down to a single call. But that shouldn’t be necessaryimport torch from torch.nn import functional as F import numpy as np image = torch.randn(1, 1, 60, 60) coor = …
Y_Y
Hi all,Suppose my my input img is processed by adding noise (noisy_img) before feed into model, when I triedgradients = autograd.grad(outputs=output, inputs=img)I can’t get the gradient. But if I usegradients = autograd.grad(outputs=output, inputs=noisy_img), it seems working without error. I set both img and noisy_img...
albanD
Hi, You should remove all the calls to Variable and that should fix it: img = img.view(img.size(0), -1) img = img.cuda().requires_grad_() noisy_img = add_noise(img)
bask0
I would like to modify an input to a forward call of a module I cannot modify usingregister_forward_pre_hook. The hook contains a forward call to another module with trainable parameters.Let’s assume we have a moduleFixModulethat we cannot modify. Also, we can’t change the inputxto the forward call, as this is done som...
albanD
Hi, The way I would do this is to add the new layer directly on the Module: def get_hook_for(mod): mod.my_linear = Linear() def hook_fn(self, input): # mod and self are the same here, so you can use any of them return (self.my_linear(input[0]), ) return hook_fn model =…
pytorcher
I have a complicated custom autograd function that requires a couple mechanisms to work, both of which are causing memory leaks. I have simplified the function to essentially do nothing and it still causes the leaks just with the other mechanisms. The simplified function is the following:class Tagger(torch.autograd.F...
albanD
In that case, if it doesn’t require gradients, I would just capture it to avoid this issue altogether: it is just a constant Tensor that the autograd doesn’t need to know about. def tagger(inp, Values): class Tagger(torch.autograd.Function): @staticmethod def forward(ctx, inp): retu…
sliorde
I want to do the following calculation:l1 = f(x.detach(), y) l1.backward() l2 = -1*f(x, y.detach()) l2.backward()wherefis some function, andxandyare tensors that require gradient. Notice thatxandymay both be the results of previous calculations which utilize shared parameters (for example, maybex=g(z)andy=g(w)wheregis ...
albanD
Ho sorry I think I misread the title of the topic and though it was an errorDoes the function f has any parameter into it? If there is nothing else in there, and the only way to get to the parameters is via x and y, I would do: x, y = g(input, params) # f must have NO parameters # Equivalent (b…
Mayank_Jha
Dear all, i am having issues with training of my feed forward NNsI have tried my best to resolve the issues but failed so far. so I come to you all for some help.Let me describe the whole code as concisrely as possible.Basically, this is an actor critic structure to find optimal control using HDP structure.There are tw...
albanD
You use .data here: def to_np(x): return x.data.cpu().numpy() You can replace it with def to_np(x): return x.detach().cpu().numpy() Also note that in both case, if you go to numpy, the autograd won’t be able to compute gradients. So no intermediary results should be done using numpy arra…
tcsn_wty
I suppose thatmodel.cuda()andmodel.to(device)are the same, but they actually gave me different running time.I have the follwoing:device = torch.device("cuda") model = model_name.from_pretrained("./my_module") # load my saved model tokenizer = tokenizer_name.from_pretrained("./my_module") # load tokenizer model.to(dev...
albanD
Hi, They do the same thing yes: send each param to the GPU one after the other. Are you sure that you don’t have something else on the machine that could be using either the GPU, the CPU or the disk and that would slow down your eval?
muammar
I am building a model that outputs a scaler, and I need to compute the gradient of those outputs with respect to their inputs. I am doing something like the following:def get_forces(outputs, coordinates): forces = [] for index, (hash, image) in enumerate(coordinates.items()): for i, coordinate in image:...
albanD
Hi, This is most likely not linked to your get_gradients() function. But more to the fact that something that you using in the loop (inputs or coordinates) already has a history (you made some operations with it while it was requiring gradients) and so this part of the graph is shared across itera…
devstorm
Greetings from India!I was referring the book: Deep Learning with PyTorch when I came across this function:from_numpyIt says in the docstring that “the returned tensor is not resizable” but when I did something like this:img = torch.from_numpy(img_arr)img.resize_(3,720,1280)It returned me a resized tensor. Can you plea...
albanD
“resizable” here does not refer to the .resize_() function. But means you can’t change the size of the underlying data container. What I guess happens here is that the size you give to .resize_() does not actually need to resize the underlying data container and so it is not an issue
Diidee
I implemented a custom layer and I’m having trouble getting the optimizer to work. I create my optimizeroptimizer = optim.SGD(net.parameters(), lr=0.01)and my training loop which consists of thisoptimizer.zero_grad() output = net(input) loss = criterion(output, target) loss.backward() optimizer.step()doesn’t update t...
albanD
Hi, How and when do you create the optimizer? Do you change the weights after creating the optimizer by any chance?
ParticularlyPythonic
I want to use a custom activation function that has a random component that gets applied to every neuron individually.If I use the standard method and call the activation function on a layer, it applies the same value to every neuron in that layer.I am looking for the most efficient way to have the activation function ...
albanD
Hi, I’m afraid the softplus function only accepts a single beta value. But you can just re-implement it batch_size = x.size(0) # Generate one beta per sample beta = torch.empty(batch_size).uniform_(self.beta_lower, self.beta_higher) softplus = ((beta * x).exp() + 1).log() / beta res = x * torch.ta…
hesana
Hello,I have a 3D-CNN which I would like to train using double precision float on my CPU.After creating the model I turn it into a double precision one using model.double() but the forward pass fails with the error:File "/opt/anaconda3/envs/ann/lib/python3.7/site-packages/torch/nn/modules/conv.py", line 480, in forward...
albanD
Hi, Did you properly convert the input to double as well by doing input = input.double()? (this is not an inplace operation on Tensors, you have to use the result).
alsuhr
Hi,I am trying to debug a network and noticed that for some reason, the outputs of a linear layer are slightly different depending on the batch size of the input tensor.Minimal working example:import torch from torch import nn torch.manual_seed(72) ll = nn.Linear(4, 8) data = torch.rand((16, 4)) print(ll(data)[0].mea...
albanD
Hi, From the point of view of floating point arithmetic, these two numbers are actually the same. We are doing some extra optimizations when the batch one is 1 leading to a different order for some accumulations. And since floating point accumulation is not associative, you see these kinds of arti…
xdwang0726
I am trying to get the main diagonal from the multiplication of two large matrices. Here is my implementation:def col_wise_mul(m1, m2): result = torch.zeros(0) for i in range(m1.shape[1]): v1 = m1[:, i, :] v2 = m2[:, i] v = torch.matmul(v1, v2).unsqueeze(1) result = torch.cat((re...
albanD
Hi, I think the best way to do this is to rewrite (assuming 2D matrices) matmul(m1, m2).diag() to (m1 * m2.t()).sum(dim=1). You can handle the extra batch dimension if you have one by just changing the the dimension you sum over.
Lusica
Hi,I got a problem when I want to get the grad for input features with a pre-trained model.The source code isH_Features = output[0].clone().detach().requires_grad_(True) V_Features = output[0].clone().detach().requires_grad_(True) print("Features:") print(H_Features.is_leaf) ...
albanD
Hi, It is expected that requires_grad=False inside the custom Function. These are built explicitly so that you specify what the backward should be. So there is no reason to track the gradients during the forward. You’re missing a return statement there btw. Why are you using a custom Function her…
Ahmed_Abdelaziz
Hi,While training my model I got NaNs as the result of loss function after many iterations. I usedanaomly_detectionto see what is causing that issue and I got that error.Function 'LogBackward' returned nan values in its 0th outputThis is the only log funtion I used in my forward pathreturn o.log()And that is a sample o...
albanD
It does, but it can only look at the backward pass. So if nans happen in the forward, they won’t be reported. You will need to add prints directly in your code to check where the nan appears. In particular, you can check your_tensor.isnan().any() ? To check that in the forward.
blackbirdbarber
emb = nn.Embedding(10, 3) print(emb.weight.shape) print(emb.weight) input = torch.LongTensor([[1,2,4,5],[4,3,2,9]]) print('input:', input.shape) embo = emb(input) print(embo.shape) print('embo:',embo)Hereis a demo code that works but I don’t understand what is 10.Since our input is torch.Size([2, 4]), output is torch.S...
albanD
Hi, Not the maximum number of elements. The maximum value in thereAs you can see, everything in there is in [0, 9]. If you try to set one value to 42, you will get an error (anything >= 10 will as it is 0-indexed).
shangguan91
import matplotlib.pyplot as plt import numpy as np plt.rcdefaults() fig, ax = plt.subplots() # Example data y_pos = np.arange(len(label_list)) performance = y3 error = np.random.rand(len(label_list)) rects3 = ax.barh(y_pos, performance, xerr=error, align='center') ax.set_yticks(y_pos) ax.set_yticklabels(label...
albanD
Hi, What is your question? Could you give more context on where you got this code from? What you’re trying to do and what is the issue?
be7f984b2f2e66ba7969
Hi,I tried to build from source of pytorch on gtx-1070ti.python setup.py build developbut found no inference speed up, the results seem to be opposite to this post (https://medium.com/repro-repo/build-pytorch-from-source-on-ubuntu-18-04-1c5556ca8fbf)any idea?
albanD
In that case you want to make sure you have the latest cuda/cudnn installed. For distributed, the gloo backend should be already properly provided. For mixed precision I think basic cuda libs handle that well. For linear algebra. You want a good blas/lapack lib on cpu like mkl or openblas. And fo…
alameer
I am getting the above warning message when running my code. I have looked at thispostto fix the issue, but that didn’t helpimport torch import torch.nn as nn class Conv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, NL='relu', same_padding=False, bn=False, dilation=1): ...
albanD
Hi, This warning appears because you’re using upsample somewhere. You should find where and replace it with interpolate if you want to get rid of the warning.
jgdo
I’m trying to port some tensorflow code to pytorch where a whole tensor is dropped out occasionally. This is done by multiplying the whole tensor with zero.If I do the same in pytorch, I get errors from autograd about an invalid inplace operation:RuntimeError: one of the variables needed for gradient computation has be...
albanD
Hi, The error mentions that you modify inplace a Tensor whole value is needed in the backward pass. In particular here, it seems that the content of context is needed. And so if you do context *= maybe_dropout (which modifies it inplace), then you can’t backward anymore. You need to make sure not…
f10w
Suppose that I have a CUDA extension with which I can define a customautogradfunction like the following:import my_cuda_extension class MyFunction(torch.autograd.Function): @staticmethod def forward(ctx, x, y): ctx.y = y return my_cuda_extension.forward(x, y) @staticmethod def ...
albanD
Hi, All the code outside the custom Function is autodiffed. And so gradient will be computed for each op you do. So all will work fine here! Note that in the custom function, you should not save inputs in the context but use ctx.save_for_backward(y) and y, = ctx.saved_tensors to avoid memory leak…
ychnh
In multi_head_attention_forward under torch.functional, there is a check to make sure the batch is the second index in the tensor. However, it calls linear() proceeding this, which requires the batch to be the first index of the input tensor. This does not seem to be correct from my understanding, please correct me if ...
albanD
Hi, Actually, Linear consider anything that is not the last dimension as batch. So this is not an issue here.
MiloKnell
I’m using triplet loss on a siamese network where each half receives a different sized input (128 and 512), how would you recommend that I compute the loss? Would expanding the 128 by copying it 4 times mess with autograd? For now I am just padding the input but I was wondering if there was a more efficient way
albanD
Both replication and padding are differentiable so no issue on the autograd side
mfkasim
I wonder how to set up an NN module whose parameters are non-leaf variables.What I would like to do is something like below:class NNTest(torch.nn.Module): def __init__(self): super(NNTest, self).__init__() self.module = torch.nn.Linear(2, 3, bias=False) def forward(self, x): return ...
albanD
You can do this by first deleting the original one and then assigning your non-leaf Tensor: del nn.module.weight nn.module.weight = d
curious
I am trying to find the value of loss for a temporary set of variables in a neural network so that I can have their gradients but I do not want these variables in the computational graph. I have a matrix of weights, I want to know their gradients but this matrix is not in the neural network’s model parameters.
albanD
If these are used during the computation of the loss in a differentiable manner, you can get: call .retain_grad() on these intermediary elements so that their .grad field will be populated when you call loss.backward(). Get the grad only for these with grads = autograd.grad(loss, interm_tensors).
ElToto
I think I found a pytorch bug but I’m not entirely certain.Before I’m writing an issue I’ll post it here.I have uploaded the sample code to google colab and the output with the error is visible in the output field. colab link hereGoogle ColabDont forget to activate the gpu in notebook settings.I am generating 4 RGB ran...
albanD
Hi, Yes there were some maxpool fixes in 1.6. The one you linked looks like the one. Hopefully you can just use 1.6 without issues now
n4tman
Hi All,I have been reading through autograd recently.Which operations I should be using in order for gradients to be correctly calculated by autograd?Thanks!
albanD
Hi, You should be using torch implementation of any function you use. All pytorch function will work. Or raise an error if you’re asking for things that are not supported/non-differentiable.
Gilles_Jack
Hi, I am trying to implement maxpool fonction from scatch (for fun) and use backward() on it.In my implementation below, the output Y of maxpool is correct (I verified it).But the gradient of the input at a zero tensor, which is wrong.code :import torch def maxpool_fp(X): pool_dim = 2 pool_stripe = 2 bs, cx...
albanD
Hi, The .item() that you use converts the result of your max into a python number. And we can’t track gradient for it. So it is ignored. You will need to remove this .item() to get proper gradients.
erfan_mhi
I was reading about different implementations of the ReLU activation function in Pytorch, and I discovered that there are three different ReLU functions in Pytorch. As I readthis post, I realized that the difference betweentorch.nn.ReLUandtorch.nn.functional.reluis more about the coding style. However, there is a third...
albanD
Hi, The short answer is none. The longer answer is that our binding code to cpp is set up so that most low level optimized functions (like relu) get bound to the torch.foo namespace. In this case, you can use torch.relu and torch.nn.functional.relu interchangeably yes.
aviasd
Hi,I am trying to understand the way torch functions.I have tried to search the docs, but though torch docs are very descriptive, I couldn’t find a concrete answer.I will write this question differently, I will write what I have understood, and I will be glad if someone will correct me.I understood that the way PyTorch...
albanD
Hi, I think all of these are pretty correct yes. Just keep in mind the distinction between autograd (that just runs the backward pass and compute gradients) and torch.nn (that is a set of utilities to work with neural nets). We actually build the graph under the hook. The only place where you c…
Haxxardoux
I have a simple implementation of a VAE, code to train is as follows;model = torch_VAE().to(device) optimizer = optim.Adam(model.parameters(), lr=vae_params.lr) for epoch in range(vae_params.no_epochs): result = train_VAE(epoch, train_loader, model, optimizer, device)train_VAE is constructed in the standard way, ...
albanD
Hi, I think that you are storing you self.convrelu as a plain list. Which prevents functions like .parameters or .cuda() to work properly. You must use nn.ModuleList() to replace this list (it will behave the same way as a regular python list).
Florian_Dietz
How do I find out what the version numbers of a Module’s Parameters are?I know that pytorch keeps track of this information, because it will raise an exception if you try to backpropagate through a graph that was based on Parameters that have been updated since.I need this because I have a pretty complex and unusual co...
albanD
Hi, You can access these with the read-only ._version attribute on Tensors. Note though that this is an internal implementation. And the absolute values might change (though equal or not equal will of course still be true).
shangguan91
i import Torch already, how come tensor is not defined.also tried from torch import tensor
albanD
That is surprising. Do you delete it later? If you have just this import and this call. This will work fine.
R0dluvan
I’m using gradient checkpointing (1.7.0.dev20200709) and I’m observing a behavior that I don’t understand.Basically, I have a code snippet in myforwardthat goesfoo = bar * bazwherebarisrequires_grad=Falseandbazisrequires_grad=True.I call this code with the same inputs first outside, then inside acheckpoint()call.In the...
albanD
Hi, When you do checkpointing, the forward is called twice. Once during the forward without tracking gradients (and so requires_grad=False) and once, during the backward, with tracking enabled to recover all the buffers.
Arale_Mononoko
Hi!I have and autoencoder, and between the coder and decoder I transform the data using torch.sign . When I do it, the backpropagation of the gradient stops in that point.If I replace torch.sign by torch.sigmoid, then I don’t have that problem and the backpropagation goes back to the beginning.Do I have to do something...
albanD
Hi, the sign function is not differentiable (or if you look at it in a differentiable manner, the gradient is 0 almost everywhere). So it is expected that you won’t be able to get gradients through it.
Shani_Gamrian
Is there an implementation in PyTorch for L2 loss? could only find L1Loss.
albanD
Hi, L2 loss is called mean square error, you can find ithere.
jwillette
I have some numerical issues and I am trying to find out if there is a bug in my calculation or not. I am using a model which samples weights and therefore I am using logsumexp over the sample dimension such as this if we assume I have a tensor of(sample_n, instances)…ll = torch.logsumexp(log_lik.sum(dim=1), dim=0) ll ...
albanD
Hi, It is actually the whole point of having a single function that does log + sum + exp, it is much more precise than doing them one after the other. The trick is to remove the maximum value from the values in the exp. You can move it out of the sum and do log(exp(max_val)) = max_val. And the onl…
Carol_Ye_Liu
In python, I can easily index a tensor using another tensor like the example below.But in C++, when I executed the following code, I got an error.auto category = torch::tensor({1,2,7,9});auto sample = torch::tensor({1,0,2,2});std::cout<<category[sample]<<std::endl;What would be the right way to do this? Thanks!
albanD
Hi, Yes we couldn’t overload the [] operator to do be the same as in python. You can check thedocfor the corresponding c++ API. I think category.index({sample}); in this case.
Carol_Ye_Liu
torch.manual_seed seems not honored in torch.randint.I ran the following program multiple times in torch 1.5.1 and got different output each time.torch.manual_seed=123torch.randint(3, 5, (3,))torch.manual_seed(123) call used to work before torch 1.4, but with torch 1.5.1 I got the following error. So I changed the cal...
albanD
Can you restart the notebook? This is most likely because above you did torch.manual_seed = 123. Doing import foo multiple times in python does not import it again, it just returns the same module.
melody_marks
In the forward method my my model, I come across a list of tensors. All of those tensors have requires_grad=True. However, when I try to obtain a tensor from this list using torch.FloatTensor(myTensorList), the requires_grad of the resulting tensor is False, which is breaking the graph for computing gradients. Will set...
albanD
Hi, It is because FloatTensor creates a brand new Tensor from raw values. You can use torch.cat(myTensorList) or torch.stack(myTensorList) to do this.
cherepashkin
NN receives images of circles with different radii at the input, the center of the circle is in the center of the picture. The task is to estimate radius of the circle, then using image generator create an image with found radius. Finally, one needs to calculate loss between input and predicted image.I understand that ...
albanD
Hi, When you do .item() on the y_pred element, you actually convert the Tensor into a python float for which we cannot track gradients. So no gradient can flow back all the way to your model. You will need to make sure center_circle_gen takes a Tensor as input and generates the output in a differ…
Hmrishav_Bandyopadhy
This question might seem to be a bit theoretical and not suited as it is not directly linked to pytorch, but please bear with me as I have been asking this about and haven’t got a reply from anywhereWe know that during backpropagation, the weight update of the last layer is calculated by calculating the derivative of t...
albanD
Hi, In pytorch, the weights are only updated when you do optimizer.step() which happens after the .backward() pass is completed. So no. In general, if you rewrite all your formulas to add a t parameter to your weights to differentiate the version before the update and the one after. You will see t…
Hao_Zhou
Hello everyone,I am writing a simple python c++ extension for Linear. But I encountered a problem:My C++ extension code is as follows:#include<vector> #include<torch/extension.h> torch::Tensor d_sigmoid(const torch::Tensor &z) { auto s = torch::sigmoid(z); return (1 - s) * s; } torch::Tensor dense_forward(co...
albanD
Hi, Are you sure that you recompiled the cpp module with the latest version? And that you don’t have a cached version with an older version of your code where the c++ module only took 2 arguments?
torchlight
Would this break the autograd? And what is the difference between doing this and using self.register_buffer
albanD
Hi, In the init of the nn.Module? No that won’t change anything from the point of view of the autograd. The benefit of having it being a buffer is that it will be moved around when you do things like model.cuda().
a_d
Is there any way we could have complex-valued tensors in PyTorch… similar to dtype.complex in tensorflow…If nit is there anyway I could implement it?
albanD
Hi, We are actually adding this right now. Complex dtypes already exist (complex64 and complex128). Basic ops are working fine. We have first draft of the autograd support with a limited set of functions right now. Note that this will be in the upcoming 1.6 release. Was there some specific feat…
pytorcher
I have some functions that require storing error values at a current layer as they are passed through. For example if the nonlinearity of a layer is sigmoid the line of code looks like:grad_output[0].detach()*(Value + sigmoidPrime(F.sigmoid(self.totalOut)))and I have a defineddef sigmoidPrime(x): return x * (1-x)I...
albanD
I’m still unsure what your goal here isBut if you want the forward and backward functions, you just need to differentiate the functions. For example, you have mse that does this in the forward: mse(x, y) = (x - y).norm(2).mean() Then you can differentiate wrt to x and do mse_backward_x(grad_ou…
Sundar_Krishna
Hi ,whatever I try to print out or displaytensor([[-0.1028, -0.0493, 0.0453, -0.0668, 0.0362, 0.1089, 0.1205, 0.0165, 0.0700, 0.0195], [-0.1050, -0.0383, 0.0408, -0.0668, 0.0474, ...
albanD
Ho right! This value tells how wide the. screen is. And the value is in characters. The usual default is 80. But if your screen is extra wide, you can increase that to use more of it. If you set it to 20, then as you saw, it will be forced to write things in column as there isn’t enough space in …
mortonjt
I’m noticing that if I runmodel.to(device), the tensors used in theforwardare not necessarily transferred over the GPU. Below is a minimal example of thisimport torch from torch.distributions import MultivariateNormal class SimpleModel(torch.nn.Module): def __init__(self, q): super(SimpleModel, self).__ini...
albanD
Hi Yes I don’t think the distribution objects are moved around by the nn.Modules. But If you want _zero_mean and _eye_covar to be moved around, you need to register them as buffers in the nn.Module.
rahul003
I understand that backward passes are serialized for a particular model with multiple loss tensors for example. But if I have independent modules can I run backward pass in parallel?
albanD
Hi, No you cannot do that at the moment I’m afraid. Can you share more about your use case and why it would be interesting for you?
mhong94
No matter what I put for batch_size, the batch_size defaults to 1. Here is my codetrain_dataset = DataLoader(dataset=dataset, batch_size=4, shuffle=True, num_workers=0)and dataset is a custom dataset as followsclass ImageDataset(data.Dataset): def _...
albanD
And what is the size of the dataset? Doesn’t it contain a single element?
vadimkantorov
How do I compute/check/understand gradients of inplace ReLU? I didclone()to bypass “a leaf Variable that requires grad has been used in an in-place operation”. Gradient should obviously be 0, but I get 1.import torch import torch.nn.functional as F # not in place x = torch.tensor([-1.0]).requires_grad_().clone() print...
albanD
Hi, Since you apply the relu inplace in the second case, x now points to the output of the relu. And so you actually do dx/dx = 1. If you do the following to have access to the gradient of the original x (before the inplace), it will work. x = torch.tensor([-1.0]).requires_grad_() x2 = x.clone() …
pizuzadan
I know that code below is thread-safe (Many modules, many threads.):void foo(const std::vector<std::shared_ptr<torch::jit::script::Module>>& modules, int idx) { torch::NoGradGuard no_grad; torch::Tensor X = torch::rand({ 1, 10, 1, 300 }); auto out = modules[idx]->forward({ X }); } void first_inference() { using na...
albanD
Hi, In general, all the objects in pytorch are thread safe to read. But are not to write into. If your Module doesn’t write into shared structure, then it should work just fine yes.
Fridolin
Hi all,I am trying to implement a U-NET. I stumbled upon a problem using MaxUnpool2d. The solution is not unique, hence, I get different solutions each time I run it.I reproduced the error here:import torch import torch.nn as nn x = torch.load("x.pt") indices = torch.load("indices.pt") unpool = nn.MaxUnpool2d(kernel_...
albanD
Hi, Yes the seeding won’t change anything for the determinism. Unfortunately, the only options I can see here is to change the pooling to avoid overlapping kernel.
tiwa
I have a model that produces logits that I sample from. When I sample, I get a sequence of one-hots.Part of my loss function involves passing this sequence into an RNN which will output a scalar. This RNN takes a batch of lists of indices, which get packed (they’re of variable length) and sent through the network, whic...
albanD
Yes that’s right. Basically, the Embedding layer cannot be plugged in in a middle of any system as it is not differentiable wrt to its inputs. It has to be the first layer.
Rocco_Fortuna
What would be the best way to make an identity matrix directly on GPU?I couldn’t find a torch.cuda.eye() factory function.I am currently simply making aFloatTensor, then filling it with zeros with.fill_(0)and finallyusingtorch.masked_scatter_()to put ones on the diagonal.Any faster/more elegant way to do this?
albanD
Hi, The eye function takes a device= argument. You can specify "cuda" there. Or provide a device object.
Ahmed_Abdelaziz
I am connecting two models, one model that extracts entities out of a document and the other uses these entities to generate a text summary. Both models are originally trained disjointly in a pipeline. I am trying to train them jointly in a way that gradients can flow all the way from the end model to the first. Howeve...
albanD
Hi, You will need to use the scores in a differentiable manner and give a differentiable input to the second network if you want gradients to be able to flow back. Note that if the inputs of the second network are integers, this most likely won’t be possible as you can’t get gradients for non-cont…
zplovekq
If i do this simply code:w=torch.tensor([1.0],requires_grad=True) w=w.cuda() #some compute l.backward() #w.grad will still be NoneTypeThen the tensor w will not be the leaf node in autograd’s graph (the w will be copybackward).The parameters in net are all initialized as “requires_grad=True”.So if i do net.cud...
albanD
Hi, When you do net.cuda(), you should do it before you give the parameters to the optimizer. And the conversion to cuda is actually not done in a differentiable manner, so the Parameters remains leaf (but now on a different device).
mahsa
Hi,I implemented my code and got good results. Is there any way to find out which seed is used for my results on server code? I didn’t set the seed manually and want to make sure I can reproduce the results.Thanks
albanD
You can check the dochere. It returns the value used to initialize the random number generator. You can also use get/set rng state (https://pytorch.org/docs/stable/torch.html#torch.get_rng_state).
shangguan91
hey, i have to install package everytime when i use colab, is there anybetter way
albanD
Hi, Google colab comes with a version of pytorch pre-installed no? If you need a special one, I’m afraid you’ll have to install it by hand yes.
iffiX
I am trying to implement a mechanism which needs to be detected when parameters are updated, there are three ways to implement it:useregister_backward_hook(problematic, it will not work sometimes, proved by experiment and statement in doc.useregister_hookon every parameter (usable, but will not be executed right after ...
albanD
Hi, You can definitely use register_hook to know when gradients are computed for a Tensor (it is executed just before the gradient is accumulated and the new value is passed as an argument). But I don’t think you will be able to have a callback every time a Tensor is modified inplace
tiwa
I’m building a model that generates sequences. Internally, the sequences are a(N,1, length, W)tensor of width-Wone-hots, but part of the loss function involves converting sequences to strings (using a dictionary) and passing them as an argument to another PyTorch neural network that returns a scalar. Furthermore, certa...
albanD
Sure something like that will work: import torch inp = torch.tensor([[[[0., 0., 1.], [0., 0., 1.], [0., 1., 0.], [0., 1., 0.], [0., 0., 1.], [0., 0., 1.], [0., 1., 0.], [0., 0., 1.], [1., 0., 0.], [0., 0., 1.…
rahul003
When I return a Long gradient, Pytorch 1.5 complains with this error that it should be a floating type.https://github.com/pytorch/pytorch/blob/54c05fa34e1fbbb5096746a8ae92e27a08116de4/torch/csrc/autograd/engine.cpp#L610However when I cast this to float gradient in Pytorch 1.2, it complains that expected Long gradient b...
albanD
Hi, Gradients for Long Tensors were never really supported. And were raising errors if used at random places. We now unified this and properly raise an error when they are created (as you cannot use them anyway) so that the user can easily pinpoint the issue.
Mohamed_Elashry
Hello,I know thatregister_buffermethod would create variable that won’t be updated during backprobagation. So It won’t be a problem if applied in-place operation on that variable. right?but when I did that it gives me the error ofRuntimeError: one of the variables needed for gradient computation has been modified by an...
albanD
Hi, When you do self.sigma_weight * self.epsilon_weight, then to compute the gradient of self.sigma_weight which is you Parameter, you need the value of self.epsilon_weight. So if you modify it inplace, after it was used in this computation, then you will see this error. The out of place version …
contraidees
Hello,I’m using PyTorch as an audodiff tool to compute the first and second derivatives of a cost function to be used in a (non-deep-learning) optimization tool (ipopt). The cost function depends about 10 parameters. I am using the newtorch.autograd.functional.jacobianandtorch.autograd.functional.hessianadded to PyTorc...
albanD
Hi, The short answer is: Pytorch is actually built in such a way that the overhead of the graph creation is low enough (compared to all the computations you do in the forward) that you can do it at every iteration. The long answer is: This is true for neural network and when each op is quite “la…
yzz
Hi,I wonder if there is any way that can directly report parameters gradient after each layer’s backward computation. Through the hook function on tensor or module, we are only able to get the intermediate results of the current layer but not the parameters’ gradient.Thanks in advance.
albanD
Yes, the hook is given the grad as the argument. Note that if you want to modify the gradient that is saved in the .grad field, you can return the new value from the hook and it will be used.
Kai_Eiji
Hi,I’m using a sparse matrix in part of my neural network and I was wondering if there is a way to get the gradients with respect to only the non zero values of a sparse matrix. If I convert the sparse matrix into a dense one, the matrix is going to be too large and it’s going to take too much time to compute the gradi...
albanD
Hi, Unfortunately, at the moment, very few of the backward formulas formulas support sparse gradientsBut you can call autograd.grad(out, inp, sparse_grad_out) to try and propagate sparse gradient in the backward pass. If you want to create them during the backward, I think a custom Function can…
Mohamed_Elashry
I am using a custom Linear Layer in Pytorch, whose job is to add noise to the network.I have checked also whether there are in-place operation but everything seems okayclass NoisyLinear(nn.Linear): def __init__(self, in_features, out_features, sigma_init=0.017, bias=True): super(NoisyLinear, self).__init__...
albanD
Hi, The call to normal_() are actually inplace. Have you tried removing those (as an experiment to see if they are the ones that are problematic?
Yuerno
Hey all. The GAN code below has been working fine for me in an older version of PyTorch that I’ve been working with for a while (1.2), but recently I updated to PyTorch 1.5, and all of a sudden it no longer runs. I’m now getting the following error:RuntimeError: one of the variables needed for gradient computation has ...
albanD
Hi, You can check the update doc for 1.5 and in particular the section about optimizers and inplace. We fixed the inplace detection for optimizer and the inplace operation that is problematic here is the optimizer.step() that changes the weights inplace. You will need to either move the .step() a…
jdhao
I find that doing the backward for each reweighted loss is much slower than accumulate the loss and then backward.
albanD
Here are three equivalent code, with different runtime/memory comsumption. Assume that you want to run sgd with a batch size of 100. (I didn’t run the code below there might be some typos, sorry in advance) 1: single batch of 100 (least runtime, more memory) # some code # Initialize dataset with…
rajcscw
Hi,I would like to initialize a zero loss tensor which will be used to accumulate losses dynamically based on some condition. Sometimes, there will not be any loss accumulation and in this case, when I backpropagate, it throws the following run time errorRuntimeError: element 0 of tensors does not require grad and does...
albanD
Ho right you can’t use it inplace… The first one is definitely best. Or use you original code and check that total_loss.requires_grad before calling backward on it.