user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
gsasikiran | In the following code, I see,requires_gradeis False fora**2but True foraeven after usingtorch.no_grad(). Why isa.requires_gradis still True?print(a.requires_grad)
print((a**2).requires_grad)
with torch.no_grad():
print(a.requires_grad)
print((a**2).requires_grad)Output:True
True
True
False | albanD | The main one is that there is no consensus that this is the right way to do it.
Having t.requires_grad change based on a global flag that could be controlled from other code could be quite surprising to the user as well.
Also many people are now used to the current behavior so we want to have a so… |
ericrhenry | Using the C++ frontend, during training I compute a loss tensor with a construction similar toauto x=module->forward(inputs);auto loss=loss_function->compute(x,targets);if(loss.requires_grad()) { // tests to trueloss.backward();}This is being done in a closure passed to an optimizer; this closure then returns the loss.... | albanD | Yes.
So maybe it’s simpler to consider the autograd.grad(loss, w) API first:
Given the output and input of a function, it will return the gradient dloss/dw to you.
In the context of torch.nn, to avoid the user the burden of moving these gradients around, we use loss.backward() that will populate … |
Meraki | Maybe the title is confusing. Here is the small example:w = torch.tensor([3.2], requires_grad=True)
p = torch.tensor([2.0, 1, 7], requires_grad=True)
g = torch.sum(p ** 2)
e = w * g
e.backward(retain_graph=True)
f = p.grad
l = e + 0.5 * f.mean()
l.backward()here f is the funciton of w, however we loss gradient graph o... | albanD | Hi,
You want to do e.backward(create_graph=True) that will make sure the backward pass run in a differentiable manner.
Also creating a .grad that requires grad is usually not recommended because when you do l.backward() here, you will accumulate in the same p.grad which can easily become confusing… |
pyscorcher | Apparently thebackward()in a customautograd.Functiondoes not get called by a python method directly (see also this blog entryregarding coverage tests), which is why breakpoints set within thesebackward()methods never get triggered. Is there another way to use a python debugger for these backward passes? | albanD | Hi,
What I usually do when I need this is to trigger it directly from inside the backward function with import pdb; pdb.set_trace():
import torch
from torch import autograd
class F(autograd.Function):
@staticmethod
def forward(ctx, foo):
return foo.clone()
@staticmethod
def backw… |
polm23 | I’m trying to train some entity embeddings, but when doing a backward pass I get an error about Leaf Variables being moved into the graph interior. I saw there are other threads where people had that issue and it’s due to in-place operations or assigning to tensors, but I’m not doing anything like that so I’m unsure wh... | albanD | Yes !
I opened an issue there:https://github.com/pytorch/pytorch/issues/28370 |
asha97 | I am trying to run the following SINGAN code,Linkbut whenever I am training ,following error comes/pytorch/aten/src/ATen/native/TensorFactories.cpp:361: UserWarning: Deprecation warning: In a future PyTorch release torch.full will no longer return tensors of floating dtype by default. Instead, a bool fill_value will re... | albanD | Hi,
The problem is that in this for loop:https://github.com/tamarott/SinGAN/blob/e1384a9f6dfa45497f4aed5f3e52466d4200fcfb/SinGAN/training.py#L173you reuse the same fake commputed with the original netG above.
But when you do the first optimizerG.step(), then you modify the weights of netG inplac… |
cqhoneybear | Hi,I would like to keep the maximum value to be 1 and others to be 0 in a tensor. But the backward function does not produce gradient for the tensor.I attached the example. Thanks!import torchx = torch.Tensor([[0, 1, 2, 3]]).requires_grad_()b = (x==x.max(dim=1,keepdim=True)[0]).type(torch.FloatTensor).requires_grad_()o... | albanD | “b = (x==x.max(dim=1,keepdim=True)[0]).type(torch.FloatTensor)” is actually not differentiable and so that x.grad is none?
If returns a Tensor that does not require gradients even though the input does. This means it is not differentiable yes.
And is there a way to keep the maximum value to be … |
smonsays | I was surprised to realise that it is possible to callbackward()in a computational graph that invokes torch.bernoulli(). However, I am not completely sure what happens in the background.In this small example the gradients wrt to the Bernoulli probabilities are as far as I can tell always zero.import torch
p = torch.ran... | albanD | Hi,
Yes this is expected.
It is specified here:https://github.com/pytorch/pytorch/blob/727463a727e75858809a325477ac2b62ccd08e7e/tools/autograd/derivatives.yaml#L270-L271 |
pyscorcher | I’m trying to implement a custom autograd.Function, where one of the arguments for the forward pass does not need a gradient (let’s say an index or a string or something like that). To illustrated I just modified theexample from the tutorialas follows:class MyReLU(torch.autograd.Function):
@staticmethod
def for... | albanD | Hi,
No need to do anything specific in the forward. And in the backward, returning None is the right thing to do |
ab-10 | I would like to implement a sinusoid activation function intorch.nn.functional, this is motivated by the strong results demonstrated using the activation function inImplicit Neural Representations with Periodic Activation Functions(ArXiv,paper’s webiste, andGithub repo).I’m curious about whether this looks like a valua... | albanD | Hi,
The general policy we have here is the following:
We expect the given paper to have a significant amount of citations and have proven to be valuable over time (we want the core library to remain small enough)
Exceptions can happen when it is hard/impossible to implement a given paper with the… |
fgauthier | I am new to Pytorch and I was wondering if they are any way of using callback like in keras. I know Ignite can do it but is there any other way using only Pytorch?Thanks a lot! | albanD | Ho.
So in some sense you want to be able to specify in a json file a python function to be called later.
I think the simplest would be to have a file containing all the possible callbacks and the json file just contains the name of the one you want to use. Then in your function you can just call t… |
I_H_Yoo | As the title says, why istorch.tensor(source_tensor)not preferred and whytensor.clone().detach()is more preferred when a tensor is copied? | albanD | Hi,
Mostly for clarity. tensor.clone().detach() makes it very clear what happens to the Tensor: You first allocate new memory for it then detach it from the autograd graph from the original one.
torch.tensor(source_tensor) does the same thing but you can easily forget it and have hard-to-debug iss… |
Dhorka | Hi,I have a doubt related to the function torch.from_numpy. I’m trying to convert a numpy array that contains uint16 and I’m getting the following error:TypeError: can’t convert np.ndarray of type numpy.uint16. The only supported types are: float64, float32, float16, int64, int32, int16, int8, uint8, and bool.I suppose... | albanD | Hi,
I think the answer here depends on the use case.
If you want to be use not to loose any precision, then yes you want to convert it to an int32 before converting to pytorch.
If you don’t want to use double the space, you can use int16 and it should work just fine as long as your numbers are no… |
AshviniKSharma | What is the difference between require_grad and requires_grad? I am trying to freeze layers of the network. But during the implementation of the freeze function, I used require_grad = False for freezing layers, and now when I am checking it with requires_grad it says layers are not frozen i.e. result in requires_grad=T... | albanD | Hi,
require_grad is not a pytorch thingSo it has no effect.
Note that you can set any attribute you want on Tensor, this is why you didn’t see any error (param.foo = 3 would work as well). |
akashs | What is the relationship betweennum_workersof the data loader inDistributedDataParallelmode? For example, if thenum_workers=8and the number of GPUs is 4, then whether each distributed process inDistributedDataParallelmode will getnum_workers 2 or 8? | albanD | Hi,
They are completely independent.
DataLoader processes will only be used to load data from your Dataset.
The processes for DistributedDataParallel have nothing to do with it. |
kirk86 | I’m trying to backprop through a long tensor but autograd complains. Changing it to float still throws an error.Here’s a MWE, could some point out any alternative solutions?x = torch.randn(100, 3)
y = torch.randint(3, (x.size(0),))
w = torch.nn.Parameter(torch.randn(3, 3))
optimizer = torch.optim.Adam([w])
for i in ran... | albanD | Hi,
can you update to the latest 1.5.1 release? This should be fixed |
Sathvik_Joel | I am new to PyTorch so apologies if my question is very basicI am trying to implement some visualization techniques from different papers and I observed that hooks really play a very important role in this.But when I wanted to find the documentation for torch.utils.hooks, I could not find it anywhere.Is it because it’s... | albanD | Hi,
torch.utils.hooks are just internal utility functions that we use to implement hooks but that’s it.
You can find Tensor hooks by looking for register_hook() on Tensor.
You can find nn.Module hook by looking for register_forward_hook(), register_pre_forward_hook() on nn.Module. |
cruzas | Hi everyone,I’ve taken a look around but haven’t been able to find an answer.Is there an equivalent to Python’storch.mean()in C++?Thank you for your help. | albanD | Note that if you have a pytorch Tensor on your cpp side, at::mean(t, dim) will work .
You can find these in the cpp API doc:https://pytorch.org/cppdocs/search.html?q=mean&check_keywords=yes&area=default |
arnabsinha | self.fcVar = nn.Sequential(*[nn.Linear(output_ndf, output_nc)])What does the * signify in this line of code when creating a network?Thanks for the help in advance. | albanD | Hi,
This is a python construct.
It can be used to unpack the elements of a list or tuple into positional arguments for the function:
def foo(a, b):
return a + b
data = [1, 2]
foo(data) # Error as a single argument is given
foo(*data) # Works |
prophet_zhan | My model can run slowly in cpu, but it cannot run in GPU.When I was using CUDA(10.0.130), I will getSegmentation fault (core dumped).So I try to usegdb python, and I got:Thread 1 "python" received signal SIGSEGV, Segmentation fault.
0x00007f231cdd9cc0 in _IO_vfprintf_internal (s=s@entry=0x7ffd3aee5f00, format=<optimize... | albanD | Hi,
That looks bad indeed.
The segfault happens while pytorch was trying to raise a Type Error when constructing a Tensor.
Do you have a small code sample that reproduces this behavior? I would be happy to take a closer look ! |
Valerio_Biscione | Hello, I don’t mean to be polemic, I am just curious. I was wondering why, in PyTorch, we need to specify the input size of a linear layer. In keras, after I flatten a layer, I can feed this to a linear layer without having to specify the input size (I assume this can be computed by flatten()). This is very convenient ... | albanD | Hi,
The main reason is that pytorch needs to create the weights at the initialization of the layer (and thus know the input size).
This is to make sure that calls like model.cuda() or your_opt = optim.SGD(model.parameters(), ...) works as expected even before your model has seen a single sample.
N… |
Barbany | Hi fellows!I’m implementing a model that is inspired in themusic translation networkby Facebook.Essentially, we have an encoder network (take input belonging to some class and output latents) and a classifier that tries to predict the class of the input solely based on its latents. The minimax game here is for the enco... | albanD | Hi,
You need to use retain_graph because .backward() goes through the whole graph (both encode/decoder here). And so if you want to be able to backward in the decoder again you need to retain_graph.
You can use retain_graph if you don’t change any value required by the backward. In particular here… |
copythatpasta | Hello, I would like to know how I can traverse a tensor with dims{5,3,36,36} by batch. I would like to traverse each batch and return it into another tensor to do an operation using the c++ torch front end. I am using v1.3.0 so cannot use Slice in the new v1.5.0 libs. How can I do this ? | albanD | Hi,
You can use .select(dim, idx). Where you want to use dim=0 and idx being the batch index. |
111341 | Hi, I am trying to calculate higher order derivatives of a customized module. However, gradients output of torch.autograd.grad() or backward() has no grad_fn even for setting create_graph=True. The customized module is a cuda extention. Specifically,PreciseRoIPooling.I created a small example.import torch
import torch.... | albanD | The custom CUDA extension is differentiable
How?
The autograd only tracks torch functions. Your extension uses cuda directly yo compute the result. So it is not differentiable! |
fulltopic | I am running pytorch c++ in Amazon AMI and encountered a hang.Env:(base) [ec2-user@ip-172-31-20-6 ~]$ uname -a
Linux ip-172-31-20-6.ec2.internal 4.14.173-137.228.amzn2.x86_64 #1 SMP Thu Mar 19 16:50:21 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
(base) [ec2-user@ip-172-31-20-6 ~]$ gcc --version
gcc (GCC) 7.3.1 20180712 (R... | albanD | Hi,
No this is expected. Half of them are OMP worker thread and one of them is an autograd engine worker thread.
These are worker threads that are kept around so that we don’t have to recreate them every time we need them. OMP does that by default and we do it ourselves as well in the autograd eng… |
divinho | def forward(x, dur_cnts):
N = x.size(0)
T = x.size(1)
durs, counts = dur_cnts
idx = 0
joined = to.zeros((N, self.dim_in), dtype=to.float32, device=x.device)
for i, (dur, count) in enumerate(zip(durs, counts)):
x_part = x[idx: idx + count, :dur]
joined[idx: idx + count] = x_part.s... | albanD | Hi,
I’m afraid that if you have general indices and counts, you won’t be able to do this in a single op.
You will need a custom kernel that implements this. |
rohithkrn | I am experimenting with implementing a custom activation function. To start with, I tried to mimic the behavior ofrelu. So, I added the custom opmy_reluinATen\native\native_functions.yamlwhich dispatchesrelu.- func: my_relu(Tensor self) -> Tensor
use_c10_dispatcher: full
variants: function, method
dispatch:
CPU: ... | albanD | Hi,
You will need to specify it in tools/autograd/derivatives.yaml then recompile.
You can check the entry for relu there and the comment at the beginning of the file for more details. |
johnestar | Hi there, I’m trying to use DataParallel with one model implementation but got this weird error.My code is roughly like this:# constructing the NN
net = ...
device = torch.device('cuda:0')
if torch.cuda.device_count() > 1:
print("Let's use", torch.cuda.device_count(), "GPUs!")
net = nn.DataParallel(net)
net.to... | albanD | Given that you use torch.no_grad(), I guess that you don’t want this to be taken into account in the backprop. So the simplest solution is just to apply this inplace before doing the DataParallel forward. |
witha | Hi everyone!I’m new to PyTorch and I have a problem regarding nested PyTorch nn modules. The problem as follows.I have a main nn model lets say model A. Which in turn uses two objects created from another nn class inside a for loop that contains lstm cells(single-cell).First, the autograd complains that the graphs need... | albanD | Hi,
Do you properly re-initialize the hidden state to make sure it does not backrprop through the previous iterations. Otherwise you will get the error that you see above with trying to backward though the graph multiple times. |
duskybomb | I am trying to calculate the gradient (d(loss)/dj). But I get grad is Noneclass model(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Linear(256, 2)
def forward(self, j, labels):
e = self.fc(j)
print(labels.shape)
print(e.shape)
j.require... | albanD | Hi,
The problem I think is that you set j.requires_grad after you used it. So the graph is not created when you do the forward.
You should move this at the beginning of the forward() function. |
johnestar | Numpy uses NHWC, pytorch uses NCHW, all the conversion seems a bit confusing at times, why does Pytorch use NCHW at the very beginning? | albanD | IIRC, NHWC allows you much better implementation for convolution layers that gives a nice boost in perf (because the value for all channels is accessed for every pixel, so data locality is much better in that format).
The problem is that batchnorm-like layer are so much faster in NCHW, that vision … |
oboul | what would be the best accuracy and loss visualization tool for writing reports instead of tensorboardX ? | albanD | Hi,
If you want to stay with tensorboard, there now is a builtin Tensorboard support in pytorch, seehere.
Otherwise, you can look into visdom which is another visualization project similar to Tensorboard. |
arnabsinha | Below is my code for training a GAN:def train_discriminator(optimizer, real_data, fake_data):
#set optimizer gradients to zero to store fresh gradients
optimizer.zero_grad()
#adversarial discriminator loss
prediction_real = disc(real_data)
error_real = loss_bce(prediction_real, real_data_targe... | albanD | Because you want the discriminator loss to only compute gradients for the discriminator and not the generator.
The .detach() here allows you to make sure this happens.
If you do it for the generator loss, then the generator loss won’t contribute to the generator gradient which is not what you want… |
KeisukeShimokawa | When I was training the GAN, the first iteration worked well, and the second training probably caused an error on the Discriminator side.The details of the error are as follows. This dimension [3, 48, 3, 3] means the first layer of the Discriminator, but I didn’t use any in place operation.one of the variables needed f... | albanD | Hi,
Is the training loop the onehere?
Given that it happens not at the first backward it can be:
An optimizer.step() modified a weight that was already used by a forward and you call backward after:
out = model(inp)
opt_model.step() # Modifies the model's weights inplace
out.sum().backward() #… |
Alpha | For example, I want to explicitly multiply 2 on the convolution layers’ weight.I motify the officialconv.py.pyfrom :def forward(self, input):
return self._conv_forward(input, self.weight)todef forward(self, input):
new_weight = self.weight * torch.ones(self.weight.size())*2
return self._conv_for... | albanD | Hey,
No need to ping, we look at the postsAnd yes it is expected that after doing any differentiable operation on it, you get a Tensor.
Keep in mind that nn.Parameter are only the leafs stored in the nn.Module that nn recognize as being part of the parameters.
Also you can write the same thing… |
Sudarshan_Babu | for batch_idx, (data, target) in enumerate(train_loader):
meta_data = data
meta_data.requires_grad = True
print(data.requires_grad) // prints True, since we are not doing deep copy
data, target = data.to(device), target.to(device) // moving tensors to GPU
optimizer.zero_grad()
... | albanD | Hi,
It is because .to() is a differentiable op. And so the data that you get back is not a leaf anymore (if you print it, you’ll see the grad_fn attached to it). |
0xfede | I posted a question several hours ago and it’s grayed out. What does this mean? | albanD | In the main page. Posts that are greyed out are the posts you already looked at. You can try looking at other posts and they will grey out as well. |
Umair_Javaid | I have a model that outputs a tensor of shape[b,n,r,c], wherebis the batch size. I want to multiply this tensor with a trainable tensor of shape[b,n,1,1]. I am confused about how to deal with batch size since we construct our models without knowing the batch size. How to go about it? How can I multiply a trainable ten... | albanD | I’m not sure to understand the question. A regular multiplication will work. The fact that one of the Tensor is a Parameter does not change anything. |
theairbend3r | I’m trying to implement the GradCam paper which uses the gradient information flowing into the last convolutional layer of the CNN to assign importance values to each neuron for a particular decision of interest.The paper says -image745×511 62.6 KB1.The first step to implementing GradCam would be obtaining the gradient... | albanD | Hi,
Hooks can allow you to get gradients wrt to intermediate results in the forward, not just the weights/biases.
For backward hooks, you should only use the Tensor version right now (the nn.Module version is not working properly at the moment).
To you a module hook for the output of cnn1 for… |
Vishu_Gupta | The following are the 2 of the implementation of the same code:class ResidualNetwork(nn.Module):
def __init__(self, input_dim, output_dim, hidden_layer_dims):
"""
Inputs
----------
input_dim: int
output_dim: int
hidden_layer_dims: list(int)
"""
... | albanD | Hi,
Both will work quite fine. Usually people like to pack many modules in a list for convenience but you don’t have to.
For stateless modules like relu, you can reuse it yes! |
blade | Given anNxNmatrixMat, I would like to have a vector of upper diagonal elementsVecof the matrix. Are there anyways, without using a nested loop, to do this? With a nested loopVec = None
for i in range(N):
for j in range(N):
if i>j:
if Vec is None:
Vec = adjacency[:, i, j].unsqueez... | albanD | Hi,
You should be able to use triu_indices()hereto get the indices and then just index adjacency with it using a single function call. |
Jack_Rolph | Suppose I have a tensor:a = torch.randn(B,N,V)I want to get the third column of the tensorAalong axisV, in the format(B,N,3,1).I could do this by:a_slice = input[:,:,3,None]Particularly, I worry that this element of my code may not be differentiable. Is this the case?If so, is there a way of doing this with Torch funct... | albanD | Hi,
All the indexing ops are differentiable. So no need to worry about it ! |
benf.stokes | Suppose we have a weighted loss (theta are the networks parameters):o = model(data; theta)L = wi*F.cross_entropy(o, target, reduction=“none”),where the wi are the result of another network (model_w). Assume we’re using SGD to update the parameters in model so that:theta’(wi) = theta-lr x wi x grad(F.cross_entropy(data,... | albanD | Hi,
The issue is that you want to backprop through the optmizer step?
Well the issue is that the optimizers in pytorch are not differentiableSo I would recommend using a library likehigherthat is built do differentiate through gradient updates! |
dedeswim | Hi!I have seen that within the 1.5.0 release, the possibility to compute HVP of a function has been added.As far as I understand from the documentation, the HVP (as well as the VHP, VJP and so on) can be computed w.r.t. the input only, and not w.r.t. some other variable (such as, for instance, the parameters of a model... | albanD | Hi,
You don’t have to do each parameter one by one, you can give all the params/grads as tuples.
You get all zeros because your function f does not use the inputs x to compute the output.
You can do something like this to use the autograd API with torch.nn:
# Utilities to make nn.Module function… |
Mike2004 | Hi, can someone explain to me the differences between this models of autoencoders:https://github.com/L1aoXingyu/pytorch-beginner/tree/master/08-AutoEncoderAnd explain me better the network structure of all of them? I want to know more about this models.Thanks. | albanD | You might want to check the code in more details, but the “basic architecture” described in the wikipedia article seems to match the code in spirit. |
Bernicchi | HiI have neural network that I trained on my PC and then jit compiled and run inferences on my Android phone. I can see from Android Studio debugger it is processing using the mobile’s CPU. How can I check and use GPU if available on android mobile?Thanks in advance | albanD | Hi,
Unfortunately, mobile GPU is a completely different language and architecture to everything else. So we don’t support it yet.
It is work in progress though and you can see all the PRs working it here:https://github.com/pytorch/pytorch/pulls?q=is%3Apr+is%3Aopen+vulkan |
navid_mahmoudian | Suppose that I have a list of tensors (the tensors have different sizes), and I want to save this list into a single file. Is there any way to do this? The tensors are not model parameters and they are just some data. | albanD | Hi,
You can just torch.save() the whole list. It will create a single file with the list. |
remidebette | Hi,I have a simple beginer question about autograd.Thanks for the nice library.I really like the functionality and I understand that it simplifies a lot of code by packaging the derivative against a variable directly in the variable.What I am fearing is that the .backward() => .grad mechanic relies on the user keeping ... | albanD | Hi,
The .backward() and .grad fields are built to work nicely with the torch.nn and torch.optim libraries.
It allows you to handle computing the gradients and updating all the parameters without the user having to handle passing all the gradients by themselves.
If you are not working with these l… |
12wang3 | We know that we can implement our own custom autograd functions by subclassing torch.autograd.Function and implementing the forward and backward passes which operate on Tensors. As shown inhttps://pytorch.org/docs/stable/autograd.html#functionclass Exp(Function):
@staticmethod
def forward(ctx, i):
resu... | albanD | Hi,
The functional methods in torch.nn are not all elementary functions for the autograd. So there isn’t a single backward function to call for them.
What you can do though is get the gradient with the regular autograd:
# inp that requires_grad=True and grad_output that match what you want to com… |
Luvata | I’m implementing MAML, but currently I’m struggling to understand how to calculate the gradient of the outer loss w.r.t model’s parameters before any inner gradient step. So I made a naive example, but I’m not sure if I missed anything ?import torch
from torch.autograd import grad
# f(x) = 2x + 3
x_train = torch.tens... | albanD | Note that the right way to update the weight is with:
with torch.no_grad():
W -= outer_loss_wrt_W * 0.01
.data should not be used anymore!
Your code looks good at first glance. What is the issue that you have with it? |
smanschi | Hi there, I played around with the computation of a Jacobian. My goal was to find the fastest possible implementation. Therefore, my idea was to feed all output / input combinations into the grad function all at once instead of iterating over it with a for loop. The corresponding method is called jacobian in the code b... | albanD | Hi,
I would say this is caused by the “No free lunch theorem”This is a rather fundamental limitation of AD I’m afraid.
The issue you have here is thatall your outs and inputs are dependent. And so all the gradient “flowing” for one will flow the same way as the ones flowing for another. And so … |
ResidentMario | I tried to upgrade a model training script from a 1.4.0 pytorch environment, in which it is working, to a 1.6.0-nightly pytorch environment, in which it is not.The fact there are no code changes leads me to believe that there’s some broken behavior in 1.6.0-nightly, which is why I’ve filed this issue as a bug report:gi... | albanD | Hi,
You can check the release note for 1.5. In particular the part about fixing the inplace detection code for the optimizer.step() functions for the builtin optimizers.
The issue you have is that the optimizer.step() modifies the weights inplace. But if these weights are needed to compute the bac… |
csailnadi | During training we are update weights inside the model.Say we take conv layers.How do I access the weight update matrix?Is there an api for this sort of thing or do I need to save weights of interest myself and then find the difference of those?Thank you | albanD | Hi,
If you’re using the builtin optimizers from torch.optim, then not really. Because each optimizer is free to make the update as it sees fit. And some of them (life LBFGS) actually does multiple updates.
If you’re doing the update yourself by hand, then I guess you can do this by making your up… |
solarflarefx | So to my understanding, pytorch has the capability of doing direct GPU inference. For example, if the inputs are already in the GPU I can tell the inference network the input location in GPU memory and also specify where to place the output in GPU memory. The Torch::From_Blob method would be used for this.My question... | albanD | Hi,
Unfortuatly, from_blob can only take raw memory pointer (and size/stride informations). So you won’t be able to wrap complex data types inside a torch Tensor.
But if one copy is ok, you can dump it into a new contiguous memory buffer and use that. |
nierth | Hi,I am currently fiddling around with a PPO implementation where the loss depends on the entropy of a multivariate normal distribution. The entropy is calculated as followsclass Actor(nn.Module):
def __init__(self, state_dim, action_dim, config):
super(Actor, self).__init__()
self.net = nn.Sequent... | albanD | Hi,
The problem is that self.action_std is not the Paramter, the .to() op creates a new Tensor.
You should do
self.action_std = torch.nn.Parameter(torch.ones(action_dim, device=device)*action_std) |
yanweiw | Hi everyone -I am trying to backprop gradients to different parts of a computation graph. I have the following setup:out0 = model0(input0)
out1 = model1(out0, input1)
out2 = model1(out0, model2(out0))
loss1 = criterion(out1, ground_truth)
loss2 = criterion(out2, ground_truth)
loss3 = criterion(out2, input1)How to achi... | albanD | I assume there is a typo in your example and model2 is the one used to generate out2 right?
If so, if you a single optimizer, the best way I can see is:
model2.zero_grad()
loss2.backward(retain_graph=True)
model0.zero_grad(); model1.zero_grad()
(loss1 + loss3).backward()
opt.step() |
SwagJ | Dear all,I have a question about the memory consumption of tf.gather and pytorch equivalent implementation.So I have a tensor A of size: [Nx32], and an B array of [Nx3], every row of B is contains the row indices I wanted to select from A, so the final output I want will be an array of size:[Nx3x32]for exampleA = torch... | albanD | There are no extra concatenation here and it just reads the values and write to the result when you do indexing like that. So I would guess yes, they will use the same amount of memory. |
Landu | hello i found that 1.5 upgrade has change of autogradand also there is a tutorial for me who doesn’t know what’s wrong(https://github.com/pytorch/pytorch/releases) issue:[torch.optim optimizers changed to fix in-place checks for the changes made by the optimizer]def model(input, target, param):
return `(input * pa... | albanD | Hi,
The problem is that the original code here was computing wrong gradients.
You can modify this quite easily by overriding the linear forward function for this case:
class MyLinear(nn.Linear):
def forward(self, input):
return F.linear(input, self.weight.clone(), self.bias.clone())
… |
maaft | Hi,I have two convolutions which have the same shared weight. One is using dilation=1, the other is using dilation=2.Letxbe an input tensor, andwthe shared weight.Is there anything I can do to save memory when calculating:y = F.conv2d(x, weight=w, dilation=1) + F.conv2d(x, weight=w, dilation=2)and doing the backward pa... | albanD | Hi,
The memory consumption is doubled most likely because both outputs are saved.
Indeed, to compute the backward of the convolution, we need to know what was the output. So if you do two of them, we need to know both outputs. |
r_khanna | I am trying to visualize CNN(Vgg-16) by optimizing a random input image so as to maximize the activation of a given channel in a given layer. But after every certain number of iterations, i want to upsample the image as well. After the first time upsampling happens, this error is presented -RuntimeError: Function Cudnn... | albanD | Hi,
As a general rule, .data is never the solution you’re looking forEven though it can fix your issue, it is very likely to break many other thingsHere you just want the python variable “img” to point to a new leaf that is built based on the upscaled image:
img = upscale(img).detach() # Deta… |
cevvalu | I am trying to remove specific words from my string to have a clear output. Words are adding one by one in a loop:text += ’ ’ + wordtext looks like this for example:start this is a sentence end(need to remove start and end) | albanD | If you’re doing this after the fact, you can use the regular python string builtin to replace a string with another: sentence.replace("start", "").
Or if you always want to remove the begining and end, you can do sentence[len("start"):-len("end")-1]. |
Rio1210 | I am trying to train two models on two mutually exclusive portions of a datasets.Now while I am training both the models, I want to manually extract the Gradients from Model A and Model B, after forward propagation, then before updating the weights, I want to average both the model’s gradients and put the average of th... | albanD | Hi,
I would bet the issue is with:
pA.grad = avg
pB.grad = avg
Here you set the same Tensor to be the gradient for both parameters. So the backward passes will accumulate in the Same Tensor.
If you don’t want that, you need to add a .clone() for at least one of them.
Note that i… |
quoteunquote | Hi there, im a newbie at pytorch.I am running into the warning: “UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won’t be populated during autograd.backward(). If you indeed want the gradient for a non-leaf Tensor, use .retain_grad() on the non-leaf Tensor. ... | albanD | Hi,
This warning only means that you are accessing the .grad field of a Tensor for which pytorch will never populate the .grad field.
You can run your code with python -W error your_script.py to make python error out when the warning happens and so show you where it happens exactly.
The gist of t… |
111319 | I have a simple resnet. When training, I call forward to get output and calculate the loss. Then I backward the loss to get the gradients of weight and call optimizer.step() to train the net. Here, everything is OK. But then I want to call output.backward() again to get the gradients of inter-results of resnet, such as... | albanD | Hi,
Another solution is to compute these intermediate gradients before doing the step of the optimizer no? |
Nick_Cooper | Hi, I am attempting to train a system of two related networks in pytorch. However, I cannot seem to perform .backward() operations on the independent losses. When I do I get errors saying either:RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_gra... | albanD | Hi,
By default pytorch will differentiate your whole program.
If there are parts where the gradients should not flow back, you should make it explicit by doing t_without_grad_tracking = t.detach().
Here in particular, if you teacher uses the output of your student’s net for training, but the grad… |
seliad | I know that in pytorch 1.5to()andclone()can preserve formats and therefore we can send non-contiguous tensors between devices.I wonder, what is the case forcopy_()? can we send non-contagious tensors with it?If not, is there any suggested workaround for avoiding copy?for examplea = torch.randn(10,1, device="cuda:1").s... | albanD | Hi,
.copy_() will not change the contiguity of any Tensor.
It will just read the content from b and write it to a. Not changing the size/strides. |
satyajitghana | there’s this weird thing happening with me, i have a custom Residual UNet, that has about 34M params, and 133MB, and input is of batch size 512, (6, 192, 192), everything should fit into memory, although it doesn’t, it crashes consuming the entire gpu memoryhere’s the model:https://gist.github.com/satyajitghana/b24bfb6... | albanD | HI,
You can check the doc about how we manage the CUDA memoryhere.
In particular, this will explain why the memory is not returned to the OS when you delete your model.
For trying batch sizes, there are many things that can change the way the memory is allocated on the GPU and so, because of the… |
arijitthegame | Hello everyone,Hope everyone is staying safe. I have this monstrous functionf(x,p,t) = \int_{-\infty}^{\infty} sech^{2}(x + y/2)sech^{2}(x - y/2) × [2 sinh(x + y/2) sinh(x − y/2) +\sqrt(2) sinh(x − y/2)exp(i3t/2) +\sqrt(2) sinh(x + y/2)exp(-i3t/2) + 1]exp(−ipy)dyThis is essentially a Fourier transform but there is a sh... | albanD | I edited you message with ``` to do a code block and make it easier to readIt would be slightly different:
class dWdx(Function):
@staticmethod
def forward(ctx, x, p, t):
np_x = x.detach().numpy() # The detach should not be needed here, will be in a future version of pytorch
… |
S_M | HelloI aimed to calculate the jacobian of a tensor (n by m) with respect a tensor (m by d) so i tried this code:torch.autograd.functional.jacobian(output,W)where output is the output of my network and gives me the following erroroutputs = func(*inputs)TypeError: ‘Tensor’ object is not callablewould you give me some adv... | albanD | You can do that.
But if you already have a module, you can do:
mod = nn.Linear(10, 10)
jacobian(func, x) # To get the jacobian of the output wrt x
You should set create_graph=True if you want to backprop through that operation. |
yzz | Hi,I know that .backward() can dynamically calculate the gradient. I wonder how we can obtain the weight’s gradient layer by layer during the .backward() calculation. Hope someone could helpI know we can monitor the input and output of each layer during the .backward() by using .register_backward_hook(). I wonder iflay... | albanD | Hi,
The difference is that out.backward() will compute the gradient for all the leaf Tensors that were used to compute out and accumulate these gradients in their .grad field.
autograd.grad(out, inp) will compute the gradient of out wrt inp and return that gradient directly.
One way to see it is… |
theairbend3r | For instance, if I have a network as follows -class SomeClassifier(nn.Module):
def __init__(self):
super(SomeClassifier, self).__init__()
# all three conv blocks maintain the original image size.
self.cnn1 = nn.Conv2d()
self.cnn2 = nn.Conv2d()
self.cnn3 = nn.Conv2d()
... | albanD | Hi,
You should make your custom module an actuall independent nn.Module. And that will solve your issuesInstantiate it in the __init__ and use it in the forward. |
Steven_Duan | Hi:I am trying to implement an generative poisoning attack method and the paper can be found here:[1703.01340] Generative Poisoning Attack Method Against Neural Networks. So the problem I am having is very tricky and let me explain it step by step:Repeat:Step 1: I trained a resnet18 with animal images from 4 classes.St... | albanD | Hi,
The optimizer step done with pytorch optimizers are not differentiable I’m afraid. So the gradient won’t be able to flow all the way back. You can check the higher libraryhereto see how they do this using their custom differentiable optimizers.
Also you should not use .data. If you want to u… |
ku294714 | Hello All,I have come across a situation where i have a function written in matlab and i call it in my pytorch model to perform final computation on my model output. But during back propagation, my model parameter’s gradients are not calculated.I reproduced the issue with a toy example for better understanding:import t... | albanD | Hi,
When you use .detach(), you break the graph and so gradients cannot be computed anymore.
But the root issue is that for the autograd to work, the autograd engine needs to be able to know how to compute the gradient for each operation that is done.
Unfortunately, if you don’t use pytorch ops, … |
lifeblack | Hi!I want to code this matrix multiplication:B=16, h=32, w=56, b*b=64, n=25my code:torch.mul(torch.rand([16, 32, 56, 64]),torch.rand([16, 32, 56, 64,25]))but I encountered in with this error:The size of tensor a (64) must match the size of tensor b (25) at non-singleton dimension 4Would you mind helping me to fix this ... | albanD | Hi,
I think the simplest is to write it as a matrix matrix multiplication. And so add a temporary dimension of size 1 on the first Tensor:
torch.matmul(torch.rand([16, 32, 56, 1, 64]),torch.rand([16, 32, 56, 64,25])).squeeze(-2) |
Y_Y | Hi all,I got the error messageopt/conda/conda-bld/pytorch_1579022060824/work/aten/src/ATen/native/cudnn/RNN.cpp:1266: UserWarning: RNN module weights are not part of single contiguous chunk of memory. This means they need to be compacted at every call, possibly greatly increasing memory usage.when I tried to run the fo... | albanD | Hi,
Have you tried using module.flatten_parameters() on your RNN module to make sure the weights are nicely layed out in memory again? |
millanp95 | Hi, I have defined the following 2 architectures using some valuable suggestions in this forum. In my opinion they are the same, but I am getting very different performance after the same number of epochs. The only difference is that one of them uses nn.Sequential and the other doesn’t. Any ideas?The first architectur... | albanD | One has a Softmax for output and one has a LogSoftmax. Is that expected? |
mscipio | ContextI am trying to use Pytorch’s optimizers to performnon-linear curve fitting. I have an overall code that is working. Here it comes:import torch
import torch.nn as nn
import torch.nn.functional as F
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(device)
import matplotlib.pyplot as plt
class Net(nn.... | albanD | Hi,
Your problem is a bit different from the classical neural net as you have one weight per sample that you just try to hardcore over-fit to it.
In your current code, even though you have a single loss which is the mean, since each element before the mean is computed completely independently from… |
slavavs | I have a I have a matrix [5.5].I have to average and get the matrix [1,5].How do I do that? [5,5].I have to average and get the matrix [1,5].How do I do that? | albanD | Hi,
You can specify the dimension you want to reduce over in the mean functions:
A.mean(dim=0). |
sscardapane | Hi everyone! For my research, I have the need to compute aJacobian-vector product(JVP), where the Jacobian is of the outputs of ann.Module(on a mini-batch) w.r.t. its parameters. Basically, the output of the JVP has the same size as the outputs of the original network.I installed PyTorch 1.5 because of the newfunctiona... | albanD | Hi,
Yes the nn.Module construction makes it quite hard to be functional as it is based on the fact that the parameters are part of the state.
But here you can cheat by removing the parameters from the module and setting the new Tensors one by one before the forward. An example is below, you should… |
cbd | What strict=false do in load_stat_dict?I read it load with missing parameter. For an example if i have module of 4 convolution layer followed by BN and RelU. Then if i have pth file of 3 convolution layer followed by BN and RelU OR 5 convolution layer followed by BN and RelU then it is possible to load weights using t... | albanD | It will if the ones that match have the same name and the same paramters.
In general, it is used if you extend a given Module to add extra stuff but you still want to be able to load a checkpoint from the original module that contains the paramters from all the common pieces. |
Sam_Pr | I’m implementing a version of DDPG, and trying to calculate the policy loss.# TODO: Should find grad for states, policy_actions but treat q_model params as constant
policy_loss = -self.q_model(states, policy_actions).mean()I can do this by looping throughq_modelparams, storing current values, settingrequires_gradtoFals... | albanD | Hi,
I don’t think there is any update. The for loop is simple and is the most efficient thing that can be done here.
Especially with your special logic of things already not requiring gradients, that would be tricky.
Note that you can add a method to your q_model module yourself to do that to mak… |
Anshumaan_Dash | Greetings everyone,I am trying to define a loss and use backward() on it. However, I am getting the error: One of the variables needed for gradient computation has been modified by an inplace operation.Here is the code:for displaying the target image, intermittentlyshow_every = 400iteration hyperparametersoptimizer = o... | albanD | Hi,
You can try adding this at the beginning of your code:
for mod in modulelist:
if hasattr(mod, "inplace"):
print(mod)
mod.inplace=False
All the ReLU in vgg are inplaceAnd they modify your img1/img2 inplace. |
John_J_Watson | I am trying to pass an output of a pretrained classifier model to a bunch of conv2D and linear layers (to get some embeddings eventually), but since the classifier outputs a dim of [4,10], I am having trouble passing this to the conv layers.So, I have:def forward(self, data):
x = data
x = self.model_f... | albanD | Hi,
The conv2d expects an input of size: (batch, channel, height, width). |
andrea_bragagnolo | As title says, does PyTorch perform some kind of under-the-hood optimizations for zeroed-out parameters in a network’s layers? I.e., would the forward() method of a normal network be slower than the same architecture but with some of its weights set to 0? | albanD | Hi,
No we don’tChecking for the content of a Tensor is usually more expensive in most cases than the potential gain you could get from it here. |
Neofytos | Is it possible to access and edit the graph on the go?What I mean is the following:Say, we have variables a and b and we can compute c as a function of a and b, i.e. c = f(a, b). For the forward propagation we need to know a, b and the function and for the backward we need the derivative of the function and then any pa... | albanD | I guess the simplest way is to implement a custom autograd function here:
class CheapF(autograd.Function):
@staticmethod
def forward(ctx, *args):
return g(*args)
@staticmethod
def backward(ctx, *grad_outs):
return f_backward(*grad_outs)
# Use it as
outputs = CheapF.apply(inputs)
N… |
Neofytos | I have some images “X” which I pass through a network that outputs some boundary boxes. Based on these boundary boxes I crop “X” and get “cropped X”. The “cropped X” is reduced to grayscale and the mean is computed (per image).In case the mean is < 0.8, I change it to 0, otherwise, it keeps its value. This is then used... | albanD | Hi,
Indexing operation is not differentiable with respect to the index. So no gradient will flow back bbxes. Is that expected?
Indexing operation is differentiable with respect to the indexed tensor. So if it requires grad, then the output will too, otherwise it won’t. You should not set it by han… |
anshu957 | Hi everyone,I’m new to the forums, so correct me if I have not framed the problem correctly.I’m in a situation where I have to make a copy of a specific block of the network for some further calculations (like Jacobian)My network looks like this:class AutoCanonical(torch.nn.Module):
def __init__(self, d_in, d_hidde... | albanD | Hi,
Given that all the modules are on the same module, you will have to work with the whole Module.
You can make a simply copy of it here by doing
new_model = AutoCanonical()
new_model.load_state_dict(current_model.state_dict()) |
Megh_Bhalerao | Hi all,I am using a feature extraction module as given below:class FeatureExtractionModule(nn.Module):
def __init__(self,feature_dimension,input_channels, kernel_size = 5, dropout_p = 0.3,leakiness = 0.01):
super(FeatureExtractionModule,self).__init__()
# Defining the hyperparameters of the convolut... | albanD | Hi,
You can check the doc for F.linearhere: the weights should be passed one after the other, not as a tuple of two Tensors. |
bing | I am trying to use transfer learning. I want to freeze the parameters of the model apart from the batch norm layers. I am using the below code but gettingtoo many values error.for name,param in model_transfer.parameters():
if ("bn" not in name):
param.requires_grad = FalseError:ValueError ... | albanD | Hi,
If you want both the name and the parameter, you need to use model_transfer.named_parameters(). |
antonio | I followedthis previous threadto measure how much memory is being allocated for the input tensor to my CNN. After applying the formulatensor.element_size() * tensor.nelement()I discovered that each example allocates 1.18 Mb. The dimension of this tensor is (batch_size, num_images, input_height, input_width, n_channels)... | albanD | Hi,
When we send things to the disk, we always compress them.
But when they are on memory, to be able to use them efficiently, we cannot keep them compressed. So yes it is expected that they take more time in memory than on disk. |
Megh_Bhalerao | I am training a model on my local MacBook. My dataloader looks something like this:data_train_source = MNISTSourceTrain("path1","path2")source_train_loader = DataLoader(data_train_source,batch_size=64,shuffle=True,num_workers = 0)When I setnum_workers=0, the program runs. But, for any value ofnum_workers>0, I get the f... | albanD | Hi,
As mentionned in the error, does your program has the proper if __name__ == '__main__': guard? |
seliad | We want to profile backward time for in place operations, e g:a *= bFor this we need to detach a, and set requires grad to True.However then it’s a leaf variable modified inplace which autograd doesn’t allow.Is there any workaround? | albanD | Hi,
I’m not sure to understand your goal?
You want to benchmark the runtime of a single op ?
If so, you can do:
base = torch.rand(10, requires_grad=True)
a = base + 1 # The backward of this is an identity so as fast as it can get
a *= b
a.backward(a)
But note that you’re mostly going to measu… |
sumching51 | def backward_theta(self, x, y):
self.vgg16.train()
loss, prob_trees = self.get_loss(x, y)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()This code above can run normally, but the code below raise the error “CUDA out of memory”. Is something wrong in the else plac... | albanD | Hi,
The backward pass will clear all the buffers saved in the computational graph. So yes it can do that.
If you want to do the same, you need to make sure all references to the computational graph are gone. so del loss and del prob_trees here most likely. |
Umair_Javaid | a = torch.rand(2,5,10)I want to select at most 5% of values from tensorarandomly and then multiply those values with-1? How to do that? kindly, give a generic solution as the shape of the tensor is not fixed | albanD | Hi,
I guess you can do out = (torch.rand_like(a) - 0.05).sign().type_as(a) * a assuming a is a floating point number. This should select around 5% (the bigger the Tensor, the more precise it will be). |
Ibrahim_Banat | the file of this function is imported and when running (python train.py --epochs 1) i got this error:--------------Training is starting-------------
Traceback (most recent call last):
File "train.py", line 48, in <module>
suppFunctions.train_network(model, criterion, optimizer, trainloader, epochs, 20, power)
... | albanD | The problem is thathereyou return model, criterion, optimizer
Buthereyou unpack model, optimizer, criterion.
Notice that the optimizer and criterion are swapped. You need to swap them back. |
Aeglen | I am trying to use “mult” as learnable weights in this model, yet despite being in model.parameters() and requires_grad=True the weights aren’t being updated (and indeed mult.grad = None). What could have gone wrong?class NeuralNetB(nn.Module):
def __init__(self):
super(NeuralNetB, self).__init__()
... | albanD | Hi,
The nn.Parameter() always require gradients, no need to specify it.
Also when you do .to() you get a new Tensor (which is not a leaf Tensor !) Didn’t you get a warning when you did the optimizer step?
You should change the definition to self.mult = nn.Parameter(torch.rand(3, device=device)) |
Umair_Javaid | vgg16 = models.vgg16(pretrained=True).features[:16]
brach_A = vgg16.clone()I get the following error on the above code:**'Sequential' object has no attribute 'clone'** | albanD | Hi,
This is because we don’t have a method to clone nn.Modules.
If you want another ref to the same module, use b = a
If you want a shallow copy, you can use the copy module from python
And if you want a deepcopy, you can use the deepcopy module from python. |
Umair_Javaid | vgg16 = models.vgg16(pretrained=True)
vgg16_ = models.vgg16(pretrained=True)I want to know ifvgg16andvgg16_are pointing to the same memory address? If yes, how do I get two separate vgg16 models? And, also how do I check this? | albanD | Hi,
No they will be pointing to different memory.
You can check that by checking the data_ptr() of the different weights and make sure they don’t match. |
yzz | I see torch.autograd.grad() can calculate the gradient for input and output, and returns the gradient. If I understand the code correctly, the returned gradient tensor is allocated while performing the computation. I wonder if it is possible to ask torch.autograd.grad() to output the results to a user predefined tensor... | albanD | If you use .backward(), then you can simply do that by setting the .grad field of your parameters before calling the .backward() function. No need to change anything else. |
angshine | Asrelease note of pytorch 1.5says,Tensor.clone,Tensor.to,Tensor.empty_like, and similar functions preserve stride information instead of returning contiguous tensors. When migrating to pytorch 1.5, I met “RuntimeError: view size is not compatible with input tensor’s size and stride (at least one dimension spans across ... | albanD | Hi,
Yes I think it comes from there.
Does this error happen during the forward or the backward pass?
If forward, can you give the stack trace that shows which function is faulty?
If backward, you can enable the anomaly mode (torch.autograd.set_detect_anomaly(True)) to get a warning that will tel… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.