user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Intel_Novel | I am having problems with this:# hidden features
n_hidden = 256
# input activation factor
n_fac = 42
# batch size
bs = 512
class Model007(nn.Module):
def __init__(self, vocab_size, n_fac):
super().__init__()
self.l1 = nn.Embedding(vocab_size, n_fac)
self.l2 = nn.Linear(n_fac, n_hidden)
... | albanD | I don’t think so. Wasn’t he doing m(*mb) ? Notice the *. |
Maziar | HiI am trying to understand/instrument autograd in PyTorch. I’ve put a pdb.set_trace() before backward and traced the code until Variable._execution_engine.run_backward() is called which prevents pdb to step into. I presume this is where the code calls C++ extensions.If so, is there a way to continue debugging and step... | albanD | The cpp engine is based onFunctionwhich are similar to the python ones. They are the elementary operations that are considered.
The forward pass attaches a grad_fn to the Tensors during the forward pass. Then you have a graph of Functions stored in cpp. Accessed from the next_functions field.
Wh… |
pytorcher | I am doing an abnormal network that needs to have values manually set to specific values. Currently porting to the newest pytorch, but everything was working as expected in an older version. When I now do (nn.Conv2d).weight = (other nn.conv2d).weight I am getting the “leaf variable has been moved into the graph inter... | albanD | Hi,
Since I guess you don’t want gradients to flow back this op, you should do:
with torch.no_grad():
(nn.Conv2d).weight.copy_((other nn.Conv2d).weight) |
m2q | I’m sorry if the answer to this question is obvious, but I’m not sure: If I have multiple parallel threads, and each thread has its own input tensor; will evaluating the net->forward() from each thread happen in parallel?(Btw you people have done insanely good work with LibTorch!!! Keept it up) | albanD | Hi,
I think forward ops are but not backward.@goldsboroughshould be able to give you a more decisive answer for libtorch. |
fanl | Pseudo code:def forward(self,x):out = torch.zeros(10,10,10,10)…out[:,:,:,col][:,:,row,:] = x # col row are indicesI feel like this is weird,because I did not operate on x itself. Instead, x is assigned to a part of another leaf tensor. Does this have a influence on backward? | albanD | Hi,
You can do this, and if the backward does not raise an error you will get the correct gradients.
What can happen though is that you get Tensor needed for backward has been changed by an inplace operation. As inplace operations can change a tensor needed during the backward pass. The engine is … |
gergi | This code should produce the same tensors printed at the end.#some random values and indices
m_size = 2
indices = torch.randint(low =0, high=m_size, size=(2, m_size+100)) #plenty of indices
values = torch.rand(m_size+100) #plenty of random values
#build the sparse tensor
sparse_tensor = torch.sparse.FloatTensor(indice... | albanD | Hi,
For indexing, you don’t need lists, so you can remove the tolist().
The problem here is that you set multiple values at once and so there is a race condition and only one of them is set at the end.
You should useindex_put_()with accumulate=True to get what you want:
regular_tensor.index_pu… |
Sophia_Wright | Is there a migration guide for PyTorch 1.0? (for converting PyTorch 0.4 code to PyTorch 1.0 code), any links to articles/posts on this topic would also help. Thanks. | albanD | There is no migration guide for 1.0 as there are no major changes to be done in your code.
You can check the Breaking Changes section of therelease notesto make sure that your code does not rely on any of them and then you’re good to go ! |
nurlano | I have a model, i switch to eval() mode which should set requires_grad to False for all parameters. Why does it complain about “Can’t call numpy() on Variable that requires grad” when i convert the torch output to numpy? | albanD | Hi,
.eval() is not setting requires_grad to False !
What eval does is to run your layers in evaluation mode. In particular, dropout will not drop anymore and batchnorm will use saved statistics instead of the ones computed on the fly.
If you want to disable the autograd, you should wrap you funct… |
NouBel | I want to compute the gradient between two tensors in a net. The input X tensor is sent through a set of convolutional layers which give me back and output Z tensor.I’m creating a new loss and I would like to know the MSE between gradient of norm(Y) w.r.t. each element of X. Here the code:# Staring tensors
X = torch.r... | albanD | Hi,
I think the problem is that you forgot that indexing is a proper operation. And so X[i] returns a different Tensor than X, and X[i] was not used to compute the norm, hence the error.
If you give X as input, you should get the gradients for all X and then be able to access X.grad[i]. |
Ran | nvidia-smi works, torch.backends.cudnn.enabled returns True, but torch.cuda.is_available() returns False. Reboot can’t do any help.I don’t know what’s wrong?CUDA path is as follows:export PATH=/home/ubuntu/cuda/bin${PATH:+:${PATH}}export LD_LIBRARY_PATH=/home/ubuntu/cuda/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}} | albanD | Hi,
If the cuda samples don’t run. Then the problem is with your cuda install.
I would advice in that case to cleanly remove all cuda install from the system. And reinstall them from scratch with nvidia drivers that correspond. Then make sure that the cuda samples work properly. Once these work, y… |
barakb | Hi, I have a small question, I want to exit my network, but not it the end, let’s say I’m certain in some level that my result is correct after 3 layers, and I don’t want to do the other 2 layers, How can I do it?I have the condition, and I’m counting the number of time itshouldexit, But I’m puzzled how to exactly exit... | albanD | Hi,
I don’t think you can do anything else that checking after every stage and breaking when you’re done. You have to do this for loop anyway, so adding an if statement into it is not a big deal. |
ElleryL | Hey; I have multiple loss functions, each with respect to a batch of data point. I want to save each gradient to a buffer.Here is my way of doingbuffer = []
for b in range(num_batch):
weights.zero_grad()
loss = loss_func(batch[b])
loss.backward()
buffer.append(weights.grad)However, I’m wondering if ther... | albanD | If you use the same weight you will have to do the for loop I’m afraid.
Note that in your code, you want to do weights.grad.clone() on the last line. All changes to .grad are inplace and so after you do weight.zero_grad(), your buffer will contain only zeros if you don’t clone. |
Ravneet_Punia | I am learning PyTorch and i came up with a code i.e “torch.manual_seed(7)” Explanation I got is its setting up random seed. But what is seed?? What its physical significance?? | albanD | Hi,
When you ask for random number in pytorch (with torch.rand() or t.uniform_() for example) these random numbers are generated from a specific algorithm.
A nice property of this algorithm is that you can fix it’s starting point and it will always generate the same random numbers afterwards. That… |
Jiacheng_Li | I want to write a loss function which will create new variables according to the shape of input data. The matter is when I use my loss withloss.cuda(0), the data in it won’t move to gpu device, and if the input data is on gpu it will occur error.I referred to the code of loss functions already exists in PyTorch and no... | albanD | Hi,
When you call .cuda() all the parameters and buffers of the module are moved to the gpu.
Parameters are everything that you saved as self.foo = nn.Parameter(args).
Buffers are any Tensor that you saved on self as self.bar = torch.rand(10).
All this is done in the__setattr__functions of th… |
Matthias | I am wondering how to implement the following scenario:I am executing my neural network to compute a loss. Additionally, I compute a regularizer on every hidden layer’s output. Crucially, this regularizer should only affect that individual layer’s weights. The regularizing gradient for a layer should not propagate back... | albanD | Hi,
This is whatautograd.grad()is forIf you add your regularizer to the final loss and call backward on that, then it will compute the gradient of this new function. In particular if you just want to do a weighted sum of the loss and the regularizers, that will work as you expect ! |
Val | Hello,I have a simple module that given a 2D tensor, multiplies it by another 2D tensorMfixed in advance (element wise), then computes a weighted sum. I use a loop to multiply the weights to the elements of the sum. There is probably a better way to do so, but this is only a simple example of my more complicated proble... | albanD | This creates a rather large computational graph indeed.
self.M*x though could be computed a single time and then reused in the loop, that will reduce it quire a bit !
Also even though your use case is more complex, remember that using .expand() and then doing one single multiplucation (possibly wi… |
jelo | I have a zero tensor in the forward pass of my module, whose size is depending on the batch size. Currently i am creating on each pass the tensor and sending it to the GPU if the input is on the GPU.Can i somehow put this zero tensor once on the GPU and clear it after each step?Easiest way would be to declare it as a p... | albanD | If you need a new Tensor every time, then you will need to create it every time, there is not way around it. You can use torch.zeros(your_size, device="gpu") to create it directly on the gpu and avoid the copy.
If you use it once then you can use resize_().zero_() (after detaching the current Tenso… |
arc144 | Hi guys I’m implementing a custom pooling function where there is a trainable tensor. So far I’m usingVariableto wrap the tensor andrequires_grad=True. However, it seems the that the variable is not changing as the model trains, it keeps stuck at the init value of 3. What am I doing wrong?Here is the code:class General... | albanD | Hi,
Variables don’t exist anymore so you don’t need them, you can do torch.cuda.FloatTensor([3], requires_grad=True) directly.
In nn.Module, for something to be recognized as a parameter (and thus be returned by mod.parameters()), it needs to be of type nn.Parameter(). So you should do:
self.p = … |
AreTor | Is there a way to preserve a subgraph of the DAG which does not contains its root? As an example, consider the following code:x1 = torch.randn(10, requires_grad=True)
x2 = x1 ** 2.
y1 = torch.randn(10, requires_grad=True)
y2 = y1 + 1.
z = (x2 + y1).sum()
z.backward(retain_graph=True)I need to reusex2, for other subsequ... | albanD | You can do exactly what you did here and reuse x2 in another computation.
A graph is kept only as long as something can reference it.
x1 = torch.randn(10, requires_grad=True)
x2 = x1 ** 2.
# Let call Graph 1 the part of the graph that give x2
y1 = torch.randn(10, requires_grad=True)
y2 = y1 + 1.
#… |
andreydung | I’m compiling a pytorch library (faster rcnn) with CPP extension (pytorch 1.0 and latest cpp extension method).The code can compile and run with python 2.7, but it fails to compile with python 3.6. Here is the compilation error:/home/ubuntu/anaconda3/envs/fasterrcnn_py36/lib/python3.6/site-packages/torch/lib/include/to... | albanD | Hi,
Did you installed pytorch the same way your did for python 2.7? Make sure there is no old version of pytorch present before installing a new one. |
chari8 | Based on the official tutorial, during prediction (after training and evaluation phase), we are supposed to do something likemodel.eval()
with torch.no_grad():
# run predictionBut let’s assume that we want to use state_dict extracted from trained model.In this case, we usually domodel.load_state_dict(torch.load('pa... | albanD | Hi,
There will be a small difference in most cases I think.
If you set every requires_grad to False. After each op, it will check whether the output requires gradients.
If you set the no_grad mode, then it won’t even try. |
Jiacheng_Li | While using PyHeat to analyze the time cost of my code, I find that the operation of Tensor.cuda() costs a lot, even more than that of using net to generate a result. Here is the cut of my PyHeat report:train1596×432 93.6 KBeval1562×266 72.2 KBI tried using Tensor.cuda() in the function ofgetitemin my dataset but faile... | albanD | Hi,
Because sharing cuda tensors across processes is a nightmare and because of the async nature of cuda not needed. |
Shisho_Sama | Hi, I want to multiply a vector by a matrix (batch, c, h,w).I can do it using a for loop like this :In [68]: x=torch.rand(2,3,2,2)
In [69]: y=torch.rand(3)
In [70]: for i in range(x.shape[1]):
...: x[:,i,:,:] = x[:,i,:,:]*y[i]I know I can simply do :In [101]: for i in range(x.shape[1]):
...: var=y[i]
... | albanD | Hi,
You can set dimensions to 1 so that they will be broadcasted:
y = y.view(1, 3, 1, 1)
out = x * y |
isalirezag | I want to apply softmax to each channel of a tensor and i was thinking the sum of elements for each channel should be one, but it is not like that.thispostshows how to do it for a tensor but in batch-wise manner.can someone helps me what should i do to apply softmax on each channel and the sum in each channel be 1?impo... | albanD | Ho ok
So you want out.sum(-1).sum(-1) to be 1!
Then you need to collapse the last dims together before the sofmax:
# Variables don't exist anymore, you can remove
# them and just use Tensors everywhere
A = torch.rand(1, 2, 3, 3)
A_view = A.view(1, 2, -1)
out_view = F.softmax(A, dim=-1)
out = ou… |
Shisho_Sama | This is a follow up to my previous question asked hereHow can I insert a branch variable in a model graph in pytorch?,The problem is , I noticed when training, the GPU utilization is very bad, and at first I thought maybe its because I didn’t make my parameters usecuda()it seems a lot is being off loaded to CPU instead... | albanD | Now if you have args.use_cuda=True, your model will use the GPU.
Keep in mind that if your model or input is very small, you might not use the gpu very efficiently and thus gpu usage will remain small. You need to perform large enough ops for the gpu to be properly used. Increasing the batch size i… |
John1231983 | To work with larger batch size in the limited GPU resource, we often use accumulate gradient strategy as follows:optimizer.zero_grad()
loss_sum = 0
for i in range(iter_size):
loss = criterion(output, target_var) / iter_size
loss.backward()
loss_sum += loss
optimizer.step()The stratgy often used in SGD. Doe... | albanD | Hi,
Yes it will work as this just change how you compute the gradients, nothing else. An optimizer like adam is agnostic to the way you obtained your gradients.
In your code you want to do: loss_sum += loss.item() to make sure you do not keep track of the history of all your losses. .item() (or yo… |
iman.mirzadeh | Hi,Say I have a network, like the figure below.During the training, I want to freeze layer 1 and 3 and only update weights on layer 2. Is it possible?I don’t know how to do because according to the Autograd documentation, if at least one the inputs of a node in the computation requires grad, then that node requires gra... | albanD | Hi,
You can go through every parameters that you don’t want to update and set them not to require gradients:
for p in layer2.parameters():
p.requires_grad = False
This means that no gradients will be computed for these parameters.
As further optimization, you can give to your optimizer only … |
fangyh | Is there any python code which implements the forward pass of the following one?torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True) | albanD | Hi,
No there is none.
There are specific cpp/cuda kernels to do this. In the case of gpu, it mostly uses cudnn own implementation that use many different algorithms itself.
The classic implementation that we use on CPU is based on matrix multiplication and would look like this in python (note tha… |
Shisho_Sama | Hello all.This has confused me for sometime now. I am learning pytorch and for improving my understanding of how everything works, I’m experimenting with different sections of the framework.Recently I though about creating custom operations and layers in pytorch.The problem is, all of the examples I have seen so far ha... | albanD | Hi,
First of all you do not need to explicitly register the parameters. This is done for you automatically when you save an nn.Parameter as self.foo. This means that you can remove your register_hook function completely and it won’t change anything.
The problem here is that the operations that you… |
Driesssens | I’m trying to verify that my code (CPU only) is utilizing all available computation resources. Doestorch.get_num_threadsgive the number of threads that are potentially available or that are actually used by the current part of the code?In the latter case, where should I print its return value for diagnosis i.e. which p... | albanD | Hi,
It prints the total number of threads that are usable (they may or may not be used at the moment).
Only heavy cpu computations (mm, element-wise ops, linear algebra…) operations use that at the moment.
You need to be carefull which BLAS library you use to be sure to get the best possible perf… |
DaddyWesker | HelloThe problem or idea, whatever, is: i want to put my own kernel/filer to conv2d. For example, i have generator of kernels and i want to apply it to batch of images. In tensorflow there are tf.nn.conv2d which have “filter” as input, but these “filters” are of size [in, out, height, width]. No batch size. But i need ... | albanD | Hi,
The nn.Conv2D() layer has a .weight and a .bias that contain the weights and bias used by the convolution.
As you can see in the module’s implementationhere, it’s just using the functional interface and give these weights and biases to it. You can use directly this functional interface if yo… |
aliutkus | dear all,For some reason, I would need to compute the back-propagation for some module with a known value for the gradient.In other words, I want to callbackwardfor some module, without previously calling aforward.For instance, on a linear module with weights W and no bias such thaty=Wx, this backward pass amounts to m... | albanD | Hi,
It’s not possible in general because some modules actually require the forward pass to be able to do the backward.
For the case of the linear, if you want the gradients wrt the weights, then you need the forward to have save the input tensor to be able to compute the gradients.
Of course in s… |
dfalbel | This is more a conceptual question… Consider:NoGradGuard guard;
b -= lr * b.grad();I know thatNoGradGuardwill disable action recording for the next gradient calculation.But how does it really works? | albanD | Hi,
It actually sets a global flag that is checked by the backend whenever an op is done on a variable.
The guard itself saved the current status and set it to false in the constructor. And restore the saved status in it’s destructor. That way it is similar to a with torch.no_grad(): block in pyth… |
JisongXie | I have encountered an odd problem:My lab has a server with four 1080Ti GPU(about 12G),and it’s used by multiusers. I have installed CUDA9.0, cuDNN7.4.3 for CUDA9.0, pytorch 0.4.1。When I create a random tensor, neither small size of big size, when it’s print or copy, it occur an error, which say “cuda runtime error:out ... | albanD | Hi,
Tensorflow has the bad habbit of taking all the memory on the device and prevent anything from happening on it as anything will OOM.
There was a small bug in pytorch that was initializing the cuda runtime on device 0 when printing that has been fixed.
A simple workaround is to use CUDA_VISIBL… |
Dawid_S | It is hard for me to understand all the components, structure, and the history of PyTorch project.I know there is Torch library that works with Lua. Somewhere there, there’s C part of the code, that works with CUDA (but CUDA is written in C++, so how it is?). Suddenly some people took some part of these things and crea... | albanD | Hi,
The initial torch7 (which is what you call Torch) library was written in lua and based on a pure C library called TH for cpu computation and cpp library called THC for gpu computations (this include all the cuda/cudnn dependancies). There was also THNN and THCNN for neural network specific ops.… |
Mactarvish | I just updated my pytorch from 0.2.0 to 1.0, finding that the lr_scheduler is never valid. Where can I get the information about every update? Thanks. | albanD | Hi,
You can find all the release notes on the github release pagehere. |
alvations | I am trying some weird evolutionary neuron connections on a simple XOR problem.And when I am back-propagating the losses, theloss.backward()throws a IndexError:IndexError Traceback (most recent call last)
<ipython-input-2-39958196b2d6> in <module>
86 for loss, idx, network in fit... | albanD | Hi,
loss is a Tensor at this line:
loss['model'].backward()
So you should not try to get the 'model' attribute from it.
loss.backward() should work though |
hotcheetos_puff | When using torch.nn.parallel.data_parallel for distributed training, models are copied onto multiple GPU’s and can complete a forward pass without the copied models effecting each other. However, how do the copied models interact during the backward pass? How are the model weights updated on each GPU?When reading the d... | albanD | Yes the locking is builtin and the weights will properly be updated before they are used. |
Asger_Kjaerulff | This is just a super basic question that I have not been able to successfully google an answer to.I’m trying to understand how the torch.Tensor object stores information on its position in the graph. Since autograd can calculate gradients based on operational relations between torch.Tensor objects, information about th... | albanD | Hi,
First, this part is not really documented more on less on purpose as the backend is moving quite a lot still. Even though we make sure the python/cpp user facing interface do not change, there are still some changes in the backend and what I’m going to describe below is the current state and ma… |
0xFFFFFFFF | is there an equivalent of Tensorflow Serving in Pytorch? More specifically, automated inference server that handles batching requests to maximize performance, switching models, running experimental models and recording performance…tensorflow serving:https://www.tensorflow.org/serving/ | albanD | Hi,
No there is not such thing at the moment but contibutions are welcomed |
mufeili | An important pooling like operation is to take elementwise maximum along an axis. For batched tensors with same sizeN, D1, D2, ...,torch.maxis all we need. But when it comes to the case where the first dimension of tensors are different withN1, D1, D2, ...,N2, D1, D2, ..., …, we need segment max. Is there a recommended... | albanD | Hi,
Pytorch does not have all the segmentation ops like tensorflow.
The best way to do this depends on how you have the tensors to start with. If they’re already in one Tensor with padding, then keep it that way. If you have a small number of them or widely different sizes , a for-loop will be bet… |
Zichun_Zhang | prop_f = torch.empty([b,c,h,w], device='cuda', requires_grad = False)prop_f is a tensor that I created , so in theory, it is a leaf.after that,prop_f[bb,:, hh, ww] = productI use prop_f to store some important intermedian variable tensor that are in the computation graph.So, after that, is prop_f requires grad now? a... | albanD | Hi,
Yes the gradients will flow back properly to the layers above.
For convolution-like operations, you might want to check the im2col function. It might help you speed up your code depending on what you want. |
Shisho_Sama | Hi everyone,I’m trying to run training on imagenet, but I face the mentioned error! I have no idea what is causing the issue. Any help is greatly appreciated .Here is the full log :=> creating model 'resnet18'
=> Model : ResNet(
(conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
(... | albanD | The line that is interesting is this one: /pytorch/torch/lib/THCUNN/ClassNLLCriterion.cu:101: void cunn_ClassNLLCriterion_updateOutput_kernel(Dtype *, Dtype *, Dtype *, long *, Dtype *, int, int, int, int, long) [with Dtype = float, Acctype = float]: block: [0,0,0], thread: [10,0,0] Assertiont >= 0 &… |
weixia-cs | Compute the truth value of x1 OR/AND/NOT x2 element-wise inNumpyisnumpy.logical_or,numpy.logica_and,numpy.logical_notThe same function ofTensorFlowistf.logical_or,tf.logical_and,tf.logical_notand i do not found in PyTorch docs, Is there some equivalent in PyTorch and if not, would it be possible to add these functions... | albanD | On a byte tensorz you can use the python syntax for them or directly __or__, __and__ etc |
Roman_Steinberg | I’ve tried to run WGAN model and meet some strange behavior. I’m not sure is it my bug, or pytorch bug. I made aminimal exampleto discuss it here.So, we have an errorRuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward... | albanD | Hi,
Yes this comment was more to explain the details of the issue without writing too long stuff on the github PR.
You can either use inplace=False or use the version of relu that I gave you above with inplace=True. |
atakanokan | I have been experiencing really slow read times (when I call data.next() in my training loop) when I use Google Cloud Compute. However my school’s HPC is reading the same file 20x faster and I couldn’t find the reason behind this difference.Any help is appreciated!def __getitem__(self, idx):
if self.f_open == F... | albanD | Hi,
Isn’t the difference simply the read speed on the drives? If you have locall ssd on the schools hpc and remote hdd storage on GCC ? |
Zichun_Zhang | Hello!Is there any possibility that when use A*B in pytorch, the operator * automatically produce dot product if A,B are not suitable size for matrix product, and produce matrix product otherwise???I am so confuse since this change when I use sometimesSo! is torch.mul(A,B) the really matrix product operation and A... | albanD | Hi,
None of them is dot product. They both are element-wise multiplication.
Dot product/matrix multiplication is done with torch.mm or torch.mv or the @ symbol in python3. |
Pengbo_Ma | I was training my model using Yolo v3When I set my input size = 416, I can train my model with batch size = 9 without any errors.However, when I decrease my input size to 320, I ran into Cuda memory error even when my batch size = 7.I found this particularly strange, has anyone encountered anything similar before?Erro... | albanD | Ho,
What happens if you add torch.backends.cudnn.enabled=False at the beginning of your code? Does the error still occurs? |
JuanFMontesinos | I was looking at the code of batchnormdef __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True,
track_running_stats=True):
super(_BatchNorm, self).__init__()
self.num_features = num_features
self.eps = eps
self.momentum = momentum
self.affine = affine... | albanD | Hi,
You have two kinds of Tensors that a Module want to hold to:
Some that are learnable. Represented as nn.Parameter and that should be registered with mod.register_parameter("name", value) where value can be either None or an nn.Parameter
Some that are not learnable. Represented as regular torc… |
Zichun_Zhang | Hello, How to concatenate two feature(1 * C * H * W) tensor together, without using extra space of GPU,for instance, just append the second tensor B after the first tensor A, so become the output tensor(1 * 2C * H * W )Thx! | albanD | Hi,
You can use torch.cat([t1, t2], dim=1). |
Driesssens | Is there a specific reason whytorch.nn.functional.mse_lossis wrapped in the classtorch.nn.MSELoss(and likewise for the other loss functions)? Feels slightly cumbersome to first instantiate a class and then call itsforward. Is there some autograd magic going on? | albanD | Hi,
First you should never call the .forward() method of an nn.Module. But call the module instance with the inputs.
The advantage of the class version are:
For modules with parameters or buffers, it is nicer to just save these in self
It allows to use simple structure constructions like nn.Sequ… |
fashandge | In fairseq code, I saw some use of the “out=” argument for tensor operations similar to below. Are there any performance benefits of using “out=” parameter? It seems less natural and less readable. Does it offer performance gain like avoiding generating intermediate results? Or is it just good for specifying the destin... | albanD | If you create an empty tensor, then give it as out=, then it will be resized and filled with the result. This will be the same as c = a + 3 in your first example.
Doing c[:] = a + 3 will create an intermediary result and copy it into c (which will work only if c has been resized beforehand).
If ca… |
nima_rafiee | HiI have a Tensor of shape [n, m, m] ( n images each m*m ). I want to mask each image according to the max value of each row of the image. the final matrix has the same shape as the original one but the [m,m] is now mask matrices. what is the fastest way on GPU to do this? | albanD | You have comparison function that will give you a 0-1 ByteTensor that contains a mask.
For example:
import torch
t = torch.rand(5, 10, 10)
tmax = t.max(-1, keepdim=True)[0]
mask = t.gt(tmax) # stritly greater
mask = t.ge(tmax) # greater or equal |
bat67 | Hi~It’s great to hear PyTorch release a stable 1.0 version today! But when I was going to update it, I noticed on theofficial website, no 9.2 is written in CUDA’s supporting row, only 8.0, 9.0 10.0 and None. What I’m using currently is PyTorch 0.4.1 with CUDA 9.2 on Windows 10, and I remembered there was a conda instal... | albanD | Hi,
The problem is that each binary is (very) time consuming to do and the process needs to be done from scratch for every CUDA version.
So the decision has been made to support only one version of CUDA for all the 9.X series.
If you stay with CUDA 9.2, I’m afraid you will have to compile from so… |
jxgu1016 | I find some codes inthisand become curious about the function of@once_differentiable. | albanD | Yes.
You should use it when you write a backward that cannot be used for high-order gradients. |
0xFFFFFFFF | My understanding of THCudaTensor_data( state, tensor ) is that its general function is to retrieve the data from a pytorch’s tensor and save it as an array. However, I cannot understand the specifics.what is the state?what if the initial tensor is 2D or beyond? Does it flatten the 2D into long 1D array?is the date type... | albanD | There are similar but they are not always cudaMalloc-ed. Indeed, there is a custom allocator inside pytorch that handles the allocation of the data for Tensors.
I am not sure what you call a “cudaMalloc-ed array” but these datas contain flattened data where the storage_offset, size and stride prope… |
sroy | Hi,I have my own implementation of batch norm layer in pytorch. When I use the custom BN in a layer which comes before a layer with dropout then it works perfectly fine. Whereas when the BN is used after a layer having dropout then it causes OOM.Could you please let me know why the activations of previous batches keep ... | albanD | Hi,
That depends how you implement your custom batch norm.
Did you make sure to use .detach() properly when saving statistics not to keep backpropagating into previous batches. |
beneyal | Hi,I’m trying to understand the language model example here:https://github.com/pytorch/examples/tree/master/word_language_modelI can’t understand what’s happening at the last two lines of theforwardmethod in this model (I removed irrelevant code):class RNNModel(nn.Module):
"""Container module with an encoder, a rec... | albanD | The self.decoder here is just the linear layer to goes from the hidden units to the output size.
And to decode all the outputs for each time step and each element in that batch, it reshape the output tensor that was (where x is the separator for different dimensions) batch x nb_steps x hidden_size … |
John1231983 | I have an equations likes$y = \sum_{i=0}^3 \alpha_i * prob_i$where $prob_i$ is a vector 1x32 and $alpha_i$ is a learned parameter. It will be learned during training. So, my code isclass parameter_learning(nn.Module):
def __init__(self):
super(parameter_learning, self).__init__()
self.alpha_... | albanD | You should save alpha_list as a ParameterList to ensure it is detected properly by the rest of the nn code.
You can also create a single vector of size the number of alpha and then do a dot product to compute your loss. |
marcman411 | I believe that conv2D is implemented with some cudnn tricks. But how does it scale so well with batches?When I run a batch size of 1:bs = 1
h = 128
w = 256
in_channels = 512
out_channels = 1024
kernel_size = (3,3)
stride = (1,1)
padding = (1,1)
dilation = (1,1)
cuda = True
test = Test(
in_channels=in_channels,
... | albanD | The thing is that the cuda API is asynchronous so the only thing you measure here is the time to launch the job, not how long it takes to run on the GPU. You need to synchronise:
# Make sure nothing was still running on the GPU
torch.cuda.synchronize()
s = time.time()
pytorch = F.conv2d(x,
wei… |
erickrf | I found that if I create a new parameter and then move it to the GPU, it is not included in the model’s state dict:In [18]: class A(nn.Module):
...: def __init__(self):
...: super(A, self).__init__()
...: self.linear = nn.Linear(10, 5)
...: tensor = torch.randn(10)
.... | albanD | Hi,
The thing is that .cuda() is an out of place operation. And so the result is not a Parameter anymore, it’s just a Tensor. Since it’s not a Parameter, it is not included in the state_dict.
You can use tensor = torch.randn(10, device="cuda") to create the tensor directly on gpu and avoid such p… |
AreTor | in PyTorch 0.4.1, how can I check if a tensor contains boolean values?Is the following code, the standard way?t1 = torch.tensor([True, False, False])
print(t1.dtype == torch.uint8) | albanD | Well no Tensor contains only boolean values. They will contain uint8 as you have seen. But they could contain numbers bigger than 1 as well. |
isalirezag | I have a tensorT=torch.rand(1,1000,10,10)and i want to save it and reuse it later.I can do it via.ptand.pthwhat is the difference between them?also, is there any other way of saving a tensor that save more space/memory? | albanD | They will do exactly the same thing. The saving format will not change depending on the file extension. |
jaeyung1001 | the df is DataFrame and contain“data”, “label” columnand I want to use DataLoader function to split the data every batch_sizebatch_size = 32
test_loader = DataLoader(dataset=df, batch_size = batch_size,
shuffle = True, num_workers=2)
for i, data in enumerate(test_loader):
print(data['data']... | albanD | Hi,
The dataset should be atorch.utils.data.Datasetsubclass, not a DataFrame. |
soshishimada | Hello.I am writing codes to train neural networks.When training with a small size dataset, there’s no problem, however, when training with a large dataset, the system says “RuntimeError: CUDA error: out of memory”.In my understanding, GPU memory use isn’t influenced by the size of the dataset since Pytorch load and sto... | albanD | Hi,
Aren’t you missing a .item() when you accumulate D_adv_loss ? I think that running_train_Dloss actually has the graph of all previous iterations here. |
beneyal | Hi,I couldn’t understand from the documentation what thenarrowmethod does on a tensor, the example doesn’t make sense to meMore specifically, I’m trying to understand what’s going in this code (fromhttps://github.com/pytorch/examples/tree/master/word_language_model):def batchify(data, bsz):
# Work out how cleanly w... | albanD | Hi,
If you’re more familiar with advanced indexing, for a 2D tensor t2d, t2d.narrow(1, 0, 10) is the same as t2d[:, 0:10] and t2d.narrow(1, 5, 2) is the same as t2d[:, 5:7].
narrow is interesting as for higher dimensionnal tensors, you don’t have to do : for every other dimension. Also narrow() (l… |
deepmo | Hi all,In my program, I restore a model(torch.nn.DataParallel) and use device 2 to continue training. However, Like the picture shows, the program not only uses device 2, but also takes up some gpu memory of device 0 and 3. I am confused about that.I guess it may happen when my model is first trained from device 0 or 3... | albanD | Hi,
475MB is most certainly only the cuda initialisation on this device, no Tensor.
Maybe you want to specify the map_location argument oftorch.loadwhen you load your model to avoid initializing the other GPUs.
Another way is to use CUDA_VISIBLE_DEVICES=2 as an env variable for your script so t… |
Sun_ShiJie | Hi, I run the code:import torch
class MyModule(torch.jit.ScriptModule):
def __init__(self, N, M):
super(MyModule, self).__init__()
self.weight = torch.nn.Parameter(torch.rand(N, M))
@torch.jit.script_method
def forward(self, input):
if input.sum(... | albanD | As suggested in the error, you just want to cast it to a proper boolean:
if bool(input.sum() < 0): should work no? |
dragen | Hi, How to copy value from tensor to nn.Parameter()sincev_parameter.copy_(v_tensor)requires same type. | albanD | It requires same type in the sense of float/double/long right? You can use type_as() on v_tensor before giving it to copy. You should enclose this into a with torch.no_grad(): block to avoid errors because you modified inplace a leaf tensor. |
HaziqRazali | I am trying to get the gradients of the loss wrt the input in my RNN model. It uses a VGG 16 as a feature extractor and an LSTM for sequence modelling. I registered the hook to the first layer of the VGG16 deep net. According toExact meaning of grad_input and grad_output,grad_inis supposed to be a 3-tuple that contains... | albanD | Hi,
register_backward_hook can have some unexpected behaviours sometime.
If you want the gradient wrt an input, your can call register_hook on this input tensor directly that will be called with the gradient for this input. |
acgtyrant | https://pytorch.org/docs/master/search.html?q=Tensorstucks in SEARCHING.2018-11-14-131850_1637x579_scrot1637×579 45.9 KBBy the way, the search engine in the stable docs works. | albanD | I can reproduce that, we’ll look into this. Thanks for the report ! |
pwr617 | This post was flagged by the community and is temporarily hidden. | albanD | Hi,
torch.cuda.synchronize() just wait for all the work to be done on the GPU.
If the synchronize takes different time for different models, I guess that means that one requires more things to be done on the GPU. There is not much you can do here.
Also, unless you are doing time meansurement, you… |
youngminpark2559 | A is RGB image and hat A is predicted RGB image from PyTorch CNNSame with S.How to get “triangle down (gradient) image”? | albanD | Hi,
You can set requires_grad=True on the input before feeding it to the network. That way after the backward pass you can check it’s .grad field to get the gradients. |
MichaelA | Hi,I’m wondering whether resize operation will affect backpropogration. If I have a tensor: input, with size (n1n2n3,1), then run the following codes where netA and netB are two networks:inputv = Variable(input, requires_grad=True)output = netA( inputv )output = output.view(n1,n2,n3)output = netB( output )output.backwa... | albanD | Hi,
Resizing is seen as any other op and is perfectly differentiable. So you can .view() is any way you want and it will work ! |
fryasdf | Hi all. I am sorry to bug you again with this kind of question but the notation is really confusing (if not wrong in my opinion). The question is about torch.optim.SGD.Question in short: Isn’t torch’s SGD just a regular ‘step into the direction (-gradient)-optimizer’ instead of SGD? Shouldn’t it be named ‘GD’ instead o... | albanD | Yes the update step for GD and SGD are the same and so from the optimizer point of view they are both the same.
If you want to the S to be meaningful, you can see it as Sub Gradient DescentBut here again if you had real gradients, the update would be the same.
It is not possible to save gradien… |
Fractale | WhyMultiLabelMarginLosstake torch.long has arguments?From understandingMultiLabelMarginLosstake not labels but one hot encoding labels so we can use multiclass multilabels prediction.WhyMultiLabelMarginLossarguments shoud be long? It’s compose of only 0 and 1.I have the following error if I try with uint8RuntimeError: ... | albanD | Hi,
The target tensor is not expected to contain one hot encoding. from thedoc:
"
The criterion only considers a contiguous block of non-negative targets that starts at the front.
This allows for different samples to have variable amounts of target classes
"
It should contain label values and… |
Diego999 | Hi everyone,Basically, I have a matrix computed from another program that I would like to use in my network, and update these weights.In [1]: import torch
In [2]: import torch.nn as nn
In [4]: linear_trans = nn.Linear(3,2)
In [5]: my_weights = torch.tensor([[1,2],[3,4],[5,6]])
In [6]: linear_trans.weight
Out[6]:
Param... | albanD | You should not use .data anymore but use the with torch.no_grad(): context manager with the most recent versions of pytorch.
See how the nn.init module work for examplehere.
And yes to all your questions otherwise, it will work exactly that way.
Note that setting requires_grad = False will make … |
Moon_Lee | Hello all, I have a network architecture as follows:input --> conv1 (3,1,1) --> bn --> relu --> conv2 (3,1,1)
| ^
|-------------------------------|where conv1(3,1,1) means kernel size is 3, stride 1 and padding 1The output of conv1 will be concatenate wi... | albanD | I guess it’s like a resnet module:
class ConcatMod(nn.Module):
def __init__(self, args):
# Use args properly to set conv params here depending on your application
self.conv1 = nn.Conv3d(32, 64, kernel_size=3, stride=1)
self.conv1_norm = nn.BatchNorm3d(64)
self.co… |
thisthuan | Model specs:RGB imagesfilter709×621 136 KBI build:class Model(nn.Module):
def __init__(self, num_classes=5):
super(Model, self).__init__()
self.conv1 = nn.Conv2d(3, 96, kernel_size=11, stride=4, padding=2)
self.lu1 = nn.ReLU()
self.pool2 = nn.MaxPool2d(kernel_size=3, stride=2)
... | albanD | # Last convolutionnal layer return 4D output
output = self.pool8(output)
# Rephase to a 2D element to work with Linear layers
output = output.view(output.size(0), 7*7*192)
# Do Linear operations now
output = self.fc9(output) |
bonzogondo | Hi,I am new to PyTorch and I am currently working on an image classification project, in which I need to use ResNeXt-50 provided byFB.I downloaded the repository and tried to load the model using ‘load_lua’ command (.t7 extension), but it gives me an error:T7ReaderException: don’t know how to deserialize Lua class torc... | albanD | Hi,
Aren’t these resnet models the same as the ones provided in torchvisionhere?
import torchvision
resnet50 = torchvision.models.resnet50(pretrained=True)
# There you have it ! |
wwiiiii | When I use simple forward hook and backward hook on any CNN model, memory leak occurs.Here’s simple snippet to reproduce the phenomenon.def bar():
model = models.resnet101()
model.eval()
a, b = None, None
target_layer = model.layer4[-1].conv3
def forward_hook(module, input, output):
non... | albanD | This is “expected” behaviour as stated inthis commentin the code.
For the record,
In your case you trigger this because:
The last Function on which you put the backward hook contains the backward hook.
This backward hook function because of the partial, references the parent nn.Module
This nn.… |
kaixin | What is the difference between[None, ...]and.unsqueeze(0)when adding a new dimension to data?In my test, both methods share the original storage and.unsqueeze(0)is slightly faster. Is[None, ...]just a wrapper of.unsqueeze()?Thanks. | albanD | Hi,
[None, ...] is numpy notation for .unsqueeze(0). The two are equivalent. The version with advanced indexing might be a bit slower because it has more checking to do to find out exactly what you want to do. |
lxtGH | I want to know whether pytorch support cuda10 now ?? I can’t see it in the offical website page. | albanD | Hi,
Binaries are not available for CUDA 10. It will be added for 1.0
You can use CUDA 10 if you compile from source though. |
Bassel | I read the examples in the documentation and the explanation but i still can’t understand what this function does. | albanD | Hi,
It is setting particular values of a tensor at the provided indices. The value that you set can either be always the same or provided by another tensor wich is the same size as the indices tensor.
For example, if you want to do a one hot encoding of a 1D tensor of labels, you can start with a … |
pytorcher | I am getting the following error.RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.I am moving my code from 0.2.0.4 to 0.4.1. With a few checks for version the code runs on both up to a few epochs, b... | albanD | Hi,
I think the best practice is to just remove all Variables and .data from your code.
Variables are not needed anymore and you can pass requires_grad=True when you create a tensor if needed.
The .data should be replaced by either .detach() if the goal is to prevent gradient from flowing back. O… |
barakb | I got this warning:volatile was removed and now has no effect. Usewith torch.no_grad():instead. inputs = Variable(inputs, volatile=True)So I started to investigate :torch.no_grad(), and I have 2 small question about her:1.In the validation file I had those lines:inputs = Variable(inputs, volatile=True)targets = Variabl... | albanD | Hi,
You should actuall wrap the whole validation code (that requires no backward) within this torch.no_grad() block. Note that you can also use it as a decorator of your eval function:
@torch.no_grad()
def val(args):
# You validation function
return accuracy
1-bis In recent pytorch versi… |
Joy_Chopra | I have 3 networks with same architecture - A, B & CThe weights of C are set as convex combination of weights of A & B as shown belowfor a_param, b_param, c_param in zip(a.parameters(), b.parameters(),
c.parameters()):
c_param.data = weight * a_param.data + (1 - weight)... | albanD | Does the following work ?
for a_param, b_param, c_param in zip(a.parameters(), b.parameters(),
c.parameters()):
# Don't use data of A and B params for the gradient to flow back to them
# Use .copy_ here to change the value of the params of C, d… |
Espen | When definingforwardmy lizard brain always reels at code like:def forward(self, x):
x = nn.foo(x)
x = nn.bar(x)
x = nn.baz(x)
return xordef forward(self, x):
return nn.baz(nn.bar(nn.foo(x)) #imagine depper nesting and longer namesand wants to write something like:from toolz.functoolz import pipe
de... | albanD | Hi,
The autograd engine only records the “basic” operations done on Tensors. So any logic that you add around it will not impact the whole autograd engine.
The overhead you will have is the overhead of running more python code. Depending on the size of your net, that can be completely negigeable (… |
divinho | Is that possible somehow? I looked at the Caffe2 and Torch cmake files and there did not seem to be a straightforward way to do it (but I’m a newbie with C++ compilation and cmake). | albanD | I am not sure what you want. But the NO_CUDA=1 flag will disable all cuda stuff. |
yangcheng001 | My own loss function is special and can not be solved by the ‘autograd’ function. so I want to define the backward() in my loss function. But I don’t know if I can get the gradient of loss by hand and make it back throughout the network automatically?import torch
class MyLoss(torch.autograd.Function):
@staticme... | albanD | Yes you can do that. See more detailsin the doc.
Be careful:
You should not instantiate an instance of the Function. You should do loss = MyLoss.apply(output, label). If you prefer to instantiate an instance, you can simply create a new module like:
class MyLossMod(nn.Module):
def forward(s… |
Joy_Chopra | I was looking at code ofLayer normand the tensors are implicitly being assigned float32 data type.Why has this been done? | albanD | Hi,
All module’s parameters are created with the default tensor type torch.Tensor.
If you want to change this, you can either change the default tensor type withtorch.set_default_tensor_type()or by changing the type of the layer afterwards with your_layer.double() to convert to double or your_la… |
tomguluson92 | Hello,it really made me confused when reading the@SimonWrefered source code inAutoGrad about the Conv2d.When i read the detail of functionTHNN_(SpatialConvolutionMM_updateGradInput), Could any warm-kinded people tell me the meaning ofgradInput,gradOutputandgradColumsand the correct order of reading Autograd mechanism ... | albanD | Yes, if you’re in the backward of the layer l,
grad_input = di,l
grad_output = di,l+1 |
ohlr | Can someone explain to me what that function _convolution_double_backward()does? And when it is called?It is located inConvolution.cpp | albanD | HI,
As you can seehere, it defines the backward of the backward function for convolution.
It is used if you need higher order derivatives through a conv layer.
The autograd could build it automatically from the backward implementation of conv but this custom function is much faster. |
Juna | Hello, I would like to get a gradient of certain module, so I did some experiment, andI found something that I cannot understand.I made a model that has only one layer and one weight, and then put a single number into a layer then I tried to get a gradient of this number. so I coded like followingclass fcl(nn.Module):
... | albanD | Hi,
The backward hooks for nn.Modules are not working properly at the moment (should be fixed soon).
The gradients that you see here are not the ones you expect.
To check gradients, I would add hooks inside the forward function like:
def get_hook_fn(name)
def hook(grad):
print("grad … |
bananacode | The following code snippet produces the RuntimeError “one of the variables needed for gradient computation has been modified by an inplace operation”for i in range(n):
arr[i] = torch.cross(vec[i], vec[i+1])
arr[i] = arr[i] / torch.norm(arr[i])Whereas if I refactor it to the following:for i in range(n):
tmp = torch.cros... | albanD | if arr is a torch tensor, then assiging into arr[i] will copy the data inplace in the tensor.
So yes this is an inplace operation. |
piojanu | Hi!I have following problem during PyTorch compilation on Linux (I’ve been able to successfully compile it on macOS):Install the project...
-- Install configuration: "Release"
-- Installing: /macierz/home/155079jp/Programs/pytorch/torch/lib/tmp_install/share/cmake/Gloo/GlooConfig.cmake
-- Installing: /macierz/home/1550... | albanD | Hi,
It does look weird indeed.
It looks like it splits the compilation command line in the middle and so the compiler does not have input files specified, and it tries to execute the compiler arguments as bash methods.
Do you by any change used a windows computer to get the code before putting i… |
wwiiiii | I’m now trying to implement Guided backpropagation fromhttps://arxiv.org/abs/1412.6806, which alters the gradient calculation in ReLU layer.When given model is implemented in the way containing nn.ReLU() instance as its submodule, I can easily register backward hook function to its every submodule as below.model = resn... | albanD | Hi,
Unfortunately I’m not sure if it is easy to do this.
I guess you could always replace F.relu by a custom function that would use the nn.Module version with your hook.
Otherwise, you can add a hook on any tensor you want, but that would require modifying the forward method of your module. |
daquexian | In my model, the weight of conv is determined by another tensor(let’s call itweight_real) on the fly while running model, the actual parameter to be optimized isweight_realbut not theweightitself.So I create a new module that callsF.conv2dinforward. What I expected is the grad propagates first from the output to thewei... | albanD | Hi,
The only gradients you actually care about are for weight_real no?
In that case you can just make weight_real a Parameter of your module and create weight in a differentiable manner during the forward. |
Chieh_Wu | HelloIf I have 2 networks, the output of the first network is passed into the 2nd network.I would run back-prop on an objective function using output of the 2nd network. However, I only want to update the first network and leave the 2nd network alone (by minimization). Later on, I want to update only the 2nd network ... | albanD | Hi,
I think the simplest way is to have two different optimizers.
Each one work with the parameters of one of the two networks. Then you do your forward/backward as usual and just call .step() for the optimizer of the network you currently want to update. |
Naman-ntc | I am working on adversarial attacks with pytorch.I was initially using floatTensors but my backpropogation was not consistent.After searching I foundhttps://github.com/pytorch/pytorch/issues/5351. Due to iteratively using thr wrong values my answers differ significantly across experiments.Then after I moved to DoubleTe... | albanD | Hi,
This problem is not linked to pytorch itself.
Doing numerical differentiation with finite difference (what gradcheck does) can be quite far from the truth depending on the function, which point you differentiate and the value of epsilon you use.
The autograd in any framework you will use do t… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.