user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
lxtGH
Has anyone know this operation in Pytorch ?
ptrblck
If you would like to use a sliding window of kernel size k, you could try the following code (originally created by@fmassa) : n, c, w, h = 1, 3, 24, 24 k = 3 stride = 1 x = torch.randn(n, c, w, h) input_windows = x.unfold(2, k, stride).unfold(3, k, stride) print(input_windows.shape) > torch.Size([…
radek
I have a 3-dimensional tensor. 10_000 examples x 10 predicted labels x outputs from 3 models.(10_000, 10, 3)I also have a tensor with ids of the model outputs I would like to use for each label. It has 10 values between 0 and 2.Is there any way I could index into the 3d tensor picking an output for a label from a speci...
ptrblck
If I understand you correctly, you would like to select from the last dimension using an index tensor with values in [0, 2]. The same operation should be performed for all examples? If so, you could try the following code: a = torch.randn(20, 10, 3) idx = torch.zeros(10).random_(3).long() idx = …
Diego
I’m trying to load a model that has been trained on GPU intp a machine that doesn’t have CUDA available and I get the following error:THCudaCheck FAIL file=torch/csrc/cuda/Module.cpp line=51 error=35 : CUDA driver version is insufficient for CUDA runtime version Traceback (most recent call last): File "main.py", line...
ptrblck
Try to load your state_dict or model with these arguments to force all tensors to be on CPU: torch.load('my_file.pt', map_location=lambda storage, loc: storage)
Yongjie_Shi
for example, the shape of the output of the network is batchsizewh=1678, how can I get the top left element of every batch, is there some pytorch operator to do it?
ptrblck
You could just index your output: batch_size = 10 output = torch.randn(batch_size, 7, 8) output[:, 0, 0] This will return output at pos [0, 0] for every batch sample.
Brando_Miranda
According tothe docs:class ToTensor(object): """Convert a ``PIL.Image`` or ``numpy.ndarray`` to tensor. Converts a PIL.Image or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]. """but I’m getting a DoubleTensor from a numpy array I sav...
ptrblck
Seems like a small bug to me. Or at least it’s inconsistent with the doc string. Thanks for reporting!
EonianSky
I am using the pre-trained model of vgg16 through torchvision. Now I don’t need the last layer (FC) in the network. How should I remove it?image613×567 42.8 KB
ptrblck
In this case you could use the following code: model.classifier = nn.Sequential(*[model.classifier[i] for i in range(4)]) print(model.classifier) EDIT: Alternatively, you can also call .children, since the range indexing might be cumbersome for large sequential models. model.classifier = nn.Sequ…
WangWenshan
Hi all,I have a float label ( label = label.astype(‘float’) ) in data_loader when I realize the Regression model.However, I met the following type error:TypeError: FloatMSECriterion_updateOutput received an invalid combination of arguments - get (int, torch.FloatTensor,torch.DoubleTensor, torch.FloatTensor, bool), but ...
ptrblck
In numpy the flag 'float' corresponds to 'float64' by default. You could change the line to: label = label.astype('float32') and run it again.
uhotspot4
Getting the following error:RuntimeError: bool value of Tensor with more than one value is ambiguouson running:nn.ReLU(torch.nand(2))
ptrblck
nn.ReLU() create a class. You should assign it to a variable and use an input on this instance: relu = nn.ReLU() output = relu(x) Alternatively you could use the functional API: output = F.relu(x)
Mactarvish
I’ve noticed that optim.optimizer has a variable named ‘param_group’, and it seems can divide a network into many groups and set different learning rate and optimization method for them for better training. But how can I divide a network into those groups? Original network seems is included by just one group. Thank yo...
ptrblck
Have a look at theper-parameter option doc.
mfluegge
Hey,Let’s say I have one trained neural network and want to train another one with the exact same topology.In the 2nd network’s loss function I’ll have a base loss function like MSE and I want to extend it and add something else to the loss. This “something” is the similarity between both networks’ parameters.For now I...
ptrblck
Interesting idea! I think you can try it, although I’m not sure, if your current similarity calculation is really useful. Your criterion would yield a low loss, if the weights are just scaled with a constant, but represent the same transformation. However, I’ve created a small example with some d…
wxwx
I use MINST benchmark to training a simple MLP neural network(batch size = 32), but in the test phase, i want to use one picture to test. Does anyone know about it ?
ptrblck
You shouldn’t wrap your DataLoader instance into a sampler.RandomSampler. Just use this loop: for data in test_loader: img, label = data # or for img, label in test_loader: # your training code
cyvius96
Pytorch 0.4.0a = torch.rand(10, 10)a[:, :0] = 0Then a 's first column becomes 0. Is this a bug?
ptrblck
Can confirm the syntax seems to have a different behavior than numpy. In numpy a[:, :0] gives: array([], shape=(10, 0), dtype=float64), while pytorch gives the first column.
mohan
I am new to pytorch. I have this doubt. Will Pytorch be able to compute the gradients for predefined tensor functions like torch.sum, torch.cat, etc. ? Here is a code snippet for exampleclass Module1(nn.Module): def __init__(self, input_size, output_size): super(Module1, self).__init__() self.input_size = input_...
ptrblck
PyTorch’s autograd is able to compute the gradients for most of the functions. Have a look at theAutograd Tutorial. It’s a nice explanation, how autograd works. Also, your code snippet is missing!
shavitamit
I’m getting two different behaviors ofautograd.Variableand I’m wondering if it’s because of the pytorch version.On my local machine (OS X, pytorch version 0.4.0), I getIn [6]: type(autograd.Variable(torch.from_numpy(np.array([10,2])))) Out[6]: torch.TensorOn the server I’m using (pytorch version 0.3.0.post4), I getIn [...
ptrblck
Tensors and Variables were merged in version 0.4.0. Have a look at theMigration Guide.
Raylene
It looks like I have installed the version 0.4.0 successfully as the attached screenshot.06%20AM2544×350 61.7 KBBesides, I also ran !pip freeze to confirm torch==0.4.0However, when I run the code below. The version still shows ‘0.3.0.post4’!import torch torch.__version__Does colab forbid 0.4.0 or is there anything wron...
ptrblck
Could you try to uninstall PyTorch and run the following command instead: from os import path from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag()) accelerator = 'cu80' if path.exists('/opt/bin/nvidia-smi')…
freelv
I’m new to pytorch. Yesterday, I installed pytorch on our server since source code. Before installation, I have to solve the problem of cuda version and cudnn version. Previously, our server’s cuda version is 8.0, while cudnn version is 5.1. So that the latest pytorch cannot be installed successfully, it needs cudnn ve...
ptrblck
If you build it from source, the script will try to find your CuDNN installation. You can see some information in the terminal while building, e.g. which libs were found and which are missing.
TellonUK
I have grey-scale images in .png and i’m loading them in using ImageFolder(), and I then do the following transforms to get them as a single channel tensor,transformations = transforms.Compose([transforms.ToTensor(),transforms.ToPILImage(),transforms.Grayscale(),transforms.ToTensor()])It works, but im wondering if this...
ptrblck
Why do you need to transform it to a Tensor first, then back to a PILImage? Won’t it work if you remove the two first transforms?
TellonUK
Could someone provide me some starter code for dataloader to load the following into pytorchFolder - DataFolder - trainFolder - 03.png10.png13.png…Folder - 12.png9.png16.png………The folder name is the label for the data, each file is a 28x28 size png.
ptrblck
The easiest way would be to usetorchvision.ImageFolder. This class uses assigns different classes to your folders. TheDataLoderclass wraps the Dataset and provides more functionalities like multi-processed loading, shuffling and batching. Here is an example how your code might look like: data_…
Shounak_Kundu
Hi ,I need to build an RNN (without using nn.RNN) with following specifications :It should have set of weights [It is a chanracter RNN.It should have 1 hidden layerWxh (from input layer to hidden layer )Whh (from the recurrent connection in the hidden layer)W ho (from hidden layer to output layer)I need to useTanhfor ...
ptrblck
Sure, then you would have to call F.log_softmax(output) before passing it to NLLLoss or add it as a layer in your model. CrossEntropyLoss basically combines a log_softmax with NLLLoss.
spacemeerkat
Hi all, I’m using the nll_loss function in conjunction with log_softmax as advised in the documentation when creating a CNN. However, when I test new images, I get negative numbers rather than 0-1 limited results. This is really strange given the bound nature of the softmax function and I was wondering if anyone has en...
ptrblck
Since you are using the logarithm on softmax, you will get numbers in [-inf, 0], since log(0)=-inf and log(1)=0. You could get the probabilities back by using torch.exp(output).
Kong
I have a dataset whose labels are of shape [torch.FloatTensor of size 316x2] for a one hot encoding with 2 classes. My neural network has output layer of 2 neurons. When I tried to use criterion = nn.CrossEntropyLoss() I get this error Expected object of type Variable[torch.LongTensor] but found type Variable[torch.Flo...
ptrblck
No, your last layer should return the number of classes. So it would have dimensions [batch_size, classes]. The target vector should only contain the class indices.
Joey_Bose
Is there a way to split a batch of say N by K where N is the number of samples with K being the feature dimensionality into equal chunks? Torch.split() does the job but it, unfortunately, returns a list which I don’t think you can backprop through. torch.view() could also work but i’m not sure on the order of traversal...
ptrblck
Seems like a valid approach for me. Currently I don’t know another method for your use case. Could you check, if this order is right: N = 9 D2 = 10 x = torch.arange(N).unsqueeze(1).repeat(1, D2) print(x) print(x.view(N/3, 3, D2)) As you can see, the D2 dimension is still the same.
PangWong
As stated inpytorch documentation,NLLLossis defined as:I found there is nologoperator in NLLLoss which is different from what I saw ineq.80 in chaper3 of book Neural Networks and Deep Learning.Also I found indocumentationit explainstorch.nn.CrossEntropyLossas a combination ofLogSoftMaxandNLLLoss,which is also different...
ptrblck
Separating log and softmax might lead to numerical instability which is why you should use log_softmax as one function. For NLLLoss you need to pass log_softmax(x) into the criterion. It you prefer to handle raw logits, you can use CrossEntropyLoss, which adds LogSoftmax by itself.
bhushans23
I am reading images from H5 File as belowsyn1 = hf['data_1'] syn1 = np.array(syn1[:,:,:]) .... .... synImage1 = torch.utils.data.DataLoader(syn1, batch_size=50)But, DataLoader does not apply transform where I can normalize image.Can we use Datasets on Dataset collected from H5 file separately to normalize?How to apply ...
ptrblck
You could try something like this: class MyDataset(Dataset): def __init__(self, numpy_arr, mean, std): self.data = torch.from_numpy(numpy_arr) self.mean = mean self.std = std #normalize here or in __getitem__ def __getitem__(self, index): data = self…
gwding
I’ve encountered a problem of gradients of conv2d layer having random behavior on GPU. It only happens on GPU with certain hyperparameters.Specifically, for the same input and same network, the gradients are not exactly the same every time.import torch import numpy as np from torch.autograd import Variable import torch...
ptrblck
Could you try to disable cudnn, since it has some non-deterministic behavior: torch.backend.cudnn.enabled=False
TheShadow29
Say I have a 2D signal which is basically 4 channels of 1d signals and each 1d signal is of shape 100. So my input is of shape 100x4. Now I have a single kernel,torch.nn.Conv1d()and I want to apply the same kernel to each of the channels individually. What is the most efficient way to do this?The method I have come up ...
ptrblck
You can initialize it with the same weights for each input channel. The vanilla weight updates will change the weights without the constraint to have the same values. If you need to backpropagate, the better method would be to change the view of the input channels, so that the channels are stored i…
Freyj
Hello,I am making a neural network to make a binary classification and I would like to check the predictions made in the testing phase of my network, but I don’t seem to be getting the proper values.What I want is not the loss over the whole batch but each prediction over every test sample to compare it to the true val...
ptrblck
It’s probably user’s preference, but I would remove the keepdims=True ans .view_as, like in my code.Ah ok, I understand. You could just store them in a list. preds = [] targets = [] for i in range(10): output = F.log_softmax(Variable(torch.randn(batch_size, n_classes)), dim=1) target = …
Brando_Miranda
I was looking at:trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2) testset = torchvision....
ptrblck
I had a look at your code and it seems your error calculation does overflow. In this method you are calculating the error: def error_criterion(outputs,labels): max_vals, max_indices = torch.max(outputs,1) train_error = (max_indices != labels).sum().data[0]/max_indices.size()[0] return …
machine
I don’t understand since we always use optimizer.zero_grad() to clear the gradinet saved in the variable, why it keeps the last gradient.Is there any other place to use the previous gradient?
ptrblck
You could simulate a larger batch size by accumulating the gradients from a few forward passes and call backward() on these. Also in theDCGANexample the gradients from the “real” and “fake” loss are accumulated and the optimizer is called just after both backward passes were called. It gives you…
Kiuhnm_Mnhuik
I’m using float64 values on the cpu but I want to use float32 values on the gpu. What’s the fastest way to convert a DoubleTensor to a cuda.FloatTensor?
ptrblck
Ah ok, I understand. Well you could use a = torch.DoubleTensor(10) a = a.type(torch.cuda.FloatTensor) , if you would like to have a single command. I tried to time it with torch.cuda.synchronize() and got mixed results. Currently my GPU is busy, so the timing is most likely useless in this stat…
amazing_coder
the code is shown below:class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) # an affine operation: y = Wx + ...
ptrblck
Calling a nn.Module like self.conv1(x) or net(input) calls the internal __call__ method. Have a look at thesource. This method performs some operations regarding forward and backward hooks and calls forward.
tux
Hello everyone !I am trying to code a DCGAN from scratch but I have some issues and I hope you can help me with it.I defined my Generator as following :class Generator(nn.Module): """docstring for Generator.""" def __init__(self): super(Generator, self).__init__() self.Tconv1 = nn.ConvTranspose2...
ptrblck
You have an unnecessary comma after the definition of self.Tconv1, which makes it a tuple with one entry. Remove it and also change the in_channels to 100 to match z's channels.
machine
I konw the parameters of neural network should be wrapped by Variable to update the value, but the input data never change, why it should also be warpped by Variable?
ptrblck
In the next release Variable will be merged with Tensor, since the Variable class adds indeed some conceptual overhead, which might confuse new PyTorch users.Hereis the GitHub issue, in case you would like to follow the development.
ousan
Hello Dear all,I have newly started using pytorch. Actually my question is not completely related to pytorch.I want to know the image whether consist a specific object or not. Simply I mean, does a picture consist a Plane?To determining this and using cnn, what should the number of output class be? My code is posted be...
ptrblck
Yes, one output is fine. You could use a nn.Sigmoid layer as the model’s output and BCELoss. In case you would like to use logits, you could skip the sigmoid and just use BCEWithLogitsLoss. The second approach should be numerically more stable. In the post before I said logsigmoid which was wrong …
joe8767
Firstly, a bunch of data is classified by the CNN model. Then, I’m trying to make prediction on correctly classified data from first step, which is expected to give an accuracy of 100%. However, I found the result is unstable, sometimes 99+%, but not 100%. Is there anybody know what is the problem with my code? Thank y...
ptrblck
You should set your model to evaluation by calling model.eval() in your test method. This makes sure that some layers like BatchNorm and Dropout are switched to evaluation mode, i.e. for BatchNorm the running statistics are used instead of being updated. The previously correctly classified samples…
lelouedec
hey,I am using the code example fromherein my code :dsets = datasets.ImageFolder(‘./dataset/’)dset_loaders = torch.utils.data.DataLoader(dsets, batch_size=1, shuffle=False)but I end up getting the following error :TypeError : batch must contain tensors, numbers … found <class PIL …Am I doing it wrong ?
ptrblck
You have to transform the images into Tensors. You could use this code taken from the ImageNet example: normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_dataset = datasets.ImageFolder( traindir, …
venmadh
I’m trying to build a simple Auto-encoder with pytorch with the encoder being a standard convnet that outputs a latent code. The decoder is a reverse of the encoder that takes in the latent code and outputs the generated image. After a bit of training, the reconstruction is perceptually acceptable.However, the trained ...
ptrblck
I guess you didn’t set your model to evaluation before generating the samples. Since you are using some BatchNorm layers, the running statistics will be calculated and updated using the current batch. Try to call model.eval before the inference step. This will make sure to use the approximate runnin…
Oktai15
Hi there!I successfully trained my model that was declared as:model = ModelClass(...) model = torch.nn.DataParallel(model, device_ids=[0, 1, 2])During training, I saved my weights like this:best_model = copy.deepcopy(model.state_dict()) torch.save(best_model, path)And I could get my weights for test (it isn’t NoneType,...
ptrblck
You don’t have to assign the trained_model to load_state_dict. model should have all weights loaded. Have a look at theSerialization info.
siddharthm
I want to call a function defined in my dataset class at the end of every epoch of training. I’m not sure if it’s the right thing to do and I wanted some feedback. The current structure looks something like below:class my_dataset(nn.data.utils.Dataset): __init__(self, ...) __len__(self) __getitem__(self, id...
ptrblck
What would you like to achieve? You could also call train_loader.dataset.my_func(). Both ways should work though.Igniteprovides some event handling like @trainer.on(Events.EPOCH_COMPLETED). Maybe the code would be cleaner, if you need a lot on these events.
ForeverZH0204
When i set the module into eval mode, what is the BN layer’s use?Q1:The doc says it use gamma and beta to change the input, but where is it from?Q2:What dose the momentun parm do in the BN?
ptrblck
Yes, exactly. You have to be a bit careful with the meaning of momentum, since it weights the currently observed value. It’s default value is thus 0.1. You will find the opposite definition in other frameworks, with a default value of 0.9.
Yana_G
Hi all,I’m trying to solve a problem of video recognition using 3d cnn’s.I want to classify the videos into 6 classes, I tried training an END-TO-END 3d cnn’s model that didn’t give me good results (around 40% accuracy) so I decided to try a different approach and training 6 models of binary classification for each cla...
ptrblck
Ok, interesting idea. So as far as I understand your approach, each models uses its mean and std, which were calculated on the positive samples for the appropriate class. Am I right? Did this approach outperform 6 different models using a global mean and std? However, you could relocate the stand…
Sieyk
The PyTorch example atfor face landmarksseems to suggest that training with that many target (in sets of two) is possible.I have attempted to incorporate their working in order to set up my own dataset, but when I try to train, I just get:RuntimeError: multi-target not supportedI am at a loss how one would train the da...
ptrblck
Which criterion have you used? It seems you used a criterion, which is not suitable for multi-target prediction, e.g. NLLLoss. Could you try it again with e.g. MSELoss?
prateekagarwal3
I am facing a bug, for which most of the people say that the solution is building pytorch from source, and I dont know how to do that.
ptrblck
Have a look at thisguideto install PyTorch from source. It should be easy, but let me know if you encounter any problems. Version 0.4 is not officially released yet, so you have to build it yourself at the moment.
alexisrozhkov
Hey, I’m trying to reproduceCrossEntropyLossimplementation (in order to change it later for my needs), and currently I’m not able to match the results when non-uniform weights are provided andsize_averageis set toTrue(but if weights are uniform and/orsize_averageisFalse- results match, at least their printed representa...
ptrblck
I think fot size_average=True you have to sum the weighted loss and divide by the sum of the used weights: CE = torch.sum(weights.index_select(0, target)*(-torch.log(p_t))) / torch.sum(weights.index_select(0, target)) This should yield the same result.
jpcenteno
I have a large dataset (over 200,000 images) that I am using for semantic segmentation. My batch size is 1 due to the size of images and network parameters. I would like to train this model by iterating 4000-5000 images per epoch so I can run validation more often. In Keras, you have an option using fit_generator to as...
ptrblck
The easiest way is to call your evaluation every x steps: steps = 4000 for batch_idx, (data, target) in enumerate(train_loader): # your training routine if batch_idx % steps == 0: # your evaluation routine
nicoliKim
Hello everyone,I have a simple issue but I am not sure how to deal with.Let’s say I have a tensor (B, N, N, F) where B is the Batch Size, N the dimensions of a square matrix and F the dimension of my feature space. What is the most straight forward way to mask the diagonals with 0?
ptrblck
As far as I understand you problem, you have two matrices. Let’s name them m = [N, N] and x = [batch_size, N, N, F]. Somewhere in m are zeros and you would like to get the indices. Using these indices you would like to set all matrices in x for each batch and each F to zero. Is this the right und…
dohwan.lee
I think there is no difference between BCEWithLogitsLoss and MultiLabelSoftMarginLoss.BCEWithLogitsLoss = One Sigmoid Layer + BCELoss (solved numerically unstable problem)MultiLabelSoftMargin’s fomula is also same with BCEWithLogitsLoss.One difference is BCEWithLogitsLoss has a ‘weight’ parameter, MultiLabelSoftMarginL...
ptrblck
You are right. Both loss functions seem to return the same loss values: x = Variable(torch.randn(10, 3)) y = Variable(torch.FloatTensor(10, 3).random_(2)) # double the loss for class 1 class_weight = torch.FloatTensor([1.0, 2.0, 1.0]) # double the loss for last sample element_weight = torch.FloatT…
Martin_Matas
Hello, I’m starting with torch and I don’t know how to add another number to Tensor.For examle, I have FloatTensorxand I would like to add Tensorzat the end of it and get something like tensory.Screenshot_2018-03-14_12-07-15386×673 6.91 KBIs that possible? Thanks a lot and sorry for my English
ptrblck
You could try torch.cat: x = torch.ones(2, 3, 8) z = (torch.ones(6) * 5).view(2, 3, 1) # or this z = torch.ones(2, 3, 1) * 5 y = torch.cat((x, z), dim=2)
tjoseph
Given a tensor of size 4x5x100 (rows x cols x k) I want select a different column for each rows resulting in a 4x100 tensor.For example for row 0 I want to chose column 2, for row 1 I want to chose column 4, for row 2 I want to chose column 0 and so on!Is there a single operation in Pytorch which takes a tensor and the...
ptrblck
A bit ugly, but for now this should work: a = torch.randn(4, 5, 100) indices = torch.LongTensor([2, 4, 0, 1]) torch.gather(a, 1, indices.view(-1, 1).unsqueeze(2).repeat(1, 1, 100))
Sohrab_Salimian
hello,so im trying to visualize the ouput of my spatial transformer component and when i try to apply a transpose to the output of the stn which is of shape (1, 50, 22, 22) by applying a transpose of (1,2,0) i get an axes dont match error. im trying to follow this demo:http://pytorch.org/tutorials/intermediate/spatial_...
ptrblck
You could visualize each “slice” of the activation volume coming from the convolution. I created a small code snippet: def show_activation_volume(grid): grid_arr = grid.numpy().transpose(1, 2, 0) grid_arr -= grid_arr.min() grid_arr /= grid_arr.max() plt.imshow(grid_arr) x = Vari…
Shani_Gamrian
How to normalize a vector so all it’s values would be between 0 and 1 ([0,1])?
ptrblck
Broadcasting wasn’t available in version 0.1.12. You could try: tensor_vec = tensor_vec / tensor_vec.sum(0).expand_as(tensor_vec)
ankitvad
I have a model in which the Loss is maximizing the Entropy(not cross-entropy) of the output. ie. I’m trying to minimize the negative Entropy.H = - sum(p(x).log(p(x)))Let’s say:def HLoss(res): S = nn.Softmax(dim = 1) LS = nn.LogSoftmax(dim = 1) b = S(res) * LS(res) b = torch.mean(b,1) b = torch.sum(b) return b ...
ptrblck
I think it’s just a matter of taste and apparently I like the Module class, since it looks “clean” to me. All parameters are defined in the __init__ while the forward method just applies the desired behavior. Using a function would work as well of course, since my Module is stateless. If you would …
WangWenshan
Hi all,I have a question that how to extract the probability of specific class from the softmax output?Given specific class labels, how can we extract the probability ?Thanks.
ptrblck
You could use torch.gather for this: output = Variable(torch.randn(10, 3)) prob = F.softmax(output, dim=1) classes = Variable(torch.LongTensor(10, 1).random_(0, 3)) class_prob = torch.gather(prob, 1, classes)
Chong_Toby
Hello, I was trying to get the total pixel count for an image tensor.The only solution I found is torch.Tensor(np.prod(tensor.size())) which isn’t as elegant as I would like it to be.Is there somewhere in the documentary I overlook that contains a way to directly return the value? If not, will it be useful if I make a ...
ptrblck
Try tensor.nelement().
juliohm
Hi,I am new to PyTorch, and I am enjoying it so much, thanks for this project!I have a question. Suppose I have an image of reduced size obtained through multiple layers of convolution and max-pooling. I need to down sample this image to the original size, and was wondering what are your recommendations for doing that?...
ptrblck
I suppose you would like to upsample your image to the original size. If so, you could use ConvTranspose2d or Resize from torchvision. There are mixed results with both approaches. I think the original UNet implementation used ConvTranspose2d.
alwynmathew
In numpy,*operator is element wise multiplication (similar to the Hadamard product for arrays of the same dimension), not matrix multiply as perthis.When I used*operation with twotorch.cuda.FloatTensorAandB, resultstorch.cuda.FloatTensorC>>> A.size() (131072, 3) >>> B.size() (131072, 1) >>> C = A * B >>> C.size() (13...
ptrblck
PyTorch supports numpy’s broadcasting. Have a look atthis explanation. Numpy should show the same behavior: a = np.random.randn(10, 3) b = np.random.randn(10, 1) c = a * b print(c.shape) >> (10, 3)
soshishimada
I am currently implementing residual connection on my architecture. I found codes that use .clone() at a junction. But, will I have a problem if I don’t use .clone() for skip connection?This is the simplified code of my model.def forward(self, input): out = self.conv1(input) out = self.BatchNorm1(out) out ...
ptrblck
When you are assigning a Tensor to another, they will share the underlying data. Using .clone assigns the data to the new Tensor. Example: a = torch.zeros(10) b = a c = a.clone() a[0] = 1 print(a) print(b) print(c) Probably in the code you’ve seen, they will manipulate X later on and wish to kee…
ssh983
Right now, most of the examples just give out image, lables based upon the folder sturcture. How do i write a dataloader/dataset, such that i can use it for a network that take input image and outputs image?
ptrblck
You could create your own Dataset like this: class MyDataset(Dataset): def __init__(self, data_paths): self.paths = data_paths def __getitem(self, index): image, target_image = load_images(self.paths[index]) # load as np.array or PIL.Image # transform your images h…
michaelborck
I get you can’t keep supporting older GPUs, so this is not a complaint, just seeing if there is a way to explore torch.cuda() functionality.I am on a Mac with a GeForce GT 750M which is of CUDA capability 3.0. (Driver CUDA 9.1, cuDNN 7, MacOSX10.13.sdk). I managed to fumble through and compiled torch-0.4.0x, cmake out...
ptrblck
Might be a stupid question, but Is it working?This threadsuggests to ignore the warning as far as I understand.
soshishimada
I want to apply gaussian filter on output of the network for smoothing purpose.Is there a function for that?
ptrblck
You could use the functional API with your custom weights: # Create gaussian kernels kernel = Variable(torch.FloatTensor([[[0.006, 0.061, 0.242, 0.383, 0.242, 0.061, 0.006]]])) # Create input x = Variable(torch.randn(1, 1, 100)) # Apply smoothing x_smooth = F.conv1d(x, kernel)
mohamadal
I have an unbalanced image dataset with the positive class being 1/10 of the entire dataset. Classification models trained on this dataset tend to be biased toward the majority class (small false negative rate and bigger false positive rate). I would like to do some augmentation only on the minority class to deal with ...
ptrblck
You are correct regarding the transformation. The transformation will be applied on the fly on your minority class data. You are also correct regarding the WeightedRandomSampler, if you are keeping the default replacement=True argument.
ptrblck
Could you post your network definition, so that I could run it on my machine please?EDIT: I will just use your snippet from the first post and assume it’s the complete network.
ptrblck
Yes, weight initialization is one crucial step in training a network from scratch. PyTorch has a lot of differentinit functions. E.g. one popular method for conv layers is xavier_uniform. Depending on your architecture, different weight inits might speed up training of even make it possible. Hav…
AreTor
Does exist a PyTorch function to generate a tensor with constant values? In NumPy I would callnp.full.So far, I have used:constant = 3.0 t1 = torch.ones(3, 4) * constant
ptrblck
You can use .fill_(): t1 = torch.Tensor(3, 4).fill_(3.0)
Chieh_Wu
HelloI am not getting good results training my simple fully connected layered network. I am aware that since it is a highly non-convex function, i am probably just finding the local minimum. I have constructed my own resnet, with Kaiming initialization, and relu as activation function. In search of improving my resul...
ptrblck
You can have a look at various pre-trained models fromtorchvision.models. I think these models are pre-trained on imagenet. You are right, if you have a specific network architecture, you have to train the network yourself. At least I don’t know any obvious technique for weight transferring betw…
Ashwin_Raju
I would like to train a model where it contains 2 sub-modules. I would like to train sub-model 1 in one gpu and sub-model 2 in another gpu. How would i do in pytorch? I tried specifying cuda device separately for each sub-module but it throws an error.Error:RuntimeError: tensors are on different GPUsclass Net(nn.Module...
ptrblck
What kind of error do you get? This should work: class MyModel(nn.Module): def __init__(self, split_gpus): self.large_submodule1 = ... self.large_submodule2 = ... self.split_gpus = split_gpus if split_gpus: self.large_submodule1.cuda(0) …
christianperone
From thetorch.nn.BCELossdocumentation, it says that theweightparameter, if given, has to be a Tensor of size nbatch. However, when I use weight of size nbatch, I got the following error:The size of tensor a (200) must match the size of tensor b (36) at non-singleton dimension 3.My tensors sizes are:input = (36, 1, 200,...
ptrblck
That’s strange indeed. It seems that a call to _infer_size() in binary_cross_entropy() is throwing this error. For a workaround you could try creating the weight tensor with dims [36, 1, 1, 1].
LJ_Mason
Hi,everyoneI have a model based on vgg16 net, I want to save its layers and each layers’ parameters(except the maxpooling layers) into separate npz files. just like the pictures showed. The parameters can be used for other programmes to use and test without installing Pytorch first.if you have any ideas, plz letme kno...
ptrblck
Using nn.Sequential will give you the same dict with layer names defined as ascending numbers. Try this as a model definition and run the loop with it: model_seq = nn.Sequential( nn.Linear(1, 5), nn.ReLU(), nn.Linear(5, 1), nn.LogSigmoid() ) EDIT: Alternatively you could use an Or…
yngtodd
I am getting stuck when setting the input shape of a tensor from a linear layer to a 2D convolutional transpose layer in the decoder network of my variational autoencoder.After sampling from my encoder network, I have an input tensor of shape(1 x 8)for this decoder:class Decoder(nn.Module): def __init__(self, laten...
ptrblck
You are trying to reshape a Tensor with dim [1x8] to [1x1x16x16], which has 16*16=256 elements. Try to increase the output dimension of self.fc to 256 or reshape to e.g. [1x1x2x4], which might not work due to your kernel size of 4 in the first ConvTranspose2d.
ilmucio
I’d like to understand why this script:github.compytorch/examples/blob/master/mnist/main.pyfrom __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.autograd import Variable...
ptrblck
Well, as you can see the network architecture in Keras is quite different from the example in Pytorch. Anyway, lower the learning rate to 0.001 and you should be fine with batch_size=1.
Janinanu
I am trying to train a LSTM model in a NLP problem.I want to use learning rate decay with the torch.optim.lr_scheduler.ExponentialLR class, yet I seem to fail to use it correctly.My code:optimizer = torch.optim.Adam(dual_encoder.parameters(), lr = 0.001)scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gam...
ptrblck
You should add optimizer.step() into your training loop and move scheduler.step() into the epoch loop.
lesscomfortable
Hi!I need to create a 2-layer convolutional net that takes as input a 3-224-224 image, uses 50 kernels of 33, 50 kernels of 44 and 50 kernels of 5*5 in each layer to perform convolutions and then returns an image.Can someone help me with an example of this? I tried the following code with a batch size of 16 but the ou...
ptrblck
Remove out = out.view(out.size(0), -1) from your forward method amd you will get an output shape of [batch, 3, 218, 218]. .view works like reshape in numpy. So basically you are flattening your output, which gives [batch, 3*218*218=142572]. If you need the same width and height (224) in your outpu…
Pablo
Hello everyone.I just configured my GPU and I was trying to use Pytorch with CUDA.I am facing quite a simple error I think.I run:import torcha = torch.randn(10).cuda()and i get:Traceback (most recent call last):File “<stdin>”, line 1, in <module>File “/home/pablo/.local/lib/python2.7/site-packages/torch/_utils.py”, lin...
ptrblck
Yeah, you are right. Apparently I was looking at the 710m. Since Pytorch needs compute capability >=3.0, you should be fine. What does torch.cuda.is_available() return? Have you tried to reinstall Pytorch?
Zen
Hello,After an update, some parts of my code don’t work anymore.I have a tensor X of size 64 * 1 * 3 * 3 and a tensor Y of size 1 * 3 * 3, and I want to make the coeff-wise multiplication Z = X * Y. It would be equivalent to:Z = X.new().resize_as_(X) for i in range(64): Z[i] = X[i] * YIs the solutionZ = X * Y.unsqu...
ptrblck
Ah ok, broadcasting was introduced in version 0.2. Try to update Pytorch to version 0.3. Just select your config and follow the instructionshere.
jharo
Hi all,I’m quite new to Pytorch and i’d like to find an example ofFaster R-CNNthat can run on a simpleCPU. I’ve found several examples in GitHub but i don’t know if running them on a CPU will be very complicated. Has anyone tried? Any kind of guide would be appreciated.Thanks in advance for your help!!
ptrblck
Just get rid of all .cuda() calls and run the script. This prevents moving the model or tensors onto a GPU. Often there are optional arguments for the main script where you can specify using a GPU or not. EDIT:This codeuses an argument for GPU usage. (Haven’t tried it myself)
chenchr
Hello. I need to pad a tensor in the forward of a function. On the doc website I can’t find function that can pad a tensor…
ptrblck
You could useF.padfrom nn.functional: a = torch.randn(1, 3, 6, 8) p2d = (1, 1, 2, 2) # pad last dim by (1, 1) and 2nd to last by (2, 2) F.pad(a, p2d, 'constant', 0) >> [torch.FloatTensor of size 1x3x10x10]
soshishimada
I’d like to reconstruct 3D object from 2D images.For that, I try to use convolutional auto encoder. However, in which layer should I lift the dimensionality?I wrote a code below, however, it shows an error “RuntimeError: invalid argument 2: size ‘[1 x 1156 x 1156]’ is invalid for input of with 2312 elements at pytorch-...
ptrblck
You are trying to reshape your fc1 output of size 2312 to (1, 1156, 1156) which is 1156*1156=1336336. You could try to change the linear output to self.fc1 = nn.Linear(2312, 1024) and corresponding to this in the forward pass out = out.view(out.size(0), 1, 32, 32).
YingdiZhang
when I run this code,I want to see the creator attribute of y,while gives me an error of: AttributeError: ‘Variable’ object has no attribute 'creator’how to resolve it?import torchfrom torch.autograd import Variablex = Variable(torch.ones(2, 2), requires_grad=True)y = x + 2print(y)print(y.creator)
ptrblck
I think .creator was replaced with .grad_fn in May as can be seen here:https://github.com/pytorch/tutorials/pull/91/files
jdhao
Hi, I contruct my own dataset according to the data loading tutorial and using the standard Dataloader provide by PyTorch. The code is like this,train_set = MyDataset(some_parameter...) train_loader = Dataloader(dataset=train_set, other_setting...) for batch_idx , data, target in enumerate(train_loader): #trainin...
ptrblck
The DataLoader seems to use a reference to the Dataset object, so that your regenerate should work. Here is a small sample code, which works fine for me: class MyDataset(Dataset): def __init__(self, data): self.data = data def __getitem__(self, index): return self.data[ind…
mattrobin
What’s the appropriate way to keep a constant that’s part of a module on the correct device. If I define a constantVariablefor use in a module, calling the module’scuda()method will not move the constant to the GPU. However, if I set the constant as aParameterthat does not require gradient, then turning off and on the ...
ptrblck
You could use register_buffer for automatic handling of your constant. class MyModule(nn.Module): def __init__(self): super(MyModule, self).__init__() self.exponent = nn.Parameter(torch.Tensor([1])) self.e = torch.Tensor([np.e]).float() self.register_buffer('e_co…
Smith_Jack
Hello. I am training my model on a single GPU (on a remote sever) and the script gets stuck and corrupts randomly without any error output. When I print the size of some tensors in the loss function, it seems that the scripts runs normally. GPT-4o says I can addtorch.cuda.synchronize()after the cuda operations and addf...
albanD
Hey! What you’re describing sounds like a machine that runs our of RAM. And so it hangs for a while trying to recover and start killing process in a hard way. Can you check that RAM usage is ok on your machine?
Areg_Petrosyan
I read abouttorch.autocastand how FP16 matrix multiplication is faster than FP32 on CUDA. However, on my Mac M1 (Intel chip), a 100x100 matrix multiplication takes 50 times longer in FP16 than FP32. Reducing the matrix size decreases the computation time, but FP32 still remains faster.I’m trying to understand howtorch....
albanD
Hey! Long story short, this is where most of the mm calls end up at on MPS device:pytorch/aten/src/ATen/native/mps/operations/LinearAlgebra.mm at 2ed4d65af0a1993c0df7b081f4088d0f3614283e · pytorch/pytorch · GitHubAnd for CPU it ends up inpytorch/aten/src/ATen/native/CPUBlas.cpp at main · pytorc…
3di
I first get a future warning telling me to set weights_only to True for security puporses, but when I do, it says I can’t use weights_only = True. I get the below error.state_dict = torch.load(path_to_state_dict, map_location="gpu",weights_only=True)torch\serialization.py", line 1096, in loadraise pickle.UnpicklingErr...
albanD
Hi, The error message here mentions: “don’t know how to restore data location of t orch.storage.UntypedStorage (tagged with gpu)” Indeed, “gpu” is not a valid device in PyTorch, I guess you meant “cuda” ?
Johannes
Hi all,I want to copy the computational graph betweennn.Parametertensors. I think the MWE below illustrates my use case in its simplest form.class Test(torch.nn.Module): def __init__(self): super().__init__() self.p = nn.Parameter(torch.tensor([1.])) t = Test() t1 = Test() t1.p = ( * ) (t1.p ** 2...
albanD
Hey! I think the simplest thing to do would be: t1.p.grad = torch.zeros_like(t1.p) t.p.grad = t1.p.grad
fgirella
Greetings,during some testing withMultiheadAttention, I requiredgradient calculation on the attention weights(or scores), but I encountered a problem.My goal was to obtain the gradients of the attention weights used during the attention operation.I have a layer of MultiheadAttention, and I perform the forward operation...
albanD
This is indeed expected I’m afraid, the result of the view is not what is part of the computation in the “main branch” and thus you don’t get any gradient for it. I’m afraid there aren’t any great options here: You can use a modified version of MHA indeed You can try and suggest upstream MHA to a…
nicaushaz
Hello,I am having trouble tracing why the model.to(‘device’) is not moving my whole model to the mps device on a M1 macbook pro.I am creating custom layer blocks to use within an encoder decoder setting as following:class Conv2dLayer(nn.Module): def __init__(self, nin, nout, kernel_size, stride_sz, pad_sz, ...
albanD
Your example above will work fine yes. Appending to the ModuleList will do what you expect. You can check that moving such a Module to mps will work fine. If you change self.network = [], the rest of the inittialization code will run fine but you’ll see that the move to mps will not work anymore.
cherry
What is the difference between pytorchF.cross entropyvstorch.nn.Cross_Entropy_Loss?As far as I understandtorch.nn.Cross_Entropy_Lossis callingF.cross entropy
albanD
Hi, There isn’t much difference for losses. The main difference between the nn.functional.xxx and the nn.Xxx is that one has a state and one does not. This means that for a linear layer for example, if you use the functional version, you will need to handle the weights yourself (including passing…
mst72
Is it possible to initialize only one layer when multiple LayerNorm layers need to be used in Pytorch? For example: self.layernorm = nn.LayerNorm() instead of writing self.layernorm1 = nn.LayerNorm() self.layernorm2 = nn.LayerNorm()And I would like to know which other ones are possible to initialize only one and which ...
albanD
Hi, ReLU and Dropout don’t have learnable parameters no. But there is no downside at defining 3 so you can do that if it is easier for you to use.
vadimkantorov
Example inCPU implementation of Conv1d seems to work non-deterministically · Issue #116369 · pytorch/pytorch · GitHub. For both cases there, conv2d kernels are usedWhat would be used for thetorch.matmulwith transposed inputs?I think in theory both should use the same gemm path accepting and producing transposed values ...
albanD
Hey! My expectation is that historically, the conv2d kernel was the most optimized of them all and so it was the simplest and overall fastest fallback. But if there are easy to identify cases where matmul is faster, then we can definitely add a branch there to call matmul instead!
hhxx
I am reading the documentation aboutjvp. I believe it is used to compute the dot product between the Jacobian and v. However, I find its behavior strange when the inputs are 2-D matrices.According to its usage:torch.autograd.functional.jvp(func, inputs, v=None), we can define the func and inputs as follows:def func(x):...
albanD
Hey! Indeed, this definition of computing a dot product only makes sense for 1D inputs. But you can also view your 2D input as a 1D input (.view(-1)), compute the jacobian vector product and then reshape again the result to be the shape of the output. In this view, the jacobian has size nb_elemen…
KFrank
Hello Forum!I tried a test where I expected to get “RuntimeError: Trying to backwardthrough the graph a second time,” but instead I get results that make nosense to me.The basic question: What should happen if you move part of the buildingof the computation graph out of the optimization loop?Here is the test script (w...
albanD
The first question is why, when .backward() is called the second time through the loop, does autograd not complain about part of the computation graph having been freed? This is because the part of the graph being shared is two ops: one indexing and one contiguous. neither of these saves any Te…
Robin_Lobel
Is there a way to know programmatically if mps is available or not ?Something similar totorch.cuda.is_available()ortorch.cuda.device_count()
albanD
Hey! Yes, you can check torch.backends.mps.is_available() to check that. There is only ever one device though, so no equivalent to device_count in the python API. This docMPS backend — PyTorch master documentationwill be updated with that detail shortly!
Ryan.L
I’m a fresher on PyTorch and I found the following code in aten/src/ATen/native/TensorFactories.cpp:254Tensor empty_cpu(IntArrayRef size, c10::optional<ScalarType> dtype_opt, c10::optional<Layout> layout_opt, c10::optional<Device> device_opt, c10::optional<bool> pin_memory_opt, c10::optional<c10::Memor...
albanD
Hey! The Tensor and TensorBase objects are pretty much the same thing. TensorBase is just a trick we use to speed up compilation by removing the dependency of the whole library (that depends on Tensor) to all the methods on Tensor. So TensorBase is the Tensor object with all the methods defined in…
pvtien96
Hi,I want to get the best model state_dict as in the following code snippet:def finetune(model, train_loader, val_loader, num_epochs, max_num_epochs, ori_acc, acc_drop_threshold): _, best_top1_acc, _ = validate(val_loader, model, criterion) best_model_state = model.state_dict() epoch = 0 while epoch < ...
albanD
Hi, The .state_dict() method does not copy the parameters but returns a view into the ones in the model. So if you want to get an independent version (that will not be updated inplace by training), you need to deepcopy it: best_model_state_dict = copy.deepcopy(model.state_dict())
Vendrick17
Hello, I am trying to implement the function below and compute its gradient usingbackward(), but I have an in-place operation that I cannot solve, below I show an option I tried and didn’t work.def modified_gram_schmidt(A): m, n = A.shape Q = torch.zeros((m, n), requires_grad=True).clone() R = torch.zeros(...
albanD
Hi, A simple solution is just to remove the inplace change into Q and only create it at the end: def modified_gram_schmidt(A): m, n = A.shape Q = [] R = torch.zeros((n, n), requires_grad=True).clone() for j in range(n): v = A[:, j].clone() for i in range(j): …
kmaeng
I want to call a function on each operator of the forward pass of my NN.So naturally, I am registering a forward hook.However, I am currently doing something like this:for name, module in net.named_modules(): module.register_forward_hook(hook_fn)and it only registers a hook for named module, e.g., Conv2d, but not f...
albanD
Hi, I am afraid these functions are at a much lower level than torch.nn and you won’t be able to use a direct hooking system. One thing you can try to do is wrap your input in a Tensor-like object and write a custom implementation that calls your hook and then delegate to the original pytorch impl…
Vinayaka_Hegde
Hi, sorry if this question was asked before…I want to make few changes to the fileutils.data.dataloader.pyandutils.data._utils.worker.py. Precisely, I want to add some log statements to both the files.I have downloaded and installed pytorch in Windows 10 usingpip3 install torch.... Now, I wanted to know :how can I edit...
albanD
hi, If you only want to change some python code, then there is a hacky way to do this by modifying directly the intall you got from pip. You can locate the file from the install by running python -c "import torch; print(torch.utils.data.dataloader.__file__)" Then if you modify this python file, i…
ringohoffman
Why is import aliasing preferred to__all__to explicitly export module variables? What is the reason for this preference? Is this documented anywhere?nn.Parameter, nn.DataParalleltorch.testing.assert_close
albanD
Another data point is the public API definition that we have:Public API definition and documentation · pytorch/pytorch Wiki · GitHubBut for these, yes we’re happy to fix them!
Siladittya_Manna
I am trying to assign a ndarray of zeros to the grad of the model parameters, but I am getting the error in the title.I was just trying to see if I can assign a numpy array to theparam.grad. But in my project I won’t be assigning zeros actually.for param in model.parameters(): #print(param.grad) ...
albanD
Note that this comes from the fact that the Tensor from numpy was on the CPU, while the param was on the GPU. Another way to solve this (without having to send the whole model back to the CPU) would be to send the new grad to the GPU as well with .to(param.device).
Balamurali_M
I have two GPUs, and I am using cuda:1 for validation. The model and dataset ran in cuda:1. But when I use the .to(‘cpu’) it uses some memory from cuda:0. Is this normal or I am doing some mistake ?
albanD
Hi, It may. You want to make sure that you set the cuda device to be 1 to avoid using the 0th one. Note that if you never want to use the other device, the best way is to set the env variable CUDA_VISIBLE_DEVICES=1 and you won’t even see the GPU 0 anymore.
ritchieng
How do you average the related variables holding the gradients?loss / len(minibatch)?
albanD
I think a simpler way to do this would be: num_epoch = 10 real_batchsize = 100 # I want to update weight every `real_batchsize` for epoch in range(num_epoch): total_loss = 0 for batch_idx, (data, target) in enumerate(train_loader): data, target = Variable(data.cuda()), Variable(tar…