user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Dennis_Hugle | Hey Community,lets say i want to change the dropout in densenet in the last layers, so i choose layer 10 and 11 and update the respective dropout like shown. As you can see, the dropout remains 0.2 even after model.eval() is called.Why is that the case?Is there a more appealing way to change the dropout in the respecti... | ptrblck | self.drop_rate is an attribute of the _DenseLayer module as seenhere.
The value won’t change by calling model.train() or model.eval().
Instead the functional dropout call inthis line of codewill use the self.training attribute to decide if dropout should be used or not. |
some_user | Dear Community,i encountered some none-intuitive behaviour. I load a model, set it to evaluation mode and predict a single image using model(input). Then, I set the model to training mode and predict a single image again. (Note that there is no .backward performed, I even disabled requires_grad for all parameters). Whe... | ptrblck | densenet121 uses batchnorm layers, which will update their running estimates during training in each forward pass.
During evaluation these running estimates will then be applied instead of the batch statistics, which explains the difference in your outputs. |
xian_kgx | Suppose I have a model that takes as input a multi-level mask like a segmentation map where each pixel can take one of N > 2 classes.My question is should the input shape be (batch_size, num_classes, height, width) or can I instead use only one channel to encode the class index with an input shape of (batch_size, 1, he... | ptrblck | You can encode the input information as you want.
E.g. you could certainly pass the input in a one-hot encoded way, as a single channel image, or even a color image, where each color represents a certain class.
The “right” approach also depends on your current model.
I.e. are you creating a model… |
eyk | HiI am trying to resize my images through transforms, but I get the error: “AttributeError: ‘Resize’ object has no attribute ‘resize’”Here is my code:class swe_dataset(Dataset):definit(self, train, label,transform):self.x_data=trainself.y_data=labelself.len = len(self.x_data)self.transform=transform#self.transform= tra... | ptrblck | In your functional approach you are unpacking sample to inputs and target, thus passing a tensor to resize, while you are trying to apply self.transform on the tuple directly, which won’t work.
Unpack sample or pass self.x_data[index] directly to self.transform. |
c.justin | Hi there,I’m really new to pytorch and when I do validation in training I got this error in using batchnorm1d:cuDNN error: CUDNN_STATUS_NOT_SUPPORTED. This error may appear if you passed in a non-contiguous input.By taking a took athttps://github.com/ttumiel/pytorch/commit/36d310827c73bfed6aae6f4d68725d86f447d428, I th... | ptrblck | You could try to install the binaries with cudatoolkit=10.2, which should ship with a newer cudnn version, use theNGC container, or build PyTorch from source with your local CUDA and cudnn installation. |
Kareem_Metwaly | Hi,I have a saved model that I’m trying to load.The training was initially done over the GPU.When I load it to the GPU, it works fine. However, when I load it to the CPU, sometimes it works and sometimes it doesn’t (I have some Nan values).I’m using the following functions to save and load the model,def save_checkpoint... | ptrblck | Could you try to run the code in the environment with numpy==1.18.1 please? |
eyk | Hi,I need to split my images to validation and train set in cross validation, in a way that images of each patient be either in train or validation. each patient has about 8-11 images.root|___patien_1im1| | __ im2 …||___patient_2im1| | __ im2 …|...how I can split images based ... | ptrblck | Each patient should belong to a unique group, so the range should be [0, 299]. |
seankala | Hello. I’m not sure if I’m just unfamiliar with saving and loading Torch models, but I’m facing this predicament and am not sure how to proceed about it.I’m currently wanting to load someone else’s model to try and run it. I downloaded theirptfile that contains the model, and upon performingmodel = torch.load(PATH)I no... | ptrblck | The stored checkpoints contains most likely the state_dicts of the model and optimizer.
You would have to create a model instance first and load the state_dict afterwards as explained in theserialization docs:
model = MyModel()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) # change to… |
Alymostafa | im facing a runtime error when trying to implement cnnScreenshot from 2020-04-07 01-58-071600×900 136 KBthis is the link of model :https://github.com/Alymostafa/ml/blob/master/cnn_using_pytorch.ipynb | ptrblck | Permute the input, so that the channel dimension is in dim1 and set the in_channels to the number of input channels, not the height. |
jasg | Friends I get this error:RuntimeError: expected stride to be a single integer value or a list of 1 values to match the convolution dimensions, but got stride=[1, 1]This apperar in : y_pred = CNNmodel(X_train)How can I customize the kernel values in this code pleasekn = torch.Tensor([[1 ,0, -1],[2, 0 ,-2], [1, 0... | ptrblck | Your kernel shape in kn is wrong, as nn.Conv2d uses a weight with the shape [out_channels, in_channels, height, width].
This code should work:
kn = torch.Tensor([[1 ,0, -1],[2, 0 ,-2], [1, 0 ,-1]]).unsqueeze(0).unsqueeze(0)
class ConvolutionalNetwork(nn.Module):
def __init__(self):
su… |
murph213 | I cannot gettorch.loadandmap_locationto work as expected. I have tried three of the suggested methods for loading a model onto the GPU usingmap_location(from references listed below). The model always ends up on the CPU, despite the documentation seeming to indicate thatmap_locationcan load tensors directly onto the G... | ptrblck | I still think that you are hunting down two separate issues.
torch.load(..., map_location) will load the tensor or state_dict onto the specified device.
However, since you are piping this operation directly to model.load_state_dict, internally most likely param.copy_ will be used, which will then … |
Aminul_Huq | I wrote the following code snippet and it gave me the following errortorch version 1.4.0torchvision version 0.5.0I tried installing using both pip and conda. Both produces the same errorimport torchvisionRuntimeError Traceback (most recent call last)in----> 1 import torchvision~/anaconda3/l... | ptrblck | Could you delete all torchvision installations and re-install it again, please? |
AreTor | From the PyTorch 1.4.0 docs in thetorch.optimpage:image850×161 16.6 KBDoes this happen also when using.to('cuda')? | ptrblck | Yes, to('cuda') and .cuda() are equivalent calls.
Make sure to push the model to the appropriate device before creating the optimizer. |
dugr | I want to look into the output of the layers of the neural network. What I want to see is the output of specific layers (last and intermediate) as a function of test images.Can you please help? I am well aware that this question already happened, but I couldn’t find an appropriate answer. I have pretrained neural netwo... | ptrblck | You could use forward hook to get the layers outputs as describedhere. |
Kenisy | For example I have 2 tensor:x = torch.randn(4)y = torch.randn(2, 2)If I want to copy y to x I have to do this:x.copy_(y.view(x.shape))Is there any more efficient ways to do it ? I notice that torch7 is able to do x:copy(y) but pytorch can’t. | ptrblck | The view operation will change some meta data of the tensor and will not copy y, so you shouldn’t see any performance hits. |
111273 | I need to use nn.Sigmoid(), but I need sigmoid growth when the number is greater than x, not zero.Thanks a lot. | ptrblck | Would adding or subtracting the desired constant to the input tensor work?
You would then calculate sigmoid(input-x), which will move the function on the x-axis. |
ttbb | I searched on the forum, but couldn’t find any topic with exactly same problem described below.Currently, I do some research on computer vision deep learning topic.I noticed, that in “Conv2d”, there is an option to specify a “groups” value.According to PyTorch docs:At groups=2, the operation becomes equivalent to havin... | ptrblck | Sorry for the misleading message.
The input will completely processed. Each group will see half the input channels, and producing half the output channels, and both subsequently concatenated (from the docs).
This code demonstrates the behavior better:
conv = nn.Conv2d(6, 6, 3, 1, 1, groups=2, bia… |
namduc | I have trained model with layers stacks in nn.Sequential for classification problem.The ConvNet architecture look like this:class ConvNet(nn.Module):
def __init__(self,num_classes=8):
super(ConvNet,self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1,64,kernel_size=7), ... | ptrblck | Sorry for being not clear enough.
You won’t be able to copy the child modules directly to an nn.Sequential container, as all functional calls as well as locally defined modules in the original forward function will be missing.
Also, removed contains the order of modules as they were created in the… |
braindotai | Hi there, in first file I’m defining the model class as “Classifier” and training the model and then saving it usingtorch.save(model, 'model.pt', dill). Code in first script looks like-class Classifier(nn.Module):
def __init__(self):
super(Classifier, self).__init__()
# a toy example model
s... | ptrblck | You could save the jitted model, which can then be loaded in other applications.
As far as I know, there is no way of storing the model directly without recreating the file structure.
Generally this workflow is also not recommended and you should store and load the state_dict instead. |
hadaev8 | I have variable length data and want to pack it to batches with size of max sample len in batch repeating shorter samples.For example like this[[0, 1, 2, 3, 4], [0, 1, 2]] => [[0, 1, 2, 3, 4], [0, 1, 2, 0, 1]] | ptrblck | Oh sorry, I apparently missed the most important part of the question.
I’m not sure, if there is a function for this, but this code snippet should work:
x = [torch.tensor([0, 1, 2, 3, 4]), torch.tensor([0, 1, 2])]
max_len = max([t.size(0) for t in x])
res = [torch.cat((t, t[:max_len-t.size(0)])) f… |
dhecloud | Hi, i am using apex to try to fit a larger model (T5-large) on a single K40 GPU. i understand K40 is using the kepler gpu, so most of the benefits of apex will not be usable on the K40. However, i read that is it still possible to use fp16 to fit a larger model so i went ahead with that. I managed to start training wit... | ptrblck | The losses should not get an NaN values, while the gradients might encounter NaNs, which will reduce the loss scaling.
Could you check the models operations for custom ops, which might require FP32 precision due to overflow in FP16?
Also, if you just want to save memory, you could try to use torch… |
mayool | Hi everyone!I’m pretty new to pytorch and interested in Semantic Segmantion.I know there are severeal pretrained models included in pytorch, but i would like to build one from scratch to really understand what is going on.What I want is abinarypixelwise prediction that says me for each pixel, if that pixel belongs to a... | ptrblck | Based on this description, it seems you would like to work on a multi-class segmentation rather than a binary segmentation, as you are dealing with multiple classes.
Alternatively, if each pixel might belong to multiple classes, you would work on a multi-label segmentation.
The parameters for up… |
shrutee | I am usingtorch.cuda.ampfor mixed precision.My forward pass calls many functions with their ownforwardpasses.I tried to decorate all the forward passes in the subsequent functions withtorch.cuda.amp.autocast(enabled=True)but the error persists.Forward pass:with torch.cuda.amp.autocast(enabled=True):
h, ... | ptrblck | The error points towards a device mismatch:
RuntimeError: Expected object of device type cuda but got device type cpu for argument #1 'self' in call to _th_mm
amp needs a GPU to run properly, so you would need to call .to('cuda') on the model and input.
Also, you might need to register self.n_ as… |
nobodykid | Hello, I’m quite new in Pytorch and I have a questionInDataLoader, there’sbatch_sizeargs that will determine size of data per batch and number of batches based on total data in the set. However, I’d like to manually control number of batches I’d like to run per epoch. Is there a way I could do this while still using Da... | ptrblck | A simple approach would be to use the index of the training loop and call break once you sampled the desired number of batches.
Alternatively, you could also split the Dataset using random_split and the desired length or use a sampler, but I think the first approach would be the easiest, if you jus… |
zhishen_nie | For example,there are 3 two-dimensional matrices. And it’s shape is [3,2,2]Of course, i could calculate their 2-norm by this way:x = torch.randn(3, 2, 2)for i in range(x.shape[0]):print(torch.norm(x[i], 2))and it’s output istensor(2.2709)tensor(1.4141)tensor(2.7118)This is a solution. Well, as we all know the for-loopi... | ptrblck | You can pass multiple dimensions to the norm operation:
x.norm(dim=[1, 2])
> tensor([2.3191, 1.7451, 2.1392]) |
shrutee | I have an array of models, corresponding optimizers and losses. Without mixed precision, I sum the losses and then apply backward.(loss1 + loss2 + ...).backward()Now while doing mixed precision training withtorch.cuda.amp, acc to the sample code given I should apply backward on individual losses.scaler.scale(loss1).bac... | ptrblck | Yes, you can also sum the losses and call backward once. |
luminoussin | I have 2 model, one is a base model and another one which has a slightly different architecture from the base model which I called new model. So I am trying to load the weight from base to new model using load_state_dict but I keep getting unexpected key error on the new module part even though I already initialize the... | ptrblck | Do you get the same error, if you use strict=False in load_state_dict?
This option should warn you, but ignore missing or unexpected keys. |
csailnadi | I am trying to update weights manually without using optimizer, but somehow model weights are NoneType…class TwoLayerNet(torch.nn.Module):
def __init__(self):
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(784, 128)
self.linear2 = torch.nn.Linear(128, 128)
self.li... | ptrblck | If you are dealing with a multi-class classification, you could use nn.CrossEntropyLoss as the criterion.
I assume your model outputs logits in the shape [batch_size, nb_classes]. If that's the case, you can directly use it in the criterion and use a target tensor containing the class indices in th… |
ZdsAlpha | I am getting this error because of the following code."RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [8, 16, 240, 427]], which is output 0 of AddBackward0, is at version 3; expected version 2 instead. Hint: enable anomaly detection ... | ptrblck | As the error states, you’ve modified a variable by an inplace operation by using x += ....
If you want to sum the conv output to x, you should write out the operation as:
x = x + self.activation(conv(x)) |
lycaenidae | Hi,It may seem dummy for some of the developers, but this is the first time that I am dealing with around 50gb training data. Until now, I was only implementing homeworks and can store the data in my local.Now, I want to debug the baseline code, visualize the data and training& validation curves by using tensorboard (i... | ptrblck | If you are working on a remote server (with docker), you could open a specific port (e.g. 6006) and use it to for the tensorboard visualization.
The workflow might differ, but you could of course directly work on the server, with a code editor in the terminal or you could use a remote session with … |
uhmbg | If I have a tensor like thistensor([[0.3843, 0.3552]],[[0.1743, 0.2439]],[[0.3474, 0.1554]],[[0.1325, 0.0778]],[[0.2280, 0.1096]],[[0.3842, 0.3997]],[[0.1599, 0.0283]],[[0.1876, 0.0815]]])How could I get a tensor from him like that:tensor([[0.3843]],[[0.1743]],[[0.3474]],[[0.1325]],[[0.2280]],[[0.3842]],[[0.1599]],[[0.... | ptrblck | You can directly index tensors via tensor[] as e.g. in numpy:
x = torch.tensor([[[0.3843, 0.3552]],
[[0.1743, 0.2439]],
[[0.3474, 0.1554]],
[[0.1325, 0.0778]],
[[0.2280, 0.1096]],
[[0.3842, 0.3997]],
[[0… |
Deepak | Context:The output of my network has 6 channels. In my custom loss function, I break the 6 channels into two groups of 3 channels each. Process the first group using l1_loss (got a scalar output), the second group using bce_loss (got a scalar output), & add the two scalars obtained to get the final loss. Then I useloss... | ptrblck | Yes, Autograd tracks the indexing operation as well as additions, so your model should get valid gradients as shown in this example:
x = torch.randn(1, 6, 4, 4, requires_grad=True)
x0 = x[:, :3]
x1 = x[:, 3:]
x0.mean().backward()
print(x.grad)
x1.mean().backward()
print(x.grad) |
DominikP | I want to train a network for smoothing a point cloud.It is applied independently for each point and has the surrounding points as input.The function below performs the actual smoothing by splitting the points (x) and the neighborhoods (y) into batches and then calling the model.def do_smoothing(x, y, model, batch_size... | ptrblck | Could you try to use torch.no_grad() in a with statement:
model.eval()
with torch.no_grad():
xbatches = ...
If I’m not mistaken, your current approach shouldn’t change the gradient behavior. |
mohamed_nabil | I’m making a simple autoencoder on Mnist DigitsSo the problem i’m facing is that i’m defining 3 different lossesand when i combine them the loss doesn’t decrease while using only one seems to work fineepochs = 3
model_2.train()
for e in range(epochs):
loss_r = [0,0,0]
r = 0
for train , test in zip(train_loa... | ptrblck | Both approaches should result in accumulated gradients.
Since the gradients are accumulated, you might need to lower the learning rate or scale the losses. |
antmillar | I have a docker image of a PyTorch model that returns this error when run inside a GCE VM running on debian/Tesla P4 GPU/google deep learning image:CUDA kernel failed : no kernel image is available for execution on the deviceThis occurs on the line where my model is called. The PyTorch model includes custom c++ extensi... | ptrblck | I would uninstall all previous instllations to make sure you are really using the new build. |
chenjesu | I have run this code:z = torch.load(load_path)
for k, v in z.items():
print(z)
model.load_state_dict(z)..........('base_loss', tensor([[0.]], device='cuda:0')),
('b', tensor(5., device='cuda:0')),
('x_grid',
tensor([[[[[-1.0000, -1.0000, -1.0000, -1.0000, -1.0000, -1.0000, -... | ptrblck | Could you try to call .contiguous() on all expanded tensors?
I’ve seen a similar issue before and will create an issue in a moment to track it. |
MehdiZouitine | Hi everybody ! I’m currently building LSTM auto_encoder and i use linear layer.Linear layer need a flat vector in input but i got a batch_size so i dont know how to handle it. Let’s see the code to be more preciseIninitINPUT_FC = self.sequence_len * self.hidden_dim
self.fc = nn.Sequential(
nn.Linea... | ptrblck | nn.Linear expects the input to have the shape [batch_size, *, nb_features], the tensor should not be completely flattened to a 1-dim tensor.
Usually you would use out = out.view(out.size(0), -1) before feeding the activations to the linear layer.
However, I’m currently unsure, if you are using bat… |
AnupKumarGupta | I am applying some transformations on an Image. Is it possible to backpropagate over the operations using the autograd ?data_transforms = transforms.Compose([
transforms.ToPILImage(),
transforms.Grayscale(),
transforms.CenterCrop(88),
transforms.ToTensor()
])I am ... | ptrblck | I thinkkorniais able to differentiate through (some) operations.
CC@edgarriba, who is one of the main authors of this lib. |
ShengweiAn | The indices return by torch.topk is strange.In my option, ifsorted=False, then the returned indices should be sorted, that is the elements in the indices are ascending.However, in the following example,t2has something wrong:2144, 20, 104, 118, 123, 136, 137, 144, 171>>> import torch
>>> t0 = torch.load('./t0.pt... | ptrblck | If you don’t specify sorted=True, there is no guarantee of any order (sorted or original order).
Yes, that’s most likely the reason at least for GPU runs. I’m not sure, how this method is implemented on the CPU. |
nshrimali | Creating my first pytorch image classification project, stuck at this error, not really sure what I am doing wrong. Please help!!!..class GarbageNet(nn.Module):definit(self):super(GarbageNet,self).init()self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=3,stride=1, padding=1)self.relu1 = nn.ReLU()self.m... | ptrblck | Your forward method accepts an x input, while you are using input as the first argument to your conv layer.
Change it to self.conv1(x) and it should work. |
IcarusWizard | I have a workstation with 3 gpus. Whenever I run a model on the device other than gpu:0 (say gpu:1), the model still allocates some additional memories on gpu:0 (from my observation, it varies between 600M to 900M, which seems depend on the model I am training). I call it additional memories because when I run the same... | ptrblck | Based on the size, the CUDA context seems to be initialized on GPU0 (and I thought we got rid of this, but cannot find the issue on GitHub).
Anyway, if you only want to use a specific device, you execute your script via
CUDA_VISIBLE_DEVICES=1,2 python script.py
to mask all other devices.
Note th… |
Mah | Hello! I have this code and I want to get the variance inside each cluster. Thanks for helping.import torchvision.datasets as dsetstrain_dataset = dsets.MNIST(root=’./data’, train=True, transform=transforms.ToTensor(), download=True)from sklearn.cluster import KMeansnum_class=10data = train_dataset.data.numpy()data=dat... | ptrblck | This doesn’t seem to be PyTorch-specific, as you are using sklearn.
You could probably use the labels_ to get all samples for the clusters and then calculate the variance between these samples. |
Yimi | H(Q2{5I@CNA_%7(SRMI(WF861×398 65.9 KBThe Github code I ran needs Pytorch >= 1.4.0, while Pytorch in my server is 1.3.1. Does the version of Pytorch cause this problem? How can I fix it? | ptrblck | torch.hub and torch.utils.model_zoo were already in 1.3.1, so could you please double check your version?
Generally, we recommend to use the latest version, as it ships with bug fixes as well as new features. |
MehdiZouitine | Hi everybody ! I’m currently try some experimentation on times series data (1D sequences).So I built a kind of autoregressive model using lstm cell !My code is running well but the model doesn’t converge.Some clues :I checked my model parameters on many epochs and it didn’t change.I checked the grad of layers it set at... | ptrblck | Could you try to initialize outputs as a list, and append all out tensors to it.
Once you are done, create a tensor via outputs = torch.stack(outputs) and return it.
I assume the creation of outputs as a tensor, which requires gradients might break the computation graph.
I would assume you’ll get… |
mgloria | Since very recently, inception_v3 is available intorchvision.modelsand getting it is as simple as typingmodel = models.inception_v3(pretrained=True)Since the model was pretrained on ImageNet it has 1000 output classes which I wanted to change to 2 for my binary classifier - so I created the following head:from collecti... | ptrblck | inception_v3 was added inMarch 2017, so I’m not sure, if we are talking about the same model.
Anyway, theFinetuning Tutorialhas specific code paths for the inception model and for its auxiliary outputs.
Logits are basically the input to a softmax layer.
Since nn.CrossentropyLoss is using F.lo… |
smani | I am getting two different loss values in the following situations, although I expect them to be same.ce = torch.nn.CrossEntropyLoss(classWeights, reduction=‘none’)loss = ce(input, targets).mean()ce = torch.nn.CrossEntropyLoss(classWeights, reduction=‘mean’)loss = ce(input, targets)What could be the reason for that? | ptrblck | You would have to normalize the unreduced and weighted loss with the classWeights as shownhere. |
snip3r77 | Objective = Normalize the data: subtract the mean RGB (zero mean)X_train.size()torch.Size([50000, 3, 32, 32])X_train.mean(dim=0, keepdim=True).mean(dim=2, keepdim=True).mean(dim=3, keepdim=True).size()torch.Size([1, 3, 1, 1])just to confirm, we are flattening X_train over dim 0,2,3.the reason we skipped dim=1 because w... | ptrblck | Yes, you are skipping dim1, as you don’t want to calculate the mean in this dimension.
The code can also be written as X_train.mean([0, 2, 3], keepdim=True). |
jitesh | I am trying to implement Faster RCNN for Object Detection. I am followingthisparticular GitHub repo for implementation. However, I have a doubt fromthisparticular line in the code and just want to clarify if I have understood things correctly. There is block of code following this line where a few layers have been fixe... | ptrblck | That’s correct. Note that other (custom) layers might also change their behavior via train()/eval(), if they use the self.training argument internally.
Not necessarily. L274 sets the base to eval(), while L275+ sets the 5th and 6th module back to train. Afterwards all batchnorm layers are reset… |
Demetry | Hello everyone,I’m building an app that makes calculations using CUDA (it makes some optimization based onSimulated annealing). I successfully followedCustom C++ and CUDA Extensionstutorial and made stable version on simple GPU, so now I would like to use multiple GPUs (some tasks has huge amount of data, that could no... | ptrblck | Would splitting the data and sending each chunk to a specific device work?
Something like this could already solve your use case:
data = torch.randn(4, 100)
chunks = data.chunk(4, 0)
res = []
for idx, chunk in enumerate(chunks):
res.append(my_fun(chunk.to('cuda:{}'.format(idx))).to('cuda:0'))… |
Muyun99 | he Code is here:import torch
from torchvision.models import alexnet
if __name__ == "__main__":
net = alexnet()
x = torch.rand((1, 3, 224, 224))
for name, layer in net.named_children():
x = layer(x)
print(name, ' output shape:\t', x.shape)The output is here:features output shape: torch.Si... | ptrblck | One approach would be to create a new custom model class by deriving from alexnet as the base class and add print statements to the forward method.
However, this might be too cumbersome just to get the output shapes.
I usually just register hooks for all modules, which seems to work fine for some … |
caiusdebucean | Hello,So I’ve been trying to create a custom function and test things out, but I can’t seem to know how to make the data or function work. I’m a little confused. Here is the code:from collections import OrderedDict
import numpy as np
import torch
from torch import nn
from torch import optim
import torch.nn.functional a... | ptrblck | You would have to create instances of your Custom module before calling it (same as with other modules, e.g. nn.Linear).
Currently you are trying to pass the activation directly to the module instantiation:
x = Custom(x)
Instead define instances of Custom in the __init__ method of Network and cal… |
adaber | Hi,A model instance/object has to be initialized before we can load the model weight values to the object from a file if I understand correctly. Let me know if I am mistaken.If I used a UNet, for example, where the only variable initialization parameters (used to initialize a UNet instance) are the number of feature pl... | ptrblck | You could use some utility funcitions fromthis topicor load your jitted model directly (which seems to be the recommended way). |
alx | Hey guys I was wondering if anyone knew what loss detectron2 was using?I found L1 here but I’m not too sure. | ptrblck | Based onthis code, it seems cross entropy and a smooth L1 loss are used. |
sigma_x | For Faster/Mask RCNN, before training the model, min and max size of the input images is fixed, which is determined to a great extent by the CUDA memory capacity. This is OK.What I found at inference time, is that accuracy of the model strongly depends on the size of the input image. By default,min_size=800, max_size=1... | ptrblck | I would assume the model should work the best during validation using images with shapes and other properties as close as possible to the training data.
The shape limits are most likely added due to the architecture (but I haven’t looked into the source code to verify it). |
Neofytos | Hi everyone,I am trying to perform the following experiment and I’d like your advice on what’s the best way to implement it in Pytorch. Given a mini-batch, weight gradients dW^{(t)} are computed based on minimizing a loss function. When we step towards that direction, we get our new weights and can calculate the new lo... | ptrblck | Your approach might work, if you are using a simple optimizer, e.g. SGD without momentum.
When you are using momentum or an optimizer with running estimates, the reversed step might not work out of the box and you might need to look into the applied formula to check, how to revert it.
Here is a sm… |
CesMak | Hey there,I have an ActorCritic (used for PPO) and want to export it as onnx:ActorCritic((action_layer): Sequential((0): Linear(in_features=180, out_features=64, bias=True)(1): Tanh()(2): Linear(in_features=64, out_features=64, bias=True)(3): Tanh()(4): Linear(in_features=64, out_features=60, bias=True)(5): Softmax(dim... | ptrblck | The export method tries to call forward, which is currently not taking any input (besides self) in your implementation and also isn’t implemented.
Would it work, if you pass another flag (e.g. a bool) to forward and then fork to act or evaluate? |
dhecloud | Hi, apologies if this has been asked before.I have a tensorxof shape(batch_size, seq_len, vocab_size), say shape(1, 3, 2). I have a tensoriwhich is(batch_size, vocab_indices), say shape(1,3)which are the indices of the vocab size dimension inx. I want to get values from the last dimension (vocab_size).For example,x = ... | ptrblck | No, you wouldn’t need a for loop and for batched input this should work:
x[torch.arange(x.size(0)).unsqueeze(1), torch.arange(x.size(1)), i] |
Yolkandwhite | I have question about array indexmriidx = self.mriids[idx] #img file name
maskidx = self.maskids[idx] #mask file name
mask_file = os.path.join(self.masks_dir, maskidx)
img_file = os.path.join(self.imgs_dir, mriidx)
img = Image.open(img_file).convert("RGB")
mask ... | ptrblck | You are reassigning and then slicing again the object:
obj_ids = obj_ids[1:] # here it will only have a single element
print('obj_ids[1:] shape :', obj_ids[1:].shape)
print('obj_ids[1:] :', obj_ids[1:]) # is empty now |
peps0791 | Hi,I have a seq2seq encoder model (Custom class), of which I want to access the RNN properties such as:hidden state sizenumber of layersnumber of directions.I am able to get the LSTM object (‘torch.nn.modules.rnn.LSTM’) by invoking the._modulesproperty on the encoder model. On printing the LSTM object, I see this outpu... | ptrblck | You can directly access these properties and print them:
model = nn.LSTM(10, 10, 2, 0.3, bidirectional=True)
print(model.hidden_size)
print(model.num_layers)
print(model.bidirectional) |
shamoons | In keras / Tensorflow, I believe you have to specify the size of the sequence, so it works well for fixed sequences. But with the PyTorch implementation, it seems that it can handle arbitrary sized inputs. Is that correct? | ptrblck | Since convolutions use a sliding window approach (in theory), you would need to specify the number of input channels. Defining the sequence length is not necessary, as the kernel can just be applied on whatever temporal shape is used.
I’m not sure about TF and would be surprised, if you have to set… |
SurajSubramanian | Using transfer learning for a multi-label image classification task (changed the classifier layer of resnet50).I have changed the fully connected layer of resnet50 as follows :model = models.resnet50(pretrained=True)
n_inputs = model.fc.in_features
model.fc = nn.Sequential(
nn.Linear(n_inputs, 256... | ptrblck | The training loop looks alright.
Are you working on a multi-label (each sample belongs to 0, 1 or more classes) or multi-class (each sample belongs to a single class only) classification?
In the former case nn.NLLLoss is most likely the wrong criterion to use.
Also, what did you change in the res… |
07hyx06 | Hi! I want to do some augmentation on pix2pix model. I need to do the same random crop on 2 images. Ho to usetransforms.RandomCropto do that?I addedtorch.manual_seed(1)beforetransforms.RandomCrop, but it fails, output 2 different crop image | ptrblck | I would recommend to use the functional API as shownhere. |
chantk | Hi all, I’m trying to accomplish an event detection task with 2 models where model_a will produce the event tag and model_b will produce the event localization (aka label at each time frame). Basically, I’m trying to do update the two models according to the combined loss of these two models.I tried the following code ... | ptrblck | Both approaches will yield the same result, but the method using two losses is wasteful, since you need to call the backward method twice.
Here is a small code snippet to demonstrate the behavior:
# Setup
torch.manual_seed(2809)
modelA = nn.Linear(1, 1)
modelB = nn.Linear(1, 1)
criterion = nn.MS… |
shamoons | If I have aConv1dlayers:self.conv1 = torch.nn.Conv1d(
in_channels=feature_dim,
out_channels=feature_dim,
kernel_size=kernel_sizes[0],
stride=1
)
# padding=kernel_sizes[0] // 2)
self.conv2 = torch.nn.Conv1d(
in_channels=feature_dim,... | ptrblck | It’s hard to tell which padding value you need, as the kernel sizes are not defined in the code snippet, however you could try increasing the padding until the temporal size matches your expectation.
I would also recommend to check, if adding padding in the intermediate layers wouldn’t be the bette… |
Alex_Ge | Hello,I’ve read quite a few relevant topics here ondiscuss.pytorch.orgsuch as:Loss function for segmentation modelsConvert pixel wise class tensor to image segmentationFCN Implementation : Loss FunctionI’ve tried withCrossEntropyLossbut it comes with problems I don’t know how to easily overcome.So I’m now trying to use... | ptrblck | Your logit output shape is missing the class dimension.
In my code snippet I’m creating the logits as [batch_size, nb_classes, height, width] and the target es [batch_size, height, width]. If you stick to these shapes, it should work.
nn.CrossentropyLoss expects logits and uses F.log_softmax + nn… |
shamoons | I have 2 models:modelandbaseline_m. I froze all of the weights ofmodel, so I can use those gradients to update the parameters ofbaseline_m.baseline_output = baseline_m(baseline_input)
out, output_sizes = model(baseline_output, input_sizes)
decoded_output, decoded_offsets = decoder.decode(out, o... | ptrblck | Yes, the workflow should work as shown in this dummy example:
baseline = nn.Linear(1, 1)
model = nn.Linear(1, 1)
for param in model.parameters():
param.requires_grad_(False)
x = torch.randn(1, 1)
out = baseline(x)
print(out.grad_fn) # prints valid grad_fn
out = model(out)
out.mean().backward(… |
cuongnguyen220592 | Hello,I am working to family with Pytorch.I created a 3D network to classify image. The input shape of image I used is (1, 1, 48, 48, 48) and the output shape is torch.Size([1, 256, 3, 3, 3]).Now I want to continue use Sobel filter for edge detection. I used this following code:inputs = torch.randn(1, 1, 48, 48, 48)
x ... | ptrblck | You could use a grouped convolution to and expand the kernel to the necessary shape:
x = torch.randn([1, 256, 3, 3, 3])
sobel = [[1, 2, 1], [0, 0, 0], [-1, -2, -1]]
depth = x.size()[1]
channels = x.size()[2]
sobel_kernel = torch.tensor(sobel, dtype=torch.float32).unsqueeze(0).expand(depth, 1, chann… |
torchMaster | image803×495 32.5 KBDear pytorch gurus,I’m building a neural paraphrasing model andtrying to implement copy mechanism, which uses some tokens in the input sequence as they are when producing output tokens.Easily put, copy mechanism produces a probability distribution over input tokens. After getting the probability, I ... | ptrblck | scatter_add_ should correctly propagate the gradients as seen in this example:
x = torch.rand(2, 5, requires_grad=True)
out = torch.ones(3, 5).scatter_add_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]]), x)
out.sum().backward()
print(x.grad)
> tensor([[1., 1., 1., 1., 1.],
[1., 1., 1.,… |
uertenli | Hi!I am using FasterRCNN from torchvision to perform validation. Everything worked fine until I tried to store the predictions of the model to an array. I am getting only 10 predictions per image and I have 120 frames. Plus, I transfer all the variables to the cpu and store them there. However, at each iteration (i.e. ... | ptrblck | Wrap your code in a with torch.no_grad() block, if you don’t need to call .backward() in this part of the code or detach the tensor from the computation graph, so that it can be freed via:
predictions[i][key].detach().to('cpu')
Even though you are pushing the prediction to the CPU, the attached co… |
brijraj | Why does out varies in both of these executions:Execution 1:input=torch.rand(2,3,32,32)resnet18 = models.resnet18(pretrained=True)output1=resnet18(input)Execution 2:model_1=resnet18c=model_1.childrenchildren=[]for item in c():children.append(item)class CHILD(torch.nn.Module):def __init__(self):
super(CHILD, self)._... | ptrblck | Modules or parameters in Python list and dict won’t be registered properly as such (and will thus be missing in e.g. model.parameters()).
Use nn.ModuleList or nn.ModuleDict instead. |
shafei | class Network(nn.Module):definit(self):super().init()self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)self.conv2 = nn.Conv2d(in_channels=6, out_channels=12, kernel_size=5)self.fc1 = nn.Linear(in_features=12*4*4, out_features=120)
self.fc2 = nn.Linear(in_features=120, out_features=60)
self.out... | ptrblck | You are accidentally reusing self.conv1 (and self.conv2), which will throw this error, so you should remove the first usage. |
jitesh | I am building a Custom Autoencoder to train on a dataset. My model is as followsclass AutoEncoder(nn.Module):
def __init__(self):
super(AutoEncoder,self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(in_channels = 3, out_channels = 32, kernel_size=3,stride=1),
nn.ReLU(inplace=T... | ptrblck | Based on your input shape and layer configs, you would need to set output_padding=1 in the first and third nn.ConvTranspose2d layer to get the same output shape for your input. |
serenayj | Hi,I have a standard encoder architecture and try to run it with input sequence:x_input = torch.tensor([ 0, 83, 0, 1257, 0, 25, 34, 239, 31, 275, 1057, 171, 7, 809, 174], device=device)
enc = Encoder(10889, 128, True).to(device)
x_h = enc.initHidden()
x_out, x_h = enc(x_inds,x_h)But I kept getting ... | ptrblck | Could you update to the latest stable PyTorch version (1.4.0) or, as the error message suggests, to at least 1.2.0?
I would recommend to use the latest version, if possible, as it’ll ship with new features as well as bug fixes. |
Niki | Hi,I am looking for saving model predictions and later using them for calculating accuracy. The dataset has 20000 samples, I was trying to useprediction_list.append(prediction)And then usingtorch.saveto save them. But this gives this error:RuntimeError: CUDA out of memory. Tried to allocate 16.00 MiB (GPU 0; 31.72 GiB ... | ptrblck | If you are not running the code in a with torch.no_grad() block, you will store the whole computation graph in the list for each prediction.
Use prediction_list.append(prediction.detach()) to store the tensor only (and use the no_grad() guard to save more memory, if you don’t need to calculate the … |
amin_sabet | I’m need to modify the pretrained alexnet model to process a sequence of images. During processing an image from a sequence of images, the input tensor to a convolutional layer is first subtracted from the input tensor of previous image that I stored before. Then the convolution is performs of the subtraction results.S... | ptrblck | The code looks generally alright.
Based on the logic you are using, I assume you don’t want to train the latest_tensor?
If that’s correct, you could register is as a buffer (self.register_buffer('latest_tensor', torch.zeros(...))) and store the detached version of the input:
self.latest_tensor = … |
pallgeuer | I have two models, one with 20K parameters and one with 1900K. They have the same inputs and outputs, and both follow a similar pattern of downscaling 4 times followed by upscaling 2 times (with conv2d’s inbetween), so I would expect that the 20K model runs much faster than the 1900K one. This is not the case however.T... | ptrblck | I think the slower runtime is due to the higher number of modules (71 vs. 240, if I’m not mistaken).
Even if your first model uses much more parameters, the number of layers (and thus kernel launches) is much lower, which could explain the difference in the runtime. |
Yolkandwhite | hi I’m having difficulties with making datasets.I have 2 folders. One with image files and the other one with the mask files.I tried to make the data in order using sort()the image data were lined like1, 10, 11, 12, 13but mask data were like 10, 11, 12, 13, …, 19,1image011604×763 1000 KBimage021468×694 926 KBhow can I ... | ptrblck | Based on your file names, the order is also wrong, as you didn’t prepend zeros to the actual number.
E.g. after 1 comes the file with 10 in your images.
You could use sorted with a lambda function as the key argument, get the desired file index and ignore the rest of the string. |
lesser_evil | Hello,I am trying to build a “mirror” autoencoder where the encoder parameters would be the same as decoder parameters.In the simplest case, autoencoder:• conv
• fc_1
• fc_2
• convTHow can I denote parameters of fc_1 to be the same (mirrored) as parameters of fc_2?Similarly, how can I share parameters between the 1st c... | ptrblck | I think the easiest way would be to define the parameters manually and use the functional API for all operations, e.g.:
out = F.conv2d(intput, weight)
where you’ve defined the weight as a parameter before. |
ykukkim | Hi all,I have a quick question regards to binary cross-entropy classification. I am very new to this field.At the moment I am working on time-series data fed into LSTM. However, I am not certain about my method of validation and loss as to what to expect.Below is my code for loss and accuracy.My true positive output ha... | ptrblck | For an imbalances use case, the accuracy might be misleading due to theAccuracy paradox.
In this case it would be better to observe the confusion matrix and other stats such as Sensitivity, Specificity, etc. |
theairbend3r | Hi all!I was wondering what the difference between usingrandom_splitandSubsetRandomSampleris.Do we use SubsetRandomSampler together with Subset?What are the pros and cons of usingSubsetRandomSamplerandrandom_splitmethods for creating a train-val split (or any split for that matter)for image datasets? | ptrblck | random_split returns two Datasets with non-overlapping indices, which were drawn randomly based on the passed lengths, while SubsetRandomSampler accepts the indices directly.
Both can be used for different use cases.
E.g. if you want to run a training epoch with certain samples only (e.g. from a s… |
Yiman_von | Hi, guys!I created a new tensor to observe the occupation of video memory. When I load it on the GPU, I can see a significant increase in video memory (by nvidia-smi). However, when I load it to the CPU and release it (I usedtorch.cuda.empty.cache(), I know that if this is not used, the video memory occupation may not ... | ptrblck | The memory should be used by the CUDA context, which is initialized with the first CUDA operation, e.g. creating a tensor.
You cannot release it during the runtime of your script. |
uertenli | Hi!I am trying to use the pretrained Mask RCNN model directly from PyTorch. However, I would like to separate the backbone part from the RPN and the head part, i.e, I want to create two models from the initial model. I have seen many people ask this but, could not find a solution:If I divide the model usingmodules = li... | ptrblck | nn.Sequential is a container used for simple feedforward models.
In case of more complicated models, you would have to be careful to not lose any functional API calls in the original forward method.
That being said, I would recommend to either derive your custom class from the base class and manip… |
WYBupup | I am facing one confusing problem when I worked on “VISUALIZING MODELS, DATA, AND TRAINING WITH TENSORBOARD” of pytorch tutorial.At the sixth part called “Assessing trained models with TensorBoard”, I found something confusing about SummaryWriter.add_pr_curve() function.(the code of the tutorial is showed in the pictur... | ptrblck | class_index is assigned to the current class index in the for loop over all classes.
Your code (testset.targets == class_index) wouldn’t use the model predictions, but just all targets and the current selected class target.
The function will plot a PR curve for each class.
EDIT: Issue might be re… |
songyuc | Hi, guys,I am learning about DeepLabV3+ model these days.And I meet a strange phenomenon that using the same batch size in evaluation trigger “RuntimeError: CUDA out of memory.”, which is normal in training.But the inference speed seems quite faster than the training.Any idea or answer will be appreciated! | ptrblck | You could use torch.cuda.memory_allocated(), torch.cuda.memory_cached() etc. in your script to check the memory. Also, nvidia-smi will give you the overall memory usage (including the CUDA context). |
jitesh | Hi, I am defining a Custom Model for image classification. My code is as followsclass CustomNeuralNet(nn.Module):
def __init__(self,num_classes):
super(CustomNeuralNet,self).__init__()
self.conv_1 = nn.Conv2d(in_channels=3,out_channels=32,kernel_size=3,padding=1,stride=1)
self.activation_1 ... | ptrblck | You would have to create a model instance before passing in the inputs:
model = CustomNeuralNet(num_classes)
outputs = model(inputs)
Based on the error message it seems you are trying to pass the inputs directly to the initialization of the model. |
RichardOey | I want to make a custom loss function of MSE Loss by doing GMM computation for the result.The MSE Loss will be computed using the GMM result and target value.Here is my codeclass StyleLoss(nn.Module):def __init__(self, target_feature, ncomp, initial_mus, initial_covs, initial_priors):
super(StyleLoss, self).__init... | ptrblck | self.input_gmm was also detached in the line before.
The general rule is, as long as you use PyTorch functions, don’t detach the tensors (via recreating new tensors, calling .detach() or item()), Autograd will be able to track the computation graph and calculate the gradients. |
HaziqRazali | I can ignore missing keys when loading weights by settingstrict=False. What about weights where there is a size mismatch? How can I ignore it i.e. not load it at all? | ptrblck | You could try to filter out the wrongly shaped parameters from the state_dict and try to load it using strict=False afterwards. |
Felipe_Mello | Hi everyone,Suppose I have a tensormytensor = torch.tensor([10, 20, 30, 40)]Each node has a different threshold. Lets say that min thresholds are:mythreshold = torch.tensor([2, 50, 25, 100])I wanted to dotorch.clamp(mytensor, min = mythreshold )and get as outputtorch.tensor([10, 50, 30, 100]).Is it possible?Thanks! | ptrblck | torch.where should work:
mytensor = torch.tensor([10, 20, 30, 40])
mythreshold = torch.tensor([2, 50, 25, 100])
torch.where(mytensor < mythreshold, mythreshold, mytensor)
> tensor([10, 50, 30, 100]) |
John_Deterious | I’m reading ResNet code from official website, however, I see this norm_layer used without ever defined:github.compytorch/vision/blob/2611f5cc79230f3729393279093775d08bc52718/torchvision/models/resnet.py#L50base_width=64, dilation=1, norm_layer=None):super(BasicBlock, self).__init__()if norm_layer is None:norm_layer = ... | ptrblck | norm_layer is defines as nn.BatchNorm2d by defaulthereand passed to the blockshere. |
Arjun_Gupta | I am trying to use PyTorch to get the outputs from intermediate layers of AlexNet/VGG:alexnet_model = models.alexnet(pretrained=True)
modules = list((alexnet_model).children())[:-1*int(depth)]
alexnet_model = nn.Sequential(*modules)What is odd is that I get the same output values (i.e. the same exact model) whendepth=1... | ptrblck | You can access a module inside an nn.Sequential block by indexing it:
model = nn.Sequential(
nn.Conv2d(3, 6, 3, 1, 1),
nn.ReLU(),
nn.Conv2d(6, 1, 3, 1, 1)
)
# get second conv layer
c = model[2] |
Kirty_Vedula | This is a follow up to the question I askedpreviouslya week ago. Thanks to@ptrblck, I followed his advice on following Approach 2 in my question and I am getting better results. However, there still seems to be a few issues.Here’s just a quick intro: I am training an autoencoder for a multiclass classification problem ... | ptrblck | The training loss looks alright. I used the provided shapes to check the input and target and think y = (y.long()).view(-1) should be unnecessary. Could you verify it?
The test loss might be alright. I’m not too familiar with your use case, but note that you are not applying thenormalization. Yo… |
BramVanroy | I am trying to make my training code as deterministic and reproducible as possible. When running the same training code multiple times, and always re-initialising the model, I get different results - even if I set the seeds manually, before all runs start. I found that when I reset the seed on every training run, all r... | ptrblck | As@ybj14said, the pseudo-random number generator uses the seed as its initial seed and generates all sequential numbers based on this initial seed.
That doesn’t mean that every “random” number will have the exact same value (which would create a useless random number generator), but that the sequ… |
nihal-rao | I am using a pretrained mobilenet as follows :model = torchvision.models.mobilenet_v2(pretrained=True)model.children()gives all the layers, including the last classification head.However ,model.featuresgives all the layersexcludingthe classification head.Why is this so? Are there any cases where both give the same resu... | ptrblck | model.features is defined inside the model’s __init__ method and thus not a general attribute of nn.Modules.
Depending how you are designing your model you might want to create certain “blocks” e.g. features, classifier etc. In autoencoder-like models you would most likely find a model.encoder and m… |
Patrice | I just started learning Pytorch and I do not have good programming skills. I am trying to perform a segmentation task and given the limited amount of training samples, I have opted for transfer learning approach. I have managed to run the following model with my own data and the result is very bad.class fcn(nn.Module):... | ptrblck | Yes, that;s correct. While this might work for resnet50, it might not for other architectures.
That might be the simplest method. Classification models usually have a classification layer created as model.fc or model.classifier, which you could replace with your custom convs. |
mukulkhanna | I am training an encoder-decoder network for semantic segmentation from single RGB image.The network is being trained to detect 40 classes for the semantic segmentation.Theground_truththat I have has the dimensions -[batch_size, 256, 256]where each pixel in the 256x256 matrix corresponds to a class ID between 0-39.The ... | ptrblck | Yes, everything looks good as long as your model outputs logits (i.e. no non-linearity as the last layer).
You could get the predictions using pred = torch.argmax(output, dim=1) and visualize them e.g. with matplotlib. |
YinYang_Untalan | I have a dataset of images and I used the ImageFolder for that. I have another dataset A with the same labels as the previous. Now I want to combine them such that each label corresponds to an img and something from A. How do I do this? Help. Thanks. | ptrblck | You could write a new custom Dataset, pass both datasets to it and use your logic inside __getitem__ to draw the corresponding labels from your ImageFolder and datasetA. |
Grossmend | Good day!I’m new to PyTorch. Please, help me how will look this TensorFlow (2.1.0) code on PyTorch.def cbr(x, out_layer, kernel, stride, dilation):
x = Conv1D(out_layer, kernel_size=kernel, dilation_rate=dilation, strides=stride, padding="same")(x)
x = BatchNormalization()(x)
x = Activation("relu")(x)
r... | ptrblck | Do you have a first attempt on porting this code and could share it?
If not, you could start by implementing a custom module, define all layers in its __init__ method and write the forward pass in its forward:
class CBR(nn.Module):
def __init__(self, in_channels, out_channels, kernel, stride, … |
Teng-Martin-Ma | I am new to pytorch, not familar with the gradient graph. I just created 2-layers NN, however the weights did not update during training process. Please help me out.import torch
import torch.nn as nn
torch.set_default_dtype(torch.float64)
class Nets(nn.Module):
def __init__(self):
super().__init__()
... | ptrblck | Recreating a tensor will break the computation graph in torch.tensor([e]).
Try to either concatenate this tensor directly, or alternatively append e in a list and call torch.stack on it afterwards. |
vishalagarwal | Inception v3 is taking a lot of time to load compared to other torchvision models. Is there any bug?using torchvision 0.4.2 | ptrblck | Yes, it’s a knownbugand here is the correspondingbug.
You should be able to pass init_weights=False in the nightly binaries to bypass the scipy issue. |
seankala | Hello. I’m trying to run my model with some data and am getting the following error:TypeError: expected Variable[CPUType] (got torch.cuda.FloatTensor)I’ve checked some of the answers here and it seemed that I hadn’t pushed my model onto the device yet.However, I checked the code and I have in fact done that, and I even... | ptrblck | You are creating new tensors on the CPU in this line of code:
weight_prod = torch.DoubleTensor(self.weight_mat(x))
If you want to change the data type, use out = out.double() instead and make sure it’s the right type for all further calculations. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.