user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Mammothbagpipe | Sorry for my questions, though I am fairly new into this topic. I am trying to learn a model to guide a gradient step in MAP restoration. My first question is simply if it is possible to backpropagate a gradient step (with adam optimizer)?My second question is how to do this?My code, for one step, is following (shotene... | albanD | I think you can specify a grad_callback in higher if you want to modify them before the optimizer step |
seliad | Hi,I saw that in 1.5 usage oftensor.dataas removed from most places,I wonder,why?I want to change weights explicitly so the forward and backwardwill notbe used on same data (I used .data so far to do it). What options do I have for that? | albanD | can you elaborate on the side effects you know?
Break the computational graph
Break the inplace correctness checks
Allow untracked inplace changes
Allow inplace metadata changes of a Tensor
When using nn.Parameter, it alias with the .data in that class that refers to the underlying Tensor.
whe… |
WaterKnight | When I prints shape from a tensor I get:torch.Size([0, 1, 1004, 1002]).This means that there is no element in that tensor? | albanD | Hi,
Yes that means that the Tensor is empty. |
ecdrid | I am getting this weird error when i am using the following funcs in my training loop as soon as it hitsloss.backward()def pos_weight(pred_tensor, pos_tensor, neg_weight=1, pos_weight=1):
# neg_weight for when pred position < target position
# pos_weight for when pred position > target position
gap = torch.... | albanD | The problem is that pos_weight is not actually differentiable because the argmax op is not differentiable.
But due to a bug on our side, this is detected too late and here is a minimal repro:
import torch
from torch import nn
t = torch.rand(10, requires_grad=True)
bad = torch.argmax(t)
res = ba… |
Lupos | The newer PyTorch version 1.5 is now preinstalled on google colab. But my code is not working on the newer version, that’s why I want to install the PyTorch version 1.4.But when using(i dont know if that breaks cuda on colab hopefully not):!pip install pytorch==1.4I get the error message:ERROR: Could not find a version... | albanD | You can find the instructions on the websitehere.
In particular, you’re missing the -f part of the command. |
smani | I have a feature map of size NxCxWxH, where,N is the batch sizeC number of channelsW widthH heightI have indices of length N where each index in this list corresponds to a channel. I need to select the channels based on these indices. The size of the output should be Nx1xWxH or NxWxH. How can I do this? | albanD | Hi,
I think you want to expand your indices as Nx1xWxH by doing ind.view(N, 1, 1, 1).expand(N, 1, W, H).
Then you can use gather to get the values: res = value.gather(ind, 1).
Then if you want to remove the dimension of size 1, you can do res = res.squeeze(1). |
Ge0rges | Hello,Sometimes my program crashes with the following stack trace:File "/Users/GeorgesKanaan/Documents/Development/Python/KNet/src/main_scripts/train.py", line 101, in l1
penalty += param.norm(1)
File "/Users/GeorgesKanaan/Documents/Development/Python/KNet/venv/lib/python3.8/site-packages/torch/tensor.py", line 3... | albanD | So testing the code and changing the hook to:
def __call__(self, grad):
try:
grad_clone = grad.clone().detach()
if self.is_bias:
grad_clone[self.currently_active] = 0
else:
grad_clone[self.currently_active, :] = 0
… |
azeeshan | I want to update the weights (theta) of my neural network using the update rule (t+1:next epoch, A is a constant, f and g are function of theta):theta_{t+1} = theta_t + A f(theta) \nabla [ g(theta) + f(theta) ]where nabla gives the derivative of the g and f with respect to theta.Currently, the way I am implementing thi... | albanD | That would depend what your optimizer is.
It might be clearer to have a custom optimizer that does the scaling by A * f?
out = g + f
out.backward() # Compute \nable [ g + f]
optimizer.step(A * f)
But both should do the same step in the end (if your optimizer above is like SGD and has a lr of 1). |
jwillette | I have a training loop iteration that looks like this…mu, logvar = m(x)
alpha = torch.zeros(size, requires_grad=True)
loss = alpha * criterion(mu, logvar)
loss.backward(retain_graph=True, create_graph=True)
for p in m.parameters():
p = p - LR * p.grad
x_next, y_next = data[j + 1]
mu_next, logvar_next = m(x_next)
... | albanD | I think the problem in your code is:
for p in m.parameters():
p = p - LR * p.grad
This does not modify p inplace ! It just assigns the result to a variable name p that you override just after. So you could remove these lines and your code would run the same.
This is why you don’t see the link.
… |
JPSmith | So I have the following code:import torch
import torch.nn as nn
import math
torch.autograd.set_detect_anomaly(True)
def sigmoid(x):
return 1 / (1 + torch.exp(-x))
dtype = torch.float
device = torch.device("cpu")
# device = torch.device("cuda:0") # Uncomment this to run on the cpu
# N = batch size
# D_in = input... | albanD | Hi,
The torch.no_grad() hides these ops from the autograd engine so that when you call .backward(), they won’t be taken into account. So this is the right use here.
The error you’re seeing is different: when the forward pass needs some Tensor to be able to compute the backward pass, this Tensor is… |
carlogarro | Hello, I have a doubt with dataoader. If batch size = 1 and workers = 0, when iterating the dataset, when printing I receive one print output.But when batch size = 1 and workers = 1 I receive two print outputs, is it normal? I thought I should receive also one. And when, for example, batch size = 2 and workers = 2 I sh... | albanD | Hi,
When workers = 0, the loading happens synchronously on the same process and so each batch is loaded when asked for.
When workers > 0, since loading is done in other processes, we have more freedom. In particular, we preload future batches in advance so that when you ask for them, they are (hop… |
Dominik | I’m using PyTorch for physics simulations and I’m facing the problem that the output of the simulation is NaN. I checked all my inputs (the parameters of the simulations,requires_grad) and they are all non-NaN.So I’d like to traverse the graph backward, inspecting the value of each node, in order to find out at which s... | albanD | I’m afraid the graph that we create to compute gradients does not store all the intermediary results (only the ones that are required) and they are not easily accessible to the user in general.
What I mean by binary search is:
Take the middle of your code
Is the nan already there?
If so, do the s… |
Abueidda | Hi all,I have a model that has multiple inputs, and I was wondering if it is possible to find the gradients of the output with respect to the inputs.The layout is as follows:output = f(inp1, inp2, …)To do so, we minimize the loss: Solve MSE optimization problem loss ||output-target||Then after the model is trained I am... | albanD | Hi,
First, make sure your inputs require gradients:
If they don’t, just call requires_grad_() on them before giving them to your net
If they do and are leaf (inp1.is_leaf()) then you’re good to go
If they do but are not leafs, you can do inp1.retain_grad() to make sure the .grad field will be pop… |
vainaijr | when I apply Jacobian in PyTorch autograd (torch==1.5.0), it gives me three dimensional output.for example,def exp_reducer(x):
return (x**2).sum(dim=1)
inputs = torch.rand(2, 2)
torch.autograd.functional.jacobian(exp_reducer, inputs)tensor([[[0.3296, 0.9791],
[0.0000, 0.0000]],
[[0.0000, 0.0000],
... | albanD | Hi,
Yes we follow a slightly different semantic.
The usual definition for multivariate functions is given a 1D input and 1D output, you end up with as 2D Jacobian.
What sympy is doing here is to linearize the inputs from a (2, 2) Tensor into a (4,) Tensor. And so the Jacobian is (2, 4).
Because … |
JWL | I have a snippet of code that uses gradient checkpoints fromtorch.utils.checkpointto reduce GPU memory:if use_checkpointing:
res2, res3, res4, res5 = checkpoint.checkpoint(self.resnet_backbone, data['data'])
fpn_p2, fpn_p3, fpn_p4, fpn_p5, fpn_p6 = checkpoint.checkpoint(self.fpn, res2, res3, res4, res5)... | albanD | Hi,
This most likely happens because the first part of your model doesn’t get gradient because of some quirks of how checkpointing works.
Can you try making data['data'] require gradients before giving it to the checkpoint? (you can ignore the computed gradient, just add a data['data'].requires_gr… |
ksarker1 | I am working on a project that requires me to write a method that is not differentiable. Hence I have calculated the gradient w.r.t the input of this method. Now I have tried to use register_hook to return the calculated grad to be able to flow the gradient backwards from there. But register_hook is not being called fo... | albanD | Hi,
You can use a custom Function to specify a backward for a given forward. You can seeherehow to do this. |
ProGamerGov | Is it possible to create a tensor like this in a more efficient manner?height, width = 128,128
w = torch.arange(0, width)
h = torch.arange(0, height)
tensor = torch.zeros((width, height, 2))
for vi in w:
for vj in h:
tensor[i][j] = torch.tensor([float(vi) / height - 0.5, float(vj) / width - 0.5]) ... | albanD | Hi,
The following will generate the same Tensor without the loop:
full_size = (width, height)
w_exp = w.unsqueeze(1).expand(full_size).true_divide(height) - 0.5
h_exp = h.unsqueeze(0).expand(full_size).true_divide(width) - 0.5
tensor = torch.stack((w_exp, h_exp), -1)
tensor = tensor.reshape(width… |
TinfoilHat0 | Hi,I’m trying to implement the algorithm describedhere.A short description of the related part is as follows.Screenshot from 2020-04-22 06-09-37527×523 48.5 KBMy attempt is as follows.# 1. Forward-backward pass on training data
_, (inputs, labels) = next(enumerate(train_loader))
inputs, labels = inputs.to(device=args.... | albanD | Hi,
I think you’re missing a create_graph=True in the first backward if you want to be able to backprop through the backward pass.
Also pytorch’s optimizers are not differentiable (yet). So you won’t be able to backprop through that step either.
I would recommend using the higher package to do th… |
Shashank_Holla | Hi, Im trying to train resnet18 on tiny Imagenet dataset.But during the model training, the execution is failing at NLL Loss calculation with error message- RuntimeError: cuda runtime error (710) : device-side assert triggered at /pytorch/aten/src/THCUNN/generic/ClassNLLCriterion.cu:110.I have enabled -os.environ[‘CUDA... | albanD | Hi,
And error in this place is usually wrong labels.
Can you try running your code on CPU to see what it says? |
Aptha_Gowda | #model1
def getmodel():
model = EfficientNet.from_pretrained('efficientnet-b5')
model._fc = nn.Sequential(
nn.Linear(in_features=2048, out_features=1024, bias=True), #first layer
nn.ReLU(),
nn.BatchNorm1d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
... | albanD | Hi,
The thing is that in your case, you have a ReLU between the Linear and Batchnorm. So that statement may not be true for your model.
I think that statement comes from the fact that the batchnorm will center the values. So a bias is useless in the previous layer as it will just be cancelled by … |
TinfoilHat0 | Say I have 2 independently trained models (with identical architecture) with parametersparams1andparams2.I’d like to find out if there exists real valuesw1andw2s.t. the model with parameters(w1 x params1+w2 x params2) / 2performs well on some validation set.To test this, I’ve written the following piece of code.w = tor... | albanD | It’s not going to be very clean. But the following should work:
import torch
from torch import nn
model = nn.Sequential(nn.Linear(2, 2))
# Save the location of the parameters now
# Since we delete them later, we won't be able to call this function anymore
model_params = list(model.named_parameter… |
111293 | Hello everyone, i am just a beginner in Pytorch, recently i try to adjust STN to make it works on fish eye image, but i am trapped in problem of “one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [1, 2, 28, 2]], which is output 0 of SliceBackward, is at v... | albanD | Hi,
The error states that you are modifying inplace a Tensor that you are slicing. So an op like your_tensor[ind] = xxx.
It states that because the original value of this Tensor is needed for backward computations, this is not valid.
You should replace this by and out of place operations.
In par… |
Omroth | Hi, I’m trying to implement a simple Reinforcement Learning model with training, but on the line “loss.backward();” - I get “leaf variable has been moved into the graph interior”. Can anyone help?(I have looked at other posts here from this error but I’ve been able to spot the issue.)struct CNetwork : torch::nn::Modul... | albanD | Yes that looks like a suspicious place.
And yes this is the right way to use the guard. This is the same as using with torch.no_grad() in python.
Does this fix your issue? |
mowolf | I need the gradient of this warping operation.// - tensor : output of my neural network
// tensor.requires_grad = True
warped_tensor = F.grid_sample(tensor,
grid,
align_corners=True,
mode='bilinear',
... | albanD | Depends on the warping you apply.
You can loose precision when you warp if you collapse multiple input pixels into a single output one?
I can take a look if you have a small code sample yes ! |
Nitesh | I’m using the technique of saving and loading the models as suggested in the Pytorch docs. I checkpoint the model whenever the current loss is lesser than the previous one. The problem here is that when I evaluate my validation data set, I’m getting the same accuracy with or without using checkpoint to load the model. ... | albanD | Hi,
The problem is that when you get the state dict, it does not clone all the Tensors but gives you reference to them.
So when further training updates your model, it also updates the values stored in your checkpoint.
You can do: checkpoint['state'] = {name: t.clone() for name, t in model.state_… |
csailnadi | I could not find a good documentation onregister_backward_hook()function.I cannot figure out what it receives for the argumentgrad_in.def hook_layers(self):
def hook_function(module, grad_in, grad_out):
self.gradients = grad_in[0]
print("len(grad_in) ", len(grad_in))
print("g... | albanD | Hi,
You can check the doc for itherein particular the warning in there that explains that this is a known limitation (or bug) of the current implementation. |
Andrea_Rosasco | I was given access to a remote workstations where I can use a GPU to train my model. Of course all the resources are shared and the GPU memory is often partially used by other people processes.Does getting a CUDA out of memory error means I just made someone else’s process crash? | albanD | It’s possible but not sure.
Basically whichever user asks for memory when it is full will see its process getting killed.
So it can happen to only one user, or all of them if they all happen to ask for memory at that time. |
sait | Say there is function F . which cannot be computed exactly but it’s gradient can be perfectly defined can I define function s.t I tell the autograd , how gradient should be computed instead of autograd figuring about by computation graph. So my requirement is as following,function F(x) :
#cannot be computed exac... | albanD | Hi,
You will need to use a custom autograd.Function for that.Thissection of the doc shows you how to do so and how to use it. |
ttoosi | Hi,I am trying to define customized modules (Linear, Convolutional, etc) where I would like to have all sorts of regularizations on parameters. I provided a snippet below to clarify my question.I don’t want to calculate gradients of those regularization loss functions manually, so I am usingautograd. The problem is tha... | albanD | Hi,
If you’re not running with creat_graph=True, then the backward runs with autograd disabled.
If you need to enable it locally you can use with torch.enable_grad():. Also I would advise you to use autograd.grad here to get the gradient more easily:
local_net = nn.Sequential(nn.Linea… |
csailnadi | I cannot figure out why .grad is None while the weights have required_grad = True?class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Lin... | albanD | Hi,
The problem is that you index the weights when you do [1]. So you get a new Tensor that does not have a .grad field.
model.convos[1].weight.grad should not be None right? |
reubens | I have factory reset my iMac today. Installed latest Anaconda, created env, activated env, followed instructionshere.This is the error message I receive when I try to run any code with torch.File "torch.py", line 1, in <module>
import torch
File "/Users/reubenschmidt/code/python/nn/cxr_net/torch.py", line 3, in <... | albanD | Hi,
This most likely happens because you have a local file called torch.py. And so when you do import torch, it tries to import that local file instead of the torch library. You should not have a file (or folder) with the same name as a library you use locally to avoid issues |
Alex5 | Hi,I’m running make html in docs folder in order to generate offline documentation but I got an error:Traceback (most recent call last):File “source/scripts/build_activation_images.py”, line 68, infunction = torch.nn.modules.activation.dictfunction_nameKeyError: ‘GELU’Makefile:17: recipe for target ‘figures’ failedmake... | albanD | If you are on the master branch, you need to have a pytorch from the master branch installed. You can check with print(torch.__version__) in a command line.
If you have 1.3.1 installed, you will only be able to build the 1.3.1 doc. |
dfalbel | This may be a fairly rare edge case, but wanted to confirm if this should be possible with the c++ api.Suppose I have the following program callingbackwardof a different graph inside the backwardhookof another one from a different thread.I always need to call backward in a different thread because the main thread must ... | albanD | Ho right.
The thing is that your hook actually waits on the other backward to finish because it waits on the the other thread.
The thing is that because the hook is blocked waiting on this, another thread cannot use run backward (this current thread can though).
So you either want to run this oth… |
pzamo | Hello,I find that the doc and the topics around autograd.grad are very unclear. Especially concerning the Jacobian-vector product.Here is what i struggle with:I need to compute the Jacobian-vector product vJ for one layer of neural network.Say f(x, w) is a parametric function from R^(2xn)xR^2 in R^n (n being the batch ... | albanD | Hi,
I think the misconception here is between vector jacobian product vs jacobian vector product.
Reverse mode AD that all DL framework use for vector jacobian products. Where v is of the size of the input.
If you want to do jacobian vector product, (and so v is the same size as the input), you n… |
nik31096 | I tried to implement multi-env DDPG in PyTorch and (I don’t know how) implemented it with a stochastic policy. And it worked. Here is the code:[main loop from DDPG file]for epoch in trange(1000):
for step in range(1000):
actions = online_policy_network_cpu(states['observation'], states['desired_goal'], stat... | albanD | If you don’t want gradients to flow back as before, you can use .detach().
Otherwise you want to make sure that your observation/desired_goal/achieved_goal are Tensors that do not depend on the previous iteration (in a differentiable way) and use .detach() where needed to break these links if they … |
barakb | In order to explain my issue, I’ll just show step by step:First let’s build a simple model:class Model(nn.Module):
def __init__(self):
super(Model,self).__init__()
self.fc = nn.Linear(10,2)
def forward(self,x):
return self.fc(x)Let’s declare the model ,optimizer and a random input:model = Mode... | albanD | You can simply look at dloss1/dloss * dloss/dout
Here you do a product of matrices: [1, 1] * [[S0(1-S0), -S0*S1], [-S1*S0, S1(1-S1)]].
And so the result is: [S0(1 - S0 - S1), S1(1-S1-S0)]. But because your softmax has only two entries, we know that S0 + S1 = 1. So the result for the gradient is [0… |
murph213 | Like others, I have found that trying to manually initialize weights in-place is successful when throughweight.databut not throughweightalone. But I am trying to understand this more deeply. The following code shows three possible (not necessarily equivalent) ways and whether they work.import torch
import torch.nn as... | albanD | Hi,
.data should never be used. It is doing very dangerous things under the hood and has many unwanted side effects.
To make operations that are not recorded by the autograd, you should use with torch.no_grad():.
This is exactly what the nn.init module does as you can seeeherefor example. |
murph213 | I know that the.dataattribute of tensors has been deprecated (when Variable got merged into Tensor) and I also know its use is discouraged because it causes problems with gradient computation. However, I still come across old code bases that use it extensively. In initial phases of my short-term projects, I do not wa... | albanD | would it be dangerous or lead to unintended consequences to use .data here?
Another major difference between .data and .detach() that you don’t mention here is inplace correctness.
Basically, when we save Tensors because their value is needed to compute the gradients, we have special logic that … |
Angry_potato | Hi,I am implementing neural style transfer. So for optimising loss i update input image which is a torch.FloatTensor. Till now i was explicitly performing optimisation by multiplying gradient with learning rate as i cannot use the inbuilt optimizer such as Adam as the argument to optimizer should be iterable or dict of... | albanD | Hi,
If you have a single parameter, you can pass it to the optimizer in a list that contains a single element (this single parameter). |
themoonboy | Hi guys, when usingtorch.where, it works as a threshold thus unable to pass the grad by torch.autograd.grad(…). Instead, is there a way to keep to same graph and pass through to next differentiable operation?For example, in a very simple code belowimport torch
a = torch.tensor([[1.0, 2.0], [3.0, 4.0]], requires_grad=T... | albanD | Hi,
You can. write a custom Function whose backward will be the identity while the forward is your torch.where.
You can findherehow to write such Function. |
Sriharsha-hatwar | While reading a pytorch code there was comment where it said we have to once again move the model trained in the GPU to device using.to('CUDA'). So I was wondering the scope of.to('CUDA)? Will it persist in the cuda memory until the program is terminated or the scope of function is terminated? what happens if we pass t... | albanD | Hi,
Yes it is a one time thing. And the weights will stay on the GPU until you delete the model, or move it back to the cpu().
This comment might be related to loading of a saved model maybe? With the saved model being on CPU. |
2CuteChiquita | Hello,How do I move a CUDA extension after it has been build?Right now I rebuild the extension every time i rerun the code but as the code inside the extension is unchanged this shouldn’t be necessary.Is there an easy way to do this? | albanD | You can specify the build directory if you want and share that directory between your docker images (seedoc). |
AnupKumarGupta | I have to apply the following operations on a video (frame-wise)RGB to grayscaleCenter CropColor NormalizeGive the video (the sequence of the frames) as input to a model.Moreover, I have to compute gradients over these operations later. I asked thisQuestionand was suggested to useKorniawhich supports gradients over the... | albanD | Hi,
The reshape operation is differentiable in pytorch. So it should not prevent you from computing any gradient.
Also I think you want to permute dimensions, not reshape them: input = input.permute(1, 0, 2, 3). |
oneil512 | Hi,I am training an RNN, and computing a loss for each step of the output sequence. Is calling loss.backward(retain_graph=True) for each step of the output more memory efficient/faster than summing loss = loss_step1 + … + loss_stepn and then calling loss.backward()? I have tried both, and they seem to give the same acc... | albanD | Hi,
summing the losses and calling a single backward is going to be more efficient unless each loss work with independent networks and it will be the same.
But basically you can’t go wrong with doing the sum and a single backward !. |
disguise | I run the code:y = t[0, :]
y += 1
print(y)
print(t[0, :])the result is :tensor([5, 9, 9])
tensor([5, 9, 9])yandt[0,:]share memory. But after I changed the index, I run the new code:y = t[0, [1, 2]]
y += 1
print(y)
print(t[0, [1, 2]])the result is:tensor([10, 10])
tensor([9, 9])yandt[0, [1, 2]don’t share memory。Do you ... | albanD | Hi,
This is because advanced indexing methods (fancy things in brackets) try to return view but they cannot always do it. So you should not rely on it returning the same memory.
If you just want to change this part of t, you can use t[0, [1, 2]] += 1 that will change t inplace properly. |
James_e | I have some questions regarding the theory of autograd:1.) Are y and x the input and output respectively?2.) Where does v come from? and how is it computed?Screenshot 2020-03-24 at 23.31.421662×760 92.8 KB | albanD | Hi,
When you write y = f(x), that means that x is the input. And y is the output.
v can be any Tensor you want. A special example is if you function has a single output (like a loss function in NN) then J will be a simple row and by setting v = 1, you get the gradient of your function. |
Eugene_Lee | Hi there. Let’s say we obtain a set of gradients for a set of weights as follows:grad = torch.autograd.grad([output], [m for m in self.parameters()],
grad_outputs=[grad_input],
create_graph=True, retain_graph=retain_graph,
... | albanD | You will have to differentiate between the leant parameter in netB and the ones that are computed at each forward.
One thing you cal do is rename parameters like weight into weight_orig. Then del the weight. And in the forward part, set the weight as weight_orig + your_udpate. |
odats | In my custom dataset, the data is loaded from Pandas. There is augmentation by creating a new item based on a simple rule:def augmentation_by_color(x, colors):
x = np.array(x)
return np.array([colors[xi] for xi in x.flatten()]).reshape(x.shape)
colors = [0,1,2,3,4,5,6,7,8,9]
colors = np.random.permutation(color... | albanD | Hi,
Yes I would say that doing this as a single indexing operation would make it much faster.
Maybe something as simple as colors[x]? Or colors[x.flatten()].reshape(x.shape) ? |
polo5 | Hi, I use forward mode differentiation and I get the same gradients as reverse mode but much slower. The bottlneck of my code is the Hessian vector product which uses a for loop, is there a more efficient way of doing it?D = n_weights
K = n_hyperparams
Z = torch.zeros((D, K)) # input that changes through time
HZp = to... | albanD | The problem is not the product but that you only want to gradients corresponding to part of it. In some sense, you have K different loss functions. So if you want the gradients for each of them you need to do K backwards. I don’t think there is any way around this. |
Giuseppe | Hy guys, I have different values in my code if I use mode.eval (That give the results almost right) instead of model.eval(). I am going to explain better.I use my training set for testing and, cause I have a loss in training time of zero, I think that my net give me the same result of ground truth. But it doesn’t. an... | albanD | The thing is that batchnorm behaves very differently in training and eval mode. And there are many examples of models that have this exact problem. When using the saved statistics, the quality of the result is not as good. |
seyeeet | I have a tensor which is on gpu 0.how can I move (or make a copy of it one gpu 1)?A = torch.rand(1)
cuda0 = torch.device('cuda:0')
cuda1 = torch.device('cuda:1')
A.to(cuda0)
# now I want to move A to gpu 1
A.to(cuda1)gives me error:RuntimeError: CUDA error: invalid device ordinal | albanD | Hi,
Are you sure the second GPU is properly available? What does device_count() returns?
You might be hidding the second GPU with CUDA_VISIBLE_DEVICES=0 as well. |
babababadukeduke | I am trying to make a custom C++ extension usingthistutorial, but I am getting an error when I am trying to compile the code. I am basically trying to call the grad function inhere. I am getting the following error…error: ‘grad’ is not a member of ‘torch::autograd’return torch::autograd::grad(outputs, inputs, grad_outp... | albanD | I’m not sure this function was already added back then. You should try to upgrade to the latest version. |
Imran_Rashid | I am trying to modify my gradients by multiplying them by a constant. As a test, I multiply the gradients by zero, so I expect that the losses should stay constant.However it looks like the model still updates the weights of the network even though I have tried to force the weights gradients to be zero. Why aren’t the ... | albanD | For Adam, if any “momentum-like” term is non-zero, then you will update the weights even with a gradient of 0. So this is expected. |
oasjd7 | Hi, all.I’m trying to implement the loss like (2) in the figure.But I don’t know how to get gradient for the loss. | albanD | For the dot product in the formula to make sense, both the classifier and the encoder must have the exact same parameter structure. So you should just make sure to give the encoder is a way that you get the right gradients. |
matthias.l | When writing a custom function with custom forward and backward:Assume the moduleclass IMyFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, x, a, b):
# a is a learnable parameter. b is a constant tensor
# b.requires_grad is False
ctx.save_for_backward(x, a, b)
# C... | albanD | No this is expected. You should return as many elements as there were inputs to the forward function. If something is non-differentiable, you should return None. |
netaglazer | hi, i built a loss function, and the backward is very slow:def loss_function(p, y, b):
eps = 0.0000000001
losses = 0
k = len(y[0])
ones = torch.ones(k).cuda()
for i in range(b):
loss1 = -((ones-y[i])@(((ones-p[i])+(eps)).log()))
prod = (ones-y[i])*k - y[i]*((p[i]+ eps).log())
... | albanD | Assuming that your inputs are 2D, the code below shows how to do it
import torch
def loss_function(p, y, b):
eps = 0.0000000001
losses = 0
k = len(y[0])
ones = torch.ones(k)
for i in range(b):
loss1 = -((ones-y[i])@(((ones-p[i])+(eps)).log()))
prod = (ones-y[i]… |
shamoons | I get the equation:image1232×274 13.9 KBbut it depends on Lin and Lout. I want them to be the same, but when defining my network, I don’t know what my input size will be. In my__init__, I have:l_in = 128
padding1 = l_in - 1
padding1 *= strides[0]
padding1 += 1
padding1 -= l_in
pa... | albanD | So for stride of 1, you have:
padding = dilation * (kernel -1) / 2
Assuming dilation of 1 as you don’t use it in your code, you have (kernel - 1)/2.
Since pytorch only supports padding as an integer number (what would be non-integer padding?), then you need kernel to be an odd number and you have… |
doliolarzz | Hello,A model has time-series structure.So, I’ve split each time-step into each gpu, due to insufficiency of gpu memory.But I got an error when calling loss.backward():File "/home/xxx/.local/lib/python3.7/site-packages/torch/autograd/__init__.py", line 99, in backward
allow_unreachable=True) # allow_unreachable fl... | albanD | Well the issue is that the backward formula has not been updated to reflect this… You can seeherethat it assumes that all inputs are on the same device. |
lastrasl | I have observed what I regard as strange/undesirable behavior. This is observed in python 3.7.4; I have not verified on other versions.In essence, simply adding an nn.Linear module which is not used anywhere in the network changes the behavior of SGD and Adam.Here’s a simple example showing the behavior:import torch
im... | albanD | Hi,
This happens because when you add this module, it initialises its weights and so uses the random number generator. If you try to use the random number generator again afterward, you will get different results as more random numbers were drawn before. |
Egon_Schl | Hey everyone,for my high school project I want to give a talk about neural networks, and connecting it to our calculus class. I now want to implement a small example in python and found pytorch for it.Now I want to compute the gradient of the loss function wrt to the parameters of my model f(w).The gradient of the loss... | albanD | Ok.
So you don’t actually want the gradient for x, only W right?
I think the +1 difference in the size comes from the bias term that is often added in linear regression that you are missing when you do x*W only.
You can either have another parameter of size 1 b and compute x*W + b. And now you ge… |
songyuc | Hi guys,I just read some materials from Internet that the checkpoint in PyTorch could be utilized to decrease the usage of GPU memory, and I want to know if that is true?Any answer or idea will be appreciated! | albanD | Hi,
No it applies to any module.
It allows you to reduce the number of intermediary results between ops. So it will only be useful if you checkpoint a function that contains multiple ops. |
adamce | Hi,tl;dr: is it possible to make a checkpoint for a whole sub-network and learn its weights with a nice api?I’ve learned that i can replaceresult = self.net(x, y)[0]byresult = torch.utils.checkpoint.checkpoint(self.net, x, y)[0]where in my case self. net is a sub-model with some logic and several layers, and x and y ar... | albanD | I’m sorry I don’t understand this. autograd.grad is does forward differentiation, doesn’t it?
No it does backward mode as well. Only that instead of populating the .grad field of all the leaf Tensor, it computes and returns the gradients for a list of Tensor that is given.
My thinking was tha… |
tlaurent | I am using a boolean mask in a network that perform some attention mechanisms. The boolean mask is updated in-place in some loop which causes autograd to crash. Here is an example of the kind of stuff that I do and that does NOT work:import torch
import torch.nn.functional as F
d = 4
x = torch.rand(d, requires_grad=T... | albanD | The thing is that the backward operation of masked_fill() needs to know where the input was written into. So it needs the value of the mask. So if you modify it inplace, the autograd engine will fail to compute gradients. |
nirandaperera | Hi,I was wondering if all the nn layers have a correspondingtorch.autograd.Functionassociated with them (in python side)?Best | albanD | Hi,
No they don’t. Even at the cpp level, some of them are implemented with a single elementary Function but many of them have multiple. |
Rafi_zunaed | my below code snippet:model = …#somemodelmodel = model.cuda()model, optimizer = amp.initialize(model, optimizer, opt_level=“O2”)model = nn.DataParallel(model)in dataloader batchimages = images.cuda()output = model(images)last line is giving me this error:Expected tensor for argument#1‘input’ to have the same device as ... | albanD | Hi,
I think this is a known limitation of amp. You can see this issue on their repo for more info:https://github.com/NVIDIA/apex/issues/503 |
el_samou_samou | Hi,I was wondering who have “memory rights” on tensors created in a pytorch Cuda extension.I have created several custom cuda extension following this tutorial:https://pytorch.org/tutorials/advanced/cpp_extension.html.I am now using those extensions in a training loop (i.e. a network is using some of my custom operatio... | albanD | if then the python script delete this tensor, does it effectively clear the memory?
Yes
is it deleted once we exit the function scope like in Python or do we have to delete it manually?
It is deleted when you exit the scope, unless you return it.
How do you monitor the cuda memory? Note that… |
NHH | Given a model (e.g. a cnn) with two losses, with the first loss (loss1) computed halfway through the cnn and the second loss (loss2) computed at the end of the cnn. Then, these two losses are summed and we do total_loss.backward() (total_loss = loss1 + loss2). Will the gradients of the second half of the cnn be impacte... | albanD | Hi,
No it won’t because for a parameter w in the second half of your net, dloss1/dw = 0. So the contribution of these will just be 0 (ignored in practice). |
Jamesswiz | Hi,what is the simplest way to compute full Jacobian and Hessian of Loss w.r.to neural network biases only.I want to do this layer wise but considering one layer at a time and I am not worried about speed for now.Thanks | albanD | The y should be a single Tensor right?
So flat_y here should be a 1D Tensor. And flat_y[i] will be a single number. So it is a scalar output.
Is the error coming from this function? |
takafusui | Hi,I am solving a non-linear optimization problem and usetorch.autograd.gradto provide Jacobian that an optimizer requires.Please see the code snippet below:_stateplus = torch.stack([x[0], x[1], _ar1_plus]).numpy()
_controls_plus[z_idx, epsilon_idx, :] = policy_plus[z_idx].evaluate(
_stateplus)wherexis a tensor vari... | albanD | Hi,
Unfortunately, you will only be able to get gradients using autograd if you use pytorch’s Tensor and operators to do all the computations.
If you have an operation that you cannot do this way, you will need to provide the gradient formula yourself for that step. You can see how to extend the a… |
alxwo | Hi, I have two tensors tensor1 and tensor2, with shape (16, 768, 64, 64) and I want to stack them such that I have a tensor output with shape (16,2,768,64,64), BUT I also want the channel dimension 768 to be an alternating zip of tensor1 and tensor2.tensor1[:, 0, :, :] and tensor2[:, 0, :, :] are stacked together as a ... | albanD | Hi,
I’m not sure to understand what you’re trying to do here. You can get the same result as your zip_and_stack_tensors() using a single torch.stack(). Am I missing something?
import torch
from torch import nn, optim
def zip_and_stack_tensors(tensor1, tensor2):
num_of_channels = len(tensor1[0… |
tlaurent | Just a quick question: the following are exactly equivalent, correct?with torch.no_grad():block of codewith torch.set_grad_enabled(False):block of code | albanD | There is no difference.
Just that one takes a bool as input and not the other.
Also torch.set_grad_enabled(False) can be used as just a function to set the grad mode forever. |
kirk86 | I was wondering if things that show up in pytorch as deprecated or duplicates are going to be removed at some point in order to have a cleaner and more consistent interface? | albanD | Hi,
Yes they are. But because Variable what so widely used by the users, we are leaving it for now.
It is only a no-op that gives you a Tensor right now.
But for deprecation:
We just removed old style autograd.Function code: they will be actual errors in 1.5
We are removing .data internally to … |
cetinsamet | Hello,I’m sorry if this question is already answered but I couldn’t find any similar question.Let’s say i have two different models modelA and modelB. They work sequentially. modelA feeds modelB with its output tensors. And these two models’ weights are updated together.optimizer = SGD(parameters=list(modelA.parameters... | albanD | Hi,
You are right: If they are not used in the loss computation, they won’t contribute to the computed gradients ! |
jusjusjus | Hi pytorch friends!I want to optimize per-example gradient computation, and found an interesting behavior when increasing the batch size. My findings can be reproduced inthis notebook. Essentially I compute per-example losses then to callbackwardon each one:t0 = time()
losses = loss_fn(model(samples), labels)
model.... | albanD | But the fact that you do as many backwards as there are samples in the batch makes them slower when the batch size increases.
In that case, I can buy that there is a sweet spot for a small number of samples.
Also note that each call to backward uses the FULL graph. So the more sample, the more exp… |
mchobanyan | I am trying to replicate a call to tensorflow’s real 2D inverse Fourier transform using torch.irfft. Here is the code that I am using to test:import numpy as np
import tensorflow as tf
import torch
x = np.random.randn(2, 8, 8)
x_tf = tf.complex(x[0], x[1])
x_tf = tf.signal.irfft2d(x_tf)
print(f'Tensorflow output: {x_... | albanD | Hi,
I am not a specialist, but given thedoc, it seems that if the size does not match, you can use the signal_sizes=(8, 14) to make them match what you expect. |
gotlieb | I have a torch tensor of size torch.Size([10, 1, 224, 224]), holding 10 images of size 224x224. I would like to extract single images but keep the tensor size as torch.Size([1, 1, 224, 224]). How can I achieve this? | albanD | Hi,
To do this, I usually use .narrow() and extract a single element. For example to get the second image: data.narrow(0, 1, 1) |
nullgeppetto | I’m working on a Variation AutoEncoder example and I have a simple question that is mainly about PyTorch.Let’s suppose that we use binary cross entropy (torch.nn.BCELoss()) as the reconstruction loss; that is, we apply BCELoss on the reconstructed images (output of decoder) and target images (original images).However, ... | albanD | Variable and Tensor have been merged. So they are now exactly the same thing ! (since version 0.4)
You can just give regular Tensors to your forward pass. And if you need them to require gradients, you can either create them with torch.rand(10, 10, requires_grad=True) or set it with your_tensor.r… |
James_e | Hi,(I am quite new to neural networks to please forgive me if I say anything that is incorrect)Q: Is it possible to put 2 different optimisers in a neural network? e.g different optimiser for certain layersThanks for your helpJames | albanD | Hi,
Yes it is possible.
You just need to give the corresponding parameter to the right optimizer. |
Imran_Rashid1 | I am training a simple LSTM model however pytorch gives me an error saying that I need to set retain_graph=True. However this takes the model longer to train and I do not think I need to do this.class SequenceModel(nn.Module):
def __init__(self):
super().__init__()
self.lstm = nn.LSTM(input_size = ... | albanD | If you want to learn the hidden layer initial state, starting from 0:
class SequenceModel(nn.Module):
def __init__(self):
super().__init__()
self.lstm = nn.LSTM(input_size = 3, hidden_size = 3, bidirectional=False)
self.hidden = nn.ParameterList((nn.Parameter(torch.zero… |
kirk86 | Hey folks,I was wondering if someone could clarify some aspects of the cuda context manager.For instance lets say we have dummy function, and we want to either send the whole function to cuda or whatever tensors are created/manipulated inside that dummy function to automatically get sent to cuda.def dummy_func(input, o... | albanD | There isn’t but that’s by choiceYou could do something like torch.set_default_tensor_type(torch.cuda.FloatTensor) but this is strongly advised against. Anything you will create will be on the GPU (temporary stuff for printing, internal buffers,…) and you most likely don’t want these on the GPU as… |
saluei | Hi I am new to Pyttorch and may be the question be simple,I want to create Sequential model that have multiple Sequential segment or slice so that is my codeclass Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
#input 3 32 32
self.slic1=nn.Sequential()
... | albanD | Hi,
This is because you have slic1 both in self. and self.layers.
If you only want it in self.layers, you should not create it as an attribute of self:
slic1=nn.Sequential()
slic1.add_module('conv1', nn.Conv2d(3, 6, 7,padding=3))
self.layers = nn.Sequential()
self.layers.add_module('slic… |
Phantomfancy | I’m trying to process some videos by dividing each video into 4 clips(video length=40, clip length=10) and pass them through the model.Here is the code:feature_dim = 1024
N, C, T, H, W = video.shape # T=40
clip_pos = [0, 10, 20, 30]
# approach I
feature = torch.empty(N, 4, feature_dim)
for i in clip_pos:
feature[... | albanD | Hi,
I think your reshape is wrong:
In [10]: a = torch.zeros(3, 1)
In [11]: b = torch.ones(3, 1)
In [12]: c = torch.stack([a, b])
In [13]: c.view(3, 2, 1)
Out[13]:
tensor([[[0.],
[0.]],
[[0.],
[1.]],
[[1.],
[1.]]])
You can see that you mixup the batc… |
srikarym | I’m trying to implement a learnable bias layer which would add a constant value to every element of the input. Learnable bias layer exists in lasagne but I was unable to find such a layer in pytorch. I initialized bias as a parameter but the value is not changing. Is this the right way to do it? -class Net(nn.Module):
... | albanD | Since you use the tensor inside your bias with self.bias.data, this will not work with the autograd system.
If you are using the master branch with automatic broadcasting, your can simply do:
def forward(self, x):
x = self.conv1(x)
out = x + self.bias
return out
If not, you will need … |
nirandaperera | Hi,Is there a way to copy the values (data and grad) of a tensor to another in a different device?x = torch.ones(2, 2, device='cuda:0')
y = torch.zeros(2, 2, device='cuda:1')
# something like
x.copy_to(y)And what is the implication of this on this on the grad_fn? | albanD | Hi,
You can move a Tensor to a specific device by doing x_cuda1 = x.to("cuda:1").
This is a differentiable operation. So if x requires gradient, then any op on x_cuda1 will contribute to the gradients toward x.
For the .grad field, you can do x_cuda1.grad = x.grad.to("cuda:1"). |
abhishek_karanath | I have a torch.autograd.variable.Variable named “unw” of shape 6x64x300 and another torch.autograd.variable.Variable named “powers” of shape 6. I need to compute the power of each of the 6 matrices in “unw” with each of the 6 values in “powers”. So I wrote down the below code:for j in range(unw.shape[0]):
unw[j,:,... | albanD | Hi,
I think the simplest would be:
unw = torch.pow(unw, powers.view(-1, 1, 1).expand_as(unw))
That removes both the inplace and the for-loop |
Durotan97 | Hey !I am quite new to using pytorch and it seems like I can not figure out how to solve my problem.I am implementing a custom loss function for a neural network. The network receives an input and outputs a tensor. However, the loss which I try to use to train this network incorporates the output of a second network.de... | albanD | Hi,
when you run in torch.no_grad, then nothing will traverse that block of code.
In this case, if you just don’t want to compute gradient for that net, you remove the torch.no_grad and set its parameters not to require gradients with something like:
for p in gen.parameters():
p.requires_grad_(… |
Dongyue_Oliver | I am trying to share the weights in different layers in one model. Please take a look at this example code:this code tries to share weights in fc1 and some parts of fc2import torch
import torch.nn as nn
import torch.optim as optim
class testModule(nn.Module):
def __init__(self):
super(testModule, self).__... | albanD | Hi,
.data is in the process of being removed and should not be used. As you have experienced, it only does very confusing thingsYou will need to have only nn.Parameters to be the true parameters and you will have to recompute other things at each forward:
import torch
import torch.nn as nn
impo… |
Florent | Hello everyone,I’m implementing a network in C++ using libtorch in Qt. I successfully built and trained a network, but I have now a problem while trying to deploy it.To summarize my issue, it seems that when I loop over the forward function of my model, it runs well for several iterations, then suddenly run around 40x ... | albanD | Hi,
This happens because the CUDA api is asynchronous. So the first iteration, what you measure is just the time to queue work on the GPU.
After a while, that queue is full and you have to wait for stuff to be actually done before being able to enqueue more work.
You can use the equivalent of tor… |
fojjta | Hi,I am trying to implement a method from a paper, which requires to solve eqation. The p_\theta is a CNN, which has a sigmoid function at the end, \alpha, \beta, … are known values, \theta are parameters of the CNN, A_i and B_i are images for i-th sample. It is suggested to use weighted BCE Loss to solve this, but I a... | albanD | Hi,
would definitely work. Note that you want to keep the sum over all the samples right?
I am not sure you can set the weights this way with the BCELoss we have. But the formula above is a bit unclear on what are different samples in a batch and what is not. But the function we have might enforce… |
entslscheia | For example, I have a tensoraof shape[k, m, n]and tensorbfo shape[k, ]. What I want to do is to geta[torch.arange(k), b]. Is there any api provided by PyTorch can directly deal with it? Creating a new tensor usingtorch.arange(k)doesn’t look that elegant. | albanD | Yes, you can do: a.gather(1, b.view(k, 1, 1).expand(k, 1, n)) will give you what you wantBasically, use the gather function, and since you want all the elements over the last dimension of size n, you just expand the Tensor of indices there. |
eduardo4jesus | So far, I’ve check all these posts that I found on the issue, butNoneof them seems to fit my case.backward-not-called-bugsbackward-not-calledcustom-autograd-function-backward-pass-not-calledusing-backward-of-custom-autograd-function-with-loss-backwardHere is my codeclass _Conv2dCustom(autograd.Function):
# Kernel ha... | albanD | Sorry I missed your conv2d as a static function, my bad.
Few details:
You nn.Module does not work for me and through the not implemented error from _conv_forward
You should never call the .forward() of the nn.Module directly. You should use the __call__ on it as result = layer(image).
You don’t… |
Vibhatha_Abeykoon | Yes that is true.What I meant was using autograd function, on a given tensor and get it’s gradient update value.Generally what we do is, we have this leaf node or loss value and call backward().So, it traverse back and calculate all gradients for us. Is this right?If so, I can access w.grad and get the weight updates.W... | albanD | This overhead is mainly the discovery of what needs to be done to compute gradients. So it needs to traverse all the graph of computation, which takes a bit of time.
Note that if you’re simply experimenting, this overhead won’t kill you. But it won’t be 0. |
ElleryL | Consider I have an array of matrixM.shape = (N,D,D)whereDis the dimension of co-variance matrix andNis the number of co-variance matrices.I have a method that convert a single co-variance matrix to a correlation matrix defined asdef convert_to_correlation(m):
inv = torch.inverse(torch.diag(torch.diag(m)).sqrt())
... | albanD | Hi,
I’m a bit confused by your convert_to_correlation. It does not use m.
For 1: all the operations your use support batching (.diagonal, .inverse and matmul), so you can write a convert_to_correlation that works on the whole batch at once.
For 2: we have an implementation of derivatives for inve… |
yumu | hello im currently working on a spiking neural network and trying to implement exponential regularizationthe cost function on exponential regularization give a loss value per neuron that i then sum before adding it to the loss variable by doing loss = F.nll_loss(output, target) + lossumhowever doing this seems to do no... | albanD | Hi,
This value is taken into account.
But if it is constant, grad(loss + C) = grad(loss) + grad(C ) = grad(loss). So adding a constant to your loss won’t change the gradients you get. |
Unity05 | I’ve been facing this problem since several days now.I have converted my model just like this:model = DenoisingAutoencoderSheetEdges()
model.load_state_dict(torch.load('models/model_3.pth').state_dict())
model.threshold = 0.75
model.hard_mode = True
model.eval()
qmodel = quantization.convert(module=model)
qmodel = tor... | albanD | From the beginning of the stack trace, it seems like you’re trying to make a Tensor which is too large (600MB). Is that expected? How much memory does it use if you run it on your machine? |
Faraz | I am new to PyTorch can someone please have a look if I am doing it right? I am trying to run validation in same epoch as training.for epoch in range(num_epochs):
logs = {}
total_correct = 0
total_loss = 0
total_images = 0
total_val_loss = 0
model.train()
for i, (data, target) in enumerate(... | albanD | Hi,
A few things:
Variable is not needed anymore, you can have simply images = data.to('cuda:0')
You are missing the optimizer.zero_grad() before the backward ! You need to manually reset the weights to 0 when you pytorch (see discussion about this here:Why do we need to set the gradients manu… |
kaiseryet | So I am using PyTorch for some numerical calculation, and my problem can’t be vectorized because NestedTensor has yet to function in stable PyTorch release… Currently, I am usingmapfunction to do some tensor calculation. Here are two questions:Is there a more efficient way to do the parallel computation in PyTorch? e.g... | albanD | Hi,
I’m afraid there is no map in pytorch.
If all the operations are very small, single threaded CPU will be the fastest I’m afraid.
If you can share your problem, maybe we can help you achieve some parallelization using the existing functions though. |
jmandivarapu1 | Hi All,I have normal question which I thought. Imagine if I have a model(either linear regression or neural network …etc) and trained on certain Data(D) which has 1000 samples(for example) and now after I finished training if I discarded the data. So, now I am left with model (either linear regression or neural network... | albanD | Hi,
The subfield you’re looking for is privacy preserving machine learning I think.this blogpostgive a nice intro about it. |
toho | I am trying to build a minimal working example in PyTorch using an LSTM. I use a mock example that predicts for a sequence of 3 time steps one out of 4 labels.I get an error message which saysExpected object of scalar type Double but got scalar type Float for argument#2‘mat2’ in call to _th_mmI am not sure what is miss... | albanD | Hi,
The problem is that your model is created in type float by default. So if you need it to be of a different type, you need to change it with: model.double(). after you created it.
Another thing, you cannot use .view() directly on the output of the lstm (because of the way the lstm returns its o… |
songyuc | Hi guys,I am studying about semantic segmentation these days.And I need to transform a grey image into a matrix with the value of trainId, asSo, I want to use PyTorch to realize the function of looking up table in a most efficient way.And your suggestion and idea will be appreciated! | albanD | Hi,
I don’t think any pytorch-specific feature is needed here. You can use regular python dictionaries to do this |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.