user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
ptrblck
Are you using conda?If so, try:conda install -c pytorch pytorch=0.3.1
ptrblck
Could you post the error? What does this command output? conda install pytorch==1.1.0 torchvision==0.3.0 cudatoolkit=9.0 -c pytorch
Vish2020
I’m using CNN2D for text sentiment analysis with the following settings:optimizer = optim.Adam(model_pyt.parameters())criterion = nn.BCEWithLogitsLoss()I’m currently training various neural networks and I’m trying to ascertain how the gradient is behaving at each training step and thus would like to plot the gradient m...
ptrblck
You can get all gradients by iterating the parameters after the backward operation: for name, param in model.named_parameters(): print(name, param.grad) Using this approach you can store the gradient magnitude and plot it for each iteration using e.g. matplotlib. To get the learning rate and …
learner47
I am trying to do a seq2seq prediction. For this, I have an LSTM layer followed by a fully connected layer. I employ Teacher training during the training phase and would like to skip this (I maybe wrong here) during testing phase. I have not found a direct way of doing this so I have taken the approach shown below.def ...
ptrblck
Your approach is fine, if you want to set the teacher_training argument independently. Alternatively, you could also use the internal self.training flag, which will be changed by calling model.train() or model.eval().
rina
I have the following model:model = torch.nn.Sequential( torch.nn.Conv3d(1, 128, kernel_size=3, padding=1), torch.nn.ReLU(), torch.nn.Conv3d(128, 128, kernel_size=3, padding=1), torch.nn.ReLU(), torch.nn.Conv3d(128, 128, kernel_size=3, padding=1), torch.nn.ReLU(), ...
ptrblck
The first two nn.Conv3d layers with an an input of [1, 1, 160, 256, 256] will already take ~20GB during the forward pass (with intermediate activation needed for the backward pass). The complete model will thus have a much higher memory usage and I assume your GPU doesn’t have enough memory.
unnir
Hi all,I just want to be sure, where should I use the .zero_grad() function?In the official MNIST example, the .zero_grad() function is used in the beginning of the training loop.def train(args, model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader...
ptrblck
Both approaches are valid for the standard use case, i.e. if you do not want to accumulate gradients for multiple iterations. You can thus call optimizer.zero_grad() everywhere in the loop but not between the loss.backward() and optimizer.step() operation.
Gelassen
Hello,I am new in pytorch&CUDA stack in ML and at this moment stuck on issue with error message above.Most likely the issue in uncompatibility of CUDA and NVIDIA driver as an error message says. I am working on design and train model within educational notebook so it correctness should be verified by creator. I started...
ptrblck
PyTorch needs CUDA>=9.2 so you won’t be able to compile it with CUDA7.0. That being said, if you are installing the conda binaries or pip wheels, the CUDA runtime (and cudnn etc.) will be installed so that your workstation would only need the appropriate NVIDIA driver as described in Table2 in you…
khalil
When I use DDP package to train imagenet, there are always OOM problem.I check the GPU utilization and I found there are many processes on each GPU ?What is the reason and how can I avoid this problem ?
ptrblck
This shouldn’t happen and each process should use one GPU and thus create one CUDA context. Are you calling CUDA operations on all devices in the script or did you write device-agnostic code, which only uses a single GPU?
offset-null1
Hi,I have a module Impl consisting of various registered CNN, batch norm modules. I would like to know the way to get this module’s name in libtorch.
ptrblck
You could iterate all modules and get their names via: for name, modules in model.named_modules(): print(name) # or print(model.named_modules())
amin_sabet
Hi,In my code, I want to keep the latest input feature map to the layer and subtract it with the input feature map and then update the latest value.The code is working on a single GPU, but I get the following error when running on multiple GPUs. Any thoughts?RuntimeError: Expected all tensors to be on the same device, ...
ptrblck
Sorry for forgetting the second part of the right approach.The new error is not raised by input.clone(), but should still be raised by self.latest_input, which is now on the CPU as it wasn’t properly registered. To make sure model.to() pushes all internal parameters and buffers to the desired de…
Gusto
Hi,I’m trying to create a multioutput / multihead feedforward neural network with some shared layers and two different heads.Based on a condition, the forward step should split the features such that one group of samples should go into the one head and the other group of samples should go into the other head. I’m using...
ptrblck
The indexing of the input data and “selectively” calling backward works as expected in this code snippet: class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.base = nn.Linear(1, 10) self.head1 = nn.Linear(10, 10) self.head2 = nn.Lin…
FantasyJXF
I buildtorch-1.6.0a0+b31f58d-cp36-cp36m-linux_x86_64.whlon my Tesla V100 machine, when I install thewheelpackage on my Tesla T4 machine, I met the warning like this:Tesla T4 with CUDA capability sm_75 is not compatible with the current PyTorch installation. The current PyTorch install supports CUDA capabilities sm_70.I...
ptrblck
I’ve answered in the GitHub issue.
Stonepia
Hi there,I want to write a custom convolution_backward_overrideable function with cudnn backend.It should return a tuple with std::make_tuple(grad_input,grad_weight, grad_bias).The weight and input could be handled by usingcudnn_convolution_backward_inputandcudnn_convolution_backward_weight.But according to31524, handl...
ptrblck
The bias is handled outside of the cudnn call, as it’s faster to let PyTorch add it explicitly and calculate its gradients. If you want to use the cudnn backward call, you can still usecudnnConvolutionBackwardFilterandcudnnConvolutionBackwardDatamanually.
ed-fish
I have a list of tensorst_listand I need to get the element wise sum. I am concerned that because the tensors are in a batch that my method is incorrect.Code examplet_list = [t1, t2, t3, t4] #where ti is a tensor 32 x 1 x 128 t_list = torch.stack(t_list) # giving 4 x 32 x 1 x 128 sum_list = sum(t_list) # result is 1 x ...
ptrblck
Your approach might work, but if you want to set a dim argument you could use torch.sum(t_list, dim=0).
budui
Hello,I’m performing a batch of matrix multiplication usingtorch.matmulfunction ortorch.mmfunction.but, I found that the output ofmatmulis not equal to batch ofmm, especially when the dimensions of the matrix are large.For reference, here is what I used:import numpy as np import torch def diff(x, y): x_expand = x...
ptrblck
If you calculate the relative difference using: torch_diff.max()/(x@x.t()).abs().max() you’ll get differences in the range ~1e-7 to ~1e-6, which points to rounding errors due to the limited floating point precision which are created e.g. by a different order of floating point operations.
Ethereal
Hi, this is my first time writing a Neural Network using PyTorch and I encountered the following error'Linear' object has no attribute 'log_softmax'Here’s my code:class ConvNet(nn.Module): def __init__(self): super(ConvNet, self).__init__() self.conv1 = nn.Conv2d(in_channels=3, # 224 x 224 -> 222 x 222...
ptrblck
You are accidentally returning the self.fc2 layer in your model: x = self.fc2 return x instead of calling it with x and returning the activation. Change it to: x = self.fc2(x) return x and it should work.
Ripley
Hi, I would like to ask how can i read a list of list and count the numbers of True inside?For example,tensor([[ True, False, True, False, True],[ True, True, True, True, True],[False, False, False, True, True]])How do I iterate and count the numbers of True inside the whole list?
ptrblck
You could use x.sum() to get the number of True values inside the tensor.
thiennp
I’m not sure this is a bug or not.I need to deploy the AWS elastic inference for our service. The Elastic Inference requires using CPU to load and run models.but our code runs well on GPUs, but CPU.as the simple code below, it can be run on GPUs but on CPU it returns “index out of range in self” Error.CPUs returns inde...
ptrblck
The code raises an error on the CPU as well as the GPU using the latest stable version (1.7.0). Note that assert statements in CUDA code were mostly disabled in 1.5.0 due to a bug, so that your code doesn’t raise the proper error if you are using the GPU. The reason for the error is that your weig…
kunasiramesh
Hello,I’m running into troubles while training a CAE(Convolutional Auto Encoder) model. I defined my own dataset class as follows:def make_dataset(dir, class_to_idx, extensions): label_list = [] input_list = [] dir = os.path.expanduser(dir) for target in sorted(class_to_idx.keys()): d = os.path....
ptrblck
@kunasiramesh,@GkvThe memory issue might be related to the training procedure or another part of the code. Could you post the code so that we can have a look? Usually the computation graph is unintentionally stored somewhere, e.g. by using losses += loss instead of losses += loss.item().
Toby
Hi,I met a strange bug:My model: EfficientDet-D4 (followingthis repo)While training the model, I usemodel.train(), then change it tomodel.eval()in validate step and it worked normally.However, in the test phase, my code is:from efficientdet.model import Classifier model = EfficientDetBackbone(num_classes=len(params.obj...
ptrblck
model.eval() disables the dropout and uses the internal running stats in all batchnorm layers (also custom modules might change their behavior using the self.training flag, which is changed by calling eval()). If your validation loss and predictions are bad, this might point to bad running estimate…
lisyuan
Hi, could I set the different batchsize for training and validation? The gpu ram is not enough.For example,Training: batchsize 128Validation: batchsize 1I think the batchsize of validation will not affect on the validation loss and accurancy, right?
ptrblck
Yes, you can use different batch sizes and the batch size during evaluation (after calling model.eval()) will not affect the validation results. Are you using larger inputs during the validation or why do you have to reduce the batch size by 128x?
vorlket
Hi I have the following code:https://gist.github.com/vorlkets/f38c91aa52cb4e68976e1f638d251a85. When run, I get the following error:python hw2main.pyUsing device: cpuTraceback (most recent call last):File “hw2main.py”, line 142, inmain()File “hw2main.py”, line 76, in mainloss.backward()File “C:\Users\Cliff\AppData\Loca...
ptrblck
I haven’t checked the complete code, as it’s quite long, but if you are using your custom loss definition note that the operations are not differentiable and will thus detach the loss value from the computation graph: x = torch.randn(10, requires_grad=True) ratingOutput = torch.round(x).long() cate…
robsoncs
Hello there. I’m new to PyTorch and I’m trying to utilize the ENet NN (fromgithub) to classify underwater images from SUIM dataset and evaluate its performance. Throughthis postI tried to implement the class index mapping of the masks but when I start training the network, some specific masks cause a crash on cuda. I’v...
ptrblck
In your code snippet you’ve dropped the NEAREST interpolation method again for Resize. By default a LINEAR interpolation will be used, which will create colors “between” black and red.
snowe
Hi everyoneI was wondering whether there is an easy option to access the first layer in a custom non-Sequential CNN. When the network is constructed the ‘sequential way’, you can just use:network[0]. Is there anything similar to that?Any help is very much appreciated!All the bestsnowe
ptrblck
Not a beautiful approach, but you could register forward hooks for each layer and print its name when it’s called. Based on the output you would see which layer was called first in this execution. Note that this is also not a bulletproof approach, as your forward might have conditions, loops, etc…
pytorchbearer
Dear all,I am running into a problem when training a segmentation net on Pascal VOC using multiple GPUs (DistributedDataParallel). Pytorch seems to expect targets to have label values only between 0 and n_classes–1 (inclusive). However, this does not consider the presence of the ignore label (whose value is often 255)....
ptrblck
I used theImageNet exampleand set one target value to 1001 using a single GPU and DDP. In both cases it crashed with the expected error message. After using ignore_index=1001 both runs passed.
Soori
Hi,When I check the folder of my images by below code, there is no corrupted images.but when I use a custom dataset and start to train the network this error happens during training (it does not stop the training and it will go on after that, but I do not know if it affect the parameters being trained and I wonder how ...
ptrblck
I would try to track down the image file, which is raising this error and either remove it or load and save it again to hopefully get rid of the JPEG corruption.
mbacher
Hi, I am using colab, pytorch version 1.6.0+cu101. When I try to allocate a model or a parameter to GPU I get the error below. I have tried to reproduce several tips/corrections that were listed in the forum but no one has worked so far…any ideas?Thanks!device = torch.device('cuda' if torch.cuda.is_available() else 'cp...
ptrblck
Thanks for the rest of the code. While running it I get a proper error message: RuntimeError: Tensor for argument #2 'mat1' is on CPU, but expected it to be on GPU (while checking arguments for addmm) which points to a device mismatch in Generator. After checking the code it seems that z is crea…
nore
I’m trying to use a precompiled library for custom implementations of standard routines. I’ve been looking on the internet but have not had much luck finding documentation. Does anyone know how to start/ where to look for more information?
ptrblck
You should be able to add your library to cmake as explainedhere.
Anna_yah
I changedtorch.tensor(x)totorch.tensor(x).clone().Detach()but the problem is not solved.Do you know what I am doing wrong here?Thanks in advance!for epoch in range(num_epochs): outputs = [] outputs = torch.tensor(outputs, requires_grad=True) outputs= outputs.clone().detach().cuda() for fold in range(0,...
ptrblck
The warning points to wrapping a tensor in torch.tensor, which is not recommended. Instead of torch.tensor(outputs) use outputs.clone().detach() or the same with .requires_grad_(True), if necessary.
Ohm
Hi, How can I update my model parameters while I am keeping the original one unchanged?Fix_net = model()Fix_net = Fix_net.named_parameters()NotFix_net_par = dict(Fix_net)net = model()net.load_state_dict(NotFix_net_par)…Now the Fix_net changed as well. However, I would like to update the NotFix_net_par, but keep Fix_net...
ptrblck
You could use copy.deepcopy fo create NotFix_net_par.
Anna_yah
Iused pytorch to create 3DCNNMy code works with 2 layers of conv. But does not work with 3 layers of conv.input image size:120120120Result: RuntimeError: mat1 dim 1 must match mat2 dim 0I think the problem is with this lineout = self.fc1(out)can you help me please ?thank you in advance!class CNNModel(nn.Module): de...
ptrblck
Could you add a print statement before the usage of fc1 and check the shape of the activation tensor? print(out.shape) out = self.fc1(out) I guess that out.shape doesn’t match the expected input features as 128*28*28*28 so that you might have to adjust this value in self.fc1.
NightRain
What is the most efficient way to have deterministic data augmentation (i.e. transformations every epoch are random, however they can be reproduced reliably for every data point)?Currently I am thinking of creating a list with a numpy RandomState object for every datapoint. Even if the DataLoader uses multiple processe...
ptrblck
I think one good approach would be to use the worker_id and seed all 3rd party libraries with this id. You can get the id viatorch.utils.data.get_worker_info(). PyTorch itself should yield deterministic data samples, if you’ve properly set the seed before. However, if you are using e.g. the Pyt…
Aditya1
I have re-implemented ResNet 18. I verified if the architecture is correct by printing my model and the actual pytorch resent implementation. However my resnet model does not seem to learn, what could be the reason for this eventhough printing the model shows that the archs are identical?
ptrblck
Printing the model via print(model) shows only all created modules, not the forward implementation and thus neither how the modules are used. Also all functional calls are missing from the output, which could be used in the forward. You could either compare the source codes directly (your vs. torc…
MadFrog
The data in mytrain.csvlikes this:[ [0, 0,……, 0], [0, 1,……, 0], [0, 2,……, 0], [0, 3,……, 0], [1, 0,……, 0], [2, 0,……, 0], [3, 0,……, 0], [1, 1,……, 1], [2, 1,……, 1], [1, 2,……, 1], [3, 1,……, 1], ]The training set has 800,000 rows data and the test set has 20,000 rows data.The value ofy_trainis only 0 and 1, and there are mo...
ptrblck
800,000 would then be the batch size (or the total number of samples) while 153 would be the feature dimension. In that case use self.fc1 = nn.Linear(153, any_value) self.fc2 = nn.Linear(any_value, 2) The batch size is not part of the layer definition, as all PyTorch layers accept a variable bat…
Debasmit_Das
I have been working on fine-tuning and freezing. Systematically, the method is to set torch.requires_grad = False for those parameters which are to be frozen. But is it required other than for computational reasons ? As a toy example if I want to freeze l1 and train l2 the following code should also work, right ? I don...
ptrblck
You don’t need to set this attribute if you are using the posted code snippet and l1 won’t be updated. However, I would recommend to explicitly set it in case your code tries to use the gradients of the models in any way, which might be hard to debug later on.
S.silvie
Hi all,I have trained three separate pre -trained models (squeeznet, resnet, alexnet) and I want to create an ensemble. This how my code look like but when i do model.eval(), I got the error : RuntimeError: mat1 dim 1 must match mat2 dim 0Can you please help me out? Where I am doing wrong?Thank you so much!class MyE...
ptrblck
Based on the error message I guess that the number of input features in self.classifier doesn’t match the feature dimension for x. Print the shape of x after using torch.cat and before feeding it to self.classifier and adapt the in_features if necessary.
ritesh313
Hello,I am using this in my training function:for epoch in range(num_epochs): train_mean_loss = 0 train_mean_acc = 0 rand_var = 0 for i, (train_input, train_label) in enumerate(train_dataloader): if(train_input.device != device_available): print("Train Data wasn't on cuda but now...
ptrblck
No, this won’t work and you would have to use: os.environ['CUDA_LAUNCH_BLOCKING'] = 1 at the beginning of your script. Make sure to restart the runtime and set this env var before PyTorch or any other library was imported otherwise this variable might not have any effect.
mn01
Hello - I am new to pytorch & these forums, apologies if I haven’t directed this question to the right place. Before I begin, I am using Python 3.7 and torch==1.5.0 incase either of these matter.I am struggling to take inputs forward through an arbitrary pre-trained CNN, one layer/module at a time. I understand that f...
ptrblck
You could apply all child modules, if the model would generally work in an nn.Sequential container. The model would thus have to define only nn.Modules in its __init__ method and apply these modules sequentially. However, this is often not the case and the forward method often uses functional call…
ryoukai
ErrorkeyTraceback (most recent call last): File "/home/sumeetbatra/PycharmProjects/RL Algorithms/PPO.py", line 142, in <module> train(env, device) File "/home/sumeetbatra/PycharmProjects/RL Algorithms/PPO.py", line 127, in train loss.mean().backward() File "/home/sumeetbatra/RL37/lib/python3.7/site-packag...
ptrblck
Could you post a minimal executable code snippet using your classes to reproduce this issue? Also, which PyTorch version are you using at the moment? If you are not using the latest stable version (1.7.0), could you update to it?
LearnerYme
In my network structure, I’d like to attach an additional neuron to the input of a fully connected layer, i.e. the output of its former layer has 128 neurons, and I want to let the model take another feature ( the number of rows of the input) into consideration, so I apply torch.cat((x, n_tensor), 1) in network’s forwa...
ptrblck
That’s not the case as seen in this minimal code snippet: x1 = torch.randn(2, 3, requires_grad=True) x2 = torch.randn(2, 1, requires_grad=True) y = torch.cat((x1, x2), dim=1) y.mean().backward() print(x1.grad) print(x2.grad) To verify it, you could also check the .grad attributes of your model …
salahelabyad
Is there a way in pytorch to borrow memory from the CPU when training on GPU. I am training a model related to video processing and would like to increase the batch size. This is to know if increasing batch size can improve the results of the model by better training it, especially the batchnorm3d part.I am trying to t...
ptrblck
I think Microsoft released a PyTorch package some time ago, where intermediate tensors could be pushed to the CPU temporarily to reduce the GPU memory usage. However, I can’t remember the name at the moment and don’t know if it’s still maintained. That being said, you could trace compute for memo…
stases
Hello! I am quite new to PyTorch and training DNN models in general. I’m working on audio separation and I would like to augment my dataset by cropping random overlapping segments of audio, adding noise, etc. What bothers me is how in general data augmentation works, meaning will I augment my data, save it to HDD and t...
ptrblck
Data augmentation is applied on the fly for each batch during training. If you are using a Dataset and pass it to a DataLoader with multiple workers, the data loading and processing would be executed in the background while the model is training. I would have a look attorchaudiowhich ships with…
ixombi
I’m writing a reinforcement learning program and I’m using nn.BatchNorm1d for the first time. The code trains fine but when it goes into evaluating the policy I get the “Expected more than 1 value per channel when training” error because nn.BatchNorm1d expects a batch of observations but I’m sending a single observatio...
ptrblck
You would have to call model.eval() to use the running stats in batchnorm layers and disable dropout layers.
nima_rafiee
Hifor the explanation ofshuffleas an argument to Dataloader it’s mentioned that:’ set toTrueto have the data reshuffled at everyepoch’shouldn’t it be at everyiterationor I’m missing something?
ptrblck
The indices will be shuffled for the complete dataset once per epoch and then used to create batches. Each batch will thus contain random samples and I think the documentation explains it correctly.
ydcjeff
PyTorch 1.7 debug build returns True, run with python -m torch.utils.collect_envInstalled withpip install torch==1.7.0+cu101 torchvision==0.8.1+cu101 torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.htmlfrompytorch.org.Collecting environment information... PyTorch version: 1.7.0+cu101 Is debug build: ...
ptrblck
Thanks for raising this issue. We’ll check, if this needs to be removed.
Hari_Krishnan
I’m building a model similar to a GAN, the sigmoid layer of discriminator outputs1when the discriminator gets better. This causes the loss functionlog(1 - D(Z))to become-inf. This is the code for my discriminator:class Discriminator(nn.Module): def __init__(self, hidden_size, latent_dim): super(Discriminato...
ptrblck
The gradient norm clipping wouldn’t work, since multiplying a +/-Inf gradient with the scale factor won’t change the gradient (used here). While clipping the gradient with values would work for +/-Inf values, unfortunately the +/-Inf loss might create NaN gradients as seen here: model = nn.Linear(…
skerlet_flandorle
The total loss and the inference result will be the same value every time.gpu cpu is working normallydetaset CIFAR100Please tell me if there is not enough information. I will add it.import torchimport torchvisionimport torch.nn as nnimport torch.optim as optimimport torch.nn.functional as Ffrom torchvision import datas...
ptrblck
Remove the nn.Softmax at the end of your model, as nn.CrossEntropyLoss will apply F.log_softmax internally. PS: you can post code snippets by wrapping them into three backticks ```, which makes debugging easier
ayushm-agrawal
Hello,I save my model’s initial parameters with names using the following code in a dict.for name, param in model.named_parameters(): if param.requires_grad: pre_params[name] = paramThen I save the parameters again after a single epoch into a different dict. When I try to compare if these parameters were changed ...
ptrblck
You are storing references so you might want to clone the parameters: pre_params[name] = param.clone()
Aymane_G-r
After defining my model:‘’def forward(self,x):C1=F.relu(self.CONV1(x))M1=self.MAX1(C1)C2=F.relu(self.CONV2(M1))M2=self.MAX2(C2)C3=F.relu(self.CONV3(M2))M3=self.MAX3(C3)h0= Variable(torch.zeros(2,64,500)) c0=Variable(torch.zeros(2,64,500)) Pred,(hn,cn)=self.LSTM(M3,(h0,c0))''With ‘’ summary(net, (1,4000)) ‘’ , I keep ge...
ptrblck
I think this is a known issue in torchsummary, which doesn’t seem to support RNNs as seenhere. Also, there is a fork intorch-summarywhich has apparently fixed this issue.
Jordan_Howell
Hello,I’m getting an error that I’m having trouble solving. It’s a binary classification problem on tabular data. It’s something to do with the dimension(I think ) on thelog_softmax. Below is the error.Traceback (most recent call last): File "<ipython-input-4-626b771bc4cb>", line 39, in <module> outputs = mod...
ptrblck
Your target tensor might have an additional unnecessary dimension as [batch_size, 1], so remove dim1 via target = target.squeeze(1) if that’s the case.
vahvero
Hi!I have trained a model on MonuSeg-dataset (20k unique cells and from 30 unique images) which I transformed with min/maxing to bounding boxes.rcnn_trainset927×1111 444 KBwhich I traindef create_model(pretrained=False, num_classes=2): """Creates faster rcnn 50 model Args: pretrained (bool)...
ptrblck
You can define the max. number of detections via the box_detections_per_img argument.
blackberry
I have seen some triplet loss implementations in PyTorch, which callmodel.forwardon anchor, positive and negative images; then compute triplet loss and finally callloss.backwardandoptimizer.step, something like this:anchor_embed = model.forward(anchor_images) pos_embed = model.forward(pos_images) neg_embed = model.forw...
ptrblck
When you compute the forward pass using different inputs, each output will have its own computation graph attached to it. It’s not overwritten by the next call, so there should be no problem in your current approach. You are right that the gradients are accumulated in consecutive backward calls, bu…
shamoons
If I have:self.layer1 = torch.nn.Conv1d(in_channels=512, out_channels=512, kernel_size=1)isn’t that equivalent toself.layer1 = torch.nn.Linear(512, 512)?
ptrblck
Yes, should be the case: # Setup conv = torch.nn.Conv1d(in_channels=512, out_channels=512, kernel_size=1).double() lin = torch.nn.Linear(512, 512).double() # use same param values with torch.no_grad(): lin.weight = nn.Parameter(conv.weight.squeeze(2)) lin.bias = nn.Parameter(conv.bias) # …
snowe
Hi everyoneI am currently working on a CNN project and after looking at the PyTorch tutorial (https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#) I have some questinos regarding normalization.The tutorial mentions that since the PIL images are in range [0,1], they use a mean and standard deviation of 0...
ptrblck
Yes, but the propsed method might still work “good enough” for the tutorial.I think you should be able to find a proper explaination inGoodfellow et al., Deep Learningand I’m sureBishop, Pattern Recognition and Machine Learningexplains it as well (which is also a general recommendation to t…
nicofish
I realize there are similar questions particularly this one:Could someone explain batch_first=True in LSTMHowever my question pertains to a specific tutorial I found online:Building RNNs is Fun with PyTorch and Google Colab | by elvis | DAIR.AI | MediumI do not understand why they are not using batch_first=true.image10...
ptrblck
Most likely for performance reasons. The input will be permuted in the forward method via: # transforms X to dimensions: n_steps X batch_size X n_inputs X = X.permute(1, 0, 2)
ChrisLiu2
When I run my code, this message is displayed: How can I fix it? I’m writing a neural network with pytorch-lightning and dgl with multiple optimizers, and I’m training with ddp on 1 gpu.Traceback (most recent call last): File "main.py", line 50, in <module> trainer.fit(model, train_loader, val_loader) File "/af...
ptrblck
Are you seeing the same issue without using Lightning? Also, could you post an executable code snippet so that we could reproduce this issue?
prophet_zhan
Now, we bought a 4 way rtx3090 24g GPU server, and I want to confirm there will be total 48g memory while I use nvlink to connect two 3090.If rtx3090 supports this feature, how should I change my pytorch code?Thanks.
ptrblck
No, the devices should not show up as a single GPU with 48GB. You can connect them via nvlink and use a data or model parallel approach.
YASH-ROCKY
pytorchhh888×414 12.3 KBi am getting error - size mismatch, m1: [10 x 32], m2: [320 x 564] at C:\cb\pytorch_1000000000000\work\aten\src\TH/generic/THTensorMath.cpp:41
ptrblck
The complete input batch will be used and you don’t have to specify the batch size in any layer arguments, such as the number of input features etc.
mariekiii
Hi there,I am new to Pytorch with very little understanding of programming classes. While everything worked out so far, I don’t understand the following problem now:In oder to allow my feed-forward network to process data with different input feature size, I was trying to implement an encoder, thatprocesses each featur...
ptrblck
In these lines of code: latent = torch.empty(x.shape[0], self.hidden_features, 1) for feature in range(x.shape[-1]): latent = torch.cat((latent, self.encoder(x[:,:,feature]).unsqueeze(2)),dim=2) you are appending an empty and thus uninitialized tensor to itself. Since you are not initiali…
eprox
Hi,I am getting the following error:Traceback (most recent call last): File "train.py", line 549, in <module> task.execute() File "train.py", line 271, in execute train_loss, train_acc = self.train(phase) File "train.py", line 147, in train answer = self.model(batch) File "/home/eprox/.local/lib/pyt...
ptrblck
Based on the error message it seems that the input to the embedding contains an index of 12209, while the number of embeddings is set to 4949. Could you check it via print(batch.premise.max()) and make sure the indices are in the valid range ([0, num_embeddings-1])?
zzzf
Suppose I have a machine with 8 GPUs and 64 CPUs.Using DistributedDataParallel, it will run 8 processes and each process uses a single GPU. I’m wondering how about CPUs? Are they evenly distributed across the 8 processes? Can we specify which process use how many CPUs?
ptrblck
I’ve seen approaches to set the CPU affinity for a GPU device using nvml as describedhere. However, I don’t know if and how this approach would work for a general PyTorch process and if you would benefit from it.
jagraves21
I am trying to do batch learning on a large dataset that will not fit on the GPU. I am not sure where to clear the gradients and compute the loss. Is this the correct way to use aDataLoaderand move the data to the GPU in pieces for batch learning?train_dataset = torch.utils.data.TensorDataset(X_train, y_train) train_...
ptrblck
Yes, in that case you shouldn’t zero out the gradients in each iteration and note that each backward() call would accumulate the gradients. In batch training the gradients are usually calculated using the mean, so you might also need to scale the gradients before applying the optimizer.step() operat…
ChrisLiu2
Hi, I have a situation in my neural network that I don’t know how to handle, can someone help me get this straight?I’m implementing a new graph pooling layer, and this graph pooling layer will be inserted between graph conv layers. However, the learnable components in the pooling layer uses a completely different loss ...
ptrblck
You can pass subsets of parameters to an optimizer while creating it, which makes sure that the optimizer only updates these parameters.
peepeepoopoo
I’m wonder how one could be able to do something like this in pytroch:for example I want to initalize 64 copies of nn.Conv.2d, I tried to call a for loop and store the network like this:self. conv_array = [] for i in range (64): self. conv_array.append(nn.Conv2d(1, 16, stride=2, kernel_size = 2))This apparentl...
ptrblck
Use nn.ModuleList instead of a Python list to register these modules properly.
Sakhiwo_Mtwenka
Hi ThreHow do I fix the below error:NotImplementedError Traceback (most recent call last) <ipython-input-2-db4fff233cd4> in <module> 6 input = torch.rand(5,3) 7 print(input) ----> 8 out = model(input) 9 for epoch in range(2): 10 running_loss = 0.0 ~\Anaconda3\lib\site-p...
ptrblck
You have a typo in forward (you are using foward), so you would need to fix this. Once this is done, remove the nn.Softmax, as nn.CrossEntropyLoss expects raw logits. PS: you can post code snippets by wrapping them into three backticks ```, which makes debugging these issues easier.I’ve formatte…
svrc
I am trying to install pytorch from source because my gpus compute capability is 3.0. I get the error below for different files each time. Also, there is a warning at the beginning.These are installed:nvidia driver: 418.113cuda: 10.1cudnn: 8.0.4.30I followed the instructions onhttps://github.com/pytorch/pytorch#from-so...
ptrblck
I don’t think you can compile for compute capability 3.0, as __ldg() is defined for >=3.5 as describedhere.
grizzlycoder
Hello,I am working on trying to run the training module from (traini3d.py) :https://github.com/piergiaj/pytorch-i3don my own dataset of videos (they do it for Charades).With some help, I have successfully gotten a Dataset module functioning to extract features. Now, in the training module, I have a dimension issue her...
ptrblck
Depending on your use case you could either change the model to output a prediction for the whole sequence or alternatively change your data loading logic to return labels for each time step in the sequence. Currently you are trying to mix both approaches, i.e. you are using a single label for a mo…
TUM
Hi there,I want to implement a class of sparse neural networks, the picture is an example for the class H_0 for the parameters d = 5, d_star = 1, M_star = 2.This network class works kind of good, but when I use a random uniform distributed values as input, I get always an almost constant output (untrained).When I train...
ptrblck
Not necessarily and you could check all intermediates to have a look what is “happening” in the model: class smallDense(nn.Module): def __init__(self, d, d_star): super(smallDense, self).__init__() self.fc1 = nn.Linear(d,4*d_star) self.fc2 = nn.Linear(4*d_star,1) def forward(sel…
bing
Hi,I am trying to perform stratified k-fold cross-validation on a multi-class image classification problem(4 classes) but I have some doubts regarding it.According to my understanding, we train every fold for a certain number of epochs and then calculate the performance on each fold and average it down and term it as a...
ptrblck
Yes, you are resetting the hyperparameters and are training a new model in each iteration. k-fold CV gives you a better “unbiased” estimate of the generalization performance of your model.@rasbtexplains this techniqueshereand also compares it to other hold-out methods. Often you would u…
krishna511
I just started coding in Pytorch. I have converted my wav files into text using glob library. But now I want to split that text file into train and test. Actually the dataset is very small and imbalanced. To be more clear it has 7 classes in file name only. But different classes have different samples like 100, 50 etc....
ptrblck
If you want to randomly split your Dataset, you could use torch.utils.data.random_split. Alternatively, if you want to apply a stratified split, you could usesklearn.model_selection.train_test_splitand pass the targets as the stratify argument.
Tomojit
Hello - I’m working on a Convolutional Autoencoder model where I’m optimizing one cost on output layer and other cost on the bottleneck layer. Please see the picture below(I took it from a published paper). Please note I’m not minimizing any clustering loss on the bottleneck layer. My cost is a different one. I know h...
ptrblck
As long as you are using PyTorch operations Autograd would be able to create the computation graph and calculate the gradients of the loss w.r.t. to all parameters in this graph. You can verify it by checking the .grad attributes of all encoder parameters before the first backward call (should be N…
Marceline
I’m using Detectron2 with pretrained COCO-PanopticonSegmentation model on a GTX960. But as you can see, it’s barely using any resources. (That spike you see is me opening the screenshot utility)image810×587 24.4 KBThus, the inference is taking ages, even on Colab.What could be going wrong?What should I read to fix it?
ptrblck
The Windows Task Manager doesn’t show the compute workload by default, if I’m not mistaken, so you should either select another view from the drop down menu or use nvidia-smi to check the GPU utilization.
Kiki
Hello, I’m new at pytroch and I’m currently working on my first cnn for image recognition. My images have the size 28*28 and are gray, so they have a channel of 1. I get a message every time that i have a size mismatch. I can’t figure out what is wrong. Can anyone help me? IError Code:Traceback (most recent call last):...
ptrblck
Check the shape of the activation after flattening it and before passing it to self.fc1: x = torch.flatten(x, 1) print(x.shape) This should give you a shape as [batch_size, num_features], where num_features should be equal to the input features of self.fc1. Based on the error message you are seei…
Leockl
I am running a PyTorch ANN model (for a classification task) and I am using skorch’sGridSearchCVto search for the optimal hyperparameters.When I runGridSearchCVusingn_jobs=1, it runs really slowly.When I setn_jobsgreater than 1, I get a memory blow-out error. So I am now trying to see if I could use PyTorch’sDataLoader...
ptrblck
The linked post mentions to wrap the Dataset into SliceDataset, not the DataLoader, which cannot be directly indexed. I don’t know about the skorch internals and don’t know, if this would solve your issue, but this explains the raised error.
Bahaa_Kattan
I got this error while working with text datasetfor text, labels in trainloader: clf.train() output = clf(text).squeeze() # compute loss function loss = loss(output, labels.float()) print(loss)here is the full codetext = pd.read_pickle('seq_df.pkl') print(text[:5]) # [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...
ptrblck
You are overwriting the loss criterion name with the loss output tensor of the criterion, so that the next iteration will fail: # first iteration # loss is the criterion here loss = loss(output, labels.float()) # loss is a tensor from here on # second iteration # this will raise this error, since…
SAI_VARSHITTHA
In the following,x_6 = torch.cat((x_1, x_2_1, x_3_1, x_5_1), dim=-3) Sizes of tensors x_1, x_2_1, x_3_1, x_5_1 are torch.Size([1, 256, 7, 7]) torch.Size([1, 256, 7, 7]) torch.Size([1, 256, 7, 7]) torch.Size([1, 256, 7, 7]) respectively. The size of x_6 turns out to be torch.Size([1, 1024, 7, 7])I couldn...
ptrblck
Negative dimensions start from the end, so -1 would be the last dimension, -2 the one before etc.: [1, 256, 7, 7] pos dim: 0, 1, 2, 3 neg dim: -4, -3, -2, -1 If you are passing dimensions outside of this range, you should get an error: IndexError: Dimension out of range (expected to be…
hadaev8
I want to use feature dropout like dropout2d and fill it with mean value (or Gaussian noise for example) instead of zeros.How to do so?Easiest thing to do is runing dropout2d and fill zeros, but i have zeros in data.
ptrblck
It depends, what you want to achieve. The original mask before the unsqueeze and expand operations can be used to index x directly, which would yield: x = torch.ones([1, 167, 128]) batch_size, length, features = x.size() p = 0.5 mask = torch.distributions.Bernoulli( probs=(1 - p)).sample((batc…
adityamnk
This is my first time in these forums. Hence, please let me know if I could describe my issue with more clarity. I am only running on CPU right now, but will move on to powerful GPUs once I get it to work on CPU. I am using pytorch 1.6.0.My intention is to use LBFGS in PyTorch to iteratively solve my non-linear inverse...
ptrblck
Thanks for the code. self.rec = torch.nn.Parameter(torch.from_numpy(init)) is creating a tensor, which is not contiguous due to the moveaxis operation on the numpy array. Use: self.rec = torch.nn.Parameter(torch.from_numpy(init).contiguous()) and the code should work. You can add code snippets …
xiangyu_tang
I have an RTX 3080 and I want to use it to train a deep learning model. Both CUDA and Pytorch I installed are version 10.2. However, when I train this deep learning model, it freezes when loaded into CUDA. Is there any solution?
ptrblck
If you’ve installed the CUDA10.2 binaries, the first CUDA operation would call into the JIT and compile the kernels for your compute architecture. You could use the nightly binaries, which are build with CUDA11 and support sm_80 via: conda install pytorch torchvision cudatoolkit=11.0 -c pytorch-ni…
Hacking_Pirate
def build_model(n_features, n_features_2, n_labels, label_smoothing = 0.0005): input_1 = layers.Input(shape = (n_features,), name = 'Input1') input_2 = layers.Input(shape = (n_features_2,), name = 'Input2') head_1 = Sequential([ layers.BatchNormalization(), layers.Dropout(0.2), ...
ptrblck
For a general introduction to writing custom PyTorch models, have a look atthis tutorial. To convert the TF model to PyTorch you should initialize all modules in the __init__ method of your custom model and use these modules in the forward method. The layers are almost equivalently named, i.e. la…
ptrblck
You could iterate all modules and register hooks with them as seenhere.I’m not sure, if there is another cleaner way of checking for “layers” besides the used if condition.
ptrblck
You are trying to access an undefined key 'fc[0]' in print(activation['fc[0]']), while you are registering the hook with 'fc'. Also, you are registering the hook after the forward pass, so you would have to rerun the forward pass to store the activation or register the hook before the first forward…
Huseyin
class GraphConvolution(nn.Module):def __init__(self, in_features, out_features, dropout=0., act=F.relu): super(GraphConvolution, self).__init__() self.in_features = in_features self.out_features = out_features self.dropout = dropout self.act = act self.weight = glorot_init(in_features, out_featu...
ptrblck
I cannot reproduce the slowdown using your (partial) code snippets and get approx. 0.0152s/iter for CPU and 0.00044s/iter for a GPU run using: import torch import torch.nn as nn import torch.nn.functional as F import time class GraphConvolution(nn.Module): def __init__(self, in_features, out_f…
paganpasta
Hi, I wanted to implement a pytorch equivalent of keras code mentioned below.self.regularizer = self.L2_offdiag(l2 = 1) #Initialised with arbitrary value Dense(classes, input_shape=[classes], activation="softmax", kernel_initializer=keras.initializers.Identity(gain=1), bias_initializer="zeros",kernel_reg...
ptrblck
The bias parameter is automatically added to nn.Linear, if you don’t explicitly set bias=False in its creation. To add a regularization term for the weight parameter, you could manually add it to the loss: output = model(input) loss = criterion(output, target) loss = loss + torch.norm(model.layer.…
savvas17
Good day all,I know there have been many answers for similar questions, however I havn’t found a solution. My cuda_is_available() is returning False, but weirdly it used to return True with the same configuration. The code is running on a GPU cluster. I was wondering if any people wiser than me can identify anything wr...
ptrblck
After e.g. a driver change, the nvidia-smi output might still be valid, but CUDA programs might not work properly and thus you should restart the system. As a test you could compile any CUDA sample and run it. Since other conda envs are also not working, I assume that someone might have indeed chan…
peepeepoopoo
I’m currently trying to replace values AxBxC matrix with given array of indexes and corresponding values.for example I have an index array [[0,1], [1,0], [3,4]] for a 6x6x4 matrix, with corresponding value [[1,1,1,1],[2,2,2,2],[3,3,3,3]]. I’d like to replace the values in the 6x6x4 matrix at [0,1,:], [1,0,:], and [3,4,...
ptrblck
This should work: A, B, C = 6, 6, 4 x = torch.zeros(A, B, C) idx = torch.tensor([[0,1], [1,0], [3,4]]) val = torch.tensor([[1,1,1,1],[2,2,2,2],[3,3,3,3]]).float() x[idx[:, 0], idx[:, 1]] = val print(x) > tensor([[[0., 0., 0., 0.], [1., 1., 1., 1.], [0., 0., 0., 0.], …
JamesDickens
If I have an even sized convolutional filter, say 2 by 2, f_{i,j} for 1<= i <=2, 1<= j < = 2Then if I apply it to a window centered at (x,y) (assuming appropriate padding),then will it apply something likef_{1,1} (x,y) + f_{1,2} (x+1, y) + f_{2, 1}(x, y+1) + f_{2,2}(x+1, y+1) in Pytorch?I’m not sure what the formula w...
ptrblck
I’m not sure what your notation means exactly, but you could use a simple example as given here: weight = torch.ones(1, 1, 2, 2) x = torch.arange(4*4).view(1, 1, 4, 4).float() print(weight) > tensor([[[[1., 1.], [1., 1.]]]]) print(x) > tensor([[[[ 0., 1., 2., 3.], [ 4., …
eyeris
I am struggeling to determine a cause for following behavior of 3 class classification code I have below. The classifier takes a 2D matrix oftorch.Size([1, 1, 512, 512]). The output istorch.Size([256, 3]).class Classifier(nn.Module): def __init__(self): super(Classifier, self).__init__() self.laye...
ptrblck
The view operation is wrong and will change the batch size. Use out = out.view(out.size(0), -1) instead and set the in_features of self.fc1 to 128*128*64.
Ashutosh_Mishra
I have written a custom dataset class to load an image from a path along with two transform functions as given below:class TestDataset(torch.utils.data.Dataset): def __init__(self, root, split, transform=None): self.image_path = list() for (dirpath, dirnames, filenames) in os.walk(root + split): self.i...
ptrblck
It’s not completely identical, since you are using *args instead of img, which will unwrap the image tensor. I.e. the error is raised in the second transformation, which will use args to pass an image tensor in the shape [channels, height, width] to Normalize. Using t(*args) will unwrap the image …
trkylmz
I am trying to implement binary classification. I have 100K (3 channel, 224 x 224px pre-resized) image dataset that I am trying to train the model for if picture is safe for work or not. I am data engineer with statistician background so I am working on the model like last 5-10 days. I have read many answers fromptrblc...
ptrblck
The last squeeze() operation is most likely not needed (x = x.squeeze(1)), but might be alright if your target has the same shape ([32]). Could you try to overfit a small data samples, e.g. just 10 samples and see if your model is able to do so by playing around with some hyperparameters. I think …
bender
I am trying to perform a multi dimensional slice operation on a Tensor to obtain a ROI using the following code:// Image resolution is 800x600 cv::Mat img = cv::imread("test.png"); auto img_tensor = torch::from_blob(img.data, {img.cols, img.rows, 3}, torch::kByte); auto slice_tensor = img_tensor.index({ torch::indexin...
ptrblck
Yes, more or less. I think this shape and thus also the slice might be wrong: {img.cols, img.rows, 3} OpenCV should use a [height, width, channels] layout, so shouldn’t it be {img.rows, img.cols, 3}?
Leockl
I have an ANN model (for a classification task) below:import torch import torch.nn as nn # Setting up artifical neural net model which separates out categorical # from continuous features, so that embedding could be applied to # categorical features class TabularModel(nn.Module): # Initialize parameters embeds, ...
ptrblck
I guess the NeuralNetBinaryClassifier expects the output to have one logit, since it’s used for a binary use case. If you want to use two output units for a binary classification (which would be a multi-class classification with 2 classes), you would have to use another wrapper I guess. I’m not de…
vulfgang1
I am following this tutorialhere. When I try to run the code to get the output image I get this error:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [1, 128, 385, 256]], which is output 0 of AddBackward0, is at version 2; expected ve...
ptrblck
Replace the inplace operations such as style_score *= style_weight with their out-of-place versions and rerun the code.
JamesDickens
I have a tensor of shapez = (38, 38, 7, 7, 21) = (x_pos, y_pos, grid_i, grid_j, class_num), and I wish to normalize it according to the formula:I have produced a working example of what I mean here, and the problem is that it is extremely slow, approximately 2-3 seconds for each grid entry (of which there are 49, so 49...
ptrblck
This should work: x = random_score_map.clone() s = (x**2).sum(4, keepdims=True) n = torch.sqrt(s) x /= n print(torch.allclose(x, score_map)) > True Note that you should avoid for loops where possible and try to use vectorized code instead.
JonathanSum
image1174×598 63.6 KBaren’t the model and its weights automatically saved in Pytorch lighting?
ptrblck
The events... file should be created by tensorboard, while the second file seems to contain some hyperparameters, not the state_dict. Since I’m not deeply familiar with Lightning, CC@williamFalcon.
111394
Hi I am a pytorch newbieI tried 3D deeplearning and I got first batch’s outputs and labels.outputs : torch.Size([32, 4])labels : torch.Size([32, 4])outputs : tensor([[ 0.6386, 0.8804, 0.0802, -0.6856],[ 1.5065, 0.8598, 1.0433, -2.3924],[ 0.0379, 3.3215, -0.5928, 0.2159],[ 0.9913, 3.5304, 0.0685, -1.3560],[-...
ptrblck
Your posted labels tensor only contains class0 and class1, so the output is expected.
Mona_Jalal
I am trying to pass Normalize to images but since it only works on single image I am using a syntax like below:for image in images: image = norm(image)This is the error I am getting:--------------------------------------------------------------------------- RuntimeError Traceback (m...
ptrblck
This error is raised, if you try to normalize a ByteTensor or LongTensor with floating point numbers. Transform your image to a FloatTensor via image = image.float() before applying the normalization and it should work.
Mona_Jalal
I need to normalize my train set in the following code:network = Network() network.cuda() criterion = nn.MSELoss() optimizer = optim.Adam(network.parameters(), lr=0.0001) loss_min = np.inf num_epochs = 1 start_time = time.time() for epoch in range(1,num_epochs+1): loss_train = 0 loss_test = 0 ru...
ptrblck
You are passing the transforms.Normalize object to the network instead of applying it on the input data. Pass the input to transforms.Normalize and pass the return value to the model.
Alan_Wang
Suppose forward passes are performed multiple times through a single model within a for loop, but only a single backward pass is called. Can PyTorch handle this scenario? Do the intermediate values of the forward pass get overwritten with each new forward pass, thus rendering the backward pass incorrect? Or does PyTorc...
ptrblck
Your approach would calculate the gradients of the used model parameters w.r.t. the “lowest loss”, i.e. sort_losses[0]. Note however, that all computation graphs (with all intermediate activations) will be stored during the execution of the loop, which will of course increase the memory usage. Als…
s_roy
I am new to Pytorch, Kindly help to understand error.class LSTMClassifier(nn.Module):def __init__(self, input_dim, seq_size, hidden_dim, label_size, batch_size, bidirectional, num_layers): super(LSTMClassifier, self).__init__() self.input_dim = input_dim self.seq_size = seq_size self.hidden_d...
ptrblck
The linear layer is raising this error, as the number of input features from the activation doesn’t match the in_features from the layer. Check the shape of lstm_out and make sure it’s [batch_size, *, in_features]. PS: I would also be careful with using torch.squeeze without specifying the dim arg…
deJQK
I am trying to usetorch.conv2dortorch.nn.functional.conv2dwith groups specified, but it reports runtime error. The code is something like this:a = torch.rand(4, 3, 8, 8) b = torch.ones(3, 3, 3) out = torch.conv2d(a, b, groups=3)The error is something like this:RuntimeError: expected stride to be a single integer value ...
ptrblck
3 groups with a filter using in_channels=3 would need 9 channels. Thegrouped conv sectionor the docs give you more information on the usage of the groups argument. If you want to process each input channel separately, use: input = torch.rand(4, 3, 8, 8) weight = torch.ones(3, 1, 3, 3) out = tor…
Mona_Jalal
Could you please walk me through how to fix this?I also don’t know how to use PyTorch to find the mean and std and add it in the Normalize as args.The error is:size of train loader is: 12 images shape: torch.Size([64, 600, 800, 3]) landmarks shape: torch.Size([64, 8]) -----------------------------------------------...
ptrblck
You are passing the input images as “channels-last” (NHWC), while PyTorch expects “channels-first” (NCHW). permute the input batch such that the channels are in dim1.