user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
Alex_Luya
Is possible to usetorch2trtto convert trained model to TensorRT,then convert the result to TorchScript?
ptrblck
Usually TensorRT would be the last deployment stage. What is your use case that you would like to transform a TensorRT model back to TorchScript?
Alex_Luya
I found a line of code:out_a, out_p, out_n = model(data_a), model(data_p), model(data_n)in:https://github.com/liorshk/facenet_pytorch/blob/master/train_triplet.pyas you can see that the “forward()” is invoked multiple times before “backward()”,In my test,the gpu consumption will increase accordingly,so GPU memory leaki...
ptrblck
The memory is increasing as each forward pass creates intermediate variables, which are used to calculate the gradients. So it shouldn’t be a memory leak. If you just need the features without backpropagating through your model, you should wrap your code in with torch.no_grad(): to avoid storing th…
bing
I am trying to run a deep learning model for the segmentation task.I have 2 gpus.My doubt is whether can I parallelise my model or not?My batch size is 1 and can’t change it (maybe change it but I have to figure that out) because of some image transformations in the code.
ptrblck
You could most likey use nn.DistributedDataParallel to use both GPUs each using a batch size of 1. I assume your model fits on a single GPU and you don’t need to split it onto two devices. Would that work for you?
silverant
Hi all,this is my first post and I am new to AI and RL… please apologizeI use ubuntu 18.04.1I follow installation guide frompytorchand followed cuda instalation guidenvidiaI notice that I cannot choose cuda 10.2 but that nvidia download site only offer cuda 10.2.And after following above guide,torch.cuda.is_available()...
ptrblck
The binaries ship with their own CUDA, cudnn, etc. so that you don’t need to install these libs locally, if you are fine with the provided versions. Could you uninstall PyTorch in your conda environment and reinstall it (with cudatoolkit=10.1)? If you want to use e.g. CUDA10.2, you would have to i…
Asad_Ullah
Trying to implement KL divergence loss but got nan always.p = torch.randn((100,100))q = torch.randn((100,100))kl_loss = torch.nn.KLDivLoss(size_average= False)(p.log(), q)output = nanp_soft = F.softmax( p )q_soft = F.softmax( q )kl_loss = torch.nn.KLDivLoss(size_average= False)(p_soft.log(), q_soft)output = 96.7017Do...
ptrblck
According to the docs: As withNLLLoss, the input given is expected to contain log-probabilities and is not restricted to a 2D Tensor. The targets are given as probabilities (i.e. without taking the logarithm). your code snippet looks alright. I would recommend to use log_softmax instead of so…
Kong
How do I initialize a layer if it is not constructed using nn.Linear for example?self.nlc =Variable(torch.randn(10,1,1,1,1).type(torch.FloatTensor), requires_grad=True)Is there like a method below?self.nlc =Variable(torch.glorot(10,1,1,1,1).type(torch.FloatTensor), requires_grad=True)
ptrblck
Your example is correct. Note that you should wrap this tensor in nn.Parameter, if you would like to optimize it inside an nn.Module. nn.Parameters will be automatically registered inside modules, if you use assign them as attributes: class MyModule(nn.Module): def __init__(self): supe…
syaffers
I’m trying to use the pre-trained Faster RCNN in PyTorch. I found that thetorchvisionpackage has the Faster R-CNN ResNet-50 FPN pre-trained network. Seeing that it uses ResNet as its feature extractor, I assumed the preprocessing was the same as if I used the ResNet models intorchvision: which is to use the ImageNet pr...
ptrblck
Detection models will normalize the images internally as seen inthis line of code. You could pass your own calculated stats or just use the default ImageNet stats. Could you remove your normalization and rerun the code?
lcy
Hi,I have a batch of tensor. How can I efficiently normalize it to the range of [0, 1].For example,The tensor is A with dimension [batch=25, height=3, width=3]. I can use for-loop to finish this normalization like# batchwise normalize to [0, 1] along with height and width for i in range(batch): min_ele = ...
ptrblck
Thanks for the code. This should work: AA = AA.view(A.size(0), -1) AA -= AA.min(1, keepdim=True)[0] AA /= AA.max(1, keepdim=True)[0] AA = AA.view(batch_size, height, width)
DoubtWang
Corresponding to the same part of the code,torch.cuda.empty_cache() will make the GPU utilization 0 and make the training time very slow. Why is that?optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) scheduler = Warmup[args.schedule](optimizer, warmup_steps=args.warmup_st...
ptrblck
torch.cuda.empty_cache() will, as the name suggests, empty the reusable GPU memory cache. PyTorch uses a custom memory allocator, which reuses freed memory, to avoid expensive and synchronizing cudaMalloc calls. Since you are freeing this cache, PyTorch needs to reallocate the memory for each new d…
sunshower76
Hello, everyone!When we learn or research deep learning and the other things related to ML or DL we use PyTorch…I’m also a user of Pytorch.Using PyTorch, I suddenly think that I want to study PyTorch from scratch!I’ve wondered how the tensor is defined and how the values are back-propagated.So, I’ve decided that I stud...
ptrblck
I would suggest to pick an easy looking issue on GitHub, post that you are interested and new, and either someone will guide you through the PR or could suggest another one, if your pick is not beginner friendly. You will learn the internals of PyTorch while working on a real fix instead of staring…
hadaev8
I need alluxary classification in very imbalanced data.And dont need major class.Before i had linear layer with 9 neurons and ignore index - 1.But now i think it is better to have 10 classes (this values still used in another part of model).Is it same to set weight zero for major class as i used to ignore it with ignor...
ptrblck
ignore_index will ignore valid as well as invalid target indices. E.g. if you are dealing with 10 classes, your model output would have a dimension of [batch_size, 10] in the vanilla multi-class classification setup, while the target will be a LongTensor of shape [batch_size] containing class indic…
redtailedhawk
After countless searches, and putting pieces of the puzzle together, I came up with this code for a “boilerplate” custom image Dataset class. I wanted to ask if this is satisfactorily simple and efficient, or does anyone see where I might possibly run into trouble?The use case is to quickly, simply and efficiently just...
ptrblck
Your custom Dataset should work fine. However, currently you could also just use ImageFolder directly without wrapping it in Dataset and pass it to a DataLoader. If you want to customize the samples inside __getitem__, your approach looks good!
tomguluson92
Hi, when I start to train a simple version StyleGAN2 in PyTorch 1.0.1.Since I do not want to useretain_graph = True, ARuntime Error Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.raised here.The code of mine is ...
ptrblck
It seems one BiasAdd module is reused somewhere in the code, but I cannot spot the line. This should be unrelated to your current issue, but I would recommend to setup the bias tensor and wrap it into nn.Parameter as the final step to create a leaf variable. Currently you are creating a non-leaf v…
maria
I created a fine-tuned model based on resnet18:resnet18 = torch.hub.load('pytorch/vision:v0.4.2', 'resnet18', pretrained=True) reset18_base = torch.nn.Sequential(*(list(resnet18.children())[:-2])) head_layers = [some layers.. ] resnet_head = nn.Sequential(*head_layers) model = nn.Sequential(reset18_base, resnet_head)I ...
ptrblck
I would create the custom module, load the resnet inside and write the forward method as you wish. Once this module works as you want it to, save the state_dict and reload this one. This approach will make it easier to use your custom module without having to map the original resnet parameters to …
assyl_coop
I have model trained on cuda:0 pytorch 0.4.But when I try to reload model on cuda:1 pytorch 1.2 its still shared betweed 0.1 gpus.I have tried map_location to map from cuda to cpu, from cuda:0 to cuda:1.Nothing works yet.
ptrblck
Are you sure the model is still on cuda:0, i.e. are you seeing the same amount of used memory on both GPUs? The CUDA context might have been created on GPU0, which will take some memory. If you don’t want to use GPU0 at all, you could just mask it via: CUDA_VISIBLE_DEVICES=1 python scripy.py Not…
Julio_Marco_A_Silva
Hi, everyone!I am writing a neural classifier and its output is two classes, with a batch size of 5, so output is a tensor of size (5, 2).Also, I am using BCEWithLogitsLoss as the loss function.As you know, BCEWithLogitsLoss accepts a vector of integers (one for each element in the batch) and I have a one-hot vector of...
ptrblck
That’s not correct, as nn.BCEWithLogitsLoss expects raw logits as the model output (FloatTensors) and a target tensor with the same shape and type as the output containing values in [0, 1]. I’m a bit confused about your use case at the moment. If you are dealing with a multi-label classification …
Sam_Pr
When would we choose to use theModuleforms of the loss functions rather than the functional forms? For example,torch.nn.MSELossovertorch.nn.functional.mse_loss. I just realised that I’ve never used theModuleforms, and I’m wondering whether I’m missing a useful trick or something? It seems to me that loss is something w...
ptrblck
I’m usually creating the criterion as a module in case I want to store some internal states, e.g. weight, a specific reduction etc. Also, I would say it basically depends on your coding style and the use case you are working with. E.g. if you are reusing the criterion in multiple places (e.g. GAN …
Rocket
Hi,How to access datasets label?import torchvision.datasets fashion_train = torchvision.datasets.FashionMNIST(root = './data/torchvision/fashion_mnist', train = True, download = True)data could be accessed byfashion_train.data[0]how to access labels?is there attribute for checking keys?
ptrblck
fashion_train.targets should work.
Rocket
When I runprint(train_y[0])it returnstensor([43], device=‘cuda:0’)When i runnum = train_y[0] da=data[num]da is empty. why?When I runnum=43 da=data[num]da has data.
ptrblck
Could you recheck the value of num = train_y[0], as this dummy code snippet is running fine? train_y = torch.tensor([[43], [0]]).cuda() num = train_y[0] print(num) data = torch.randn(50) print(data[num]) > tensor([-0.2206]) print(data[43]) > tensor(-0.2206)
gfotedar
It looks like the time to copy one batch of data from cpu to gpu varies according to model size or maybe inference time. If model size or inference time is large, time taken is larger. I can’t understand why I am seeing this behavior.Below is the code to reproduce and results:import time import torch import torch.utils...
ptrblck
CUDA operations are asynchronous, so you should synchronize via torch.cuda.synchronize() before starting and stopping the timer. Most likely, your code waits at the x = x.cuda() calls, while the model is still running in the background, which will accumulate the actual model time into the time to t…
Mamsheikh
error915×359 12.1 KB
ptrblck
PIL throws this error, if the loaded image file is truncated. You could try to isolate this file and remove it or use from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True to load this file nevertheless.
hongtaesuk
Hey guys,can anyone of you could explain why such things below happened?def __init__(self, config): super(BertForMultitask, self).__init__(config) self.bert = BertModel(config) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.apply(self.init_weights) self.multitask_rati...
ptrblck
Plain Python containers, such as list and dict won’t be properly registered inside your module, so usenn.ModuleDictin that case (or nn.ModuleList instead of list).
gmkim90
Hello. Can i update the input tensor without updating network weight?For example,input = torch.rand(10,5) # minibatch size = 10, data dimension = 5 net = nn.Linear(5,3) optimizer = optim.Adam(net.parameters(), lr=0.1) target = torch.rand(10, 3) #minibatch size = 10, data dimension = 3 output = net(input) loss = torc...
ptrblck
That should be possible, if you create your input using requires_grad=True and pass it to the optimizer. Have a look atthis cosine similarity exampleI’ve written yesterday.
wittenator
Hi Pytorch people,I am currently trying to build a tensor iteratively in Pytorch. Sadly the backprop does not work with the inplace operation in the loop. I already tried equivalent programs with stack for example. Does somebody know how I could build the tensor with a working backprop?This is a minimal example which p...
ptrblck
I’m not exactly sure, what your use case is, but from the code perspective, it should work, if you use remaining_sticks = remaining_sticks * (1-km[:,i]) instead of the inplace operation. Additionally, you could also initialize sticks as a list and use torch.cat to create a tensor afterwards.
pedro
I want to applyskimage’s Local Binary Pattern transformationon my data, and was wondering if there was any possibility of doing this inside my torch’s Transforms, which right now is the following:data_transforms = { 'train': transforms.Compose([ transforms.CenterCrop(178), transforms.RandomHorizonta...
ptrblck
If you want to add the skimage transformation between other Image transformation, you could use the following code snippet as a base class and apply the desired transformation inside: class MySkimageTransform(object): def __init__(self): ''' initialize your transformation here, …
Rojin
I have an adjacency matrix and based on that I would like to build a costume connection between the input and the first hidden layer. I was wondering if someone can help me understand how I should go about the implementation?
ptrblck
The gradients will be zero at the masked points: x = torch.randn(1, 10) weight = nn.Parameter(torch.randn(5, 10)) adj = torch.randint(0, 2, (5, 10)).float() out = torch.matmul(x, (adj * weight).t()) out.mean().backward() print(weight.grad) > tensor([[ 0.1776, -0.1401, 0.0000, -0.0000, 0.0000, …
mahmoodn
How can I reduce the RAM usage of compilation from source viapython setup.py installcommand? It automatically spawns many threads and I don’t want that!
ptrblck
Yes. You could also set it in front of the install command: MAX_JOBS=2 python setup.py install.
mgloria
I am doing distributed training with the mnist dataset. The mnist dataset is only split (by default) between training and testing set. I would like to split the training set in training and validation set.I could do this as follows:# Shuffle the indices indices = np.arange(60000) np.random.shuffle(indices) # Build the...
ptrblck
The cleanest approach would probably be to create a DistributedSubsetSampler, if you want to combine these both samplers together. However, I think the easiest workaround would be to use DistributedSampler and wrap your Dataset in Subset using the desired indices.
taleslimaf
class network(nn.Module): def __init__(self): super(network, self).__init__() self.linear1 = nn.Linear(in_features=40, out_features=50) self.bn1 = nn.BatchNorm1d(num_features=50) self.linear2 = nn.Linear(in_features=50, out_features=25) self.bn2 = nn.BatchNorm1d(num_features=...
ptrblck
Yes, this should be the case as shown by the following code snippet using your example code: model = network() x = torch.randn(10, 40) output_list = model(x) output_list[0].mean().backward(retain_graph=True) for name, param in model.named_parameters(): print(name, param.grad) output_list[1].m…
aturahc13
Hi. I would like to use “DataParallel” in DNN training in Pytorch but get some errors.Before I use “DataParallel”, the code is;<Code 1>for epoch in range(epochs): train_loss = 0.0 val_loss = 0.0 train_loader2 = MakeDataset(file_x_train, file_y_mask_train, tmpbatch_size, shuffle=False) test_loader2 ...
ptrblck
So are you multiplying the batch size by the number of GPUs (9)? nn.DataParallel will chunk the batch in dim0 and send each piece to a GPU. Since you get [10, 396] inside the forward method for a single GPU as well as for multiple GPUs using nn.DataParallel, your provided batch should have the sha…
two_Two
Hi everyone I am new to pytorch and there’s one issue that really confuses meWhen I try to use transfer learning and take the resnet50 as base from this linkvision/torchvision/models/resnet.pyAnd download the weight fromresnet50-19c8e357.pthHere’s the problems:While I am initializing the weights from pretrained model...
ptrblck
You are only saving the parameters in these lines of code: names = {} for name,param in model_resnet.named_parameters(): names[name] = 0 while the running estimates are stored as buffers. You could append these buffers using: for name, buf in model_resnet.named_buffers(): names[name] = 0…
skyline
When I set on the detection I get the trace I seen this sentence went wrongalphas[t] = torch.logsumexp((potential[t]*alphas[t-1].unsqueeze(dim = 1)),dim = 0)How to fix it,does this sentence use inplace?One of the variables needed for gradient has been modified by an inplace
ptrblck
torch.cat will not block the gradient flow: alphas = [torch.ones(1)] potential = torch.randn(5, requires_grad=True) for t in range(5): alphas.append( torch.logsumexp( (potential[t]*alphas[t-1].unsqueeze(dim = 1)), dim = 0)) alphas = torch.cat(alphas) alphas.mean().backw…
avtrulzz
I used random_split() to divide my data into train and test and I observed that if random split is done after the dataloader is created, batch size is missing when getting a batch of data from the dataloader.import torch from torchvision import transforms, datasets from torch.utils.data import random_split # Normalize...
ptrblck
Yes, because indexing a Dataset will return the sample without a batch dimension. The DataLoader creates the batch. Since random_split returns a Dataset, you won’t have a batch dimension using this approach.
Majid_Shirazi
Hi everyone,I got my ground_truth data which is one hot vector, like ground truth[56] = [0, 1, 0, 0, 0].Now i want to train my classifier to give me output of five element like the ground truth vectors, plus I would like to checkout my accuracy. After using my codes I see some vectors like [[ 2.2090e-02, 1.6277e-02, ...
ptrblck
This comment is wrong and might come from an older code snippet: criterion = torch.nn.MSELoss() # Softmax is internally computed. For a multi-class classification, I would recommend to use nn.CrossEntropyLoss and pass the targets as class indices to the criterion. You could create the class in…
balbok0
I was recently trying to train a resnet on ImageNet with consistent images inputs across runs, yet still with data augmentation, such as cropping, flipping rotating, etc.I run into a problem with the fact, that there is no way of consistently getting the same random crops.Here is a minimal example I created:import torc...
ptrblck
Some torchvision transformation use the Python random library to sample the numbers. Add random.seed(1) to the loop and you should get the same results.
TO_Kocsis
Hi,Im conducting research, and I would like to investigate multi branch architecture. I want to have a network that is based on resnet50, but branches based on rules at layer 4, and uses only that branch for given ‘extra_label’ input.Im working on this for quite some time, but I cant find the reason why my architecture...
ptrblck
The code will output the same result as the reptrained resnet50 during evaluation (and using the same self.fc at the end for the sake of debugging). Code snippet: class PABN(nn.Module): def __init__(self): super(PABN, self).__init__() num_classes = 576 self.bac…
Majid_Shirazi
Hi everyone,I first padded my PIL image list, for that reason I had to transform my PIL list into numpy-array. Now for doing torchvision transforms on my images I need to first transform my images back to PIL. But my images look like this:004796×555 114 KBIs there anyone who could save me?
ptrblck
Thanks for the code! I’ve debugged it and it seems PIL is unable to properly create an image out of the np array. In fact Image.from_array(j, mode="RGB") creates the same interleaved output. You could fix it via: images_data=[] for j in padded: j = j * 255. j = j.astype(np.uint8) ima…
CarlosHernandezP
I am trying to solve a multiclass classification problem in which I have over 7000 pictures with labels. While preprocessing the data, I use a torchvision.Compose with Normalize() function included at the end. Said function performs the following operation for all the three channels:Which is convenient for many cases b...
ptrblck
If you are using “ImageNet-like” images, you could try to use the calculated stats from the ImageNet dataset as used in our tutorials: normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) You could of course calculate the mean and…
chunchun
When I run the train.py in pysot which is an open sourece for trackers,it shows before any iteration which means it achieves no iteration:DataLoader worker (pid 101735) is killed by signal: Killed. Details are lost due to multiprocessing. Rerunning with num_workers=0 may give better error trace.But when I try to set n...
ptrblck
Let’s continue the discussion onthis topic.
Jonson
I noticed thatscriptmodulehave graph() and graph_for() methods, but I am confused about those two methods. Does anyone can tell me the difference? really thanks!
ptrblck
graph_for should try to optimize or fuse the graph for the provided inputs, while graph should print the IR directly.
Ahmed_Mustahid
I have been trying to carry out regression with my data from the following “my hdf file” to predict TWO outputs. But I have been getting different values for loss at different executions. Each execution produces 0 output value for either one or both the outputs.The true output (targets) is the following:label_batch te...
ptrblck
I’m not sure, if you are asking for bitwise reproducibility or why your model converges to a single class. For the first point, have a look at theReproducibility docs. The second issue might occur, if your training is “unstable”. Did you play around with some hyper parameters or e.g. removed the …
a-parida12
I am trying to train on the unet fromtorch.hub. Some of the image-label pairs give me aCUDA error: device-side assert triggered.Screenshot%20from%202019-12-11%2000-52-03806×341 40.9 KBHow Can I fix this?
ptrblck
Does this model work on the CPU without any errors? Usually you might get a better error message by running it on the CPU.
dato_nefaridze
in net class input picture dimention is 3x100x100.batch_x=(X[x:x+batch_size]).permute(0,3,1,2) batch_y=Y[x:x+batch_size].long()do i permute dimentions correctly? (it doesn’t output error, but in test set it predicts same value over and over again)above batch_size=64.i am trying to input 64x3x100x100 picture.
ptrblck
In that case, try to overfit a small data sample (e.g. just 10 samples) and play around with the hyperparameters. Once your model is able to overfit the small data, you could try to scale up the experiment and use more data samples. If the model isn’t able to overfit, there might be some other bug…
MLSlayer
For some reason, even if I am following the formula in pytorch docs, it seems I am getting different results when trying to simulate batchnorm2d by hand vs pytorch.Here is the manual version>>> x = t.tensor([[[[1., 2.], ... [3., 4.]], ... [[3., 4.], ... [5., 6.]]], ... ...
ptrblck
Have a look atthis manual implementation. Skimming through your code it looks like the variance calculation is unbiased in your case.
eshan87
please find code snippet below:-def load_torch_model(self): if self.pre_trained_model == 'VGG16': self.torch_model = models.vgg16(pretrained=True) print(self.torch_model) self.torch_model.classifier[6] = nn.Sequential(nn.Linear(in_features=self.in_features[0], ...
ptrblck
How did you save the state_dict and what keys are inside it? Saving and loading the state_dict using your model, works fine: torch_model = models.vgg16(pretrained=False) torch_model.classifier[6] = nn.Sequential( nn.Linear(in_features=4096, out_features=1, bias=True), nn.ReLU(), …
ElleryL
Hi; I’m training a model on CeleberityA dataset as followstransform = transforms.Compose([ transforms.Resize((64, 64)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ]) trainset = torchvision.datasets.CelebA(root='./data', split="train", ...
ptrblck
The first execution of the dataloader loop (for data in loader) won’t be recorded in total_time_used. This would correspond to the initial loading all a batch using all specified workers.
vainaijr
I get tensor astensor([[[0.1200], [0.0700]], [[0.0216], [0.0048]], [[0.0026], [0.0035]], [[0.0002], [0.0004]]])how do I print after four digits, that is something like, 0.120001203, 0.070020133?f'{x:.5f}'throws errorTypeError: unsupported format string pass...
ptrblck
You could usetorch.set_printoptionswith the precision or profile argument to get more decimals.
ati
HiI have a code as below:dataset = MNIST(path=data_path, download=True, shuffle=True) if train: images, labels = dataset.get_train() else: images, labels = dataset.get_test() images, labels = images[:n_examples], labels[:n_examples] images, labels = iter(images.view(-1, 784) / 255), iter(labels)but when i run...
ptrblck
You could access the underlying data and targets using: dataset.data dataset.targets Where did you see the get_train method?
dl_noob
Hi,I have a tensorywhich has the size 1024 x 10 x 10, basically I have 1024 matrices of 10x10I also have 2 indices tensorsaandbsize 1024 x 15 and 1024 x 15, to access elements of each 1024 10x10 matrices, I guess this is some form a gather functionThus, my final outputzshould be 1024 x 15Currently I do this with loop e...
ptrblck
The creation of z is not working using the provided shapes and you should probably use torch.stack instead. Anyway, this code should yield the same result: N = 100 y = torch.randn(N, 10, 10) a = torch.randint(0, 10, (N, 15)) b = torch.randint(0, 10, (N, 15)) z = y[torch.arange(N).unsqueeze(1), a,…
ginobilinie
Hi guys,I’m currently using nn.DataParallel for mutli-gpu (8-gpu) training in a single node. However, if I put the data and model to devices[0], I found the memory on GPU 0 will be huge and make the program exits (cuda out of memory) at the begining of training. Can anyone help?BTW, I find if I use DistributedDataPara...
ptrblck
This effect is described by@Thomas_Wolfinthis blog post. We generally recommend using DDP.
markorei94
I have a model in which I create a rotational matrix as a function of angle and would like to have angle as a trainable parameter of the model. However, angle is not updated, although it has requires_grad=True.class Rotation(Affine): def __init__(self,scale,center=None, angle=None): super().__init__(scale,c...
ptrblck
Recreating a tensor (in rotational_matrix) will detach self.angle from the computation graph, so you should use torch.cat or torch.stack instead.
travis-harper
Hello. Within the forward method of my neural network, I want to pass a tensor of size (batch_size, seq_len) to an nn.Embedding layer that ought to output shape (batch_size, seq_len, embed_dim). However, my embedding layer is returning (batch_size, embed_dim) which is unexpected according to my understanding of the doc...
ptrblck
It seems you are using nn.EmbeddingBag, which outputs [batch_size, embedding_dim], not nn.Embedding, which works as expected: N, seq = 2, 5 emb = nn.Embedding(num_embeddings=10, embedding_dim=100) x = torch.randint(0, 10, (N, seq)) output = emb(x) print(output.shape) > torch.Size([2, 5, 100])
guitarman
Let’s say I have a sparse vector of ones and zeros (NxM) and I would like to have it as a dropout filter on the conv2d layer output which is also (NxM). Is it possible to achieve that by just multiplying it with the output?Furthermore, is it possible to set a different dropout “mask” for each of the X batch samples? Or...
ptrblck
You could check the internal self.training flag inside the module.
SeanAbnerNash
Hello I’m new to Pytorch and I’ve been trying to work through this tutorial.[https://github.com/pytorch/tutorials/blob/master/intermediate_source/torchvision_tutorial.rst]I’m using Visual Studio Code, conda installed the Pytorch. Initially the issue was that it was missing the module engine. But this problem was solved...
ptrblck
Probably pycocotools is missing, which can be installed via: # install pycocotools cd $INSTALL_DIR git clone https://github.com/cocodataset/cocoapi.git cd cocoapi/PythonAPI python setup.py build_ext install
ROODAY
Would autograd still work if I used non torch functions on my tensors? My model outputs a series of human poses in the form of 3D coordinates (each frame/pose is composed of 17 such coordinates), so the shape of output and target being fed to my loss function would be (seq_len, batch_len, 17, 3). I want my loss functio...
ptrblck
Yes. A loop does not detach the computation graph and as long as you are using PyTorch methods, Autograd will create the backward pass for you. If you need to leave PyTorch and e.g. use numpy in the forward pass, you would need to implement the backward function manually.
wulongjian
It seems no different between these .>>> import torch >>> a=torch.randn(4,4) >>> a tensor([[ 2.0155, -1.1138, -1.7522, 0.7299], [ 1.0620, 0.1840, 0.2790, 1.1942], [ 1.7519, 1.8871, 1.4988, -0.1911], [-1.6222, -0.2044, 1.6316, -1.0949]]) >>> a.max(1,keepdim=True)[1] tensor([[0], [3...
ptrblck
The usage of .data is not recommended, as you’ll get access to the “real” underlying data and Autograd cannot track the changes applied on it, which might yield wrong results and thus silent errors. If you don’t want to track some changes on your tensors, you should wrap these operations in a with …
bernhardschaefer
I have trouble building PyTorch with CUDA 9.0 from source.Everything works when I install PyTorch 1.1.0 from conda with CUDA 9.0 using:conda install pytorch==1.1.0 torchvision==0.3.0 cudatoolkit=9.0 -c pytorchThen I tried to upgrade to PyTorch 1.3.1 by building from source, since the release only has prebuild PyTorch w...
ptrblck
How did you install cudnn locally? Did you use a .deb file and made sure it’s for the right CUDA version?
Sami_Hassan
Hello, This is my first week as a PyTorch user.How can we define a custom Conv2d function which works similar to nn.Conv2d but the multiplication and addition used inside nn.Conv2d are replaced with mymult(num1,num2) and myadd(num1,num2). It’s for some hdl simulation purpose. Even if it’s a slow implementation it doesn...
ptrblck
There seem to be a few minor mistakes in the code: h and w should probably de defined as input.size(2) and input.size(3), respectively. Currently you are assigning the same input value to both. However, since you are passing input directly, they can also be removed completely. As already mentione…
curie-ahn
m1 : [a x b]m2 : [a x c]and I want to make a new matrix with shapem3 : [a x d]where d = b*c.i.e, the new matrix column-wisely multiply m1 with m2.Which can I use?
ptrblck
I’m not sure, if I understand the use case correctly, but could you check, if this code snippet would work for you: a, b, c = 2, 3, 4 x = torch.randn(a, b) y = torch.randn(a, c) z = torch.matmul(x.unsqueeze(2), y.unsqueeze(1)) z = z.view(a, -1) If not, could you provide dummy tensors and the exp…
skyraker
Hello, I am new to Pytorch, I need to train two different networks, and their inputs are different. I need to multiply their outputs and train them simultaneously, how to do it ?
ptrblck
Your forward method seems to be missing the return statement, so you should add: return x at the end of it.
idontknow
Hi, I am working on omniglot images and I am struggling with this error. I believe the problem is with my dataset generation. Please help me figure it out. Here is the dataset code:import os from PIL import Image import numpy as np from torch.utils.data import Dataset import torch from torchvision import datasets, tran...
ptrblck
Could you check the type of outputs and labels? I guess labels is passed as a tuple instead of a tensor. If so, you could return labels in your __getitem__ as: torch.tensor(self.labels[idx])
mgloria
I wanted to build a simple ANN and train it from scratch on the Mnist dataset. The accuracy values look fine as expected but the loss is just way too high, as if I was not computing it correctly. What am I missing in the code below?import torch import torchvision import torchvision.transforms as transforms import torch...
ptrblck
Your total_loss consists of the losses of all samples in your Dataset. Usually you print the average loss per sample. To do this, you could divide total_loss by len(train_set).
cclover
I don’t have CIFAR10 data locally, and then I download one, but it doesn’t download automatically, and the read fails.import torchvision as tv import torchvision.transforms as transforms from torchvision.transforms import ToPILImage import torch as t transform = transforms.Compose([ transforms.ToTensor() ,tr...
ptrblck
Might be. I’ve seen all kind of weird restarts etc. with notebooks. So if something doesn’t seem to right, I would recommend to run the script in a terminal, which should work.
abder
Hello,I would like to ask about the value of padding we set in theConv2dfunction.I know what zero-padding is. However, what does it mean that the padding is 0 for instance, or 1,2, or 3. What do these values mean? Do they represent the number of columns and rows that will be filled with zeros?Thanks a lot.
ptrblck
Yes, the padding argument specifies how many rows and columns on each border will be added. E.g. padding=1 will add one column on the left, right, upper, and lower border.
guitarman
I was wondering if it is possible to somehow grab the inputs NxN that are processed for each of the kernel convolution on each pixel of the image?I’m trying to analyse each of the kernel data before and somehow connect it with a specific output neuron.Thank you.
ptrblck
I’m not sure, if I understand your use case correctly, but if you want to compute the convolution manually, you could use unfold. Have a look atthis post, which might be a good starter.
dalalaa
I got this error while trying to convert nn.module to torchscript.Traceback (most recent call last): File "/home/dai/scripts/mobileocr/detector/mobilenet_east_deploy.py", line 240, in <module> script_module = torch.jit.script(net) File "/home/dai/py36env/lib/python3.6/site-packages/torch/jit/__init__.py", line ...
ptrblck
Try to use the suggested torch.tensor instead (lowercase t). I would generally not recommend to use torch.Tensor, as this might give you uninitialized code, e.g. by calling torch.Tensor(10). torch.tensor is the factory method to pass values as a list etc.
Niki
I want to use Xavier initialization scheme, for initializing weights, for Resnet inhttp://www.pabloruizruiz10.com/resources/CNNs/ResNet-PyTorch.htmlSo I added this in the network:def xavier_init(ms): for m in ms : if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d): nn.init.xavier...
ptrblck
Probably some layers do not have a bias parameters, so you should add a condition to the weight init function.
111191
Blow is my keras and torch codeimage1675×786 227 KBQ :I am wondering why the performance is poor when implementing with torch.
ptrblck
nn.CrossEntropyLoss expects raw logits, so you should remove the softmax at the end of your model.
cclover
Hi, I’m just getting started with the pytorch.Preformatted textIn this example, I don’t understand why the input of the full connected layer is the output latitude of the previous convolution multiplied by the size of the convolution kernel?This is my codeclass net(nn.Module): def __init__(self): super(net...
ptrblck
The 5*5 are not derived from the kernel size, but the spatial size of the input to the linear layer, which is apparently also 5*5. You can add a print statement right before feeding the activation to self.fc1 to see the activation shape, which should be [batch_size, 16, 5, 5] before flattening.
ptrblck
The shapes are alright.If the target only contains values 0 and 1, it should work:criterion = nn.CrossEntropyLoss() output = torch.randn(1, 2, 256, 256) target = torch.randint(0, 2, (1, 256, 256)) loss = criterion(output ,target)
ptrblck
Most likely since cv2.resize uses some interpolation method (default is linear interpolation if I’m not mistaken) other than “nearest neighbors”. Try to pass cv2.INTER_NEAREST as the method to this function.
dato_nefaridze
take look at my code:optimizer=optim.Adam(net.parameters(),lr=0.001) optimizer.step()how does optimizer changes net parameters? it is passed once and then they don’t have any connection.is there any pointer stuff there?or i missed something while learning pytorch\python.
ptrblck
The optimizer will use the references to all passed parameters and update them in the step function. You could check the id of each parameter in e.g. optimizer.param_groups[0]['params'] and will see that the ids match the parameter ids in the model.
fmsilver
Problem:When I try to normalize my data, the model never start learning, without error message it just run without actually running, see uploaded picture. The green “In [1]” appears after a few seconds, but the red square keeps being red.Non-working code:class DATA(Dataset): def __init__(self,x,y,transform): ...
ptrblck
Normalize works on tensors, so ToTensor() should be applied before it. I’m not sure, why your notebook isn’t raising an error, but if you are running it in your terminal directly, you should get a proper error message.
Raul-Ronald_Galea
Running the following code yields very strange results:for i in range(100): a = torch.rand((189,4)) b = torch.rand((189,4), dtype=torch.float64) print(torch.max(a[:,:2]+b[:,:2]))Gives:tensor(2.8119e+275, dtype=torch.float64) tensor(nan, dtype=torch.float64) tensor(nan, dtype=torch.float64) tensor(2.8119e+27...
ptrblck
Could you update to 1.3.1, as some indexing/assignment operations with type promotion were broken in 1.3.0?
Lame
Hi all,Is it possible to concat two tensors have different dimensions?for example: ifA of shape = [16, 512]andB of shape = [16, 32, 2048]How they could combined to be of shape[16, 544, 2048]?Any help/suggestion, please?
ptrblck
I’m not sure, how you would like to fill dim2 in your first tensor, but if you just want to repeat the values, this code would work: a = torch.randn(16, 512) b = torch.randn(16, 32, 2048) a = a.unsqueeze(2).expand(-1, -1, 2048) c = torch.cat((a, b), dim=1) print(c.shape) > torch.Size([16, 544, 2048…
Swisher
Hi, I implemented the code like below:import torch from torch.autograd import Variable import torch.nn as nn from torchvision import datasets, transforms transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.5],[0.5])]) data_train = datasets.MNIST(root="./data/", transform=transform, train=T...
ptrblck
Sure, I didn’t mean it will always be an int, but still can be an integer. Using your code to create a small code snippet works fine: N = 50000 running_correct = 0.0 running_correct += torch.sum(torch.randint(0, 2, (N,)) == torch.randint(0, 2, (N,))) running_correct /= N print(100*running_correct)…
B4D_0M3N
Hello,I am trying to retrain AlexNet, however, in order to check if I could improve accuracy, I would like to feed it a scalar information, namely before the last fully connected layer. Nonetheless, I cannot find any way to flag “input layers” using pyTorch, so I have no idea how to achieve this. Does anybody tried any...
ptrblck
You can simply modify the forward method of your model and pass an arbitrary number of parameters. PyTorch does not use specific “input” tensors etc.
Fawaz_Sammani
Hi,I need to detect equality in my tensors. I am using two equivalent ways to multiply 4D metrics, which is element-wise then sum, and torch.bmm. The results are the same, but when checking with the ("==") operator, they dont seem to be.import torch a = torch.rand(3,2,100) b = torch.randn(3,4,2) a_expanded = a.unsqueez...
ptrblck
Due to floating point precision you might get small errors (usually at ~1e-6), so I would suggest to compare the results with torch.allclose (and specifying the tolerance manually, if necessary). A direct comparison for floating point numbers is often not the best idea.
Swisher
I implemented the code like below:class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1), nn.ReLU(), nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1), ...
ptrblck
CIFAR100 contains images for 100 classes (this is what the 100 stands for), so you need to change the output units to 100 in your last linear layer. If you want to use just 10 classes, you should use CIFAR10 instead.
rasoolfa
Hi,Is there any advantage to using “load_state_dict” not “deepcopy” or vice versa when one wants to ‘deep’ copy, i.e. updating model_B doesn’t change model_A after copy, one model to another?class DummyNet(nn.Module): def __init__(self,..): super(dummyNet, self).__init__() ... def forward(....
ptrblck
As you said, both codes should work, so that a parameter update in one model does not change the other and vice versa: modelA = models.resnet18() modelB = models.resnet18() modelA.load_state_dict(modelB.state_dict()) # Compare random parameter print((modelA.fc.weight == modelB.fc.weight).all()) > …
hyperlight
If my model includes BatchNorm or Dropout layers, do I need to set my model in evaluation mode before computing the training accuracy?def accuracy(batch, model): x, y = batch y_pred = (model.predict(x)).type(torch.FloatTensor) y = y.unsqueeze(1) correct = (y_pred == y).type(torch.FloatTensor) retu...
ptrblck
Usually you would just calculate the training accuracy on-the-fly without setting the model to eval() and recalculate the “real” training accuracy for this epoch. Mostly because it’s just too expensive and the running loss estimate is often good enough. That being said, there are some issues in you…
hunar
what is the mean of (most likely classes )?top_p, top_class = ps.topk(1, dim=1)Look at the most likely classes for the first 10 examplesprint(top_class[:10,:])
ptrblck
I assume ps gives you the class probabilities (or logits), so topk will give you the highest class probabilities (logits) with the class indices for the current samples. Since you are using .topk(k=1, dim=1), you’ll only get the single most likely prediction.
Vlad_Dumitru
I’m still a beginner in terms of AI and Neuronal Networks and during the time this time of learning I’m trying to do some examples but I have a problem and no idea how can I fix it. If any of you would be able to help me, I would be really grateful.What I’m trying to do?A simple image classification with 10 types of an...
ptrblck
I’m not exactly sure, what your custom Dataset is doing, but based on the folder structure you have, you could probably just use torchvision.dataset.ImageFolder and pass the transformation to it. This will assign a class index to each folder. If you would like to stick to your custom Dataset, if s…
Rojin
I would like to look at my decoder weight matrix ( as a heatmap). I am a bit confused about the shapes, shouls I user the 5th matrix? ( the size can be seen in the model.parameters().Model( (encoder): Encoder( (model): ModuleList( (0): Linear(in_features=6000, out_features=100, bias=True) (1): BatchNo...
ptrblck
No, ReLU does not contain any parameters. They correspond to the nn.Batchnorm layer in the encoder. The index in encoder.model.1 is corresponding to the ModuleList index when you print the model.
Mactarvish
Hi, I’m trying to add a ReLU layer to PART of my model’s output, here is my code:import torch.nn as nn import torch input = torch.ones(2).cuda() linear = nn.Linear(2, 2).cuda() output = linear(input) output[0] = nn.ReLU(inplace=False)(output[0]) loss = torch.sum(output) loss.backward()but I got the error:RuntimeError:...
ptrblck
The error is thrown, if the output of the computation is needed for the backward pass, as explainedhere(the linked topic doesn’t exactly use your model, but might give you an idea).
agadetsky
I have function that translates image into puzzles usingunfold:def make_jigsaw_puzzle(x, grid_size=(2, 2)): # x shape is C x H x W C, H, W = x.size() assert H % grid_size[0] == 0 assert W % grid_size[1] == 0 C, H, W = x.size() x_jigsaw = x.unfold(1, H // grid_size[0], W // grid_size[1]) x_...
ptrblck
This postmight help.
imagination
I have pretrain model like resnet50, I want to retrain for new datain keras, I do following, how to do it in pytorch:for layer in base_model.layers:if not isinstance(layer, layers.BatchNormalization): layer.trainable = FalseHow to iterator every layers in pytorch model to find out nn.BatchNorm2d?
ptrblck
You could filter out the batch norm layers and set the requires_grad attribute of all other parameters to False: model = models.resnet18() def freeze_all_but_bn(m): if not isinstance(m, torch.nn.modules.batchnorm._BatchNorm): if hasattr(m, 'weight') and m.weight is not None: …
bongbang
I’m trying to visualize an already trained CNN model according tothese instructions, which involve finding an input image that maximizes a feature map of interest. Unfortunately, the input variable is stuck with aNonegrad after back-propagation, so learning is impossible. How can I get the gradients to be computed?devi...
ptrblck
By rewrapping your intermediate activation in a new tensor, you are detaching it from the computation graph: self.features = torch.tensor(output, requires_grad=True, device=device) You could assign self.features directly to output, which will give you a valid gradient in your input tensors.
dennismckinnon
Hi,I’ve run into this task several times when I want to work with a network design so I create a module class for it, but then I want to experiment with varying the number of layers. Unfortunately the simplest solution of just creating an array of the modules during init means that these sub modules will not be added t...
ptrblck
I’m not sure, if I understand the question correctly, but nn.ModuleList should be able to register modules in a list. Why did you implement your own ModuleList? Is nn.ModuleList not working or did you just miss this class?
hunar
what doesrunning_lossin this code ? i know it calculated the loss , and we need to get the probability .please take a look at the comment sectionsfor e in range(epochs):running_loss = 0for images, labels in trainloader:# this loop through 938 images and labels (length of trainloaderimages = images.view(images.shape[0],...
ptrblck
The average of the batch losses will give you an estimate of the “epoch loss” during training. Since you are calculating the loss anyway, you could just sum it and calculate the mean after the epoch finishes. This training loss is used to see, how well your model performs on the training dataset. …
Jordan_Howell
Should i use softmax on the last layer with Cross entropy loss for a binary classification? Is there a cheat sheet out there on how to pair up the last layer and loss criteria?
ptrblck
You can use: raw logits (no activation function at the end, just the raw output of the last layer) + nn.CrossEntropyLoss F_log_softmax on the model output + nn.NLLLoss If you need to see the probabilities for debug/printing purpose: use softmax and print the output use exp() and print the ou…
Omar2017
Why we use random cropping for the image in deep learning, is it one of data augmentation? What if an important portion of the image is cropped?
ptrblck
Yes, it’s a data augmentation method. Often your crop size is not much smaller than the original image size, e.g. you are cropping 224x224 patches out of a 256x256 image. However, some techniques (IIRC in Inception) use larger differences between the crop size and original size.
Chame_call
Is that possible to use rnn network to classify sequence of increasing numbers like “Increasing” and sequence of decreasing like “Decreasing”?Or if I have sequences of numbers representing height of mouth between lips of speaking people and non-speaking ones then can I classify whether sequence of numbers represents sp...
ptrblck
In NLP tasks you are usually using a mapping between word indices to dense feature tensors using nn.Embedding. An RNN should be able to take your (floating point) features, however I’m not sure which architecture would work best for your use case.
shuxp
I am training my own code, and I want to implement one function:After training n(=100) iterations, I want to see feature maps.Now I have done with register_forward_hook to see the feature maps, But I want to see them after n iterations. Any idea about how to implement this?Thanks.
ptrblck
That’s an interesting approach! Based on this, you could also create a “hook class” holding this internal parameter, which could be simpler than creating new modules: class ActivationHook(): def __init__(self, name, every_steps=1): self.name = name self.every_steps = every_step…
seongmin
Hi,I am testing my understanding of torch.nn.BatchNorm2d but there is a slight error in numbers that I have failed to resolve.I thought what the Batch Normalization in training mode without any update shall do(x - E[x]) / sqrt(var(X) + 1e-5)which in python code(x - x.mean([0,2,3], keepdim=True)) / (x.var([0,2,3], keepd...
ptrblck
I guess the difference domes from the var calculation, which should apparently be unbiased. I’ve written a manual implementation some time agohereso feel free to compare your code to this one.
talhak
GettingTHCudaCheck FAIL file=..\aten\src\THC\THCCachingHostAllocator.cpp line=278 error=719 : unspecified launch failureerror during the execution of epochs of my LSTM model after a few epochs. The error stacktrace points the lineout, hidden = self.rnn(x, hidden)in theforwardfunction as the reason for error.Here is my ...
ptrblck
Could you run your code with CUDA_LAUNCH_BLOCKING=1 python script.py args and post the stack trace here again, please?
MrRobot
QuestionI would like to implement a network architecture similar to Inception shown below. They are similar in the sense that there are multiple half-way branches (the part within in blue block).image828×301 61 KBIn order to implement this architecture, I could write thoseHalfWayBranchwithinMainBranch. However, I would...
ptrblck
If I understand your use case correctly, you would like to add these auxiliary modules into your model. I would recommend to write a main module and initialize the base model as well as these aux modules inside the __init__. Then in the forward you could simply use an intermediate output, feed it …
FrancescoMandru
I’m new to PyTorch and I’m trying to build a CNN which is structured as follows:Net((conv1): Conv2d(1, 32, kernel_size=(5, 5), stride=(1, 1))(conv2): Conv2d(32, 64, kernel_size=(5, 5), stride=(1, 1))(fc1): Linear(in_features=576, out_features=256, bias=True)(fc2): Linear(in_features=256, out_features=128, bias=True)(ou...
ptrblck
It seems you are not using Ni in your model architecture, but Fm3 instead. The number of input features to the first linear layer should match the (flattened) output shape of the preceding layer. If your conv layer outputs an activation of [batch_size, out_channels, 1, 1], in_features of the linea…
markl
I’m trying to train two nets simultaneously on my machine. When starting the second training script, I got this strange errorRuntimeError: CUDA out of memory. Tried to allocate 136.00 MiB (GPU 0; 12.00 GiB total capacity; 4.51 GiB already allocated; 130.87 MiB free; 164.77 MiB cached)If I have 12.00 GiB total, and 4.51...
ptrblck
I’m not familiar with the Windows task manager output, but it will most likely also show the cached memory (which is allocated by PyTorch and can be reused). The overhead depends also on the layer type. E.g. convolution layers have a small memory footprint regarding their parameters, but a larger …
zhaopku
I am using K40c GPUs with CUDA compute compatibility 3.5. I installed PyTorch viaconda install pytorch torchvision cudatoolkit=10.1 -c pytorchHowever, when I run the following program:import torch print(torch.cuda.is_available()) print(torch.version.cuda) x = torch.tensor(1.0).cuda() y = torch.tensor(2.0).cuda() prin...
ptrblck
Yes, that’s why I asked about Windows.The driver should be new enough for Linux. It seems the minimal compute capability is now 3.7 based onthis commitfor the binaries, so you might need to build from source.
dancedpipi
I can’t find anywhere to download libtorch previous.Could you provide one?
ptrblck
I’m not sure, if there is a better way, but you could try to change the URL from the latest release: https://download.pytorch.org/libtorch/cu101/libtorch-shared-with-deps-1.3.1.zip to e.g. https://download.pytorch.org/libtorch/cu100/libtorch-shared-with-deps-1.2.0.zip for 1.2.0 with CUDA10.0