user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
Niki
Hi,I got confused about the image index concept by usingtorch.utils.data.DataLoader. This index is the index of image for the entire training/testing dataset or just index of image for the mini_batch? If it’s for the mini_batch then it means in the next mini-batch, the image with index 1 is the same as the previous ima...
ptrblck
You could write a custom Dataset and return the index with the data and target. def __getitem__(self, index): # your data loading logic x = self.data[index] y = self.target[index] # transformations ... return x, y, index This would yield an additional batch of the used…
CesMak
Hey there,I have this model:class PlayingPolicy(nn.Module): def __init__(self): super().__init__() # Parameters self.gamma = 0.9 # reward discount factor # Network in_channels = 4 # four players out_channels = 8 self.conv418 = nn.Conv2d(in_channels, out_ch...
ptrblck
state is passed as a numpy array, which is not supported. Try to pass it as a tensor and check, if it’s working.
YinYang_Untalan
if i call .eval() on my model that had dropout layers… does pytorch automatically scale the weights? and calling .train() will rescale accordingly as well?
ptrblck
Yes, the activations will be scaled automatically. In face this is done during training, while model.eval() just uses the model as it is.
Hari_Krishnan
Hi,Here is a snippet of the code I have implemented.class BiDAF(nn.Module): def __init__(self,char_embeddings,glove_model): super(BiDAF,self).__init__() self.context_highway = Context_Highway() self.question_highway = Question_Highway() self.char_embedding_dict = char_embeddings ...
ptrblck
If you need to create these tensors inside create_question_char_embedding, you could try to use the device attribute of a model parameter and create the new tensors on the same device: char_tensor = torch.zeros(50, 45, device=self.parameter.device)
YinYang_Untalan
I trained my ann with all layers unfrozen. Then I froze all all my layers using layer.requires_grad = False.Then I trained it again. The outputs change. I have taken a look at the state_dict of one of the layers to see if the weights have been changed - they are still the same.Am I missing something here? How do I prop...
ptrblck
I guess you might have some dropout or batchnorm layers in your model, which are still active even though the trainable parameters are frozen. Calling model.eval() will use the running stats in batch norm layers (instead of using the current batch stats and updating the running estimates) and dropo…
YinYang_Untalan
Say I have a 3x3 kernel for a conv. A normal conv2d would multiply the same 3x3 numbers to all the channels and add them up. What if, say i have 3 channels as input and instead of using the same 3x3 numbers for all the channels, i have different numbers effectively 3(channel) x 3 x 3 (kernel size). How would I do this?...
ptrblck
The second use case is actually a vanilla convolution and you can check the kernel shape via: print(nn.Conv2d(3, 1, 3).weight.shape) > torch.Size([1, 3, 3, 3]) # out_channels, in_channels, height, width Have a look atCS231n - Convolution layers, which describes the underlying method quite well.
Aka
I’m applying transfer learning to the resnet50 from torchvision models, i.e. replaced the last fc layer with 2 neurons for binary classification problem. All other layers are frozen. I started training the network with learning rate 1e-2 and reducing it by a factor of 0.1 after 5 epochs if validation loss is not decrea...
ptrblck
Your initial learning rate might be too high. Lowering the learning rate might “start” the training. If your dataset is quite easy (based on the step size it seems you are using very few samples), the model might instantly overfit the training data.
Ameen_Ali
Hello,I have two tensors :first = [A , B , 2048].second = [C , D 2048]Where A > C and B > D.how can I padd the second tensor with zeros so it match the first tensor dimensions, and in generally does padding affectu accuracy ?Thanks
ptrblck
You could use F.pad: A, B, C, D = 5, 4, 3, 2 a = torch.randn(A, B, 2) b = torch.randn(C, D, 2) out = F.pad(b, (0, 0, (B-D)//2, (B-D)//2, (A-C)//2, (A-C)//2)) print(out.shape == a.shape) Note that F.pad pads starting from the last dimension. This might be the case, but I think as long as you pad…
KUSHAL_JAIN
Many papers use Google Lenet pool5 layer’s as features for images/video-frames. I need a feature vector whose dimension is 1024. I figured out the corresponding layer in PyTorchtorchvision.models.googlelenet()is theAdaptiveAvgPool2dlayer. However, the ouputs from this layer for one image are of shape [1, 1024, 1, 1]. I...
ptrblck
Yes, you could squeeze these dimensions and process your activation as [batch_size 1024].
chat_on
Hello,I am really sorry for this question which is probably trivial to answer but I am struggling to find an answer and I am a beginner.I am trying to implement a simple autoencoder following the RedNet architecture designed for denoising (I know there exists many implementations but it is just a way for me to understa...
ptrblck
Hi Francois, Autograd will track all operations in the forward pass in a computation graph and use it in the backward pass to calculate the gradients for all parameters. You can pass the output of one module/model to another one. As long as you don’t detach the activations e.g. via tensor = tensor…
Uk_Jo
Help meimport torchimport randomt = torch.randn((32,100))a = torch.tensor([random.randint(0,100) for a in range(32)])torch.gather(t, 1, a)Traceback (most recent call last):File “”, line 6, inRuntimeError: invalid argument 4: Index tensor must have same dimensions as input tensor at C:\w\1\s\windows\pytorch\aten\src\TH/...
ptrblck
If you want to use a as the index in dim1 for t, this code should work: t[torch.arange(t.size(0)), a]
Thabang_Lukhetho
I was printing the shape of my tensor inside thegetitemfunction, and noticed that it does not print to the console the shape of the tensor when num_workers>0. I’m using windows 10 and pytorch 1.1.0
ptrblck
Do you get the outputs eventually or are these outputs lost? The output of multiple workers might overlap, but should be printed. That being said, I’m not really familiar with Windows. Also, could you update the the latest stable release (1.4.0) in case this was a known issue and was fixed alread…
lycaenidae
What is the purpose of the usage of aux_loss?
ptrblck
The Inception models used it to increase the gradient signal during the training as explained inGoing Deeper with Convolutions.
Innisfree
Hi, I would like to pretrain BERT by using DDP.I saved pretrain dataset(350GB of large corpus) as torch.tensor.When I run the code below, dataset is loaded in memory 8 times.python -m torch.distributed.launch --nproc_per_node=8 train.pyHow can I prevent it?Thanks.
ptrblck
Did you store the complete dataset in a single tensor? If so, I think you might need to load it once and store smaller chunks of the data (and load only certain chunks in each process) or load the data lazily from the beginning.
Sybil
I have read posts about model sharding and have found really good examples.However, when I implemented it, at the 2nd epoch, I got the following error:RuntimeError: Expected tensor for argument #1 'input' to have the same device as tensor for argument #2 'weight'; but device 0 does not equal 1 (while checking arguments...
ptrblck
Did you call to() on the model after the first epoch, e.g. in your validation loop? Could you post a code snippet to reproduce this issue?
maroov
I’m trying to build a network for my thesis that splits VGG into three modules (smaller networks) and train it with THE CIFAR10 dataset. I’m kind of new to pytorch wo please be kind. I probably made HUGE mistakes, so it would be great to know the proper way to fix them so that I can get a better understanding on the fi...
ptrblck
The error is raised, because you are trying to feed the output tensor again to the complete model via self.features. Remove self.features as it’s not doing anything at the moment. Once this bug is fixed, you’ll run into a shape mismatch, as our activation won’t have 128 features to be suitable for…
ykukkim
Hey all,I am using IterableDataset as my data’s length are not uniform and it varies a lot. Now I am trying to implement a validation step in my training loop which requires the length of the dataset, but as it iterable, len() cannot be used.def val(self, epoch):test_loss = 0 correct = 0 with torch.no_grad(): ...
ptrblck
I think your approach of storing the number of samples in total is valid for your use case. Instead of dividing by len(self.test_loader.dataset), just divide by total.
wenyugu
The documentation for torchvision.transform seems to be not clear enough. There are several questions I have.Does Compose apply each transform to every image sequentially. If order matters, what if I want to don’t want to apply transform in a composite way? (i.e. if I want to apply either flipping and then normalizatio...
ptrblck
Yes, the order of transformations will stay the same, if you don’t usetransforms.RandomOrderor manipulate the list in another way. You could usetransforms.RandomApplyor RandomChoice it that fits your use case. Otherwise just add a condition to switch between both approaches (e.g. in your Datase…
JakeAndFinn
I am playing around with making several different data loaders using different transformations and methods and got this errorRuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 280 and 499 in dimension 2 at /opt/conda/conda-bld/pytorch_1579022034529/work/aten/src/TH/generic/THTensor...
ptrblck
Based on the error message it seems the spatial size is different for the loaded tensors, which will raise this error while creating a batch. You could add transforms.Resize(size) to the transformation to create tensors with the same spatial size.
kuzand
Can someone please explain whattorch.multinomialdoes?With numpy’snp.random.multinomialit is more or less clear: it take the number of trials (experiments), the probabilities for each outcome (which sum up to 1) and the size of the output (i.e. the number of drawn samples). So for example, if we the experiment is to thr...
ptrblck
torch.multinomial will return the drawn indices, while numpy returns the count of the drawn samples. To get the count, you could use unique(return_counts=True): weights = torch.tensor([1/6.]*6, dtype=torch.float) out = torch.multinomial(weights, 20, replacement=True) out_count = out.unique(return_…
Vikings
I’m a beginner of PyTorch and when I trying to run the following code:x=torch.tensor([[5,3],[5,3]])z1=x.view(1,4)z2=x.view(4,1)print(z1+z2)I got:tensor([[10, 8, 10, 8],[ 8, 6, 8, 6],[10, 8, 10, 8],[ 8, 6, 8, 6]])Why doesn’t the compiler throw an error? Why two tensors with different dimensions can be added to...
ptrblck
This behavior is called broadcasting and tries to stay as close as possible to numpy’s implementation, which is describedhere.
gamingsam77
Why does CrossEntropy throw this error. Im new to pytorch and deeplearning in general so not sure what is really going on here.import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader import torch.optim as optim import pandas as pd import numpy as np df ...
ptrblck
nn.CrossEntropyLoss is used for a multi-class classification, while your model outputs the logits for a single class. If you are dealing with a binary classification, you could use nn.BCEWithLogitsLoss, or output two logits and keep nn.CrossEntropyLoss.
sinaabdollahi
Suppose that I defined a class as follows:class A(nn.Module): def __init__(self, some_params): #SOMETHING HERE (for example several Linear) def forward(self, x): #SOMETHING ELSE HERENow, suppose I want to use an array of class A in another model. Does the following way work?class B(nn.Module...
ptrblck
This won’t work, as your A module won’t be registered in a plain Python list, so you would have to use a nn.ModuleList instead. This will make sure to register the passed module as well as all parameters in the parent module. Calling B.parameters() will thus yield all parameters. You could double…
Mohamed_Ragab
I train on 10% percentage of my data. I use subset randomsampler but it seems that it select different subsets each epoch, How can I fix the same subset each epochsubset_idx = torch.arange(1000) # 10%my_sampler=SubsetRandomSampler(subset_idx)train_dl = DataLoader(MyDataset(X_train_Si,y_train_Si), batch_size=hparams[‘ba...
ptrblck
I’m not sure to understand the use case completely. If you are calling this line of core once per epoch, you would only get a single batch. On the other hand, if you are calling it in each iteration, you are recreating the Iterator every time. Could you try to iterate the DataLoader directly via: …
ahkarami
Can we use theFaster-RCNNmodel of torchvision, batch-based on the inference time?for example:import torch from torchvision import models model = models.detection.fasterrcnn_resnet50_fpn(pretrained=True) model.eval() img = torch.randn(2, 3, 224, 224) # [N, C, H, W] pred = model([img]) # Pass the image to the modelt...
ptrblck
Batching should be done under the hood, if you pass a list of tensors.self.transformwill e.g. resize all tensors to [3, 800, 800] and create a batch as [batch_size, 3, 800, 800].
blidger
Hi! I am trying to define a python function with learning rate as the only parameter, which would instantiate a pytorch model, train it using an optimizer with the passed learning rate, and then print out training statistics. My code looks like this:def get_lr_performance(loc_lr): loc_model = nn.Sequential( #so...
ptrblck
You are passing opt to train, while train_model gets optimizer passed in. Could opt refer to some global optimizer?
R_Tux
I have created my training data for a CNN and would like to save it for future training.How would I go about saving my training data and then loading it again?My training data looks like:X.shape Out[346]: torch.Size([30, 1, 362, 362]) y.shape Out[347]: torch.Size([30, 131044, 3])
ptrblck
torch.save and torch.load should work.
sidd.suresh97
How do I obtain true zero pixels after I have applied the following transform since the values of 0 pixels change? Is there a way of obtaining the zero values along each color channel separately?tfms = transforms.Compose([ transforms.Resize(224), transforms.CenterCrop(224), transforms.ToTensor(), transf...
ptrblck
You could create the masks containing zeros for the black boxes and ones everywhere else, and multiply the normalized input tensor with it.
G.M
I’m usingnn.Unfoldto implementing a custom pooling layer, however, I’d like to keep the last value, like whatceil_mode=Truefor MaxPool would do. It seems that Unfold does not support this, is there a workaround?Thanks.
ptrblck
You could pad the input to create the desired output shape.
aktgpt
I’m trying to implement stratified sampling in my dataset and calculate the weights for each sample in the dataset with the following function:def make_weights_for_balanced_classes(labels):unique_labels, counts = np.unique(labels, return_counts=True)weight_per_class = np.sum(counts) / countsweights = [0] * len(labels)f...
ptrblck
Which line of code is throwing this error? The sampler should rerun a single index and it works fine in this dummy code snippet: dataset = TensorDataset( torch.arange(10).float()) weights = [0.1] * 10 sampler = WeightedRandomSampler(weights, len(weights)) loader = DataLoader(dataset, sampler=…
Laurence_J
Hi, I’m new to audio signal processing and to pytorch and I’m having some trouble understanding this part of the docs of the torchaudio load function:normalization (bool, number, or callable, optional) – If boolean True, then output is divided by 1 << 31 (assumes signed 32-bit audio), and normalizes to [-1, 1]. If numb...
ptrblck
I also assume 32-bit audio corresponds to the bits per sample. 1 << 31 is a left shift by 31 positions, so it translates to 1 << 31 == 2**31 == 2147483648, which would be the max value of each sample. If I’m not mistaken, 32bit audio would have the range [−2,147,483,648, 2,147,483,647], so you wo…
BierOne
Hi! guys! I have a question about weight_norm.My PyTorch version is 1.0.1 in all environments. By the way, I have set the same seeds. But when I use weight_norm in python2.7 and python3.7 respectively, I got different weight_g but the same weight_v.Moreover, I got the same weight_g when I init the linear layer with a ...
ptrblck
I just tried to reproduce this issue, but get similar values for Python2.7 and 3.7 in both use cases (~2.6 and ~26.1). Could you update to the latest stable release (1.4) in your Python3.7 environment and rerun the code? That being said, note that Python2.7 support is dropped and you shouldn’t use…
veeresh_d
Hi all,just wondering can we use the batch normalization layer after thenn.ConvTranspose2dlayers ?
ptrblck
Sure, that’s possible. Are you seeing any issues or errors using it?
HaziqRazali
How can I initialize weights for everything in my class except forself.fcnbelow ? I could write ann.init.xavier_uniform_()for every component but it gets tedious.class EMBED_MP_MLP(nn.Module): def __init__(self, args): super(EMBED_MP_MLP, self).__init__() # fully convolutional network ...
ptrblck
Maybe not the most beautiful approach, but should get the work done: class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.fc = nn.Linear(10, 10) self.non_fc = nn.Linear(1, 1) def forward(self, x): return x def weight_in…
learner47
I have three neural networks,model1,model2andmodel3. I feed an input tomodel1and output of this network is fed tomodel2and further, the output of themodel2is fed tomodel3. I have two loss functions. One formodel2alone and one a global loss function which optimizesmodel1andmodel3weights only.model2is optimized only for ...
ptrblck
model2's parameters won’t be updated unless you call model2_opt.step(). However, if your model contains batchnorm layers, the running estimates will be updated during the forward pass, if you keep these layers in .train() mode. Also, dropout will be applied, but of course there is nothing to updat…
Topsoil
I have a dcgan training on a dataset of living room images of 256 * 256 * 3 size. But for some reason, even after 10 epochs, after some uniform grayscale at the beginning, its output looks like this:https://imgur.com/a/ObzqTrcLosses (sampled each batch) look like this:Code is available at:https://github.com/Grubzeruser...
ptrblck
I guess the view operations will interleave the image pixels, if you try to swap the dimensions with them. Check which shape each loaded sample has in your ImagesDataset. If the sample has the shape [height, weight, channels], you should call sample = sample.permute(2, 0, 1) instead of sample = sa…
E4CE
Hello, I am new in pytorch and currently I trained mnist data in resnet 34 model. After I extracting my feature the size is [1, 512, 10, 10] which I was expecting [1, 512, 1, 1]. Can someone explain to me what does 10 10 stands for?
ptrblck
Thanks for the code. Since you are rewrapping some modules and remove the last linear layer, the output shape will be the last activation after the average pooling layer. For your input shape, it’ll be [batch_size, 512, 10, 10]. If you want to get a single pixel in the spatial size, you would hav…
Janine
Hi all,I need a bit of help with my PyTorch code. I am trying to generate a random image, and then optimize its cell values in order to be classified as a targeted class by an image classifier, the optimization seems to work for the first iteration, and then raise the ValueError: can’t optimize a non-leaf Tensor.I am q...
ptrblck
You are creating a non-leaf tensor with the torch.clamp operation: created_image = torch.normal(mean=1, std=1, size=(1,1,28,28), requires_grad=True) print(created_image.is_leaf) > True created_image = torch.clamp(created_image, -1, 1) print(created_image.is_leaf) > False Try to change the output o…
brtrentini
Hi everyone,this is my first post in the forum and I believe you can help me clarify one thing: is it acceptable to have validation log loss lowe (or much lower) than training log loss? And if so, how much this gap should be at most?I am using Inception V3 to classify 120 classes of images with 30K training examples wh...
ptrblck
Aurelien’s explanations seem reasonable and it’s what I observe usually. If you want to make sure dropout and the running estimates might be the cause for the gap, you could set your model to model.eval() and use the training dataset after the epoch (same as where you are calculating the validation…
Tino
Is it possible to visualize the activations of each layer? I am using the ImageNet dataset and would like to see the features.
ptrblck
You could use forward hooks as describedhere.
Kirty_Vedula
I am training an autoencoder for a multiclass classification problem where I transmit 16 equiprobable messages and send them through a denoising autoencoder to receive them. I am trying to implement the result (modification of Fig. 3b) in this paper, to be specific: Please refer to Fig. 2 inhttps://arxiv.org/pdf/1702.0...
ptrblck
Your first approach would reinitialize your model, so I assume this won’t work, as you are not testing your trained model. The second approach looks alright. Could you check the data type of (pred_labels != test_labels) and make sure the sum does not overflow? This shouldn’t be the case in the cur…
k11
In my denoising work, I usetorch.optim.lr_scheduler.StepLRto adjust learning rate. But it seems different betweenscheduler.step()andscheduler.step(ave_train_loss)that I called in each training epoch’s end.After training,I test both two models in same images, and get following result:TIM图片202002181459101086×540 190 KBFi...
ptrblck
If you are passing the epoch argument to StepLR, it will be ste inthis line of codeand used to calculate the learning ratehere. Since you are passing the average training loss, this should influence your learning rate scheduler.
Yuerno
Hi all. If I have a batch of uniform 3D grids of coordinate locations, with shape (for example), [1, 32, 32, 32, 3], what is the best way for me to split this up into multiple even chunks, so I could end up with something such as [1, 4096, 2, 2, 2, 3]? In other words, I’m splitting up that one big 32 x 32 x 32 cube whe...
ptrblck
tensor.unfoldcould be used here. Have a look atthis postfor an example.
jerry0098
Hi,I’m using PyTorch to implement a CNN model for collaborative filtering but I got an error like this:Given groups=1, weight of size 1 64 9 9, expected input[1, 1, 16, 16] to have 64 channels, but got 1 channels instead.Input for the model is a tensor havingtorch.Size([1, 1, 256, 64])Code for the CNN:CNN_modules = [] ...
ptrblck
Your second conv layer is returning an activation with a single output channel, while the next conv layer expects 64 input channels (same issue in all following layers). You should set the number of output channels to 64 and your model should work.
ElleryL
Considertorch.Tensor([torch.exp(torch.Tensor([10000]))])it givestensor([inf.])without raising any warning or error. During the training, many time I end up with nan value; and have to debug all the way to figure when did the numerical issue occurs.Is there anyway to fix itI’m using pytorch 0.4.0 on Mac(Both jupyter not...
ptrblck
Checking each value for an overflow could yield bad general performance. To debug an invalid value, you could use torch.autograd.detect_anomaly.
mnslarcher
If I runmodel = models.googlenet(pretrained=False) params_count = sum(p.numel() for p in model.parameters() if p.requires_grad) print("GoogLeNet number of trainable parameters: {}".format(params_count))I getGoogLeNet number of trainable parameters: 13004888But, from the original paper, the number of parameters should b...
ptrblck
When you skip the aux layers, you should get the ~6 million parameters. It seemsTable 1of the original paper does the same.
songyuc
Hi, guys,I am working on reimplementing the DeepLabV3+ these days,and I am thinking about whether the torch.nn.Sequential can take alistof modules as the input?I think this would be an awesome feature!Any answer or idea will be appreciated!
ptrblck
We had discussions in the past about passing multiple inputs to nn.Sequential e.g.in this PRandhere, but in the end the changes were rejected. You could of course use the posted custom sequential containers for your model, if that makes its definition easier.
ssalome
HiI’m using Resnet18(Not Pre-trained) for training images with shape(1, 224, 224)I have 15 output classes.Hence I have modified the first conv2d and the last linear layer accordingly.BlockquoteSequential((0): Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3))(1): BatchNorm2d(64, eps=1e-05, momentum=0.1, a...
ptrblck
It seems you’ve wrapped all modules into an nn.Sequential block. If that’s the case, you are removing the flattening, which is usedheredirectly in the forward method. You could keep the original architecture and change both layers by reassigning the new layers: model = models.resnet18() model.c…
Tino
I have built a network and it seems that my first fully connected layer has not been set the correct input size, my problem is I don’t know how to properly set it. I keep getting the error:in inner(_it, _timer)/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias)1368 if input....
ptrblck
Your forward method uses x as the variable name, while you are passing out to the first layer.
lc5415
Hello, I’m relatively new to PyTorch, I want to to apply Instance Normalization to my images. I am wondering if I can use Normalize as a stand alone function, without needing a tranforms.Compose() or any of the sort. Here is how I am currently trying to implement it:img = someTensor # dimensions [1x224x224] I am using ...
ptrblck
You should unsqueeze the statistics, as you are currently passing scalar values: normal = transforms.Normalize(mean.unsqueeze(0), std.unsqueeze(0)) This should avoid the error, which is caused by mean[:, None, None] inside Normalize.
cedricchan
I setrequires_grad=Falsefor some parameters, and their grad is zero. However, when I runoptim.step(), those parameters still update their values.This is my codefor p in self.G.enc_layers.parameters(): requires_grad_flag = p.requires_grad p.requires_grad = False z_rec = self.G(img_fake, mode='enc') gzr_loss = F....
ptrblck
If these parameters were updated previously using an optimizer with running estimates, changing the requires_grad attribute to False might still result in updates due to the running estimates of the optimizer. If that’s the case, you might need to set these gradients to None, so that they will be s…
SamChen
Hi all,Here is my experimentinput = torch.rand(3,10,6) #method1 as_matrix = torch.bmm(input, input.contiguous().transpose(2,1)) # method2 one_by_one = [] for i in range(input.size(1)): query = input[:, i:i+1, :] temp = torch.bmm(query, input.contiguous().transpose(2,1)) one_by_one.append(temp) one_by_one =...
ptrblck
You shouldn’t worry about the small difference as the errors are in the range of the limited floating point precision. These small absolute errors are created by e.g. different ordering of your operations as seen here: x = torch.randn(10, 10, 10) s1 = x.sum() s2 = x.sum(0).sum(0).sum(0) print((s1…
Mason-Qin
hi!I was attempting to train some part of my model with fp8 and fp16, and i’d like to ask:is there a way to achieve the 1-5-2 fp8 in some calculation, such as plus or mul?normally the fp16 is 1-5-10, is it possible to make it 1-6-9 or 1-4-11?thanks!
ptrblck
I don’t think there is an easy way of changing the exponent and mantissa of the underlying values. You could of course try to simulate these number formats, but I’m not sure how much work that would be.
fdokic
Hi allI have two different instantiations of a model, gn and gx, both consisting of following operators:I instantiated gx using exactly the same parameters as gn (reference).Image Pasted at 2020-2-19 14-471668×1430 251 KBwhat I did:I passed the same input, operator for operator through both models and saved the interme...
ptrblck
Could you post the model definition by wrapping the code into three backticks ```? Also, are you using e.g. torch.backends.cudnn.deterministic = True as describedhere?
VijayStroup
model = models.vgg16(pretrained=True).to(device) optimizer = optim.Adam(model.parameters(), lr=1e-3) criterion = nn.NLLLoss().to(device) # using NLL since our last output is log BATCH_SIZE = 50 EPOCHS = 1 def load_data(): mean=[0.485, 0.456, 0.406] std=[0.229, 0.224, 0.225] data_transforms = { 'tr...
ptrblck
I think the error is raised, since model.classifier[0] might not have been pushed to the device. While you are using model = models.vgg().to(device) correctly, you are manipulating the classifier later without calling .to() again on this part of the model, so it should stay on the CPU.
Bendrien
Hello there, i am using CrossEntropyLoss for training on sequence data. On my sequence there are sparse single events of which i have labels and their position as indices for the output sequence. I would like the neighbouring samples of a single event to be labeld in the same manner as the event it self but with reduce...
ptrblck
Your approach should work, if you also slice the labels tensor. However, if might be easier to avoid the loss reduction via reduction='none' and multiply your loss tensor with a weight tensor. However, I doubt you will see a huge performance difference.
cbd
I convert 2d array(arr2d) to 3d array(arr3d) and save as image using below code. arr2d is float64 type. Why save image is not color image?arr3d[:, :, 0] = arr3d[:, :, 1] = arr3d[:, :, 2] = arr2darr3d=arr3d*255im=Image.fromarray(np.maximum(np.minimum(arr3d, 255), 0).astype(np.uint8))im.save(“sample.png”)
ptrblck
This dummy code produces a color image: x = np.random.randn(224, 224, 3).astype(np.float64) x = x * 255 x = np.clip(x, 0, 255) img = Image.fromarray(x.astype(np.uint8)) Could you check that your color channels have different values?
zhishen_nie
Recently, I use pytorch to generate some adversarial samples, and the algothim is FGSM. Just likehttps://pytorch.org/tutorials/beginner/fgsm_tutorial.html. It was very smooth at the beginning of mu program. But soon pytorch told me that cuda is out of memory. I guess there will be a part of the GPU memory has not been ...
ptrblck
Duplicate post fromhere. Let’s please keep the discussion in your created topic.
zhishen_nie
While i run the code of FGSM, i find there is 1mb gpu memory can’t br relased in every loop.And available GPU memory is decreasing. My code is here:def gen_adv(model, device, data, target, epsilon):data, target = data.to(device), target.to(device) data.requires_grad = True # 1067mb 1068mb output = model(data) # 12...
ptrblck
Are you storing some tensors in e.g. a list without detaching them? Also, could you use: with torch.no_grad(): data_grad = data.grad instead of calling the .data attribute, as it might yield unwanted side effects.
parth_soodan
Hi, I am new to using Pytorch. I am facing the above error. My system specifications are given below:OS : Ubuntu 16.04CUDA version - 10.1Device count - 1Device name - GeForce GT 720Device capability - (3,5)Pytorch version - 1.4.0Can someone guide me as to how to resolve this issue?Thanks in advance.
ptrblck
The PyTorch binaries ship with CUDA for GPUs with compute capability >=3.7, while your GPU has 3.5, so you would need to build from source as shownhere. Let us know, if you get stuck somewhere.
oasjd7
I want to train learnable parameterwto re-weight loss.Butwis never changed.What`s wrong?w = nn.Parameter(torch.tensor(0.1), requires_grad=True).cuda() optimizer = optim.SGD(list(network.parameters()), lr=0.1, momentum=0.9, weight_decay=5e-4) ... loss = loss * w optimizer.zero_grad() loss.backward() optimizer.step()
ptrblck
w doesn’t seem to be passed to the optimizer, so that even if this parameter gets valid gradients, it won’t be updated. Also, call cuda() on the tensor, not the nn.Parameter, as this operation will create a non-leaf variable.
JoYeY
Dear all,I train a CNN with GPU and get an error information as figure shows. 30.00 MiB data is to be allicated and 967.43 MiB free but a CUDA out of memory is given:image1319×433 77.4 KBI have no idea on it
ptrblck
In that case the error message might be misleading. How much memory is your training code using with batch_size=1?
Patrice
Hello dear programmers,I am very new to Pytorch with basic programming skills. My task consists of performing segmentation of seismic data. My training data consists of 9 channels and the labels are of one channel. I have managed to build up a network. However, it can not train and it shows the following error“TypeErro...
ptrblck
Try to remove the numpy call for label_pred and label_true and pass the tensors to get_accuracy.
Aviv_Shamsian
Hi all,I have an abstract class which inherits fromnn.Moduleand parent class which inherits fromAbstractClasswhen I try to assign the model to CUDA I don’t get any error but by looking at nvidia-smi the model is clearly not assigned. When I tried to useis_cudaI got an error that my model does not recognize this method....
ptrblck
.is_cuda is a tensor attribute and cannot be used on a module, as a module can hold parameters on different devices. Instead of calling it on the model, you could check some internal parameters. e.g. model.layer.weight.is_cuda.
helson73
SYSTEM info:OS: Ubuntu 18.04CUDA: 10.1pytorch: 1.4.0 installed from condaNVIDIA apex: latest installed from pipGPU: Titan RTX 24GBDriver: 430.64cudnn version: 7603I tested my system with following code:import torch import torch.nn as nn from torch import optim from apex import amp from torch.nn import functional as F ...
ptrblck
Grouped convolutions might not trigger the FP16 path and thus might not use TensorCores.
Mohamed_Ragab
Hi all, I am trying to convert TensorFlow code to PyTorch. But I don’t have any prior knowledge with TensorFlow, I will be grateful if someone can help with this situation. Here is the codedef trial_fun(xs, xt):xs = xs - tf.reduce_mean(xs, axis=0)xt = xt - tf.reduce_mean(xt, axis=0)xs=tf.expand_dims(xs,axis=-1)xs = tf....
ptrblck
The mapping should be: tf.reduce_mean -> tensor.mean tf.expand_dims -> tensor.expand tf.transpose -> tensor.permute Let us know, if you have any trouble.
Xiaoyu_Song
Hi, I’m loading pretrained model for training, and I specified the gpu id for training is 1, but during the training, I saw the gpu 0’s memory is also occupied. Someone could explain? Thank you
ptrblck
Most likely the CUDA context is also initialized on the default device. You could mask all devices and only pass the wanted one via: CUDA_VISIBLE_DEVICES=1 python script.py args
JhonPool4
Hi,Do you know why a have this warning, and what I need to modify so that it doesn’t appear:/pytorch/torch/csrc/autograd/python_function.cpp:622: UserWarning: Legacy autograd function with non-static forward method is deprecated and will be removed in 1.3. Please use new-style autograd function with static forward meth...
ptrblck
Try to use: x, mean = BinActive.apply(x)
martinferianc
Hi,I have the following problem. I am trying to propagate multiple outputs out of my network which are scalars, for example, latency or memory consumption of respective layers in addition to the output itself. These outputs I would then like to add to the main loss, let’s say cross-entropy.With a single GPU, I am using...
ptrblck
If you are using nn.DataParallel the model will be replicated to each GPU and each model will get a chunk of your input batch. The output will be gathered on the default device, so most likely you wouldn’t have to change anything. However, I’m not sure about the use case. How are you calculating …
yaneura-no-gomi
Hi, I’m new to Pytorch and I’m sorry I can’t explain it because English is not native.I am doing GAN implementation now and am confused by weight initialization.In the code I am referring to, initialize the weights as follows:def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1:...
ptrblck
Stick to the second approach, as the first one is deprecated and might yield unwanted side effects. In a torch.no_grad() block all new operations won’t be tracked. The requires_grad attribute of your parameters will not be changed: model = models.resnet50() with torch.no_grad(): print(model.f…
Joshua_Clancy
Hello! So this is a bit of weird one…I have a (b, c, 7, 7) tensor. For each “pixel” in this tensor I am going to put the (c, 1, 1) through a pretrained decoder to produce a (1, 4, 4) pixel image. In this way I intend to turn the (batch, channel, 7, 7) into (batch, 1, 28, 28). The problem is that I can not figure out ho...
ptrblck
The first view operation might interleave the values, so you should permute the channel dimension to the last dimension first: x = torch.rand((b, c, x_in, y_in), requires_grad=False) x = x.permute(0, 2, 3, 1).view(b*x_in*y_in, 6) I’m not sure how the output is calculated, so it’s hard to tell, if …
Deb_Prakash_Chatterj
Hey, I made an Image Classifier and now I want my model to predict and classify the images of DataLoader_Test. Here is my code -from google.colab import drive drive.mount('/content/drive') data = "/content/drive/My Drive/FT-BD" # choose the training and test datasets train_data = datasets.ImageFolder(data+"/train", tr...
ptrblck
This line of code unsqueezes the tensor twice, which will most likely create the issue. Remove one None and rerun your code.
Suraj_Subramanian
I have 32 images of size 3 x 128 x 128 in a single batch. I want to display them as a grid, so I used the torchvision.utils.make_grid function as in the code below. But the images in the grid are very small. Is there anyway to increase the size of the grid ?def show(img): npimg = img.numpy() plt.imshow(np.trans...
ptrblck
You could increase the size of the shown image directly in plt.imshow or alternatively save the image and use your default viewer. I assume the output is small as matplotlib tries to scale it down to fit your notebook/IDE
hbg
Hi could someone tell me the difference between len(dataloader) and len(dataloader.dataset) thanks
ptrblck
The length of the DataLoader gives you the number of batches, while the length of the Dataset is usually defined as the number of samples. If you are writing a custom Dataset, you are setting the length in the __len__ method, so that’s why I said “usually”.
mahsa
Assume we want to select all the elements in the tensor which are greater than 5. I know that the following code can do that:B = A[A > 5]But I want to know the indices of the selected elements. Is there any way to select and find the indices of the selected elements?Thanks
ptrblck
nonzero() should work: A = torch.randint(0, 10, (10, 10)) idx = (A > 5).nonzero()
mojzaar
Hi,I’m wondering whether we can use the PyTorch capacity to create a kernel-wise operator or not. By kernel-wise operator, I mean an operator like max pool which applies to a window (kennel size) but instead of getting the max value over that window applies another function over that window. Is there any way to have su...
ptrblck
You could try out your method by creating each window patch via unfold, apply your method, and reshape it to the output shape.This postgives you an example of this approach. Note that this approach will most likely be slow, but might be good enough to experiment with your method. If you need a m…
bing
I want to initialise the value of a tensor which doesn’t get value from a certain function as below -img_path = "Path_to_single_image" mask = function(img_path) class0,class1 = mask.unique(return_counts = True) class0,class1The general default output looks like this -tensor([0, 1, 2, 3]) tensor([304960, 13746, 10765, 4...
ptrblck
You could use the returned unique values to index another tensor and add the counts to it: counts = torch.zeros(4) data1 = torch.randint(0, 4, (1000, )) u, c = data1.unique(return_counts=True) counts[u] += c data2 = torch.randint(0, 3, (1000, )) u, c = data2.unique(return_counts=True) counts[u] +…
saqib_mobin
When building from the source it throws up nvlink error. I have followed theseinstructions.[386/3538] Performing build step for 'nccl_external' FAILED: nccl_external-prefix/src/nccl_external-stamp/nccl_external-build nccl/lib/libnccl_static.a cd /codehub/external/pytorch/third_party/nccl/nccl && env CCACHE_DISABLE=1 S...
ptrblck
That’s strange. Somehow -gencode=arch=compute_53,code=sm_53 is generated. Could you try to build it via: TORCH_CUDA_ARCH_LIST="5.0" python setup.py install
Chriexpe
First of all, I don’t know if this problem is supposed to be reported here or only on Conda’s Github, but there isn’t active as here so anyway…I’m trying to use Super-SloMo, wich require PyTorch to be installed on (in my case, Anaconda2-2018.12-Windows-x86_64), but when I try to install with the following command:conda...
ptrblck
Could you try to uninstall the ipaddress package (if you don’t need it) or alternatively create a new conda environment and try to reinstall pytorch and torchvision?
Upgrade_Yourself
What I would like to know is how to choose a reasonable number for the step size. This is a multilabel classification with 21 labels.My batch size is 8. And the number of images is 7000 images. Number for gradient accumulationis 4.Thank you
ptrblck
Thanks for clarification. From thepaper: The length of a cycle and the input parameter stepsize can be easily computed from the number of iterations in an epoch. An epoch is calculated by dividing the number of training images by the batchsize used. For example, CIFAR-10 has 50, 000 training…
TinfoilHat0
I’ve an image dataset given as bunch of json files. Each key is a class label and the corresponding value is a subset of images that have this label, represented as a list of integers.How should I pre-process and save this data such that I can use DataLoader to fetch batches of it during training?
ptrblck
Based on your description it seems you have multiple json files, where each file might contain the same class indices as keys with the corresponding image samples. If that’s the case, indexing into these file would work using the class label, which would have the drawback of a possibly complicated …
qavvv
I am new to PyTorch and making a transition from TF/keras to PyTorch so I apologize if my question is very basic.I have started with some tutorials and in one of them I have the following training loop function where it iterates over the dataset, trains the model for 1 epoch computes the loss and updates the weights.tr...
ptrblck
Thanks for the notebook! Your indentation of the return loss statement is wrong as you would return after a single iteration, which also explains the runtime difference.
Sayeed_Shaiban
iter = 0for epoch in range(n_epoch):for i, (images, labels) in enumerate(train_loader):####################### # USE GPU FOR MODEL # ####################### if torch.cuda.is_available(): images = Variable(images.view(-1, 28*28).cuda()) labels = Variable(labels.cuda()) else: ima...
ptrblck
The shape seems to be correct, but the labels should be zeros and ones.
Carolmeir
Hello,I am trying to runthisFirst I didsh ./create_dataset.shAnd gave the correct path to scenflow_data_path.Now I am trying to run this:python main.py --maxdisp 192 --with_spnas given, I am getting this following error. Please let me know how to correct this.The error is:Traceback (most recent call last): File "main...
ptrblck
This error seems to be specific to the linked repository so you might also want to create an issue in the repo to get a better answer.That being said, based on the error message it seems as if the files are not found or the download failed.
aktgpt
I’m running the follwing code:pool = torch.nn.MaxPool3d((4, 4, 4), return_indices=True) unpool = torch.nn.MaxUnpool3d((4, 4, 4)) o, i = pool(x) #x is tensor of size [1, 4, 256, 256] y = unpool(o, indices=i, output_size=x.size())But the unpool operation throws follwing error:IndexError: tuple index out of rangeI’m ...
ptrblck
You are using 3d layers, while your input would work with 2d layers. If you add another dimension, the code should work: x = torch.randn(1, 4, 256, 256, 256) pool = torch.nn.MaxPool3d((4, 4, 4), return_indices=True) unpool = torch.nn.MaxUnpool3d((4, 4, 4)) o, i = pool(x) y = unpool(o, indice…
Vedaant_V
I’m using anaconda for python 3.7, and have CUDA 10.1 installed. My GPU is a GTX 760, with 3.0 CUDA capability. I’m getting true values fortorch.cuda.is_available, but I keep getting this error whenever I try to use CUDA for anything.Here’s the error:RuntimeError: CUDA error: no kernel image is available for execution ...
ptrblck
Thanks for the error message. Could you refer tothis post, install the latest VS 2019, and try to rebuild it? Please let us know, if you are continuously running into this error, as it seems to be hard to reproduce on the Windows CI.
bing
I am trying to perform certain operations on a single image, while in a training loop.In case ofbatch_size = 1, it could be easily done by usingtorch.squeezebut I am unable to think of a way when I can do it for other batch sizes.Below is the minimum code for representation -def train(n_epochs, loaders, model, optimize...
ptrblck
If you want to perform some operations on single samples, you could use a for loop and iterate your batch: for d, t in zip(data, target): # op on single sample
111233
Hi all! I have 4 GPUs 1080 Ti, and when I run training inception_v3 net on multiple GPU model have strange behavior. I didnt rewrite my code much from training on 1 GPU, just add:model = nn.DataParallel(model, device_ids=[0,1,2,3]).cuda()When I run script with device_ids=[0,1] GPUs full utilized and train much faster, ...
ptrblck
Thanks for the information. This points towards some communication issues between the GPUs. Could you run the PyTorch code using NCCL_P2P_DISABLE=1 to use shared memory instead of p2p access?
ziqipang
I want to use multiple gpus for training. But as I have to do this training job on a cloud server, I cannot know the ids of gpu. However, the tutorial I have seen all need gpu ids to specify the usage.https://pytorch.org/tutorials/beginner/former_torchies/parallelism_tutorial.htmlandhttps://pytorch.org/tutorials/beginn...
ptrblck
You could use torch.cuda.device_count() to get the number of GPUs and then torch.cuda.get_device_properties(idx) to get the information of the device using idx.
bedrick
this is my model:def __init__(self, features, num_classes=8, init_weights=True): super(VGG, self).__init__() self.features = features self.roiNum = 6 self.roi_pool = _RoIPooling(5,5,1.0/32.0) self.rois_classifiers = [] classifier = nn.Sequential( nn.Linear(512 * 5 * 5, 512), nn...
ptrblck
You would have to use nn.ModuleList instead of a Python list for self.roi_classifiers to properly register them as submodules. Inside a module, all directly assigned nn.Modules and nn.Parameters will be registered. Tensors, which should not be trained, can be registered as buffers via self.registe…
cnn_beginner
Hi, can anyone tell me, what is the purpose of this Layer. I’m reading mobilenetV3 and GhostNet btw.class SELayer(nn.Module): def __init__(self, channel, reduction=4): super(SELayer, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(c...
ptrblck
It looks like theSqueeze-and-Excitation block.
cruzas
Hi everyone,I believe this has been answered implicitly but not explicitly elsewhere.Do PyTorch optimizers minimize or maximize a loss function?Thank you.
ptrblck
Optimizers subtract the gradient of all passed parameters using their .grad attribute as seenhere. Thus you would minimize the loss using gradient descent.
StoneOcean
Hi,Recently I’m doing some research on network pruning and built a custom layer for my vgg network.My custom layerMaskcontains a set of parameters that have the same shape as the input feature map. However, after I implemented the module together with my other conv layers usingnn.Sequential, the parametersself.maskdoes...
ptrblck
If you’ve passed all parameters to the optimizer after initializing the model via: optimizer = optim.SGD(model.parameters(), lr=1e-3) the self.mask parameter won’t be included and thus not updated, since it wasn’t initialized yet. Could you pass the desired input shape to the initialization of th…
Subhankar_Ghosh
https://pytorch.org/docs/stable/torchvision/models.html#video-classificationI am going through the tutorial in the link above. It’s mentioned:We provide models for action recognition pre-trained on Kinetics-400. They have all been trained with the scripts provided inreferences/video_classification.I’m unable to find wh...
ptrblck
You can find the scriptshere.
science
On the PyTorch documentation it says there is a method torch.angle that returns the element wise angles between the input vectors. Does this method still exist? I’m trying to use it except it gives the error:module ‘torch’ has no attribute ‘angle’Thanks in advance.
ptrblck
Could you check your PyTorch version via torch.__version__? I guess your build might be too old.
kaiseryet
Let’s say if I have a tensor of size(a,b,c_1), and now I wish to inflate it to(a,b,c_2)for somec_2 > c_1, is there a function to do this? Note that I am NOT changing the number of dimensions of the tensor; instead, I am just increasing one or more dimensions of the tensor. Thanks.
ptrblck
You could use tensor.expand, if you want to increase a singleton dimension with a view, tensor.repeat to repeat the values in this dimension, or torch.cat to concatenate different tensors and thus increasing the size in this dimension.
sigma_x
Torchivison’s model uses ResNet51+FPN as a feature extractor.I usually transform images by first converting them to a tensor, and then multiplying again by 255t_ = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(img_size), transforms.ToTensor()...
ptrblck
No, it’s common to normalize the inputs for a lot of machine learning models, as this might accelerate and stabilize the training. Some methods e.g. RandomForest classifiers are not sensitive to the input range, while e.g. neural networks are. You would have to check the dataset creation (or just …
SangYC
Why can the dimensions of input and target be different when using this class of torch.nn.CrossEntropyLoss? I remember that one_hot processing was needed when using keras. This’s why?
ptrblck
nn.CrossEntropyLoss expects the target as a LongTensor containing the class indices rather than a one-hot encoded target. Since you are indexing the logits for the target of the corresponding sample, you can use the class indices directly. Have a look at thedocsfor more information.
S_M
HelloI load MNIST dataset using torchvision, then I’ve tried to access some special indexes like belowtrain_dataset = MNIST(‘…/data/MNIST’, train=True, download=True,transform=transforms.Compose([transforms.ToTensor(),transforms.Normalize((mean,), (std,))]))mini_train_dataset = torch.utils.data.Subset(train_dataset, in...
ptrblck
You could try to usethis codeto remap the class indices.
ElleryL
Hi; I’m working on gradient estimator; so I need to implement model that requires manually compute and apply gradientshere is my current scriptfrom itertools import chain net1 = Net1() # neural network net2 = Net2() # neural network opt = Adam(list(net1.parameters()) + list(net2.parameters()), lr=1e-3) params = chain...
ptrblck
Thanks for the code. Could you clone the grad, so that you won’t create a view of this tensor? p.grad = grad[i].clone()