user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Takumi3 | Hi. I have the problem here.Now, I am trying to get predict interval with using Monte Calro dropout.However, I got following errors when I callloss.backward()after the running of following codeI do not kown why, any reply will be appreciated.thanks.class Net(nn.Module):
def __init__(self, x1, x2, p, m, mode=0):
... | ptrblck | In your predict method you are explicitly detaching the tensors from the computation graph in:
samples_ = [self.forward(x).detach()
for _ in range(samples)]
so that the samples_ doesn’t have a valid grad_fn anymore (it’s not attached to any computation graph) and thus the backward call… |
alinak | Hi,I’m currently working on a single-GPU system with limited GPU memory where multiple torch models are offered as “services” that run in separate python processes.Ideally, I would like to be able to free the GPU memory for each model on demand without killing their respective python process. However, if I only delete ... | ptrblck | You could reduce the CUDA context size by removing kernels e.g. via dropping libraries such as MAGMA or cuDNN, if these are not used.
Besides that I’m not aware of reducing the operator set in the framework itself. |
Mert_Dunver | Hello in our project we are trying to implement several fixed filtersto each convolutional layer.image_2022-01-26_153425951×662 31.4 KBAs shown in the code we have two filters that we want to add to each layer but weren’t able to grasp how we add these filters. If you could show us a way to do so we would be very grate... | ptrblck | You are creating the weight tensor as a LongTensor, so either call .float() on it or use floating point values via:
with torch.no_grad():
conv.weight = nn.Parameter(torch.tensor([[[[1., -1.],
[-1., 1.]]]])) |
degenerateml | I’m trying to convert a TensorFlow-Keras model to PyTorch, and encountered the following error:Traceback (most recent call last):
File "model.py", line 480, in <module>
train_loop(model, device, train_dataloader, val_dataloader, optimizer, scheduler, model_name, epochs)
File "model.py", line 164, in train_loop
outputs ... | ptrblck | I guess the “reduction” in the temporal dimension is missing in your model or alternatively you could only use the last time step from the LSTM output. Currently your model is returning logits for a sequence, which doesn’t fit the target. |
Mona_Jalal | I am doing binary classification with a batch size of 8 and the output of my model is:out shape is: torch.Size([8, 2])
out is: tensor([[-1.2086, 0.8501],
[-0.8705, -0.2427],
[-1.0448, 0.5410],
[-1.2318, 0.2670],
[-1.0920, 0.0126],
[-0.9867, 0.1056],
[-1.2848, 0.97... | ptrblck | Your train_loss seems to be a plain float (i.e. not a tensor) so make sure you are calling backward on the actual loss tensor not the Python float scalar. |
Oussama_Bouldjedri | I am working on a json dataset, I manege to get the data into this shape :[[[…],label 1],[[…].label2],…]but I still cannot iterate tghough the data set this is my custum data set:class JsonDataset(IterableDataset):definit(self, files):super(JsonDataset).init()self.files = filesself.data_full_list=[]
for i in range(... | ptrblck | Your code snippet seems to have a typo in __len__(self) (note the two underscores while your code uses single underscores). |
Anshumaan_Dash | I can find just a docstring when I go totorch.nn.functional.pixel_shuffle. Where can I find the actual implementation?github.compytorch/pytorch/blob/master/torch/nn/modules/pixelshuffle.pyfrom .module import Module
from .. import functional as F
from torch import Tensor
class PixelShuffle(Module):
r"""Rearranges... | ptrblck | You won’t be able to locally change a C++ source file and see the changes without rebuilding it.
To apply changes to the PixelShuffle implementation, usethis guideto build PyTorch from source, manipulate the file, and rebuild it.This Contributing READMEmight also be useful for incremental buil… |
bbharland | I would like to know the correct way to write a module that will avoidRuntimeError: Expected all tensors to be on the same device. (I am using torch.jit.script if this is important)I recently asked a related question about the .to(device) function and was helpfully told that “valid members for this operation is other ... | ptrblck | I think this use case should be possible if you make sure the shapes are as expected.
Here is a small example, which concatenates a new tensor to the internal buffer and checks that it’s also added to the state_dict:
class MyModel(nn.Module):
def __init__(self):
super().__init__()
… |
kmkurn | Hi,Is there a reason why the default value ofset_to_noneinAdam.zero_grad()isn’t changed toTrue? The current default results in parameter update even though they aren’t used to compute the loss. I suppose this also holds true for other similar optimisers. Setting it toTrueseems like what you would expect, no? | ptrblck | I think the set_to_none attribute is set to False by default for backward compatibility reasons.
Note that it’s a performance improvement (avoiding an accumulation kernel to add the new gradients to zeroes) and wasn’t introduces to dodge the side effect of parameter updates with a zero gradient for… |
Alexander_Pollack | Hello!I am running Windows 10, with python 3.7.9, with pip 21.3.1, and CUDA 10.1 installed. I’ve had pytorch installed on this machine before but am having to reinstall after some changes were made. I previously had no issues, but now when I try to install as before, torch can only be installed with cpu backing. I am t... | ptrblck | You might be hitting a connection issue as describedherewith some workarounds. Could you check, if e.g. specifying a proxy would work? |
pasindu | I’m trying to swap resNet blocks with resNext blocks in my current model. All worked and I even trained the model for 1000+ epochs with the resNet blocks but when I added the following class to the model, it returned this error. (ran without errors in my local CPU but got the error when running in colab)Added Class :cl... | ptrblck | You are currently appending the new nn.Conv1d layers to a plain Python list in self.conv_list, which will not properly register them.
Use nn.ModuleList instead and it should work. |
Abir_ELTAIEF | Please, I need help to run my model and I am stuck!I try here to train a Siamese BERT model, using a particular dataset (that I transformed in dataloader…)But I got this error (the GPU is : ‘Tesla P100-PCIE-16GB’)RuntimeError Traceback (most recent call last)/tmp/ipykernel_34/2427691835.py ... | ptrblck | The indexing error is raised in:
return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
so check the min and max values of input and make sure they match the weight dimension, i.e. the input should contain values in [0, num_embeddings-1].
Here is an example of a working an… |
Mona_Jalal | I am trying to run the cats and dogs example for vision transformer by lucidrain but the following Webpage from PyTorch doesn’t exist anymore. What is the link I should use for retrieving the train.zip and test.zip files?https://pytorch.org/docs/stable/torchvision/datasets.htmlScreen Shot 2022-01-21 at 5.09.43 PM1274×7... | ptrblck | The datasets docs can be found here:torchvision.datasets — Torchvision 0.11.0 documentationYou can generally use the search in the docs to check if pages were moved. |
AlexandreBrown | Hello,I’d like your opinion on some approaches for applying preprocessing to images for deep learning (eg: semantic segmentation).Important note :Take for account that this would be performed in a pipeline therefore every new training would re-apply this (consider the disk to be emptied between training for instance). ... | ptrblck | This sounds like a valid approach, as the data augmentation is applied on each sample during training and could potentially save some preprocessing time. In any case I would profile the image decoding (e.g. JPEG decoding) vs. loading the raw binary data (speed and file size). E.g. loading a 1200x1… |
NullPointer | I perform a Fourier transform with my data and then feed it into the network, but I get type mismatches. I believe that this is whycomplexPyTorchstill exists, but I was wondering if there is a way to pass a complex tensor into a model without getting a type error. Any example (related to a GRU if possible) that could b... | ptrblck | Complex modules are not fully supported yet and you could thus try if the modules you want to use would already work. E.g. GRU seems to work on the CPU already:
rnn = nn.GRU(10, 20, 2).to(torch.complex64)
input = torch.randn(5, 3, 10).to(torch.complex64)
h0 = torch.randn(2, 3, 20).to(torch.complex6… |
RuiZhangJerry | Hi, I want to know how to implement the LBFGS optimization in libtorch? | ptrblck | This testmight be helpful as a template. |
pzemp1 | I am getting this error, when usingnn.CrossEntropyLoss()def train(model, device, train_loader, optimizer, epoch, batchSize, test_loader, ValidationPrice):
model.train() # When you call train(), tensor function
total_loss = 0
total_classification = 0
total_correct = 0
for batch_idx, (data, target) i... | ptrblck | Most likely the shape of the targets for nn.CrossEntropyLoss is wrong.
Check thedocsand the expected shape of the input and target. E.g. if you are passing class indices, make sure that the target contains the class indices (not one-hot encoded) as a LongTensor and thus does not use a “channel/cl… |
blade | I am trying to combine twoParameterLists in Pytorch. I’ve implemented the following snippet:import torch
list = nn.ParameterList()
for i in sub_list_1:
list.append(i)
for i in sub_list_2:
list.append(i)Is there any functions that takes care of this without a need to loop over each list? | ptrblck | You could unwrap the sub lists and pass their content to nn.ParameterList as seen here:
sub_list_1 = nn.ParameterList([nn.Parameter(torch.ones(1))])
sub_list_2 = nn.ParameterList([nn.Parameter(torch.ones(1) * 2)])
param_list = nn.ParameterList([*sub_list_1, *sub_list_2])
sub_list_1 = [nn.Parameter… |
blade | I have a tensor of N unique target labels, randomly selected from [0,R], where N<R. I would like to transform the labels to [0,N]. Is there a function available for this target transform? e.g. input vector: [12, 6, 4, 5, 3, 12, 4] → transformed vector : [4, 3, 1, 2, 0, 4, 1] | ptrblck | unique with return_inverse=True would yield the desired result:
x = torch.tensor([12, 6, 4, 5, 3, 12, 4])
x.unique(return_inverse=True)
# > (tensor([ 3, 4, 5, 6, 12]), tensor([4, 3, 1, 2, 0, 4, 1])) |
hankyul | Question: How to reduce latency(computational cost) inConvTranspose2d?I compared latency betweennn.Conv2d,Upsample(mode=nearest),ConvTranspose2d,Upsample(mode=bilinear)in different batch size. It looks like deconvolution operation takes a lot of time in large batch (=64). Is there a way to reduce computation time for d... | ptrblck | You could add torch.backends.cudnn.benchmark = True to let cuDNN profile different kernels and select the fastest one and use to(memory_format=torch.channels_last) since you are using amp, which could give another speedup if permutations are avoided. |
CDhere | Hi! I have some basic questions regarding versions of CUDA,cudatoolkit, and the driver:When selecting “Compute platform” when installing pytorch from thePytorch website, or choosing the docker image fromPytorch official page on Docker Hub, does it mean the CUDA version pytorch is pre-built with, or the version the targ... | ptrblck | The pip wheels and conda binaries ship with their own CUDA runtime (as specified during the installation), so you would only need a corresponding NVIDIA driver to run your code. Your local CUDA toolkit will be used if you are building PyTorch from source or a custom CUDA extension.
The docker ima… |
LeanderK | I have the following problem: I have a bunch of parameters that I need to project into a the valid parameter space. I can only efficiently compute the valid parameter-space during the forward-pass (it changes with the parameters).So I have computations like this:lower_bound, upper_bound = compute_bound(input)
param[par... | ptrblck | I think your use case should work if you wrap the inplace manipulations of param into a with torch.no_grad() guard as seen here:
import torch
import torch.nn as nn
import torch.nn.functional as F
lower_bound, upper_bound = 0., 1.
param = nn.Parameter(torch.randn(10, 10) * 10.)
optimizer = torch.op… |
Dhruv_Jain | Hi,I am trying to use a pretrained model of resnet3d on my gpu. But somehow it is getting reversed. I am not sure how this is possible. I am usingself.resnet3d = torch.hub.load('facebookresearch/pytorchvideo', 'slow_r50', pretrained=True)And I am getting,Net((blocks): ModuleList((0): ResNetBasicStem((pool): MaxPool3d(k... | ptrblck | The order of execution is defined in the forward method of each module while printing the model should print the modules in the order of their initialization (at least that’s what I’ve seen so far).
Are you seeing the forward pass “reversed” or just the printing of the submodules? |
ElQadasi | I have this code and I spent a lot of time figuring out why the size is still the same [28,28]:class FashionDataset(Dataset):
def __init__(self,dataset_dir,train_option,transform=None):
self.dataset = datasets.FashionMNIST(root=dataset_dir,
train=train_option,
... | ptrblck | Your code works as expected:
idx, x, y = next(iter(train_loader))
print(x.shape)
# > torch.Size([10, 1, 224, 224])
idx, x, y = next(iter(test_loader))
print(x.shape)
# > torch.Size([10, 1, 224, 224]) |
wassimseif | Hello,I am trying to find a way to add layers to a model after without changing the definition of the modelFor example let’s say i have this layer that I want to add after everyReLUlayer i have in aResNetclass SimpleCustomLayer(nn.Module):
def __init__(self):
pass
def forward(self,x):
log_tenso... | ptrblck | I’ve assumed that your custom layer would have parameters, but you are right that it would work if that’s not the case. |
Arham_Khan | I am using a boolean tensor to index another tensor. I am building a very basic Deep Q Learning model with experience replay, the below code is meant to NOT the mask denoting which state transitions are terminal, using this to index the state value estimates tensor and place the needed values there.In the end the tenso... | ptrblck | The shapes are also [32] in my example, but the number of True values in idx is 31.
Indexing x with 31 True values will return a tensor of the shape [31]:
x = torch.randn(32)
idx = torch.ones(32).bool()
idx[0] = False
print(x[idx].shape)
# > torch.Size([31])
which will then create the error since… |
t326wang | Hi all,Here are the piece of code when I try to load a gpu-trained model to cpu (and want to use CPU for evaluation):model_conv.load_state_dict(torch.load(model_file, map_location='cpu'))
model_conv = model_conv.cpu()and the error message is:Traceback (most recent call last):
File "prediction.py", line 269, in <modul... | ptrblck | PyTorch 0.1.12_1 is one of the earliest releases, so I would strongly recommend to update to the latest stable release (1.5.1).
In 0.1.12, you had to pass a function to map_location via:
torch.load(..., map_location=lambda storage, location: 'cpu') |
HallerPatrick | Hello,I am a little confused by what a Loss function produces.I was looking at this post:Multi Label Classification in pytorch - #45 by ptrblckAnd tried to recreate it to understand the loss value calculated. So I constructed a perfect output for a given target:from torch.nn.modules.loss import BCEWithLogitsLoss
loss_... | ptrblck | nn.BCEWithLogitsLoss expects logits which are unbound and have values in [-Inf, +inf] and can be seen as “unnormalized” probabilities (I’m sure@tomor@KFrankcan give you a proper mathematical definition), so your output_tensor won’t match the targets perfectly. Since your output contains probabil… |
dhsusf | I’ve been running into this problems for days with the Pytorch Forcasting package.Running this code:for idx in range(10): # plot 10 examplesbest_tft.plot_prediction(x, raw_predictions, idx=idx, add_loss_to_title=True);I get this message:/usr/local/lib/python3.7/dist-packages/pytorch_forecasting/models/temporal_fusion_... | ptrblck | Based on the error message the indexing operation is failing in once of these tensors:
encoder_target[idx]
# or
decoder_target[idx]
make sure the size of the tensors in dim0 is sufficiently large for the index. |
denexo | I was wondering how the convolution operation is implemented for a batch of N images, i.e. for a tensor of shape (N, C, H, W). Is it fully vectorized or is there a for-loop over N images? Also, if we have more filters than one, does it use one additional for-loop over the filters? | ptrblck | im2col can be applied via unfold. There should be no loops in the matrix multiplication and the unfolding should be implicit for performance reasons.
The usage of loops might slow down the execution in a lot of use cases, but there might be use cases, where it would make sense to use a loop instead… |
genjiii | Let’s say I have a tensor a = torch.tensor(([0,1,2],[3,4,5])). I have another tensor, b = torch.tensor([0,1]), that I want to use to index a, such that we obtain the 0th position of the first row, 1st position of the second row (resulting tensor is [0, 3]). How can this be done? It’s not the same as index_select, which... | ptrblck | Wouldn’t the result be [0, 4] in this case?
If so, this should work:
a = torch.tensor(([0,1,2],[3,4,5]))
idx = torch.tensor([0, 1])
a[torch.arange(a.size(0)), idx]
# > tensor([0, 4]) |
Angry_potato | Hello all,I am currently working on a kaggle competition for which I have to finetune an efficientnet model.I have a finetuned efficientnet model which loaded from torch hub and saved it usingtorch.save. But when I usetorch.loadto load the model and weights in a different notebook there is aModuleNotFoundErrorsaying'Py... | ptrblck | I’m not sure I understand the question correctly.
You could initialize a model with random parameters via your code snippet or generally as:
model = MyModel()
where MyModel is the model class. Afterwards, you could load the state_dict via model.load_state_dict(state_dict).
The difference between… |
tree33 | Hi, I’m using another third-party code where the authors define a input x as nn.Parameter and computes the grad himself (without using loss.backward() for sparsity). So the code looks likex = nn.Parameter(..., requires_grad=True)
# then come custom ops
# not loss.backward() here
sparse_grad()
optim = optim.RMSprop([x])... | ptrblck | Yes, this should work as seen here:
x = nn.Parameter(torch.randn(2, 2))
y = x**2
y.backward(torch.ones_like(y) * 2)
print(x.grad)
print(2*x*2) |
arya47 | Does pytorch have a implementation of TV??Thanks | ptrblck | I don’t think there is a built-in total_variation method in torchvision, but based on theTF implementatioyou could use try to use the same approach as it looks quite simple. |
fnak | I have a pth model that I have trained and saved.I load the model and run it on a test dataset with the following code:for i, (image, label) in enumerate(dataloader):
with torch.no_grad():
output, min_distances = model(input)On one machine, the model works perfectly, getting around 97% correct predictio... | ptrblck | The majority of layers are not depending on the batch size besides e.g. normalization layers, which calculate the batch stats and normalize the input activation with them during training. If you are using e.g. batchnorm layers, call model.eval() before evaluating your model to use the running stats … |
henrikgruner | HiDoes anybody have a way to go back from flattening all the weights and putting them into a numpy vector (as done in the code snippet below). I trained the network for 3 days, before my allotted time expired, causing the program to cancel before converging. I have the checkpoints saved as numpy vectors. The model arch... | ptrblck | Yes, manually unwrapping the data should work. Something like this might help:
# flatten
gg = []
for name, weight in network.named_parameters():
gg.extend(weight.cpu().detach().numpy().flatten())
# restore
sd = {}
i = 0
for name, weight in network.named_parameters():
param_len = weight… |
lpreuett | I am working on porting an effective model from TensorFlow to PyTorch but have been unable to get the network to learn effectively in PyTorch. I suspect there is a simple misunderstanding on my end of how PyTorch operates. I have been working on this port too long now and am finally willing to admit I could use a littl... | ptrblck | I don’t know what might be causing the issue as I’m able to overfit random data using your model and this code:
N = 64
data = torch.randn(N, 10, 1)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = Discriminator(hidden_size=32, target_seq_len=1, num_classes=5)
optimizer… |
rmd | Hi, so I’ve been working on a model that uses a few different components and when benchmarking found some bizarre inconsistencies with the performance of the various models.All models are just basic ConvNets with BatchNorm and ReLU layers.Specs:RTX 3090CUDA 11.4PyTorch 1.10.0cuDNN 8.2.0The initial setup looks somewhat ... | ptrblck | CUDA operations are executed asynchronously so to you would need to synchronize the code via torch.cuda.synchronize() before starting and stopping the timers.
Otherwise you would profile the kernel launches, will see accumulated times in blocking operations etc., which seems to be the case here. |
Haziq_Muhammad | GPU utilisation is low but memory is usage high. This is my code:from tqdm import tqdm
import torchvision.transforms as transforms
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.datasets import CIFAR100
import torch.nn as nn
from torch.functional import split
import torch
import ss... | ptrblck | I would recommend to check out theperformance guide, which would point to towards using e.g. torch.backends.cudnn.benchmark = True and to e.g. avoid synchronizations via item() calls. |
lattice | When training with random data, the loss and model parameters do not change in the for loop.So, the accuracy is always the same. What’s wrong with my code? Thank you for checking it out.random dataimport torch
X_train = torch.randn(10000, 20, 4)
y_train = (torch.rand(10000) > 0.5).float()
X_test = torch.randn(2000, 2... | ptrblck | nn.BCEWithLogitsLoss expects logits, which can be interpreted as unnormalized probabilities. In your current model you are using F.relu as the last non-linearity, which I would remove to allow positive as well as negative logits. Once this is done, use a default cutoff of 0.0 to get the predicted cl… |
fried-chicken | I have a Dataset named unlabeled_set and a corresponding DataLoader named unlabeled_loader. To get batched data, I know that I can do the following on DataLoader.unlabeled_loader = DataLoader(unlabeled_set, batch_size=batch_size, shuffle=True)
for img,_ in tqdm(unlabeled_loader):
out=model(img.to(device))which run... | ptrblck | in = torch.cat((in, ...)) will slow down your code as you are concatenating to the same tensor in each iteration. Append to data to a list and create the tensor after all samples of the current batch were already appended to it. |
Sang_Dinh | I shortly will describe my project:+2 input for 2 networks: image(3x256x256) & 20 features(1 tensor of 20 number)+Stacking ensemble.moreThis is my model:class MetaMelanoma(nn.Module):
def __init__(self,out_dim=9,n_meta_features=0,n_meta_dim=[512, 128]):
super(MetaMelanoma,self).__init__()
se... | ptrblck | apex.amp is deprecated so use the native mixed-precision training utility via torch.cuda.amp. You can find the exampleshere. |
Omar_AlSuwaidi | I’ve been playing around with the autograd engine, attempting to “manually” update a network’s parameters via the autograd mechanism, replicating SGD. However, in doing so, I’ve got different results compared to the automatic/conventional way of updating a network’s parameters (using opt.step()). I’ve had the following... | ptrblck | If the parameters are equal but the results still differ, your input data is either not the same or your model is applying some random operations (e.g. dropout) which can be disabled via calling model.eval(). |
Arta_A | Hi, I have implemented an actor-critic method with linear networks on both actor and critic also I am using a custom function for loss calculation which is loss function used in PPO. The reward function of environment is different from the loss function of networks.This is the loss calculation:dist = self.actor(states)... | ptrblck | Yes, calling total_loss.backward() looks correct. I don’t know if the implemented training logic fits your use case, as I’m not familiar with it.
Yes, as long as no tensors are (accidentally) detached. To verify it, check the .grad attributes of the parameters of both models before and after th… |
smrolfe | Hello,I am interested in using PyTorch with@MONAIto segment multiple organs in fetal mouse scans. I’m a beginner and started by following the tutorial 3DMulti-organ Segmentation with UNETR. I have this working on my system with the provided sample data.Now I’d like to try adapting the example to my own data, with 50 la... | ptrblck | Yes, this would create an indexing error.
Also note that you are apparently dealing with 52 labels, which doesn’t fit the model output shape.
In any case remap the target indices to the expected range in [0, nb_classes-1]. |
887574002 | Hi, I am trying to use the model.half() to get rid of out of memory error. So, first I want to check it for a simple model and then try it for a complex model.In the following example, I am usingmodel.half()for a simple CNN and MNIST dataset. I think I did all thing correctly, but I gotNanfor loss.I am wondering if you... | ptrblck | Calling model.half() manually can easily yield NaN and Inf outputs, as some internal values can overflow.
We recommend to use automatic mixed precision training as describedhere, which takes care of these issues for you.
To use amp you would have to install the nightly binary or build from master… |
LeErnst | Hello together,firstly enjoy the christmas holidays. Secondly i have a question regarding the torch functiontorch.index_put. As an input it receivesindices(tuple of LongTensor) and i am wondering whether this function is supported on the GPU or does it move all the involved data to the RAM and use the CPU. I think atup... | ptrblck | Yes, index_put is available on the GPU and the data from the passed Python types is extracted.
The CUDA implementation calls index_put)impl_ and dispatches toindex_put_with_sort_stubif accumulate=True or deterministic algorithms are selected, which then callsindex_put_with_sort_kernel. |
Lady_Hangaku | For an encoder decoder task, I want to get every first element in the whole batch to feed it into the decoder (first element of every document is always the tag).Let’s say I have this output tensor:tensor([[ 1, 1870, 1871, ..., 0, 0, 0],
[ 1, 1159, 1160, ..., 0, 0, 0],
[ 1, 11... | ptrblck | Your approach would work but alternatively you could also use target_tensor[:, 0]. |
ingu_jeong | Hi, all.I have some questions about the torch.nn.functional.batch_norm.I train the model, extract the model’s values with state_dict(), and then proceed with inference using the torch function based on it.However, the value of the model implemented as a function by myself is different from the value in the original m... | ptrblck | I don’t think you can directly compare F.conv2d with BinarizeConv2d as it’s not a plain nn.Conv2d layer, but “binarizes” the data and parameters by manipulating their .data attribute as seenhere:
class BinarizeConv2d(nn.Conv2d):
def __init__(self, *kargs, **kwargs):
super(BinarizeConv… |
Ajay-Meena-IITBombay | I have a Transformer model, where I have declared an additional module of patch_embedding(let’s call this patch_embedding_2) ininit() of the model. The surprising thing I observe is even when not using patch_embedding_2 during forward pass, the training loss is different compared to when not declaring patch_embedding_2... | ptrblck | Yes, this should be the case since the module would not influence the calculation of other layers.
That’s not entirely the case, since your unused module could call into the pseudorandom number generator to initialize its parameters, which will thus change the other calls and will not yield the e… |
sleepyo | Hi, I am currently learning PyTorch. Following some tutorials, I have learned to do some little augmentation using PyTorch and albumentation.But somehow the augmentation that I’ve done only augments each image once.If I want to randomly augment to add two more data for each image (maybe rotate then crop randomly), How ... | ptrblck | Based on your code each image will be randomly augmented in the epoch.
If you want to return the same image using different augmentations (and thus increase the number of samples in the epoch) you could just call self.aug multiple times and return all augmented images. |
gkrisp9 | I am working with the OAI MRI dataset for knee osteoarthritis classification. Each one of 435 MRIs I got has to be classified to a grade. For each MRI in a folder, there are 160 2D images. I created this function to read the dataset:def dicom2array(path):
dicom = pydicom.read_file(path)
data = dicom.pixel_array
d... | ptrblck | Based on the error message some samples seem to have 160 channels while others have 163.
Due to this, the collate_fn cannot stack the samples to a single batch and raises the error.
Check the shape of each sample and make sure the channel dimension as well as the spatial size are the same. |
subedir | I have two models A and B. The output of model A is fed to model B and the loss is calculated(example below)opA = modelA(inp)opB = modelB(opA)loss = criterion(opB, GT)I want to update weights of model A only. How can I achieve this? | ptrblck | No, setting the model to .eval() will change the behavior of some layers (e.g. dropout will be disabled and batchnorm layers will use their running stats) and will not change the behavior of the gradient calculation.
Yes, that works. |
jaehwanee0411 | I’ve define a auto-encoder model as below.class AE(nn.Module):definit(self, img_c, z_dim):super(AE, self).init()self.enc = Encoder(img_c, z_dim)self.gen = Generator(z_dim, img_c)self.model = nn.Sequential(self.enc,self.gen)def forward(self, x):return self.model(x)Encoder and Generator are another class(nn.Module) I hav... | ptrblck | Create a separate optimizer by passing ae.enc.parameters() to it and use this new optimizer to update the encoder parameters only in opt_enc.step(). |
gokijam | First Problem:RuntimeError: expected scalar type Float but found DoubleI tried to fixed this by adding this:i = i.float()recon = model(i)#TrainingmodelAfter this changing, I received:not enough memory: you tried to allocate 10616832000 bytes.It is about 10GB, I worked on CPU because my GPU is GTX 970 but i have 32GB of... | ptrblck | Based on the error message I don’t think you are running out of memory on your GPU but on your host, so you might want to double check the memory requirements of your script for host RAM. |
hsc | Let’s say I have a cascaded model:e.g., x → modelA → modelB → output <-loss-> gtnow, there are multiple losses (loss1, loss2, loss3) I’d like to calculate but I want to backpropagate only loss1 and loss2 to modelA, not loss3.The modelB needs to be updated using every loss though.I could do it using retain_graph=True, b... | ptrblck | Assuming loss1 and loss2 are supposed to create the gradients for modelA and modelB, you could use loss3.backward(retain_graph=True, inputs=modelB.parameters()) and call loss.backward() on the accumulated loss from loss1 and loss2 afterwards.
It would require more memory if you don’t free the comp… |
venuv | I am trying to fine tune MaskRCNN instance segmentationfollowing this tutorial. My custom dataset and model build seem to pass, but I run into this ZeroDivisionError upon training. Any hints on how to debug are appreciated. Happy to include more code, did not want to overwhelm with irrelevant …ZeroDivisionError ... | ptrblck | I don’t know why shuffle=True should raise the error only, as it seems that your dataset might be empty.
While creating the DataLoader a RandomSampler or SequentialSampler will be created if shuffle is set to True or False, respectively, and no custom sampler is passed as seenhere.
In both cases … |
Torcione | Hi everyone,I want to modify the value of my learning rateat each stepinstead of doing it at the end of each epoch.In particular at each step of my training I compute a generic measurexand I want to modify the learning rate for the next step as a function ofx.Just to give a more explicit idea of the pipeline, given the... | ptrblck | I’m not sure if there is a more flexible class for your use case, but I guess you might skip using the scheduler and update the learning rate manually as you wish via:
for param_group in self.optimizer.param_groups:
param_group['lr'] = lr |
cbd | I am creating network as below. Is it possible to write “if” condition inside nn.Sequential? I want to make customize if condition is true add nn.LeakyReLU else not.conv_layers.append(nn.Sequential(nn.Conv2d(3, 5, kernel_size=3, stride=1,padding=1),nn.LeakyReLU(0.2,True) ) | ptrblck | Yes, you can use a condition to add a new layer to a list first and then create the nn.Sequential model:
layers = [nn.Conv2d(3, 5, kernel_size=3, stride=1,padding=1)]
cond = True
if cond:
layers.append(nn.LeakyReLU(0.2,True))
model = nn.Sequential(*layers) |
cbd | In below code, input is passed from layer “self.linear1” in forward pass. I want to print the layers from which input is passed though other layer like “self.linear2” is initialise. It should be print only “linear1”.import torch.nn as nn
import torch.nn.functional as F
import torch
from torchsummary import summary
cla... | ptrblck | Maybe printing the graph in e.g TensorBoard as given inthis tutorialmight be helpful. |
elemeo | I have a multidimensional dataset, (1827, 5).From that dataset I exctract the variable I want to predict and im left with my X and y variables as such:X has size (1827, 4) and y has size (1827, 4).Then i further split them into train and test datasets giving 20% to the test dataset. now the shapes I have are these:> pr... | ptrblck | This seems to be wrong, since the layer dimensions are not depending on the batch size.
You should defined the layers using their expected input features, not the number of samples they would see during training/inference.
Based on your initial description you are dealing with 1827 samples where … |
marsggbo | set seedimport torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_lightning.utilities.seed import seed_everything
seed_everything(666)
num=6
x = torch.rand(4,num)
print(x)
>>> tensor([[0.3119, 0.2701, 0.1118, 0.1012, 0.1877, 0.0181],
[0.3317, 0.0846, 0.5732, 0.0079, 0.2520, 0.5518],
... | ptrblck | I get the same expected results if both approaches are using eval and training mode, respectively.
During training the batch stats will be used to normalize the input (and the running stats will be updated) while the running stats will be used to normalize the input during eval.
Thedocsexplain … |
rickhuang | Hi, x is a 4-D tensor and y is a 2-D tensor, and i want to replace the value of x by corresponding value in y with x as index. Like the code I write below. Because x.shape[0] is so big, it will make my code be very slow, so I want to know whether some quick method to do this by some torch function. Thanksindex_array = ... | ptrblck | Direct indexing with broadcasting should work:
x = torch.randint(0, 10, (10, 2, 3, 4)).float()
y = torch.randn(10, 10)
index_array = x.clone().long()
for i in range(0,x.shape[0]):
x[i] = y[i][index_array[i]]
x2 = y[torch.arange(y.size(0))[:, None, None, None], index_array]
print((x - x2).abs… |
yoshitomo-matsubara | Hello,When training only specific layers in a model, which one should make training faster,detach()orrequires_grad = False? Or no difference?Assuming you have some pretrained model and want to fine-tune some of its layers while freezing the other layers and your optimizer contains updatable parameters only (i.e., those... | ptrblck | I think both approaches would yield the same execution as Autograd should be smart enough to stop the backpropagation where no gradients are needed in previous layers (approach 1).
The difference of passing all parameters or only the subset which requires gradients would be inthis check, which che… |
Samah_Abu_saleem | I was training GCN model on my Linux server and I suddenly got this error.RuntimeError: Unexpected error from cudaGetDeviceCount(). Did you run some cuda functions before calling NumCudaDevices() that might have already set an error? Error 804: forward compatibility was attempted on non supported HWPytorch version: 1.1... | ptrblck | Based onthis issueother users were running into the same error message if
their setup was broken due to a driver/library mismatch (rebooting seemed to solve the issue)
their installed drivers didn’t match the user-mode driver inside a docker container (and forward compatibility failed due to the… |
ziba | Operating System: Windows 10Python Version: 3.7.11PyTorch Version: 1.10.1I have two below tensors:import torch
embedding_vectors = torch.tensor([
[0.01, 0.02, 0.03],
[0.07, 0.08, 0.04],
[0.05, 0.09, 0.06],
[0.51, 0.92, 0.67],
[0.55, 0.99, 0.64],
[0.17, 0.23, 0.85],
[0.45, 0.66, 0.31],
... | ptrblck | You could use the functional API via:
F.embedding(indices, embedding_vectors)
or assign embedding_vectors to the .weight attribute of an nn.Embedding layer. |
tangolin | I installed cuda10.1 in the docker container. Upon runningnvcc --version, I getnvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2019 NVIDIA Corporation
Built on Sun_Jul_28_19:07:16_PDT_2019
Cuda compilation tools, release 10.1, V10.1.243Now on my actual machine whennvcc --versionis ran, I getnvcc: NVIDIA (R) Cu... | ptrblck | Yes, the pip wheels and conda binaries ship with their own CUDA runtime (as well as cuDNN. NCCL etc.) so you would only need to install the NVIDIA driver. If you want to build PyTorch from source or a custom CUDA extension, the local CUDA toolkit will be used. |
fulltopic | Build Pytorch from source.export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
USE_LMDB=ON python setup.py installThe build failed at very beginning (about 3/5xxx) when building protobuf related.The whole shell exited quietly without visible output.The output of collect_env.py:PyTorch version: N/AI... | ptrblck | This might point to an out of memory issue, but I would expect to see a “Killed” message in your terminal.
Based on your screenshot also cudafe++ and cicc processes are used, so nvcc is compiling something, which wouldn’t fit into the crash at the protobuf stage.
In any case, try to rebuild it vi… |
duyducvo4444 | Hello all~For theF.conv1dfunction. Suppose I have the inputinput = [[a, b, c],
[d, e, f]]And I have the weightweight = [[x, y],
[z, w]]Mathematically, the F.conv1d function will returnoutput = [[a, b, c] * [x, y]] + [[d, e, f] * [z, w]] # * is the cross-correlation operatorNow my problem is, I want t... | ptrblck | You could use the groups argument as describedhere. |
sid_1289 | what is the difference between 1x1 conv and avergaepool1d ? | ptrblck | A 1x1 conv layer will use a kernel size of 1x1 (i.e. a single pixel) and would act as a linear layer in the default setup. The nn.AdaptiveAvgPool1d layer works on 3D inputs in the shape [batch_size, channels, seq_len] and returns a desired output shape in the temporal dimension by applying an adapti… |
markmorr | Hi,I am trying to go through the tutorial on langauge translation atLanguage Translation with TorchText — PyTorch Tutorials 1.7.1 documentationRunning the first cell in the tutorial produces an error at this line:return Vocab(counter, specials=[’<unk>’, ‘<pad>’, ‘<bos>’, ‘<eos>’])init() got an unexpected keyword argume... | ptrblck | It seems the specials argument was removed inthis PR.
The new usage seems to be shown in e.g.this tutorial. |
hitbuyi | on torch.utils.data.sampler.SubsetRandomSampler(), if I want to choose 5 indices out of 100 randomly, is it right?torch.utils.data.sampler.SubsetRandomSampler(idx, 5)where len(idx) = 100in tutorial of Pytorch, I can’t find using it at this way, why? | ptrblck | No, your usage is wrong and won’t chose 5 out of 100 indices.
As described in thedocs:
Samples elements randomly from a given list of indices, without replacement.
which means you are supposed to pass the indices the sampler should randomly sample from as the first argument.
E.g. if your orig… |
Javier | Hi all!this is probably somewhere in this forum’s history but I can’t seem to find it.My problem is the following: I have two tensors containing each a list of 3D points, one is S of size (81,3) and the other P of size (20000, 3). What I’d like to do is to compute the “displacement” vectors D = S-P between every 3D poi... | ptrblck | You could unsqueeze the tensors and let broadcasting do its job as seen here:
S = torch.arange(0, 5*3).view(5, 3)
P = torch.arange(1, 10*3+1).view(10, 3)
D = S.unsqueeze(0) - P.unsqueeze(1)
print(D.shape)
# > torch.Size([10, 5, 3])
print(D) |
jungminc88 | My model takes two batched sequences (along with their attention masks) and is supposed to return a tensor of shape (batch_size, batch_size) whose (i,j)-element should be cosine similarity of the i-th element of the first (b_que_iis[j]) and the j-th element of the second (b_art_iis[j])I ran this with batch_size 16 on a... | ptrblck | This is expected, since the result will be concatenated in dim0 again.
Each device returns 4x4=16 values and thus the result of 4 devices is 4*4*4=16*4=64.
Assuming the additional values are created as function between the samples in a batch, you could try to calculate them after nn.DataParallel … |
tsuijenk | Hello,I’ve been struggling for a while with the runtime error. I have visited most, if not all, of the posts on this forum that has this error, and tried to replicate the solution, but I still cannot fix it. Any suggestions would be appreciated!Essentially, I have a custom PyTorch dataset class, where I set requires_gr... | ptrblck | No, this would only be needed, if you really want to calculate gradients in the input (e.g. for adversarial attacks).
This is also not needed and I don’t know right now a valid use case where the targets need gradients.
Could you explain how this return value is treated?
return torch.mean(torch… |
Sumera_Rounaq | Question 1: In many research papers, researchers tend to suggest normalization of images from [-1 to 1] . How can we achieve it in code?Question 2: What is the meaning of following line of code?transforms.Normalize(0.5, 0.5)Question 3: Let say I trained my model with learning rate: 0.0001 and then save the state of my ... | ptrblck | Something like this should work:
x = torch.randn(10, 10, 10)
y = x - x.min()
y = y / y.max() * 2 - 1
print(y.min(), y.max())
> tensor(-1.) tensor(1.)Normalizesubtracts the mean and divides by the stddev to create normalized/standardized outputs, which are also known as z-scores.
It depends… |
Sherzod_Bek | Hi,I want to implement single class classification(output should be just single probability number). is there any example? or guide ?I did multi-class classification, but I couldn’t modify it to single class… (if I use single class, training always shows loss: 0) | ptrblck | A single-class classification wouldn’t make much sense, since your model wouldn’t learn anything and will just output a high probability for the single class.
A “perfect” classifier would thus be:
def predict():
return 0
as no other class indices are valid.
Assuming you are dealing with a bi… |
tamersaleh | Hello, have a nice day!!When to try implement the code;def has_mask(mask_path):img = cv2.imread(mask_path, 0)thresh = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)[1]if np.mean(thresh) > 0.0:return Trueelse:return Falsedef get_dataloader(rank, world_size):“”“Creates the data loaders.”""train_df = dataset.create_df(co... | ptrblck | An example would be to pass a valid image path as a string:
img = cv2.imread('/tmp/image.jpeg')
Right now df_row['building_label_path'] is an np.float64 value, which is a floating point value and not a path string so you would check your df_row content and make sure to index the right column/row. |
Sang_Dinh | I want to study about ensemble in pytorch for my project which using efficient and resnet. But I dont know how to start with it? I also search for information on google. Probably my keywords are not good to have good document. Anyone know? Thank you so much. | ptrblck | This postand the entire thread might be helpful for you. |
jojojo | Hi fellows,I have a doubt. I am working on 2D Cnn network for OCR. After my 6th CNN layer output, tensor shape will be (B, C, H, W). I have to pass this output to linear layer to map to number of classes(76) required to have for CTC loss. Now how should i reshape my CNN output tensor to pass to linear layer. Also after... | ptrblck | There are multiple possible approaches and it depends how the activation shape is interpreted.
E.g. using [64, 512, 1, 28] you could squeeze dim3 and use dim4 as the “sequence” dimension (it’s one of the spatial dimension).
In this case, you could permute the activation so that the linear layer wi… |
kahroba | Hello. The following code snippet has a runtime errorimage934×462 22.2 KBRelevant error:File “run_dst.py”, line 863, inmain()File “run_dst.py”, line 848, in mainresult = evaluate(args, model, tokenizer, processor, prefix=global_step)File “run_dst.py”, line 296, in evaluateoutputs = model(**inputs)File “/usr/local/lib/p... | ptrblck | Your target values are out of bounds. nn.CrossEntropyLoss expects the target to contain class indices in the range [0, nb_classes-1], so check the min/max values of the target and make sure they contain only valid values. |
C_J | When I run my code, I get this runtime error below:CUDA out of memory. Tried to allocate 88.00 MiB (GPU 0; 8.00 GiB total capacity; 6.04 GiB already allocated; 0 bytes free; 6.17 GiB reserved in total by PyTorch)I don’t understand why it says 0 bytes free;Maybe I should have at least 6.17 - 6.04 = 0.13 GiB free?I’m afr... | ptrblck | You are trying to allocate 88MB. ~130MB are in the cache, but are not a contiguous block, so cannot be used to store the needed 88MB. 0B are free, which shows that the rest of your device memory is used to store the CUDA context, memory for other applications etc. |
user36 | Hi! I am trying to use 1D convolution in order to classify a set of time signals. Every data unit I need to classify is made out of 65 different time series, each one contains 50 time samples, so if I write:dataset = MyDataset(train,y_train_one_hot)
a,b = dataset[1]
print(a.shapeI will get:[56,50].I want to run 1D conv... | ptrblck | I guess you are reshaping the activation in the forward method of your model and might change the batch size to 1. If you are using x = x.view(-1, SHAPE) to flatten the tensor, then replace it with x = x.view(x.size(0), -1) which will keep the batch size and might raise a valid shape mismatch error… |
vadimkantorov | Why are loss modules (criterion) often not wrapped by DDP?Is it because loss modules typically have no learned parameters?(and thus if they have, they should be part of DDP?) | ptrblck | The loss calculation is performed of each node and doesn’t need any communication. In case your loss needs to communicate some gradients, I guess it could be used as part of the model (and would thus be treated as any nn.Module). |
humza | Traceback (most recent call last):** File “test.py”, line 55, in **** from torchvision.transforms import transforms as T**** File “/home/manager/env/lib/python3.8/site-packages/torchvision/init.py”, line 4, in **** from .extension import _HAS_OPS**** File “/home/manager/env/lib/python3.8/site-packages/torchvis... | ptrblck | This would point to a broken installation in the other environment you are using (I don’t know how you are executing the script in the failing case). |
Ali-Arch808 | Hi, I’m trying to make a script for a model trained on cifar-10.scripted_model = torch.jit.script(model, torch.rand(1,3,32,32))I get the following error:TypeError:'numpy.int64' object in attribute 'Conv2d.in_channels' is not a valid constant.
Valid constants are:
1. a nn.ModuleList
2. a value of type {bool, float, int,... | ptrblck | The error message claims you are using numpy.int64 to specify the in_channels argument in an nn.Conv2d layer as seen here:
# works
conv = nn.Conv2d(3, 3, 3, 1, 1)
torch.jit.script(conv)
# fails
conv = nn.Conv2d(np.int64(3), 3, 3, 1, 1)
torch.jit.script(conv)
> TypeError:
'numpy.int64' object in … |
StaleChexMix | I’ve looked at many articles and have been Googling for a few days now without being able to fix the issue I’m having. I am having an issue with the autograd PyTorch function in my sequential models. I am trying to implement the PPO algorithm, but for some reason, the gradients don’t propagate to my networks after call... | ptrblck | You are recreating the tensor here without any gradient history:
currCriticVals = torch.tensor(currCriticVals[0:advantages.shape[0]], dtype=torch.float, requires_grad=True, device=device)
currCriticVals is a new tensor, which requires gradients without any history and will thus detach the computat… |
Liquidmasl | I am currently trying to get another loss function to work, but I always get the same error:Found dtype Double but expected FloatBut how is that possible?class MSLELoss(nn.Module):
def __init__(self):
super().__init__()
self.mse = nn.MSELoss()
def forward(self, pred, actual):
... | ptrblck | I cannot reproduce the issue and both approaches work as expected:
criterion = nn.MSELoss()
x = torch.randn(10, 10)
y = torch.randn(10, 10).double()
loss = criterion(x, y)
class MSLELoss(nn.Module):
def __init__(self):
super().__init__()
self.mse = nn.MSELoss()
d… |
The_duke | There is something I don’t quite understand in this tutorial:https://pytorch.org/docs/stable/notes/extending.htmlThere is example that implements a simple linear function in pytorch:Inherit from Functionclass LinearFunction(Function):# Note that both forward and backward are @staticmethods
@staticmethod
# bias is an op... | ptrblck | You are missing the use the gradient calculated by the loss (or the next layer).Backpropagation for a Linear Layerby Justin Johnson derives the formula for a simple case and was part of the CS231n lecture. |
MartinZhang | This a function about fuse torch.nn.BatchNorm2d by myselfimport torch.nn as nn
class FuseBN(nn.Module):
def __init__(self, layer):
super().__init__()
eps = layer.eps
mean = layer.running_mean
var = layer.running_var
weight = layer.weight
bias = layer.bias
bi... | ptrblck | You are comparing the native batchnorm layer in training mode with your FuseBN layer, which uses the eval logic.
Also, after initializing the batchnorm layer the running mean would be all zeros and running_var all ones so you might want to train it for a few steps so that both layers would indeed n… |
MartinZhang | In Pytorchimport torch
temp_data = torch.tensor([1, 2, 3, 4])
# temp_data = tensor([1, 2, 3, 4])
temp_data[0] = 5
# temp_data = tensor([5, 2, 3, 4])So how can something similar be done in c++??Thanks a lot. | ptrblck | tensor.index_put_ would be the right approach as given inthese docs. |
Olii | Hi, how can I copy specific layer structures and weights to a new model? I need to use Resnet but with additional layers and operations. What would be the best practice?here’s my sample codeclass Encoder(nn.Module):
def __init__(self, args1, args2):
super().__init__()
resnet = models.resnet50(pretr... | ptrblck | Your code looks alright and should work assuming you fix the attribute names.
Alternatively, you could also create a custom model by deriving from a resnet implementation in case that’s easier or cleaner. |
aktgpt | I want to copy a pre-definednn.Sequential()like thetorchvisionResNetlayer1and make a new module that is trainable, without going through the pain of using_make_layerfunction. Is there an easy and safe way to do this?Something like this:class MyModel():
def __init__(self):
model = torchvision.models.resnet18... | ptrblck | Yes, you can reassign modules as seen in your code snippet. You would have to change the attribute names of course to valid ones and you could use copy.deecopy for safe_copy_way. |
cbd | In below code “tensor_a” is one dimensional tensor with all value 1. From “tensor_b” i want to find out the index for which all the channel values are greater than 100 and “3rd channel” value should be greater than value of “1st channel” and “2nd channel”. That index value in “tensor_a” should be replace with 0.In bel... | ptrblck | This should work:
a = torch.tensor([[[[160, 56, 20],
[54, 6, 97],
[65, 119, 56]],
[[185, 13, 90],
[10, 6, 220],
[67, 88, 4]],
[[210, 92, 74],
… |
zhenshan_wang | I wanted to conduct the code following‘from torch._C import *,’at the first line in my python file,but when I was doing this, the program would stay there for a long time and do nothinghow can I handle itthanks!! | ptrblck | Thanks for the update!
Since it’s working fine in Xshell, what’s the setup causing the slow execution/hang and how do these setups differ? It sounds as if your environments might be different (e.g. re you using conda/pip envs?) and one of them might be broken. |
blade | I’m trying to run my code using 16-nit floats. I convert the model and the data to 16-bit with no problem, but when I want to compute the loss, I get the following error:return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)RuntimeError: “nll_loss_fo... | ptrblck | nn.NLLLoss and thus also nn.CrossEntropyLoss don’t support float16 tensors on the CPU, if I’m not mistaken, so you could either use the GPU or transform the model output tensor to float32 before calculating the loss.
Also, in case you don’t want to manually transform your tensors, use the mixed-pre… |
Tanuj | I have been trying to obtain the output of all but last linear layer of Mobilenet v3. The last module in small mobilnetv3 is a Sequential one:print(mobilenet_v3_small.classifier)
Sequential(
(0): Linear(in_features=576, out_features=1024, bias=True)
(1): Hardswish()
(2): Dropout(p=0.2, inplace=True)
(3): Linear... | ptrblck | Wrapping submodules into nn.Sequential containers often fails, as you might be missing functional API calls used in the forward method.
In your case,this torch.flattenoperation is missing and will yield the shape mismatch.
You could either add it as an nn.Flatten to your nn.Sequential model or d… |
Azerus | Hello,I’ve got an error in a convolution using the optionspadding='same'andpadding_mode='reflect'.Given a kernel of size 3, stride=1, and dilation=1, I was expecting those two convolutions to be equivalent:conv1 = torch.nn.Conv2d(2, 2, 3, padding = 'same', padding_mode = 'reflect')
conv2 = torch.nn.Conv2d(2, 2, 3, pad... | ptrblck | Your code works for me in 1.11.0.dev20211101+cu113. Which PyTorch version are you using?
If an older one, could you update to the latest nightly binary and check if this issue might have been already fixed? |
Kalle | When saving a model like the following snip of code, does it then matter if the model is in train() or eval() mode? Does train() and eval() change the model.state_dict()? And if so, should model.train() be called before saving the model?for epoch in range(5):
# prepare model for training
model.train()
for i... | ptrblck | No, it doesn’t. Calling model.train() or model.eval() will change the internal self.training flag to True or False, respectively. This flag is then used in some modules (e.g. nn.Dropout and batchnorm layers) so switch the behavior in their forward method. |
erfan_asadi | Hello everybody,Recently, I am trying to implement a two-layer LSTM model and train it with my dataset.This is my model implementation:class LstmModel(nn.Module):
def __init__(self, device):
super(LstmModel, self).__init__()
self.lstm1 = nn.LSTM(
input_size=2048, hidden_size=1024, batch_... | ptrblck | The error message points to a dtype mismatch in the inputs and model parameters.
Note that numpy uses float64 by default and based on your code you are not transforming the numpy arrays to float32.
Add x = torch.from_numpy(x).float() into your __getitem__ method and it should work. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.