user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
sigma_x
I learnt of this functionality. For example, we have a VGG16 model:import torchvision.models as models model=models.vgg16() model._modules['classifier'][6] = 1Sequential( (0): Linear(in_features=25088, out_features=4096, bias=True) (1): ReLU(inplace) (2): Dropout(p=0.5) (3): Linear(in_features=4096, out_feature...
ptrblck
You could reassign a new matix with your desired shape. Changing the in_* and out_features will not change the underlying weight parameter.
yuyaya
Hi, I transfer trained my original dataset after trainingFCHarDnetwith CItyscapes data.During loading the trained weight for inference, I met problem.While transfer train FCHarDnet,I inserted the layer to match the class number.Like below# While Training, I wrap HarDnet & layer with nn.Sequential model = FCHarDnet.to(d...
ptrblck
Based on the error message it seems the state_dict might have been saved directly using the FCHarDnet model without wrapping it into an nn.Sequential container. Could this be the case? If so, you could add the mitssing 0. in front of the keys. However, this would also mean that the parameters of …
abailey
Hi,I have come across a problem where despite setting random seeds, I obtain different outputs from a simple network depending on whether I use CPU or GPU. I also receive different CPU results using different computers but receive the same GPU results.The model weights are equal as is the randomly generated input “a”, ...
ptrblck
The differences you are seeing are approx. 1e-6 which comes most likely due to the limited floating point precision of float32. The order of operations might yield different results as seen here: x = torch.randn(10, 10, 10) s1 = x.sum() s2 = x.sum(0).sum(0).sum(0) print((s1 - s2).abs().max()) > te…
ash95
I would like to modify the Normalization.cpp file in the aten submodule of pytorch (which I had installed via conda). However, I can’t seem to find it. So how do I modify it and rebuild the dependencies.
ptrblck
If you’ve installed the PyTorch binaries via conda, you should fine some files in your conda directory, e.g.: /opt/conda/lib/python3.6/site-packages/torch/include/... However, modifying them won’t have any effect. Instead, you should build PyTorch from source as describedhere. Also, theContrib…
Ameen_Ali
HelloI have a problem converting a python list of numbers to pytorch Tensor :this is my code :caption_feat = [int(x) if x < 11660 else 3 for x in caption_feat]printing caption_feat gives :[1, 9903, 7876, 9971, 2770, 2435, 10441, 9370, 2]I do the converting like this :tmp2 = torch.Tensor(caption_feat)now printing tmp2...
ptrblck
Could you try to use torch.tensor with a lowercase t?
satinder147
I am trying to train a UNet for road segmentation. When I normalize the images using transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5)) the loss decreases but if I normalize the images by dividing them by 255.0 then the loss stops decreasing after a certain point. What is the difference between the two?
ptrblck
It’s not generally true, I think, and might depend on your application. You can find literature about how standardizing whitens the input data and this creates a “round” loss surface, but I’m not sure if these simple abstractions are applicable for deep neural networks. Have a look atthis postwr…
CCL
Here, I’ve declared a custom multi-task loss in Pytorch with BCEWithLogitsLoss for the (binary) mask segmentation loss, and BCELoss for the classification loss (I use fully-connected layers and then sigmoid). I weight BCEWithLogitsLoss at 0.9 and BCELoss at 0.1, sum them, and back propagate this summed loss. I’m using ...
ptrblck
Are you using the sigmoid for both layers? Note that nn.BCEWithLogitsLoss does not expect probabilities, but raw logits. Could you post the training code, so that we can have a look?
dlsf
I would expect DataLoader to load batches concurrently to the main process, refilling the buffer as soon as a batch is consumed from the buffer. However, when I track the utilization of GPU and order of loading vs execution I see some different behavior:loading of the whole buffer (expected)consuming the whole buffer b...
ptrblck
In a lot of use cases training a complete epoch takes a lot of more time than reinitializing the worker processes, so that the epoch start could be ignored. It’s probably an edge case, but you could also manipulate some arguments of the DataLoader itself or the underlying Dataset between epochs. H…
mlearner
Hi,after I use the transformationsResizeandCenterCropI would like to go back to the original image, with the integer RGB values (in [0,255]) for the channels. How can I do this?I need it because I have to open it withopencv, that only accepts this format to correctly open the image.Thanks
ptrblck
Resize and CenterCrop do not normalize the image, so the pixel values should still be in the same range. You can hardly undo a cropping operation, as you lose information during the crop. If you want to undo the normalization, you could multiply with the same stddev and add the mean to the tensor. …
nombreinvicto
Hi everyone,completely new to DL/Pytorch here so feel free to treat me like a nube. I have been training an image dataset of 3 category animals (Cats, Dogs and Pandas) on a very simple CNN architecture. The structure goes like below:from torch import nn class ShallowNetTorch(nn.Module): def __init__(self, width, h...
ptrblck
This might be the case or the model is classifying the wrong classes with a higher confidence.
gon1332
I’m using torch of version 1.3.1+cpu and torchvision version of 0.4.2+cpu.I’m using the VAE example in master (0c1654d) but the interpreter results in this warning:/home/gon1332/Development/Training/ML/learning-data-augmentation/model.py:147: UserWarning: Using a target size (torch.Size([128, 784])) that is different t...
ptrblck
The printed shapes correspond to the shape mismatch mentioned in the error message. How would you like to compute the binary cross entropy with a different number of samples? Did you change anything in the example code? I just retried it with the latest nightly build and it seems to work without …
CCL
I predict a binary segmentation mask using an array with values 1 and 0, multiply this by 255, and try to save the resulting array as an image. However, I’m getting the following error:Traceback (most recent call last):File “test.py”, line 71, intorchvision.utils.save_image(predicted, path_ + idx[0])File “C:\Users\CCL\...
ptrblck
Internally the output array will be created via: ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy() so you don’t need to multiply your predictions with 255 and can pass it as a float tensor. The error is thrown at the .add_(0.5) step. The documentation…
Core_Park
I have encountered a very strange error with the datatypes. I am very new to PyTorch, I apologize if this is a simple mistake.The minimal version of the error is:import torch as torchclass Net(torch.nn.Module):definit(self):super(Net, self).init()self.conv1 = torch.nn.Conv2d(in_channels=1,out_channels=16,kernel_size=5)...
ptrblck
PyTorch uses float32 by default, while you are creating an input tensor with float64 (double). If you don’t specify the dtype or set it to torch.float, the code should work.
madarax64
Hello all,For my research, I’m required to implement a convolution-like layer i.e something that slides over some input (assume 1D for simplicity), performs some operation and generates basically an output feature map. While this is perfectly similar to regular convolution, the difference here is the operation being pe...
ptrblck
You could use unfold as descibedhereto create the patches, which would be used in the convolution. Instead of a multiplication and summation you could apply your custom operation on each patch and reshape the output to the desired shape.
111227
I want to change this Keras function into PyTorch. Should I rewrite a new function or there is a function that Pytorch had already exist? Thanksbatch=input_shape.dim_size(0)i_h=input_shape.dim_size(1)i_w=input_shape.dim_size(2)i_ch=input_shape.dim_size(3)k_h=filter_shape.dim_size(0)k_w=filter_shape.dim_size(1)o_ch=filt...
ptrblck
If you want to grab the dimension shapes, you could use: size = my_tensor.size() # or N, C, H, W = my_tensor.size() .shape should also work.
CDahmsCellarEye
With a pip3 install oftorch 1.4.0andtorchvision 0.5.0, the python statementtorch.backends.cudnn.version()shows a result of7603. What does this mean?7.6.3.x?? or7.6.0.3x?? or something different ??
ptrblck
The output of 7603 corresponds to cudnn7.6.3.x.
al314
Hey,Sorry for maybe super basic question but could not find it.What is a correct Pytorch way to encode multi-class target variable?I have> 30target classes for target variable - likeAA, AB, BB, BA, BC ....Should I use ScikitLearn tools and then convert numpy arrays into torch tensors?Or there is built-in functionality?...
ptrblck
You could use this code snippet to transform your class indices into a one-hot encoded target: target = torch.randint(0, 10, (10,)) one_hot = torch.nn.functional.one_hot(target)
Jiajun_Zha
I wrote this toy dataset example for MPII dataset, but the dataset actually has different image size. So the Dataloader malfunctions when concatenate images together into one batch. I’m sure that my mode is able to handle different input size since I’m using deeplabv3_resnet. The problem is just how to concatenate diff...
ptrblck
If you want to create a batch containing data with different shapes, you could use a custom collate_fn as describedhere. However, deeplabv3_resnet101 is be a segmentation model, so your keypoint prediction might not work out of the box, but that’s just a side note and you might already have a plan…
barakb
Hi, I want to adjust the learning rate of part of my model, let’s call it PartA using lr_schedulerAAnd PartB using lr_schedulerB.I didn’t find a way to do this, the only solution I found is to duplicate my optimizer, and put the parameters of each part in the corresponding optimizer:optimizerA = torch.optim.SGD(parame...
ptrblck
Your approach looks reasonable as you are not duplicating the optimizer but rather use two different optimizers and schedulers for different parts of the model. I think this use case looks clean and is quite easy to understand so I would stick to it and not hack around param_groups of the optimizer…
880n
Hi, I’m meeting a problem loading the pre-trained model of Resnet-50.I just simply load the model and meet the following problem. I can’t find a solution to solve it.import torchvisionres= torchvision.models.resnet50(pretrained=True)Traceback (most recent call last):File “”, line 1, inFile “/home/hzha3251/.local/lib/py...
ptrblck
This error might be thrown, if pickle ends unexpectedly, e.g. if the downloaded file is corrupt. Did you try to rerun the code? If you still see this error, could you please delete the cached files? They should be located in /home/USER/.cache/torch/checkpoints by default.
11152
I want to make the value of a specific index equal to 0. but very very slow…mask = [1,2,3,4] input = torch.zeros(100,64,32,32) for m in mask: for i in range(100): input[i][m] = 0How do I optimize my code?
ptrblck
This code should work: x = torch.zeros(100, 64, 32, 32) mask = torch.tensor([1,2,3,4]) x[:, mask] = 1 Note that I changed the assignment to a 1, otherwise you would reassign a 0 to the tensor containing all zeros.
kranti
I notice a wired behavior of pytorch, where the network defined after the data loader has a different loss value as compared to the case where the network is defined before the dataloader. I have fixed the random seed to the same number in both cases by adding the lines below.np.random.seed(0)torch.manual_seed(0)torch....
ptrblck
If you’ve added these lines at the beginning of the script, the order or calls to the pseudo random number generator might still be different in your two use cases. E.g. initializing the random indices in the DataLoader will change the following call to the PRNG for the parameter initialization in …
Ghasem_Abdi
Hi,I have two different image data-set but related to a same class. I am going to use pre-trained net like alexnet for both to detect features and then, concatenate those features into a classifier (and optimize this classifier not the whole models). I would appreciate if you can help me within this context. Here is th...
ptrblck
The code looks alright from what I could see. PS: it’s generally better to post code snippets directly by wrapping them in three backticks ```.
f3ba
Suppose I have a list of indices:ind = torch.tensor([0, 2, 1, 3]), and a 4x4 tensorA.I need to assign some values to the itemsA[i, ind[i], fori=1,4. For example:for i in range(4): A[i, ind[i]] = r[i]wherercontains the target values in this example.GivenA,ind,r, Is there a way to vectorize this operation?
ptrblck
This should work: # Setup ind = torch.tensor([0, 2, 1, 3]) A = torch.zeros(4, 4) r = torch.randn(4) # Your code for i in range(4): A[i, ind[i]] = r[i] # Alternative B = torch.zeros(4, 4) B[torch.arange(4), ind] = r print((B == A).all()) > tensor(True)
Aditya_Kumar
#include <torch/torch.h> #include <torch/script.h> // One-stop header. #include <iostream> #include <memory> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; using namespace std; int main() { std::cout << std::fixed << std::set...
ptrblck
If I’m not mistaken, OpenCV reads the image as [height, width, channels], while PIL.Image returns the array as [channels, height, width]. The torch::from_blob call might thus interleave the pixels. Have you checked the outputs? Also, resize should use the linear interpolation by default in OpenCV …
Sami_Hassan
This is probably a human error but i would like to note down accuracy of AlexNet with already trained networks and then replace conv layers with my custom layers and note down results again.I can find AlexNet and pre_trained weights here[AlexNet]The Datasets are downloaded from here[AT]Main Folder Name : imagenet2012Su...
ptrblck
Based on your code it looks like you are using ImageFolder on your validation directory, which seem to contain only the images without any subfolders. ImageFolder creates the targets based on subfolders, so your current Datasets might contains only a single class label. Could you check that?
Sasafras
Hey all!This is my first post here, and I tried looking for the answer everywhere but couldn’t find any satisfying answers. However, please let me know if anything I ask has been asked and answered before.I was working on an implementation of a neural network that uses prototypes. It took me countless of hours of debug...
ptrblck
I assume you’ve called the to() operation on your nn.Parameter not the internal tensor? If so you would create a non-leaf variable, as the result is created by the to() operation, which is differentiable (so that the gradients can flow between different devices). Try to call the to() operation on …
coincheung
Hi,My dataset contains 40 samples, but I need to train my model with batchsize=64. I hope that I can fetch training sample batches continuously until certain number of iters is accomplished. I also need to shuffle the dataset if it is repeatedly used, how could I do this please ?
ptrblck
If you only have 40 samples, you could probably define the length of your dataset as e.g. def __len__(self): return 2 * len(self.data) and use index = index % len(self.data) operation inside __getitem__ to draw the current batch. You can pass this dataset to a DataLoader and set shuffle=True …
torlarse
Hi, sorry for yet another SVHN grayscale and resize problem permutation. After following lots of advice here on the forum I have a solution that renders some output. However when plotting a sample image it just shows a distorted color image, instead of the expected grayscale house number.EDIT: I want a SVHN dataset wit...
ptrblck
matplotlib uses the viridis colormap by default. In your first code snippet you were setting the color map to gray via: plt.imshow(test_img[0, 0], cmap='gray')
el_samou_samou
Hi,Does the.contiguous()function creates a copy of the memory corresponding to the tensor’s data?This was mentioned by@ptrblckhere:Contigious vs non-contigious tensorbut I would like to know if anyone is sure about this.Thank you in advance for your help.Samuel
ptrblck
If you call contiguous() on a non-contiguous tensor, a copy will be performed. Otherwise it will be a no-op. You could add some print statements to the linked example code and will see an increased memory usage after the y.contiguous() call.
YinYang_Untalan
I want to take a dataset i created from ImageFolder and save it into a file. I then will use the file in another computer.I tried torch.save which was not good for datasets. It did save a file but it doesn’t bring the images with it, only the info it needs to build the dataset - so when I used it on another machine, i...
ptrblck
Since ImageFolder loads the images lazily, i.e. in each call to its __getitem__ method a single sample will be loaded from one of the folders, I don’t think you can simply store the Dataset in this way. A possible workaround would be to zip the parent folder containing all image folders and move it…
Deathstroke_Twelved
I am working on an inference model of a pytorch onnx model which is why this question is being asked.Assume, I have a image with dimensions32 x 32 x 3(CIFAR-10 dataset). I pass it through a Conv2d with dimensions :3 x 192 x 5 x 5. The command I used is:Conv2d(3, 192, kernel_size=5, stride=1, padding=2)Using the formula...
ptrblck
As explained, the 3 would stand for the number of input channels. You have basically 192 kernels each with 3 channels and a spatial size of 5x5. The provided link explains the applied method. PyTorch dispatches to different backends as seenherein case you are interested in the implementation de…
che85
Hi all,I am trying to figure out, why torch allocates so much memory for a tensor that at least to me doesn’t seem it should allocate this much memory:weights = torch.tensor([0.3242]).cuda()This tensor allocates more than 737MB on my GPU and I have absolutely no idea why this would happen.I am using torch1.1 but also t...
ptrblck
The CUDA context will be created on the device before the first tensor is created, which will use memory.
Nitesh
In my code, I’ve used nn.batchnorm1d(64) as one of the layers where 64 is the batch size. Now after training my net I want to test the result for a single sample but it shows a error saying that I need to pass 64 samples. Is there any workaround to test the net with single sample?
ptrblck
If the batch norm layers are between linear layers, the shape should most likely once be changed before the first linear layer. Anyway, you could define a Permute layer and use it inside your nn.Sequential container: class Permute(nn.Module): def __init__(self, dims): super(Permute, se…
Sami_Hassan
Convolution operation can be converted to matrix multiplication using[1][2]and then you can use torch.matmul() . My question is i have to replace the addition and multiplication with my own functions mymult(num1,num2) and myadd(num1,num2). Currently i am using loops to replace torch.matmul() and multiply and add elem...
ptrblck
Thanks for the code! What is mymult applying internally (if you don’t want to share it due to research etc., it’s OK)? If you are using some PyTorch methods internally, they should be able to use tensors (or batches of tensors) instead of scalar values. On the other hand, if you are using some ot…
spnova12
I found some differences between the torch 1.1 and torch 1.3 initialization methods during deeplearning experiments.Are there really different default weight initialization methods for torch1.1 and torch1.3?
ptrblck
The default weight initialization for batch norm layers was updated to 1s instead of sampling from a uniform distribution inthis PR, which shipped with 1.2, if I’m not mistaken. Besides that I’m unaware of any changes.
AbuOmair
HiI am facing this waning I don’t understand the warning what does it meanC:\Users\NUC-i7 8gen\Anaconda3\lib\site-packages\torch\nn\modules\loss.py:431: UserWarning: Using a target size (torch.Size([32, 6])) that is different to the input size (torch.Size([32, 1, 6])). This will likely lead to incorrect results due to ...
ptrblck
Since your output and target shape do not match, but are broadcastable, you might get a wrong result. Have a look at this example: x = torch.arange(1, 5).view(2, 2) y = torch.ones(2, 2) loss = x - y print(loss) x = x.unsqueeze(1) loss = x - y print(loss) While you would most likely expect the fi…
AbuOmair
Hi guys, I am trying to train my data with this model NN I have 7 inputs (features) with 1 output (label) I am trying to classifying the data and train and calculating the loss. I did not understand why this error exactly why its not matching!?This is my NN model. 7 input(features) and 1 output (labels) hidden lyres a...
ptrblck
You could chose between two different approaches: treat the binary classification as a multi-class classification with two output units and use nn.CrossEntropyLoss. The target should then contain the class indices ([0, 1] in your case) use a single output unit and use nn.BCEWithLogitsloss Sorry …
Forelli
HiCUDA calculations do not work on my system. I think I’m missing an important point somewhere, but I can’t find the error. Can you guys help me with this?Here are the steps I take for the installation:Reset Windows 10 Home (64bit - Build 10.0.18.363) and install the latest Updates => OK.Is the graphics card CUDA compa...
ptrblck
The binaries with with their own CUDA, cudnn, etc. libraries, and won’t use your local CUDA installation. Your GPU with compute capability 2.0 is not supported using the binaries, as the only cc>=3.7 is supported with the latest binaries. Usually you would need to build PyTorch from source for an …
oasjd7
binary_op(): expected both inputs to be on same device, but input a is on cuda:1 and input b is on cuda:0class GaussianNoise(nn.Module): def __init__(self, sigma=1.0): super().__init__() self.sigma = sigma self.noise = torch.tensor(0.0, device='cuda:0') def forward(self, x): sam...
ptrblck
Inside the forward pass, you could create sampled_noise from the attributes of x: sampled_noise = torch.empty_like(x),normal_(mean=0, std=self.sigma) or push the noise tensor to the device of x: sampled_noise = ... sampled_noise = sampled_noise.to(x.device)
akhilesh_rai
Trying to train an xception model that has the following code`""" Creates an Xception Model as defined in: Francois Chollet Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/pdf/1610.02357.pdf This weights ported from the Keras implementation. Achieves the following performance on the val...
ptrblck
Your input images has a single channel, while three are expected. This might be the case when you are dealing with grayscale images, so either change the number of input channels in the first layer to 1 or repeat the channel dimensions 3 times.
florobax
Hi there !I am facing a strange behaviour from cuda when using a handmade model. I have been using variants of resnet for some time now, but as I am overfitting I decided to create a smaller model to see how it goes.The thing is, when I am using resnet18 (which has around 11M parameters) it uses around 3GB of cuda memo...
ptrblck
Pooling layers don’t have any parameters, so check the activation shapes instead, which are more likely bigger in your model using max pooling.
Geoffrey_Payne
I take a dataset and split it into 3 and then configure a dataloader to access each one, as follows;full_data_args={‘data_dir’:‘penguin_data/data’, ‘data_file’:‘penguin_csv.csv’,‘stage’:‘full’}data_batch = dataset.PenguinData(**full_data_args)train_data_params = {‘batch_size’:512, ‘shuffle’:True, ‘num_workers’:0, ‘pin_...
ptrblck
I don’t think this is a better approach and I would stick to separate DataLoaders for each split. Why do you think it might be a better approach?
Maziar
Hi,Compiling theDCGANtutorial code:https://pytorch.org/tutorials/advanced/cpp_frontend.html, I receive this error:.../pytorch/examples/cpp/dcgan/dcgan.cpp:48:23: error: ‘struct torch::nn::ConvOptions<2>’ has no member named ‘transposed’ 48 | .transposed(true)), |Any idea how to handle this?
ptrblck
If you are using 1.4.0, you would have to change the code to torch:nn:ConvTranspose{1,2,3}d. From the release notes: If users have transposed originally set to true in torch::nn::Conv{1,2,3}dOptions , they should migrate their code to use torch::nn::ConvTranspose{1,2,3}d layers instead. The tut…
TinfoilHat0
I’ve been tryingsimulatefederated learning (FL) with Pytorch.For FL, there’s a benchmark calledLeafwhich contains some datasets that are particularly suitable for non-iid data partition setting that arises in FL context.Is there an easy way to integrate the datasets from that benchmark to PyTorch? As far as I can see,...
ptrblck
If you want to preload the complete dataset, you could pass it to a TensorDataset. On the other hand, if you are dealing with image data, which is stored as separate image files in folders corresponding to the classes, you could use ImageFolder. Depending on the dataset and how each sample is stor…
ding3820
Hi all,I tried some of the available API in Pytorch but I think none of them meet my requirement.The most similar API in Pytorch is torch.take but the input is in 1D. However, tf.gather_nd probably could work but I couldn’t find the same function in Pytorch.Here’s the task:I have a 3D tensor in shape (B, H, K) as indic...
ptrblck
Indexing the tensor might work. I assume the initialization of k_block should be outside the first loop? Otherwise, you would throw away the first results. Based on this assumption, this code should work: # Setup B, H, K = 2, 3, 4 N, M = 5, 6 indices = torch.randint(0, N, (B, H, K)) x = torch.r…
justanhduc
Could you please explain why we should write data to buffer likethis? I fail to see the advantage of doing so.Thanks
ptrblck
My best guess is, that this is one valid approach to create PIL.Images using the lmdb format of the LSUN dataset.
domst
Hey I’m initializing a trainable parameter and adding it to the optimizer like so:lamb = nn.Parameter(torch.tensor(0.0, requires_grad=True, device=device, dtype=torch.float32)) params = [ {'params': net.parameters(), 'lr': 1e-3}, {'params': lamb, 'lr': 1e-3} ] optimizer = Adam(params)This parameter i wanna us...
ptrblck
My code snippet should yield valid gradients for all tensors in xi. Based on your initial code snippet it seems you want to get gradients for all subtensors, as you were initializing it with requires_grad=True. If you want to keep a portion of a tensor constant without updating it, your new approa…
apisarek
Hi all,I am working with reimplementing a model in PyTorch and reusing pretrained weights. I have encountered errors which I thought are coming from floating point related problems.I am providing a simple example which shows difference between convolution over input of ones vs summation of filter weights.import torch f...
ptrblck
The internal order of operations will most likely be different and e.g. a simple sum can also yield these floating point precision errors: filters = torch.randn((1, 2, 2, 2)) res1 = filters.sum() res2 = filters.sum(0).sum(0).sum(0).sum(0) print(res1 - res2) > tensor(2.3842e-07)
Yolkandwhite
I am trying to make an VGGNet by myself with CIFAR-10 datasets.and this is the model what I madeCNN((layer1): Sequential((0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(1): ReLU()(2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))(3): ReLU())(layer2): Sequential((0): MaxPool2d(k...
ptrblck
If each epoch takes 30 minutes, it seems the GPU might not be used. Could you run this dummy code snippet and report the time for each epoch you are seeing: model = models.vgg16().to('cuda') dataset = datasets.CIFAR10( root=ROOT, transform=transforms.Compose([ transforms.ToTensor()…
Huimin_ZENG
Hi, I got confused by observing some inconsistency regarding the time cost due to certain operations.Case 1:acc_start = time.time() acc = torch.mean((predicted_labels==targets).float()).item() train_acc_his.append(acc) print("acc calculating time: ", time.time() - acc_start)This returns1.739304780960083.However, I also...
ptrblck
If you are using the GPU, note that CUDA operations are asynchronous, so that you should call torch.cuda.synchronize() before starting and stopping the timer.
f3ba
Is there a way to theDataLoadermachinery with unlabeled data?
ptrblck
Yes, DataLoader doesn’t have any conditions on the number of outputs of your Dataset as seen here: class MyDataset(Dataset): def __init__(self): self.data = torch.randn(100, 1) def __getitem__(self, index): x = self.data[index] return x def __len__(…
hadaev8
Something likedef set_dropout(m, p): if isinstance(m, nn.Dropout2d): m.p = p netG.apply(set_dropout(0.1))
ptrblck
Yes, you can use a lambda for this: def set_dropout(m, p): if isinstance(m, nn.Dropout): m.p = p model.apply(lambda m: set_dropout(m, 0.1)) Note that you are checking for nn.Dopout2d, while the “vanilla dropout” is nn.Dropout. If you are using nn.Dropout2d in your model, please ignor…
111226
I’m trying to stack tensors with different size. But only dimension 2 is different while other dimensions are all same. Is there any way to do this?image922×543 15.4 KB
ptrblck
torch.cat should work: a = torch.randn(5, 5, 1) b = torch.randn(5, 5, 4) c = torch.cat((a, b), dim=2) print(c.shape) > torch.Size([5, 5, 5])
f3ba
I am using the following code to load the MNIST dataset:batch_size = 64 train_loader = torch.utils.data.DataLoader( datasets.MNIST('../data', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor() ])), batch_size=batch_size)If...
ptrblck
dim1 represents the channel dimension. Since MNIST uses grayscale images, the channel dim has a value of 1. nn.Conv2d and other 2-dimensional layers expect an input of [batch_size, channels, height, width].
Daniel_Joseph
Hello everyone ,I want to get the test loss and accuracy for every image in every batch and its index, not accuracy and loss for the hole bach. i.e : dictionary that store every single image tested label, loss, index.Thanks in advance
ptrblck
I would recommend to store all predictions and targets in a list (don’t forget to wrap this code in a with torch.no_grad() block or detach the predicitons) inside the loop. Once you’ve collected all predictions and the corresponding target, you could use sklearn.metrics.confusion_matrix (or search …
gebrahimi
I am trying to train vgg-16 model on birds-200 data. the input is size [3, 448, 448] and there are 200 classes. My gpu is empty but when i try to run the code, i get the following error.RuntimeError: CUDA out of memory. Tried to allocate 392.00 MiB (GPU 0; 7.93 GiB total capacity; 7.28 GiB already allocated; 111.25 MiB...
ptrblck
Could you try to lower the batch size even further or resize the spatial size of your input images to e.g. 224x224?
Wong
Hi everyone,We have a question. What is the difference between optimizer.zero_grad() and model.zero_grad()? Do they need to be defined together when programming?Thanks.
ptrblck
While creating an optimizer, you could pass parameters to it. In a lot of cases, you would just pass all model parameters to a single optimizer, so both calls will yield the same result (zeroing out the gradients of all parameters). However, you could also pass the first half of the model paramete…
adrjj
HI guys,In the context of semantic segmentation (19 classes) my model output a tensor of size :(b, 19, h, w).I need to merge some classes to get a tensor of size(b, 10, h, w)with respect to a mapping dictionary:dic = {9:[0,1], 8:[3,4], 7:[9,10,11], 6:[6,7,8], 5:[2,5], 4:[18,17,16], 3:[4,5,6], 2:[12,13], 1:[15], 0:[14]}...
ptrblck
I’m not sure, if you could use an alternative to a simple for loopb, h, w = 2, 4, 4 x = torch.randn(b, 19, h, w) z = torch.zeros(b, 10, h, w) dic = {9:[0,1], 8:[3,4], 7:[9,10,11], 6:[6,7,8], 5:[2,5], 4:[18,17,16], 3:[4,5,6], 2:[12,13], 1:[15], 0:[14]} for key in dic: d = dic[key] z[:, k…
RichardOey
I want to make a Discriminator (GAN) and below is my code,def __init__(self): super(_D, self).__init__() self.conv1 = nn.Conv2d(3, 128, kernel_size=3, stride=2, padding=1) self.batchNorm1 = nn.BatchNorm2d(128) self.leakyReLU1 = nn.LeakyReLU(negative_slope=0.2, inplace=True) ...
ptrblck
The error message seems to point to the loss calculation. Could you check the shape of your model output and target and make sure the batch size is equal?
chunchun
I get the error ‘nan or inf for input tensor’ when I change SGD to RMS,Why?
ptrblck
I’m not sure, but my guess would be the internal functionality of RMSProp. This optimizer divides the gradient by a running average of its recent magnitude. If your gradients are quite small, since you’ve already trained your model for a few epochs, I assume this division might blow up.
jwillette
I am using a model where I want to initialize some random state in my Dataset that decides how many context points to add to the current instance (from this paper:https://arxiv.org/pdf/1807.01613.pdf)I can’t figure out how to call a function on each batch. The only requirements I have is thatIt can be seen by the Datas...
ptrblck
You could probably create an internal attribute in your Dataset's __init__ and manipulate this attribute inside the training loop via: loader.dataset.my_flag = my_value. This .my_flag could be checked in __getitem__. However, if I’m not mistaken, this will only work using a single process. For mu…
hyperactve
I’m trying to run the following code and run a network on Cuda. However, it seems I’m running into problem as the error:RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the sameon the lineout = net(p).Here is the code:import torch import torch.nn as nn import torch.nn.func...
ptrblck
Your modules won’t be properly registered, if you append them in a plain Python list. Use nn.ModuleList instead and the model.to() call should push all parameters to the device.
copyrightly
I am usingthis codeto do experiments on MNIST. I am wondering how to save the images receiving wrong predictions and the wrong predicted results (like a 7 predicted as 1). Thank you!
ptrblck
You could adapt the test code to check all wrong predictions and store the passed images as shown here: import torchvision.transforms.functional as TF def test(args, model, device, test_loader): model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, target i…
Majid_Shirazi
Hi everyone, I would like to do image classification of my own dataset (containing nump images). I am using RNN for this purpose but I got runtime error of " Expected object of scalar type Byte but got scalar type Float for argument#2‘mat2’ in call to _th_mm". this happens when images going to pass to model.here is my ...
ptrblck
Could you check the type() of your images tensor? I assume, if might by a ByteTensor, while a FloatTensor is expected to match the tensor type of the model’s parameters. In that case, you could call images = images.float() to get the expected type. Also, if that’s the case, I assume you have not …
seankala
I’m currently loading in my data with one single dataset class. Within the dataset, I split the train, test, and validation data separately. For example:class Data(): def __init__(self): self.load() def load(self): with open(file=file_name, mode='r') as f: self.data = f.readlines() ...
ptrblck
I’m not sure there is a clean way of handling different subsets within a single Dataset class. If you want to handle the split yourself, I would rather create a custom function or class (if statefull) and return the corresponding dataset using e.g. TensorDataset or Subset. E.g. this might be a usa…
seankala
Hello. The make the question title a bit more eloquent, basically I’m running a model with PyTorch tensors and for some reason every time I try to get the ouput from the model I get*** RuntimeError: Expected object of device type cuda but got device cpu for argument #1 'self' in call to _th_index_selectHere’s the model...
ptrblck
Could you run the code with CUDA_LAUNCH_BLOCKING=1 python script.py and post the stack trace here? This would hopefully point to the line of code, which throws this error. Also, could you add print(indices.device) before the self.embed(indices) call in MatEmbedding?
seankala
Hello. I’m currently trying to run a deep learning model using PyTorch. This is a rather common question, but I’m not able to figure out what the problem is with my code.Right now, the model block that I’m running looks like this:self.linear = nn.Sequential(nn.Linear(in_features=2048, out_features=512), ...
ptrblck
Could you post your code here so that we can have a look? Based on your description, it should work, and we cannot debug any further without seeing the code.
John_Deterious
I have an autoencoder with 2 submodules (trained and ready). How to split it to two separate NNs each with its own weights and forward method?
ptrblck
How did you define your current model? If both submodules are instances of nn.Sequential, you could recreate them separately outside of your current model and just load the state_dicts into them. If your modules and forward is more complicated, you could still redefine the submodules, but would mo…
Shashank_Shekhar
While training semantic segmentation i had 23 classes including Ignore label, during my prediction i get only 22 classes. I have usedcross entropy lossand providedignore index as 255.What looks from the predicted image is one of the class(class_name:vegetation, id:21)merge with ignore index as seen in the below image....
ptrblck
This would explain, why your model predicts random classes for these pixel locations. Basically, your model will not get any information for these locations, as they are ignored, and can just output any random class. In your case it seems the vegetation class was picked. You could transform all 25…
Neda
I am wondering why CPU inference time varies for Vgg16 and ResNet18. I am using the following script to measure the inference time on CPU for three different modes which I did train from scratch for my custom dataset.inference time: ResNet18 = 12.88 millisecond, Vgg16 = 66.85 millisecond, and my propsoed model = 11.72 ...
ptrblck
Your code looks generally fine for profiling the CPU. The inference speed might not linearly depend on the number of parameters. E.g. convolution layers have very few parameters (just the kernels, which are often small and the bias which is also usually small), while the actual operation might be …
Marat
I have simple example (1.1.0 pytorch)import torch print(torch.__version__) x = torch.rand(1, 3, 2, 2) for running_stats in [False, True]: for eval in [False, True]: print('running_stats:', running_stats, 'eval:', eval) bn = torch.nn.BatchNorm2d(3) bn.track_running_stats = running_stats ...
ptrblck
This shouldn’t be the case as shown here: x = torch.rand(1, 3, 2, 2) bn = nn.BatchNorm2d(3) bn.eval() print(bn.running_mean, bn.running_var) out = bn(x) print(out) bn.running_mean = torch.tensor([100., 100., 100]) print(bn.running_mean, bn.running_var) out = bn(x) print(out)
Filos92
Hey Folks,My problem is this.Currently I have an almost arbitrarily large dataset with which I want to train a common network architecture e.g. Resnet18.My problem now is that this data set does not consist of images but only of single variables. So I have to get from a 10x1 to 3x224x224 somehow.should i create a first...
ptrblck
The main question would be: how would you like to “reshape” your 10 values to a tensor of [3, 224, 224]? I.e. you could somehow interpolate the values, just repeat them, fill with some other information?
kabilan
I have saved my model using the codetorch.save(the_model.state_dict(), PATH)after trainingwhile loading, I am confused. can someone explain this codethe_model = TheModelClass(*args, **kwargs) the_model.load_state_dict(torch.load(PATH))
ptrblck
These constructs are used to pass a variable amount of arguments to a class instantiation or function in Python. Have a look atthis explanationfor more information.
Huimin_ZENG
Hi! I have read this post:CUDA memory leakage.In the discussion, I find that this makes great sense to me:Often memory leaks are created by trying to store some training information like the loss without detaching it from the computation graph, which will store the whole graph with it.However, I don’t understand why th...
ptrblck
Yes, this should be the case, if you didn’t wrap the code block in a with torch.no_grad() block. Which model are you using? Also, how are you checking the memory usage? Could you print it using torch.cuda.memory_allocated() in the loop?
vainaijr
How do I set a high dropout rate during the beginning of training, to make weight matrix more sparse, and after every certain epochs, keep reducing this dropout rate?for example, for the first 50 epochs, dropout rate could be 0.7, for next 50 epochs, 0.6, then 0.5, and for last 50 epochs, dropout rate could be 0.2.And ...
ptrblck
If you are using dropout as a module, you could manipulate the .p attribute after your specified number of epochs: drop = nn.Dropout(p=0.5) x = torch.randn(10) out = drop(x) print((out==0.).sum()) > tensor(5) drop.p = 0.2 out = drop(x) print((out==0.).sum()) > tensor(1) In your case, the manipul…
chunchun
I try to print loss.backward() then I got none,but the network training is still running.Why ?
ptrblck
Yes, if you want to print out all gradients, you could use: print(model.layer.param.grad) # or to print all gradients for name, param in model.named_parameters(): print(name, param.grad)
justanhduc
I have a CUDA kernel and I want to add FP16 support for it. Any idea where I should start?
ptrblck
What is your use case, i.e. would you like to perform the computation in FP16 or pseudo-FP16, i.e. FP32 math for FP16 inputs? Also, what kind of operations are you using inside your kernel? Have a look atnvidia/apexfor some use cases.
heroadz
Hi guys, I am trying to fine tuning BERT with Pytorch. And I use torch.nn.Parallel to train the model in 8 GPUs. After the evalution I delete the model and using torch.cuda.empty_cache().The most interesting is that when the script is running, my server is good. But one I click the “Interrupt the kernel” button, my ser...
ptrblck
Yes, the samples numbers are “correct”, but as you can see they are not fixed. I would recommend to store the randomly initialized state_dicts once and just reload them to the appropriate model during your experiments, to get reproducible results. This would at least reuse the same parameters. No…
TitsHunter
I want to do modify the shape of the convolution layer so that it doesn’t just calculate the up and down direction. It should be something like thedeformable convolutionbut with less flexibility.For example, I may want to implement a 2D Conv with shape like this:directional_conv587×582 510 BytesIs that possible with bu...
ptrblck
If you have the mask for the current pattern, you could use it to zero out the initial randomly initialized weight matrix as well as the populated gradients after the backward() call. Each backward will accumulate the gradients in the param.grad attribute. Let me know, if you get stuck.
dato_nefaridze
in pytorch transfer learning tutorial there is following code:model_ft = models.resnet18(pretrained=True) num_ftrs = model_ft.fc.in_features # Here the size of each output sample is set to 2. # Alternatively, it can be generalized to nn.Linear(num_ftrs, len(class_names)). model_ft.fc = nn.Linear(num_ftrs, 2)they remove...
ptrblck
You can see the layers via print(model) or have a look at thesource code. You’ll see that, model.fc addresses the last linear layer, so you can just reassign a new layer to this attribute. Each nn.Linear layer has a weight matrix (and optionally bias), which is defined by the input and output sha…
cyanM
For some reasons, I use retain_graph = True and hook to get the gradient while backward, but this will lead to the gpu memory leak because the computation graph is not released. so how can i free graph manually?
ptrblck
If I’m not mistaken, the graph should be cleared once all attached tensors are deleted. Since Python uses function scoping, you could wrap your calls in a function and the computation graph should be freed once you leave the function scope (if you don’t return the output tensor and keep it alive of…
111215
Experts, ‘polyp’ is my category, and only this category, and I’m running on a network called ‘RefineDet.’ how can I fix this?image1895×742 139 KB
ptrblck
It seems the error is raised, since 'polyp' isn’t defined in the self.class_to_ind dict. Also it seems your data loading pipeline is implemented in RefineDet.PyTorch-master/data, so you might get a better answer from the maintainers of the used repository.
Tupac
Hi, I have the below CNN code, but I get an error when computing the Cross Entropy loss. Seems the shape of my y_hat is different from y_train, so how do I make the dimensions match?X_train: torch.Size([1, 3, 708, 256])Y_train: torch.Size([1, 708, 4])class CNN(torch.nn.Module): def __init__(self): super(CNN...
ptrblck
Could you explain the shape of your target a bit? Based on your model definition it looks like you are dealing with a multi-class classification, where you try to classify one out of four possible classes for each sample. If so, the target should be a LongTensor with the shape [batch_size] contain…
soaxeus
I’m convertingpytorch.tensor()object tonumpy arraylike the below code.tensor_data.cpu().detach().numpy()But it takes approximately 0.33 seconds. Is it normal?
ptrblck
If your data is on the GPU, you would have to transfer the data to the RAM first via .cpu() and call numpy() on it. Note that (as@albanDmentioned) the numpy() call should be really cheap, as the underlying data will be shared and no copy will be involved. Since CUDA operations are asynchronous, …
jonas15
Hi everyone,I’m implementing a Siamese network. Herefor I always need two images, which should be randomly sampled with p=0.5 as both from the same class and from different classes.My idea isclass SiameseDataset(MyOwnDataset): # Source: https://github.com/harveyslash/Facial-Similarity-with-Siamese-Networks-in-Pytor...
ptrblck
Your approach sounds reasonable. I think you could change SiameseDataset a bit and just sample from the ConcatDataset as shown here: class SiameseDataset(Dataset): def __init__(self, dataset): super().__init__() self.dataset = dataset def __getitem__(self, index): …
Weng_zhiqiang
Hi everyone,I have a question about how to change the Normlization methond in resnet. When I first look at the code of resnet, I found that there is a attribute named norm_layer, where we could create BN layer. So, I try to initializing the norm_layer withnn.GroupNorm. However, I notice in the code of resnet, we just d...
ptrblck
Rewriting the model definition would of course work. However, using getattr and setattr might be the hacky but faster way: class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.conv1 = nn.Conv2d(3, 3, 3, 1, 1) self.bn1 = nn.BatchNorm2d(3) …
Rocket
Hibatch_size = 100 train = TensorDataset(train_X,train_Y) trainLoader = DataLoader(train,batch_size, shuffle=True,num_workers=1) model=model.cuda() for i,data in enumerate(trainLoader): train_x, train_y = data train_x = train_x/255 #train_x,train_y = Variable(train_x), Variable(train_y) train...
ptrblck
Are you using the same batch size to compute the new output? If you don’t need to train the model, wrap the code in a with torch.no_grad() block to save memory.
phantom90
Hi there,I am current using the dataloader (torch.utils.data.DataLoader) to get batches for model training.By default, is each sample selected exactly once in one epoch? A epoch is defined as follows:for epoch in range(10): for j, (inputs, labels, _) in enumerate(dataloader): somethingThanks!
ptrblck
By default the DataLoader will use a SequentialSampler, if shuffle=False, otherwise RandomSampler with the default argument replacement=False, which would yield each sample only once in each epoch.
sinang
I noticed that there is a weird slow down after using an if statement in my code. I load an image onto CUDA device, then my neural network (fixed parameters) detects if there is an object or not in the given image. If there is an object, pixel values take values different from zero in the corresponding region, otherwis...
ptrblck
You are most likely just measuring the kernel launch times in your second code snippet. To properly time a segment, you would have to synchronize before starting and stopping the timer. E.g. this code should show a high duration in the actual forward pass: while i < 10: with torch.no_grad():…
Zhaoyi-Yan
IncompatibleKeys(missing_keys=[], unexpected_keys=[])When I tried to use IBN-net as an feature extractor, I met an error.GitHubXingangPan/IBN-NetInstance-Batch Normalization Networks (ECCV2018). Contribute to XingangPan/IBN-Net development by creating an account on GitHub.class LargeModel(nn.Module): def __init__(s...
ptrblck
This is not an error, since no incompatible keys were found. Since this message was quite misleading, it was removed already and you shouldn’t see it in the current stable release (1.3.1).
MarcSteven
Is it possible to do the task of softmax layer in pytorch, I know Tensorflow can do it
ptrblck
You can return dicts in your forward method: class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.fc1 = nn.Linear(1, 1) self.fc2 = nn.Linear(1, 1) def forward(self, x): x1 = self.fc1(x) x2 = self.fc2(x) r…
aauker
Hi All,I have what I hope to be a simple question - when mu and variance are calculated in the batchnorm layer, are the gradients propagated to the scaling? I.e., are the mu and var in y = (x - mu) / sqrt(var + eps) simple numbers or the gradient tracked tensors?I’m asking because I want to implement a modified versio...
ptrblck
I wasn’t sure, but based on this small code snippet, it seems the latter approach is used: # Manual without detach torch.manual_seed(2809) x = torch.randn(10, 3, 4, 4, requires_grad=True) mean = x.mean(dim=[0, 2, 3], keepdim=True) invstd = torch.sqrt(x.var([0, 2, 3], unbiased=False, keepdim=True) …
lfolle
Why does thetorch.utils.data.WeightedRandomSamplersample theses values only approximately equal with equal weights?list(WeightedRandomSampler([0.3, 0.3, 0.3], 1000, replacement=True)).count(2) Out[15]: 346 list(WeightedRandomSampler([0.3, 0.3, 0.3], 1000, replacement=True)).count(1) Out[16]: 339 list(WeightedRandomSamp...
ptrblck
The passed weights are used in torch.multinomial as seenhere, which is a random function, so you cannot expect a perfectly sampled distribution. The sample count will approximate the expected number, the more samples you are drawing.
Alex_Luya
For example,in a dataset which contains cats and dogs,In C==1 case,the requirements is:Just segmenting out cats,treating all others as background(of course target will just label cats as 1,set all other pixels to 0)In this case,should the output channel be 1 or 2?In my opinion,it can be either 1 or 2,if setting output ...
ptrblck
For a binary classification use case, you can use either one or two output channels. For a single channel output, you could use nn.BCEWithLogitsLoss. If you are using two output channels, you could treat your use case as a multi-class classification (only one valid class per pixel) and use nn.Cr…
Alex_Luya
CrossEntropyLoss doc say the target value must be:0≤targets[i]≤C−1And I have 4 type of objects which must be segmented,in this case C==4,and if I want to use single channel target image where all values must be <=4,if 0 for background,1 for the first type of objects…and How to encode the FOURTH type of objects?Or shoul...
ptrblck
You would treat the background as a separate class, thus your target mask will have values in the range [0, 4].
Shubhankar
How to use NVIDIA AUTO TUNE with pytorch.
ptrblck
I’m not familiar with TensorFlow, but it seems their “auto tune” functionality corresponds to torch.backends.cudnn.benchmark = True mode.
Naruto-Sasuke
It is fine to eval net with BN layers with batchsize > 1?
ptrblck
Yes. During evaluation (after model.eval() was called), the running estimates for the mean and variance will be used for every sample, so the batch size doesn’t matter.
Yolkandwhite
Hi I’m an newbie in pytorchI’m studying torch on this tutoralhttps://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-pyimport torchimport torchvisionimport torchvision.transforms as transformstransform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((...
ptrblck
The DataLoader calls into the passed Dataset's __getitem__ method to load and process the next sample. Have a look atthese lines of codeto see, how the CIFAR10 datasets loads each sample.
HuynhSang
Hello everyone, I wonder if someone could help me with this. I created a mini test with pytorch.nn.CTCLoss, and i don’t know why it return negative.import torch from torch import nn print(torch.__version__) # 1.3.1 # Initialize random batch of input vectors, for *size = (T,N,C) input = torch.FloatTensor([[[0.1, 0....
ptrblck
nn.CTCLoss expects log probabilities as the input as described in thedocs. If you call ìnput = input.log_softmax(2)`, you’ll get a positive loss value.