user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
waterhorse1
Hi, I want to implement torch.autograd.Function with arbitary length of input, so here is the exampleclass my_func(torch.autograd.Function): @staticmethod def forward(ctx, x_1,x_2....,x_n):#the size of n can vary result = f(x_1,.....x_n) ctx.save_for_backward(result) return result @s...
albanD
Hi, You can use the vararg construct in python that looks like: def forward(ctx, special_arg, *all_others): And here, special_arg will contain the first arg and all_others is a tuple with all the other positional arguments that were given. Note that special_arg is just an example here and you ca…
philipturner
This thread is for carrying on any discussion from:About the mps categorympsI have proof that says otherwise. Under the “Intel UHD 630” file, I have MPS running matrix multiplications with up to 95% ALU utilization.https://github.com/philipturner/dlprimitives-mps-comparison-benchmarksEdit: I agree that further discussi...
albanD
Hi, Sorry for the inaccurate answer on the previous post. After some more digging, you are absolutely right that this is supported in theory. The reason why we disable it is because while doing experiments, we observed that these GPUs are not very powerful for most users and most are better off u…
Tiffany_Zhao
I want to implement this function: x / ( 1 - e^(-x )). However, after I’ve done that, all of my loss became nan. I don’t know what happen to meand here is my code:class MyAttn(nn.Module): def __init__(self, channel, reduction=16): super(MyAttn, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1...
albanD
Hi, exp will no break the graph. But given the function, if x is 0 then you will end up dividing by 0 and will get bad numbers. Can you check that this is not the cause of your problem?
pannous
This simple pytorch hello world script (xor_torch.py) does not converge with mps:gist.github.comhttps://gist.github.com/pannous/1b820d6dc4ba434910ac513609b024acxor_torch.py#!/usr/bin/env python import torch import torch.nn as nn import numpy as np device = torch.device("mps") # factor 100 slower AND erroneous !?!? dev...
albanD
Hi! I am afraid the speed difference will be true for any GPU-like device you use. There is a small overhead related to using such hardware and so if your model is very small, that overhead is going to make the whole program a lot slower. There is indeed an issue in the initialization sorry about …
maqboolurrahim
Hi Pytorch,Great work everybody to bringPytorchto Mac M1s! I am working on a text classification problem.I installed a nightly version of Pytorch to usempsbackend. However, I can only install the version0.12.0oftorchtextand which throws the error ofImportError: Symbol not foundI believe it is because of the version mis...
albanD
Hi, Thanks for the report! This is indeed “expected” today: domain libraries do not provided nightly builds for arm. So you are getting the latest released version which is not binary compatible with a nightly version of torch. As of right now, you can build torchtext from source to solve this. W…
dmack
Hi,I’m trying to pass ParameterList to the forward and backward pass to torch.autograd.Function, however the error as returned to me asks for a Variable.As some example code let’s borrow and adjust some code fromthe documentationto replicate the behavior:import torch from torch.autograd import Function from numpy impor...
albanD
As mentioned on a github issue. It is expected. autograd.Function never open up data structures.
ocanevet
Hi all,I am facing an issue when training an autoencoder on CPU (I am designing a lab for students to be made on a platform with no GPU, but the problem I will describe does not happen on GPU).After some point, the time of an epoch starts increasing a lot. I provide a minimal working example code to reproduce the issue...
albanD
Hi, Could you try adding torch.set_flush_denormal(True) at the top of your script to see if that fixes the issue?
treadmill
Trying to optimize a custom defined function “copt2” in pytorch using standard optimizers. I got an error when trying to use Rprop so I switched to Adam. Adam optimizer will run but the objective is not decreasing and after checking the gradient is not being defined it seems. What is the cause of this? Is it the max fu...
albanD
Why do you do x = torch.tensor(x/norm, requires_grad=True) ? This will create a brand new tensor that is unrelated to the given input. That would be the part that breaks the gradient propagation. You should just do x = x / norm.
Sentient07
Hello.Given a function $ R^{3} \mapsto R^{3} $ implemented aspoint-wiseMLPs, what is the most efficient way of computing the Jacobian matrix?In my case, my input and output are of shape(B, N, 3)and the desired Jacobian matrix would be of shape(B, N, 3, 3)as the feedforward function is applied point-wise. I firstviewas(...
albanD
I meant diagonal in a generalized way here. But yes, the summation gives you what you want as all the off-diagonal elements will be 0. Under that assumption, you can indeed do things in a faster way. I think the simplest is to expand your parameters to have a batch dimension. And do a regular backw…
drydenwiebe
Hello,I have a quick question about how tensor elements are accessed.What would be the difference between:c = x[a][b]and:c = x[a, b]Does the first way create an intermediate tensor and then index that? Or are these functionally identical?Thanks!
albanD
Hi, Assuming both a and b are integers: Yes the first one uses the method to index a single dimension twice with a temporary Tensor in the middle. The second one calls the general indexing method that will handle this call in one go. If they are Tensors or iterables, the story is a bit different…
HaFred
My problem is best illustrated with an example.I wrapped theautograd.Functionclass into theuniformfunction and used it in the forward function oftarget_fnclass, which works fine as below.def uniform(k): class qfn(torch.autograd.Function): @staticmethod def forward(ctx, input): ... return out ...
albanD
Yes that does work on my end. You should double check your code to make sure you don’t have an old version of the custom Function around.
basingse
I recently got to know aboutregister_bcakward_hookandregister_forward_hookfornn.Module.I have some queries aboutregister_backward_hook. This is the sample code I am usingclass Model(nn.Module): def __init__(self): super(Model, self).__init__() self.fc1 = nn.Linear(3, 4) self.relu1 = nn.ReLU(...
albanD
Hi, Unfortunately the Module backward hooks have been broken forever for such “complex” model. If you’re using a recent version of pytorch, you can use the “full” versionsModule — PyTorch 1.9.0 documentationthat will have the expected behavior.
anlytix
In theautograd tutorialin the 60 minute blitz, the vector jacobian product calculation seems to miss a constant factor (m) on the right hand side (for example, in the first product, there are m equal terms of dl/dx1, that add to m.dl/dx1 - not just dl.dx1:Screen Shot 2020-05-03 at 9.34.45 PM884×296 9.79 KBIs there some...
albanD
All we’re doing here is doing an abuse of notation. You should say that dl/dyi * dyi/dx = dl/dx_i where the _i signifies that this only considers the contribution from y_i. If we write things down: You have a function Y = f(X). And we are given for every entry in Y, a gradient wrt a loss dl/dyi. …
blade
I’m trying to access model parameters using the internal._parametersmethod. When I define the model as below, I get model parameters without any issuemodel = nn.Linear(10, 10) print(model._parameters)However, when I use this method to get parameters of a model defined as a class, I get an emptyOrderedDict().class MyMod...
albanD
This is indeed unrelated. If you enable anomaly mode, you will see that the problem is that some of the params are saved for backward but modified inplace. The fix is to make sure they are not: for i in range(epochs): model.train() train_loss = 0 params = dict(model.named_parameters())…
Maxwell_Albert
Now here is a distributed computing problem.I write this function for communication between GPUsclass RemoteReceive(autograd.Function): @staticmethod def forward(ctx, input:torch.tensor = torch.tensor(1.0),from_rank:int = 0): dim = torch.tensor(1.0) dist.recv(dim,from_rank) size = torch....
albanD
Hi, The backward that you implement is not the same as the one that gets called. The one you write will only work with gradients. You can solve this by simply passing both the from_rank and to_rank to the apply (and so take both as input for your forward). And in your forward save anything that y…
kasra_sehat
i want to implement a deep network like resnet. i want to prepare a block of conv and linear layers that are repeated through the code. i believe the name of layers will result in issues on backprop and training process because of repeatation of layers names. is it true? if yes, so what is the soloution? how can i crea...
albanD
Hi, No naming of your variable will be a problem for autograd. Autograd works “below” torch.nn so you can set up your network whichever way you want and it will work just fine.
lingvisa
I have 4 gpu and 3 are being used, but the 3rd one is empty, so I want to use it, as shown below:Screen Shot 2021-10-21 at 10.39.09 PM1168×548 158 KBThen in my script, I have:device = torch.device("cuda:3" if torch.cuda.is_available() else "cpu")However, this gives me a weird error message:RuntimeError: CUDA error: inv...
albanD
From nvidia-smi screenshot, you can see that there are 4 GPUs, however, the torch.cuda.device_count()=3, If you still have the CUDA_VISIBLE_DEVICES that hides the 4th GPU that is expected. Keep in mind that nvidia-smi does NOT respect this env variable and will always show you all the devices. T…
Yuki-11
I am trying to create a module class that inherits from two classes as follows:from torch import nn class Module1(nn.Module): def __init__(self): nn.Module.__init__(self) self.l1_loss = nn.L1Loss() class Module2(nn.Module): def __init__(self, damy): nn.Module.__init__(self) self.damy = damy ...
albanD
A simple fix in your particular case is just to do Module12(Module2, Module1) to make the order go to Mod2 first and then Mod1: from torch import nn class Module1(nn.Module): def __init__(self): print("Mod1 entry") super().__init__() print("Mod1 after super") se…
cbd
I have list “c=[[1, 2], [6, 7]]”. I want element wise sum of list(0) and list(1) such that output is“out=[7,9]”.
albanD
Hi, Are you asking in python in general or using pytorch? Using PyTorch, you can simply do torch.tensor(your_list).sum(1).
emanuelnk
I am using autograd in order to get a derivative of the output w.r.t the input features, using the following code:torch.autograd.grad( outputs=pred, inputs=input, allow_unused=True, retain_graph=True, create_graph=True)[0])I had to se...
albanD
The requires_grad_() call is not retro-active. You need to set the requires_grad field before you do computetation with the Tensor. In this case, before you evaluate the model.
AlphaBetaGamma96
Hi@albanD,Thank you for the quick response! So, I’ve checked the shapes of theforwardandbackwardmethods in my custom Autograd Function, and they’re the same shape of[1, 4, 4].I did have a look at the library torchviz to compare betweentorch.detand mycustom_detfunction. Mycustom_detfunction seems to add in a Tensor of s...
albanD
Ho if one has 1 as batch and the other B, then it will broadcast which is not what you want to do here for sure. This is most likely the issue indeed.
wyg1997
Hi, I have a question how inplace sin could use output_value to calculate input_grad?As the function: y = sin(x),x_grad = grad * sign * sqrt(1 - sin^2(x)). But we don’t know that the sign is positive or negative.It looked as though it must save the value of original x tensor. But it can’t save memory in this way.Can we...
albanD
Hi, I am afraid you can’t no. You have to save something of the size of the input. (either the sign or the input itself). So in core, we save a clone of the input.
Tessa_van_der_Heiden
Hi all,I’d like to compute the second derivative of the loss w.r.t. a model (nn.module), but I cannot do this:params = torch.cat([p.flatten() for p in policy.parameters()], dim=0) for i in range(200): y = get_expected_return(policy) grad = torch.autograd.grad(y, params, create_graph=True)[0] with torch.no_grad(...
albanD
Is this correct? Yes that looks correct. In my code, where am I computing right upper and left lower elements? You are computing the whole thing. You have two loops over the params creating a full size n x n matrix.
mrityu
Hello All,I have just started learning this awesome tool called PyTorch but sadly I am stuck in an equivocal situation.Below is a code snippet from one of the tutorialswith torch.no_grad(): weights -= weights.grad * lr bias -= bias.grad * lr weights.grad.zero_() bias.grad.zero_()I am kind of...
albanD
Hi, It is illegal because it would mean that the weight update would be done in a differentiable manner. So that means that in the next iteration, when computing the gradients, it will flow back through multiple iterations of your training loop which is most likely not what you want to do !
nateanl
I have a matrix of dimension (…, N, N). I usetorch.linalg.eigto get the eigenvalues and eigenvectors. How to select the eigenvector which has the largest eigenvalue?Sample code here:m = torch.rand(2, 100, 8, 8, dtype=torch.cdouble) w, v = torch.linalg.eig(m) _, indices = torch.sort(w.abs(), dim=-1, descending=True) v_m...
albanD
Hi, You can use gather with expanded indices: import torch seconds_in_a_day = 24 * 60 * 60 seconds_im = torch.rand(2, 100, 8, 8, dtype=torch.cdouble) w, v = torch.linalg.eig(seconds_im) _, indices = torch.max(w.abs(), dim=-1, keepdim=True) print(indices.size()) print(v.size()) v_max = v.gather(-1,…
numpee
Hi,I’ve noticed something peculiar when using PyTorch backward hook functions. Perhaps this was designed so on purpose, but it makes using backward hooks a bit unintuitive.First off, a backward hook function would look something like this:def hook_fn(module, inputs, outputs): # something herewhere the function’s pa...
albanD
Hi, Are you using Module.register_backward_hook()? If so, this is a known issue and if you check the latest doc, they have been deprecated in favor of Module.register_full_backward_hook() that has the exact same API and doc (but actually do what the doc says they’re supposed to do).
TomerF
Hello,I consider a model consists of 3 fully-connected layers: Layer1, Layer2 and Layer3.In addition, I would like to minimize 2 losses: LossAll and LossPartial.Regarding to LossAll, I would like to update the weights of all layers.Regarding to LossPartial, I would like to update the weights of Layer1 and Layer3 only. ...
albanD
Yes it isThat should work as you expect.
eduardo4jesus
I am looking at thedocumentation pagefor the definition ofat::_fft_r2c. In that page it says theat::_fft_r2cis defined in theFunction.hfile. Where is this file located? I can’t find it.
albanD
Hi, This file is automatically generated during compilation. The specifications of these generated files can be found here:pytorch/native_functions.yaml at master · pytorch/pytorch · GitHubAnd from there, you can see which function is being called on CPU, CUDA, etc
Mathieu_Grosso
I’m trying to convert CNN model code from Keras to Pytorch.here is the original keras model: it comes from this article: " Squeeze-and-Excitation Networks"def se_block(in_block, ch, ratio=16): x = GlobalAveragePooling2D()(in_block) x = Dense(ch//ratio, activation='relu')(x) x = Dense(ch, activation='sigmoid...
albanD
Hi, That looks good. Aren’t you missing the last multiply though? If you you might want to modify your forward to keep a reference to the input and return input * x.
cpsanders
If I want a network’s parameters, I can easily throw them into a list usingparams = list(network.parameters())Is there an easy way to do this for the gradients of the network parameters? I know each gradient can be accessed usinggrad = param.grad, but storing all these gradients in an array requires me to iterate over ...
albanD
Hi, You can use grads = autograd.grad(loss, network.parameters()) and it will return to you a list of all the gradients. If you already did a .backward() that populated the .grad fields, you can do grads = [p.grad for p in network.parameters()] as well.
schaefertim
I’d like to updateBackPACKfromregister_backward_hooktoregister_full_backward_hook. However, this changes the forward hook registered withregister_forward_hook.Expected/old behaviour:In the forward hook, the argumentinput[0]of the succeeding module is identical with the argumentoutputof the preceding module.New behaviou...
albanD
Ho sorry, I missed this. Is this the intended behaviour? It is expected yes that they are different python objects. That being said, they are exactly the same Tensor (same content). So they do have different “id” but you can use one or the other as they contain the exact same thing
Bled_Clement
Ok so I create a class and within the init I define some conv blocks (which are also classes). For example:class WienerFilter(nn.Module): def __init__(self): super(WienerFilter, self).__init__() self.relu = nn.ReLU() self.relu2 = nn.LeakyReLU() self.bn = nn.BatchNorm2d(1) se...
albanD
Hi, Everytime you instantiate the class WienerFilter() it will call the __init__ function and thus create a new set of Paramters.
IricsDo
I have two code with difference pytorch versionIn torch 1.0.0torch.randn(4, 4).view(-1)>0. The result of this is tensor([0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1], dtype=torch.uint8)In torch 1.7.1torch.randn(4, 4).view(-1)>0. The result of this is tensor([ True, True, False, False, False, True, False, True, False...
albanD
Hi, This is expected yes. Comparison operations now return the new boolean dtype instead of the old uint8 dtype. This should not be a problem as both can be used for masking and regular ops. But the using uint8 as a boolean is deprecated an will be removed in the future.
Amr_Elsersy
I am trying to convert a tensor to numpy array using numpy() functionit is very slow ( takes 50 ms !)semantic = semantic.cpu().numpy()semantic is a tensor of size “torch.Size([512, 1024])” and it’s device is cuda:0
albanD
Hi, I think the slow part is the .cpu() here, not the .numpy(). Sending the Tensor to the CPU requires to sync with the GPU (if there are outstanding computations, that will be extra slow, make sure to torch.cuda.synchronize() before timing) and copy the memory to ram. The numpy conversion itsel…
Superklez
So I have an input tensor with shape[16, 1, 125, 256]and a selector tensor with shape[124, 2]. Is there any PyTorch equivalent oftf.gather(input, selector, axis=2)? To begin with, how does Tensorflow handle both tensors despite not having the same number of dimensions (unliketorch.gatherwherein they must be equal)? Fur...
albanD
It’s still not 100% clear to me what this does. But I guess that would work: dim = 2 new_size = inp.size()[:dim] + selector.size() + inp.size()[dim+1:] out = inp.index_select(selector.view(-1), dim=dim) out.view(new_size)
phantom90
Hi there,Suppose we are using a forward hook to analyze a mid layer:class Hook(): def __init__(self,m): self.hook = m.register_forward_hook(self.hook_func) def hook_func(self,m,i,o): self.stored = o.detach().clone() def __enter__(self, *args): return self def __exit__(self, *args): ...
albanD
Hi, If you use .detach() in the hook, then no the graph will not be kept. But if you don’t do that, then yes, the Tensors will require gradients just like the ones in the forward and you can do whatever you want there
cbd
In below code, why the gradient prints number of times as epoch is increase?import torch import torch.nn as nn class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.w=torch.nn.Parameter(torch.ones([2,2])) def forward(self, x): out= x * self.w ...
albanD
Your Tensor self.w is defined once during the init and then re-used for every forward in the forward method. So if you add a hook to that Tensor, it will be taken into account at every forward as the Tensor is re-used at every forward. In your code above, if you register the hook on out you won’t …
pierremrg
Hi all,I have developed a tracking system which operates on video. I also have strong constraints about embeddability (my code needs to run on small cards/CPUs) and the tracker must be real time. Thus, I spend a lot of time to optimize my code, using torch functions and doing as many operations as possible on GPU.But t...
albanD
c is not a Tensor here but a python number. And as such it will be on the CPU. For you other questions: .float() makes a full copy if the given Tensor is not of floating type, otherwise it returns the input as-is All operations on GPU Tensors will happen on GPU. + or add() are the same thing so …
cbd
Below is the output and its code. I want to change the gradient during the backward pass. For example out1.grad[0][0] is -22 which i want to modify it to 50 manually.output and loss is tensor([8., 8.], grad_fn=<MulBackward0>) tensor(386.5000, grad_fn=<MseLossBackward>) tensor([-22., -17.]) output and loss is tensor(...
albanD
Defining my_hook on the class will make it a class method. And so you need to specify it as self.my_hook. Otherwise you can put it inline in the function: import torch import torch.nn as nn class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self…
Muhammad4hmed
I am getting above mentioned error, my pytorch version is'1.7.0'
albanD
You can check the doc for 1.7.0https://pytorch.org/docs/1.7.0/search.html?q=gaussiannllloss&check_keywords=yes&area=defaultthis module did not exist back then. You will need to use 1.8+ to be able to use that:Search — PyTorch 1.8.1 documentation
Naruto-Sasuke
Is there any way to see the gpu memory usage in pytorch code?
albanD
You also have all the functions to get the memory allocated and the memory actually used by tensors. See thedoc herefor more details.
Hanxiong_Chen
I have one vector and one 2-D vector. Say embed1= [1, 2, 3] shape is (3) and embed2=[[1, 2, 3], [4,5,6], [7,8,9]] shape is (3, 3). Now I want to expand embed1 to [[1, 2, 3], [1, 2, 3], [1, 2, 3]] so that I can do torch.cat() to concatenate embed1 with embed2 and send them to a MLP. Actually this is to avoid of doing fo...
albanD
Hi, Backprop-wise, they will give the exact same result. The difference is that if the original dimension you want to expand is of size 1, you can use torch.expand() to do it without using extra memory. If the dimension you want to expand is of size more than 1, then you actually want to repeat w…
seyeeet
is there a way to check the model and know where the hooks are located?
albanD
Not sure noMaybe you have a big library that has some hooks that you want to remove but you don’t know who added them. haha Both for Tensors and Modules there are no public API to know if there are hooks on them I’m afraid. But currently (version 1.8), you can check: Global Module hooks via `t…
PersonalFinance004
I’m trying to run a single test frompytorch/test/with pytest.I typepy.test test_vmap.py -k test_tracein the shell to execute the testtest_trace()fromtest_vmap.py.It says ‘1 skipped’, so I assume the behavior of trace is not properly tested because of the skipped test. How can I fix this, respectively what do I need to ...
albanD
Hi, Usually when a test is skipped, it is because it should not run. Either because you don’t have the hardware to run it, or it is a special kind of test (like slow tests that only run if you ask for them as they are… slow), or things that we know is not supported but it is ok. This case falls in…
Jiansong_Zhang
This is my Network structure:class Generator(nn.Module): def __init__(self, latent_size=128): # 128 << 784 = 28*28 super().__init__() self.latent_size = latent_size self.inputlayer = nn.Sequential( nn.Linear(latent_size, 25), nn.Tanh(), ) self.hidden1 ...
albanD
Hi, data_gen.parameters() returns a generator. So you most likely want to do something like: list(dat_gen.paramters()) + [Z,]
kavka
I was trying to .backward() a loss like following.model = model(2,2,1,2) #suppose model is just a linear model with 2 input, 2 neuron in 1 hidden layer, 1 output x = torch.Tensor([[0.3,0.52],[-0.1,0.2]]) 'this part try to calculate the second derivative with respect to g' g = x.clone() g.requires_grad = True UF = mode...
albanD
Hi, There are two things: create_graph=True means that you want the graph to be created while doing the backward so that the gradients have requires_grad=True. retain_graph=True means that you don’t want the graph to be deleted because you want to call backward on it again. Note that create_grap…
moutan
For my purposes, I want only a specific set of weights in Conv2D kernels to update for a batch. Lets say for kernel w/ dimensions(40,C_In,k,k)I want batch 1 to cause the update of only kernel weights[0: 20] and batch 2 to cause the update of kernel weights[20:]. For this , I define the following hooks:def hook_batch_1 ...
albanD
Thanks for the clarification. However,when the new hook is set, the weights that get updated are still the ones that hook_batch_1 defined one thing that can cause this is that some optimizer (adam, sgd with momentum, etc) actually still update the weights when the gradients are full of 0s. Becau…
Niels_PyTorch
Hi,I’d like to train only several rows of a linear layer (the linear layer is a classification head on top of BERT for multi-label classification, and I’d like to only train the head further for 10 labels). I tried the following:model.classifier.weight[other_labels_indices,:].requires_grad = False model.classifier.bias...
albanD
Hi, I am afraid you won’t be able to do that. The “requires_grad” property is associated with the whole Tensor. And cannot be set for subsets. You have a few approaches here: Compute the gradient for the full layer and then zero-out the gradients before doing the optimizer update If your optimi…
Hari_Krishnan
In the below code i am converting the input data into embedings using a pre-trained BERT model. Since I only require the pooler output which is a vector of length 768 and performing a loop throughout the data and concatenate it into thepassage_vectorstensor. But this causes the memory to run out after 15-20 data points...
albanD
Hi, If you do this on Tensors that require gradients, the autograd state might take quite a bit of memory as all the intermediary result might be saved (you go from linear to quadratic). Also why do you concatenate inside the loop? Why not just append to the list inside the loop and concatenate on…
f10w
Hello,I would like to ask for your help on making a vectorized version of the following simple operation.I have a 3D tensorxof shape(N, B, V)and I would like to get the elements ofxat indices given by two(N, K)tensorsidx1andidx2as follows:y[i, j] = x[i, idx1[i,j], idx2[i,j]].Using a for loop, this can be done using the...
albanD
Hi, Otherwise, you can linearize the two dimensions into one and then use gather like this: import torch def f(x, idx1, idx2): """Compute using for loop x: N x B x V idx1: N x K matrix where idx1[i, j] is between [0, B) idx2: N x K matrix where idx2[i, j] is between [0…
Prasad_Raghavendra
I am trying to write code for simple objective: I have usual PyTorch gradients, I make a copy of these gradients and add some noise to it. For each batch, I check the loss for the original gradients and I check the loss for the new gradients. I pick the gradients that gives me lower loss values.While I alter gradients,...
albanD
That is not true. To get a Tensor from a numpy array, you can do t = torch.from_numpy(your_numpy_array). A nn.Parameter is a thin wrapper around Tensor that has special meaning in the torch.nn library. Namely it is a parameter of a Module and so will be returned by mod.parameters() call. But, h…
spnova12
When i test my model, do I have to use model.eval() even though I am using 'with torch.no_grad() ?
albanD
Hi, These two have different goals: model.eval() will notify all your layers that you are in eval mode, that way, batchnorm or dropout layers will work in eval mode instead of training mode. torch.no_grad() impacts the autograd engine and deactivate it. It will reduce memory usage and speed up …
dirkDB
Hi everyone,I created a small benchmark to compare different options we have for a larger software project. In this benchmark I implemented the same algorithm in numpy/cupy, pytorch and native cpp/cuda. The benchmark is attached below.In all tests numpy was significantly faster than pytorch. Is there any reason for thi...
albanD
Yes, if you find individual ops that are slower than they should be, you should open an issue for each op with the corresponding benchmark code and result. That way, we can discuss what should be done for each op independently of the others.
Ilya_Kotlov
Hi.I try to adapt code which was written on pytorch 0.4.0 to a later version of torch 1.7.1,And in the old code I had:grad_target = (output_cl * label).sum() grad_target.backward(gradient=label * output_cl, retain_graph=True)But in my new pytorch version it complains about the fact that grad_target has dimensio...
albanD
Hi, In 99.9% of the cases, the output loss is scalar and so what you want here is a single 1 (which is the default value) as this will compute the full gradient of your function. If there is more than one output, then there is no natural value to set so it has to be provided by the user. Then the…
autoencoder
I have a (178741, 304) dataset where the first dimension correponds to one sample and the second dimension are the features of a sample. The means of the features range between -0.75 and 0.99 and I want to normalize the dataset so that the mean is 0.0 afterwards.x = the dataset x_mean = x.mean(axis=0) print("Before", x...
albanD
Hi, I’m afraid it is indeed a problem of numerical precision of floating point numbersThe problem here is mostly that the dimension you reduce over (178741) is big enough that all the very small errors made by each individual op build up to something that is visible at the end. Also keep in mind…
Mriganka_Nath
I am trying to put all my model’s output in an array, though I am using it in eval mode,computing the outputwith torch.no_grad():and detaching it the array is showinggrad_fn=<SelectBackward>My codem.eval() # m is my model for vec,ind in loaderx: with torch.no_grad(): opp,_,_ = m(vec) opp = opp.det...
albanD
Hi, The detach() in the no_grad block is not needed. You will need to move all the ops into the no_grad block though to make sure no gradient is tracked
ConnollyLeon
Will Torch free the gpu memory of activation values of a specific layer after its backward has done? Since the activation values are no more needed after calculating gradients.
albanD
Hey, Each “Node” in the graph implements a special functions to release all the resources it can here:pytorch/function.h at a46d56f988505547b0779838a022970b79123b3c · pytorch/pytorch · GitHubThis is called from the execution engine when retain_graph=False here:pytorch/engine.cpp at a46d56f98850…
scheon
Hello, I’m a student studying low power memory circuits / in-memory computing, and I’m trying to bring multiplication-accumulation(MAC) operation into SRAM array so most/all of convolution can be done inside memory array.Since computation inside SRAM cannot handle full precision operation like GPU, i’m trying to cut th...
albanD
Hi, This post was trying to do the same thing you do I think and the same answer applies to your code if I’m not mistaken:Make Custom Conv2d Layer efficient (wrt speed and memory)
seongmin
Hi,Let L be the result of a loss function before reduction, possibly with NaN values.I expectedtorch.nansum(L)to accumulate non-NaN values from L so that.backward()would result in valid gradient.However, my expectation does not match the result.Here is a snippet to reproduce the problem.def test(): import torch ...
albanD
Hi, You can use tensor.register_hook(your_fn) to be able to print the gradient for each given Tensor. In particular, here, I think that the loss before the nansum won’t have any nan as you expect. The problem is that the backward of the mse will create nan values because some of the y has nan. Yo…
Idriss_Mghabbar
Hello,I am using pre-trained models on imagenet to build custom video classification models.In the first phase, we compute the forward on every frame:outputs = [] for i in range(n_frames): outputs.append(pretrained_model(video[i])Given that “outputs” is updated at each iteration, this loop results in a nested comp...
albanD
Ideally, I want to tell PyTorch to use the same computational graph of the first frame for the next frames as it does not change. The thing is that what takes memory is not the graph itself, but the intermediary buffers that are needed to do the backward. And these buffers are different for each …
omarfoq
I am training multiple models in a sequential way on the same GPU, and I need them to share the parameters after a given number of iterations. For GPU sonsumption optimization I need to free the gradients of each model at the end of each optimizer iteration. A simple solution is to set all gradients to None manually, i...
albanD
Hi, Depending on the particular model and training loop, it may improve perf and not. Note that a simpler way to do this is via the regular zero grad: model.zero_grad(set_to_none=True).
AbishekBashyal
According to the docs, when we call the backward function to the tensor if the tensor is non-scalar (i.e. its data has more than one element) and requires gradient, the function additionally requires specifyinggradient.import torch a = torch.tensor([10.,10.],requires_grad=True) b = torch.tensor([20.,20.],requires_grad=...
albanD
Hi, If you consider a function f that has n_input and n_output. And a Jacobian matrix containing all its partial derivatives J_f of size (n_output x n_input). Then what backpropagation (or AD whichever way you want to name it) does is to compute v^T J_f for a given v. If your function has a singl…
AbishekBashyal
I was reading theOptional Reading: Tensor Gradients and Jacobian Productssection ofthis blogand it stated:In many cases, we have a scalar loss function, and we need to compute the gradient with respect to some parameters. However, there are cases when the output function is an arbitrary tensor. In this case, PyTorch al...
albanD
Hi, The idea is that it always does a vector Jacobian product. It just happens that when the output is scalar, it is 1D and so the vector is of size 1 and can be replaced with just the value 1. that will give you the full jacobian (and thus gradients).
111491
For some reason I need to call loss.backward() to tarin a special parameter in the middle layer of my model, but for the sake of saving calculation expenses I don’t want the backpropagation to continue once I get the gradient for my parameter, otherwise I’ll run out of my kaggle-GPU free usage. So is there any way toma...
albanD
Hi, You can use autograd.grad(loss, input) and it will return gradients for that input and only perform the necessary computations to get that value. If you prefer for the .grad fields to be populated, you can use loss.backward(inputs=input).
nalbwa
Hi, at some part of my project, copy_() operation struggled me a bit,thus I tried to make a toy example as below but could not find a solution for it.import torch class A(): def __init__(self): self.tensor = torch.zeros((5, 6), dtype=torch.float) def check(self, b): self.tensor[[2, 4]].copy_(b...
albanD
Hi, The problem is that advanced indexing like [[2, 4]] does not always return a view into the original Tensor. It sometimes returns a different Tensor. And so when you do tensor[[2, 4]].copy_(b.tensor), you actually do the copy into a Tensor that is completely independent of tensor. For this to w…
s_n
I have observed that batch normalization parameters such asrunning meanandrunning statsget update after we do the forward pass through the model ( as in just after we dooutput=model(input)).So when we train the model and do the evaluation after every epoch is it recommended to put the model in eval mode and then do the...
albanD
Hi, When using batchnorm in training mode, the running stats are always updated yes. You should be using the eval mode to use these stats and stop updating them when evaluating indeed.
mel
I want to increase specific indices in a tensor by 10%.I have a tensorx = torch.randint(-2,2,[4,3]) tensor([[-2, 0, 1], [-2, 1, -2], [ 0, 0, -1], [ 0, -1, 1]])and the following indicesindices = torch.tensor([[0,0,1],[2,1,1]])I want to increase the values by 10% on the indices above, so tha...
albanD
Ho in that case you can do: vals = x[indices[0], indices[1]] updated_vals = vals + vals.abs() * 1.1 x[indices[0], indices[1]] = vals
zzzf
I’m using PyTorch for auto-grad without any neural network involved.I’m unable to provide a reproducible code otherwise it will be too many lines. From a high level, it looks like the following:class MarkovModel(nn.module): def __init__(self): super(MarkovModel, self).__init__() self.potentials = nn...
albanD
Hi, What this error means is that some part of the graph is shared between iteration. This is most likely due to the fact that you pre-compute something outside of the for loop and re-use it at each iteration inside. If you want gradients flowing throw these computations, you should move them insi…
huangdi
Hi, all.I’ve meet a speed problem when allocating temp memory in cpp/cuda extension.I’m writing an cuda operator, which needstemp memoryduring gpu computing. However, after measuring the speed of the operator, I found that the slowest part in the operator is the allocation of the temp memory. Moreover, allocating it in...
albanD
Hi, Which time library are you using? Is it cuda aware and doing the proper synchronization (via torch.cuda.synchronize() for example)? Also your code creates the Tensors on cpu then move them to the gpu, you can do the following to avoid this: torch.zeros(4, 1, 20, 20, 20, 32, device="cuda") The…
christios
Hello,I’m trying to implement Integrated Gradients (explainability method) for my seq2seq NMT model since there are no public implementations available. For that, I would be required to compute the gradient of my output w.r.t. my input, which would in turn require me to setrequires_grad = Truefor my input variables. Co...
albanD
Hi, You won’t be able to get gradients wrt to the input of the embedding layer I’m afraid. Since, as you pointed out, they are not of contiguous dtype. You might want to do use that technique on the output of the embedding layer instead?
Ilya_Kotlov
Hi, will be glad for some help to solve thisissue.The problem is:# RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operationThis is my code:def train_single_scale(netD, netG, reals, Gs, Zs, in_s, NoiseAmp, opt, centers=None): real = reals[len(Gs)] opt.nzx =...
albanD
Yes, this was a bug on our end. Recomputing fake is the right thing to do here yes!
Linux-cpp-lisp
Hi all,We have a model that involves an autograd call as part of its forward pass, something along the lines of:return torch.autograd.grad( [prev.sum()], wrt_tensor, create_graph=True, # needed to allow gradients of this output )[0]When we scale the hidden dimension of our m...
albanD
Hi, You can enable anomaly mode. That will show you the forward op that corresponds to the one that is failing in the backward. Can you share this trace?
Dan3
Hi,I want to be able to use the univariate spline class from scipy with pytorch but I am not able to do this while maintaining autograd. I have been looking atCreating Extensions Using numpy and scipy — PyTorch Tutorials 1.8.0 documentationto try and get the scipy code working in pytorch but I am unsure that the correc...
albanD
Ho, I added one None “randomly” just to make sure to return two things in the backward. But if the forward takes bin and x as input, then the backward should return the gradients wrt bin and gradients wrt to x.
Semir_Elezovikj
The transfers to GPU seem to be slow - wondering whether I can do anything with the below snippet of code to speed things up.Gpu.IDS is just an array. Example:IDS = [4, 5, 6]device = torch.device('cuda:' + str(Gpu.IDS[0]) if torch.cuda.is_available() else 'cpu') print('running on ', device) model = model.to(device) if...
albanD
Hi, No the code looks ok. The one thing is that you can collapse this: ground_truth = ground_truth.to(device) ground_truth = ground_truth.to(torch.float32) into ground_truth = ground_truth.to(device=device, dtype=torch.float32)
mattief
I have a function f(x;a) between two vector spaces parametrised by a. I’d like to take the derivative of the Jacobian D_x f(x;a) with respect to the parameters a, that is ∇_a (D_x f(x;a)). It’s obviously possible to code up the Jacobian by hand and callbackward()on it like this (i’ve used a 1D space for simplicity):imp...
albanD
Hi, You need to make sure to pass create_graph=True the first time you run autograd.grad (or backward()) to be able to backward through that. Also you can use the autograd.functional.jacobian(..., create_graph=True) to get the full Jacobian directly.
xinsss
Based on the documentation, the tensor.argmax should returns the index of the first occurrence of multiple largest values.But when the tensor contains all same values, it returns the index of the last value.For example,torch.tensor([0, 0, 0, 0]).argmax(dim=0), outputs istensor(3). Shouldn’t it be 0?
albanD
Hi, Which version of pytorch are you using? This was fixed in 1.7+ versions only IIRC
lnair
Hello!I reviewed “A guide to convolution arithmetic for deep learning” (Dumoulin and Visin 2016), which states that “it is always possible to emulate a transposed convolution with a direct convolution”. However, they mention that this is an inefficient implementation. So how does Pytorch implement the transposed convol...
albanD
Hey! So the way to go is: function.conv_transpose2d calls into torch.conv_transpose2d. torch.conv_transpose2d is nowhere in python filesSearch · conv_transpose2d · GitHubmeaning that it comes from c++ All C++ functions are defined in a nice yaml file:pytorch/native_functions.yaml at master ·…
TeaWaterSleep
Hi,I try to implement a stabilized attack method, which consist of a classical iterative fast gradient sign method (FGSM) plus a stabilization term.Here is the definition of the loss stabilized (W is gaussian kernel, eta the sign grad through iteration) :Below my implementationdef smia_attack(image, epsilon, alpha, mod...
albanD
Hi, Note that it would be better to replace: L_smia.backward() eta = epsilon * attack_image.grad.data.sign() by grad, = autograd.grad(L_smia, attack_image) eta = epsilon * grad For your issue, what is the value of alpha? Also you can check the gradients flowing …
Zecheng_Zhang
Hi,I have a question about the second order derivative of with respective to the input. Say,class Test(nn.Module): def __init__(self): super().__init__() bo_b = False bo_last = False self.l1 = nn.Linear(1, 1, bias = bo_b).to(device) self.l2 = nn.Linear(4, 1, bias =...
albanD
Hi, The problem is that your function is linear. So the first gradient is constant and the second order gradient is independent of the input. This error message happens because of the independence (and thus, it is not used in the graph).
TinfoilHat0
Hi,Is there a way to access the update values computed by the optimizer?For example, if I’m using plain SGD with a learning rate a, then update values are simply a*gradients.More concretely, these values should be what .backward() method computes, for each instance in the batch, and automatically adds to the model weig...
albanD
I’m afraid that in the general case no, there isn’t any other way to get thatAs a fun fact, some optimizers like lbfgs might actually do the step as multiple “sub-steps”, so in that case, checking before and after is really the only thing you can do.
Naruto-Sasuke
import torch import torch.nn as nn learning_alpha = torch.ones(1) learning_beta = torch.zeros(1) learning_alpha = nn.Parameter(learning_alpha) learning_beta = nn.Parameter(learning_beta) c = learning_alpha + learning_beta print(type(c))<class 'torch.Tensor'>
albanD
Hi, nn.Parameter are just a Tensor subclass for nn.Module to know what is a parameter there or not. But there is no need for them to remain Parameters and they can be used just as any regular Tensor.
sh0416
Sorry for the irrelevant issue.Is there anyone who knows how to change my username?I want to change my username to “sh0416”.Thanks,
albanD
Sure, it should be good now.
siyuchen95
I am running the command given on pageStart Locally | PyTorchto install pytorch locally. I have a GPU (GeForce GTX 1070), the latest version of NVIDIA driver (455.32.00) and have previously installed CUDA (11.1). However, conda automatically fetches a cpu-only pytorch package to install:pkgs/main::pytorch-1.3.1-cpu_py2...
albanD
You should be getting pytorch 1.7 Can you run conda update conda first? Then try to install torch.
tshmak
Hi, I’m trying to modifynn.Module._load_from_state_dict()(torch.nn.modules.module — PyTorch 1.7.1 documentation).My class inheritsnn.Module:class foo(nn.Module): def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs): ...
albanD
I think the simplest way to do that is to pre-process your state_dict before giving it to the Module.load_state_dict function. That will make sure that your code keeps working with new versions of PyTorch as internal API might change without notice.
Nreon
Hello everyone, I come to you in time of great need,I need only the input for my model to be affected by backpropagation.It is an experiment. I know it might sound silly, but I was wondering how to achieve this.I tried settingx.requires_grad = Truefor my input variable and thenlayer.requires_grad = Falsefor all the lay...
albanD
Hi, If you only want the gradient for the input, the simplest thing I can think of is: model = # Your model input = # Your input # Make sure input requires grad input.requires_grad_(True) # Do the forward as usual output = model(input) loss = crit(output, label) # Ask only for the grad wrt the …
saul_santos
The question says it all. Thank you in advance.
albanD
Hi, If you don’t get an error when you backprop, then it isA quick check shows that it is: import torch a = torch.rand(10, 10, requires_grad=True) mask = torch.randn(10, 10).clamp(min=0).bool() # Generate random mask out = torch.masked_select(a, mask) out.sum().backward() print(a.grad) # A T…
A_A
Hello,I have a slightly less conventional scenario involving my custom autograd function (M). Given target of shape: [*, N, *, *], The computational graph looks like this:> INPUT -> NN -> M.forward (out shape: [*, C, *, *]) -> Zero pad to match C = N -> Loss on all N channelsDuring backward I want the gradients to the ...
albanD
True, but the memory would be an issue. I’m not sure to see why. Currently, you already have a x → M → z → PADDING → z_p I think you want (x, z_g) → M_AND_PADDING → z_p And in that new custom Function, you don’t need to do anything beyond what the padding is currently doing.
cbd
I want to initialize tensor “a” as shown in below code and want to access it in forward call. But it shows the " NameError: name ‘a’ is not defined "import torchimport torch.nn as nnfrom torch.autograd import Functionclass run(Function):definit():a=torch.linspace(0,1,0.2)@staticmethoddef forward(cxt,input):cxt.save_for...
albanD
I’m sorry I can’t really follow this. What would be the pair (x, expected_y) that you want? What would be the initial weights w0? It means we should never take ReLU output as our final output ? It is not advised in general no. Mainly because it does not have any benefit (if you’re value is po…
MrPositron
I want to clone the model. However, PyTorch fails to detach and clone the model.temp_enc = model.encoder_net.detach().clone()Error I gettorch.nn.modules.module.ModuleAttributeError: 'Encoder' object has no attribute 'detach'When I clone without detaching I receive similar error:torch.nn.modules.module.ModuleAttributeEr...
albanD
Hi, Both clone and detach are constructs on Tensors, not nn.Modules. If you want to make an independent copy of a model, you can use the regular python deepcopy.
adityamnk
I am trying to write my own backward function to calculate gradients. However, I get the following error: “RuntimeError: No grad accumulator for a saved leaf!”. This error can be reproduced using the code below. Any help is greatly appreciated! Thank you.import torch from torch.autograd import gradcheck class CustomAu...
albanD
Hi, The problem is that you’re using ctx.save_for_backawrd() for things that are neither inputs or outputs. You can just save these on the ctx. and it will work: import torch from torch.autograd import gradcheck class CustomAutoG(torch.autograd.Function): #REF: https://pytorch.org/tutorials/…
Legolas
Hi,I have a multiclass classification problem in NLP. For simplicity, let us have just three target classes: ″SPORT″, ″CULTURE″, ″TRAVEL″. Also, let these classes have corresponding labels: 0,1,2.Let us say that we want during training toadd penalizationin cross-entropy lossaccording to some relationship between two in...
albanD
I don’t think you need a custom backward here no. You should simply update your function to only work with Tensor all the way and do not “repack” them with torch.tensor() or call .detach() on them as these would break the autograd link.
rb11
I want to implement neurons splitting and don’t know how to approach this using Pytorch.I’m working on an RL problem and observe that the number of dead ReLU neurons (i.e. neurons which are zero forever) in my model constantly increases.This is at least partially related to the fact that the distribution of the trainin...
albanD
Hi, There is no automatic way to do that for sure. And it’s not even always true that you will have a change to the downstream layer that will give you what you want. In particular, you mention “sum”, that could lead to multiple nodes being used with the same weights and so you cannot modify these…
gilbertocunha
So from my knowledge nesterov momentum should look something like this:nesterov1113×206 8.21 KBAccording to this formula, the loss function should be calculated not according to our model’s parameters, but with a prediction of the future model’s parameters.And using a torch SGD optimizer with Nesterov should look like ...
albanD
Hi, I am not 100% sure but I think the trick is to have the parameters actually contain \theta_t - \mu v_t. That way a regular forward/backawrd evaluates the right value and you only need to update the step formula to take this into account.
morphism
Hello, everyoneAs far as I know, model parameters (W and b) have settting requires_grad = True, by defaultwhen they are intializedThen, how about data matrix and label ??Should I set requires_grad = True when I initialize data matrix (input data or batch data) as torch.tensor??Also, should I set requires_grad = True wh...
albanD
It won’t break anything, the things that can happen are: you will compute gradients for some Tensors and don’t use it. Slowing down your code slightly for no reason. If your label is of a non-contiguous dtype (like long), it will raise an error if you try to set requires_grad=True. Because that is…
eduardo4jesus
Dear fellows,I am wondering about the executing time for the forward and backward stages of the convolution 2d operation.Check this notebookAs far as I know, the forward pass is composed by a single convolution operations. When doing the back propagation, the derivatives w.r.t each of the inputs would be computed with ...
albanD
Hi, I think you’re missing the following linebackward1 *= 1e3 # From seconds to miliseconds Then all the timings will be what you expect.
tueboesen
My code keeps crashing after a couple of thousand iterations (suddenly all the weights go to nan), but nothing obvious seemed to trigger it, so now I turned on anomaly detection and I get the following error already in the first iteration, but I can’t really see the problem.[W ..\torch\csrc\autograd\python_anomaly_mode...
albanD
Hi, The gradient for sqrt(0) is going to be +inf. So it is a fairly dangerous thing to have! It might be better to compute the sqrt first and then set to 0 the values you want to zero out. That way, all the gradients will remain well defined.
qualix
I’m struggling to write a function ConvToToeplitzTr() which takes a conv2d’s weight matrix W as the input, constructs a new matrix using its entries (a Toeplitz matrix representation of the given conv2d, transposed)by referenceand returns this new matrix M. Both W and M are then used to calculate the output of the laye...
albanD
I am not sure this is true. You don’t use detach or no grad so the gradients will be properly tracked through your convmatrix2d function (even though the output matrix does not share its memory with the input, if you backprop, the gradients will flow back all the way to the input.
coincheung
Hi,I am learning the source code of pytorch, and I would like to know how can pytorch compute the rank along cerain dimension of a tensor. However, the code is too abstract to understand, so I am asking what method is used to compute this please ? Did you use thrust combined with a for loop to compute it many times, or...
albanD
Hi, argssort is implemented by doing sort(same_args)[1]You can see that implementation here:pytorch/LegacyDefinitions.cpp at 22a34bcf4e5eaa348f0117c414c3dd760ec64b13 · pytorch/pytorch · GitHubAnd for sort, you can see here that it comes from the old THC library:pytorch/native_functions.yaml a…
kirk86
It seems that modules provide some functionality through functions of the formmodule.some_functionbut alsomodule._some_function(i.e. notice the_underscore_notation).For instancemodule.parameters() vs. module._parameters.It seems thatmodule.parameters()returns the parameters andmodule._parametersreturns anOrdereredDict(...
albanD
This makes sense but I’ve seen a lot of code online that uses the non public API and if I’m not mistaken I’ve seen also some pytorch examples uses it as well. Can you link such example please? On another note, if you wanted to loop over the params of a module, do some operation and then remove …
ProGamerGov
So, I am trying to recreate this TensorFlow function in PyTorch, but it doesn’t seem to be working:d_previous = tf.placeholder("float32") d_logit = fwd_gradients(T("softmax2_pre_activation"), T(layer_name), d_previous)[0] def fwd_gradients(ys, xs, d_xs): """Forward-mode pushforward analogous to the pullback defi...
albanD
Hi, You need to give create_graph=True to the first call to grad if you plan on doing a backprop through it. Also I don’t think you want to give torch.zeros_like(xs) for the second grad. It should be the d_xs that is in the tensorflow version