user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
mathmerizing
Hello! I was trying to translate my PyTorch code into LibTorch.Using the following PyTorch code I was computing second-order derivatives of nn.modules.import torch from torch.autograd import Variable def derivative(u,x,order = 1): ones = torch.ones_like(u) deriv = torch.autograd.grad(u, x, create_graph=True, ...
tom
This sounds very fishy and I would double check.
Hiperdyne19012
Can I create a vector or array of Torch tensors with differing dimensions as long as they have the same data type? I want to use pointer arithmetic to access the tensors.
tom
After a few 4GB tensors (assuming 32 bit values), you might run out of memory, but other than that, yes, it works.
freezek
Is there any method to save computation graph in pytorch? Just like tensorflow could save graph…
tom
The typical thing is to use the JIT to trace or script your model. This is - at a very high level - somewhat similar as the computational graph in TensorFlow.
MichaelMMeskhi
Hello,How would one go to initialize a Conv layer for a regression problem? Input is not an image. I would like to test out and see what kind of feature engineering a conv layer can perform. Say my input is 290 features and output is 1 value.
tom
Well, so what nature are these 200 by 300 inputs? Are they independent or is there some notion of locality in either dimension such that a thing and the thing next to it have more relation than the thing and the thing 100 places further? Do you expect your prediction to depend on the relation betwee…
Achu_Chandran
I am a using a custom sampler class similar to the one described here :How upload sequence of image on video-classificationsuggested by@ptrblck(https://discuss.pytorch.org/u/ptrblck) to stack up images sequentially from the datasets before feeding into the network.Now I also wanted to use WeightedSampler to balance th...
tom
I don’t think there is anything wrong per se with looping over the dataset to get the class distribution. That said, if it takes a long time and you expect to run your training often, the typical thing is to make it a preprocessing step (just like e.g. the famous ImageNet mean and std for normalizat…
BuzzLord
I just tracked down an issue in my project that seems like a bug. I’m shuffling a (large) tensor by making an index tensor with torch.linspace(), randomizing it with randperm(), then using the shuffled indices to index_select() the original tensor. The index tensor argument has to be torch.long, so I make it by setti...
tom
Don’t use linspace here but use arange. linspace uaes floating point under the hood more and that isn’t a good match with largeish integers. Bestregards Thomas
Kla
Hi everyone, I’m trying to implement a resnet18 network for my dataset but I become an error: “optimizer got an empty parameter list”. May someone tell me what I have done wrong?optimizer = optim.SGD(running_programm.parameters(), lr=0.01, momentum=0.9)My network looks so:class Resnet_Speaker_Recognition(nn.Module):def...
tom
I think you’re missing a bunch of self. in the init. Best regards Thomas P.S.: If you put triple backticks ``` before and after your code, you’ll get proper formatting.
Michael_Lempart
Hi all,Iam totally new to PyTorch as Iam transitioning from keras.Iam about to translate one of my projects, where one epoch is either as long as the number of samples devided by the batch size or as long as the number of iterations defined by a user.Now Iam wondering how I could accomplish the same thing in PyTorch?I ...
tom
The easiest way would be to just iterate over subepochs and break after the number of iterations you want. for e in range(num_epochs): it = 0 while it < num_it: for batch in data_loader: it += 1 if it >= num_it: break .... It’s a tad verbose, but in the end at 5 a…
Mahmoud_Abdelkhalek
Is thetorchaudio.transforms.MelSpectrogramclass intorchaudiodifferentiable? As in, can I backpropagate through it? If so, can someone point to me towards some documentation on how this backpropagation works?
tom
I think so, just do requires_grad_ on your input. In the end it goes through torchaudio.transforms.functional.spectrogram and uses the torch.stft function. This calls torch.fft (I think), which has a derivative defined. There are several texts about how the inner parts of PyTorch work,I wrote some…
mohit117
In my CNN at some stage I want to multiply a feature map with some scalar which should be learnt by the network. The scalar has to be initialised to 5. So I think of the following solution,def __init__(self): super(..., self).__init__() ... ... alpha = nn.Parameter(torch.ones(1)*5) ... def forward(...
tom
I agree with your that torch.tensor(5.) would seem to be even better here for what you’re trying to achieve. It seems most concise. The tensor will be truly a scalar (0-dim) tensor (you’d need to do torch.ones(())) for that. There isn’t any performance aspect. (e.g. when you’re in the middle of a …
John_J_Watson
I am looking for some guidance on the correct way to use/orderscheduler.step()within epochs. So, ofcourse, the official guidance says (torch.optim — PyTorch 2.1 documentation):PATTERN:0scheduler = …>>> for epoch in range(100): >>> train(...) >>> validate(...) >>> scheduler.step()But then I also see code lik...
tom
Yes, use the pattern recommended by the documentation. No. The background is that people found out that it doing the LR step first gives unintuitive maths w.r.t. how/when the learning rate changes, so it is strictly recommended to do the LR step last. As always, advice on the internet may be outd…
TTyRAeLL
I prune a model by setting a certain channel to zero, and then theloss.backward()function isn’t working. It may due to the pruned model can’t be derivated. How can I use BP regardless of the pruned channel?
tom
If you do this for an intermediate, you should multiply with a mask rather than assigning to the value. Quite likely the operation that generated the non-pruned output wants it to compute the backwards. (Search for “inplace” in the forums.) Best regards Thomas
Sokhib_Tukhtaev
I am reading a book “Deep learnin with Pytorch” and the code is like below:print(batch.shape) # torch.Size([4, 3, 256, 256]) batch /= 255.0 n_channels = batch.shape[1] for c in range(n_channels): print("smth.shape", smth.shape) mean = torch.mean(batch[:,c]) std = torch.std(batch[:,c]) batch[:, c] = (ba...
tom
You index into the second index position (dimension 1) of the tensor [4, 3, 256, 256], so that dimension is dropped in the resulting view.
lkc
I’m implementing the max norm constraint as detailed in thispost. Max Norm would constraint the parameters of a given layer based on the L2 norm of the weights.It’s my understanding that the operations should be done in-place for memory efficiency. I have the following code.def forward(self, x): x = x.view(-1, n_in...
tom
It’s likely not memory efficiency that matters here (you’ll have other ops that use more memory and you could do this after the optimizer step when memory is less precious than after the forward) but that you change a parameter that has you want inplace. The implementation you propose looks like t…
Sharpy
Please, advise how to make this work.class HalfReLU(nn.Module): def __init__(self): super(HalfReLU, self).__init__() def forward(self, x): half = x.shape[1]//2 x[:, :half] = nn.functional.relu(x[:, :half], inplace=False) return xI’m gettingRuntimeError: one of the variables needed for gradient computation ha...
tom
I’d just use torch.cat of the pristine and relued parts.
Arohan_Ajit
I’m a beginner in PyTorch but I’ve made a data pipeline a couple of time. The way I know to split the data is, by taking indices and separating them into train and test.:data_transforms = transforms.Compose([ transforms.Resize((50,50)), transforms.RandomRotation(degrees=30), transforms.RandomHorizontalFlip(...
tom
For best practice: I would advise to separate train/val/test earlier, possibly even at the file system level. I know nothing about your dataset, but you have checked that just splitting at a image level is the right thing to do (in medical imaging, you typically want to have all images of a given …
thao
I have 2 train sets: one with label and one with no label.When training, i’m simultaneously load one batch from labelled set, calculate loss in 1 way; one batch from unlabeled set, calculate loss in other way. Finally I sum them (2 loss) andloss.backward().Is this way ok ? it’s quite uncommon in my mind so just ask if...
tom
Semi-supervised learning is a relatively common technique to deal with situations in which labeled data isn’t abundant and might look like this. PyTorch’s autograd it is much the same if the loss has 1, 2, or 10 terms - losses of minibatches typically are just sums or means of the individual items …
Duong_Pham_Anh
I got this error while trying to convert nn.module to torchscript.RuntimeError: undefined value super: File "D:\project\Kikai project\DIFRINT\models\correlation\correlation.py", line 147 def __init__(self): super(FunctionCorrelation, self).__init__() ~~~~~ <--- HERE 'FunctionCorrelation.__in...
tom
If you trace the model, you can just use torch.jit.is_tracing() to check whether you want the JIT-compatible bit and use the function otherwise. There also is torch.jit.is_scripting() for the scripting equivalent. Best regards Thomas
Julien_Despois
Hi, my setup is rather straightforward: my DataLoader’sgetitemfunctions opens up an Image, and crops it using pre-determined coordinates. I want these coordinates to be the same for a whole batch of images, but then change for each subsequent batch.Unfortunately, I can’t find a way to do that with DataLoader workers, a...
tom
If you look at thedetails in the documentation(and know where to look), you see that each batch is compiled by a single worker (it runs the collate function that makes batches from lists of examples). With this, you have two options to get “batch-level” processing: Have the dataset build and re…
mfkasim
Is there any easy way to reliably detect if a function is a JIT ScriptFunction?For example:@torch.jit.script def func1(x): return x.sum() def func2(x): return x.sum() def detect_jit_script(func): pass # should return True for func1 and False for func2I realize thatfunc1is compiled to a method (so it’s no ...
tom
Is isinstance(func1, torch.jit.ScriptFunction) working for you? Best regards Thomas
eprox
Hi,If you try set the grad to false for a layer inside with grad enabled, does this override the with clause?For example:with torch.set_grad_enabled(mode = True): self.model.lin2.requires_grad = False # Will this work? for m in self.model.mlp_f: m.set_grad_enabled = False # Or this?
tom
Keep in mind that set_grad_enabled is a state of the program (“do you want to keep track of gradients for outputs when the inputs require gradients”) and applies to new tensors, while someparam.requires_grad_(False) (which is the suggested form to disable gradients of tensors and parameters) says “t…
ReubenZ
I am very new to coding + pytorchI have an input tensor torch.full((row,col), 2.0), called Aand I want to have an output looks like [[2,2,2], [4,4,4], [6,6,6], …], called BThe idea is to multiple A and B, pytorch will do broadcasting for me if I understand correctly.So I tried:r, c = A.size()x = torch.arange( r ) + 1.0...
tom
x.view(4, 1) doesn’t change x but returns a tensor (view) of shape 4 x 1 if you want you can assign it to a new variable and use that or plug it into your operation directly.
pourya_farzi
HI, I’m wondering about batch size, which definitely influences the epoch-loss graph. If we suppose we have the following tensors as the predictions of the model and real values,the result of loss would be different due to the shifting of elements between the batches.(values are random and not normalized)loss = nn.MSE...
tom
Well, here, you have a batch size of 4 and one of 2 and set up MSELoss to average over the batch items. If you concatenate, you take MSELoss to average over all 6 items and it effectively computes the weighted average (4*8630+2*2850)/6 = 6703. When using a typical setup with PyTorch’s DataLoader, …
voqtuyen
I encounter a problem with the inference speed between inference in main thread and inside Flask API enpoint (which is inside another thread). The inference speed is about 10 times slower.Do you have any idea about this problem and any solution?
tom
Do you run your PyTorch model in Python or have you JITed it to TorchScript? We discuss this a bit inChapter 15 of our book, if you run your model through the JIT - even from Python - you avoid the infamous Python GIL for all intermediates, which may give you an edge in multithreaded deployment sc…
quangduyhcmut
Hello everyone,I am studying about quaternion convolutional neural network following this repo on github:GitHub - Orkis-Research/Pytorch-Quaternion-Neural-Networks: This repository is an update to all previous repositories with implementations of various Quaternion-valued Neural Networks in PyTorchThe repo’s work is gr...
tom
I’d imagine that it is something along the lines of qs = torch.randn(1, 4, 6, 6) # batch 1, 4 channels (1 quaternion) and 6x6 matrix, bs = 1 bs, _, h, w = qs.shape amp = torch.norm(qs, dim=1, keepdim=True) amp_uf = amp.unfold(3, 2, 2).unfold(2, 2, 2).reshape(bs, 1, h // 2, w // 2, 2 * 2) qs_uf = qs…
Andrew_Lim
Hello.While working with a project involving an RNN, I’ve ran into an error of:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operationHere is a minimum working example to reproduce the error:# Setup import torch torch.autograd.set_detect_anomaly(True) # Initializati...
tom
The error is because the weight of the linear layer has changed (through optimizer.step). One might add that here, you have the gradient computation for addmm (which powers linear) pretend it would also want to compute the input derivative for which it would need the weight which, in this trivial u…
fatvlad
Hello,I am playing with very simple dense layer implementation usingtorch.addmmand it seems thattorch.jit.tracetransformsaddmmop to sequence ofmmandaddops, leading to performance drop on CPU:import torch from torch.autograd import profiler torch.set_num_threads(1) def dense_layer(input, w, b): return torch.addmm(i...
tom
There is a secret linear functiondef dense_layer(input, w, b): return torch.ops.aten.linear(input, w, b) more seriously, I think that whatever causes addmm to be split could be considered a bug.
LeeDoYup
I think it is an elementary question about programming with GPU.First, i tried to use time.time() in python module, to measure the operation time of some modules in NNs.such asdef forward(self, x): end = time.time() output1 = self.layer1(x) time_output1 = time.time() output2 = self.layer2(output1) time_output...
tom
So the immediate takeaway from the above discussion is replace time.time with time.perf_counter() have a torch.cuda.synchronize() before taking the the start_time, maybe don’t take the first batch (of a given size)
Dunfash
trying to calculate the roc_score per epoch. my idea is to combine all the batch predictions then calculate but i keep getting error. how do you approach this. i am predicting between 0 and 1train_losses = [] valid_losses = [] for epoch in range(1, num_epochs + 1): y_true = [] y_pred = [] train_loss = 0.0 ...
tom
Storing them in a list and then doing pred_tensor = torch.cat(list_of_preds, dim=0) should do the right thing. I would personally use y_pred(output.detach().cpu()) and store a list of torch.Tensors, leaving the conversion to numpy array for later (or you might see if the array interface does its mag…
ttipri
Suppose I have the following graph and example code.import torch class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() def forward(self, x): z = x.squeeze(0) z.add_(2) x.mul_(5) return x if __name__ == "__main__": script = torch.jit.script(Net...
tom
Reodering is done with checking dependencies, including side effects: Best regards Thomas
torch_torch
I’m trying to use numba and pytorch distribution simultaneously. When I create new tensor on GPU, I got cuda initialization error:Here is my code:import torch import numpy as np import torch.distributed as dist from torch.multiprocessing import Process from numba import cuda import os def func(idx): a = torch.randn...
tom
You could either see which version of cuda numba uses see if PyTorch offers that, too (or vice versa) or you could self-compile one or the other or both.
I_H_Yoo
Hi. I guess there are three way to use activation function in a custom module:Usenn.Softmax()in the initializer in the custom model.Usenn.softmax()in the forward function in the custom model.Usenn.functional.softmax()in the forward function in the custom model.What are the differences among them and what is the proper ...
tom
I think about modules as holding state (e.g. weights, as you mention) and using that and the inputs I pass to produce the output. So for softmax, using the functional interface expresses how I think about it (i.e. as a function of the inputs and no weights etc.). But don’t make it a science, just …
chetan_patil
I am trying to convert a Torch-tensor to OpenCV-Matint32torch::Tensor A = torch::randint(0,30,{4,7},torch::TensorOptions().dtype(torch::kInt32)); cv::Mat cv_A(4,7, CV_32SC1); std::memcpy((void*)cv_A.data, A.data_ptr(),sizeof(torch::kInt32)*A.numel());When I print out the results, it shows# Torch Tensor 16 29 8 18 ...
tom
This isn’t what you think it is (it is the size of a value of the ScalarType type), you probably want elementSize(torch::Int32). Best regards Thomas
JWarlock
Hi, I’m trying to modify the mean/std of one feature with the mean/std calculated from another feature. It looks like this (certain simplification is made since original code is much more complicated)def exchange(vs, vt): # vs and vt are of the same size NxCxHxW vs_mean = torch.mean(vs, dim=(2, 3)) vs_std =...
tom
So if you run anomaly mode, the error might be thrown between the producing of NaN and before the hook is applied. (I must admit I don’t know and in lieu of a simple snippet I can copy-paste into PyTorch, I’m not going to start experiments, sorry.) One way around this might be to define your own au…
ryanaleksander
Hi everyone. I’m deploying a deeplab model onto an android application. The output of the model is a [1,21, 400,400] tensor. In order to get my final result mask, I have to run an argmax operation on the 2nd dimension. In python I figure the operation would be something like this out = np.argmax(out, axis=1). Then I’ll...
tom
You write your numpy-like processing in PyTorch as a plain python function or better yet as a nn.Module, run it through torch.jit.script similar to the TorchScript tutorials, now you can use it similar to the Android tutorials. Using a nn.Module in step 1 isn’t better in the sense that it would be…
falmasri
I have a very nested model with many Prelu. It is not possible to specify all the parameters in the optimizer as a default and respecify all the Prelu as the specific condition.I want to apply zero weight decay to all Prelu parameters and keep all the rest default.
tom
Just like for the lr in thesnippet below the note you cite, you pass weight_decay globally set to what you need and add a weight_decay : 0.0 entry to the dictionary for the param group with prelu parameters. model = torch.nn.Sequential(torch.nn.Linear(3, 4), torch.nn.PReLU()) prelus = {n for n,…
maren11
Hi there,i am new to Objetct Detection and i tried the PyTorch Turorial Object Detection Finetuning. At the end of the Tutorial I can choose an image of the test dataset and I see the prediction. I checked out some pictures and looked at the prediction with the result that only one of the Person is detected. Is there a...
tom
At the end the tutorial uses something like prediction[0]['masks'][0, 0] to get a mask. So taking the boolean selector tensor preds_to_keep = prediction[0]['scores'] > 0.8 and then indexing the masks as prediction[0]['masks'][preds_to_keep, 0]. should do the trix. use .max(dim=0).values or so to t…
f10w
Hi,There is something with PyTorch data augmentation that I would like to understand. I used the following code to create a training data loader:rgb_mean = (0.4914, 0.4822, 0.4465) rgb_std = (0.2023, 0.1994, 0.2010) transform_train = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomH...
tom
Hello, in any epoch the dataloader will apply a fresh set of random operations “on the fly”. So instead of showing the exact same items at every epoch, you are showing a variant that has been changed in a different way. So after three epochs, you would have seen three random variants of each item i…
JosueCom
Is there ongoing work to try to bring PyTorch support for AMD gpus?
tom
You can choose which GPU archs you want to support by providing a comma separated list at build-time (I have instructions forbuilding for ROCmon my blog) or use anthe AMD-provided packageswith broad support).
bat67
Hi~For sigmoid, there’storch.nn.Sigmoidto generate a instance of Sigmoid class, andtorch.nn.functional.sigmoidfunction. I noticed anothertorch.sigmoidfunction and some related topics (link1,link2).However, for softmax function for example, there’s onlytorch.nn.Softmaxandtorch.nn.functional.softmax, butnotorch.softmax. ...
tom
So the idea is to put more deep-learning-oriented functions in torch.nn.functional and keep general-purpose functions in under torch directly. softmax was deemed to fall into the former, sigmoid in the latter category. While there is torch.softmax, this is by accident (which is why it is not docume…
tmain
Hi everyone,is there an easy way to convert a torchscripted model back to an eager model ?Example:eager_model = MyModel() scripted_model = torch.jit.script(eager_model) recovered_eager_model = some_function(scripted_model) ### could not find anything about it in the docs
tom
No, and it is strongly advised that you keep your source code around when doing stuff with JITed models. That said, you can probably get a reduced model by walking the traced module, setting the children in init and using the .forward of each module. This would get you something you can run and re…
Neabfi
Hello,My saved state_dict does not contain all the layers that are in my model. How can I ignore the Missing key(s) in state_dict error and initialize the remaining weights?Thank you!
tom
Pass strict=False to load_state_dict. Then you can iterate for n, p in model.named_parameters() and do whatever you want for n not in sd or so. Best regards Thomas
chwan-rice
My torch version is 1.5.1. I found a strange behavior of torch.exp():import torchx = torch.ones(2, 1, requires_grad=True)x = torch.exp(x)x[0] = 0out = x.mean()out.backward()After running this code, I got a running error:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace o...
tom
So I covered some of that along with many “little mysteries” in acourserecently (slides 28-35). From the summary slide: There are two main situations where inplace operations cannot be used: When operating on leaf tensors, the leaf tensor would be moved into the graph, which would be bad. When …
Carol_Ye_Liu
We are trying to build a libtorch based C++ project using customized kernels which are written in .cu files, but encountered the following compiling errors. By commenting out line 191-197 in the THCNumerics.cuh, we are able to get a clean build. We are using CUDA 10.2 and cuDNN v7.6.5 on a V100 GPU server.I wonder what...
tom
From what I recall, you want to disable the built-in fp16 ops for PyTorch, something like -DCUDA_HAS_FP16=1 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ or somesuch. Quite likely the flags PyTorch itself builds with are indicative for what you need. I…
SOUMYA_SUVRA_GHOSAL
I have one tensor x of shape [64,324]. Think of 64 as batch size and 324 as number of features. I want to perform cosine similarity with another tensor w such that that the output tensor is of size [64,10] , where 64 is same as batch size and 10 is output features. I could not find any tensor w which serves this purpos...
tom
For x of shape 64x324, if w is 324x10 the product x @ w is 64x10 and is 64 x 10 scalar products (so higher = closer alignment). You effectively compare the batch features against 10 example features and measure alignment to each of them.
mcfn
i have a dataset of large images (i.e. the parameters i pass to transforms.resize or resized crop are smaller than the image dimensions and it works fine. i added small images to the dataset (i.e. smaller than the parameters). how are they handled by the transformations? also, is it/what is the best way to handle them?
tom
I would start with theTorchVision documentation of Resize. It explains If size is a sequence like (h, w), output size will be matched to this. If size is an int, smaller edge of the image will be matched to this number. i.e, if height width, then image will be rescaled to (size * height / width,…
Vibhu_Bhatia
I’m trying to optimize very simple functions like quadratic, absolute value etc using pytorch, and i was wondering if GPU will speedup that process. I am using no neural net or anything just a 1D tensor and using the above functions and loss functions and trying to find the minima.
tom
At a very basic level, GPUs work best when doing “the same thing to a lot of datapoints” (à la SIMD - Single Instruction Multiple Data), even if the details are a bit more intricate than for typical CPU SIMD units. This is applicable for convolutions, matrix multiplications (of reasonably large matr…
Capo_Mestre
I have images 128x128 and the corresponding labels are multi-element vectors of 128 elements.I want to use DataLoader with a custom map-style dataset, which at the moment look like this:# custom dataset class Dataset(Dataset): def __init__(self, images, n, labels=None, transforms=None): self.X = images ...
tom
to_pil_image wants float32 inputs, I think. It doesn’t make a whole lot of sense to me to use to_pil_image right before to_tensor, but hey, what do I know. Best regards Thomas
Javier_Rodriguez_Pui
Hi, from the literature it is known that normally in NN it is used a Softmax for classification and a Sigmoid for regression.My question is always required an activation function at the end. I am trying a U-net to acquire pixel wise depth in a scene from rgb. and I get better results if I don’t use any sigmoid at the e...
tom
Chapter 6 ofour book that you can download herehas some discussion on this. There are two main uses of the activations functions In the inner bits of the network, you need to have one to go beyond linear (i.e. to get the ability to approximate arbitrary functions), at the final layer, the main …
Kieran
Hello, I’m implementing an LSTM to predict today’s stock price using the past 10 days’ close price.Therefore, my input is [batch_size, sequence_len = 10, input_size = 1] since there is only one feature every day.Then I set batch_size = 50 and implement a train_loader with TensorDataset and DataLoader.My LSTM model is d...
tom
this passes the init_hidden method, you likely want init_hidden() instead. (Why you would need to do this when 0 initial hidden it is implicit in PyTorch, I don’t know.) Best regards Thomas
Carol_Ye_Liu
I defined a forward function in a module. The forward function checks if the noise input parameter is None or not, if None then create its own noise; if not None, then just use the input noise. However, this could not be achieved using the following code, c10::optional<at::Tensor> could not be converted to torch::Tenso...
tom
The typical thing is to just take a tensor argument (const Tensor& or Tensor). Then test t.defined(). None is translated to an undefined Tensor. Best regards Thomas
jimmy
Hi,I tried something a bit unsual. It is working, but sadly there is a memory leak. Maybe someone can help me finding it. Basicially I tried to create a gradient based integration function:Fit a model with the gradient values of a function. Here I am fitting both, the y values and the gradients in parallel.import torch...
tom
Using torch.autograd.grad (which is a better fit conceptually) dx_pred, = torch.autograd.grad(ys_pred, xs, torch.ones_like(ys_pred), create_graph=True) removes the memory leak. Note that torch.tensor is preferred over the constructors like FloatTensor and we generally avoid .data. You don’t n…
zfzhang
Hi All,I encountered a large numerical discrepancy betweenfunctional.conv2d()andfunctional.unfold()+torch.tensordot(), which causes me trouble. My PyTorch version is 1.5.0. Now I write up a minimalistic example to reproduce:import math import numpy as np import torch import torch.optim as optim import torch.backends.cu...
tom
The way I typically look at this is by relating the maximal difference to the magnitude of the results (0.000168/139) in order to avoid the problem that relative difference has with cancellation (or you could look at only positive inputs). This gives about 1.2e-6, which would seem standard fare for …
chinmay5
I have a PyTorch code written in PyTorch 0.4 and I want to upgrade it. The major part where I am getting stuck is with the CUDA kernels. I know that I need to use ATen library but I do not think it is very properly documented and hence as such I am completely stuck while trying to do the upgrade. This is just one of th...
tom
Yeah. If that bothers you in the overall picture, Probably go with a custom kernel. Best regards Thomas
Kai_Eiji
Hi,I’m trying to calculate a gradient w.r.t a sparse matrix. It seems like pytorch’s autograd doesn’t support getting the gradient for sparse matrix so I want to calculate it manually if it’s possible.the forward function is softmax(A*AXW). A is a sparse matrix and I want to calculate the gradient w.r.t Athanks!
tom
What’s large here? The problem is likely (and ha, now the formula is useful after all) that the to computation df/dA = (df/dY)@ B.t() is in all dense matrices and you don’t, in general, have the sparseness same pattern in the gradient. What PyTorch does under the hood is to compute the dense deriva…
turian
What is the best way to predict a categorical variable, and then embed it, as input to another net?My instances are tabular, a mix of categorical and continuous variables. I currently have a siamese net (net1) that uses the instances as input. The categorical variables are integer indices used before an nn.Embedding la...
tom
Yeah. 4. In other words, you take the probability vector for the categories and feed it into a Linear layer that has the embedding as weight.
HaziqRazali
I am doing semantic segmentation and was wondering if there is a method in PyTorch that will allow me to compute the CRF loss shown below? I am not trying to do inference. I just want to compute the loss based on the unary and pairwise terms.I could do it myself. Replicate the output 8 times, shift the pixels according...
tom
I think you want to give more context than that. I assume that phi is your “ground truth loss” (x being the ground truth or some such information) and psi the consistency loss. Now psi is rather underspecified in the formula. From your description, I looks like that i,j iterates over all pairs of a…
lihx
I noticed that the default initialization method for Conv and Linear layers in Pytorch is Kaimiing_uniform.I just don’t understand why the default value of negative_slope(the default act is leaky_relu) is √5.Is it written just for simplicity or for some specific reason?def reset_parameters(self): init.kaiming_unifo...
tom
My understanding (the last update is here) is that this is mainly from casting the init as it has always been done to the kaiming_uniform_ initialization scheme. I would not read it as a recommendation for that particular activation function. As such, for me there are two takeways: This is a sche…
Frida
Hi!How would you recommend to do the un-normalization of imagenet images, when:transforms.Normalize([0.485 , 0.546, 0.406], [0.229 , 0.224 , 0.225]) is used.the goal is to get back a numpy array [0,1].Thanks a lot!
tom
SoNormalizedoes x_norm=(x-mean)/std. If you want to undo that, you could do x = x_norm * std[None, :, None, None] + mean[None, :, None, None] (the indexing aligning the channel dimension) or if you prefer magic, reframe it as (leaving out the indexing) x = (x_norm + (mean / std)) * std and then yo…
Stone_Yu
Hi there,My framework contains two parts: 1). a selection mechanism 2). a predictor. The input data is a sequence but not all items in the sequence are useful. So I just use TopK items in the sequence to predict something.But I failed to calculate the gradients since using top K indices block gradients flow to the sele...
tom
Yeah, well, the core of the problem is that you are not using scores or val in the further calculation. If you then do the calculation based on the input sequence, you cannot expect gradients (which factor through dloss/dval and dloss/dscores = dval/dscores dloss/dval) to flow back. (You need to use…
xu_wang
The AdaptiveAvgPool2d layers confuse me a lot.Is there any math formula explaning it?
tom
Well, the specified output size is the output size, asin the documentation. In more detail: What happens is that the pooling stencil size (aka kernel size) is determined to be (input_size+target_size-1) // target_size, i.e. rounded up. With this Then the positions of where to apply the stencil …
Hika-Kondo
I want to log the loss of the train using the tensorboard in pytorch. I got an error there.AttributeError: 'Tensor' object has no attribute 'items'I want to solve this error and check the log using tensorboard. Here I show my code.l_mse = mseloss(img,decoder_out) writer.add_scalars("MSE",l_mse,n_iter)then I have error ...
tom
There isadd_scalar(singular, so no s at the end) that would seem to work roughly like you want (except for the .eval() in there). You are callingadd_scalars(plural) which takes name/value pairs in form of a dict if you want to add several. Best regards Thomas
moluchase
I know how to implement the sigmoid function, but I don’t know how to find the implementation oftorch.sigmoidin pytorch source code.I coun’t find the relevant implementation function in the torch directoryGitHubpytorch/pytorchTensors and Dynamic neural networks in Python with strong GPU acceleration - pytorch/pytorch
tom
I wrotea tutorial on diving into PyTorch codea while ago, but it still is largely accurate. In particular rgrep sigmoid aten/ should be helpful. Best regards Thomas
bhushans23
I am looking forward to implement ‘Quasi Newton algorithm’ in pytorch.Looking for suggestions of other optimization algorithms that you think are useful? I will go through and implement bunch of it.
tom
Last year, quite a few people talked about KFAC, but it might not be too easy to fit into the pytorch optimizer framework. One of the most prominent implementations seems to be this: Best regards Thomas
aRI0U
I need to compute the approximate derivative of a tensorxusing finite differences, i.e.x[1:] - x[:-1]. My problem is that my input tensor is multidimensional and that I need to compute those finite differences along different dimensions. I would thus need a generic functionf(x, dim)that basically do the following:if di...
tom
You can use narrow to your advantage: a = torch.randn(5, 2048, 5) print(((a[:,1:,:] - a[:,:-1,:])-(a.narrow(1, 1, a.size(1)-1)-a.narrow(1, 0, a.size(1)-1))).abs().max().item()) %timeit a[:,1:,:] - a[:,:-1,:] %timeit a.narrow(1, 1, a.size(1)-1)-a.narrow(1, 0, a.size(1)-1) gets me 0.0 14.3 µs ± 190…
jean-marc
Hello Everyone,I am building a network with several graph convolutions involved in each layer.A graph convolution requires a graph signal matrixXand an adjacency_matrixadj_mxThe networksimplified computation graphlooks as follow:Screenshot 2020-04-19 at 11.51.391576×1196 33.2 KBIn(a)thenetworkhasself.adj_mxbeing used i...
tom
This seems dubious, as it replaces the parameter(?) self.adj_mx with the multiplied version. As a rule of thumb, assigning things in forward is unlikely to be the right thing to do. Best regards Thomas
Melissa
For example, I have a tensor of size(batch_size, hidden_size, hidden_size). Is there a way to compute the trace of matrix(hidden_size, hidden_size) for every sample in this batch without a loop? So that the output tensor is a vector of size(batch_size).Any tips will help! Thanks!
tom
There are several ways to get this easily, for example b = torch.einsum('bii->b', a) or b2 = torch.diagonal(a, dim1=-2, dim2=-1).sum(-1) Best regards Thomas
Felix_Labelle
Consider the following 6x6 tensor.tst_tensor = tensor([[1, 1, 1, 2, 3, 1], [1, 2, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0], [5, 5, 5, 5, 5, 5], [5, 5, 5, 0, 0, 0], [0, 2, 3, 0, 0, 0]])I’d like to window it in 2x2 windows (or 4 x 1) as followstensor([[1, 1, 1, 2], [1, 2, 0, 0], ...
tom
For getting tiles, manually doing this is probably most efficient: windows = tst_tensor.view(3, 2, 3, 2).permute(0, 2, 1, 3).reshape(1, 9, 4) Best regards Thomas
sh0416
Hi,While implementing my code using c++ API, I have a question about memory management in pyTorch.In Python, memory management is automatically handle allocation and free. What about c++?? Do I have to manually free tensor that I allocated in c++ code?Thanks,
tom
LibTorchtracks the lifetimeof your tensors (except when you use from_blob, in which case your tensors don’t own the memory), so you would not need to delete them except letting them go out of scope. Best regards Thomas
CCL
I have a (n, n) mask and corresponding (3, n, n) image. I’m trying to use thetorch.topk()function to get the top k sigmoid pixel values and erase them from the corresponding image. However, I’m struggling quite a bit trying to understand howtopk()deals with dimensions… To properly compute this, do I need to unsqueeze t...
tom
topk takes the top k over a single dimension. So if you want to take the top k over the two spatial dimensions, you need to .view(…) your tensor to combine them to one and then “unravel” the indices. Best regards Thomas
Hippolyte_Dubois
Hi,I’m trying to manipulate a matrix by multiplying each column by a matrix.My code looks like this:for i in range(s.shape[0]): s[i,:] = torch.matmul(s[i,:],M) return sMandsarem*mTensors.When I try to backward, I get this error:RuntimeError: one of the variables needed for gradient computation has been modified by an ...
tom
Two possible ways: Use batch matrix multiplication (or einsum or whatever). Instead of overwriting s[i], collect the results in a list and do torch.stack on it after the for loop. Best regards Thomas
FantasyJXF
Questions and Helplibtorch 1.2 CU100 or libtorch 1.4 cpuWhen I try to convert the thetorch::Tensortocv::Mat, I use the following code:std::memcpy((void *) linkmap.data, score_link.data_ptr(), sizeof(torch::kF32) * score_text.numel())The tensor type isCPUFloatTypeand I usesizeof(torch::kF32)to get the tensor data, but f...
tom
That’s because torch::kF32 is a constant indicating a type, not a C++ type. I think you want elementSize(torch::kF32), which gives you the element size. Best regards Thomas
hawkeyedesi
I have two data loaders that I combine using a ConcatDataset operation. However, I am performing a clustering operation on the dataset wherein I run some clustering on every epoch and update the clustered array that each dataset belongsMy question: How does the expected behavior of the list work when using concatenate....
tom
ConcatDataset is intended for cases where you want to have the same thing per item as in the individual datas ets. You could either modify the individual data sets or go through data_concat.datasets (a list of datasets). If you need to do operations across datasets, you’re better off creating a cus…
BobChen
When usetorch.nn.DataParallelto do multi-gpu training, doesloss.backward()only calculate the grad towards the model on the master gpu or calculate the grad on each gpu and then merge them.
tom
The latter. In particular, the intermediate results needed for backward are typically on the GPU where you did the forward. Best regards Thomas
rasbt
Was just looking at the DCGAN tutorial (DCGAN Tutorial — PyTorch Tutorials 2.2.0+cu121 documentation) and noticed that .backward() is called twice:Screen Shot 2020-03-01 at 9.30.38 PM686×730 94.5 KBWouldn’t it be more efficient to computeerrD = errD_fake + errD_realfirst and then callerrD.backward()so that backward has...
tom
Hi Sebastian, I think it’s a tradeoff between time and GPU memory. For the memory: With the setup in the code, you can produce and process the autograd graphs for real and fake separately, so in a very lame sense, you can “double the batch size”. In terms of performance: In the end, yes, without …
hyperactve
This is my network:class Net(nn.Module): def __init__(self, device, channels=[2,10,10,10,10,10,1]): super(Net, self).__init__() weights = [] biases = [] gammas = [] N = len(channels) self.layers = N-1 for i i...
tom
If you only need to gradients w.r.t. the inputs (and don’t have bad things like batch norm), summing the outputs and then calling .backward will get you gradients. For weights it is more tricky to avoid gradients being accumulated. inp.requires_grad_() before passing it into the network will tell …
Chame_call
I’d like to know the following:If we have two different video cards(cuda compatible) how to find out which of them will lead quicker network training.
tom
Cuda cores, memory bandwidth, software support, task characteristics. But really it’s complicated enough that people usually do empirical measurements. If you want simple and both cards are still on the market, you could go by $$$.
Robin_Lobel
I’m using libtorch 1.4.0 on my MSI P65 laptop (Win10, RTX 2060, NV driver 441.22, Cuda 26.21.14.4122).When using the CPU, this code works as expected:auto tensor1=torch::zeros({1, 1, 2, 2},torch::kCPU); tensor1[0][0][0][0]=42; cout << "tensor1:" << endl << tensor1 << endl << endl; float tensor2Data[]{42,0,0,0}; auto t...
tom
That’s because the data is on the CPU and you’re instructing PyTorch to treat the CPU-pointer tensor2Data as a GPU pointer. You’d need to make it a tensor first and then move to CUDA. As an aside, tensor indexing as in tensor1[0][0][0][0]=42; is not efficient if you do it at scale. This statement w…
Yolkandwhite
brainMRI1611×668 242 KBAs you can see in this picture above there are lots of image files in that directory.brainMRI21245×557 235 KBI don’t know why the number of datapoints is 2doesn’t it mean the imagefolder reads 2 imagefiles?I have no idea why ImageFolder doesn’t reads the whole imagefiles I have in that directory....
tom
As per the documentationdocumentation, ImageFolder expects images to be organized as class/instance.tif with class subfolders. Best regards Thomas
kuzand
I am creating my own dataset class which takes a path to a csv file containing image paths and labels:class MyDataset(): def __init__(self, csv_path): ... def __len__(self): return len(...) def __getitem__(self, index): ... return (img, label)As you can see it contains the ...
tom
Will it work without subclassing Dataset? Probably in most cases. Do you get anything from skipping subclassing Dataset? Probably not. Will it bite you when third party code tests isinstance(ds, Dataset) to see if it got a dataset or if someone use type hinting with your code? Yes. Best regards …
felixems
I’m running a version of StarGAN where the ConvTranspose2d layers which up-sample the signal have been replaced by a resize convolution as described below. For some reason, the forwards pass through the Upsample layers are very slow in comparison to the rest of the network, which is surprising to me, considering that t...
tom
Are you sure you’re measuring that right? I’m asking because most people don’t. For integral scaling, it can be faster (and with deterministic backward and all) to use array operations. You might split this into several lines, but to give you an idea, this would upscale a BCHW inp by 2x: out = inp…
vainaijr
in the paper formula is,how do we manually calculate this value, for example,from captum.attr import IntegratedGradients import torch, torch.nn as nn, torch.nn.functional as Fclass ToyModel(nn.Module): r""" Example toy model from the original paper (page 10) https://arxiv.org/pdf/1703.01365.pdf f(x1,...
tom
A 1d example won’t do.But here is a simple 2d one. Take f(x, y) = x * exp(y). We can plot this in 3d or as a countour plot: f = lambda x, y: x * y.exp() xx = torch.linspace(-1,1)[None].expand(100,100) yy = torch.linspace(-1,1)[:, None].expand(100,100) zz = f(xx, yy) x0 = torch.tensor([-0.5, 0.5…
adaber
Hi everyone,I did some testing on copying a tensor from GPU to CPU (.cpu() method) and it seems that Pytorch allocates a new chunk of “CPU” memory (RAM) every time the .cpu() method is executed.Is there a way to copy a “GPU” tensor to a preallocated buffer in RAM (CPU side) using C++ ? I would like to avoid allocating ...
tom
You could use cputensor.copy_(gputensor) (both in Python and C++). Best regards Thomas
G.M
I’m trying to implement a C++ function that has the arguments of a Device and Dtype and will be called in Python. But I got error trying to achieve this.Here’s my C++ code:#define tensor torch::Tensorv tensor fun1(tensor x,torch::Device device,torch::Dtype dtype) { auto opt = torch::TensorOptions(device).dtype(dtype);...
tom
I don’t think this works directly right now. If you have compiled torch yourself, you see that in torch/csrc/autograd/generated/python_torch_functions.cpp the factory functions take the Python objects and unpacks them. The PyBind converters are only present for IntArrayRef and Tensor (toch/csrc/ut…
barakb
Hi, as mentioned in the docs, the student logits need to pass through a log_softmax, my question iswhy?log softmax doesn’t give us a distribution, is it because of the way pytorch implements kl loss?Thanks!
tom
log_softmax gives you logarithms of a distribution… Expanding DL(P_target || P_prediction) = P_target * (log P_target - log P_prediction), we see that P_prediction only appears as a logarithm. Given that taking the exponential and then converting back is numerically somewhat unstable, it makes sens…
dstrube
I’m enjoying reading the book “Deep Learning with PyTorch”. If I found a typo in it, do you know what would be the best way to contact the person who would correct it?
tom
Hi David, so I’m not entirely sure about how and if the essential excerpts will be updated, but if you send them to me (in PM or attv@lernapparat.de), I’ll check that we’re fixing them forthe “proper” book, it might be just in time to sneak in typo corrections before going to print, and also forw…
qbx2
I’ve searched why, and it seems to be related to simultaneous multithreading (SMT) and OpenMP.OMP_NUM_THREADSis (num of cpu cores) / 2 by default(?). Is this behavior intended in pytorch? I don’t think that this will help increase performance…
tom
If you have 4 cores and need to do, say, 8 matrix multiplications (with separate data) you could use 4 cores to do each matrix multiplication (intra-op-parallelism). Or you could use a single core for each op and run 4 of them in parallel (inter-op-parallelism). In training, you also might want to …
slavavs
I want to feed the model type float16. But I get the error RuntimeError: Input type (torch.cuda.HalfTensor) and weight type (torch.cuda.FloatTensor) should be the same. How do I set weight type float16?
tom
Did you try m.to(dtype=torch.half)? Best regards Thomas
0xFFFFFFFF
I’ve made some pull requests to Pytorch’s C++ / CUDA functions, but I was never able to fully comprehend the general structure of Pytorch to the details. I’ve dug into the directory many times, but after a attempts, I thought the best would be to hear from the hoarse’s mouth.I want to clairfy the general function call ...
tom
I have anold blog postdescribing how this works from a “where does my PyTorch function come from?” perspective. The key is the native_functions.yaml. From that the dispatching works to Convolution.cpp via autogenerated wrappers (torch/autograd/generated for the Python bindings, and also to go from…
Dennis_Hugle
Dear Community,I found that some people use the Kullback leibler divergence loss for training their model when the output layer consists of a one-hot-vector using pytorch.I actually tried it myself, and it works well. However I do not understandwhythat works. As given in the documentation, the loss over the output laye...
tom
Less briefdefinitionsof the Kullback-Leibler divergence spell out the that the term is to be considered to be 0 when log y_i is 0. This is by continuous extension: [image] The PyTorch implementation uses torch.where to achieve this. You cannot get away with x_i being zero when y_i is not, the…
stas
What is the current way to write an SGD-like code without usinggrad.data, and why is.datanot documented anywhere (other than the 0.4 migration guide).Here is a simple code that solves Ax=b using SGD w/ autograd. I can’t find an elegant way to implement the descent-part w/o usinggrad.data. Looking at optimizers in the p...
tom
Hi Stas, good to see you around! So drop the .data, wrap in no_grad works here as far as I can see: def perfect_update(x): with torch.no_grad(): x -= 0.0001 * x.grad x.grad.zero_() return x (I’m having reservations about calling it update when it also zeros grad and about retu…
entslscheia
I was trying to understand the autograd mechanism in more depth. To test my understanding, I tried to write the following code which I expected to produce an error (i.e.,Trying to backward through the graph a second time).b = torch.Tensor([0.5]) for i in range(5): b.data.zero_().add_(0.5) b = b + a c = b*a ...
tom
Don’t use Tensor(...) or .data any more! They have been deprecated since PyTorch 0.4. the reason you are not getting an error for the first is that the + backward doesn’t need any saved tensors while the multiplication needs the other argument to compute the input gradient from the output gradient.…
f3ba
In the docs it is recommended that when implementingforwardandbackwardpasses for a custom function, they be marked as@staticmethod. For example:https://pytorch.org/docs/stable/notes/extending.html.What does the annotation@staticmethoddo? I can’t find an explanation in the docs.
tom
Static methods are methods not attached to a particular instance - so they do take a self as first argument. They’re not PyTorch-specific but a general Python thing:https://docs.python.org/3.5/library/functions.html#staticmethodPyTorch’s autograd Functions store state in a special context object…
Dylan_Yung
def forward(self, input, hidden, encoder_outputs, mask):""" Run LSTM through 1 time step SHAPE REQUIREMENT - input: <1 x batch_size x N_LETTER> - hidden: (<num_layer x batch_size x hidden_size>, <num_layer x batch_size x hidden_size>) - lstm_out: <1 x batch_size x N_LETTER> """ # Inco...
tom
You cannot use indexed assignment here, as the backward of the previous operation wants to use the calculation result you are overwriting. The typical solution is to use torch.where(mask, attn_weights, neginf) where neginf is torch.tensor(float('-inf'), device=device) (I would recommend precomputin…
vadimkantorov
In PyTorch CTC gradient takes log-probabilities as input (after log_softmax operation).It seems that the CTC gradient formula in PyTorch (cpu version for simplicity) refers to and seems to be implementing eq. 16 from theoriginal CTC paper.Eq. 16 seems to compute gradients wrt logits, not log_probs, and PyTorch must com...
tom
At the risk of being the CTC person that I don’t want to be: The key that the paper is not using log space, so we are not interested in the derivative by y, but by log y. With this, we can remind ourselves that is that log probs are logits (i.e. x.log_softmax(dim=1) == x.log_softmax(dim=1).log_soft…
talesa
Hey!I’ve noticed that for sufficiently high resolution of images (e.g. full HD) I cannot get a good enough “identity grid” usingtorch.float32precision, code below.Posting here:to give a heads up to othersto double check - am I right this just a numerical precision issue?I saw@bnehoranmention in theissue on githubAllow ...
tom
Yeah well, then you have to code up the function that computes without the identity grid.
barakb
Hi, I want to make a backward pass that will calculate gradient update need just for one specific tensor.I understand that the tensors that are closer to the end of the network will also get a gradient calculation, but my goal is just for the specific tensor.So how can I stop the loss.backword() operation in some layer...
tom
You need it before the forward pass. So technically, it’s not a Module but a Parameter/Tensor property and you need to decide before you use the Tensor whether you want to differentiate later so that the autograd can start recording. Best regards Thomas
dato_nefaridze
a=torch.tensor([3.0],requires_grad=True) def sqrt(x): return x*x b=sqrt(a) print(b) c=sqrt(b) c.backward() print(c.grad)how can i see gradient of b tensor with respect c? it should be 2*x, and if b==9, gradient should be 18
tom
You can use b.retain_grad() to instruct PyTorch to store the gradients of intermediates like b. Best regards Thomas
alanzhai219
I am looking into PyTorch-jit-fusion now. I try to set a breakpoint in fuser_kernel.cpp at FusedKernelCPU::FusedKernelCPU(…) when I run a jit-trace stript. Anyone can tell me when and how such function will be invoked? Any reply will be appreicated. thanks
tom
Last I looked, CPU fusion was disabled by default, so you need to enable it with torch._C._jit_override_can_fuse_on_cpu(True). Printing myfn.graph_for(inp) will show if you have fusion for your inputs. Note that as optimized graphs are cached, you need to re-define the traced/scripted function in…
maaft
Until now I didn’t bother to restore the previous state of my Adam Optimizer to continue training.In fact, I observed that by doing this, a new best performing model is often found after this “hard” continuation.Is there anything I am missing that makes this practice absolutely wrong?
tom
Well, so restoring the state and continuing is the equivalent of doing a single larger training run. What happens is that during the first few steps, the statistics gathered by the optimizer are still “rubbish”, and so you will take steps of more or less not terribly controlled size (the could be m…