user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
seongmin
Hi,I am trying to do multi-task learning with two classification layers from single shared representation.I believe, having two nn.Linear layers would not differ from having one nn.Linear layer then split,but it occurs to me they work differently when used with nn.DataParallel.Please see the code at the bottom.<class ‘...
ptrblck
Since the error is that low, I would still assume it’s still due to floating point precision.
Novak
I have a system with a GTX 1070 and a Titan RTX installed in it.Nvidia-smi yields:| 0 GeForce GTX 1070 Off | 00000000:03:00.0 Off | N/A || 1 TITAN RTX Off | 00000000:04:00.0 Off | N/A |However,print(torch.cuda.get_device_name(“cuda:0”))print(torch.cuda.get_de...
ptrblck
nvidia-smi shows the devices by PCI order, while the CUDA driver and Runtime API should sort the devices based on their “performance”. To get the same order in your PyTorch script, you could try to set export CUDA_DEVICE_ORDER=PCI_BUS_ID before running your script.
zhengrchan
Hi, I’m having trouble loading the distributed dataparallel model to just 1 GPU. And I want to know how to load the model (trained by 4 GPU with distributed dataparallel) to another job using only 1 GPU.I have trained a model using 4 GPU and distributed dataparallel, and I saved it as the tutorial:https://pytorch.org/t...
ptrblck
I’m not sure to understand the use case. It seems you would like to load the state_dict to a single GPU machine, but in your code you are wrapping the model again in DDP. Would creating the model, loading the state_dict, and pushing the model to the single GPU not work?
Arking1995
Hi, I tend to run my binary segmentation codes with loss function nn.BCEWithLogitsLoss(). The positive and negative target is not balanced so I tend to use pos_weight. However, it returns the runtime error which I don’t know why.Code:model = model.cuda()w_pos = torch.tensor([4.538])criterion = nn.BCEWithLogitsLoss(pos_...
ptrblck
I tried the code with every tensor on the GPU but w_pos and got the same error message, thus I assumed this is the error. Could you post a code snippet to reproduce this error?
MrRobot
ProblemAs could be seen from the following snapshot, there are two thingsWhen I use less than half of the GPU memory (2392 vs. 5904). The Volatile GPU-Util is almost 100%.The maximum batch size I could have is 128. If I made it larger (like 256). My code could not run because of following errorRuntimeError: CUDA out of...
ptrblck
The utilization gives the percentage of executing kernels during a time frame. It neither gives you the percentage of used memory nor the percentage of busy multiprocessors. You could try to increase the batch size with by a smaller amount and try to max out the memory. However, not that too l…
BlueBlazin
Is the computation graph created every time you evaluate your model on an input?
ptrblck
Yes, the computation graph will be created while running the specified operations (usually in your model’s forward, but it can be created by any arbitrary operation with a tensor which requires gradients). If you don’t specify retain_graph=True, the computation graph will be cleared after the backw…
abze6213
How to set values at tensor at dynamic dim? The sizes of the tensor parameter can be dynamic.For example, for tensor = torch.rand(size=(4, 5, 6)), how to create a function like below? :def ff(tensor, dim, pos, value): # this function can also be applied to tensors # with shapes like [7,5,6,8], [11, 5, 7,5,6,8]...
ptrblck
Depending on the operation, you could e.g. use tensor.index_copy_, which accepts a dim argument.
zimmer550
Hello. This is my CustomDataSetClass:class CustomDataSet(Dataset): def __init__(self, main_dir, transform): self.main_dir = main_dir self.transform = transform all_imgs = os.listdir(main_dir) self.total_imgs = natsort.natsorted(all_imgs) for file_name in self.total_imgs: ...
ptrblck
Yes, the order should be preserved as shown in this simple example using TensorDatasets: datasets = [] for i in range(3): datasets.append(TensorDataset(torch.arange(i*10, (i+1)*10))) dataset = ConcatDataset(datasets) loader = DataLoader( dataset, shuffle=False, num_workers=0, b…
111179
image944×290 6.68 KBWhen I training the car evaluation, the training loss, validation loss and accuracy doesn’t change ,the above is my code, i am a beginner, please give me advice, thank you very much.111179:import numpy as np from collections import Counter from sklearn import datasets import torch.nn.functional ...
ptrblck
Based on your screenshot, it seems the training and validation losses do change. However, nn.CrossEntropyLoss expects raw logits, so you should remove the last softmax layer from your model.
cthnguyen
Hello,I made a little mistake in my code (I think at least …), where I put the following :# Optimizer wd = 0.01 optimizer = optim.Adam(model.parameters(), lr=10e-4, weight_decay=wd) # LR scheduler scheduler = optim.lr_scheduler.OneCycleLR(optimizer, max_lr=1e-4, steps_per_epoch=len(train_loader), epochs=epochs, pct_st...
ptrblck
max_lr from the scheduler should limit the learning rate from the optimizer. You could print out the learning rate for all optimizer.param_groups to check this effect.
Jordan_Howell
When I run my data through a reset model for a binary classification, it returns the probability for each prediction (as the final node is using a softmax). Which is the first number of the binary probability returned, the 0 or 1 class?
ptrblck
Yes, since internally nn.CrossEntropyLoss will apply F.log_softmax and nn.NLLLoss (line of code), so you would have to chose between: raw logits (no activation function) + nn.CrossEntropyLoss F.log_softmax + nn.NLLLoss
WormWakedEarlyEatenB
Here is our data’s address.I want to get a set of volumes with labels not just some labeled images, like a list contains all the volumes and images in each volume.How can I make it?
ptrblck
Do you want to load all images from the volume at once and return them? I think the best approach would be to create a custom Dataset and implement the desired logic there. Basically you could pass the volume paths to __init__, and load all images corresponding to a volume in __getitem__. Have a …
copyrightly
I want to add noise to MNIST. I am using the following code to read the dataset:train_loader = torch.utils.data.DataLoader( datasets.MNIST('../data', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize...
ptrblck
You could create a custom transformation: class AddGaussianNoise(object): def __init__(self, mean=0., std=1.): self.std = std self.mean = mean def __call__(self, tensor): return tensor + torch.randn(tensor.size()) * self.std + self.mean def __repr__…
dhecloud
is it possible to pass your own weights into the loss function during each batch such that it affects how the loss is calculated? Note: I don’t want to use the same weights for every batch (which is theweightargument), I want to weigh the loss from each output neuron dynamically based on a rule from the ground truth la...
ptrblck
If you use the functional API, you would avoid recreating the instance of the loss function. Alternatively, you could pass reduction='none' to the criterion and multiply the loss output manually with your weights. After the multiplication you could take the mean or normalize the loss values as you …
ru6928
Hi, is there an example for creating a custom dataset and training for multiclass segmentation using U-Net? I find many examples for binary segmentation but yet to find something for multiclass segmentation. Thank you!
ptrblck
If you are using nn.BCELoss, the output should use torch.sigmoid as the activation function. Alternatively, you won’t use any activation function and pass raw logits to nn.BCEWithLogitsLoss. If you use nn.CrossEntropyLoss for the multi-class segmentation, you should also pass the raw logits withou…
astri
Hello all, i am a beginner in deep learning and try to make a custom activation function from sigmoid in pytorch . I have an error when trying to implementing that custom activation function in model.def tempsigmoid(x): nd=3.0 temp=nd/torch.log(torch.tensor(9.0)) # how to write in pytorch , cant use float r...
ptrblck
You’ve forgotten to add a comma after nn.Linear(100, 8).
netqyq
When I executed the sourcecode.The code is from the tutorialhttps://pytorch.org/tutorials/intermediate/torchvision_tutorial.htmlIt said that:(base) [yq@local pytorch-examples]$python3 tv-training-code.py Traceback (most recent call last): File "tv-training-code.py", line 13, in <module> from engine import train_o...
ptrblck
From the tutorial: In references/detection/ , we have a number of helper functions to simplify training and evaluating detection models. Here, we will use references/detection/engine.py , references/detection/utils.py and references/detection/transforms.py . Just copy them to your folder and use t…
tueboesen
I’m curious to hear whether other people have managed to get satisfactory performance out of the dataloaders, especially for small networks.Right now I’m testing the dataloader on CIFAR10, with an autoencoder with only 200k parameters. For this test I have all the images saved individually on my disk. And I can’t find ...
ptrblck
If you use the CIFAR10 dataset from torchvision, the data will be loaded into the memory as you suggested (line of code). I’m not sure, which disc you are using, but have a look atthis postfor some information on potential bottlenecks.
sharjeel
I really need help with cross-correlation. From pytorch docs i saw that conv2d layer can be used for cross-correlation, but when i tried to do it i keep on getting errors and cant figure out how to use conv2d layers for cross-correlation to find a template object in a search region. Could someone help me with the code.
ptrblck
You are using an image and filter the same shape (100x100), which will create a single pixel output. This is expected in a cross-correlation as well as convolution. If you want a bigger output shape, use a smaller kernel or a larger image input.
kkjh0723
I got the following after I change my code to use multiprocessing and distributed dataparallel module.Additionally I also started to useapexpackage for mixed precision computation.-- Process 0 terminated with the following error: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/torch/mu...
ptrblck
Could you try to write a transform class and replace the lambda method with it? As far as I know there are some limitation in Python regarding pickling lambdas, which is apparently the case here.
Nathan_Drake
class FaceLandmarksDataset(Dataset): """Face Landmarks dataset.""" def __init__(self, csv_file, root_dir, transform=None): self.landmarks_frame = pd.read_csv(csv_file) self.root_dir = root_dir self.transform = transform def __len__(self): return len(self.landmarks_frame) ...
ptrblck
You have a small typo in the line of code. torch.is_tensor should work, while you are writing is_tentor
Abheesht_Sharma
I have created n patches (say) of an image. How do I return one patch at a time ingetitem() of my Image_Dataset class?
ptrblck
If you’ve created the patches in __getitem__, you could return all of them and create another loop over these patches inside your DataLoader loop, if necessary. Alternatively, if you’ve created the patches before and store them e.g. in a list, you could simply return a single patch by indexing the …
matthias.l
Hi!I am new to pytorch and my model contains a bi-linear layer (= two inputs + one bias).Therefore I implemented a simple module:class Bilinear(nn.Module): def __init__(self, input_size, hidden_size): super(Bilinear, self).__init__() self.W_a = nn.Parameter(torch.Tensor(input_size, input_size)) ...
ptrblck
Did you initialize both models with the same values? Note that torch.Tensor creates a tensor with uninitialized memory, so that you might get arbitrary values (including Infs and NaNs). I would recommend to initialize your custom model with some initialization method from torch.nn.init to make sur…
Nidhal_Baccouri
I’m new to Pytorch and I’m following thistutorialon regression with pytorch but I’m getting different results. I’m stuck on the first example of the tutorial. what I want to do is a non linear regression, the data looks like a vertex curve and I’m trying to build a model to fit the data, the wierd thing is if I use the...
ptrblck
I assume you are concerned about the chaotic lines in the last plot. Note that train_test_split shuffles the data, so you could sort the tensor before plotting: X_train_torch_sorted, idx = torch.sort(X_train_torch, 0) plt.plot(X_train_torch_sorted.detach().numpy(), coarse_preds[idx[:, 0]].detach()…
vijaytida
When I saved the weights of a layer from pretrained model into a dictionary it’s showing only some but I need all weights how can I see those numbers?OrderedDict([(‘weight’, tensor([[[[-3.4618e-02, -3.3801e-02, -2.2497e-02],[-3.2275e-02, -2.8543e-02, -1.5026e-02],[-3.1307e-02, -1.8263e-02, -1.1662e-02]],[[-6.7787e-03, ...
ptrblck
In that case, you could also try to use imhow from matplotlib, which might be clearer in case your tensor is huge.
jiacheng1gujiaxin
Thank you. After I merged conv and batchnorm. I have solved this problem, but I have encountered this problem in training - aware quantification. Do you have any suggestions?File “/home/g/anaconda3/lib/python3.7/site-packages/torch/quantization/observer.py”, line 165, in _calculate_qparamszero_point = qmin - round(min_...
ptrblck
If your weights got a NaN value, this might be due to a NaN input or a faulty weight update caused by e.g. a high learning rate. Did you observe the loss during training? If some weights are exploding, you would usually see a NaN loss.
dali_wang
#batch is a tensor with shape HW for i in range(H): batch[i,:]=i*batch[i,:]T T please
ptrblck
This should work: batch = torch.ones(10, 4) batch = torch.arange(batch.size(0)).view(-1, 1) * batch If you are dealing with more dimensions, you might need to change the view call.
AlexisW
I have a model that works perfectly when there are multiple input. However, if there is only one datapoint as input, I will get the above error. Does anyone have an idea on what’s going on here?
ptrblck
The error is most likely thrown during training and if the current batch only contains a single sample. As you’ve explained this might happen, if the length of your Dataset is not dividable by the batch size without a remainder, which happens to be 1. You could set drop_last=True in your DataLoade…
Yifei
I’m new at deep learning, and I’m writing a 1D CNN model to train my dataset. Each data in the dataset contains three channels:(raw_data, sex, age). The sample rate ofraw_datais 50Hz, and window size is 2 seconds, which means 100 samples in one data. So my data will look like this([1,2,3,4,...,100],[1],[20])where[1]mea...
ptrblck
If I understand the use case correctly, raw_data is some kind of temporal signal, while sex and age are some independent features. I would try to apply the conv layer on the temporal signal alone, use pass the other features e.g. to a linear layer, and concatenate the outputs afterwards. Alternati…
mangotree3
Hi,I have a problem training a model on my server with 8 GPUs. The model has no problems training on 4 GPUs. However, when I try with 5 or more GPUs it reboots without printing any errors or warnings. The memory, wattage, temperature, GPU-Util of the individuals GPU (monitored via nvidia-smi) look normal at the moment ...
ptrblck
Based on the description I would suspect a faulty or weak PSU, which is causing the reboot. However, could you run the code with 4 different GPUs and make sure that it works with all devices?
John1231983
In VGG network, I often saw theneural_style_tutorialcnn = models.vgg19(pretrained=True).features.to(device).eval()It will extract VGG features from pre-trained weight. If I train my network on the custom dataset, then to extract my network feature from the trained model. Instead of usingpretrained=True, can I usetorch....
ptrblck
Sorry for the late follow-up. Yes, you are right. If you want to call backward on the loss, you shouldn’t wrap the forward pass in a torch.no_grad block. This is useful for validation, test, inference, where no backward will be called and thus the intermediate variables can be freed to save memory…
markl
In thepython API, theNLLLossis allowed to take a target shape (N, d1, …, dk). However, in the c++ api, thetorch::nll_losswill crash with an exceptionmulti-target not supported at C:\w\1\s\windows\pytorch\aten\src\THNN/generic/ClassNLLCriterion.c:22Is there a multi-target NLL for c++?Here is my code#include <torch/scrip...
ptrblck
This seems to be indeed the right shape and I remembered I’ve seen this issue before! Could you check, if nll_loss2d is defined and if so use it instead of nll_loss (I’m currently not on my machine to check it)?
markl
I foundnll_lossbut I didn’t findcross_entropyin this listhttps://pytorch.org/cppdocs/api/namespace_at.html#functionsIs it missing? Also - what isbinary_cross_entropy?
ptrblck
nn.CrossEntropyLoss is calling F.log_softmax and F.nll_loss internally as describedhere. As mentioned in the linked topic,@yf225is actively coordinating the development of the C++ API. binary_cross_entropy is used for binary or multi-label classification use cases.
tueboesen
I have the following very simple resnet that I currently use:class ResNetSimple(nn.Module): def __init__(self, block, layers, channels): super().__init__() assert len(layers) == 3 layers_ = [] chan = channels for sublayers in layers: layers_.append(block(chan,chan...
ptrblck
Since scaling doesn’t require gradients, you should register this tensor as a buffer via self.register_buffer('scaling', torch.zeros(...)) This will make sure to push this tensor to the specified device(s).
haowxu
Hi, I have a training code that runs on a single GPU like this:def train(): model.train() torch.cuda.reset_max_memory_allocated() for batch_idx, (inputs, targets) in enumerate(train_loader): inputs = inputs.cuda(non_blocking=True) targets = targets.cuda(non_blocking=True) outputs =...
ptrblck
cudnn benchmarking will try different algorithms for your input shape and model. Some algorithms trade memory for speed, so you might see a higher memory usage and a slowdown (due to multiple profiling runs) for the first iteration. This shouldn’t yield to an OOM error, as cudnn shouldn’t use an a…
shirui-japina
I refer to the model in the paper‘Deep Learning for the Classification of Lung Nodules’.The model is like this:def forward(self, input_image): # (channels, height, width) ## out = self.conv_1(input_image) # 20 * 44 * 44 out = self.bn_conv_1(out) out = self.pooling_1(out) # 20 * ...
ptrblck
For a binary classification use case, you could use a single output and a threshold (as you’ve explained) or alternatively you could use a multi-class classification with just two classes, so that each class gets its output neuron. The loss functions for both approaches would be different. In the …
viniciusarruda
What is the behavior of passing all or some model parameters withrequires_grad == Falseto an optimizer ?If I have a model and want to fine tune it. Some layers are frozen (requires_grad == Falseand.eval()) with pre-trained values. Should I remove the parameters withrequires_grad == Falseto pass to the optimizer ?
ptrblck
All parameters without a .grad attribute will be skipped as shownhere. You could avoid this step by filtering out all parameters which don’t require gradients.
astri
Hello allI am beginner in deep learning who recently researching using keras and pytorch. I want to make custom activation function that based on sigmoid with a little change like below.new sigmoid = (1/1+exp(-x/a))what i do in keras is like below#CUSTOM TEMP SIGMOID def tempsigmoid(x): nd=3.0 temp=nd/np.log(9...
ptrblck
Your code should work, if you replace the numpy as Keras calls with their PyTorch equivalent: def tempsigmoid(x): nd=3.0 temp=nd/torch.log(torch.tensor(9.0)) return torch.sigmoid(x/(temp))
gggggxz
import torch x = torch.arange(25).view((5, 5)) y = torch.tensor([[3, 4, 2, 2], [0, 4, 1, 1], [2, 4, 3, 1]]) # shape: (3, 4) result = torch.zeros(3, 4) for i in range(1, 4): current_y = y[:, i] # shape: (3,) prev_y = y[:, i - 1] # shape: (3,) result[:, i] = x[prev_y, current_y] print(result)Here is the ru...
ptrblck
This should work: result2 = torch.zeros(3, 4) result2[:, 1:] = x[y[:, :-1], y[:, 1:]] print((result==result2).all()) > tensor(True)
Arta_A
I have made a dataset using pytoch dataloader and Imagefolder, my dataset class has two Imagefolder dataset. These two datasets are paired(original and ground truth image). I want to feed these to pytorch neural network. Dataset class:class bsds_dataset(Dataset): def __init__(self, ds_main, ds_energy): self...
ptrblck
You could unsqueeze the batch dimension via original = original.unsqueeze(0) before passing it to the model.
han.liu
I’m transforming a TensorFlow model to Pytorch. And I’d like to initialize the mean and variance of BatchNorm2d using TensorFlow model.I’m doing it in this way:bn.running_mean = torch.nn.Parameter(torch.Tensor(TF_param))And I get this error:RuntimeError: the derivative for 'running_mean' is not implementedBut is works ...
ptrblck
Could you try to assign a torch.tensor instead of an nn.Parameter, since the running estimates do not require gradients?
Lewis
Hi,I am working on a problem that requires pre-training a first model at the beginning and then using this pre-trained model and fine-tuning it along with a second model. When training the first model, it requires a classification layer in order to compute a loss for it. However, I do not need my classification layer w...
ptrblck
Could you try to save the state_dict instead of the model and optimizer directly? Then while restoring, try to use strict=False in .load_state_dict.
bluesky314
I am trying to load models from the model zoo in Google Colab and keep getting the errors:AttributeError: module 'torch.jit' has no attribute 'unused'I was trying to loadhttps://pytorch.org/hub/pytorch_vision_deeplabv3_resnet101/and used the offical link to open in Colab yet getting this error. Even if I try to import ...
ptrblck
Thanks for raising this issue! It seems the currently linked model cannot be imported using the latest stable release (1.2.0). However, after installing the nightly build, the model was loaded successfully in my colab notebook. Try to run the following lines: !pip uninstall torch -y !pip install…
kenneth_maanika
Hi.Whenever I Normalize my input images with its mean and std, and when i plot the images to visualize i get this message along with plots of images which are distorted in a way.Clipping input data to the valid range for imshow with RGB data ([0…1] for floats or [0…255] for integers).Clipping input data to the valid ra...
ptrblck
The easiest way would be to plot them before normalizing. However, if that’s not possible, you could also undo the normalization: x = torch.empty(3, 224, 224).uniform_(0, 1) mean = (0.5, 0.5, 0.5) std = (0.5, 0.5, 0.5) norm = transforms.Normalize(mean, std) x_norm = norm(x) x_restore = x_norm * …
munna
Hi!I am trying to use Unet++ for semantic segmentation.input shape is: [N, H, W] i.e: [16, 256, 256]target shape is: [N, 1, H, W] i.e: [16, 1, 256, 256]and output shape is: [N, 1, H, W] i.e: [16, 1, 256, 256]loss function is: BCEWithLogitsLossI have trained my model usingthis model architecture. And it’s working fi...
ptrblck
Since the last convolution layer has only a single channel, you won’t be able to use it for 3 classes. Instead you would have to assign a new nn.Conv2d layer with out_channels=3 to model.final and retrain this layer for your new use case.
Puli
Hi guys,I found that after invoking save_image(input_tensor), the input_tensor is normalized to [0, 255]. Was it designed this way? it might not be appropriate for this function to modify input in-place.Did anyone have the same problem?The source code indicates that a view of input tensor was modified in-place.def make...
ptrblck
It is a known issue and was fixedhere. You should get the fix, if you install the nightly binaries or from source.
Niki
Hi,In Torchtext,train, test = datasets.IMDB.splits(TEXT, LABEL)divides ratio between train and test 50:50, is there any ways that we change this ratio to 80:20?
ptrblck
The ratio for splitting the IMDB dataset originates from the data itself, as 25,000 reviews are provided for training and 25,000 for testing. From thedataset website: We provide a set of 25,000 highly polar movie reviews for training, and 25,000 for testing.
scarecrow21
I am trying to implement an NER tagger and I’m stuck in the implementation of loss function. I’m using cross entropy loss.They_predsize is =torch.Size([2, 49, 9])They_batchsize is =torch.Size([2, 49])# Config BATCH_SIZE = 2 EMBEDDING_SIZE = 5 VOCAB_SIZE = len(word2idx) TARGET_SIZE = len(tag2idx) # number of output tags...
ptrblck
Sorry for the typo, but apparently autocorrect “corrected” permute to permit.Could you .permute the dimensions, since view will not yield the desired results: x = torch.arange(2*3*4).view(2, 3, 4) y = x.view(2, 4, 3) z = x.permute(0, 2, 1) print(x) > tensor([[[ 0, 1, 2, 3], [ 4, 5,…
Hongkai_Zheng
Hi. I changed the transforms code part of DCGAN tutorial(https://github.com/pytorch/tutorials/blob/master/beginner_source/dcgan_faces_tutorial.py) fromdataset = dset.ImageFolder(root=dataroot, transform=transforms.Compose([ transforms.Resize(image_size), ...
ptrblck
Did you make sure all image tensors have the same width and height after removing the two mentioned transformations? Also, is this effect reproducible, i.e. how many times did you run the code?
shivam2298
I am currently dealing with a large image dataset. For each epoch I am using 10000 samples and 128 batch size. ingetitemI am randomly sampling images from my dataset. What can I do so that after every epoch the sampling is different from the previous epoch and not repeated?
ptrblck
Based on your description, if sounds rather as if you would like to just load images randomly. If that’s the case, just swap by Dataset for ImageFolder and the code should work nevertheless.
ati
Helloi have a code that it is subclassing nn.moduleclass Connection(torch.nn.module): super().__init__() def reset_(self) -> None: """ Contains resetting logic for the connection. """ super().reset_()i don’t know what exactly reset_() doesand i did not find any reset_() function in nn.m...
ptrblck
Thanks for code. I tried to create a small reproducible code snippet and it just seems the base class’ reset_ is called, which does nothing, since it’s implemented as a pass: class AbstractConnection(ABC, nn.Module): def __init__(self): super(AbstractConnection, self).__init__() …
XW324
For example, we have a model only containing a single conv2d layer(1 feature to 1 feature and kernel size of 3). How do I fixed the center weight of this conv layer?Last time I tried, I used model.conv2d.weight.grad[index for center weight]=0. It does set the weight.grad to zero, but after calling optimizer.step(), th...
ptrblck
Zeroing out the gradients should work for optimizers without running estimates. If you are using an optimizer with internal states (e.g. Adam), this approach will still work, if you zero out the gradients from the beginning: conv = nn.Conv2d(1, 1 ,3) weight_reference = conv.weight.clone() optimize…
blackbirdbarber
I checked all methods in herehttps://pytorch.org/docs/stable/cuda.html#module-torch.cudaand could not find single method that can bring me the GPU size of the device.How to get total memory of GPU device and total available GPU memory on device?
ptrblck
print(torch.cuda.get_device_properties('cuda:0')) > _CudaDeviceProperties(name='TITAN V', major=7, minor=0, total_memory=12034MB, multi_processor_count=80) will give you some information about your device. Note that the CUDA context (ant other application) might take some memory, which will not be…
lelouedec
As the title says I am trying to get a newer version of pytorch to get this option in the torch.unique function. However when I doconda install pytorch torchvision cudatoolkit=10.1 -c pytorchI do not get the latest version of pytorch (just the 1.0), which apparently does not include this option.How can I get the correc...
ptrblck
Could you try to use cudatoolkit=10.0? If I’m not mistaken, conda will try to install PyTorch 1.0.0 with CUDA9.0 if you specify a wrong cudatoolkit version.
akskuchi
Hello,I have a situation to work with multiple instances of the same model, like this:class Decoder(nn.Module): pass decoders = [] for _ in range(some_number): decoders.append(Decoder())Some weird doubts:All the decoder instances are independent of each other as long as they don’t share a tensor. True/False?To...
ptrblck
Yes, each output tensor will be attached to a computation graph, which involves the same encoder instance. If you calculate some losses based on these outputs and call backward on them, the gradients will be accumulated in the parameters of encoder: encoder = nn.Linear(1, 1) decoders = nn.ModuleLi…
Lewis
Hi. In evaluation mode, do we need to still put the line of dropout? This is the codeimport torch import torch.nn as nn x = torch.randn(4,4) drop = nn.Dropout(0.5) model = nn.Linear(4,6) model.train() model(drop(x)) model.eval() d = model(drop(x)) n = model(x) print(d == n)This gives a matrix of 0s (all False). So wh...
ptrblck
Usually you would create a model containing all layers. If you then call model(inputs), the forward pass will be executed (in your case with the linear layer and dropout). If your model is quite simple, you could use nn.Sequential, otherwise you would just write a custom nn.Module. In your example …
dashesy
To install PyTorch nightly from pytorch.otg:conda install pytorch torchvision cudatoolkit=10.0 -c pytorch-nightlyTo install PyTorch nightlyfrom anacondaconda install -c pytorch pytorch-nightlySo, which one is correct? the latter one installs pytorch-nightly from pytorch channel, the first one install pytorch from pytor...
ptrblck
I would assume the nightly binaries of torchvision and PyTorch should be matching, i.e. both should have the same build date. If some torchvision builds were skipped (for whatever reason), you might have to downgrade PyTorch to the latest matching nightly build.@fmassamight know more about it.
Arhazf
I am trying to have different activations in forward and backward paths. I wrote this code but, it seems that it does not work properly in the backward path.Do I have to include anything else?class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(28 * 28, 64) ...
ptrblck
If you assign a tensor to another, you will use a reference and thus manipulate both, x_backward and x1 using inplace operations. Try to call x_backward = x1.clone() and test the code again. Double post fromhere.
blackbirdbarber
How can we simple calculate the GPU memory model (nn.Module) use? Just a single GPU unit.
ptrblck
To calculate the memory requirement for all parameters and buffers, you could simply sum the number of these and multiply by the element size: mem_params = sum([param.nelement()*param.element_size() for param in model.parameters()]) mem_bufs = sum([buf.nelement()*buf.element_size() for buf in model…
blackbirdbarber
This is rather a theoretical question, but I like to know if one can create UNets for different input image sizes.I already think I know the UNet input size may not match the output size.
ptrblck
That should be possible. If you stick to certain spatial sizes, e.g. powers of two, I would assume that most UNet implementations can handle the input. However, if you would like to use arbitrary input shapes, most likely you would have to add some checks and pad/crop manually for odd sizes etc. T…
rajan
I’m looking to do a simple optimization, similar to the collaborative learning example that Jeremy Howard (fast.ai) showed in his Deep Learning MOOC (Lesson 4 @ 1:08)GivenblockData.shape=(20,14)filled with random numbers, I want to start with two matrices also filled with random numbers, with shapesvert.shape=(20,10)an...
ptrblck
I’m not familiar with the mentioned Lesson in FastAI, however from a code perspective you are detaching the computation graph from vert and hori by using numpy.dot and rewrapping the result in a tensor with requires_grad=True. Since vert and hori are already nn.Parameters, you could stick to PyTorc…
han324solo
How do I pass numpy array to conv2d weight for initialization?I tried using fill_ but apprarently it only support for 0-dimension value.My numpy_data is 4-dimension array.Here’s what I tried:myModel = Net()layers = [x.data for x in myModel.parameters()]layers[idx].data.fill_( numpy_data )
ptrblck
You could use copy_ instead of fill_ or assign an nn.Parameter. Also, the usage of the .data attribute is discouraged. Wrap the assignment in a torch.no_grad() block instead: numpy_data= np.random.randn(6, 1, 3, 3) conv = nn.Conv2d(1, 6, 3, 1, 1, bias=False) with torch.no_grad(): conv.weight …
Mika_S
pip3 install torch===1.2.0 torchvision===0.4.0 -f https://download.pytorch.org/whl/torch_stable.htmldoes not work anymore since the links page does not have 1.2.0 anymore:https://download.pytorch.org/whl/torch_stable.html
ptrblck
Could you try to install the wheels again, as they might have been accidentally taken down as describedhere.
guitarman
Hi!I have defined my autoencoder in pytorch as following:self.encoder = nn.Sequential( nn.Conv2d(input_shape[0], 32, kernel_size=1, stride=1), nn.ReLU(), nn.Conv2d(32, 64, kernel_size=1, stride=1), nn.ReLU(), nn.Conv2d(64, 64, kernel_size=1, stride=1), ...
ptrblck
The output of your first nn.ConvTranspose2d layer will be [batch_size, 64, 3, 3], which is too small for the next one, which uses a kernel size of 4. You could use a kernel size of 4 for the first nn.ConvTranpose2d layer. This, however, will yield an error in the last one, since you are using nn.C…
John1231983
I have a dataset A that contains the high-resolution and low-resolution of flower images. They are labeled as 6 classes. During training, I will randomly select 16 high resolution and 16 low-resolution image and feed them to the network (total we will feed 32 images–batch size =32). A cross-entropy loss will be used as...
ptrblck
You could avoid the reduction in your criterion by using: criterion = nn.CrossEntropyLoss(reduction='none') This will give you a loss values for each sample in the batch. After weighting each element, you could take the average (or normalize, sum etc.).
ihexx
I’m trying to implement a trainable hyperparameter as a member of an nn.Module inheritorI want it to be moved to the same device as the rest of the module withchild_module.to(my_device)I have done this withself.log_alpha= torch.tensor(0., requires_grad=True)then overridenchild_module.to()to move it manually then call t...
ptrblck
If self.log_alpha is trainable (requires gradients), you should wrap it in an nn.Parameter, which will also make sure to move the tensor to the device.
phkb
I have a 4D tensor x, and a 2D index tensor i of shape (N, 3), where i[n] is an index over the first 3 dimensions of x. I would like to extract the x values at these indices. After some trial and error, I found that the following does what I want:result = x[i[:, 0], i[:, 1], i[:, 2]]I was wondering if there was a bette...
ptrblck
Would splitting the index work? x[idx.split(1, 0)]
ProGamerGov
Thechunksinput is a list ofnn.Sequentialnetworks from a model I have divided up to run on multiple GPUs/CPUs. Thedevice_listinput is a list of devices, like for example['cuda:0', 'cuda:1', 'cuda:2', 'cuda:3'], or['cpu', 'cuda:0', 'cuda:1']. Both lists will have the same number of values.Unfortunately I don’t have multi...
ptrblck
You are missing the __init__ call in super: # yours super(ModelParallelModel, self) # fix to super(ModelParallelModel, self).__init__() However, I’m currently not sure, why you are deriving from nn.Sequential instead of nn.Module, as you are not using any attributes from nn.Sequential.
S_Krishna
Hi,I have trained a model to learn correlation between (audio, image) input pairs. While the original use case is for audio-visual correlation, I also want to use the embeddings from an intermediate layer of this trained model for unimodal similarity (e.g image-image or audio-audio similarity). Is it possible to do t...
ptrblck
Since you’ve wrapped the model in nn.DataParallel, you would have to access the methods via the .module attribute: emb1 = model.module.getImgEmb(src_img) emb2 = model.module.getImgEmb(dest_img)
zahra
Hi,I am reading a file includes class labels that are 0 and 1 and I want to convert it to long tensor to useCrossEntropyby the code below:def read_labels(filename): lists = deque() with open(filename, 'r') as input_file: lines_cache = input_file.readlines() for current_line in lines_cache: ...
ptrblck
Could you print the dtype of current_label before passing it to torch.as_tensor? It seems you are reading mixed object types, which would create this error (i.e. not all your values are represented as a numerical dtype).
Nathan_Drake
https://pytorch.org/docs/stable/tensorboard.htmlI just copy the code of first block.Run code in jupyter notebook and open tensorboard in anaconda prompt. Images works well, but graphs is strange.i1920×872 75 KBQQ%E6%88%AA%E5%9B%BE201909202038321916×862 53.9 KBf1339×898 17.8 KB(torch version 1.2)Is it incompatible with ...
ptrblck
This is a knownissueand should be fixed in the nightly builds. Could you update and try your code again?
Steve_Hu
i use ‘nvidia-smi -L’ to list my avaiable gpus,.i don’t set the CUDA_VISIBLE_DEVICES and run my script ‘print(torch.cuda.device_count())’ and it always return 1, anyone can tell me what’s happen? thx!
ptrblck
Could you check, if this environment variable is set somewhere in your code? The line should e.g. look like this: os.environ["CUDA_VISIBLE_DEVICES"]="0"
Mohamed_Ragab
I cannot find transformer module with pytorch version (1.1.0), please can someone help me to get the latest libraries from PyTorch
ptrblck
nn.Transformer was added in PyTorch 1.2.0, so you should update to the latest stable version. Have a look at the install instructions for the binaries:link.
cyvius96
Hi,I tried to use torch.utils.tensorboard (for replacing tensorboardX) and found that:import os import torch import torch.nn.functional as F from tqdm import tqdm from torch.utils.data import DataLoader os.environ['CUDA_VISIBLE_DEVICES'] = '4' from torch.utils.tensorboard import SummaryWriter (main code)works normall...
ptrblck
I’m not sure why this happens, but I would guess that some imports in the__init__ methodchecks for GPUs and thus grabs them (which is apparently not the case in tensorboardX). However, I’m also not sure it’s worth investigating.
oboul
Hi why do we need data normalization in MNIST Data Loader example ?Thank you
ptrblck
Yes, this would produce positive and negative values. Have a look atthis wikifor more information.
dreamer
Hi everyone, I try to convert my linear system to CNN. My linear NN class isclass Module(nn.Module): def __init__(self, D_in, H1, H2,D_out): super().__init__() self.linear1 = nn.Linear(D_in, H1) self.linear2 = nn.Linear(H1, H2) ...
ptrblck
I would guess this error is raised in self.fc2, as you are feeding the shape: x=self.fc2(-1,1901) instead of the activation x.
Swamy
Hi,Is it possible that loops are faster than Data loader?Earlier:def one_hot_vector(x_raw, n_uniq): #time_strt = datetime.now() input_len = x_raw.shape[0] input_col_len = x_raw.shape[1] x = np.zeros((input_len*input_col_len,n_uniq),dtype=np.int8) x_raw = x_raw.reshape(-1,1) for i in range(n_uni...
ptrblck
The manual loop might be faster, since you are just slicing the tensor, while your Dataset copies the data. Try to use torch.from_numpy in your __getitem__ and compare the results again.
Mandy
Hi,I was wondering if someone could tell me what’re the differences betweenConvTranspose2d(group=in_channel) and Upsample(mode='bilinear')Thanks
ptrblck
Upsample will use the mode to “mathematically” upsample the activation (no training), while ConvTranspose2d will use trainable filter kernels.
Arta_A
Hi I am trying to load my custom dataset using dataloader and custom collate_fn for training the neural network, but an error occurred saying that input should be tensor not list:def my_collate(batch): data = [item[0] for item in batch] target = [item[1] for item in batch] return [data, target]class bsds_da...
ptrblck
Also answeredhere.
KFrank
Hello Forum!I am, for whatever reason, attempting to convert a simplepytorch-1.0.1 training script to pytorch version 0.3.0.As far as I can tell,torch.no_grad()doesn’t exist in 0.3.0.My use case is that (in the training loop) I run the model(predict, based on my input data), and then do some sanitychecks and collect so...
ptrblck
In 0.3 you would use Variable(torch.tensor(...), volatile=True) to avoid creating the computation graph. Let me know, if that works for you.
shirui-japina
I try to extract image features by InceptionA (part of GoogLeNet). When there is nooptimizer.step(), it works even with the batch size 128. But when there isoptimizer.step(), it will Error:CUDA out of memory.Here is the code:model = InceptionA(pool_features=2)model.to(device)optimizer = optim.Adam(model.parameters())cr...
ptrblck
The easiest way would be to lower your batch size. If that’s not possible (e.g. if your batch size is already 1), you could have a look attorch.utils.checkpointto trade compute for memory.
lorenzo_fabbri
I’m training a simple self-attention model and I’m obtaining some good results on the validation set (in terms of accuracy, MCC, recall and precision). I’ve done this doing a train/test split several times. Theonlyproblem is that the validation loss is extremely large compared to the training loss. I’m attaching an exa...
ptrblck
It seems you are multiplying by the batch size, which would thus accumulate the loss of all samples in avg_loss. If that’s the case, you should divide by the number of samples to get the average loss, bot the length of the DataLoader, which will return the number of batches.
shresta
Hi,Can torch.clamp() which I assume is some form of ReLU change the output of my NN classification?I am running a celebrity face image on a pretrained VGG Face model. I set the model in eval mode and make a forward pass.image, label = image.to(device), label.to(device) preds = F.softmax(vgg_model_instance(ima...
ptrblck
If you’ve normalized the input data, it’ll have a zero mean and unit variance. Clamping it to [0, 1] might delete a lot of important features, which could explain the bad accuracy.
talhak
I have been using my custom transformation namelyFaceDetectionwhich I added below. Now I am trying to apply it to another dataset which contains face images within the same format of the former (.png). What am I missing? When I do not use this transformation, I do not get any errors.Your help is appreciated a lot.Here ...
ptrblck
I think the face cascade doesn’t find any faces and this loop: for (x, y, w, h) in faces: image_as_arr = np.array(frame)[y:y + w, x:x + h] return Image.fromarray(image_as_arr.astype('uint8'), 'RGB') will be empty. Since you don’t have any other return statement, your transformation will r…
gbraso
Hi!From my understanding, using the BCEWithLogitsLoss should yield the same results as BCELoss composed with sigmoid units. And the only difference between the two is that the former (BCEWithLogitsLoss) is numerically more stable.However, when I test their behavior, I get significantly different results as soon as I d...
ptrblck
You are saturating the sigmoid with such a high number. Have a look at this small test: labels = torch.zeros([1]) for x in torch.linspace(10, 100): print((torch.sigmoid(x) - 1.) == 0, ' for ', x) x = x.view(1) ce = F.binary_cross_entropy(torch.sigmoid(x), labels) ce_logit = F.bina…
Omar2017
Hi every oneI need help to visualize a frames in data set when applying each transformation operation?mean=[0.485, 0.456, 0.406] std=[0.229, 0.224, 0.225] normalize = Normalize(mean=mean, std=std) spatial_transform = transforms.Compose([transforms.RandomRotation(20), ...
ptrblck
If you want to visualize the PIL.Image after each transformation, you could create a custom transformation and call e.g. img.show() (or use any other library to plot the image): class Visualize(object): def __call__(self, img): img.show() return img spatial_transform = …
zahra
Hi,I want to do summation of outputs of several convolution layer and send generated output to the next layer. Is there sum layer (sth like pooling layer, convolution layer, …)?!How could I do it?Thanks
ptrblck
How would you like to sum the conv layer outputs? If you would like to sum over a specific dimension, you could simply use: output = conv(input) output = output.sum(dim=1) # change the dim to your use case On the other hand, if you would like to sum patches similar to a conv layer, you could def…
Mika_S
How does the dataloader create a batch of tensors? Is it simply doing:torch.cat([tensor_1, tensor_2])?Trying to understand whether there is more optimization than that or not.
ptrblck
Depending on the type your __getitem__ method from the Dataset returns, thedefault_collatewill use torch.stack, create a torch.tensor etc.
439327bcc62cd8e45e96
I want to know the number of arguments in the picture (160, 16, 64 …)Please help me.sadasdasd586×840 2.38 KB
ptrblck
You can access the internal attributes using the argument name, e.g. print(bn.num_features).
eFroD
Hello,in order to evaluate the performance of different models (not only pre-trained models), I want to use datasets from ImageNet.The problem is, that I want to go sure, that the images I present, are ‘new’ to the model in order to control the bias but it could be very likely, that popular datasets were used to train...
ptrblck
The classification models were pretrained on ImageNet, while the segmentation and detection models use e.g. COCO. Thepretrainedargument gives you information about the used dataset.
nlam
my imshow function accepts a tensor of (1, 28, 28), but my dataloader is returning a tensor of (1000, 1, 28, 28). The “1000” seems to be the value of the batch_size that I specify in the loader. Is there anyway to fix this.
ptrblck
You could index the specific image tensor you would like to visualize: my_imshow(data[0])
liyunfei1994
Hi ! I recently found a strange problem when using the PyTorch training network.When the model is trained, the loss does not decreaseI’m not sure what caused thisPlease allow me to show my code below.This is my train.py where I run the training code.import torch import torch.nn as nn import torch.optim as optim from ma...
ptrblck
Try to play around with some hyperparameters, e.g. lowering the learning rate.
sachinruk
I’m wondering if I need to do anything special when training with BatchNorm in pytorch. From my understanding thegammaandbetaparameters are updated with gradients as would normally be done by an optimizer. However, the mean and variance of the batches are updated slowly using momentum.So do we need to specify to the op...
ptrblck
No, since the running estimates are buffers and do not require gradients, you don’t have to pass them to the optimizer. You can access them via my_bn_layer.running_mean and my_bn_layer.running_var.
John1231983
I have a network likesx-->fc1(x)-->outputx y-->fc2(y)-->outputySo, when I define the network, can I used the same name for fc1 and fc2 likesclass network(nn.Module): def __init__(self): self.fc = nn.Linear(1,2) def forward(x,y) output1= self.fc(x) output2 = self.fc(y)Or I have to seperate ...
ptrblck
Both models define valid forward methods (besides the missing return statement) and it depends on your use case, which one is correct. If you would like to apply the same parameters for both inputs (weight sharing), the first definition is correct, while the second model will use two different laye…
Ankush
I am shifting to using PyTorch from Keras and TensorFlow. For both of those, the setup on Anaconda is fairly simple.conda install keras-gpuOne command does quick work of installing all libraries including cudatoolkit and keras recognizes my GPU.I installed pytorch and tried running Chatbot example by pytorch on my GPU ...
ptrblck
You just need to install the GPU driver on your machine. The binaries ship with CUDA, cudnn and other libraries. Have a look at thewebsitefor install instructions.
07hyx06
I know that the default initialization of layers aretorch.nn.init.kaiming_uniform(tensor,a=sqrt(5))where a is the gain value of nonlinearity.In my VGG, all my nonlinearity isReLU. So according to the paper ofkaiming_initialization, i should set a=0. When i use that initialization, loss fly to NAN.But when i use the def...
ptrblck
Have a look atthis answer.
Fahman
I want to change the weights of first layer of resnet model mauallythe first layer is :(conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)and the weights shape is:[64, 3, 7, 7]
ptrblck
You could reassign a new nn.Parameter to your weights or just set the values depending on your use case. Here is a small example how to assign new parameters: with torch.no_grad(): model.conv1.weight = nn.Parameter(torch.randn(64, 3, 7, 7)) # or model.conv1.weight.copy_(torch.randn(64,…
Rakshit_Kothari
I have a cluster of 10 GPUs. The default code,if torch.cuda.device_count() > 1: net = nn.DataParallel(net)Uses 8 GPUs. Does PyTorch have a max 8 GPU policy? Training number workers = 1 at the moment but this behavior doesn’t change when I tried 1, 2 or 10.image875×767 96.1 KB
ptrblck
Additionally to what has been said: how large is your batch size and is it divisible by the number of GPUs?
Abdelrahman_Mohamed
data_transforms = { 'train': transforms.Compose([ transforms.ToPILImage(), transforms.RandomRotation(15), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]), 'valid': transforms.Compose([ transforms.ToPILImage(), transforms.CenterCrop(224),...
ptrblck
Your target should contain class indices in the range [0, nb_classes-1]. In your case this would be [0, 23]. To debug this issue, you could add a print statement and check, which target batch fails this assumption.
K163897_Nafix
my dataset have 32 x 32 images, what is the error in it?class Genv2(nn.Module): def __init__(self, *args, **kwargs): super(Genv2, self).__init__() self.conv1 = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=5) self.conv2 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5) ...
ptrblck
The conv and pooling layers in your model will change the shape of your activations depending on the kernel size, stride etc. Have a look atCS231nfor a detailed description. The short version: nn.Conv2d with kernel_size=5 and no padding will subtract 2 pixels on each border (4 pixels in width…