user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
Aryan_Asadian
Hi. I have created a multi-module model by using add_module method.First I defined an empty class model:class EmptyModel(nn.Module): def __init__(self): super(EmptyModel, self).__init__() def forward(self, x): return x empty_model = EmptyModel()Then I add modules from another previously define...
ptrblck
This is expected, since the forward method was never changed. Even though you were adding valid modules via add_module to empty_model, they will never be used in: def forward(self, x): return x
yhkwon
Hi guysI’m doing a conditional sampling test from the results of the networkFor example,cond = torch.where(x> 0)x[cond].meanIf the condition condition is not satisfied in a specific batch, 0 data is sampled from x and the mean is calculated, resulting in nan.The solution, in my opinion, is to give each condition to the...
ptrblck
I think checking for an empty output before applying the mean operation sounds like a simple and valid solution. What kind of solution are you looking for and would the check not work for you?
Ameen_Ali
Hellosaying that I have a conv2d layer, I know that its a special case of a Linear layer, how can I convert a Conv2d Layer to Linear?for example :Conv2d(96, 1000, kernel_size=torch.Size([10, 10]), stride=(1, 1))
ptrblck
You could unfold the input to apply the im2col transformation and reshape the kernels to the kernel matrix as explained inthis blog postby Pete Warden.
zcajiayin
I have a batch of data:[[0.1, 0.3], [0.5, 0.2], [0.7, 0.8], [0.6, 0.6], [0.2, 0.9]]I have two networks,mlp1()andmlp2()How can I process the data[0.7, 0.8]and[0.2, 0.9]withmlp1(), and the rest withmlp2()to get:[mlp2([0.1, 0.3]), mlp2([0.5, 0.2]), mlp1([0.7, 0.8]), mlp2([0.6, 0.6]), mlp1([0.2, 0.9])]Any suggestio...
ptrblck
Assuming you have precomputed the indices, which would be used for the splitting, you could recreate the order by indexing into the result tensor: x = torch.tensor([[0.1, 0.3], [0.5, 0.2], [0.7, 0.8], [0.6, 0.6], [0.2, 0.9]]) …
entslscheia
In PyTorch, we can pass parameter groups when initializing an optimizer. This is a very useful feature. For example, we can specify parameters in different layers into different groups to have separate learning rate for each layer.However, is it the only way to achieve this? If we just create separate optimizers to opt...
ptrblck
This should be the case, as the step function iterates all groups, as you’ve already pointed out. As a quick test you could seed the code properly and compare both approaches (different param_groups and different optimizers), which should yield the same weight update and states.
DoKyung_Lim
i have four image dataset. full image, face image, face-mask image, landmarks imagein develope vae, my goal is encode full image and reconstruct image is each face, face-mask, landmarks imagebut when i load dataset using custom dataset and dataloader, each dataset shuffled but not corresponding imageis any way to get s...
ptrblck
If you are trying to sample data from multiple datasets, I would recommend to wrap all these unshuffled dataset in a custom Dataset and shuffle this “wrapper” dataset: class MyDataset(Dataset): def __init__(self, datasetA, datasetB): self.datasetA = datasetA self.datasetB = data…
ddguoll
The code is given below. How can the variable computed in the previous epoch be used forcomputing the loss function in the next epoch?for epoch in range((args.start_epoch+1), args.epochs):for input, target in train_loader:target = target.cuda()input=input.cuda()input_var = torch.autograd.Variable(input)target_var = to...
ptrblck
Even though you are calculating the center manually, does Autograd need to backpropagate through these operations? Compare it to the target of a classification use case. While the target tensor is of course not a constant value, it’s a constant in the sense that Autograd will use it to calculate th…
ftamur
Hello Everyone,I have encountered the error:RuntimeError: cuda runtime error (38) : no CUDA-capable device is detected at /opt/conda/conda-bld/pytorch_1565272271120/work/aten/src/THC/THCGeneral.cpp:50I tried many things I have seen on the internet but I could not solve my problem.I am working on a high-performance clus...
ptrblck
Could you update to the latest stable PyTorch release and retry the code? The error message seems fishy, as apparently PyTorch detects the device in the posted script.
Mrig
I wanted to create an ensemble learning model, where I retrain the same custom model over the different size of the image. Is it possible?
ptrblck
No, you don’t need to add the adaptive pooling layer at the beginning of the model. vgg16 uses this layer internally before feeding the activation to the linear layer inthis line of code. You can just use different shapes: model = models.vgg16() x = torch.randn(1, 3, 224, 224) out = model(x) …
xen
Hi,I’m trying to run code from the following github repository:https://github.com/AnticipatedLearningMachine/Anticipated-Learning-MachineIn the requirements section at the bottom, it says that pytorch 1.2.0 and CUDA 10.2 are required. I have tried installing pytorch 1.2.0 (on Windows Anaconda) via pip, but I get a vers...
ptrblck
I don’t think that the PyTorch 1.2.0 binaries and wheels were built with CUDA10.2, but with CUDA9.2 and CUDA10.0 as seenhere. If you need this config for a particular reason, you would most likely have to build PyTorch from source.
Nagaraj_S_Murthy
I’m using a pretrained resnet. My input image data contains 4 channels and they are of size 256x256. I have used an initial convolutional layer that accepts 4 channels and gives out 3 channels. After this, I have used transforms to resize the image to 224x224, so that it can be passed to the resnet block. However, whil...
ptrblck
This error is raised, if you try to pass a 4-dimensional image tensor to transforms.ToPILImage(), i.e. if it contains the batch dimension. To avoid this you would have to call this transformation in a loop for each tensor. Note however, that this approach would break the computation graph and your…
David_Alford
I am reading in the bookDeep Learning with PyTorchthat by calling thenn.Module.parameters()method that it will call submodules defined in the module’sinitconstructor. To understand and help visualize the processes I would like to use an ensemble as an example fromptrblck:class MyEnsemble(nn.Module): def __init__(se...
ptrblck
Yes, you are correct that the gradients won’t be calculated for parameters, which are using requires_grad=False. However, model.parameters() would still return all parameters, if you are not filtering them out.
shangguan91
Dear all,After running the model, how could i save the result and then calculate the best accuracy on certain epoch and average accuracy in python? is there some way to load the result into excel as well?image802×648 15 KB
ptrblck
Depending how the results should be stored you could: store the print output in a text file using plain open() calls and append the strings, store the tensors via torch.save() transform the tensors to numpy arrays via tensor.numpy() and either store it using a numpy method or create a pd.DataFram…
Infinite_Warp
I was trying the coding implementation of a research paper Attention Aware Polarity Sensitive Embedding for Affective Image Retrieval. I found this code on github:Coding Implementationprint("check point ---2") print(len(self.base._modules)) for name, module in self.base._modules.items(): print(name) ...
ptrblck
Forward hooks would work fine and I don’t think the hooks themselves create the increased memory usage. Based on the code snippet you’ve provided it seems you are executing the forward method sequentially using the child modules of the base model, which could yield the OOM error. If the model is w…
Donato_Caf
Hi, I’m new in the pytorch world and so I need help.I need to create a dataset loading multiple files stored in disk (for a total go 35 GB).Each file contains numpy array representing images pixels of shape (5000, 256, 256, 3).How can I achieve the dataset creation loading these data?I’m sorry for the lack of informati...
ptrblck
The CSV approach would be easier to implement and would allow a complete dataset shuffling, so I would recommend using it.
alameer
Is there a method available to find the best training parameters such as Epoch, learning rate, and batch size for a deep learning model? How do people go about find those values, please?
ptrblck
I think usually these hyperparameters are determined heuristically, i.e. by testing a lot of values or finetuning “good known” values. There are some approaches to automate this, such as FasiAI’s learning rate finder. Also, the general approach would be “learning to learn” or meta learning and is a …
Hari_Krishnan
I am trying out Wasserstein Autoencoders from the followingGitHub repositoryIt worked fine on the CPU. I made slight modifications to run it on GPU and the code started throwingCUDA error: an illegal memory access was encounteredBelow given code contains the network architecture and the training loop## create encoder m...
ptrblck
Thanks for the code. Your z tensor is on the CPU, while the discriminator is on the GPU. While I can reproduce this error in 1.6.0, it seems to have been fixed to a proper error message in the latest nightly binary (tested with 1.7.0.dev20200829): RuntimeError: Tensor for argument #2 ‘mat1’ is o…
Thabang_Lukhetho
I get this error when I load a model from disk. Pytorch version 1.4ImportError: cannot import name 'Optional' from 'torch.jit.annotations'
ptrblck
This error is usually raised, if you are using a newer torchvision version with an older PyTorch version, which doesn’t support the needed utilities in the torchvision model. Make sure to update both libraries to their latest stable release (or matching versions, if you need an older one).
Hari_Krishnan
Hello everyone,I have a tensor of size (batch_size, seq_length, embed_dim) and after passing through a linear layer I would like to get an input of (batch_size, latent_dim). The part of the code is shown belowclass TransformerEncoder(nn.Module): def __init__(self, head, embedding_size, pos_embed, latent_dim =...
ptrblck
Thanks for clarifying the shapes. In that case you could try to apply padding to the input and use the max. expected size.
Anej_Sterle
Hi guys, I’m new here and I have a problem. I have a tensor with datamatand an empty tensor of the same shape. I also have a 1D index tensor ‘ind’, which has indices of slices I want to copy. What I want to do is to look at index of a slice I want and put it in the same spot in the empy tensor.mat = torch.arange(0,16)....
ptrblck
Your code seems to be working fine, if you get rid of the type mismatch error by calling float() on matmat = torch.arange(0,16).reshape(4,2,2).float() empty = torch.zeros((4,2,2)) ind = torch.tensor([0,2]) empty[ind] = mat[ind] print(empty) > tensor([[[ 0., 1.], [ 2., 3.]], …
Parlak_Sair
this is a part of the network i’m creating where the numbres presente the numbre on feature maps. This is the code i proposed:self.last_one_down_1=nn.Sequential( nn.BatchNorm2d(num_features=512), nn.ReLU() ) self.last_one_down_2_p1=nn.Sequential( nn.Conv2d(in_channels=512,o...
ptrblck
nn.PixelShuffle will change the number of output channels as described in thedocs: Input: (N, L, H_in, W_in) where L= C * upscale_factor**2 Output: (N, C, H_out, W_out) where H_out = H_in * upscale_factor and W_out = W_in * upscale_factor In your case, upscale_factor=2, so the input channels a…
Sayeed_Shaiban
The code-def train_model(n_epoch, data): Encoder.train() Decoder.train() best_acc1 = 0 iter = 0 for epoch in tqdm(range(n_epoch)): for i, (images, labels) in tqdm(enumerate(data['train'])): if torch.cuda.is_available(): images = images.cuda().float() labels = labels.cuda() els...
ptrblck
As@smthsuggested, the error is raised by an out-of-bounds indexing. Based on the stack trace it seems that your model output contains logits (or log probabilities) for 2 classes, while the target uses a class index of 2, which would assume at least 3 classes. nn.CrossEntropyLoss and nn.NLLLoss e…
ParthTrehan
I have an input tensor like x = torch.rand(2,3,13,224,224) and after passing through this tensor from my model I get an output shape as torch.Size([2, 512, 13, 14, 14]). I then further want to reduce 14x14 to 1x1 so it looks like this torch.Size([2, 512, 13, 1, 1]) and then have a max of the 13 features to get an outpu...
ptrblck
Your code looks alright. Alternatively, since your desired output shape after the average pooling operation is [batch_size, 512, 13, 1, 1], you could also directly apply the mean() operation on dim3 and dim4 in a similar way as you’ve already done for torch.max (but this should yield the same outpu…
ygl
Hi, I have the data like below,txt_features = np.array([[1,2,3], [4,5,6]])num_features = np.array([[1,2,4], [4,5,7]])I want to pass it into a lstm. So how do I reshape the data to c, which is shown below, so that I can feed it into a lstmc = [[[1,2,3], [1,2,4]],[[4,5,6], [4,5,7]]]
ptrblck
You could use torch.stack as seen here: txt_features = torch.tensor([[1,2,3], [4,5,6]]) num_features = torch.tensor([[1,2,4], [4,5,7]]) c = torch.stack((txt_features, num_features), dim=1)
doctore
Hi, I have large evaluation data set, which is the same size as the training data set and I’m performing the validation phase during training to be able to control the behavior of the training process.I’ve added automatic mixed precision in the training phase, but is it safe to wrap the validation step in the training ...
ptrblck
Yes, you can also use autocast during the validation step and wouldn’t need to apply the gradient scaling, since no gradient are calculated in this phase.
ilkarman
I would like to route different observations within a batch to a different pre-processing head (small NN), then all of them go through the same backbone-CNN. I thought I could achieve this like so using ModuleDict:class NNSandwich(nn.Module): def __init__(self, num_heads): super(NNSandwich, self).__init__()...
ptrblck
Both approaches should yield the same result and I assume your models might have used different layer parameters. This code snippet shows that the different forward implementations create the same gradients up the floating point precision: import torch torch.manual_seed(0) import torch.nn as nn im…
Aryaman_Sriram
So I downloaded a trained model’s weights and loaded it using torch.load(). But I am unable to directly run inference on it since it says it is unable to reference the class of the model. Keep in mind I am not loading the state dict of the model but the whole model itself. Why do I still need to explicitly define the m...
ptrblck
I think this is a limitation of the Python pickle module e.g. as describedhereat the bottom of the page.
Rafael_R
Are these operations fundamentally different?
ptrblck
reshape tries to return a view if possible, otherwise copies to data to a contiguous tensor and returns the view on it. From thedocs: Returns a tensor with the same data and number of elements as input , but with the specified shape. When possible, the returned tensor will be a view of input . Ot…
shangguan91
is there any way to solve the annotation of overlap, or increase the size of chart, or the range of X-axisimport matplotlib import matplotlib.pyplot as plt import numpy as np label_list=['PointNet', 'PointNet++', 'EdgeConv', 'PointCNN', 'Convpoint', 'LightConvPoint', 'SplineCNN', 'RSConv'] y1 = [90, 90, 85, 90, 95, 9...
ptrblck
This seems to be a matplotlib-specific question so I would recommend to post it on StackOverflow, where you would probably get a faster and better answer.
puneeth2001
I understood that we need to move to gpu, but why do we need to move to GPU it’s not the case with keras and all right?I am learning to to transfer learning from a tutorial and I found this.
ptrblck
Keras might transfer the model parameters and data automatically for you behind the scenes, while you are responsible to do it in PyTorch. I guess it comes down to balance “convenience vs. flexibility” and I personally like to manually specify which tensor is places in which device, which e.g. enab…
adamce
I followed the tutorial to create custom c++/cuda extensionshttps://pytorch.org/tutorials/advanced/cpp_extension.html.What I have works locally (only 1 pytorch capable GPU), but I have problems running it on our cluster with 4 GPUs per node:when I start learning, I see in nvidia-smi, that 4 python processes use GPU 0. ...
ptrblck
I was wrong and a device guard is needed for custom CUDA extensions. Here is the diff to make the example executable on a non-default device: diff --git a/cuda/lltm_cuda.cpp b/cuda/lltm_cuda.cpp index 2434776..62c9628 100644 --- a/cuda/lltm_cuda.cpp +++ b/cuda/lltm_cuda.cpp @@ -1,5 +1,5 @@ #inclu…
pinazawa123
Hello,I’m currently working on a NLP multi-class classification problem, where I have an unbalanced dataset.After some research, I found out that usingWeightedRandomSampler, I could avoid the problem of always having the same biggest class being trained and predicted over and over again, with only sometimes other class...
ptrblck
I don’t think applying a weighted sampling to the validation and test data would be a valid step. In my opinion the validation dataset is a proxy of the test dataset and should give you a signal how well your model would perform an new unseen data and can be used for e.g. early stopping. Once you…
Richard_Wang
I recently know insidetorch.manual_seed(seed), it callstorch.cuda.manual_seed_all(seed), which sets the seed for generating random numbers on all GPUs.This brings me a question.If I launch program A (usetorch.manual_seed(3)) on cuda:0 and then program B (usetorch.manual_seed(5)) on cuda:1, (Both are on the same machine...
ptrblck
If both scripts are started independently (e.g. in other terminals), the seeds shouldn’t have any influence, as the python programs won’t interact with each other.
kkonstantinidis
Consider the following piece of code to fetch a data set for training fromtorchvision.datasetsand to create aDataLoaderfor it.import torch from torchvision import datasets, transforms training_set_mnist = datasets.MNIST('./mnist_data', train=True, download=True) train_loader_mnist = torch.utils.data.DataLoader(trainin...
ptrblck
Since you are only reading the files, there shouldn’t be any interactions between the processes. Yes, different seeds should result in a different shuffling.
puneeth2001
since = time.time() best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs - 1)) print('-' * 10) # Each epoch has a training and validation phase for phase in ['train', 'val']: ...
ptrblck
If seems you’ve initialized the model to output only 2 classes instead of 28: model_ft.fc = nn.Linear(num_ftrs,2) so you might want to change the out_features to 28 for the last linear layer.
Amasu
Hi I am having problem while converting rgb mask of shape [224,224,3] to mask of shape [224,224,3]. I have attached the code below.I am getting masks of shape [224,224,classes] but lose information of classes in channels only one channel has some mask will others don’tCode:class CamVid_Dataset(): def __init__(self,...
ptrblck
Since your current mask is a one-hot encoded tensor (each channel represents a class, where 1 denotes an active class), you could transform it into the desired class mask via: target = torch.argmax(mask, dim=1) Note that dim=1 is used, if your channel dimension (class channels) is in dim1.
marioo
Hi,I have a bottleneck on the dataloading during training. I run cProfiler and these are the results:1 0.012 0.012 1820.534 1820.534 models.py:15(fit) 56 0.001 0.000 1808.163 32.289 dataloader.py:775(__next__) 52 0.001 0.000 1807.264 34.755 dataloader.py:742(_get_data) 392 0...
ptrblck
Have a look atthis post, which explains some potential bottlenecks and workarounds.
jamesbond007
I would like to know about the ways to create a computational graph image from PyTorch code?One way is using the SummaryWriter in Tensorboard.Is there any other way to create this? Are any other packages/libraries available?
ptrblck
torchvizcan also be used to visualize the computation graphs.
mohammed_guermal
hi,I have a problem when going from tensor to numpy for instance when i use this :‘’‘transforms.ToTensor()’‘’then i conver my tensors to arrays to plot them i get an image where i have the same image repeatedhowever when i use “” ((torch.from_numpy(image_1))“”" I get the correct answer.My problem now is that my Neural ...
ptrblck
Most likely you are reshaping/permuting in a wrong way. Usually these kind of interleaved outputs are created, if you wanted to swap some dimensions and have used view/reshape instead of permute. Could this be the case?
pytorcher
I have a backward hook function with ‘newLayer.register_backward_hook(hook_function)’ where I do not know how to control the inputs to it. The function contains a line like.def hook_function(self, grad_input, grad_output): self.average = self.average * 0.99 + grad_output[0].sum((0,2,3)) * 0.01This results in:Runti...
ptrblck
I don’t know how self.average is initialized, but would assume this should work: self.average = self.average.to(grad_output[0].device) * 0.99 + grad_output[0].sum((0,2,3)) * 0.01 Could you check it and see, if you are still getting an error? In that case, could you post a small code snippet to re…
ONTDave
There is some chatter online that I can’t deepcopy a model… Is this right?Additionally, is there a way after loading a model to move it between cpu and gpu?
ptrblck
You can deepcopy a model: model = nn.Linear(1, 1) model_copy = copy.deepcopy(model) with torch.no_grad(): model.weight.fill_(1.) print(model.weight) > Parameter containing: tensor([[10.]], requires_grad=True) print(model_copy.weight) > Parameter containing: tensor([[-0.5596]], requires_grad=…
sunggu_kyung
I’m interested in SWA so I’m trying to use it, but I don’t know what to use. I don’t know the difference between the following blogs and docs swa.which one is the lastest version of SWA torch.optim.utils_swa or torchcontrib.SWA and what is the difference?blog:https://pytorch.org/blog/stochastic-weight-averaging-in-pyto...
ptrblck
SWA was added into PyTorch 1.6 inthis PR, so it looks as if the contrib implementation was merged into the core.EDIT:Hereis also the blog post.
tcsn_wty
I’m doing NLP projects, mostly using RNN, LSTM and BERT. I’ve never systematically learned PyTorch, and have seen many ways of putting data into torch tensors before passing to neural network. However, it seems that different ways sometimes can also influence the training process. I would like to know if anyone happen ...
ptrblck
I don’t know exactly what difference you would like to highlight. In the first approach train_inputs and train_labels seem to be undefined (as well as validation_x), so I assume you would like to use x_train etc.? Also, the DataLoader loop is different, since you are unpacking the values in the fi…
nicolalandro
Someone know what version of ImageNet are used to train the torchvision pretrained models? I do not find it into documentationhere.
ptrblck
They were trained onILSVRC2012and were not retrained, if I’m not mistaken.
Capo_Mestre
Hello,I have defined a densenet architecture in PyTorch to use it on training data consisting of 15000 samples of 128x128 images. When I want to train a densenet network, I get this error-stack:RuntimeError Traceback (most recent call last) <ipython-input-40-6dace5fb9ac5> in <module> 11...
ptrblck
It’s hard to tell, if the issue might be CPU or OS - dependent (or might be triggered by any other issue). What is concerning is that the previous issue was apparently solved after using the terminal instead of Jupyter, your local environment might also be “broken”. Could you create a new virtual …
gil_fernandes
Even though I think my code calls theoptimizer.stepviaGradscalerfunction before thelr_scheduler.step()function I am still getting this warning:/opt/anaconda3/envs/huggingface/lib/python3.7/site-packages/torch/optim/lr_scheduler.py:123: UserWarning: Detected call oflr_scheduler.step()beforeoptimizer.step(). In PyTorch 1...
ptrblck
If the first iteration creates NaN gradients (e.g. due to a high scaling factor and thus gradient overflow), the optimizer.step() will be skipped and you might get this warning. You could check the scaling factor via scaler.get_scale() and skip the learning rate scheduler, if it was decreased. I th…
navid_mahmoudian
Hello,I am trying to install Pytorch 1.6.0 viaPippackage (pip install torch torchvision) on a computing grid in which I don’t have permission to install any software by myself. Thetorch.cuda.is_available()returnsFalse, buttorch.version.cudareturns10.2.Here is the output ofnvcc --version:nvcc: NVIDIA (R) Cuda compiler d...
ptrblck
torch.version.cuda indicates which CUDA runtime was shipped in the binaries (or used to build PyTorch from source). It does not tell you, if CUDA can be used as seen by the output of torch.cuda.is_available(). For CUDA10.2.89 you would need an NVIDIA driver >= 440.33 as seenhere. You could update…
alameer
The code below calculates the MSE and MAE values but I have an issue where the values for MAE and MSE don’t get stored at each epoch in store_MAE and store MSE. It seems to use the values of the last epoch only. Any idea what i need to do in the code to save the total values for each epoch i hope this make since# loggi...
ptrblck
It seems you are reinitializing store_MAE and store_MSE inside the logging loop? Could you move this code store_MAE = 0 store_MSE = 0 before executing the loop?
bfeeny
I converted my training loop to use AMP, and I notice my accuracy numbers are now all0. What needs to be changed to work with AMP?zwas calculated within awith_autocast():clause so I thought it should be fine, but apparently it is not.print("Training..............................\r", end='') train_iter = iter(...
ptrblck
Which value are you using for the label smoothing and which criterion are you using? Are you using a sigmoid at the end of your model and nn.BCELoss? If so, could you remove the sigmoid and use nn.BCEWithLogitsLoss? The pred calculation looks a bit weird. If you are already using a sigmoid output…
EmreTokyuez
I want to use the examples in the test set of the IMDB Sentiment Analysis Dataset for training, as I have built my own benchmark with which I will compare the performance of various Models (my Matura Thesis)So after trying, I got the appending working and also managed ot split it, so that I have a validation set as wel...
ptrblck
random_split will return Subsets, which wrap the dataset. To access the underlying dataset, you could use train_dataset.dataset.get_vocab(). However, this would call the get_vocab() methon of course on the complete dataset. I’m not familiar with this method, but if it creates the vocabulary based…
Mark_McPherson
I followed the tutorial athttps://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#further-learning. Everything ran ok, but I have some questions I hope the community can help me with. If this belongs in a different topic, apologies!The tutorial states that on GPU it takes less than a minute to train (15-...
ptrblck
Depending where the bottleneck in your current system is, ~5 minutes might be expected. I just reran the script on a V100 server (which should be of course a bit more powerful) and it finished in 34s.This postgives you a good overview about potential bottlenecks and their workarounds. This…
shartzog
First off, I’m relatively new to python in general and extremely new to pytorch, so go easy on me if you check out the modules. (I’m still working through pylint issues after adapting from a notebook…)Either way, I’ve written a fewmodulesthat allow me to generate an arbitrary number of pytorch CNNs with randomized con...
ptrblck
Your use case sounds really interesting.Additionally to the mentioned approaches, you might also want to checkout differentiable architecture search approaches, such asDARTS. (I don’t know, if it’s the state-of-the art or what is used nowadays).
hunters0813
Hello, guys. I’ve some questions of image warping with optical flows.I would like to test warp the images by grid_sample, and I’ve got samples(two images with flow) from PWC-Net as follows:input image from →PWC-Net/PyTorch/data at master · NVlabs/PWC-Net · GitHubflow file from →PWC-Net/PyTorch/tmp at master · NVlabs/PW...
ptrblck
You would have to call transpose on the numpy array or .permute on the tensor to change the dimension order. The view operation (test.view(1, 2, H, W)) will interleave the pixel values and thus create the wrong image.
Maicol_Polvere
Hi everyone,I have a dataset with 885 images and I have to perform data augmentation generating 3000 training examples for each image by random translation and random rotation. However since the dataset would increase too much and I cannot store all the images on the disk. I know that I can perform transform ‘on the fl...
ptrblck
Thanks for the information. If I understand the use case correctly, you would have 884*3000 images in each epoch, where each of the original 884 images will be randomly transformed 3000 times. In that case, my previous proposal should work and this code snippet would show, what I meant: class MyD…
bfeeny
In CUDA/Apex AMP, you set the optimization level:model, optimizer = amp.initialize(model, optimizer, opt_level="O1")In the examples I read on PyTorch’s website, I don’t see anything analogous to this. How is this accomplished?
ptrblck
Native AMP is similar to the recommended O1 level and doesn’t use any other opt_levels.
Ka_Hina
I am trying to implement Bayesian CNN using Mc Dropout on Pytorch,the main idea is that by applying dropout at test time and running over many forward passes , you get predictions from a variety of different models.I’ve found an application of the Mc Dropout and I really did not get how they applied this method and ho...
ptrblck
The mean is calculated in dim0, not the first element. Here is a code snippet to show, how this operation works: batch_size = 2 nb_classes = 3 # initialize empty list output_list = [] # append predictions to list for _ in range(10): # Here you would call the model and create the outputs …
mash2612
Hello, I wanted to understand how to implement kernel regularizer(parameter in Keras/Tensorflow layer) in a layer in PyTorch. I saw examples of how to implement regularizer for overall loss, but could not find the relevant documentation for this.Could someone point me in the right direction? I saw something along the l...
ptrblck
The code snippet looks generally correct. One minor issue: named_parameters() will return a tuple as name and param, so you might need to use these two variables in the for loop or alternatively unpack i.
shivangi
I prepocessed a video and selected 5 consecutive RGB frames to form tensors of shape 15 X 256 X 256 asfile.pt. Here is my dataloader. But the dataloader is super slow. Any insights what could be the possible issue and how to speed it up?I am using batch size 128 and 4 workers. On using 32 workers,I even get some except...
ptrblck
Did you measure the data loading time during the training or just the first iteration? Note that the first step will spin up all workers, and each will load a complete batch, which might introduce some warmup time. Also, where is your data stored? Is it on a local SSD or some other hard drive? Ha…
eqy
Hi, I’m trying to see if I can finetune a pretrained vision model for a downstream task using intermediate activations as features. Since it’s cumbersome to manually save activations by editing model definitions to output multiple tensors, I was trying to do this by just adding hooks to save activations from relevant l...
ptrblck
Could you try to assign the out tensor to activations[name] instead of appending it? If I understand your use case correctly, you would only need to current output not all outputs from previous iterations (which might cause this error, if their computation graph was already freed).
alameer
I have two models both run using the same parameters (Epoch=50, Batch size=16) If I compare both models one seem to run for 965 steps, and the other runs for 395. I would expect them both to run similar steps. Any idea why would this be the case. I have attached a copy of the graph?Screenshot 2020-08-07 at 11.21.03831×...
ptrblck
The runtime difference might come from: different datasets and thus a different number of samples different print logic in your code different training (including early stopping) … Without seeing code I can just speculate.
TracyCuiq
Just as the result shows, they consists of grain noises.This is a task of generating “probability map” using a GAN with a U-Net style generator. In a sense, This task can be explained as using the U-Net structured generator of GAN to generate segmentation results.Actually, the output is right when I run the tensorflow ...
ptrblck
To compare both model implementations you could pass a constant input to them (e.g. all ones) and compare the final (and intermediate outputs). Of course you would need to load the same state_dicts in both models to make sure that you are using the same parameters. This approach would allow you to…
Alva-2020
捕获1655×441 27.9 KBHi everyone, when I use F.nn_loss() in model forward as above. Then I two GPUs to train the model in form of model = torch.nn.DataParallel(model).cuda(). I get a tuple speed_loss. Before I called loss.backward, I use torch.sum(speed_loss) to get a scalar. Is this right? The tuple is from two gpus cal...
ptrblck
The output of nn.DataParallel should be a single tensor on the default device and thus the target as well. I’m not sure, if you are using a custom data parallel approach, but if you are calculating the loss based on the model output and target, you should get a tensor (also on the default device) a…
yYang
I’m trying to implement a Linear layer with an extra constant weightweight_fbto computegrad_inputin backward pass.So I implemented aMyLinearFuncFunction similar to the onehere. In forward function ofMyLinearModule, returnMyLinearFunc.apply(input, self.weight, self.weight_fb, self.bias)and the return of backward functio...
ptrblck
The feedback_weight buffer will be registered and pushed to the device. However, you are not using it (via self.feedback_weight), but instead self.weight_fb, which is not the buffer.
Blizzard_boi2020
Here- is the directory(+= folder contents)D:/Data/…/Train/PX1_0000- T2W.nii.gz + seg.nii.gzPX1_0001- T2W.nii.gz+ seg.nii.gz..… PX1_0200- T2W.nii.gz+ seg.niiSame follows for 200 patients.def get_list_of_files(base_dir):list_of_lists = []for phase_type in [‘train’]:current_directory = join(base_dir, phase_type)patients =...
ptrblck
Code snippets can be added by wrapping them into three backticks ```, which makes debugging easier. Are you seeing an error or unexpected results when running the script? This questions doesn’t seem to be PyTorch-specific, so you might also get a better and faster answer e.g. on StackOverflow.
YaraAlnaggar
Hello,I have a model that combines the inference of two models, as the following:class model_all(nn.Module): def __init__(self,dense,shuffle): super(model_all,self).__init__() self.dense = dense self.shuffle = shuffle def forward(self,input): self.dense(input) self.shuff...
ptrblck
If a submodule already uses all SMs on your GPU, you won’t be able to run another model in parallel. A lot of layers are used in such a kernel launch configuration to saturate the GPU as much as possible.
WillThomson
I have a for loop in which the first iteration is substantially faster than subsequent iterations. This discrepancy only appears when I use a GPU. On a CPU every iteration takes more or less the same time. I’m wondering what causes this and whether there’s anything I can do to prevent the slow down in later iterations....
ptrblck
CUDA operations are executed asynchronously, so you would have to synchronize the code before starting and stopping the timer via torch.cuda.synchronize(). Otherwise you’ll only profile the Python overhead as well as the kernel launch in the first iterations until your script encounters a blocking o…
haltaha
I have a tensor of size (2,3), after running it throughtorch.unique, I get a tensor size of (2,3) for the unique but only get a tensor size of (1,3) for the counts whendim=1. I was expecting that I get (2,3)Test code:x = torch.tensor([[2, 2, 1], [0, 1, 2]]) u, c = torch.unique(x, dim=1, return_counts=True)Is there a pr...
ptrblck
The returned counts tensor c should have the shape [3] (not [1, 3]), which is also what I get. This is the expected shape, since the counts tensor will have the shape output.size(dim), if dim was specified. From the docs: counts (Tensor): (optional) if return_counts is True, there will be an add…
RahimEntezari
I want to change the order of shuffle and batch. Normally, when using the dataloader, the data is shuffles and then we batch the shuffled data:import torch, torch.nn as nn from torch.utils.data import DataLoader x = DataLoader(torch.arange(10), batch_size=2, shuffle=True) print(list(x)) batch [tensor(7), tensor(9)]...
ptrblck
The approach looks fine to me. A minor suggestion: you probably don’t need the list creation and [0] indexing here: a = [features[50000 + (i * 100):50000 + ((i + 1) * 100)]] features_list.append(a[0])
karen-gishyan
Hi everyone,I was wondering if it is possible to obtain the original name or the full path of the image after using torch.utils.data.random_split(). Achieving this would allow to save train and test split images with their original names to local directories. Thanks.
ptrblck
random_split wraps the Dataset into Subsets as seenhere. The used indices can be access via subset_dataset.indices and could be used to get the image paths. It depends what kind of Dataset you are using, but e.g. ImageFolder should contains the paths in its dataset.samples attribute.
samra-irshad
Hi everyone, I am trying to understand the behavior of torch.nn.DataParallel. The example code portion is given below for reference. Lets say I am using 8 batch size and two GPUs. Each GPU process 4 data samples. My questions are:While updating the running means for batch_normalization, does this module update the mean...
ptrblck
nn.DataParallel would update the batchnorm stats on the default device, as seen in this code snippet: bn = nn.BatchNorm2d(3, momentum=1.0).cuda() a = torch.randn(16, 3, 224, 224) * 12 + 7 b = torch.randn(16, 3, 224, 224) * 5 - 9 x = torch.cat((a, b), dim=0) model = nn.DataParallel(bn, device_id…
oasjd7
Hi, all.I have some questions about the visualization.I`m newbie in this field…so maybe this is silly questions.I have MNIST dataset. and I want to visualize the output of my encoder.(Input: MNIST data) -> MY_ENCODER -> output -> visualization.How can I visualize the data from output of CNN ?If I use MNIST dataset as i...
ptrblck
You can just use a plot library like matplotlib to visualize the output. Sure! You could use some loss function like nn.BCELoss as your criterion to reconstruct the images. Forward hooks are a good choice to get the activation map for a certain input. Here is a small code example as a sta…
Deeply
Some of the images I have in the dataset are gray-scale, thus, I need to convert them to RGB, by replicating the gray-scale to each band. I am using a transforms.lambda to do that, based on torch.cat. However, this seems to not give the expected resultsExample: Let xx be some image of size 28x28, then,In [67]: xx.shap...
ptrblck
While loading your images, you could use Image.open(path).convert('RGB') on all images. If you are using ImageFolder, this functionality should be already there using the default loader. Alternatively, you could repeat the values: x = torch.randn(28, 28) x.unsqueeze_(0) x = x.repeat(3, 1, 1) x.sh…
Blizzard_boi2020
offsets = [0, (x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2] - x2_shape[2]) // 2, 0]size = [-1, x2_shape[1], x2_shape[2], -1]
ptrblck
TheTF docsmight be helpful: If size[i] is -1, all remaining elements in dimension i are included in the slice. In other words, this is equivalent to setting: size[i] = input_.dim_size(i) - begin[i] If you provide the input and desired output (+ shapes), we could try to come up with the corr…
lisyuan
Hi, I am the first time using thepack_padded_sequence, and it seems to input the sequence length in a decreasing order. Here is the defaultpack_padded_sequencepackage fromofficial websitetorch.nn.utils.rnn.pack_padded_sequence(input, lengths, batch_first=False, enforce_sorted=True)enforce_sorted: ifTrue, the input is ...
ptrblck
Yes, if you are not planning to export the model via ONNX, you could use enforce_sorted=False and pass the unsorted padded sequence to this method.
NishantN
I have been trying to use grad-cam for a custom model I made in pytorch but can’t figure out how to do it. The model I made is a classifier model using ResNet50. Any help on how I can use gradcam to create a heatmap on images with based on my model would be really appreaciated.Thank you!
ptrblck
Captum provides a Guided GradCam implementationhere, which might be useful.
MichaelMMeskhi
Hello,I am trying to decide what is the best way to preprocess an image that I have. Basically, imagine a photo of a table that has 10 rows and 3 columns. Each cell contains a handwritten digit. I built a MNIST model and retrained with my custom data. But my question is, what is the best way to pass in such input? I wa...
ptrblck
Thanks for the information. I would try to avoid the preprocessing with bounding boxes, as this would give you more flexibility but would also add more complexity to the code, which is apparently not needed for your use case. Since the digits are located in the same zones, you could write a slice_…
Blizzard_boi2020
Screenshot_20200803-010027717 (1)941×413 120 KB
ptrblck
You could reuse the approach used in torchvision's resnet implementation as seenhere.
Quentin_Munch
Hi !I am creating a ladder like autoencoder network for video prediction.I create 2 class : one for the encoder and one for the decoder.I need these network be separate during the inference time to access some value.but I need to train the 2 networks with the same loss :I pass the 2 net parameters to the same optimizer...
ptrblck
Currently you are passing two tensors to your loss function, which don’t require gradients and are decoupled of your models. last_Y1 is still the zero tensor, while Xt is the image you’ve captured using openCV. Usually you would pass some model output as the first input and a target as the second …
Byungheon_Jeong
I was profiling the power draw of my GPU when I noticed that after the first time a layer is sent to the GPU using to(device= cuda_device), the speed at which the layers are sent to the GPU decreases by three orders of magnitude:import timeit import torch from torch import nn cuda = torch.device('cuda') #1 Layer def ...
ptrblck
The first CUDA operation will create the CUDA context, which contains the the PyTorch kernels, cudnn, NCCL, CUDA libs etc., so it’ll take some time to load these libraries. Also note, that CUDA operations are executed asynchronously, so if you want to profile the data transfer from host to device o…
SteinarLaenen
Suppose you have 4 GPUs, are batches then split evenly into 4 parts (without changing the order), and then distributed to different GPUs? Or is each individual image in the batch sent to a random GPU?The reason I am asking is because I have run into some problems training on multiple GPUs for few-shot learning. In few-...
ptrblck
A quick test shows that the data is split sequentially: import torch import torch.nn as nn class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): print(x, x.device) return x model = MyModel() model = nn.DataParallel(mod…
adm
As far as I understand the documentation for BatchNorm1d layer we provide number of features as argument to constructor(nn.BatchNorm1d(number of features)).As an input the layer takes(N, C, L), whereNis batch size (I guess…),Cis the number of features (this is the dimension where normalization is computed), andLis the ...
ptrblck
Your code looks correct, since the batchnorm layer expects an input in [batch_size, features, temp. dim] so you would need to permute it before (and after to match the input of the rnn). In your code snippet you could of course initialize the tensor in the right shape, but I assume that code is jus…
lycaenidae
Hi,I am wondering can I use pre-trained models (2d) like that order?Pretrainedmodel- 3dconv-3dconv etc
ptrblck
nn.Conv3d expects an input in the shape [batch_size, channels, depth, height, width], so you would need to reshape the output of the pretrained model to this shape. Depending which model you are using, it might already provide the desired shape or you would need to figure out how this should be don…
samra-irshad
I am training an image segmentation model and the time taken per each step in epoch seems to be rising throughput whole epoch. I am not sure if it has something to do with the way I am feeding my model with images. I am using DataLoader utility. I have pasted time for one epoch. Is there anyway to improve the training ...
ptrblck
Are you only seeing this slowdown using nn.DataParallel or also a single GPU? In the latter case, are you also seeing an increased memory usage? If that’s the case, you might accidentally store some tensors which are still attached to the computation graph, or somehow extend the computation graph …
mathematics
I have a problem while generating images of different sizes from GANs.I have input images of different varying shapes extremely like (220, 3500) or (2100,230) or different. If i reshape or modified it will be waste.I want to get images given latent random distribution which generates a varying sizes of different image...
ptrblck
You could try to useConditional GANsand treat the “shape” as a class information. You would have to define certain shape classes, but this might be OK instead of reshaping all input images to the same resulution. Also, the class label could be used to flip the transposed convolutions (swap height…
aRI0U
Hi,I am training a model and I saw that the GPU usage increases epoch after epoch, even by callingtorch.cuda.empty_cache().Here is a snippet of code:for sample_id, (packed_blocks, packed_sequences) in tqdm(enumerate(data_loader)): monitored_quantities = step(packed_blocks, packed_sequences, train=train) means ...
ptrblck
Thanks for the detailed analysis! From the plots it seems that the allocated memory stays approx. at the same level. Could you try thenative amp implementationin PyTorch 1.6.0 and check the memory usage? Also, which GPU are you using?
chetan06
cud-error741×199 23 KBI got this error while running a simple line of code. Most of the time when I get this error I just switch off my gpu and run it on cpu , and always I get what is wrong with my code. I did the same with this but It ran fine with cpu.
ptrblck
You could try to set this environment argument via os.environ['CUDA_LAUNCH_BLOCKING'] = "1". This would have to be added before any other imports in your script to work properly.
Heisenberg_082001
I am trying to do multiclass-classification using simple ANN .Dont know why my loss is not decreasing it remains constantCODE-class NET(nn.Module): def __init__(self): super().__init__() self.model=nn.Sequential( nn.Linear(6,512), nn.ReLU(), nn.Linear(512,1024), nn.ReLU(), ...
ptrblck
Again, I would recommend to play around with hyperparameters, such as the learning rate. Since the loss changes and no dropout (or other “random” operations are used), it would mean that the parameters get some updates but the overall training isn’t able to reduce the loss. Start by using a lower …
jakemdaly
I am using PyTorch with my Tegra X1 GPU, and running the NVIDIA command line tool nvprof to do some kernel profiling of DCNN layers.I am seeing, as reported by nvprof, that the half precision (16-bit) workloads have just as many (actually slightly more) FLOPS than when the layers are run with full precision (32-bit). H...
ptrblck
I’m not deeply familiar with the Tegra family. If you don’t have TensorCores, then the benefit would be the lower memory footprint, which might be used to increase the batch size and thus the throughput. However, depending on your use case, this might not be interesting (e.g. for an inference use c…
adi8862
Hi,I was using nvprof to profile the calls for various layers of MobilenetV2 in the forward and backward pass. For the Depthwise convolution the profiling says it uses the “spatialDepthwisConvolutionUpdateOutput” function, and from various other topics I have seen that PyTorch uses its own kernel for Depthwise convs in...
ptrblck
It seems to use the im2col and matmul approach as seenhere.
Alex_Dima
Hello! I am new in Pytorch and I am trying to implement a UNet. I am using some random pictures and their masks from 2 folders with the same names. I followed the implementation from the original paper. Since I am finding the choice of channels very confusing(I have no idea how to go from a 300*300 image to a mask of t...
ptrblck
Could you check the values of your mask? Resizing a target mask without specifying an interpolation technique such as NEAREST might corrupt the mask tensor. Also, your model seems to output a single channel (1 class), while nn.NLLLoss is used for a multi-class classification use case (>= 2 classes)…
Giuseppe
Hy guys I want to create a model like this:Prova716×181 6.41 KBI need to know if I made mistakes. Because I am not convinced of the code:import torch.nn as nn from torchvision.models.utils import load_state_dict_from_url import math # ResNet###### BLOCCHI ##################################### def conv3x3(in_planes, out...
ptrblck
Is Resnet50 + Encoder layers in your picture the encoder in the code? If so, the code looks alright. Ciccio and Pippo contain additional layers, which are not in the figure, but I guess that’s expected.
ChineseBest
class CNNnet(torch.nn.Module): def __init__(self): super(CNNnet,self).__init__() self.conv1 = torch.nn.Sequential( torch.nn.Conv1d(in_channels=32, out_channels=2, kernel_size=1, stride=2, ...
ptrblck
Your model might be able to train, if the data provides enough information. It’s a bit hard to provide a general statement, as it depends on the use case you are working with. However, I would assume the more “temporal” structure your data has, the better.
albusdemens
I wrote a simple script which applies a 2D convolution operation to an input image. I am running the code as a cell in a Jupyter Notebook. Every time I compile the cell, the colors of the processed image change. Why is that? Should I change how convolution is calculated?Here is my code:import torchimport torchvisionimp...
ptrblck
I assume you mean the colors of result change? If that’s the case, then it would be expected, since you are applying a random nn.Conv2d layer to the image.
chetan06
I was trying to visualize a layer of pretrained model but when I am trying to get the middle layer of model like alexnet then I am getting 2d tensor with one column but I am expecting a feature map with 3 dimensions.To get this output I am replacing all the layer that follows the desired layer with following layerclass...
ptrblck
An easier way to get the intermediate activations would be forward hooks as describedhere. I think you are seeing a flattened tensor, since you are only replacing the modules, while the functional API call in the forward (such as x = x.view(x.size(0), -1)) are still used.
VikasRajashekar
Hello,My logits are of dimention: torch.Size([64, 26, 7900])My target is of dimension: torch.Size([64, 26])It is so because the output is from LSTM for some NLP task. 7900 is the size of the vocabulary.How do I formulate the loss for this scenario?loss = nn.CrossEntropyLoss() input = torch.randn(64, 26, 7900, requires_...
ptrblck
As Chetan explained, the model output tensor should contain the class indices in dim1 and additional dimensions afterwards. Generally, nn.CrossEntropyLoss expects these shapes: output: [batch_size, nb_classes, *] target [batch_size, *]
pmeier
Consider the following snippet:from time import time import torch for run in range(5): start = time() torch.empty(1, device="cuda") end = time() print(f"{run}: {end - start:.2g} seconds")On my machine this results in the following output:0: 1.6 seconds 1: 3e-05 seconds 2: 7.9e-06 seconds 3: 7.4e-06 sec...
ptrblck
You are right. I only see the smaller ~3MB allocation, but not the creation of the CUDA context. In that case you might need to create a dummy tensor instead in the init method.
crook52
Hi.I want to convertdarts/cnn’s model to TFlite, finaly.First of all, I tried to convert it to ONNX by below code.import torch import torch.nn as nn import genotypes from model import NetworkCIFAR as Network genotype = eval("genotypes.%s" % 'DARTS') model = Network(36, 10, 20, True, genotype) model.load_state_dict(tor...
ptrblck
Yes, sorry for the unclear naming. By “eager” mode I meant the normal Python usage. Good to see the model is working generally. Could you , for the sake of debugging, remove the logits_aux from the forward and just return the logits and retry to export the model?
Saifeddine_Barkia
I’m new to pytorch and I’m trying to learn here.I’m trying to fine tune a Resnet on my own dataset :def train_model_iter(model_name, model, weight_decay=0): if args.train: model, loss_acc, y_testing, preds = train_model(model_name=model_name, model=model, weight_decay=weight_decay) preds_test, gts...
ptrblck
The error is most likely raised as you are trying to use the pretrained model, while also specifying another number of classes. You could remove the **classes argument to load the “standard” pretrained model with 1000 output classes and replace the last fully connected layer: resnet152_model = res…
ayrts
Hello,I read Thomas Woolf’sarticle on balanced loads when using multiple GPUs, and I would like to adapt it for my training. He mentioned that when usingDataParallelModeland compared totorch.nn.DataParallel, the predictions in the forward pass (predictions = parallel_model(inputs)) would be a tuple ofntensors, with eac...
ptrblck
You could use the loop and push all predictions to the default device (or the device, where label is stored). Note that, the usage of .data is deprecated and might yield unwanted side effects, so you should call torch.max on the tensor directly.
Ahmed_Jimy
Hello, I am training a binary classification model and I want my results to be reproducible. So, I am using this function before every training session begins:def seed_everything(seed_value, use_cuda):if use_cuda:torch.cuda.manual_seed(seed_value)torch.cuda.manual_seed_all(seed_value)torch.backends.cudnn.deterministic ...
ptrblck
This might be caused by the shuffling of the data, if you haven’t restored the state of epoch 20 for the data loading before continuing the training. If you are shuffling the data, you could try to add 20 “empty” epoch iterations using the DataLoader and check the final performance again.