user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
kaiseryet | So I need to get the size of a list of tensors… that’s right,[tensor_1, tensor_2, tensor_3]; apparently,.size()will not work for this, so I need to usemapfunction eventually I guess. But what’s the function to get the size of the tensor? | albanD | Fun fact, the lambda is actually significantly faster than creating a function and reusing itIn [1]: import torch
In [2]: def gs(t):
...: return t.size()
...:
In [3]: t = torch.rand(10, 3, 2)
In [4]: %timeit gs(t)
692 ns ± 12.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops e… |
jwillette | I just want to make sure that I am understanding this part correctly. I see in the MultiheadAttention module (https://pytorch.org/docs/stable/_modules/torch/nn/modules/activation.html#MultiheadAttention) that if the $q, k, v$ tensors are all the same dimension, then the model callsself.register_parameter(<name>, None)w... | albanD | This means that they are defined but don’t have values.
This is useful to make sure that user code won’t try to use this attribute (as it is already reserved to be a Parameter) leading to weird behavior later.
Note that torch.empty(<size>) actually returns a Tensor, but it contains uninitialized m… |
TinfoilHat0 | Hi,Suppose I’ve a code block wrapped with torch no grad and I call a function that does inference in it, i.e,with torch.no_grad():
my_infer(my_model, my_data)should I use withtorch.no_grad()at the beginning of my_infer() too or is the outer no_grad sufficient? | albanD | Hi,
It is a context manager. So it will enable the no_grad mode when you enter it and disable it when you leave the indentation.
So no need to do it again inside the function, it will still be activated. |
abhishek_karanath | I have a tensor of shape 4x64x300 and i need to find the dot product of all of the four 64x300 matrices to get a 64x300 matrix. What is the most efficient way to do this? | albanD | You can use torch.prod(inp, dim=0) (dochere). It is like sum but does a product instead of addition. |
TinfoilHat0 | Is there a way to access the gradients directly from the loss, without using an optimizer?For example,inputs, labels = inputs.half().to(device=self.args.device, non_blocking=True), labels.to(device=self.args.device, non_blocking=True)outputs = self.model(inputs)minibatch_loss = self.criterion(outputs, labels)minibatch_... | albanD | Hi,
If you use autograd.backward(), it populates the .grad field of all the leaf Tensors (all tensors created with requires_grad=True and nn.Parameter).
So since you use an nn.Module, you can do:
for p in self.model.parameters():
print(p.grad)
Otherwise, you can use autograd.grad to get a list… |
maaft | import torch
import torch.nn as nn
class BinaryTverskyLossV2(nn.Module):
def __init__(self, alpha=0.3, beta=0.7):
super(BinaryTverskyLossV2, self).__init__()
self.alpha = alpha
self.beta = beta
self.epsilon = 1e-6
s = self.beta + self.alpha
def forward(self, output, tar... | albanD | This is because the gradients wrt P_NG and NP_G are not 0. And these are computed in a differentiable manner wrt output. So you get some gradients for your output. |
MahdiNazemi | I am trying to understand the impact of.detach()on gradients and have set up an example as follows:import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.features = nn.Sequential(
nn.Linear(784, 100),
nn.ReLU(in... | albanD | The idea is that the gradient of 2*x is 2. So whatever is the value of x during the forward, it does not change the value of the gradient.
On the other hand, for x**2, the gradient is 2*x and so depending on the value x used in the forward, the gradient will change. |
sait | consider following code will this part of computation graph correctly and gradients are computed correctly.I mean can distributions be part of graphimport torchimport torch.distributions.normal as tdndist = tdn.Normal(mean,std)#assumenetwork predicts mean,stdloss = -1 * dist.log_prob(y) | albanD | Hi,
I think the log_prob is differentiable for Normal yes. You can check that by verifying that if mean or std has requires_grad=True, then dist.log_prob(y).requires_grad == True.
In general, the output requires grad, that means that the function is differentiable using the autograd. |
sh8 | Is possible to calculate the second-order derivative of a custom CUDA function?When I try to calculate it with a twice backward technique, I got the error as follows.RuntimeError: One of the differentiated Tensors appears to not have been used in the graph. Set allow_unused=True if this is the desired behavior.I guess ... | albanD | Hi,
How do you define your custom CUDA function?If you use autograd.Function in python to create new autograd Functions, you need to make sure that your backward can be auto-diffed. If it cannot, then your backward should call the apply of another Function that corresponds to your backward and d… |
ra_schoonhoven | Hello,I have been working withnn.utils.pruneand it seems to me that you cannot currently train those networks after pruning right? We setforward_pre_hookswhich means that the forward pass is properly pruned but I do not see anywhere how it is made sure that backprop works. Is it true that this is not implemented? Would... | albanD | Hi,
IIRC there is no need for backward hook as the pruning is done in a differentiable manner during the forward and so the autograd will give the right gradients. |
deyan | I’m working on some cuda extension for pytorch. When I received the grad_output, printing it yields correct values.std::cout << upstreamGrad << std::endl;
output
1 1 1 1 1 1
[ CUDAFloatType{1,6} ]However, accessing it with a pointer returns wrong values.std::vector<float> tmp(6);
cudaMemcpy(tmp.data(), upstreamGrad.d... | albanD | You are not checking the storage_offset and stride informations.
Given that the first value is correct but not the other one, I would guess that this is a non-contiguous Tensor and you should use the stride to read it properly.
Doing upstreamGrad.contiguous().data_ptr() should give you the right r… |
oneil512 | When you call item(), the number is no longer a tensor, does this necessarily mean that it can no longer live on the gpu? The docs for .item() don’t say anything about the data moving, however, the docs for .tolist(), which is the same as .item() except for multiple items, says the data is moved to cpu first ‘if necess... | albanD | Hi,
Yes .item() moves the data to CPU. It converts the value into a plain python number. And plain python number can only live on the CPU. |
Abdelpakey | Hi, I’m just wondering is torch.autograd.Variable replaced by torch.tensor (…, Requires_grad= True)?and why when I use this codet = torch.from_numpy(matrix_np).clone()matrix_torch =torch.tensor(t, requires_grad=True)it throws this errormatrix_torch =torch.tensor(t.clone(), requires_grad=True)main:1: UserWarning: To co... | albanD | No you don’t really need the clone.
Note that when you do t = torch.from_numpy(matrix_np) then t and matrix_np actually share memory. So modifying matrix_np inplace would modify t as well. So you might want to actually clone to avoid any issue. |
maaft | I need to measure the GPU memory consumption of my model and therefore have to wait until CUDNN’s benchmark has finished.Is there any way to detect this easily (like cudnn.benchmark_finished == True or something similar) ?I plotted the GPU Memory consumption over time with benchmarking enabled (orange) and disabled (bl... | albanD | Hi,
The benchmark will happen every time you call a convolution with inputs of different size.
So it never really “finishes” as if you try to do a convolution with new shape, it will benchmark that new shape to find the best algorithm.
Note that for a given shape, the benchmark will happen during… |
Carolmeir | I am trying to run in CPU. This is the code I have changed. Still I am getting the error. Please let me know how to correct this code.Error:Traceback (most recent call last):File “finetune.py”, line 249, inmain()File “finetune.py”, line 90, in maincheckpoint = torch.load(args.pretrained)File “/home/kbdp5524/anaconda3/l... | albanD | This error comes from this line (92): checkpoint = torch.load(args.pretrained) which is missing the map_location argument |
ironmanaudi_leon | After installing the pytorch, i found that i could not run the code with GPU.I’ve already got my CUDA installed which is 10.0.130, and the GPU driver is functioning, but no cuDNN. The server is DGX station and the version of pytotrch is 1.4.0. | albanD | Interesting.
Can you run the cuda samples properly? It seems like the segfault comes from inside the cuda library itself… |
Kataera | Hi all,I’m relatively new to PyTorch and have been having an issue with performing back-propagation that I just don’t know how to solve.First of all, my code for calculating the loss and then performing back-propagation:def discriminator_loss(self, real_samples, fake_samples):
criterion = BCEWithLogitsLoss()
... | albanD | Hi,
Are you using a custom autograd.Function ? This error is because you try to use a custom autograd Function without implementing the backward. |
hadaev8 | Do enumerating do something besdies i var? | albanD | Do you mean i is not used?
No enumerate does not do anything special, but for logging purposes, it is often convenient to have this index of where you are in the epoch. |
kaiseryet | Hey guys, so I am trying to create a PyTorch type of list for a few tensors of different sizes but same dimensions; e.g.,A = torch.randn(3,3)
B = torch.randn(5,5)So I need to create a PyTorch type object like[A, B], for the purpose of vectorized calculation (matrix multiplication, matrix inverse, …) happened later on (... | albanD | Hi,
What you would want here is a NestedTensor. This is work in progress at the moment. You can follow the current status on this issue:https://github.com/pytorch/pytorch/issues/25032 |
11158 | In much older library numpy method that copy ndarray is called copy. Why in torch the same method is called clone? Are there any specific reasons? | albanD | Hi,
I think this is mostly for historical reasons in particular copy (now copy_) was used a long time ago to copy into a tensor while clone is used to create an identical clone of a given Tensor. |
kaiseryet | Hey guys,So I am just wondering whether there is an existing function to find the Kronecker product of two matrices? Here is a Chinese article on that:https://blog.csdn.net/P_LarT/article/details/101066757in which they usedeinsumto achieve this. Though direct function would be much faster as tbh I don’t thinkeinsumis e... | albanD | Hi,
The article you link has a link to this forum. In particular this discussionKronecker Productthat seem to contain the answer you seek. |
isaac1644 | As written in topic, How can I choose part of output of convolution layer into another network? e.g. I defined a encoder with convolution layers and it generates a 100D output. What should I do for separating it into two part and only extract its first half 50D data as input of other structure? | albanD | Hi,
You can use normal indexing to get a subset of the output and then use it. I usually use.narrow()for that. |
kekmodel | Let’s assume the following situation.logits = model(inputs)
logits_x = logits[:batch_size]
logits_u_w, logits_u_s = logits[batch_size:].chunk(2)
del logits
e.g.1
pseudo_label = torch.softmax(logits_u_w, dim=-1).detach()
e.g.2
pseudo_label = torch.softmax(logits_u_w.detach(), dim=-1)Q. I want the operation between “log... | albanD | The two will actually give you the same result if you write them this way.
I would recommend the 2nd one like@tuxbecause in the first one, you first create the graph for the softmax then discard it when you detach. In the second one, you just never create that part of the graph.
But the differen… |
alchemi5t | Hi there,I am trying to convert a pytorch model to onnx and use tensorrt to optimize it. I can convert it to onnx and i have generated a trt engine but the output is completely useless. The onnx engine creation is what i suspect is the issue here. I do have a lot of tracerwarning of which most are of this sort:TracerWa... | albanD | I mean the function without the _. Which won’t modify the input inplace but return a new Tensor containing the result. See the dochere. |
Rafay_Khan | I’m pretty new to PyTorch so, please excuse me if this question is too remedial. I have the following code for inference of my trained model which takes an image, does some pre-processing on it, converts to a tensor and finally performs a forward pass through the network.img = np.array(Image.open(img_path))
or... | albanD | Hi,
The issue comes from the [None] I think. You change this line to first convert to a Tensor then .unsqueeze(0) to get the exact same result:
img_inp = torch.tensor(prepare_img(img).transpose(2, 0, 1)).float().unsqueeze(0) |
Sanjayvarma11 | Hello guys, I am new to PyTorch.I am going through an example where I found this code# Backprop to compute gradients of w1 and w2 with respect to loss
grad_y_pred = 2*(y_pred - y)
grad_w2 = h_relu.t().mm(grad_y_pred)
grad_h_relu = grad_y_pred.mm(w2.t())
grad_h = grad_h_relu.clone()
grad_h[h < 0] = 0... | albanD | Hi,
This code is a bit out of context. Where did you get it from?
So I am going to guess that you try to do the backward pass by hand for a network whole loss function is loss = ||y_pred - y||^2 with weights w1 and w2. And y_pred = w2 * h_relu and h_relu = relu(w1 * x).
If this is true, then the … |
G.M | I have this autograd function.class raw(autograd.Function):
@staticmethod
def forward(ctx, inp):
ctx.a = inp * inp + 1
print(inp.requires_grad, ctx.a.requires_grad)
return inp * ctx.a.pow(-0.5)
@staticmethod
def backward(ctx, grad_output):
return grad_output * ctx.a.pow(... | albanD | Hi,
The requires_grad field is used to track operation and Tensors that require gradients. Here since you are inside a autograd.Function. You do no use the autograd anymore to get gradients, you code the backward yourself. So the Tensors that are created in during the forward pass do not require gr… |
gbaasch | Hello. This is my first post on the PyTorch forum so forgive me if there is not enough detail.I am trying to use register_backward_hook to get the gradient from a 1d convolutional layer. I found that the gradient shape is not what I expected and it is inconsistent with Conv2d.For Conv2d the shape of the gradient for in... | albanD | Hi,
As mentionned in the doc, the backward hooks on nn.Module are not working properly at the momentHopefully we’ll manage to fix them soon.
You should ignore these results. If you want proper hooking, you should use hooks on Tensors directly as l.register_hook(you_fn) for example. |
ElleryL | consider I have a matrixx = torch.randn(2,5)I have a binary matrixb = torch.Tensor([[1,0,1,0,1],[0,1,1,1,0]])# assume thatb.sum(-1)are equal acrossdim=0; namely, each row has same number of one’sI’m wondering if there is an efficient way such that it returns a matrix with shapeNxDwhereNis number of rows inbandDis numb... | albanD | Hi,
If you are sure they contain the same number of non zero elements D, you can do x[b].view(D, N). If you want an [N, D] result, you can transpose that with .t(). |
veeresh_d | Hi all,just wondering, aretorch.stack, torch.catinplace operations? If we use the same variable name on both sides of the statement.example .torch_list = [torch.randn(2, 2), torch.randn(2, 2), torch.randn(2, 2)] torch_list = torch.stack(torch_list, dim=0)print(torch_list.shape) # torch.Size([3, 2, 2])Thanks in advanc... | albanD | Hi,
They are not inplace as we do not support a Tensor backed by multiple small memory storage.
When you do some_name = in python. It just assigns the returned object to that name. |
pinocchio | I’ve seen:for epoch in range(nb_epochs):
for i, data in enumerate(trainloader, 0):
# unpack data
inputs, labels = databut I’ve never understood why the enumerate function needs the0as an argument. Does anyone know why? | albanD | You can check the python doc for the specification of the enumerate() function:https://docs.python.org/3/library/functions.html#enumerate |
pinocchio | I saw that.clone()was part of the computation graph and thought it was really weird. Why is that?I wanted to knowwhat it even meant to take derivatives with respect to such an operation (I thought it shouldn’t be defined)Why is it part of the computation graph if one can’t take derivatives wrt to cloneLook its in the g... | albanD | Hi,
The clone function is like an identity. f(x) = x, So you can take its derivative.
You were expecting something else? |
Mikele | Hello,how would one effectively mask the parameters of a module without losing neither their link to the optimizer?More in detail:Approach 1:for weights in model.parameters():
backups.append(weights.clone().detach().data)
mask = sample_mask(some_arguments...) # this comes from weights of a wrapper module that ... | albanD | So here you have two parameters in your module:
original weights of the module
mask_params that are used to compute the mask
I would modify the module to have all the right Parameters and recompute weight for each forward.
# Example for a Linear (handle bias the same way if you want them)
mod = … |
jnx | Hello Guys,I need your help.I only have one GPU installed in my computer. I am currently working on architecture selection hence I test different architectures (e.g. 10 architectures) with one run. I do it one by one.for i in Architectures:
model = network(architecture = i)
....
for mini_epoch in Total_ep... | albanD | Hi,
Two things:
We have a custom allocator, so even when the memory is released, you won’t see it available on nvidia-smi but you will be able to use it in pytorch.
The memory is realeased only when you don’t reference it anymore. You might want to wrap the content of your inner loop in a functio… |
jwillette | def maml_simulation() -> None:
x_inner = torch.tensor(2.0, requires_grad=True)
x_outer = torch.tensor(3.0, requires_grad=True)
theta_outer = torch.randn(1, requires_grad=True)
print(f"before training: x inner: {x_inner} theta outer: {theta_outer}")
loss_func = lambda x: (x - 10) ** 2
loss = to... | albanD | I’m not sure what is the purpose of theta_two in your code above, why not use theta directly (turns out after more investigation below, this was the root of the problem, see the rest of the answer)?
Also if I read correctly, loss_one = (theta * xi - 10)**2.
So grad = 2 * xi * (theta * xi - 10).
S… |
pozimek | Hey,My training is crashing due to a ‘CUDA out of memory’ error, except that it happens at the 8th epoch. In my understanding unless there is a memory leak or unless I am writing data to the GPU that is not deleted every epoch the CUDA memory usage should not increase as training progresses, and if the model is too lar... | albanD | Hi
Could faulty garbage collection be responsible?
Python is refcounted. So no issue hereThe usual reason this happens is:
You accumulate your loss (for later printing) in a differentiable manner like all_loss += loss. This means that all_loss keeps all the history of all the previous itera… |
f3ba | I am running my training on a server which has 56 CPUs cores. When I train a network PyTorch begins using almost all of them.I want to limit PyTorch usage to only 8 cores (say). How can I do this? | albanD | Hi,
You can usetorch.set_num_threads()to do this. |
pinocchio | I am trying to extract gradients and later use them as data (so have them non-trainable). For that I am having to call.backward()twice. Doing that seems to mess up with my code as noted by mother question (What does doing .backward twice do?). However, for the code to work how I intend it (without the issue of calling ... | albanD | For " the gradient information w.grad is treated as a number if the computation graph and not as a variable that one can differentiate" you want to use w.grad.detach() for further computations to achieve that.
.data will work but can be misleading as it does not allow the autograd to perform all … |
mlearner | Hello,in theforwardfunction of a neural network I would like, in the propagation between two layers, to insert a polar coordinate conversion (the output of the first layer is intended to be a set of 2D Cartesian coordinates).How can I achieve that? Can I put it directly in the forward function or is it needed to create... | albanD | Hi,
You can make it into a 3D Tensor of size [batch, 21, 2] and use the same function as above. Since we index with -1 (last dimension), it does not really matter how many there are before.
Also if the input is always of size 42, you can do .view(-1, 21, 2). |
f3ba | I need to define a classModelthat contains my model parameters, but for which it makes no sense to define aforwardmethod. Instead, I’ll define other modules which can read the parameters fromModeland which then define theirforwardmethods.Is it natural thatModelinherits fromModulein this case (even though it doesn’t imp... | albanD | Hi,
I think you can yes. Note that you can also make this module a Submodule of your other modules that do the forward. |
two_Two | Hi,guysI would like to keep my attention to the update of pytorch,and I have few question to ask:Is there any way to know when pytorch would update and the content of it except browsing the official website once in a while?If I see something like the link below:Update weight initialisations to current best practicesHow... | albanD | Hi,
The version you get with pip depends on how you install it there. Following the instructions on the website, you can either install release versions like 1.4 or nightly which we build every night based on the current master branch on github.
If you build from source, you can either build from… |
jwillette | I have been searching around and I cannot find any easy answers to how to dynamically calculate the output size of a set of convolutional layers. I see the formulahereand most of the terms are obvious except for the dilation term.Withstride=1,kernel=3I am using omniglotinputs: (batch, 1, 28, 28)outputs: (batch, 64, 1, ... | albanD | Hi,
This is usually dilation=1 for most models. Where did you get these numbers from?
Alsothisblogpost has a nice visualization of what this parameter is doing. |
Hong_Cheng | I have a model that predict four similar category numerical data (target values).I use a CNN to extract feature for each category target value, before FC layers, I also add two values to the flattened extracted feature maps.This works in Keras. I rewrite my codes with Pytorch. But the result of prediction for each cate... | albanD | .eval() changes the behavior of some modules. For example, Batchnorm uses the saved statistics instead of the current batch’s ones, dropout becomes an identity, etc |
oasjd7 | # example 1)
list_ = []
for i in range(3):
list_.append(i)
-----------------------------------------
# example 2)
x = torch.empty(2,3)
for i in range(3):
y = torch.FloatTensor([[1,2,3],[4,5,6]])
x = torch.cat([x, y], dim=0)
print(x)
> tensor([[-1.9967e-31, 4.5713e-41, 9.6263e-38],
[ 0.0000e+00, -1.6... | albanD | One trick is to .append() to a list and then do a single .cat() at the end with the whole list.
The other is to create a custom Dataset that takes this list as input and give that to your Dataloader. Note that doing the .cat() and using a TensorDataset will be faster during training ! |
skyunyoo | Hello.I have a question about GPU allocate and cache.I have seen GPU allocation and cache using code like below (Below is nothing loaded on the GPU)device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('Using device:', device)
print()
if device.type == 'cuda':
print(torch.cuda.get_device_name... | albanD | CPU usage of 100% (that means a single core used), is expected. The CPU has the task of running the python code + queue up work for the GPU. If the model is small, this is expected that one thread is fully used on the CPU. |
G.M | I’m trying to implementsechfunction, but Pytorch doesn’t have an internal implmentation for it astanhdoes. I came up with two solutions:import torch as tc
import mathtanh_y = tc.tanh(input)
sech_y = tc.sqrt(1-a.pow(2))
#if it's in autograd.Function, I can then use the tanh_y and sech_y for backward.a, b = tc.pow(math.... | albanD | Hi,
Given all the formulas I found online, out = 1/torch.cosh(z) should be the best (less total number of operations). |
f3ba | I am trying to sum a tensor over its firstnaxes, wherenis a parameter I don’t know in advance. Why something like the following doesn’t work?v = torch.randn(100, 20, 10)
torch.sum(v, range(2)) # I would write range(n) here.This gives an error:TypeError: sum() received an invalid combination of arguments - got (Tensor,... | albanD | Hi,
In general Tensors with a very large number of dimensions are not as efficient. Cuda will limit you to 25 dimensions if I recall correctly. And on cpu, you might hit slowdowns.
But to answer your question, sum does expect a list/tuple and does not accept a generator (what range returns). |
carlo_david | what is the purpose of creating a custom dataset class if we can use ImageFolder from torchvision package | albanD | Hi,
For people that do not work with images for example.
Or for people that do but do not store images on the disk in folders the same way ImageFolder assumes it should be. |
Huimin_ZENG | Hi! I was trying to do backward on the first derivative (Jacobian). I observed that the usage of memory continues to grow ify.backward(retain_graph=True,create__graph=True).I have read this posthttps://discuss.pytorch.org/t/how-to-free-the-graph-after-create-graph-true/58476/4, where it is said the graph will be detete... | albanD | Hi,
The conclusion from the issue you linked is that this is expected behavior mostly (or something we should forbid people from doing).
torch.autograd.grad works for vectors as well. What is the issue you encounter when trying to use it? |
supervan | I have two tensors A and B. A is a float tensor with shape (batch size, hidden dim). B is a Long tensor with shape (batch size, data len). What I want is somewhat like A[:, B], a float tensor still with shape (batch size, data len), the elements are certain indices from A which depends on B.An example would be A=[[5, 2... | albanD | If you add extra dimensions, you can simply expand B in these dimensions:
A.gather(1, B.unsqueeze(-1).expand(batch, data_len, data_dim) |
ShadowVolumeGuy | Hi all,I currently try to make prediction using this pretrained networkStereoNet.After some effort (there must be some push errors on this repositery), I manage to load the pre-trained network. And unfortunately, a nice message warns me that my GPU is too low in RAM. So I removed everything that made an explicit call t... | albanD | Hi,
The cuda state on the GPU is quite big. Taking few hundreds of MB.
To avoid loading on the GPU a model saved on the gpu, you can do: torch.load('checkpoint_pretrain_secneflow.pth', map_location=torch.device('cpu')). |
cruzas | Hello everyone!This is my first post here.I have been trying to initialize bias data to a specific vector but have not found a way to do so without creating a leaf variable. I am coding in C++.In the layer “affine2”, I can initialize the entries as follows:affine2->bias[0] = 0.1;
affine2->bias[1] = 0.2;
affine2->bias[2... | albanD | Hi,
You want to make changes that are not tracked by the autograd here.
So you should wrap these into a NoGradGuard. |
ludwigwinkler | Hi there,I’m just curious how far along the amazing devs are on the PyTorch 1.4 release.I’m really excited about the named tensor capabilities.Is there a rough road map like March/April/May 2020?Best and thanks for this amazing library! | albanD | The branch has been cut, binaries are being finalized. So, in a few days |
kailing_ye | For example, I have the category feature named fruit that contains apple, banana, peach, pear. Should I do one hot encoding before sending to the Embedding layer? | albanD | Hi,
You usually associate an index to each word. The Embedding layer takes the indices as input, not one-hot encoding of these indices. |
nzinc | This code show training process for one batch (I missed all stuff before, cause its unnecessary)for j in range(critic_policy(epoch)):
output = netC(train_full)
generator_loss = torch.mean(cramer_critic(train_full, generated_full_2) * w_full * w_x_2 -
cramer_critic(generated_full_1, gene... | albanD | How are these loop nested? Like this:
for i, data in enumerate(all_dataloader):
# Generate all train_full, generated_y etc
for j in range(critic_policy(epoch)):
# The code from your first post
If so, what most likely happens is that netG has some parameters that require gradients. So gener… |
alanzhai219 | How to print at::tensor in C++ during debugging a custom op?1.code line?2.gdb? | albanD | You can use std::cout << your_tensor << std::endl; to print the content of a Tensor. |
Kevin96 | Hi,When I computed the gradient of a sparse tensor on GPU, I got out of memory issue.I need a tensor of size[1, 3, 224 * 224, 224 * 224]which only has 1 * 3 * 224 * 224 * 25 nonzero entries. So I store it in sparse_coo format.I take the summation over the last dim, then I get a tensor of size[1, 3, 224 * 224]:b = torch... | albanD | Hi,
I’m afraid that the backward of the to_dense() does not create a sparse Tensor. And so it tried to create a full size TensorThe support for sparse Tensors is quite limited so we don’t usually create them in the backward to reduce the number of errors like “XXX op is not implemented for spars… |
kai-tub | Hi,first of all thanks to everyone working on this awesome library!I’ve started looking into pytorch for a couple of months now, but I’ve reached a point where I cannot explain a specific behavior. I am sorry for not being able to get a smaller minimal example up but in the smaller versions the problems do not appear:"... | albanD | Setting np.random.seed(123) should take care of always producing the same sample
Unless later in the network, you generate more random numbers. Then depending if you run these layers, you will get different random inputs.
TODO: Explain why it makes a difference when the following
Maybe the la… |
nzinc | Code below:class Critic(nn.Module):
def __init__(self):
super(Critic, self).__init__()
self.main = nn.Sequential(
nn.Linear((data_train.shape[1] - 1), 128).to(device),
nn.ReLU(),
nn.Linear(128, 128),
nn.ReLU(),
nn.Linear(128, 128),
... | albanD | Hi,
The .to() operation on Tensor is not inplace, so you need to replace train_full.to(device) by train_full = train_full.to(device). |
razvanc92 | I’m having a technical question. Let’s consider the following example where I want to select for only the top 10 values from the last dimension. The example works as intended but I am worried that I might break the computation graph since I’m creating a new tensor in line 2. Can anyone confirm if this is the right appr... | albanD | Hi,
You can use this is a toy example to see which gradient are propagated back to support with something like:
support = torch.rand(20, requires_grad=True)
indices = # Whatever they should be
topk, indices = torch.topk(support, 10)
out = torch.zeros([B, N, N], device=self.device).scatter_(2, ind… |
kala855 | Hi everyone,I am trying to figure out where the weight update process is done when you train a GRU model. I am using Adam optimizer, however I am new in PyTorch. I need this basically because I need to find the C++ code used to do the update in order to change the precision used while the update is done. I did this bef... | albanD | Ho ok.
Then I would say:
Find out which function is used in your case (that will depend on how you installed pytorch). And if you can, change this one the same way you changed the caffe implementation.
Use thecpp_extensionsto create a custom cpp function that does what you want, and modify adam… |
111215 | I now want to use “refinedet” for target detection, loading my own dataset, but the following problem occurred when using vgg16, the backbone network.image1269×253 38.5 KB | albanD | This happens because refinedet_net is None is your code? You want to check why this happens? Did you forgot a return statement maybe? |
chunchun | I want to konw how can I get the loss=0.8133could you please tell me the details such as which one multiply which one to get this result?Thanks. | albanD | According to the formula inthe doc:
sample 0:
- x[1] + log ( sum(exp(x)) ) = 0.3133 + log( 0.2689 + 0.7310 ) = 0.3133 - 3.831e-5 = 0.3133
sample 1:
- x[0] + log ( sum(exp(x)) ) = 1.3133 + log( 0.2689 + 0.7310 ) = 1.3133 - -3.831e-5 = 1.3133
average of the results:
(1.3133 + 0.3133)*0.5 = 0.8133 |
Tupac | I have this simple tensorflow code block, what is the equivalent in pytorch? I am stuck trying to code it. I have encountered multiple Runtime errors, due to the dimensions.This is the tensorflow code:conv1 = tf.nn.conv1d(x,f1,stride=1,padding="VALID")
conv1 = tf.nn.bias_add(conv1, b1)
conv1 = tf.nn.sigmoid(conv1)
p1 ... | albanD | The tensorflow conv1d takes as input batch x width x channel no? So your Tensorflow code is wrong? |
Huy_Ngo | As far as I understand, nn.relu() is a layer that has weights and bias whereas F.relu is just a activation function. Doesn’t that make nn.relu() a bit more computationally heavy than F.relu because optimizer has to update the redundant weights and bias for that layer too? | albanD | Hi,
nn.ReLU() is a layer, but it has not weights or bias.
The two are exactly the same.
The version as a nn.Module is convenient to be able to add it directly into a nn.Sequential() construct for example.
The functional version is useful when you write a custom forward and you just want to apply… |
k_k | Hello, i have implemented a custom layer for pytorch and want to speed it up by using CUDA.I was following the tutorial given herehttps://pytorch.org/tutorials/advanced/cpp_extension.html.But it is not mentioned how to save tensors in the forward pass ctx.save_for_backward in CUDA.I would really appreciate if someone c... | albanD | In the tutorial you link, the cpp function is then used inside an autograd.Function. So you can save them in the autograd.Function that wraps your cpp implementation as you do in your current implementation. |
HuangChuan | In the following example, the variablehiddenis changed every time step, is this assignmentin place operation? If it is, does callingbackward()yield correct gradient?Thank you!def train(category_tensor, line_tensor):
rnn.zero_grad()
hidden = rnn.init_hidden()
for i in range(line_tensor.size()[0]):
... | albanD | It depends.
If they are needed to compute gradients, yes the autograd will keep them in memory.
If they are not needed to compute gradients, they will be freed when you associate a new Tensor to the python variable. |
Ren_yf | I found there seems to be one additionalparameterin thetorch.nn.Modelfor convnet as shown in the example below. And the shape the additionalparameterseems like [in_channel, out_channl]. Can anyone help explain this?Thanks in advance!conv1 = torch.nn.Conv2d(1, 2, 1)
print("conv1:", conv1.weight)
class myModel(torch.nn.... | albanD | Hi,
The second parameter is the bias. You can access it with conv1.bias.
It has the same size as the number of output channels (it is createdhere).
You can pass bias=False to the conv2d constructor if you don’t want it. |
phantom90 | Hi, I’m trying to get a hessian vector product of a network.I try to follow the hvp implemented in Tensorflow. But the following codes don’t work as expected. Does anybody know how to solve it?Thank you in advance.input = torch.randn(1, 3, 32, 32) # Batch_size is 1.
out = net(input).sum() # net is a neural network
p... | albanD | Hi,
I think the problem is that you do an element-wise product when you do g * v instead of a dot product.
Does elem_prod = sum([(g * v).sum() for g, v in zip(grads, list_of_v)]) compute what you want? |
helloWorld | Hey,I’m trying to implement the optimization algorithems by myself and to compare them . However, not sure why, but the backwards flow doesnt update the gradients and they left as None values.My optimizer :class MyOptimizer:
def __init__(self, parameters,lr=0.001, momentum=0.9):
self.momentum = momentum
self... | albanD | So the problem is that layer_dict['params'] is not a list, but just a Tensor.
So when you do for p in layer_data['params']:, you actually slice the Tensor along the 0th dimension. Since this returns new Tensors, the .grad field is not set for them.
You can either do layer_dict['params']=[layer_par… |
Upgrade_Yourself | Must freezing/unfreezing model be done necessarily before mounting it on gpu or can it be done whenever? | albanD | Moving to the gpu is recommended to be done first.
For example, it should be done before passing the parameters to the optimizer as well. |
el_samou_samou | Hi,I am implementing custom autograd functions on Sparse Tensors. As I use COO format to encode sparse tensors, the input of my auto grad functions is a pair of tensors, one containing the indices of type torch(.cuda).IntTensor and one containing the values of type torch(.cuda).FloatTensor.The indice tensor do not have... | albanD | Hi,
The wasn’t very clear about this, but the latest versionhereshould be better. In particular, you have to mark non-differentiable outputs explicitly in your custom Functions.
In you case, you should add at the end of test_discrete_grad_1's forward function:
ctx.mark_non_differentiable(new_in… |
jinujanu | Hi, I’m trying to define an object inside the autograd.Function, but when i’m calling the object inside the backward, it’s saying the object is not defined…e.g.class PermutationLayer(autograd.Function):
@staticmethod
def forward(ctx, x, x1, x2):
ctx.save_for_backward(x, x1, x2)
@staticmethod
... | albanD | Hi,
You want to double check how python classes work.
But because we use static method, we don’t create instances of this class.
To use this function, you can either define it outside of the class. Or as another static method and call it with PermutationLayer. want_to_add(). |
Alex_Luya | I have a forward method looks like this:def forward(self,x)
x=self.out_1(x)
x=self.out_2(x)
x=self.out_3(x)
return xwhen debugging,navidia-smi tells that each line will consume x MBs gpu memory,and these memory won’t get freed went out of forward method,then training crashed quickly,and I am sure th... | albanD | Hi,
Yes a lot of memory is kept until the backward call because its content is needed for the backward call computations.
You can use thecheckpointingtool to trade compute for memory: this will slow down the backward but reduce the memory usage. |
Alex_Luya | I found a line of code:out_a, out_p, out_n = model(data_a), model(data_p), model(data_n)in:https://github.com/liorshk/facenet_pytorch/blob/master/train_triplet.pyas you can see that the “forward()” is invoked multiple times before “backward()”,question are:1,Will next invoking override previous computation graph?2,In m... | albanD | The computational graph is not linked to the model, a new one est created each time you perform a forward pass. So no it is not overriden and yes the memory usage increase as you create 3 computational graphs (each containing its own intermediary results needed for the backward pass). |
Umair_Javaid | I have a custom module, which I am adding after VGG-16 feature moduleclass Last_layers_mod(nn.Module):
def __init__(self):
super(Last_layers_mod, self).__init__()
self.gap = nn.AdaptiveAvgPool2d((1,1))
def forward(self, x):
if self.train:
x.register_hook(lambda x: print("gap reg_hook: ", x.size... | albanD | You can replace if self.train: by if self.train and x.requires_grad: |
Cedric_Gullentops | I am trying to copy a modified state_dict from a model that was pruned (e.g. reducing the 0 dimension of one of the tensors by 1). The models have the same keys, the only difference is the dimensions of the tensors. I made a wrapper class to handle pruned networks as seen below:class PrunedNetwork():
def __init__(s... | albanD | Editing the dictionnary won’t help. As the dictionnary is created when you call .state_dict().
If you want to change them, the simplest solution I can think of right now is going to go through the network and for each parameter:
# mod is the current module that has a parameter weight that needs
# … |
Santosh_Manicka | Is it possible to compute directional derivatives using Pytorch?Here are some examples of the math:http://tutorial.math.lamar.edu/Classes/CalcIII/DirectionalDeriv.aspx | albanD | If I remember correctly, directional derivatives are Jacobian vector products.
So you can compute them with the trick shown inthis gist. |
FenryrMKIII | Hello,I am doing a homemade project in order to better learn the details of PyTorch and be able to write my own networks, training routine, …As part of this project, I am creating a replica of LeNet-5 neural network.The code for custom-made layer looks like this :from collections import Sequence
import torch.nn as nn
i... | albanD | Hi,
When working with nn.Module, we only check the child nn.Modules when looking for parameters.
In particular, if you store your child modules in python dictionaries or lists, they won’t be found. You can use builtin utils like ModuleDict or ModuleList (seedoc) to store collections of Modules an… |
azeeshan | The forward function of my torch.nn module initially looked like this:def forward(self, a, b, c):
#blah blah blah
inds = (c<0)
c_aug = c
c_aug[inds] = a.shape[0]
#more blah blah blahThis was giving me an error:RuntimeError: one of the variables needed for gradient computation has been modified by an inpl... | albanD | Hi,
Yes this is the correct workaround. You just want to make sure that you don’t modify the c you get as input inplace. So you clone it before changing it inplace.
Note that we usually do c_aug = c.clone() instead of using torch.clone. |
azeeshan | I am building a torch.nn.module for graph convolutional neural networks. For concreteness, let us imagine the input is a configuration of points with (x,y) coordinates and one has to predict the output (scalar) of the configuration. I want an elegant way to handle the different case (edge case) of a configuration with ... | albanD | Hi,
To handle such things I usually do the following pseudo code:
cond = bath_data.is_empty? (gives a Tensor of size (n_batch,) containing 0/1)
out_true = your_non_empty_code(batch_data) # Compute everything as if non-empty
out_false = self.empty_value.expand_as(out_true) # Your param for the e… |
Deepak | Code:from torch.nn import Linearmodel = Linear(in_features = 1, out_features = 1)y = model(x) # calling an instance of class LinearAlthough, ‘Linear’ class inherits ‘Module’ class, which has ‘__ call__()’ defined in it. I could not catch it from there. Kindly help.As far as I know; In python, to call an inst... | albanD | If a function is not redefined in the class itself, the one from its parent is used. So in this case, the __call__() method from the Module class will be used. |
Nagaraj_S_Murthy | What does “torch.cuda.FloatTensor at version X” actually mean?? How to change the version to a different value? | albanD | These versions track how many times a Tensor has been modified inplace. The version increase every time you modify it.
You cannot change the version manually. If you see error with wrong version, you need to remove inplace operations to avoid the version to be bumped. |
sh0416 | Hello,I am struggling with implementing reversible residual network.When I implement this, the computational graph is consisted of some nodes, and this nodes are constructed using Tensor.The strength of reversible network is that it can construct earlier activation with current activation. However, the computational gr... | albanD | Hi,
If you don’t want any Tensor to be saved, just don’t save anything in the ctx and no Tensor will be saved for that Function.
Every Tensor is deleted as soon as it is not referenced by anything. So the input data will be deleted as soon as you don’t use it in your forward function. |
jacek | Hey guys,is therenp.column_stackequivalent in PyTorch? Or is a easy way to replicate its functionality by usingstack,catetc. Or should I just stick to np.column_stack (I don’t need to preserve gradient at the moment)Thanks! | albanD | It is the same as stack(your_tensors, dim=0). |
MikeHsu | He guys, I am using U-net and RNN.I found my GPU memory is increasing after each step instead of remaining stable.After about 40 steps, run out of memory error occurs.Seems there is something stock in GPU memory and cause leak.I am using RTX 2080 ti.My code is here:https://github.com/vagr8/R_Unet/blob/master/R_Unet.pyT... | albanD | This most likely happen because you either store things in a list that ever grows at each iteration or if you hold onto the computational graph of the whole history.
You should be able to check the first one by printing list size in your code (in particular, buffer)
For the second one, you want to… |
EricSpeidel | In trying to understand what is really going on when switching from .train() to .eval() mode, I’ve been experimenting with replacing it with the following loop within my model:for module in self.children():
module.training = FalseIs thisexactlythe same as calling model.eval() from outside though? A few test... | albanD | You would need to call this recursively on all the children as well if you want this to work for models with nested Modules.
You can check the actual implementationhereif you’re curious. |
Jean-Eric_Campagne | Hi!,I face a problem using pytorch 1.3.0 on Cuda V100. Here the code originating fromgithub.comcszn/DnCNN/blob/master/TrainingCodes/dncnn_pytorch/main_train.py# -*- coding: utf-8 -*-
# PyTorch 0.4.1, https://pytorch.org/docs/stable/index.html
# =========================================================================... | albanD | Interesting. So I guess the pip-version linked to a wrong mkl version. Hence causing the issue !
In general, I would advise to use the conda install of pytorch if you’re in a conda environment. That will make sure you don’t have such issues !
Happy this is fixed. |
AG1991 | Hello everyone,I am trying to build a custom convolution layer (conv2d) where the element-wise multiplication will be later replaced with an approximate multiplication.(I know it will get very slow but it is fine I will deal with this problem later.)I have managed to re-build the forward part and it works fine but the ... | albanD | Hi,
The problem is that the signature of your forward: forward(ctx, x, height, width, windows, out_channels, weight, bias, n_channels): does not match the order you return the gradients in the backward: return grad_input, grad_weight, grad_bias, None, None, None, None, None. I guess it should be re… |
skyline | I have read the recent pytorch tutorial book.But I want to know more about data type in pytorch, how the computational graph work,how to define function and new module in pytorch. Is there some easy to digest resources for these topics with good example? | albanD | You can find in the doc some notes aboutthe autograd, how toextend function and modulesandtensors. |
Arvind_Subramaniam | I am multiplying a mask to my weight matrix during the forward prop to sparsify my network. However, during backprop, I want the gradient updates to be zero for the masked weights (mask[i] = 0).Is there any way to do that using register_hook?Here’s a toy code I have used, but am getting an error.mask = torch.tensor([0,... | albanD | Hi,
A hook has to be a callable function, not a Tensor. So the lambda is the way to go. |
VictoriaYyz | I have a network, for example input->conv1->bn1->relu->pool1. Now I have the gradient of pool1, and I want to calculate all the gradients of the network w.r.t the input, can it works: torch.autograd.backward(network, grad_tensors=pool1_gradient) ?Hope someone can give answers, thanks! | albanD | When you call .backward(), it will populate the .grad field for all the leaf Tensor (such as nn.Parameter) that were used to compute your output. |
songqsh | A tensor is called i-type if its entries are equal to the sum of index squared.I want to have a function to construct an i-type tensor with arbitrarily given shape. This can be done with numpy as follows:import numpy as np
def i_tensor(shape = [2,2,2]):
t = np.zeros(shape)
it = np.nditer(t, flags=['multi_index'... | albanD | The following should work (and be much faster as it only loops over the number of dimensions, not the whole output:
def i_tensor(shape = [2,2,2]):
ndim = len(shape)
view_shape = [1,] * ndim
res = 0.
for d in range(ndim):
dim_size = shape[d]
t = torch.arange(dim_size… |
h3li05 | Hey!I’m trying to implement a text classification model that retrieves K batches from replay memory based on nearest neighbour approach(using a specific encoding of our test document that needs to be classified as key) and first trains on this batch to adjust to adjust its weight minimising log likelihood loss. However... | albanD | Hi,
Few things:
You can replace this to be more efficient:
diff_loss.backward()
likelihood_loss.backward()
by
(diff_loss + likelihood_loss).backward()
When you do list(foo.parameters()), you get a reference to the weights. So if you change them to not require gradients, then you basically ch… |
mojzaar | Hi,I wanted to creat an architecture that gradient flow is blocked from a certain layer beckward and the former layer will not update. I don’t want freeze that part. I want to put gradient of the intended layer be zero and block the gradient flow somehow the former layer will not be updated in this path. Is there any s... | albanD | Hi,
If you know during the forward which part you want to block the gradients from, you can use .detach() on the output of this block to exclude it from the backward.
If you only know after the forward which part you want to block, you will need to add a hook to the Tensor that is the output of yo… |
Rocket | I look for full simple tutorial/example of pytorch avoid use of inner function except autograd such as…Linear.I have shown tutorials which are most works are automated as below.class Net(nn.Module):
def __init__(self):
super.__init__()
fc1 = linear(10,20)
def forward(x):
return fc1(x... | albanD | So first, you never want to use .data.
If you want to do your weight update manually, you can do:
loss.backward()
with torch.no_grad():
w1 -= learning_rate * w1.grad |
Johannes | Hi all,I have been reading up on differentiation techniques in DL frameworks. I came across the termssymbol-to-number differentiationwhich is used by Caffe andsymbol-to-symbol differentiation. The former describes the approach of setting actual numeric values to the computational graph and computing the derivative in t... | albanD | I would agree yes.
What I understand is that the original Tensorflow cannot do this because they build the graph ahead of time. So there are no "number"s available yet. |
smonsays | In an attempt to implement thelog_prob()method for anEmpiricaldistribution function, I need to match the entries of a big tensor with samples. My naive implementation is terribly slow:samples = torch.randn(10)
value = torch.randn(10000)
num_matches = torch.zeros_like(values)
for i, v in enumerate(value):
num_match... | albanD | You want to count how many samples each value is close to?
You can do
expanded_values = value.unsqueeze(1).expand(10000, 10)
expanded_samples = samples.unsqueeze(0).expand(10000, 10)
num_matches = torch.isclose(expanded_values, expanded_samples).sum(-1) |
asiltureli | I have written a function to parallelize the MSELoss function from torch.nn to speed things up for multiple loss calculations. The code is as shown below:from torch.nn import MSELoss
import torch.multiprocessing as mp
from multiprocessing import Process, Lock
import torch
def paral_MSELoss(*args): # Paralleli... | albanD | If your GPU usage is too low, that means that you give it either too small tasks or other things in your code is the slow part.
I would check which one it is and fix these.
Multiprocessing will only create smaller tasks and add overhead so most likely won’t solve your problem… |
gebrahimi | I need to save all the neuron values in each layer after the activation and gradient with respect to. I am very new to this and i know that i need to use hooks. Can someone please hint me how to do this for following network? Thanks.class LeNet_5(nn.Module):def __init__(self):
super().__init__()
self.conv1 = n... | albanD | Hi,
During the forward pass. You have access to x directly if you need the value after each activation.
If you want the gradient at this point, you can get it by doing x.register_hook(your_hook_fn). Where your_hook_fn will be called with one argument: the gradient of x. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.