user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Fawaz_Sammani | Hi. I’m working on some code on NLP where I require to create specific masks. However, when i do this operation:a[a==1] = 5, it tells me thataanda==1are not of same shape. This happens after the 8th epoch, meaning that it was working for 8 epochs but not after? Moreover, it happens randomly, maybe at the half or beginn... | albanD | To solve this, I would use the indices returned by the max op and do scatter(your_dim, ind, 1) |
JWarlock | Hi!I’m trying to run a dataset distillation algorithm (seepaperhere) and I’ve encountered an implementation problem. In case you’re not familiar with this paper, I will expalin its main idea briefly. Basically, dataset distillation aims at synthesizing a small number of data on which a model is trained can achieve perf... | albanD | You will need to subclass batchnorm to make that happen.
Here is an example for the 2d version:
Class MyLearntBatchnorm(nn. BatchNorm2d):
def __init__(self, *args, **kwargs):
# Initialize the regular batchnorm
super().__init__(*args, **kwargs)
# Get the size of the runnning_* buffers… |
M_Tu | Pytorch 1.2 on linux with cuda 10.0.Got the tracing info by applying torch.autograd.set_detect_anomaly(True).The error shows theRuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.LongTensor [2, 1, 1024]] is at version 1; expected version 0 instead. ... | albanD | Versions tracks how many times it has been changed inplace.
Inplace modifications are anything like positions[foo] = or positions.add_(foo) or positions += 2.
a simple fix you can use is replace your gather call to:
states = hidden_states.gather(-2, positions.clone())
The clone here will make s… |
markl | I am using bazel as my build system instead of cmake. I noticed that the filetorch.his located atinclude/torch/csrc/api/include/torch/torch.hinstead ofinclude/torch/torch.hI assume then I should configure the project to have the files atinclude/torch/csrc/api/include/torch/xxxmade available via<torch/xxx>.Is that corre... | albanD | I usually look at thecpp_extension include pathto answer this.
In particular, I don’t think you should be using this particular include anymore. But I have to admit I don’t the rational behind this. |
Alexey_Nikulkov | I have a usecase for which I want some components of my input data to be NaN (slate data with variable number of items per slate, I want to insert NaNs instead of item features for empty item slots). The NaN propagate through the forward pass properly and I ignore them when calculating the loss (by using the nanmean fu... | albanD | Unfortunately pytorch cannot know about the “irrelevant” part and only uses the chain rule. And in the chaine rule, you get 0 * nan = nan.
There are a few issues on github that discuss this problem:https://github.com/pytorch/pytorch/issues/15506andhttps://github.com/pytorch/pytorch/issues/26799… |
kolorado | Hi,I use autograd.grad function with create_graph=True. After I finish, I want to release the GPU memory the created backward graph. How can I do it? | albanD | Hi,
I don’t think this is what he wants.
retain_graph can be used if you want to call backward() multiple times on the same graph.
create_graph is used if you want to backward() through the backward(). But since this second backward() will go through the current graph, then retain_graph has to be… |
Jordan_Howell | I tried coding a custom data set. When I try to load the class into a data loader, it states that:NameError Traceback (most recent call last)in16 # Generators17 training_set = roof_dataset(partition[‘train’], labels, transform = train_transforms)—> 18 training_generator = data.DataLoade... | albanD | From the error that you linked, it seems that you’re missing a from torch.utils import data to have data.DataLoader to work properly. |
rwamit | Hi Guys,I am trying to runout.backward(torch.Tensor([2.0]))and I get a error shape mismatch, (which makes sense) but I am try to run the same in Pytorch 1.0.2 it is working if I print grad post this operation elements in the matrix get multiplied by 2.0.out.backward(torch.tensor([2.0]))throws errorRuntimeError: Mismatc... | albanD | Your full function here is:
f(x) = ( sum_i (xi+2)^2 * 3 ) / size(x) = (sum_i (xi+2)^2 * 3 ) / 4
df(x)/dxj = 2 * (xj + 2) *3 / 4
given that you start with xi = 1 for all i.
the gradients you expect with no scaling is: 2 * (1 + 2) *3 / 4 = 4.5
So if you multiply the result by 2, you get 9 as expe… |
astri | Hello allI am beginner in deep learning and doing research in keras dan pytorch. I am making custom stop training by watching the loss value and make condition I have succeeded to make a custom stop training in keras and i want make the same thing in pytorch but i am facing problems. First how should i write loss metri... | albanD | Hi,
In your pytorch model, you already have access to both loss at every iteration and train_losses at the end of the epoch.
So you don’t need a callback actually in pytorch. You can write a function with whatever you need directly. |
dpetrini | Hi,I am doing transfer learning from large network based in Resnet.It is related to image classification that outputs labels.When I feed input with one image and corresponding target as below:torch.Size([1, 1, 2500, 1900])
tensor([[0., 1.]], device='cuda:1') torch.Size([1, 2])I have correct output like:outputs: tensor... | albanD | The user can create any model he wants so there is not one way to print the model.
The best way is to look at the code of the forward function to make sure what happens |
Sudarshan_VB | Can anyone please give an example of this scenario, I am struggling to understand why this could even happen | albanD | Hi,
Here is an example:
a = torch.rand(10, requires_grad=True)
b = torch.rand(10, requires_grad=True)
output = (2 * a).sum()
torch.autograd.grad(output, (a, b)) |
pooya_khandel | As far as I understood, theDistributedDataParallelmodule performs gradient synchronization between different nodes automatically, one thing I don’t understand clearly is when this synchronization is done exactly?For example, the below snippet is fromGETTING STARTED WITH DISTRIBUTED DATA PARALLELPyTorch documentation wi... | albanD | The DDP() wrapper takes care of all the synchronizations and offer a nn.Module like api so that you can use it transparently. |
zimmer550 | def forward(self, input_seq, encoder_outputs, hidden=None):
outputs, hidden = self.gru(input_seq, hidden)
outputs = outputs[:, :, :self.hidden_size] + outputs[:, :, self.hidden_size:]
attn_weights = self.attn(outputs, encoder_outputs)
context = attn_weights.bmm(encoder_outputs.transpose(... | albanD | Hi,
Squeeze only works if the size of a given dimension is 1.
If you want to remove a dimension of size > 1 then you need to use a function to do that reduction like sum or max or mean. |
izuna385 | Currently I has index ofbatch_size * candidate_sizeand desired_candidate :batch_size * top_5like, ifbatch_size== 16 and candidate_size == 15>> index.size()
torch.Size([64, 15])
>> desired_candidate.size()
torch.Size([64, 5])
>> index[0]
tensor([104, 171, 182, 3, 56, 178, 6, 6, 4, 21, 30, 182, 27, 39, 5... | albanD | Hi,
It might depend a bit on the memory limitations you have. But the following should work (the sizes are very small for printing purposes):
import torch
b = 2
c = 3
index = torch.rand(b, c).mul(5).long()
desired_candidate = torch.rand(b, 5).mul(5).long()
print(index)
print(desired_candidate)
… |
IapCaL | Hi,Is there have any method to save a tensor for statistics?Exampleclass Exp(Function):
@staticmethod
def forward(ctx, i):
i_max = i.max()
return i
@staticmethod
def backward(ctx, grad_output):
return grad_outputThanks! | albanD | Hi,
If you want to save it for the backward pass, then you can save it within the context as ctx.i_max = i.max().
If you want to save it for external use, then you can use any pythonic way you want: use a global variable, save it in a list, have a stats object where you can record what happens etc… |
gslaller | I have the following code:x = (torch.arange(16)+1).reshape(1,1,4,4).float()
im2col = F.unfold(x, (2,2))with thexbeing:1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16I expect the this to have an output of[[1,2,5,6],
[2,3,6,7],
[3,4,7,8],
.....]but it is giving me the output of kernel size 3:[[1,2,3,5,6,7,9,10,11]... | albanD | Hi,
The only difference between what you expect and what you get is a transpose. The expected use for convolution is to do mm(w, unfold(input)).
You can seeherethat the unfold is called andherethe mm is done with the weights. |
Shisho_Sama | I have been trying to get the gradients for inputin this threadfor more than a week now.Looking at theofficial tutorial here, for getting gradients with respect to the input where the tensor used for backward is not a scaler, it says,Now in this caseyis no longer a scalar.torch.autogradcould not compute the full Jacobi... | albanD | Hoo,
The thing is that the requires_grad flag is not retroactive. If you forwarded through your model with the requires_grad flag being False, then the you cannot get gradients. Your loss1 gives you some gradients because you use imgs again after setting the flag. |
markl | I see Tensor::slice being called, for example, in this code.https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/Integration.cppHowever, slice() is not listed in any of the following filesgithub.compytorch/pytorch/blob/master/aten/src/ATen/Tensor.h#pragma once
/*
* We split Tensor.h into TensorBody.h a... | albanD | I believe it’s implenentedhere |
yunfeng | Hi friends in Pytorch community,I want to find out the inference time of each (conv, bn, relu) layer in a pytorch model (like resnet101 implemented in torchvision package), is there any way to do this? I guess mayberegister_bufferis suitable for this task, but I don’t know how to figure it out. Does anyone has any idea... | albanD | Hi,
register_buffer is used to save buffers that you then use during the forward pass.
I would recommend using theautograd profilerto measure the runtime. |
Rafael_R | Hi,I am getting an error while importing torch, things used to work fine.PyTorch was installed using conda:Python 3.6.7 | packaged by conda-forge | (default, Feb 28 2019, 09:07:38)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
Traceback (most recent call l... | albanD | Actually, looking at the stack trace I think you have a problem with local files:
the python tempfile library, when loading picks up your local random.py file as python’s original random library.
Can you import torch from another folder? If so, you will have to rename your random.py file I’m afrai… |
theevann | I want to subclassSequentialto create a Residual sequential class in a few lines.class Residual(nn.Sequential):
def forward(self, x):
return x + super().__call__(x)However, this crashes with:RecursionError: maximum recursion depth exceeded while calling a Python objectIf I understand well, thesuper().__call... | albanD | Hi,
The hooks for this module have already been called before entering the forward of your module.
So you should use super().forward(x). |
vadimkantorov | Doessave_for_backwardprevent memory reuse intorch.no_grad()mode? Should I skipsave_for_backwardin eval, no_grad mode? | albanD | save_for_backward will have no effect when you run in no_grad mode. You don’t need to worry about it. |
439327bcc62cd8e45e96 | I want to do fine turning.For example, there is a pre-trained weighyt traind from the layer1-> layer2-> layer3 structure.But I want to fine-tune on layer1-> my_layer1-> layer2-> my_layer2-> layer3 structure.Is there any way?please. help me | albanD | Hi,
This is technically possible by setting the weights to the pretrained layers yourself with something like model.layer1.load_state_dict(pretrained_layer1_state_dict).
That being said, the insertion of your custom layers might change the behavior of the network completely and make the initializa… |
fewagner | Hi!I’m trying to learn a differential equation from data, for that I defined a net that approximates the derivative at a point. I then use the output of the net to approximate the next grid-point of the solution to the differential equation and use that as an input for the next step. The function calls of the net are t... | albanD | Ho actually reading the error message in details:
“output 0 of SelectBackward” This means that the problematic one is actually ni_pred
You do change this inplace when you do ni_pred[:, j] = xxx.
Can you try changing ni_pred to be a list and only before the return do return torch.stack(ni_pred, 1… |
blackbirdbarber | Can we load in PyTorch images from the disk to GPU and then possible convert them fast to tensor? | albanD | Ho, well you can’tTo make sure you get enough data for your training procedure, we usually use DataLoader with multiple workers. That way you have multiple processes loading and preprocessing data.
You should check the examples in the doc for how to do that. |
Arun_Mallya | Suppose I have 2 3-D tensorsA, andBand want to copy some elements fromBintoA. Specifically, I have two lists of the form[(x_1, y_1), (x_2, y_2), ...]and[(x'_1, y'_1), (x'_2, y'_2), ...]and I want to performA[x_1, y_1, :] = B[x'_1, y'_1, :]and so on. Is there any fast way of doing this or is a for-loop the only way?Also... | albanD | Hi,
Here is an example implementation.
Gradients will flow as expected for the copied values from A to B (not gradient for indices of course).
Note that inplace operations sometimes prevent the autograd from being able to compute gradients so there is a flag in case you encounter this error.
Let… |
martinr | I have a rather large code base, and upon upgrading to pytorch 1.2 I started receiving thousands of warnings:/pytorch/aten/src/ATen/native/IndexingUtils.h:20: UserWarning: indexing with dtype torch.uint8 is now deprecated, please use a dtype torch.bool instead.Now, I was using torch.uint8 in one place, I replaced that ... | albanD | Hi,
You can try to make python stop on warning to get the stack trace of where that happens or add something likethatthat prints a traceback for each warning. |
OBouldjedri | Hi , I was wondering how to store some of the model modules ('including their weight and bias ) into a global variable to copy them back after ? | albanD | If you have the same tree structure, you should encounter the same modules at the same time during the forward no? So you can simply .append() and .pop() your list. |
kaka2nd | Hi.I am working on one project, and the update formula isparameter = parameter + learning_rate * gradientrather than the usual term which is subtracting.I tried to make the learning rate negative to implement the idea but this is forbidden. So my question how to add the gradient when updating?Hope for your reply. Thank... | albanD | Hi,
I guess the simplest thing is to get -gradient. You can do this by flipping the sign of your loss: loss = - loss. |
jbuddy_13 | Hello all,I’m trying to execute a modified version of matrix factorization via deep learning. The goal is to find a matrix of shape [9724x300] where the rows are items and there are (arbitrarily) 300 features. The function would be optimized when the dot product of vector_i and vector_j are really, really close to the ... | albanD | Hi,
Variables are not needed anymore. and predict methods should not be needed. An updated version of your code is:
import torch
from torch.autograd import Variable
class MatrixFactorization(torch.nn.Module):
def __init__(self, n_items=len(movie_ids), n_factors=300):
super().__init__(… |
ttoosi | Hello,How can I compute the backward gradients for each tensor in model parameters (p for p in model.parameters())? Notice that I don’t want to use module.backward_hook(), instead, I want to be able to put the hooks on tensors of parameters using tensor.register_hook().Specifically, in the snippet below, I want to know... | albanD | Hi,
The hook does not take the tensor as input but the gradient.
So the right signature would be:
def hook_fn(self, grad):
pass
So you directly have access to the gradient and can do whatever you want. |
Giuseppe | Hy guys, I have two model.The first is a compound model with fan_resnet50 and a reset ad hoc with 4 basicBlock.The second model is a resnet50 pretrained.I must remove the FC layer of these models and do a torch.cat of this 2 model.> class Identity(nn.Module):
> def __init__(self):
> super().__init__()
>
> ... | albanD | You should keep in mind that the forward method in pytorch is actually executing this code every time you do a forward with a given input.
So setting the fc models to identity can be done only once in the __init__ as well.
The cat operation takes Tensors as input, not layers.
I think you meant so… |
alibsa | Why accumulating gradients show us different value than summing them manually? Is it because of round-off errors?Code:class LogisticRegression(torch.nn.Module):
def __init__(self, input_dim, output_dim):
super(LogisticRegression, self).__init__()
self.linear = torch.nn.Linear(input_dim, output_dim)
def forward(s... | albanD | Hi,
This is most likely due to precision errors of floats.
Do you see the same behavior if you run with double by setting torch.set_default_tensor_type(torch.DoubleTensor). |
goaltender | Hello, I am trying to understand how DataParallel works. Now I am testing simple code to see speedup on 2 GPUs:import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
# Parameters and DataLoaders
input_size = 5
output_size = 2
batch_size = 10000
data_size = 1000000
device = torch.device("... | albanD | Hi,
I think the problem is that your model is so small that your task is cpu bound. So using more GPUs won’t help.
You can do the same experiment with a resnet from torchvision for example (and lower batch_size) to make sure you get a GPU bound task. |
btimar | Hi –The openAI gym environments use a seed() method that hashes its input; the relevant code snippet:seed = create_seed(seed)
rng = np.random.RandomState()
rng.seed(_int_list_from_bigint(hash_seed(seed)))(fromhere).Does torch.manual_seed() do the same? This isn’t mentioned in the docs. | albanD | Hi,
We don’t do any hashing of the seed.
But the rng engine might depending on which one is used (cuda or cpu). |
BramVanroy | When setting all seeds manually, I would expect that all new layers of a given type have the same initial weights. However, that is not the case.import torch
from torch import nn
import os
import numpy as np
import random
torch.manual_seed(3)
torch.cuda.manual_seed_all(3)
torch.backends.cudnn.deterministic = True
torc... | albanD | The reason is because generating some numbers change the state of the random number generator.
If you set the seed back and the create the layer again, you will get the same weights:
import torch
from torch import nn
torch.manual_seed(3)
linear = nn.Linear(5, 2)
torch.manual_seed(3)
linear2 = nn… |
han324solo | How do I set dtype for torch.nn.Conv2d?It seems that default dtype for torcn.nn.Conv2d is float.I want to explicitly set dtype for torch.nn.Conv2d ,as I set dtype for tensor as below:a = torch.tensor([1,2,3], dtype=torch.int8) | albanD | Hi,
You can use your_mod.type(dtype) to change its type. Or your_mod.double() to change to double precision.
Be careful that the conv module is not implemented for every types |
hadaev8 | Pytorch 1.2, tacotron gst model.I wonna try to mask out gst outputs.I have two 3d array with shape [32, 177, 512]So i just wonna have zeros in first tensor like in secondTaking mask and expand shapegst_mask = ~get_mask_from_lengths(text_lengths)gst_mask = gst_mask.unsqueeze(-1).expand_as(gst_outputs)Seems okThen i dogs... | albanD | Yes it willAs I was suspecting, gst_outputs is created with an expand. This means that this is not backed by actual memory and writing to one place of it will have effect on other places.
Using clone will force it to be backed by real memory and remove this problem ! |
mital | Hi,I’m training CNNs on MNIST dataset and would like to prioritize learning some of the samples (they will be determined during the training) and thought a straightforward way to do this would be to set a learning rate (multiplier) for these “important” samples.Another way to do this is maybe by duplicating these sampl... | albanD | Hi,
You can use a weighted loss to change the relative importance of your samples. Indeed, multiplying the loss for a single sample by 2 is the same as multiplying the gradients corresponding to this sample by 2. |
Evan_Vogelbaum | Hi Ya’ll,I am experiencing a somewhat spooky error, in which the simple act of loading a new state dictionary into my model seems to erase the graph tying parameters to an external matrix.Here is the code, and I will explain below.for grad, (name, param) in zip(recovered, model.named_parameters()):
updated_para... | albanD | Hi,
This is “expected” given the how all these functions are supposed to work.
In particular, load_state_dict is 100% breaking the computational graph so you won’t be able to backpropagate through what it does.
The nn.Parameters() that are recovered by model.parameters() are supposed to be specia… |
smutahoang | I found that there is some insignificant numerical error between the result obtained from batch mode computation and those obtained from iterating over the instances in the batch. For example:batch_size = 32
input_size = 128
output_size = 256
linear = torch.nn.Linear(input_size,output_size)
x = torch.rand(batch_size, i... | albanD | Hi,
The precision of a floating point number is around 1e-6. So anything smaller is going to be noise.
Also floating point operations are not really commutative or associative and will create very small error if you do them in a different order.
So this is expected behavior I’m afraid. You can us… |
Mgorb | I’m trying to load 8 pretrained models into another model in PyTorch. The definition of the models I want to load (loaded on top of a vgg net):self.output_layer=nn.Sequential(nn.Conv2d(512,512, kernel_size=3,padding=2,dilation = 2),
nn.Conv2d(512,256, kernel_size=3,padding=2,dilation = 2),
... | albanD | Hi,
You will need to use nn.ModuleList() for the submodules (each of your regressor) to be found properly.
You can simply replace self.branches=[] by self.branches=nn.ModuleList() and it will work as expected. |
blackbirdbarber | k=torch.tensor([2,1])
print(k.size())
k= k.contiguous().view(1,2) #1
# or
k= k.reshape(1,2) #2 | albanD | The one you prefer.reshape() has been added recently to help users more used to numpy. |
blackbirdbarber | k=torch.tensor([2,1])
k= k.view(1,2)Something likek.view_(1,2) | albanD | I think this is mostly historical as .view() is so cheap anyway that you don’t really need to do it inplace. |
blackbirdbarber | x = torch.tensor([0,0,0,0])k=torch.tensor([1,2,3,4])x.data.copy_(k)#1#orx.copy_(k)#2x | albanD | Hi,
The first one should never be used as .data should not be used.
The new api for #1 is:
with torch.no_grad():
x.copy_(k)
And the difference is clearer: use #1 (EDIT: the version of #1 given just above in my comment, not your original one) if the copy should not be tracked by the autograd … |
Rishav_Sapahia | I am trying to run my model on gpu, but I am gettingRuntimeError: CUDA error: device-side assert triggeredMy model runs fine on CPU.I have setos.environ['CUDA_LAUNCH_BLOCKING'] = "1"and it is showing error when I am loading the model on cuda on the following line -if train_on_gpu:
unet = unet.to('cuda') | albanD | The thing is that this environment variable is only affecting the initialization of the cuda driver. This means that if you set it in your notebook after the driver has been initialized, it won’t have any effect.
It either needs to be set when you launch the notebook itself. Or the first thing a cl… |
John1231983 | Hello all, I have two variablesa,bwith requires_grad=True. Theloss1will take theaandbas inputs, while theloss2will take the normalization ofaandbas input. So, should I use a clone in this case? This is my implementationloss1= loss1(a,b)
a_norm = a / 255
b_norm = b/255
loss2 = loss2(a_norm, b_norm)
loss_total = loss1+l... | albanD | When you do a_norm = a / 255, you do not modify a in any way. |
LeanderK | I am currently profiling the memory-consumption of my model. My code is essentially:log_probs = model.log_prob(inp)
loss = (-1)*log_probs.mean()
loss.backward()I have ~4 gig of GPU memory (3980MB) before calling backward and ~8 gigs (8882MB) after, but this is suprising to me. Pytorch maintains the whole computational ... | albanD | Hi,
How do you measure the gpu memory usage? You should be usingtorch.cuda.memory_allocatedto get the memory actually used by Tensors. Note that this number only counts Tensors, and not the memory required by the cuda driver at initialization.
If you check via nvidia-smi, you will see a larger n… |
darrenjkt | Hi I’m running the code snippet below.class LFBlock(nn.Module):
def __init__(self, kernel_size=(1,1,1), block_shape=(32,32,32)):
super(LFBlock,self).__init__()
self.block_shape = block_shape
self.conv = nn.Conv3d(1,1, kernel_size=kernel_size, stride=1, padding=0, bias=True)
... | albanD | Hi,
The weight is associated to the Conv2D class instance. So if you reuse one instance, then you reuse its weights.
If you want more than one instance to train different weights, you will need to create more than one instance of the Conv2D class. |
Yaroslav_Bulatov | Below is an example of matrix multiplication that incurs precision loss in float32. Any idea why the result is different when I run it on Mac vs Linux?import torch
x = torch.tensor([[11041., 13359, 15023, 18177], [13359, 16165, 18177, 21995], [15023, 18177, 20453, 24747], [18177, 21995, 24747, 29945]])
y = torch.tensor... | albanD | You can use the get_env_info() function from the torch.utils.collect_env module to get some informations.
To be sure what is used, the best way is to open python. import torch. Copy the path to the main c library with torch._C.__file__. Then in your terminal, run ldd path_to_that_library. It will l… |
dib | I’m trying to visualize the feature maps of my network through guided backpropagation. I’m running this throughmodel.eval().My first error, upon the final stages, isRuntimeError: invalid gradient at index 0 - got [1, 6] but expected shape compatible with [1, 10647, 6]. It seems this stems from:onehot_out = torch.FloatT... | albanD | Hi,
The best way to look at these issues is to enable theanomaly detectionmode. This will give you the method in the forward that caused this issue. |
Shuan_Holmes | Hello!I try to accelerate CNNs on TitanV using FP16. I use this piece of code:# ...
model.half()
# ...
image = image.half()
#...
outputs = model(image)but I wonder whether the intermediate results (i.e., accumulator) in convolution operations can be represented by FP16. Besides, several activation functions (e.g., Sigm... | albanD | Hi,
It does convert everything to float16 which indeed is not optimal in most cases.
The nvidia folks have done a lot of testing around this and release theAMPlibrary to automatically only convert the right part of the model to fp16 ! |
hjyxxxxxl | I am trying to calculate the mutual information between the hidden layers’ output and input and output using the following code:def InfoNCE(X, Y, batch_size=256, num_epochs=200, dev=torch.device(“cpu”), model=None, rg=True):A = torch.tensor([float(batch_size)] * batch_size).reshape(batch_size, 1)#.cuda()if not model:mo... | albanD | Ho, looking at the code in a nice editor made me realise that you pass layer_2_log to your second training stage. But that Tensor has some history already from the first training stage. Is that expected that this will backward in the first part of the model as well? If no, you should add a .detach() … |
LeanderK | I want to write a custom autograd-function to save gpu-memory and recompute results during the backward-pass. The whole architecture is similiar to invertible-resnets.A simplified example of what I want to write is:class MemorySaving(torch.autograd.function):
@staticmethod
def forward(ctx, keep, pred, eval_func... | albanD | Ok, maybe I’m missing something. It’s just that your implementation is very close to the checkpoint one in the sense that you save the input, and redo a forward/backward during the backward pass.
What are the types of the inputs to your function? Do you have at least one Tensor that requires gradie… |
blackberry | I would like to remove “easy” samples with negligible error from the loss, so that they do not dominate the mean loss value. Focal loss in the RetinaNet paper uses weighting to address the issue. I just want to remove those samples.I suppose, the following is not right, as it changes the loss value in place and disrupt... | albanD | Hi,
Actually your example does not do any inplace operation ! It would if you were doing loss[loss > 1e-6].zero_().
So your code should work without issue and the entries that were not selected by your mask will just have gradients of 0 in the rest of the network. |
111142 | Hi,I just encountered an error, when I perform a bool slices operation like:average = torch.mean(tensor[tensor[:] != 0]),the system returns me an error: Function ‘AddmmBackward’ returned nan values in its 2th output.I realized that this equation may not be a differentiable function, so I was wondering if there is a dif... | albanD | Hi,
This operation is fine. Note that you don’t need the [:].
This error occurs when you run in AnomalyMode? You should check which forward function it correspond to and print the output value to make sure they are in acceptable ranges. |
Mandy | When I was looking into the source codes ofoptim.sgd(), I found thatfor p in group['params']:
if p.grad is None:
continue
d_p = p.grad.data
if weight_decay != 0:
d_p.add_(weight_decay, p.data)where I think thatweight_decayis used forL1 penalty(maybe I was wrong? There is only a... | albanD | Hi,
Weight decay is an l2 penalty on the loss function.
So when you take the derivative, it becomes just the value of the weights (times 2).
So we add that directly to the gradients. |
Natasha_667 | Please help me to vectorize this code on the batch dimension at least:A = torch.zeros((3, 3, 3), dtype = torch.float)
X = torch.tensor([[0, 1, 2, 0, 1, 0], [1, 0, 0, 2, 1, 1], [0, 0, 2, 2, 1, 1]])
for a, x in zip(A, X):
for i, j in zip(x, x[1:]):
a[i, j] = 1Thanks! | albanD | There you go, this will be much fasterNote that I use .narrow(-1, 0, x_size-1) out of habit but [:, :-1] works as well if you prefer that notation.
import torch
A = torch.zeros((3, 3, 3), dtype = torch.float)
X = torch.tensor([[0, 1, 2, 0, 1, 0], [1, 0, 0, 2, 1, 1], [0, 0, 2, 2, 1, 1]])
for a, … |
Tzeviya | I have a Siamese Network with a triplet loss function at the end. E.g.:> class Siamese(nn.Module):
> def __init__(self, ae_net):
> super(Siamese, self).__init__()
> self.ae_net = ae_net
>
> def forward(self, x1, x2, x3, hidden):
>
> a = self.ae_net(x1, hidden)
> b = sel... | albanD | Ho right it is, my bad.
It is a bit tricky for Siamese network as you need to accumulate the gradients for all tree runs.
One simple way to do this is to make three copies of your network, one on each device, then send each copy to it’s respective device.
After each backward, you will need to acc… |
pmeier | Thedocumentationstates:[I]n order to make computations deterministic on your specific problem on one specific platform and PyTorch release, there are a couple of steps to take. […] A number of operations have backwards that useatomicAdd, in particular […] many forms of pooling, padding, and sampling. There currently is... | albanD | Hi,
You will get deterministic results as long as you don’t use the functions that are listed.
Indeed for these functions, no deterministic alternative is implemented in pytorch. |
cherepanovic | Hello at all!a question regarding keywords in torch.nn.Sequential, it is possible in some way to forward keywords to specific models in a sequence?model = torch.nn.Sequential(model_0, MaxPoolingChannel(1))
res = model(input_ids_2, keyword_test=mask)here, keyword_test should be forwarded only to the first model.Than... | albanD | Hi,
You can pass any single input to the sequential. So you can pass a tuple or dict if you want and unpack them in your first model.
The implementation is simple and can be foundhereif you want to see the forward method of the Sequential |
yangxi | I tried to make a recursive network. It is composed of convolution part and fully connected part, and would use previous output. The shape looks like this:RecursiveModel(
(conv_part): Sequential(
(conv_0): Conv1d(1, 4, kernel_size=(128,), stride=(1,), padding=(32,))
(conv_1): Conv1d(4, 4, kernel_size=(128,), ... | albanD | Hi,
The problem is that prev_output is linked to the previous forward you did. And so if you call backward after the new forward, it will try to backward through the previous forward as well. Hence the error you see.
You can use retain_graph=True when you call .backward() to avoid this issue but t… |
shenwei101623 | Why does this happen? | albanD | Hi,
This happens because log is only defined for strictly positive inputs. And so we return -inf for all values <= 0 as it is the limit at 0. |
591ece3a2a04495180b7 | I tried some benchmarks on CPU.I tested inference speed of one CNN model which can compute optical flow.The inference speed I checked was 0.4 s with random init, but when I loaded the state dict then the speed became 2s. I don’t know why. This situation doesn’t occur if I used other models.Does anyone know the reason? | albanD | Hi,
I would try to set flush denormal to True, seedoc.
If that solves the issue, then the problem comes from the fact that your trained model contains very very small numbers that are badly handled by your cpu. |
iArunava | So,>>> net = nn.Conv2d(3, 3, 1, 1, 0)takes>>> sys.getsizeof(net.weight.data)
72which is in bytes.But,>>> torch.save(net.state_dict(), './net.pth')
>>> !du -h ./net.pth
4.0K ./net.pthwhich if converted to bytes>>> 4 * 1000
4000is 4000 bytes!!!Please, tell me what I am missing and why is there is a massive increase in... | albanD | Hi,
Few things I think:
du -h actually counts the size of the folder as well. Running “ls -lha” will show you that the empty folder takes 4K, not the .pth file which is only 515bytes.
sys.getsizeof() measure the size of the Python object. So it is very unreliable for most pytorch elements.
The s… |
Snade_Qian | I’m using libtorch (the frontend of pytorch in c++) to train a network. To monitor the gradient, I created checker to catch the backward process, but it does not enter the self-defined backward() function.I compile the libtorch from sources on Ubuntu16.04.The checkBP class is below.#include <torch/torch.h>
#include <c... | albanD | Hi,
Note that on the python side, the Function have changed slightly as you can see in thetuto.
For cpp it is a bit more complex. a Function does only one way and its “apply” method should be implemented. It is either implemented in pure autograd by performing operations on Variables or the outpu… |
pybald | This issue is closed. It was just a bug when initializing the instances.We created a model with 15 layers, FP32, each layer size 12K (so weights are 4x12Kx12K = 576MB). So, the model size itself is 576*15= 8.6GB and there are activations, input layers etc. The size of the model alone cannot fit into an 8GB GPU.Yet Pyto... | albanD | The very high virtual memory is expected and always there.
How big is the model when you save its state_dict to disk? |
Timos_Korres | I am using batchnorm1d() in my networks. If I remove the batchnorm1d() from the configuration the network behaves fine on GPU. When I add it back I get the following error:File "/mnt/mscteach_home/s1877727/recommendations/spotlight/dnn_models/cGAN_models.py", line 115, in forward
vector = layers(vector)
File "/ho... | albanD | Hi,
the problem is that you store your layers in a regular list, not an nn.ModuleList and so it is not affected by your call to model.cuda(). |
tomguluson92 | Hi@albanD, thanks for your explanation about the definition of_convolution_double_backward(). When reading this code, I was confused about the parameter likeggI,ggW_r,ggbandgO_randoutput_maskand the target of calculatingggW,gIandgW.Under my superficial understanding of all these,ggW_rmeans the gradient of convolution k... | albanD | Hi,
I’m not sure about the *_r variables. Most likely some some cpp reasons.
The gg* variables contain the gradient of the gradient of something.
Since the forward is I, W, b -> O
the backward is gO, I, W -> gI, gW, gb
and the double backward ggI, ggW, ggb -> ggO, gI, gW |
mshuaibi | Is there a difference between the parallelization that takes place between these two options? I’m assuming num_workers is solely concerned with the parallelizing the data loading. But is setting torch.set_num_threads for training in general? Trying to understand the difference between these options. Thanks! | albanD | Hi,
Your assumption is correct:
num_workers will set the number of processes (EDITED thanks@SimonW) used to load and preprocess data in the dataloader
set_num_threads sets the number of threads that can be used to perform cpu operations like conv or mm (usually used by OpenMP or MKL). |
Deeply | It seems thattorch.sum(x, keepdim=True, dim=...)provides more control overx.sum(), whenxistensor.However, which form is more appropriate to be used in customized loss functions that are used inbackpropagation?And, how about speed? | albanD | Hi,
As of latest version, they actually have exactely the same arguments. They will do the exact same thing with the autograd. |
yunpei | What is the difference between net.cuda and net.to(‘cuda’)?Do someone know? Thank you | albanD | Hi,
The first one is the old notation, the second one is the new unified notation. They do the same thing. |
Rickyim | I came across the termin-place operationin thedocumentationhttp://pytorch.org/docs/master/notes/autograd.htmlWhat does it mean? | albanD | Hi,
An in-place operation is an operation that changes directly the content of a given Tensor without making a copy. Inplace operations in pytorch are always postfixed with a _, like .add_() or .scatter_(). Python operations like += or *= are also inplace operations. |
Bruno1 | Hi,I’m working on a custom layer which uses the unfold operator.I would like to compute the second order derivatives (for some hessian vector products…). However I have the following error:derivative for _thnn_im2col_backward is not implementedCan anyone tell me how to solve this? Or are there any workaround/hacks to s... | albanD | Hi,
When implemented in python, a forward/backward pair is defined by a Function. You can seeherein the doc how in details.
By default, if higher order derivatives are required, the autograd is applied to the backward function that is defined.
You can manually defined second derivatives by usin… |
Zhaoyi-Yan | a = torch.tensor([[1,2,3,4],[5,6,7,8]])
idx = torch.tensor([[0,2,1],[2,3,0]])
# How to do it in batch ?
c_1 = a[0][idx[0]].view(1,-1)
c_2 = a[1][idx[1]].view(1,-1)
c = torch.cat((c_1, c_2), dim=0)The desired output is:tensor([[1, 3, 2],
[7, 8, 5]])I trieda[idx], however, it goes wrong. | albanD | Hi,
gather is what your want!
c = a.gather(1, idx) |
alan_ayu | If I need to copy a variable created by an operation instead of user,andlet the copy have an independent memory,How can I do for that purpose?Thank you! | albanD | Hi,
You can use the .clone() function directly on the Variable to create a copy. |
ChangGao | Hi !I’m using a neural network to approximate a Gaussian distribution.The mean and log standard deviation are output from the NN and the loss is computed according to KL divergence.After iterations, the loss (KL divergence) is still more than 1e-8.And in some of the iteration the loss is printed to be 0.But I want the ... | albanD | If you use FloatTensor, 1e-8 is close to the smallest number you can represent precisely. At this point most the gradient computation are really noisy. You will need DoubleTensor if you want more precision. |
TrevP_1 | Hi sorry I’m new to Pytorch: if I have Model1 producing some output, which is fed into Model2 (which is pre-trained), is there a simple way to optimize Model1’s weights based on Model2’s outputs? I could of course just backprop through Model2 into Model1, but I want to assume Model2 is not accessible to Model1 other th... | albanD | Hi,
If I understand properly, you have this:
input = # ...
out1 = Model1(input)
out2 = Model2(out1)
loss = LossFunc(out2)
If you want to optimize the parameters of Model1, you can just use loss.backward() and create your optimizer to only update the first model with optimizer = torch.optim.SGD(Mo… |
juliusbk | This is a very simple example:import torch
x = torch.tensor([1., 2., 3., 4., 5.], requires_grad=True)
y = torch.tensor([2., 2., 2., 2., 2.], requires_grad=True)
z = torch.tensor([1., 1., 0., 0., 0.], requires_grad=True)
s = torch.sum(x * y * z)
s.backward()
print(x.grad)This will print,tensor([2., 2., 0., 0., 0.]),s... | albanD | Hi,
No it does not.
The thing is that a tensor full of 0 would be a stop just for multiplication. Other operations might still continue even after a 0 is encountered. So this cannot be done in general I think (even though it might in some very specific cases). |
Rifur13 | Hi everyone,The forward pass of my model increases the memory x4 after I call “loss.backward()”. I understand that it stores buffers used in gradient calculations, but is a x4 increase normal? It prevents me from using a higher number of batches. The memory is constant at 2.2GB at the beginning of every batch.Here is t... | albanD | Hi,
Large memory increase during the backward is expected as you need to have both the forward buffers, the gradient tensors, and the intermediary gradients being computed. |
Mona_Jalal | Today I learned about Shampoo. I want to know if I will have gain over SGD for transfer learning tutorial if I have a total of 1500 images?Also, I am not sure how to use something like this repo in the PyTorch code?GitHubmoskomule/shampoo.pytorchAn implementation of shampoo. Contribute to moskomule/shampoo.pytorch deve... | albanD | I guess that you use it as any other Optimizer from pytorch.
I don’t think there is any plan to incorporate it in the main repo. |
Intel_Novel | import torch
import torch.nn as nn
import torch.nn.functional as F
# input = torch.LongTensor(4,4).random_(0, 50)
input = torch.randn(4,4)
print(input)
m = nn.MaxPool2d(kernel_size=2, stride=2)
output = m(input)
print(output)I created the example that will not work, but when I setinput = torch.randn(1,4,4)it will wo... | albanD | Hi,
Yes, MaxPool2d is built to work with images which are 3D Tensors for a single image and 4D tensors for a batch of images. |
Tony_Lee | I have encountered a problem about the forward propagation, the full code is as follows:I want to accurately record the runing time of nn.conv2d function, where time1 is about0.00009901s, but time2 is about 0.00011235s. As can be seen in the code, the convolution flops is identical, I don’t know what cause the time di... | albanD | Unfortunately, GPUs are very good at doing large simple operations like element-wise ops or mm but very bad at smart things like indexing.
For the time noise, I don’t see any way around this, as I said, this is most likely some hardware quirks and I don’t know GPU internals enough to have an idea w… |
bulubulubu-Yu | Hello, everone. I’m a new in PyTorch.Today I’m trying to build PyTorch from source on Ubuntu 16.04 (as described in pytorch repo), but I’m getting an error:[1293/3131] Generating …/…/…/torch/init.pyiWriting ./torch/init.pyi[1296/3131] Generating include/renamesse2.hGenerating renamesse2.h: mkrename 2 4 sse2[1302/3131] ... | albanD | The error message /usr/lib/x86_64-linux-gnu/libcuda.so: file not recognized: File truncated` seem to indicate that your cuda install is broken. You may want to clean it and reinstall cuda and try again. |
Intel_Novel | I am not sure 100% what is singleton dimension of a tensor. I think this may be the dimension where we have 1: torch.rand(1, 2, 3, 4, 5). Can someone confirm what is this?I found this in:RuntimeError: The size of tensor a (5000) must match the size of tensor b (60) at non-singleton dimension 2I am not sure what singlet... | albanD | Yes singleton dimensions are dimensions of size 1.
This is relevant here as we do automatic broadcasting of singleton dimensions: an addition (500 x 1) + (500 x 500) = (500 x 500) where the first tensor dimensions is expanded to 500.
In your case, you have a dimension where one is of size 5000 and… |
sonsus | During dealing with the in-place operation problem ofautograd, I faced sth like below.model.py:class MyModel(nn.Module):
def __init__(self, *args):
super(MyModel, self).__init__()
self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
self.X = torch.ones(200... | albanD | Hi,
Why do you worry about the version being changed?
I would say it’s most likely changed when doing the weight initialization? |
mkwissam | HelloI’m trying to do prediction using a pre-trained model. But I’m getting the following error with some data rows“the code is executed normally but with some data rows I got the following error”, int, int, IndexType, IndexType, long) [with T = float, IndexType = unsigned int, DstDim = 2, SrcDim = 2, IdxDim = -2, Inde... | albanD | You can see in the exception " Assertion srcIndex < srcSelectDimSize failed." This means that you tried to index a Tensor with an index that is larger than it’s size.
You want to check in more details all your indices and make sure they are correct.
Note that to get a stack trace that points exact… |
Jiacheng_Li | Hi,I want to change the grad of nn.Conv2d in its backward, here is my code:def fun(module,grad_in,grad_out):
print('grad_in')
print(grad_in.shape) # add break point here
print('grad_out')
print(grad_out.shape)
class testNet(nn.Module):
def __init__(self):
super(testNet, self).__init__()... | albanD | Hi,
grad_in[2] is the gradients for the bias as you saw.
The conv takes 3 inputs: (input, weights, bias). Since for the first layer, you don’t need gradients for the input, None is returned. For the second layer, gradients for the input are needed to compute the gradients of the first layer and so… |
Carsten_Ditzel | I am suspecting NaN values in my script so I would like to use theanomaly detectorof pytorch. However, I am confused as to how exactly to use it.My dataset class uses h5py so I am wondering where I have to include the context manager in in order for it to work. | albanD | I meant the backward invocation in your training loop.
At the moment, the anomaly detection mode only detect nans that appear during the .backward() call as it is hard for the end user to poke around in what happens there.
I won’t detect nans that appear outside of the backward invocation.
If na… |
Carsten_Ditzel | What I understand from thedocsis that whenever I intend to do conputations on the GPU, I need to add the following lines to my main scripttorch.manual_seed(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = Falsewhy isnt this included by default if torch recognizes GPU computations?The articl... | albanD | Hi,
why isnt this included by default if torch recognizes GPU computations?
Because the deterministic algorithms are significantly slower than non-deterministic ones.
Is there a way to use pytorch on the GPU and not use CuDNN as well?
You can set torch.backends.cudnn.enabled = False. pytorch… |
Nayan | Hi, I am using pytorch to build CNN model. But I am facing some problem with data generation. Here is my data shape:X_train = (-1, 1, 169999, 200)X_test = (-1, 1, 3000, 200)y_train = (169999, 200)y_test = (3000, 200)train = torch.utils.data.TensorDataset(X_train, y_train)test = torch.utils.data.TensorDataset(X_test, y... | albanD | You need to check that X_train.size(0) is the same as y_train.size(0). |
Nathan_Gr | Hello,in order to implement channel pruning, I register the output of activations in my network as buffers and perform a register_hook on them. Doing so produces memory leaks after deleting the model unless the registered buffers are freed (self.buffer = None) at the end of the hook function. Freeing the buffers at the... | albanD | Hi,
Does adding a gc.collect() twice just after the del model helps? Looks like you’re making a circular reference of python object. |
jmaronas | Hello.Today I was performing some experiments using a variational autoencoder. I realized about something quite surprising that I did not expect. Hope someone can help me.I was sampling from the posterior distribution and wanted to save an image of the latent space. The image on the latent space (which comes from a gau... | albanD | No problem !
In python, only number, strings and booleans (I might be missing things here like functions but I’m not sure) are passed by value, everything else is passed by reference. |
Mehdi_Rostami | Hello everyone.I would like to take the derivative of the output with respect to the input. People in other pages have suggested this:torch.autograd.grad(output, input, retain_graph=True)[0]However, I think this method is not very efficient: Many of the operations needed to take derivative wrt inputs have already been ... | albanD | Hi,
It works as expected:
import torch
inp = torch.rand(5, 10, requires_grad=True)
w1 = torch.rand(10, 1, requires_grad=True)
w0 = torch.rand(1, 1, requires_grad=True)
out = w0 + inp.mm(w1)
out.sum().backward()
print("w1")
print(w1)
print("inp.grad")
print(inp.grad)
Keep in mind here that … |
Intel_Novel | So var I never calledgradfunction directly. Is there any reason when this is needed.I learned that gradients will be calculated in the backward pass automatically. Is this the function that PyTorch is calling whenbackward(). Doesn’t seem to be the case. | albanD | Hi,
This function allows you to get finer control of what the autograd computes even after the forward pass.
.backward() will populate all the .grad fields of leaf variables that require gradients.
autograd.grad() will compute and return the gradients of a set of specified Tensors.
You use grad … |
Zhoushuren | Assume I have a 3*3 tensor a which isa = torch.rand(3,3)
tensor([[0.5456, 0.2233, 0.1322],
[0.6037, 0.4913, 0.6274],
[0.6362, 0.7671, 0.6741]])and a 2*2 tensor b which isb = torch.tensor([[10,20], [30,40]])
tensor([[10, 20],
[30, 40]])How can I assign tensor b onto specific position on tensor a,... | albanD | Hi,
If you want to change the corners of a square matrix with 4 values, the most efficient way is to change the stride by hand to get the tensor you want:
import torch
# a must be 2x2
# b can be any squared matrix
# You can generalize to batch by keeping original size and stride below
a = torch.r… |
yuqli | As the title suggests, what does theTHprefix in the source code for Torch7 mean?Thanks!GitHubtorch/torch7http://torch.ch. Contribute to torch/torch7 development by creating an account on GitHub. | albanD | Hi,
It’s the name of the library that contains all the C backend used by torch, sourcehere. |
Intel_Novel | I found code like this:opt.step()
opt.zero_grad()and I also found code like this:opt.zero_grad()
opt.step()Which one would be more correct? Am I missing something obvious here?I foundthisanswer helpful but still is it wrong to zero the grads after thestep(), since possible we don’t need them anymore after thestep(). | albanD | Hi,
The second one is most likely a bug.
Remember that .backward() accumulates gradients and so zero_grad() should be called such that you clear the old gradients before accumulating the new ones.
The second example here actually zero out the gradients just before using them. So the step won’t do… |
NeutronT | %E6%B7%B1%E5%BA%A6%E6%88%AA%E5%9B%BE_201903122204151920×1080 797 KB | albanD | Hi,
The problem is that your gpu is fairly “old” and so is not supported by the binary builds since 0.3.1
Note that such an old gpu might actually not be faster than running on cpu if you have a fairly recent cpu.
If you really want to use it, you will have to compile pytorch from source. |
Intel_Novel | My training code looks over complicated.I searched for a good training example, but the heritage from the versions before <0.4 provides lot of noise for my search.I created the example to explain what I mean:# set the min-batch size, optimizer and the loss function
bs=512
opt = optim.Adam(m.parameters(), 0.0001)
loss_f... | albanD | Hi,
For me, “epoch” has a slightly different meaning: it means how many times you go through the whole dataset. With this, I would do:
n_smaples_seen = 0
for epoch in range(num_epochs):
for sample in dl:
# Not needed if your code handle any batch size
if sample.size(0) != bs:
… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.