user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
hoangle_tttm
Im using SELU as my activation function. As i have known pytorch is using He as weight initialization for Linear Layer. How can i apply Lecun weight initialization for my Linear Layer?
ptrblck
You can apply the torch.nn.init method (or any other custom weight initialization) on the modules directly or e.g. via model.apply() and a weight_init method as described inthis post.
L-Reichardt
Hello,i am currently looking for some input regarding computational costs.What would be computationally more efficient?:using 3x3 max pooling on a single channel tensor to create a new variableor using clamping on a different single channel tensor to create a new variableThe dimensions of both tensors are equal. If pos...
ptrblck
Note that the theoretical computational cost might differ from the used implementation, so a proper way would be to profile both workloads via e.g. torch.utils.benchmark.
Yolkandwhite
Hi, I’m loading the optimizer like this.optimizer.load_state_dict(ckpoint['optimizer'])I want to change only learning rate without changing any other things.how can I fix it?
ptrblck
You can assign a new learning rate to the desired param_group, e.g.: optimizer.param_groups[0]['lr'] = 1e-3 should work.
AntMorais
Hi, I am training a simple model on the GTSRB dataset with PyTorch C++ Frontend. There is an “INTERNAL ASSERT FAILED” error in epoch 5, as you can see in the following code:... Train Epoch: 5 1208/13200 Loss: 0.0776928 Acc: 0.831126 Train Epoch: 5 1288/13200 Loss: 0.0787623 Acc: 0.831522 Train Epoch: 5 1368...
ptrblck
Could you update to the latest nightly release and check, if this might have been already fixed? If you are still hitting this error, could you create an issue onGitHubso that we could track and fix this?
loganfrank
Hi,I’m wanting to modify the PyTorch C/C++ source code for Batch (and Group, Layer, etc.) Norm layers for part of my research, which could hopefully result in a contribution to PyTorch if successful and the work is substantial.I’m wondering what files I should look at for modifying? The hope is I can do something liken...
ptrblck
Yes, I think using a custom C++/CUDA extension should not introduce a performance penalty compared to built-in methods.
stalhabukhari
Hi, I am trying to install PyTorch1.8.0via conda, using the command provided on the main page:image1303×471 25.6 KBHowever, when I get the command to run, I see the following prompt:image1094×799 26.1 KBYou can notice that it is installing version1.7.1instead. Is this expected?
ptrblck
No, that’s not expected and I guess you might need to update your conda base environment so that the latest version can be found.
JDE65
HelloI developed a standard Conv1D model in Pytorch to predict time series with classification (4 classes).I gathered a train set (5000 data) and a test set (1000 data). The model predicts daily data by batches and is quite efficient.As the results were satisfactory, I then moved to the next step :I trained my modelI s...
ptrblck
If I understand the issue correctly, you are seeing a performance drop after loading a saved model and evaluating it on the same dataset? If so, are you calling model.eval() while the evaluation is performed? If that’s the case, could you pass a static input to the model before saving and after loa…
jon-jon-jon
Hi PyTorch lovers,I’m facing an issue or an ununderstood of how the Pytorch autograd works.I’m working with a big model where I’m only able to feed it image by image. Whatsoever, I would like to train it using a batch size greater than 1. Obviously, my image doesn’t have the same size. My data loader already push lists...
ptrblck
Your code looks correct, but you might want to divide the accumulated loss by the number of accumulation steps. Also,hereis a nice overview of different approaches in case you want to trade compute for memory etc.
Loud_BoomBox
Hi,I am trying to run inference a custom network with following state_dict and corresponding weight and bias dimensions loaded from a pre-trained model. I have attached part of the network in which the error seems to be occurring.. . . name=encoder.original_model.classifier.weight, size=torch.Size([1000, 2208]) name=en...
ptrblck
The error is raised due to a mismatch in the number of dimensions. New dimensions would be added to the front of the expanded tensor, so you would have to unsqueeze the missing last dimensions: bias = torch.randn([1104]) result = torch.randn([1,1104,15,20]) bias[None, :, None, None].expand_as(res…
cmplx96
Hi all,is there a way to specify a list of GPUs that should be used from a node?Thedocumentationonly shows how to specify the number of GPUs to use:python -m torch.distributed.launch --nproc_per_node=NUM_GPUS_YOU_HAVE ...This was already asked in thisthreadbut not answered.Cheers!
ptrblck
You can make certain GPUs visible via CUDA_VISIBLE_DEVICES=1,3,7 python -m ..., which would map GPU1, GPU3, and GPU7 to cuda:0, cuda:1, cuda:2 inside the script and execute the workload (DDP in your case) only on these devices.
DeepManuPy
Here is the dropbox link to the zip containing log file, model.py, handler.py etc.https://www.dropbox.com/s/gi8wmyxmpy1zx84/Files.zip?dl=0Model trained:image794×230 8.89 KBCommands used:torch-model-archiver --model-name foodnet_resnet18 \ --version 1.0 \ --model-file model/mode...
ptrblck
The loading behavior is not defined by torchserve but by PyTorch depending how you’ve stored the state_dict. You could either push the model to the CPU before storing the state_dict or use the map_location argument as explainedhere.
111480
Although to(at::kCUDA) was used for the model and input value, the output value printing was possible without DeviceToHost memcpy.How is this possible?Is that what’s happening internally? If so, where does it happen?
ptrblck
It should happen inFormatting.cppvia the to(kCPU, kDouble) operation.
Hmrishav_Bandyopadhy
Hi, so i am trying to write an architecture where ihave toconvert entire models to cuda using model.cuda(). However, some of the elements are variables initialised in theinit() loop of nn.Module() class. How do i convert them to cuda ? For example,class Net(nn.Module): def __init__(self): self.xyz=torch.ten...
ptrblck
While this approach would work, the proper way to register tensors inside an nn.Module would be to either use nn.Parameter (if this tensor requires gradients and should be trained) or via self.register_buffer. Both approaches will make sure that this tensor will be pushed to the specified device (in…
seankala
Hi. I’m facing some issues when I’m trying to use PyTorch optimizers with Apex AMP. My environment is:OS: Ubuntu 18.04.5Python: 3.8.5PyTorch: 1.7.1CUDA: 11.0Apex: 0.9.10.dev0Transformers: 4.3.3You can reproduce my error with the following code:from apex import amp from transformers import AutoModel from transformers.op...
ptrblck
We recommend to use the native mixed-precision utility viatorch.cuda.ampas describedhere. New features, such as the compatibility with 3rd party repositories (transformers in this case), won’t land in apex/amp, but in native amp instead.
Sowmen_Das
I am doing a binary segmentation task. I’m using BCEWithLogitsLoss. I’m using Albumentations to augment and normalize images.transforms_normalize = albumentations.Compose( [ albumentations.Normalize(mean=normalize['mean'], std=normalize['std'], always_apply=True, p=1), albumentations.pyt...
ptrblck
For a multi-class segmentation use case, you should use nn.CrossEntropyLoss where the model output should be a FloatTensor in the shape [batch_size, nb_classes, height, width] and the target a LongTensor in the shape [batch_size, height, width] containing the class indices in the range [0, nb_classe…
alphanumericnosnense
Running the code below devours all available RAM:import numpy as np from torchvision import transforms transform = transforms.Compose([transforms.ToTensor(), transforms.Resize(256)]) X = np.full((1,256,256),0) Y = transform(X)I was making custom masks for a segmentation problem and wanted constant tensors with various ...
ptrblck
Images stored as numpy arrays are expected in the channels-last memory layout. For a grayscale image you could thus pass X as [256, 256] or [256, 256, 1], which will return the expected output. In the current format, torchvision assumes that your image has a height of 1, a width of 256, and 256 ch…
sajidmahmud14
Hi I would like to create a network, where the last layer will be an adaptive max-pooling layer, and the output shape will vary on the input size of the network. Now in my dataset, the input sizes are not of equal size. Here is my network code:class Net(nn.Module):def __init__(self, blocks, block, in_channel, out_chann...
ptrblck
You could get the shape of the input via: x.size() or x.shape and use the functional API via out = F.adaptive_max_pool2d(out, output_size=...).
Marcel_Iten
What loss functions/ criterion do i choose when my model output is an image? I would like to have pixelwise L2 loss.
ptrblck
nn.MSELoss should work in this case and accepts 4-dimensional tensors (image tensors) as the model output and target.
saandeep_aathreya
I am using Dataparallel module to train my network. However, I am facing the gpu device error when the MultivariateNormal distribution module is used. with my tensors.# Using DataParallel prior = MultivariateNormal(torch.zeros(dim).to(device), torch.eye(dim).to(device)) model = Flow(dim, prior, n_block) model = model.t...
ptrblck
Thanks for the update. The workaround is invalid, as you would call the underlying model on the default device and would skip the nn.DataParallel wrapper. The device mismatch is raised, since torch.distributions do not have a to() method and are not registered as modules. Here is a minimal code s…
zepp_e
Hi,I want to work with GANs and therefore started to try to move the nets to CUDA but still got some problems with it.import torch from torch import nn, optim from torch.autograd.variable import Variable from torchvision import transforms, datasets from utils import Logger print(torch.cuda.is_available()) DATA_FOLDER ...
ptrblck
In your current code snippet images_to_vectors just creates a view of the tensor and I don’t see where real_batch is pushed to the device. Your suggested approach would probably work, but it’s not necessary to rewrap the tensor into a new tensor. Just call real_batch = real_batch.to('cuda:0') befor…
vmax
In a nn.module, for a model which fuses feature maps of different strides, I am wondering if it is possible to donn.Upsample, not with thescaleparameter, but with thesizeparameter.Thissizeparameter would be dependent on which level of feature map is being upsampled, as well as the input image size which you only see du...
ptrblck
If you want to use a constant size, you could create the nn.Upsample module in the __init__ method of your model and directly use it for all images: up = nn.Upsample(size=(24, 24)) x = torch.randn(1, 3, 10, 10) print(up(x).shape) > torch.Size([1, 3, 24, 24]) x = torch.randn(1, 3, 40, 40) print(up…
coincheung
Hi,When I use python api, I can do that bytorch.set_grad_enabled(False)which switches off the graident computation globally. How could I do that with libtorch/c++ api?
ptrblck
The RAII torch::AutoGradMode enable_grad(true/false); should work as described in thedocs. auto x = torch::tensor({1.}, torch::requires_grad()); { torch::AutoGradMode enable_grad(true); auto y = x * 2; std::cout << y.requires_grad() << std::endl; // prints `true` } { torch::AutoGradMode en…
andreys42
I’m wonder is that a correct way to init weights from pickled file for my model?.PKL file was saved after last epoch of previous training of the same model (unfortunatelly, .ckpt file lost)model = FaultNetPL(batch_size = 5).cuda() model_w = torch.load('model_weights.pkl') model.load_state_dict(model_w ) trainer.fit(mo...
ptrblck
It depends, what model_weights.pkl contains. If it was stored using model.state_dict(), your approach would work. On the other hand, if it’s containing raw tensors or a custom dict etc. you would need to load it manually using the same logic which was applied while storing these values.
Victor_George
I think there is a type for the LSTMCell example given here at api doc page:https://pytorch.org/docs/stable/generated/torch.nn.LSTMCell.htmlCurrent snippet is:>>> rnn = nn.LSTMCell(10, 20) >>> input = torch.randn(3, 10) >>> hx = torch.randn(3, 20) >>> cx = torch.randn(3, 20) >>> output = [] >>> for i in range(6): ...
ptrblck
Yes, that’s right and it was already fixes in themaster docs.
mcorange
Hi everyone,I came across a problem and can not figure out which one is right and the reason:model = nn.DataParallel(model)optimizer = optim.SGD(model.parameters())##trainingcodeoptimizer = optim.SGD(model.parameters())model = nn.DataParallel(model)##trainingcodeI guess the first one is logically right, since pytorch i...
ptrblck
Both should work, since the model is pushed to the default device and the optimization will also take place on this device.This blogpostby@Thomas_Wolfexplains it in a nice way.
Deeply
I would like to try some new regularization methods and thought of using sometorchvisionmodels.I only want to work on one model; say for examplegooglenet, what is the best way to do this:1- Downloadtorchvisionfromsource, or2 - Download the whole vision fromsource, or3- Onlydownload googlenet, which I noticed won’t work...
ptrblck
The dropout is used as a module, you could replace it with nn.Identity. Alternatively, if it’s used via the functional API, you could override the forward method and reimplement it. I still think this might be the faster and cleaner approach than to manipulate the original model and rebuild torchvi…
d099f6849ae8a1462cd0
Since my network (rnn used) does not converge, I want to see the gradient of the weights of each layer. I tried using tensor.grad to get the gradient, however, the output is always None. How can I print the gradient in each layer? Thanks
ptrblck
Once you’ve called backward to calculate the gradients, you can directly print them using something like this: model = nn.Sequential( nn.Linear(10, 2) ) ... loss.backward() print(model[0].weight.grad) In your case the model definition will look a bit different. So depending how you’ve implemen…
yf19001
I want to build a model, that predicts next character based on the previous characters.I have spliced text into sequences of integers with length = 100(using dataset and dataloader).I want to predict character at each timestep.Dimensions of my input and target variables are:inputs dimension: (batch_size,sequence length...
ptrblck
As given in the docs, the class dimension should be in dim1, so this would work: output = torch.rand(batch_size, number_of_classes, sequence_length) In your training script, you could permute the output to match these dimensions.
jda
I am trying to build a feed forward network classifier that outputs 1 of 5 classes. Before I was using using Cross entropy loss function with label encoding. However, I read that label encoding might not be a good idea since the model might assign a hierarchal ordering to the labels. So I am thinking about changing to ...
ptrblck
nn.CrossEntropyLoss should be a good fit in your case. You are not really encoding the labels in a hierarchical order as this would be the case using nn.MSELoss. Instead you provide the class indices, which will be used to get the current class probability. So there is mathematically no difference…
111410
I have this sample code in file.m (compiled by Objective-C++ compiler) in Xcode iOS project (LibTorch is loaded via Cocoapods):auto param = torch::tensor({1.}, torch::requires_grad()); auto result = 1 + param; result.backward();Executing gives this error:libc++abi.dylib: terminating with uncaught exception of type c10:...
ptrblck
I think Autograd is disabled by default in the mobile backend. You might be able to build it from source and reenable it, but I haven’t tried it and am not sure if this would still be possible (it was in the past, if I’m not mistaken).
Mona_Jalal
Could you please help me with this github issue?github.com/zhanghang1989/PyTorch-EncodingFile "/home/mona/venv/torchenc/lib/python3.8/site-packages/torch/cuda/__init__.py", line 172, in _lazy_init torch._C._cuda_init() RuntimeError: CUDA unknown error - this may be due to an incorrectly set up environment, e.g. cha...
ptrblck
If a single sample is raising the out of memory issue, your GPU memory capacity might just be too small for this workload. If you have another workstation with a bigger GPU, you could try to run it there and check the memory usage for a single sample. Alternatively, you could also try to run it on…
shahbuland
help1560×918 42.1 KBI’m using autograd for the first time (as in, I’ve never gone this low level before) and I think I’m doing it wrong. I would appreciate some help on finding what mistake I’m making. The issue is as follows:A. runs every parameter update. B. runs every 4 parameter updates (in same loop as A) and call...
ptrblck
Yes, kernel launches will be added to the queue and launched when GPU resources are available. The to() operation can be executed asynchronously, so that it shouldn’t block.
Igo312
It’s hard to descript, so let’s see the example. I get a tensor like below[[[1,1],[1,1]], [[2,2],[2,2]], [[3,3],[3,3]], [[4,4],[4,4]]]the size is(4,2,2). I want to concat diffrent channel and convert it into a new tensor with size(1,4,4), but if usingviewit will like the left array, but I want to get the right format....
ptrblck
This should work: x = torch.tensor([[[[1.1,1.2],[1.3,1.4]], [[2.1,2.2],[2.3,2.4]], [[3.1,3.2],[3.3,3.4]], [[4.1,4.2],[4.3,4.4]]], [[[5.1,5.2],[5.3,5.4]], [[6.1,6.2],[6.3,6.4]], [[7.1,7.…
ericlormul
Here’s my observations:train the whole model without freezing any parameters. one epoch can finish with no problem.freeze certain parameters. it throws “transform: failed to synchronize: cudaErrorAssert: device-side assert triggered” at random point. In my case, one epoch has 1170 batches, no shuffle, sequential feed i...
ptrblck
When you enable anomaly detection, the NaNs will trigger an error. If you are not concerned about it, you could disable anomaly detection and handle the NaN values separately. The idea of using this utility is to get a runtime error in order to debug the issue. I guess that the first 600 iterati…
ysleer
I want to duplicate multiple models and train each with a different dataloader.Simply cloning the model is expected to waste that much memory.So I’m looking for a way to use memory efficiently.I know that TensorFlow has an option called reuse like variable_scope(reuse=True).Is there any way I can use it similarly in Py...
ptrblck
If I understand thedocscorrectly, the variable_scope would create new variables using the specified names (scopes). If you set reuse=True, TF would check, if a variable with this name was already created and return it instead of creating a new one (or raising an error?). with tf.compat.v1.variab…
111479
weired_conv2d997×466 12.9 KBPlease refer to the attached image.I had three non-negative tensors of float32 type, gamma: kernel for conv2d, beta: bias for conv2d, and v: an input.When convolving seperately for each instance of minibatch v, I got normal outputs of non-negative values.However, convolution over the entire ...
ptrblck
Thanks! I could reproduce this issue and guess an internal matmul kernel might run into an overflow. As a workaround, use the CUDA10.2 binaries, which ship with cudnn7.6.5.32 or alternatively you could also build PyTorch from source using cudnn8.1. I’ve forwarded the issue to the cudnn team, which…
AbaqusNastan
To normalise, in python I simply do:F.normalize(x, p=2, dim=1)I was wondering what is the libtorch c++ equivalent of this.
ptrblck
This should work: namespace F = torch::nn::functional; F::normalize(input, F::NormalizeFuncOptions().p(1).dim(-1));
ZimoNitrome
I have been trying to implement a “color quantization module” for a project but I am getting stuck.I have tried to simplify the techniques I am using to play around with what is actually possible in PyTorch.Consider:n = 10 for input, target in dataloader: output = model(input) output = (n*output).round() / n ...
ptrblck
The round operation would kill the gradient (almost) everywhere, so it’s indeed not very useful for training as seen here: x = torch.randn(10, requires_grad=True) y = torch.round(x) y.mean().backward() print(x.grad) > tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) You could try to implementthis…
nmourdou
Hello guys,I am creating a custom neural network and I want to create a linear combination of two outputs of different layers after applying a corresponding non-linearity. So for example, if x and y are the outputs of two layers and f is an activation function (relu, softpluts etc), I wish to compute:a*f(x)+(1-a)*f(y)I...
ptrblck
I think you are missing the initialization of the nn.Softplus module and might be running into this error: torch.randn(1) + nn.Softplus(torch.tensor(1.)) > TypeError: unsupported operand type(s) for +: 'Tensor' and 'Softplus' You would have to create the module first before applying it onto the te…
Harshit_Pandey
The following error arises when I add two loss functions together. On removing one of the loss functions it seems to work fine.image1619×865 62.9 KB
ptrblck
This postexplains the error. The generator was already updated, while you are trying to calculate the gradients again via d_loss.backward() using stale forward activations. Detach generated_sample before passing it to the discriminator and it should work. PS: you can post code snippets by wrappi…
Firas_moh
I have this model which has an encoder-decoder structure. I want to change the “functional.interpolate” layer (which does upsampling layer) to “functional.max_unpool2d”. But as you can see in the following code in the “colab link”https://colab.research.google.com/drive/1UHjW5tEEG-ZwIEIlPzVuZSgvGnPuKVMI?usp=sharing, the...
ptrblck
I don’t know the theoretical complexities of both algorithms and how they are implemented. If you are concerned about the performance of these layers, you could profile them via e.g. the torch.utils.benchmark utilities.
Manuel_Alejandro_Dia
Hi everyone!I just have a question regarding how can I make sure that the tensors will stay in the same device.A bit of context: I am training a YOLOv3-based detector and the code runs perfectly on one GPU. But I want to change it in order to use 2+ GPUs in the same machine using thenn.Dataparallelmodule in order to sh...
ptrblck
You could check the internal implementation and probably use the functional distributed API to send the appropriate splits to the desired device. From a general point of view: nn.DataParallel will split the tensors in dim0, so would it be possible to make sure the data and target tensors are constr…
Nanthak_R
I created a network for training on images. It uses attention on parts of the images and used a transformer encoder on the final part. But the loss.backward() times increases for each batch during training. It remains constant initial some epochs. But after that the time increases rapidly.import torch import torch.nn a...
ptrblck
Could you check if you might be running out of memory and your system might be using the swap?
yoad.tewel
Hey,Should we except any performance changes from pytorch 1.8 Cuda 11.1 in comparison to pytorch 1.7.1 with Cuda 11?And if not, what version of pytorch should give the most out of the new cards?Thanks!
ptrblck
You shouldn’t expect a lot of changes for CNNs, as both versions ship with cudnn8.0.5. Due tothis issuewe couldn’t use the cudnn8.1 release and are working on it. For the best performance on your 3070 you could build from source using the latest cudnn release.
venuv
In VAE code I am trying to run, I get the error below, where the mismatched tensors seem like the same size. The mismatch error is triggered from the code below that is trying to instantiate a Linear layer. Appreciate any pointers on how to debugRuntimeError: size mismatch, m1: [94 x 4608], m2: [94 x 4608] at …/aten/sr...
ptrblck
The error is raised, because you are not flattening the activation before feeding it into the linear layer. Once it’s flattened via out.view(out.size(0), -1), you’ll hit a shape mismatch error and would need to change the in_features of self.fc1. This code should work: class Model1(torch.nn.Module…
cthnguyen
Hello,I’m new to PyTorch and I don’t know too well Tensorflow. I am currently re-writting a code in Tensorflow to Pytorch and they use tf.nn.dilation2d. I didn’t find any function close to the tensorflow’s one. Can anyone help me ?Thanks !
ptrblck
I don’t think a dilation is implemented yet. You could unfold the image tensor and apply the max operation on each patch. Have a look atthis exampleto see how to create the patches.
fermat97
I would like to train a model in Pytorch which has been already torchscripted. I am curious if it is possible at all to do so. I think it is possible with thetorch.jit.tracebut I am not sure if it is possible with thetorch.jit.script. Any idea?
ptrblck
Yes, you should be able to train a scripted model (as long as you are able to script it).
Wilan
When importing torch, I’m getting an OSErrorDoes anyone know what may be the issue?I’ve created an environment on Ubuntu 20.04 LTS and have re-created it on 20.04.2 LTSError:OSError Traceback (most recent call last) <ipython-input-1-fd2d69af7979> in <module> 1 import os 2 i...
ptrblck
This should already be solved inthis issue.
alannnna
I am new to JIT scripting and don’t know what this error means, and have not found this zero_grad error online nor any related errors whose solutions seem to make sense here. What am I doing wrong here?The error is this (see gist for full error):Tried to access nonexistent attribute or method 'zero_grad' of type 'Tenso...
ptrblck
I think the error is raised, because scripting assumes tensors as the input, if no annotations are used as describedhere. I don’t know, if it’s possible to script the complete optimization, but you should be able to script the model at least.
MrChenFeng
Hi guys, when tested with batchnorm layers now, i was confused by something:input = torch.rand(10,5) model = nn.BatchNorm1d(5) out = model(input) print(out.mean(0), out.var(0))Here I would expect the mean be zero while var be 1 if I didn’t misunderstand the original batchnorm operation cause we havent update the gamma ...
ptrblck
I don’t think PyTorch cannot “normalize it correctly”, but batchnorm layers don’t use the unbiased variance calculation, which is probably why you might think it’s incorrect. If you want to use the biased one, you could create a custom layer by e.g. followingthis implementation.
Hwarang_Kim
output_source = model(source_image)loss_s = crossentropyloss(output_source,0)loss_s.backward()output_target = model(target_image)loss_t = crossentropyloss(output_target,1)loss_t.backward()oroutput_source = model(source_image)loss_s = crossentropyloss(output_source,0)output_target = model(target_image)loss_t = crossentr...
ptrblck
Both approaches should work. The first one would use less memory and more compute, since you would be using two backward calls (more compute), but Autograd will be able to delete the intermediate tensors from the first forward pass, as they are not needed anymore (gradients were already computed us…
Fahd_Jerbi
Hi, I’m trying to make a CNN model that use custom filters/weights. I started by using a pretrained model and changed it according to my need (figure below to better explanation of the idea). The goal is to have a 3 channels image then filter the input with all filters in each layer. I want to ask if the weights implem...
ptrblck
The model.features[0].weight parameter has a shape of [4, 3, 3] so one dimension is missing. nn.Conv2d defines the weight parameter as [out_channels, in_channels, height, width]. Based on the current code, I guess that the number of in_channels is missing? If that’s the case, you could unsqueeze …
huangh12
The following code is runnable and bug-free. I am puzzled why theself.reludosen’t need to be cast to GPU device while theself.net1andself.net1is cast to GPU. In my considering, the default device ofself.relushould be CPU if there is no explict casting. If this is correct, the output ofself.net1is on gpu, which misma...
ptrblck
nn.ReLU doesn’t contain any parameters, so nothing has to be moved to the device. Internally the functional API will be used on the input (which is already on the GPU) via F.relu. You can check for parameters in a modules via: print(dict(module.named_parameters())). Also, while this code works fi…
John_Grabner
What is the best way to combine Dataloaders that have different batch sizes and different data shapes while still preserving the multi-process capabilities of the Dataloader?dl1 = Dataloader(dataset1, batch_size=3)dl2 = Dataloader(dataset2, batch_size=5)where data from dl1data_a.shape = (3, 7) , where 3 is the batch si...
ptrblck
You should be able to iterate these DataLoaders together e.g. via zip: datasetA = TensorDataset(torch.randn(12, 7), torch.randn(12, 11)) loaderA = DataLoader(datasetA, batch_size=3) datasetB = TensorDataset(torch.randn(10, 13)) loaderB = DataLoader(datasetB, batch_size=5) for (dataA, dataB), (dat…
zhuser
I have trained several models and would like to compare their performance on a single image. The problem is that running the same model (let’s call it A) produces different results. I have set the model to evaluation mode (i.e. A = myModel.eval()) and I am using “with torch.no_grad()” yet every time I apply the model t...
ptrblck
That’s expected, as the with torch.no_grad() block won’t switch any attributes of the model parameters, but will instead make sure that new operations performed inside this block won’t be tracked. Also, if you don’t call backward() on the output or any loss tensor and optimizer.step(), the paramete…
escorciav
Does the Dataloader copy the Dataset on each worker?The documentation doesn’t use plain English. It does mention details of multiprocessing that I dunnoI assume it copies as I have done hacks to avoid unpickable objects e.g. using HDF5I gotta implement a quick & dirty hack to improve the speed of one dataset.
ptrblck
Yes, each worker would create a copy of the Dataset.
nmvr
Hello,I currently have a set of 3D nifti images that I’m loading into a Dataset object using@MONAI.However, instead of having a Dataset object composed of multiple volumes, I wish to have a 2D dataset composed of all the slices from all the volumes.Is there a way to load the data this way or change the Dataset object a...
ptrblck
This “flattening” operation can be performed by: x = torch.randn(2, 1, 32, 128, 128) x = x.permute(0, 2, 1, 3, 4) x = x.view(-1, *x.size()[2:]) print(x.shape) > torch.Size([64, 1, 128, 128]) This could be an easy way to change the input format. The alternative approach would be to open the volume…
romain
Hello, I’d like to know how to properly implement a custom initialization scheme. For the moment, I’m doing it as below, but from PRs I gather that using the.dataproperty isn’t recommended.class MyModule(nn.Module): def __init__(self, hidden_dim: int): super(MyModule, self).__init__() self.hidden_di...
ptrblck
You could wrap the code into the no_grad() guard and use the .copy_ operation to fill the parameter. If you are initializing the plain tensor before wrapping it into an nn.Parameter, you could also skip the no_grad() guard.
b02202050
Hi all,I recently tried torch.set_deterministic(True) and observe that it could reduce the GPU memory usage of backward!If I use mixed precision, the memory won’t reduce by torch.set_deterministic(True).Can anyone tell me why these happen?(My torch version: 1.7.0)*** The code to reproduce my result is as the following....
ptrblck
The memory usage could be different based on e.g. the picked cudnn algorithms, i.e. a deterministic one could use less memory but might also be slower.
banikr
Hello All,I am working on 3D data of 114 images each of dimensions[180x256x256]. Since such a large image can not be fed directly to the network, I am using overlapping patches of size[64x64x64]. Now there are around 22,000 patches in total for 114 images. which can not be loaded into theDataloaderascudamemory runs out...
ptrblck
In that case you could lower the batch size to 1 and check, if it’s still running out of memory. If that’s the case, keep the batch size at 1, split the batch in the DataLoader loop in dim0 and loop over smaller input tensors. Alternatively, you could also try to create the patches from each image…
ataxias
In all examples with optimizer parameter groups I have seen, people split parameters in disjoint groups (groups with no shared members), like this:optim.SGD([ {'params': model.base.parameters()}, {'params': model.classifier.parameters(), 'lr': 1e-3} ], lr=1e-2, momentum=0.9)However, one may co...
ptrblck
No, that should not be possible and you would get an error: ValueError: some parameters appear in more than one parameter group
Kingsmove
Issue descriptionRecently our lab set up a new machine with RTX3090, I installed GPU driver 460.32, CUDA 11.2, and pytorch throughconda install pytorch torchvision torchaudio cudatoolkit=11.0 -c pytorchThen I tested with a seq2seq model (LSTM->LSTM) I used before, training very fast, working fine.However, when I use th...
ptrblck
Thanks for the model definition! Could you post the input shapes you are using as well, please? Your local CUDA toolkit and cudnn library won’t be used, if you’ve installed the conda binaries or the pip wheels. You could indeed build from source and compare the speed. If you are seeing a speedup …
k2lin
Hi,I ran into a really peculiar situation here.I have a pretrained network (weights frozen in training) that is supposed to take plane sweep volume (essentially stack of warped images) as input and produce intermediate results for other modules in the pipeline.My plan is to run the said network twice in a training step...
ptrblck
Thanks again for the code snippet as well as the great debugging! I was able to narrow it down to a sync issue using this “minimal” code snippet: x = torch.randn(1, 2, 4, 4, device='cuda') v = 2 m = torch.randn(1024, 1024, device='cuda') res = [] for _ in range(10): psv_tgt = x[:, 0:1].repeat…
jpj
def forward(self, x): hidden_inputs = self.hidden(x) hidden_outputs = self.sigmoid(hidden_inputs) final_inputs = self.output(hidden_outputs) final_outputs = self.softmax(final_inputs) return final_outputstorch.isnan(self.features).any() # false label_predict = self.forward(s...
ptrblck
Could you check the stats of the input tensor as well as the parameters of the linear layer, which is causing this issue? E.g. if your input contains Infs or very large values in their magnitude, the result might overflow and could be set to NaN in further operations.
Smth_w
It may be a trivial question but while reading this tutorial:TorchVision Object Detection Finetuning Tutorial — PyTorch Tutorials 1.7.1 documentationI found this custom Datasetclass PennFudanDataset(object): def __init__(self, root, transforms): #random codeWhich does not inherit torch.utils.data.Dataset (e...
ptrblck
It’s not strictly necessary, as the baseDatasetimplements the __add__ method for you and defines the __getitem__, but for the sake of code clarity I would still recommend to derive your custom class from Dataset.
Dian-Shan
Hello, I am trying to optimize the part of parameters in “one” nn.Parameter variable.e.g. a simple CNN classifierclass Model(nn.Module): def __init__(self, device): super().__init__() self.resnet = ... feature_dim, n_cls = 64, 10 self.classifier = torch.nn.Parameter(torch.Te...
ptrblck
You could define separate parts of the self.classifier parameter and only pass the parts, which should be optimized, to the optimizer. In the forward method you would then have to recreate the “full” parameter using torch.cat and/or torch.stack and apply it in the matmul. Another approach would be …
morphism
Hello, how are you?I am working on Deep Learning Project whose data has lots of categorical variables.Some of them are just binary variables (0 or 1)In Deep Learning, May I ask:What is the best way to handle those categorical variables?Can Deep Learning handle those data without any transformation?And which technique o...
ptrblck
If your inputs contains categorical variables, you might consider using e.g. an nn.Embedding layer, which would transform the sparse input into a dense output using a trainable matrix. I’m unsure what the alternatives would be and if passing these values to the model might even work in your case.
ziad
Hello!I’ve built a CNN model which I’m now attempting to training using the conventional for-loop. I’ve been having an issue the past few days in which I’m not able to get the for-loop to work properly. Essentially, what happens is that the loop prints the epochs continuously until I have to interrupt.This is the code ...
ptrblck
It sounds rather like a multiprocessing issue (or code parts are executed after the training, which are not shown in the posted code). You should be able to export the notebook as a Python script file and run it in a terminal.
zs963048949
The variable ‘inputs’ is a output of net.The variable will be inputed to loss function.However,the attribute of requires_grad was changed into ‘False’ after I executed the following:inputs = inputs.ge(0.5).float()If this case,can it execute backpropagation in the network normally?If not,why? How can I solved it? Thanks...
ptrblck
No, you won’t be able to calculate the gradients after the tensor.ge operation, since it’s not differentiable and would thus break the computation graph. You could use a “soft” function such as e.g. sigmoid instead.
Samue1
I am new to PyTorch and want to better understand PyTorch’sautogradfunctionality. Therefore I implemented a tiny network with two hidden layers. The network’s architecture is as follows:n_inputs = 2 n_hidden_1 = 2 n_hidden_2 = 2 n_outputs = 2The fully connected neural networks has therefore only 8 trainable...
ptrblck
It’s expected that the clone operation would have a performance impact, since you are creating new tensors. Since your model is tiny, you might see this overhead. I would try to avoid the inplace operations and store the results of the torch.sigmoid calls into a new tensor instead of the a “placeho…
mkserge
Hi,(I have combed through the similar topics on the forums and unfortunately still cannot find a solution for my problem)(venv_a100) [sergey_mkrtchyan@a100-demo cformers]$ nvidia-smi Thu Feb 18 17:10:56 2021 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 460.32.03 Driver...
ptrblck
Yes, that is the expected behavior.This postexplains it a bit more.
Laura_Montalvo
**Hi there! **I have a custom dataset in which (even though I have more or less the same number of samples for each class) it missclassified some of the data for some specific classes. So what I’m trying to do is oversample by using “sampler” in the dataloader and WeightedRandomSampler as follows:from sklearn.utils.cla...
ptrblck
Which sklearn version are you using, as I’m getting an error running your code with random target data: targets = np.random.randint(0, 100, (100,)) class_weights = compute_class_weight('balanced', np.unique(targets), targets,classes=np.arange(NUM_POSITIONS)) > TypeError: compute_class_weight() got …
Gwon
Hi, I have a questions about NVIDIA apexI know NVIDIA apex package creates each process per gpu, like thisimage718×195 4.14 KBso, each process are referred as local_rank variable in my codeI want to save best accuracy from each process and i coding like belowWhen i Using 2 gpusfor epochs in range(0, args.epoch): tra...
ptrblck
We recommend to use the native mixed-precision training utility viatorch.cuda.ampinstead of apex, as it should cover more tested use cases. More information can be foundhere.
miturian
I am a beginner, who have jumped into the deep end, and am trying to learn things that way. I have tried to find answers by using the official resources, but I feel like if you’re not trying to classify mnist, then the tutorials are less useful (and I already got my first toy network to work). So, after staring into th...
ptrblck
I’m unsure where the 29 comes from. Do you mean 129 or 20 or are the “29 columns” created in a special way? If it’s a typo and you would like to use the 20 channels as the temporal dimension, you could initialize the RNN via batch_first=True, which would expect an input in the shape [batch_size, se…
morphism
Hello,I am studying dropout algorithmI am implementing dropout using Python or Julia.If I have two hidden layers and dropout ratios are 0.5, 0.3 respectively,Then how much ratio should I multiply to the output when evaluating?Also, should (may) I multiply some ratio (such as 1/(1-p) for some appropriate p) to the outpu...
ptrblck
PyTorch scales the activation during training with the inverse as seenhere. This inverse scaling is mentioned in the original dropout paper (if I’m not mistaken) and allows you to just disable the dropout layer during evaluation.
Alfred
Hi, I have to define a new layer, which does the following:Given an input x (vector with N elements), and a NxM matrix W, I want as an output W^T(ReLU(Wx)), where W^T is the transpose of W. What I have is the following:class AML(nn.Module): def __init__(self, in_features: int, out_features: int,n: int) -> None: ...
ptrblck
The code looks generally alright, but I would not use torch.Tensor to create the initial parameter, as it will use uninitialized memory and will contain whatever was stored in the memory you are using. This would also mean that it might contain NaN values etc. Use the factory methods, such as torc…
nbansal90
Hi All,I am usingtorch.nn.DataParallelfor the model in multiple gpu setup (4 GPUs)as defined below and find that there is some mismatch between theinputandweight. I am using the followingModulefor aDecoderkind of a network.class DepthDecoder(nn.Module): def __init__(self, num_ch_enc, scales=range(4), num_output_cha...
ptrblck
Thanks for the update. The issue is raised, because self.convs is using and OrderedDict instead of an nn.ModuleDict, which will not properly register these modules. Change it to the latter and adapt the indexing, as nn.ModuleDict expects strings (e.g. to "upconv{}{}".format(i, 0)). Also, note tha…
ysleer
hiI am trying to train a model using multiprocessing.In the example below (Multiprocessing best practices — PyTorch 1.6.0 documentation), model.share_memory() is used.import torch.multiprocessing as mp from model import MyModel def train(model): # Construct data_loader, optimizer, etc. for data, labels in data...
ptrblck
TheWikipedia articleexplains shared memory maybe a bit easier to understand. It’s basically a memory pool, which can be used by multiple processes to exchange information and data.
yoko
I tested to create cost volume(stereo depth estimation)then I tried to evaluate 2 method belowwhat makes time that differ?start_full_time = time.time() B, C, H, W = refimg_fea.shape cost = refimg_fea.new_zeros([B, 2*C, self.maxdisp//4, H, W], requires_grad=False) print('time = %.4f [s]' %((time.time() - start...
ptrblck
Yes, you would be profiling the CPU calls and kernel launch, not the actual data transfer or any workload on the GPU as it’s executed asynchronously and the CPU can run ahead and stop the timer, while the GPU is still busy.
nbansal90
Hi Everyone,I am using 4 GPUs for training a model, which was earlier being trained on single gpu, for leveraging the data parallelism and speeding up the training process. For my code, I have set the batch size as 8, and was expecting that while training on 4 GPUs the data would evenly distribute among the 4gpus as in...
ptrblck
I don’t quite understand the “each element of the list (which is a tensor) has to shared across multiple gpu(in Dataparallel case)”. nn.DataParallel will split the input tensor in dim0 and will send each chunk to a GPU. The elements won’t be duplicated, which implies the “sharing”. Since the list …
Samuel_Bachorik
Hello please, iam using this model for segmentation and i need to initialize weights bytorch.nn.init.xavier_uniform_can someone show me please how can i do it on this model ?def double_conv(in_channels, out_channels): return nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, padding=1), torch.nn...
ptrblck
You could write a weight_init method and apply it on the model: def weight_init(m): if isinstance(m, nn.Conv2d): print('initializing conv2d weight') torch.nn.init.xavier_uniform_(m.weight) model.apply(weight_init)
ayrts
Hello, I built Pytorch from source and installed in develop mode for making open-source contributions. However, I noticed that when I have to update my local repository to keep up-to-date with the main repository, I have to re-install Pytorch in develop mode as stated in the contributing doc by runningpython setup.py d...
ptrblck
You could set the MAX_JOBS env variable to a specific number to reduce the CPU workload.
dcl
import torch from torch import nn from torch import functional as F class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv = [nn.Conv2d(1, 20, 5)] self.conv.append(nn.Conv2d(20, 20, 5)) def forward(self, x): x = F.relu(self.conv[0]) ...
ptrblck
You would have to use nn.ModuleList instead of a Python list to make sure the submodules are properly registered inside the Model.
Muhammad4hmed
I am trying to run following implementation:GitHub - Lotayou/everybody_dance_now_pytorch: A PyTorch Implementation of "Everybody Dance Now" from Berkeley AI lab.As mentioned on repo, their requirements areUbuntu 18.04 (But 16.04 should be fine too)Python 3.6CUDA 9.0.176PyTorch 0.4.1post2So Installed above using:!pip3 i...
ptrblck
The error is raised in the old THCudaMalloc callhere, so I guess that your current (CUDA) setup is not working correctly. It’s a bit hard to tell what the reason might be, as 0.4.1 was released in July 2018. The probably better approach would be to try to update the repository and make it compati…
Nolan_Cardozo
Hi everyone, I recently came across the paper on “Squared earth mover’s distance-based loss for training deep neural networks.” ([1611.05916] Squared Earth Mover's Distance-based Loss for Training Deep Neural Networks). I want to use the squared EMD loss function for an ordinal classification problem .However, I could ...
ptrblck
You could try to translate this code by using the torch namespace. E.g this might work (untested): def earth_mover_distance(y_true, y_pred): return torch.mean(torch.square(torch.cumsum(y_true, dim=-1) - torch.cumsum(y_pred, dim=-1)), dim=-1)
Nolan_Cardozo
Hi everyone,I have come across multiple examples that illustrate the working of a CNN foe classification tasks. However, there is very little out there that actually illustrates how a CNN can be modified for a regression task, particularly a ordinal regression tasks that can have outputs in the range of 0 to 4.I unders...
ptrblck
I think you could use a single output unit in the last layer via: model.fc = nn.Linear(fc_in_features, 1) and use nn.MSELoss directly by providing the target in the shape [batch_size, 1] containing the class indices. As you said, you would usually use e.g. nn.CrossEntropyLoss, but if your target …
Dagenham
Hi, I’m doing a policy gradient method in PyTorch and wanted to move the network update into the loop but it stopped working. I’m still a PyTorch newbie so sorry if the explanation is obvious. I’m using PyTorch 1.6 (built from source).Here is the original code that works fine:self.policy.optimizer.zero_grad() G = T.ten...
ptrblck
Yes, that’s correct. Additionally to this the intermediate activations were also calculated using the “old” parameters. The backward pass would use the new parameters with the old intermediates to calculate the gradients for the new parameters, which would be wrong. Yes, that would be an alternat…
PhysicsIsFun
Dear community,if I create my batch collection of a data set usingbatches = torch.utils.data.DataLoader(train_set, batch_size=bs, shuffle=True)will any data point appear in exactly one batch? I.e. is the sum of batches equal to my entire data set?Or is each batch independently sampled from the entire data set, and it c...
ptrblck
If you are using the shuffle option in the DataLoader, a RandomSampler will be created as seenhere. This sampler sets replacement argument to False by default so that a random permutation will be applied as seenhere. This makes sure that each sample is only drawn once in this setup. Note that …
omarfoq
HelloWhen printing an optimizer instance, we get a list of parameter groups, which is normal, however I can’t find the__str__and__repr__methods in Optimizer class or in its children. Do you you know where is the script responsible for this print.
ptrblck
This __repr__ methodshould be used.
ResidentMario
Thetorch.jit documentationstates that one of the limitations of tracing is that calls which differ based on whether the model is intrainorevalmode will only ever use whatever mode the module was in at trace time. Specifically:In the returnedScriptModule, operations that have different behaviors intrainingandevalmodes w...
ptrblck
If might be a bad idea, if you would like to switch the behavior of the traced model. In that case you could try to script your model.
Loud_BoomBox
Hi,I am running into the following problem -RuntimeError: Tensor for argument#2‘weight’ is on CPU, but expected it to be on GPU (while checking arguments for cudnn_batch_norm)My objective is to train a model, save and load the values into a different model which has some custom layers in it (for the purpose of inferenc...
ptrblck
Based on the error message I guess that either Net or Normie_net is raising this error, since these are using batchnorm layers. In your custom conv layer you are hardcoding the device of the tensors to be CUDATensors, so I assume the output will also be on the GPU. Based on your code, conv_model sh…
rubijade
Hello guys.I am new to PyTorch and I am implementing a two-stream action recognition architecture.For each of them, I have a CNN and at the top an Lstm.My question is how can I pass the feature extracted from the CNN to the LSTM as input. I am confused a little bit.Any guidance from you guys will be so helpful for me. ...
ptrblck
Or course it depends on your actual use case, but you could treat the height and width of the CNN output as the temporal dimension and the channels as the features and pass it to the RNN. By default the RNN modules expect an input in the shape [seq_len, batch_size, features] and you could use batch…
EvilSKy
Hi,Normally one would use a forward pass to calculate a loss and then perform a backward pass and the gradient is automatically calculated.My situation is that I don’t have the loss but I have the gradient calculated. My question is how do I set a custom gradient to a network (fully connected) and run the backward opti...
ptrblck
You can pass the gradient directly to the backward operation as an argument: output.backward(my_grad).
FelixLe
I have 4 GPUs:gpus = list(config.GPUS) gradient_loss = GradientLoss model = nn.DataParallel(model, device=gpus).cuda()Gradient loss is computed as below:class GradientLoss(nn.Module): def __init__(self, channels=3): super(GradientLoss, self).__init__() pos = torch.from_numpy(np.identity(channels, d...
ptrblck
Are you using the GradientLoss inside the nn.DataParallel module? If so, remove the cuda() operations from the GradientLoss.__init__ method, register the tensors as buffers via torch.register_buffer, and nn.DataParallel should be able to clone this module to all passed GPUs.
Mahmoud_Abdelkhalek
ContextI’m currently trying to implement the following architecture:Screenshot 2021-02-12 210143598×743 5.86 KBWhere x is an audio signal, h_\theta is a linear filter, f_\phi is a network that predicts one of two classes, either y_hat = 0 or y_hat = 1, and g_\psi is an autoencoder that attempts to reconstruct x as x_\h...
ptrblck
Could you make sure that the log operation returns valid outputs, e.g. that x is not zero? Given that spec(x) can be zero, would it also be possible that complex_norm and mel return zeros? If so, then torch.log(torch.zeros(1)) would return tensor([-inf]), which might raise this issue in the backwa…
wallyxie
Hi,Newbie question.Suppose I havetest_short = torch.rand([1, 1, 3]) test_long = torch.rand([5, 100, 3])If I want to appendtest_shortto the beginning oftest_longsuch that I repeat the elements oftest_short5 times and end up with a third tensor oftorch.Size([5, 101, 3]), how would I go about that in the most concise mann...
ptrblck
Your code looks correct to me and I’m not aware of a better way to write it.
marcortiz11
Hey community!I’ve recently been studying a very simple case where I index a CUDA tensor in GPU. As far as I know, the indexing operation is adapted for GPU execution with potential speedups regarding CPU.In the small example below, I access elements in tensoraaccording to the mask tensorb. I have both the indexed tens...
ptrblck
I agree with@googlebotwhat capturing the profiling information would be confusing and bad. Note that your current code snippet uses a BoolTensor to index a, which will yield a variable sized output tensor (in your example you are using torch.ones_like, so all values would be returned). This woul…
cpeters
I have a convolutional autoencoder, where the output layer is:self.t_conv5 = nn.ConvTranspose2d(128, 3, 3, stride=2, padding=1, output_padding=1) ... x = torch.sigmoid(self.t_conv5(x))and the loss criterion is given bynn.BCELoss(). When trying to utilise autocast for fp16 conversion, the error that BCEL...
ptrblck
If I understand the workflow correctly, you are now feeding the raw logits to nn.BCEWithLogitsLoss, which yields the same loss as in the float32 training, and use the output = torch.sigmoid(model(images)) tensor only to visualize the samples? If so, do you see any difference by converting the outp…
manthan3C273
I’m doing image prepressing during training as below:im_transform = transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ] ) im = Image.open('/content/image.jpg') # unify image channel to 3 here im = im_transform(im) # add mini-batch dim here im = F.in...
ptrblck
The interleaving in the processed image is most likely created by a view or reshape operation using a wrong memory layout (channels-last vs. channels-first). I assume this operation might cause the trouble: im_np = im_np.reshape((im_rh, im_rw, 3)) Could you check the shape of im_np before applyin…
nobodykid
Hi,Recently, I’ve been facing the same issue as inHow to fix Mismatch in shape when using .backward() functionOriginally, I usetorch(.cuda).FloatTensorto create the tensor. Comparing it to the solution on the post, this is what I got# using FloatTensor a_one = torch.FloatTensor(1) a_one >>> tensor([0.]) a_one.dtype >>>...
ptrblck
The short answer is: don’t use torch.FloatTensor to create tensors, but stick to the factory methods, such as torch.randn, torch.ones, torch.empty, torch.tensor, etc. The former approach might have unexpected behavior (as see in this topic), could yield an uninitialized tensor (as explained by@Dwi…