user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
bellos1203 | As far as I know, the random transformations (e.g. random crop, random resized crop, etc.) fromtorchvision.transformsmodule apply the same transformations to all the images of a given batch.Is there any efficient way to apply different random transformations for each image in a given mini-batch?Thanks in advance. | ptrblck | I think you would need to apply the random transformations on each sample and could use e.g. transforms.Lambda for it:
# setup
x = torch.zeros(3, 10, 10)
x[:, 3:7, 3:7] = 1.
# same transformation on each sample
transform = transforms.RandomCrop(size=5)
y1 = transform(x)
print(y1)
# apply transfor… |
algeriapy | Hi Dears,I created the following architecture which has one main branch, but in the decision layer it has two braches where resnet FC layer is shared:class Net1(nn.Module):
def __init__(self, in_features, out_features):
super(Net1, self).__init__()
self.in_features = in_features
self.out_fe... | ptrblck | It shouldn’t influence the training at all, if you are just calling its forward without using any output. |
VladimirK | I have GT 710. It has compute capability of 3.5. This means that if I want to use PyTorch with a GPU, I have to build PyTorch from source.I have already made several attempts but unsuccessfully. I didn’t expect the build process to take hours, in addition CPU is 100% busy. I work on Windows and this makes the installat... | ptrblck | You can pick any PyTorch tag, which would support your setup (e.g. CUDA9.2). The currently required min. CUDA toolkit version is 10.2, so you should double check if PyTorch 1.6.0 supports 9.2. Yes, the release/1.6 branch is correct. You could alternatively use git checkout v1.6.0.
The different… |
J_Johnson | I was going through the Python source code for the ConvNd modules and seem to have hit a dead end.What I am wondering is how the convolutions are being calculated. I.e. if we have the weights and input image, how are these being shaped/multiplied?Is it done by reshaping the kernel to a classic Toeplitz matrix and then ... | ptrblck | Yes, a matmul approach will be used for the native implementations as givenhere. Different backends (e.g. cuDNN) could call different algorithms internally, which depend on the workload shape etc. |
Torcione | I have a generic network without random element in his structure (e.g. no dropout) so that if I forward a given image input through the network, I put gradient to zero and repeat again the forward with the same image input I get the same result (same gradient vector, output,…)Now let’s say that we have a batch of N ele... | ptrblck | I don’t think the answer from the cross-post is correct, as your code doesn’t show any optimizer.step() usage so I assume you are purely comparing the gradients computed via using the entire dataset vs. single samples.
If so, I would assume the final difference would show a relative error of ~1e-5 … |
Mole_m7b5 | Hi,I’ve got a CRNN that I’m using on an audio task and I want to have it set up so I can change the size of the matrix being fed into the CNN (different resolution spectrograms etc.) and not have to change any of the code in the model - however, the input to the RNN depends on the size of the CNN output. Is there a way... | ptrblck | Yes, reinitializing the module is the wrong approach and you should register it only once. Take a look atthis postas well as the linked docs to check how to use the lazy module approach properly. |
prog_asker | I need to ensemble the features only that help in classification which I can extract it from two different models . So I need to remove the last layer first from each model then start to concatenate them … how can the ensemble method will be ? | ptrblck | You could replace the last linear layers with nn.Identity modules and create the ensemble as described inthis post. |
MartinZhang | A question about how to translate torch::tensor type into base type in c++?Such as:torch::Tensor(False) -> bool(False);
torch::Tensor(123) -> int(123);
torch::Tensor(3.1415) -> double(3.1415);or like tensor function:int a = torch.tensor(123).data // there is not data elemenetplease help me, Thanks. | ptrblck | int a = torch.tensor(123).item<int>(); should work. |
LeoSerena | Hello.In the context of a central server and several nodes that all have a similar model with different weights, I compute and back-propagate the loss of a norm on the weights on the central model given all the updated nodes models. I want to compute the gradient norm of the difference between the central model and the... | ptrblck | You could probably use grads = torch.autograd.grads which would return the gradients directly instead of using reg.backwar(). |
MartinZhang | there is a question about how to create a torch::Tensor constant in cpp?I have some data table, like this:const int a [] = {123, 456, 789};but now , I want to translate the type ofainto torch::Tensor, such as#include <torch/extension.h>
torch::Tensor a = {123, 456, 789};in this linkhttps://pytorch.org/cppdocs/api/cla... | ptrblck | from_blob should work:
float data[] = {1, 2, 3, 4, 5, 6};
auto f = from_blob(data, {1, 2, 3});
Make sure the data is alive as long as you are using f or clone() the data. |
umfengxx | Hi guys, my model can only work with pytorch <=1.1.0, unfortunately pytorch 1.1.0 can’t work with CUDA 11, which is needed in new GPU card like Nvidia A100 and 30xx series.When I tried to use pytorch 1.7 + CUDA 11, my trained model will produce strange noise in output images. Model trained on pytorch 1.1.0 is OK, mode... | ptrblck | You could skim through the release notes for each released PyTorch version and check which changes might affect your training. I would probably start with backwards compatibility breaking changes and see, if fixing these might help.
You would have to search for all CUDA 11.x related PRs and try… |
Sumera_Rounaq | I am training CGAN for generating Xray images.My training initializations are as follows:criterion = nn.BCEWithLogitsLoss()
training samples = 1200
n_epochs = 600
z_dim = 100
batch_size = 50
lr_gen = 0.0002
lr_disc = 0.0001This is the loss graph after 500 epochs. I am not able to interpret whether training is working f... | ptrblck | The losses would indicate that the discriminator is successful in differentiating fake from real examples (thus the discriminator loss is low) while the generator has trouble creating images which the discriminator would classify as “real” images. |
Johnson | What should I do to deal with this problem?Thank you very much in advance! | ptrblck | I’m not sure if this issue might be Windows-specific, but could you update PyTorch to the latest nightly release and check, if this might have been an already known and fixed issue, please? |
blade | I’m trying to run a test code on GPU of a remote machine. The code isimport torch
foo = torch.tensor([1,2,3])
foo = foo.to('cuda')I’m getting the following errorTraceback (most recent call last):File “/remote/blade/test.py”, line 3, infoo = foo.to(‘cuda’)RuntimeError: CUDA error: out of memoryCUDA kernel errors might ... | ptrblck | It’s hard to tell what might be the root cause, as it was working before and I don’t know what has changed.
I don’t believe there is a PyTorch-related fix, as the error points towards a setup issue.
You could try to test other environments (e.g. create a new conda env, reinstall PyTorch, and check… |
Mohammad_Elias_AlHus | I’ve changed the number of input channels in DeepLabV3, because I have NRGB image (N=NIR=Near infrared), the next step is I have to duplicate the weights for the Red channel to make the model be fully pre-trained.Any ideas ?import torch
import torch.nn as nn
class MyDeepLab(nn.Module):
def __init__(self, in_chann... | ptrblck | This code should work:
class MyDeepLab(nn.Module):
def __init__(self, in_channels=1):
super(MyDeepLab, self).__init__()
self.model = torch.hub.load('pytorch/vision:v0.5.0', 'deeplabv3_resnet101', pretrained=True)
with torch.no_grad():
conv_weight = self.mod… |
Karthik_Ganesan | What’s a nice way to get all the properties for a given layer type, maybe in an iteratable way?For example, for annn.Linearlayer, I am reading currently getting them as:for name, layer in model.named_modules():
if isinstance(layer, nn.Linear):
in_features = model._modules[name].in_features
out_featu... | ptrblck | You could check if the .__dict__ or dir() approach would work for you:
lin = nn.Linear(1, 1)
print(lin.__dict__)
print(dir(lin))
However, both approaches would still need some parsing, checks, etc. since a lot of internals would be printed. |
Forceless | Steps to reproduce:Load an alexnet from torchvisionChange model’s first weight to torch.tensor(float(‘inf’))Register forward hook and check the output of first conv layer and first ReLu layerI speculate this bug was caused by torch’s measure to inf valueScreen Shots:Conv Layer’s output and another parameter:image1096×4... | ptrblck | AlexNet uses inplace nn.ReLU layers as seenhere, which would explain your observation. |
James_e | I have a question regarding the.backward()calls in the DCGAN tutorial.When training the discriminator, an error for the real data,errD_real, and an error for the fake data,errD_fake, is calculated. Each of these have.backward()called on thembeforethe.step()method is called on the optimiser.How does this work? Would the... | ptrblck | No, each backward call accumulates the gradients in the .grad attribute of the used parameters, which is also why you have to call optimizer/model.zero_grad() before calculating the gradients of a new iteration. |
flpgrz | If you want to freeze a sub-module of an nn.Module object (e.g. you want to freeze some layer of a NN), what’s the difference between:A)model.layer_to_freeze.eval()B)model.layer_to_freeze.requires_grad_(False)?Thanks | ptrblck | train()/eval() will change the behavior of some layers and are used during training and evaluatio, respectively. E.g. batchnorm layers will use the running stats to normalize the input during evaluation instead of the input activation stats and dropout layers will be disabled during evaluation.
Set… |
deutschgraf | Hi all!Does Pytorch supports CUDA 11.4 toolkit? Or could I build pytorch with cuda 11.4 support? | ptrblck | Yes, you can build PyTorch from source using all released CUDA versions between 10.2 and 11.5. |
pepper8362 | Hi,I find there is slight difference between the calculation results of nn.BatchNorm2d.forward() and torch.Tensor. Specifically, If I run the following code:import torch
import torch.nn as nn
bn = nn.BatchNorm2d(10)
# feed data to update running_mean and running_var
for _ in range(100):
dummy_data = torch.randn(8... | ptrblck | Your calculation looks correct the the small absolute error points to the floating point precision limitation, which is expected. In case you need to get a lower error, you could use float64 as the dtype. |
jsetty | Hi, I have a huge network with some Deformable CNNs (torch.ops.torchvision.deform_conv2d) in it. I am using apex 0.1, Cuda 11, and torch 1.11. I have set the optimization level to O1 for mixed-precision training.I have used nn.DataParallel and also cast the model to GPU properly. Unfortunately, I have this error. Could... | ptrblck | I guess you might be using an older torchvision release, since the operation is available via torchvision.ops.DeformConv2d andthis PRadded autocast support ~1 year ago.
This code snippet works fine for me:
from torchvision import ops
deform_layer = ops.DeformConv2d(in_channels=3, out_channels=6… |
AreTor | Does the equivalent oftorch.uniqueexists in the libtorch C++ backend? So far, I have not found it yet. | ptrblck | You could use at::_unique in libtorch. |
Ahmad_Pouramini | I have a wrapper for a huggingface model. In this wrapper I have some encoders, which are mainly a series of embeddings. In forward of the wrapped model, I want to call forward of each of encoders in a loop, but I get the error:Traceback (most recent call last):
File "/home/pouramini/mt5-comet/comet/train/train.py", ... | ptrblck | Assuming the error is raised in one of the prompt_encoders, check of their internal modules are already pushed to the device and if not either call model.to('cuda') on the entire model or on each of the prompt_encoders. |
astroboy | I have a question regarding model saving in PyTorch. Let’s say you run a series of experiments and change the code gradually during the project. However, if I save the model state_dict, I would need the exact source code to use the previous pre_trained models. Is there any good way to save a PyTorch model with just eno... | ptrblck | Yes, your assumption is correct and saving the scripted model would allow you to reload it afterwards without the need to keep the source code.
However, as you’ve also mentioned you might need to add some changes to make the model “scriptable”. Depending on this effort, storing the source code for … |
krishna511 | Hi there I am training a model for the function train and test given here, finally called the main function. I need to see the training and testing graphs as per the epochs for observing the model performance. Can someone extend the code here?import torch
from torch.utils.data import DataLoader as DL
from torch import ... | ptrblck | You could return the tensors or numpy arrays containing the loss values from the train and test functions and plot it in a single plt.plot in the main script. |
jimmpy | Why the loss function is always printing zero after the first epoch?I suspect it’s because ofloss = loss_fn(outputs, torch.max(labels, 1)[1]).And if if I useloss = loss_fn(outputs, torch.max(labels, 1)[0]), I will get some values that are too high and I’m not sure if they make sense, like: 1200,800,600,500(one value fo... | ptrblck | Your labels tensor seems to already contain class indices but has an additional unnecessary dimension.
The right approach would be to use labels = labels.squeeze(1) and pass it to the criterion.
Using torch.max(labels, dim=1)[0] would yield the same output.
However, torch.max(labels, dim=1)[1] w… |
mostafaelaraby | I was wondering if gradients are scaled from fp16 to fp32 before all reducing as in Apex Distributed data parallel default flagallreduce_always_fp32.Also what is the equivalent ofdelay_allreducein torch.nn.distributed.DistributedDataParallel ? | ptrblck | I wouldn’t assume to see any automatic transformation of gradients if no ddp hooks etc. are used.
The native mixed-precision training util. via torch.cuda.amp uses FP32 parameters and thus also FP32 gradients.
You could try to increase the bucket_cap_mb to kick off the gradient sync later, if need… |
DDavid | >>> out = torch.randn(100,100)
>>> out.cuda()
>>> torch.cuda.memory_allocated(0)
40448
>>> out1 = torch.randn(100,100)
>>> torch.cuda.memory_allocated(0)
0Why is this happening? I expected the output of totorch.cuda.memory_allocated(0)be 40448 still, becauseout1is totally different toout.Note that,>>> id(out)
139989884... | ptrblck | The underscore (_) is a special variable which will get the output of the last operation as seen here:
a = 5
a
Out[2]: 5
6
Out[3]: 6
_
Out[4]: 6
_ + _
Out[5]: 12
If you are stepping through the code in a REPL env I would guess that in particular this variable can hold a reference to the CUDATe… |
joey.s | Hi, I have some questions:1- Can I perform model.train() and model.eval() separately, each of them in an independent script? or this will affect the model performance and they have to be called respectively?2- In case that we can perform only the training: after saving a checkpoint for each epoch during the training, c... | ptrblck | Yes, you can write own scripts for the training and evaluation of the model. Make sure to load the state_dict properly before starting the evaluation.
Yes, that should be possible. |
afsaneh_ebrahimi | I want to replace average pooling in one architecture with DC part of DCT transformation, but when I replace this with each other I got nan values for loss.This is my DCT transform over all channels:def dct3(self, x):
X1 = dct.dct_3d(x[0])
X2 = dct.dct_3d(x[1])
a = torch.stack([X1,X2], 3)
for i in range... | ptrblck | Could you post the code of dct.dct_3d or check, if you might be dividing by zero or any other operation which could cause invalid outputs? |
Hongnan_G | I have trouble loading batch size of 32 for the pretrained modelswin_large_patch4_window7_224from thefamous timm library. With mixed precision on, other people’s (I will link their code) pipeline can easily fit 32 batch size without CUDA OOM, but mine cannot. In order to debug this, I first ran through my code line by ... | ptrblck | I don’t think you are seeing a memory leak, but are allocating additional memory.
E.g. in your train_one_epoch you are using a pure FP32 forward pass and another one wrapped in autocast:
# Iterate over train batches
for step, data in enumerate(train_bar, start=1):
# un… |
Rami_Ismael | I wonder whether a quick method that checks if the same model will have the same weight. | ptrblck | You could iterate the parameters of both models and compare them:
for a, b in zip(modelA.parameters(), modelB.parameters()):
if not (a == b).all():
print('False')
break
Of course you can add more checks (e.g. for the shape etc.).
Also, the loop assumes the parameters are initi… |
thomas | In a project, I have a tensor that is in the shape [N, M] and I would like to reshape it to a [I, J, M] while reordering using another tensor. I am not sure how to get this result. I have looked into gather, index_select but it doesn’t seem to fit my case. (I did a 2D case below, but in my project I would like to apply... | ptrblck | This should alternatively work:
out = torch.zeros(indices[:, 0].max()+1, indices[:, 1].max()+1, x[0].size(0)).long()
out[indices[:, 0], indices[:, 1]] = x
print(out)
> tensor([[[ 7, 8, 9],
[ 1, 2, 3]],
[[ 4, 5, 6],
[10, 11, 12]]]) |
Lady_Hangaku | I want to write a sequence tagger, or NER you could say, with an (Bi-)LSTM.This is my code (provide the whole just fyi, but the most important part is the LSTMTagger class on the top and the training loop at the bottom:import sys, os
from torchnlp.word_to_vector import FastText
from pathlib import Path
import torch
imp... | ptrblck | No, the sizes are wrong as nn.NLLLoss expects the model output to have the shape [batch_size, nb_classes, seq_len] and a target of [batch_size, seq_len] for a temporal multi-class classification.
permute the model output and it should be working. |
Mriganka_Nath | I am working with object detrection, when I declare the dataset class, I make the boxes to be flaot32 but when I output them using dataloaders, it becomes float64.Also there is an error sayingVariable._ execution_engine.run_backward( 148 tensors,grad tensors _, retain_graph, create_graph, inputs, → 149 allow_unreachabl... | ptrblck | OK, I see. In that case check the dtype before calling self.transforms on the boxes (if used) and afterwards. If this doesn’t transform them back to float64, check the target['boxes'] = torch.stack(...) line. |
zilong | grads = torch.autograd.grad(loss, self.model.parameters(), create_graph=False)Is there a function liketorch.nn.utils.clip_grad_norm_for clipping the gradients in this case? | ptrblck | You could reuse the internal implementation of clip_grad_norm_ foundhere.
E.g. this should work:
# setup
x = torch.randn(2, 3, 224, 224)
model = models.resnet18().eval()
out = model(x)
loss = (out**2).mean()
loss.backward()
# create reference
torch.nn.utils.clip_grad_norm_(model.parameters(), ma… |
yuri | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
dtype = torch.float32
X = torch.tensor([[1, 2, 3, 4, 5, 6]], dtype=dtype)
Y = torch.tensor([[1, 4, 9, 16, 25, 36]], dtype=dtype)
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
... | ptrblck | Yes, you can use the inputs argument to loss.backward to specify which tensors should be used for the gradient computation. All other tensors will be ignored. |
111550 | Consider the following code:import torch
# Model definition
linear1 = torch.nn.Linear(1024,1024, bias=False).cuda()
print(torch.cuda.memory_allocated()) # memory = 4194304 (linear1 parameters)
linear2 = torch.nn.Linear(1024, 1, bias=False).cuda()
print(torch.cuda.memory_allocated()) # memory + 4096 (linear2 paramete... | ptrblck | I don’t think this operation is fused, as you’ve already mentioned that you are not scripting the model.
torch.cuda.memory_allocated() will return the currently allocated memory, not its peak (use torch.cuda.max_memory_allocated() for is or torch.cuda.memory_summary()).
Based on your description, … |
hao.liu | Dear:The problem is that, when i implement the semantic segmetation, the output shape of the semantic segmentation network is [batch_size, num_classes, width, height],it is encoded like one_hot, but i just want to directly get the output which shape is [batch_size, width, height],in the output each pixel has the v... | ptrblck | Yes, this would be my proposed approach if you can’t add the argmax operation in your deployment setup. Manipulating the forward would work or probably the cleaner approach would be to write a custom predict method which adds the argmax operation to it as described before. You could alsoreturn two … |
Samuel_Bachorik | Hi, as far i know, SGD is doing:x_new = x * learning_rate -gradientWhen we take look at Adam what is Adam doing with gradient and learning rate ? | ptrblck | Thedocsshow the applied formula and thesource codemight also be helpful to check how it’s implemented. |
Rami_Ismael | I want a simple technique that will convert a pytorch nn.module to a float 64 model. | ptrblck | To transform all parameters and buffers of a module to float64 tensors, use model.double(). |
cjenkins5614 | I always use the standard download selection panel to match cuda versions (https://pytorch.org/):pip3 install torch==1.8.2+cu102 torchvision==0.9.2+cu102 torchaudio==0.8.2 -f https://download.pytorch.org/whl/lts/1.8/torch_lts.htmlMy two questions:Does PyTorch look at strictly/usr/local/cuda's linkage and decide what di... | ptrblck | Your local CUDA toolkit won’t be used unless you build PyTorch from source or a custom CUDA extension, since the pip wheels and conda binaries use their own CUDA runtime.
You would thus only need to install a valid NVIDIA driver and can use the binaries directly. |
DSL | Hello together,i try to combine a c++ programm with my neuronal network for training. Therefore i try to set a loss manually, but when i do this and print it out i get different results.diff = part1 + part2
loss = diff.mean()
tensor(0.2783, device='cuda:0', grad_fn=<MeanBackward0>)
a = torch.Tensor([123]).to("cuda") -... | ptrblck | The grad_fn is used during the backward() operation for the gradient calculation.
In the first example, at least one of the input tensors (part1 or part2 or both) are attached to a computation graph. Since the loss tensor is calculated from a mean() operation, the grad_fn will point to MeanBackward.… |
Hongnan_G | I have been dabbling in PyTorch for a while and noticed a weird behaviour, likely because of seeding/instantiating issue.# Model, cost function and optimizer instancing
model = models.CustomNeuralNet().to(device)
if is_forward_pass:
# Forward Sanity Check
_forward_X, _forward_y = models.forward_... | ptrblck | I don’t know which higher-level API you are using, but if I understand your issue correctly you are concerned about the determinism between two different runs using is_forward_pass=True and =False.
If so, I would guess that the pseudorandom number generator is called additionally in the if_forward_… |
Hongnan_G | So I am doing a classification problem with BCEwithlogits loss, therefore, it expects my integer targets to be float. However, I definedtorch.from_numpy(df[FOLDS.class_col_name].values).float()and subsequently return{"y": torch.FloatTensor(target)}and the error isIndexError: slice() cannot be applied to a 0-dim tensor.... | ptrblck | Yes, as_tensor would probably work. If the input is a numpy array, you could also use torch.from_numpy. |
JayShreekumar | I get the following error for a GAN model I am using to perform image colorization. It uses the LAB color space as is common in image colorization. The generator generates the a and b channels for a given L channel. The discriminator is fed all three channels after concatenation.NOTE: I am using Google Colab, maybe thi... | ptrblck | I would have assumed you might be running intothis issue.
However, I don’t see this behavior in your code.
Could you replace the inplace skip connections h += poolX with their out-of-place versions h = h + poolX and check, if this would solve the issue?
I guess h is needed for a gradient calcula… |
Bibhabasu_Mohapatra | import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from skimage import io
# image = io.imread(self.image_path[item])
# mask and img learnt from Awsaf's Notebook
class CustomDataset(torch.utils.data.Dataset):
def __init__(self,image_paths,mask_paths = None,augmentations,preprocessing_fn=None... | ptrblck | As the error message explains, you need to provide default values for all arguments to a function call after the first default was set.
def __init__(self,image_paths,mask_paths = None,augmentations,preprocessing_fn=None):
is thus wrong and you would have to use:
def __init__(self,image_paths,mask… |
scollazo | Hi! I got the following errorValueError: optimizer got an empty parameter listwhen I run the code containing the following classes:class Mass_and_v():
def __init__(self, param):
self.parameter = param
# get_mass + v_circ_tot
def __call__(self, x):
ener_f = 56.0 # keV
r, mass... | ptrblck | The AttributeError is raised, as you’ve most likely forgotten to add the super().__init__() call into the __init__ method.
Yes, I would try to avoid using other libraries if possible, since you would break the computation graph and PyTorch won’t be able to track these operations. If really necessa… |
antoniopurificato | I’m trying to implement my personal version of SqueezeNet using Pytorch. I have some base code that I can not modify but I can modify all the code inside the class APNet and also all the other methods in the same script. When I try to start training I obtain always the error in the description.import torch.nn as nn
imp... | ptrblck | Based on the error message I guess your model output is a 4D tensor in the shape [batch_size, nb_classes, height, width] while the target has the shape [batch_size] and would thus indicate a multi-class classification use case.
In case that’s indeed the use case, make sure your model returns an out… |
tjoseph | Hello,I am just wondering whether I am missunderstandingAutomatic Mixed Precision examples — PyTorch 1.10.0 documentationor whether the use case there is useless.GradScaler has a singlescaleparameter. Instead of scaling two times like in the example, I could just add the losses and then scale.However, the use case that... | ptrblck | I wouldn’t call the example useless, but yes you can use multiple GradScalers if that fits your use case better. |
Gul_Zain | I am trying to run a model that requires vgg16 pretrained models. My issue is presented here:github.com/richzhang/PerceptualSimilarityCUDA OUT OF MEMORYopened06:45AM - 21 Nov 21 UTCgulzainali98I am trying to calculate lpips metric on directory of images. i use following co…de to load and calculate
```
for i in range(l... | ptrblck | In the code snippet posted in the linked issue you are accumulating the loss and are thus also storing the computation graphs which are potentially attached to it:
for i in range(len(ground_truth)):
p= lpips.im2tensor(lpips.load_image(predictions[i]))
g= lpips.im2te… |
Sherzod_Bek | I did several training with different input size [224,512,…].In inference I want to know input shape of each loaded model(weights) to get more accurate result.is it possible to know input shape of loaded(saved) model?inference works with any shape but if I use exact input shape performance will be better. (in inference... | ptrblck | There isn’t a way to check the used shapes during training if the model is able to accept variable input shapes. You could store the input shapes e.g. in the checkpoint along with the state_dict or store it as an attribute in the model code instead. |
Albert_Christianto | Hi@ptrblckI want to know what libtorch API that we can use to get the CUDA and CuDNN version?Ps:Right now I have a project that using both opencv DNN and Libtorch, but I keep getting warning because unmatch cudnn version. I use pre-built libtorch library.best regards,Albert Christianto | ptrblck | For cuDNN:
long cudnn_version = at::detail::getCUDAHooks().versionCuDNN();
for CUDA runtime:
int runtimeVersion;
AT_CUDA_CHECK(cudaRuntimeGetVersion(&runtimeVersion));
for the driver version:
int version;
AT_CUDA_CHECK(cudaDriverGetVersion(&version));
In case you want to use checks in the code… |
sara_adam | HiI’m a beginner using PyTorch modelsI need to know the name or id image prediction and store the results inside CSV file (id or name image and predictions)def visualize_model(model, num_images=10):was_training = model.training
model.eval()
images_so_far = 0
fig = plt.figure()
with torch.no_grad():
for i, (i... | ptrblck | I assume you are referring to the image name (or path), not the class name.
If so, you could create a custom Dataset as describedhereand return the image name in the __getitem__ additionally to the data and target tensors. Inside the DataLoader loop you would then have 3 values and could print th… |
fllci | Hi all. I am using CycleGAN on 1-D tensors and keep getting this error. I searched for this error all over the blogs and everyone is saying it is because of batchnorm. Yet I only use instancenorm in my model.Some say, increase your batchsize, I started with batch size=1 and increased to different numbers, did not work.... | ptrblck | As described in the docs:
The mean and standard-deviation are calculated per-dimension separately for each object in a mini-batch.
so I think this is expected as your the stats would be calculated from each sample in the temporal dimension, which won’t be possible for a single value (the stddev … |
thesekyi | index_separator = 2
all_probs = tensor([[1.7453e-01, 8.2525e-01, 2.1337e-04],
[7.9364e-01, 2.0613e-01, 2.2616e-04],
[4.1631e-02, 9.5827e-01, 1.0366e-04],
[9.2631e-01, 7.3529e-02, 1.6452e-04],
[9.9914e-01, 8.1824e-04, 4.1946e-05],
[8.0214e-01, 1.9750e-01, 3.6684e-04],
[9.9... | ptrblck | This small error is expected due to the limited floating point precision. A different order of operation could create these errors and on my system the difference between the manual calculation vs. the difference tensor is ~4e-8. |
gonzrubio | What are the drawbacks/advantages of defining a function that builds a given layer as a member of the neural network class as opposed to defining it outside the class?For example, as a class member:class Discriminator(nn.Module):
"""C64-C128-C256-C512 PatchGAN Discriminator architecture."""
def __init__(self, ... | ptrblck | I think it mainly boils down to your coding style and in particular if and where you would like to reuse this method.
I don’t see any issues with writing make_conv as a class method in Discriminator in case this is the only model using it. Otherwise, I would define it outside of the class so that o… |
flaviomaia77 | Lets say I have datasets A and B. I want to receive at runtime batches that are either from A or from B, (not mixed batches) and also their origin. So some tuple like (‘A’, BatchFromA).How to implement that? | ptrblck | To get the dataset name in each sample, you could return it in the __getitem__ of each Dataset.
A custom sampler might be the best approach to create batches from unique datasets and to make sure they are not mixed. |
laro | I want to useVGG16(transfer learning), but I don’t have enough memory:According tonvidia-smiI have 4GB of memoryModel:model = torchvision.models.vgg16(pretrained=True)
for p in model.parameters():
p.requires_grad = False
sin = model.classifier[0].in_features
model.classifier =... | ptrblck | If the model parameters already take more memory than your GPU has I don’t think there is a way to make it work besides using only a subset of the model on the GPU and the rest on the CPU.
I don’t know if you would expect any speedup due to the transfer of tensors between the GPU and the host, so y… |
sahar.mi | hi everyone, I’m trying to update the parameters of a pretrained masked language model with a new custom loss function, but it seems that the gradient of parameters are none. I used a pretrained bert for masked language model and a pretrained classifier. I have concatenated a vector to the batch and made a new batch, w... | ptrblck | Your code will explicitly return the parameters only, which all should be leaves. You should check the is_leaf attribute of the parameters before and after concatenation manually.
a = nn.Parameter(torch.randn(1))
b = nn.Parameter(torch.randn(1))
print(a.is_leaf)
> True
print(b.is_leaf)
> True
c =… |
hema_rathore | >>>unfold = nn.Unfold(kernel_size=(2, 3))
>>> input = torch.randn(2, 5, 3, 4)
>>> output = unfold(input)Can someone explain the exact operation of using F.unfold please. Like I read doc but its not clear I need to understand the whole maths behind.Thanks | ptrblck | Unfold uses a sliding window approach as seen in this code snippet:
unfold = nn.Unfold(kernel_size=(2, 3))
input = torch.randn(2, 5, 3, 4)
output = unfold(input)
output_manual = []
kernel_size = [2, 3]
# sliding window approach
for i in torch.arange(input.size(2)-kernel_size[0]+1):
for j in to… |
laro | I’m trying to use VGG16 with transfer learning, but getting errors:model = torchvision.models.vgg16(pretrained=True)
print(model)
for param in model.parameters():
param.requires_grad = False
input_size = model.classifier[0].in_features
model.classifier[0] = nn.Sequential(
nn.Linear(input_size... | ptrblck | The error is a shape mismatch as returned a bit higher in the stack trace:
RuntimeError: mat1 and mat2 shapes cannot be multiplied (64x2 and 4096x4096)
This is caused because you are assigning the new nn.Sequential block to model.classifier[0] and keep all other modules from the original model.cla… |
Yash_Jakhotiya | What could be going wrong here?converting a scalar to a LongTensor returns an arbitrarily large value.This is the source.A bug?Changing the source toid = torch.LongTensor([bos_id])works fine. | ptrblck | You are creating a LongTensor of the size 1 using uninitialized memory.
Using the “tensor type” constructors is not recommended, as it’s creating this unexpected behavior (the same applies for e.g. torch.FloatTensor).
E.g. if you are passing a scalar value of 10 you would get a tensor with 10 unin… |
Giorgio | Hello, I’ve experienced a serious data corruption while saving tensors to a pickle file (about 1 giga byte of data). Probably I’ve tried to write to it again before the previous writing was complete? It’s a google colab script that saves data to its google drive environment, and each writing operation came a minute or ... | ptrblck | Often file corruptions are caused by writes to the same files from multiple processes. Since you have apparently excluded this issue I don’t know what might be causing this error as I haven’t seen it before. |
dieptran149 | Hi everyone,I’m running the Densenet121 Model. After loading weights. I have 2 unwanted blocksmodel.features.denseblock4andmodel.features.transition3. I’m trying to remove these 2 blocks of layers. Could any please tell me the way to do it? I’ll very appreciate it.prune830×505 26.1 KB | ptrblck | An easy way would be to replace them with nn.Idenity layers (assuming their input shape matches their output shape). Alternatively, you could also override the forward in a custom module and skip these layers directly. |
seyeeet | HelloI am doing something like this in my code but it is very slow.I was wondering if there is a faster way to do it.in my exampleshiftandndividesare subject to change from case to case.x = torch.arange(0,32*400).reshape(1,32,400)
cat = []
shift = 4
ndivides = 99
for i in range(ndivides):
cat.append(x[:,:, i*shift:... | ptrblck | tensor.unfold should work:
x = torch.arange(0,32*400).reshape(1,32,400)
cat = []
shift = 4
ndivides = 99
for i in range(ndivides):
cat.append(x[:,:, i*shift:(i+1)*shift +(shift //2)*2])
results = torch.stack(cat,dim=1)
tmp = x.unfold(2, 8, 4).permute(0, 2, 1, 3)
print((tmp == results).all())
>… |
Kalle | I have 3 different GPUs available and do not experience deterministic behavior. My GPUs are:GeForce GTX 1080 TiGeForce RTX 2080 TiTesla P100-PCIE-16GBIm using PyTorch version 1.3.1 and currently using the following settings to try to achieve the same reproducible result:seed = 3
torch.manual_seed(seed)
torch.backends.c... | ptrblck | Determinism cannot be guaranteed between different hardware families, so you cannot expect to get bitwise accurate results between all three devices.
You could update to the latest PyTorch release (1.9.0) and set all settings as described in theReproducibility docsto get deterministic behavior b… |
Sumera_Rounaq | Hi all,I am saving state of optimizer and getting this error“state_dict() missing 1 required positional argument: ‘self’”.Code:torch.save({
'epoch': num_epochs,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': opt_func.state_dict(),
'lr':lr,
'l... | ptrblck | This is expected.
Your current method uses the opt_func argument as a function not an object:
def fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):
[...]
optimizer = opt_func(model.parameters(), lr) # !!! this is wrong if opt_func is already an optimizer object
s… |
hideinshadow | I tried to run my training code with torch1.10.0+cu113, only to find that the speed is slower than that of torch1.8.2+cu102. Does anyone have the same problem? | ptrblck | Thanks for sharing this output!
I was able to reproduce a minor regression in the 1.10.0+cu113 wheels, which seems to be resolved already using the latest cuDNN release (8.3.0.96).
Code used to profile the workload:
random.seed(2021)
np.random.seed(2021)
torch.manual_seed(2021)
print(torch.cuda.… |
TigerVersusT | I’m using pytorch=1.3.1 to load model saved by pytorch=1.7.1 and received the following error:RuntimeError: version_number <= kMaxSupportedFileFormatVersion INTERNAL ASSERT FAILED at /pytorch/caffe2/serialize/inline_container.cc:131, please report a bug to PyTorch. Attempted to read a PyTorch file with version 3, but t... | ptrblck | PyTorch doesn’t support forward compatibility (loading data from a newer into an older release), but backwards compatibility, so you would need to update PyTorch or save the model in 1.3.1. |
Abhishek_K | Hello All,I am trying to implement a U-Net Architecture for Image Segmentation task.Problem: :Out of Memory Errorthrown even before completing a single forward pass for a batch size of 32 and greater. But for a batch size of 5, I am able to train the model without any errors.Model :Taken frombrain-segmentation-pytorch... | ptrblck | Your GPU doesn’t seem to have enough memory for the used batch size, so you would need to reduce the memory usage e.g. by lowering the batch size or by trading compute for memory via torch.utils.checkpoint. |
Hamster | Hello!I’m currently having some CUDA“out of memory”errors during training after a certain number of iterations, and only when back-propagation is being used and precisely when trying to allocate new tensors in thebackwardmethods of myautograd::Functionsubclasses. I’m using custom activation functions & layers for which... | ptrblck | I think the issue is caused by the wrong usage of directly string the tensors in ctx and if I’m not mistaken, we’ve seen a few similar issues in the past posted here.
Use ctx->save_for_backward and the memory leak should be gone. |
Chris_XU | Hi I am wondering what’s the difference between the newly addedtake_along_dim&gather? It seems that they are pretty much similar other thantake_along_dimcan have user not specifyingdimparameter. In this case seems that torch can find the best broadcast, for example I triedlogitsof shape (N, K) and use index oflogits.ar... | ptrblck | This method was adden inthis PRas part of the numpy compatibility workload and thus might be similar to gather. |
follower | Hi, I have some problems when I use L-BFGS optimizer on pytorch.My problems are below.L-BFGS optimizer with CUDA doesn’t converge or converge too early (converge on high loss value)L-BFGS with CPU work perfectly.If I set data types of all tensor to float64, It is work.I think that these problem depends on my environmen... | ptrblck | Could you disable TF32 via torch.backends.cuda.matmul.allow_tf32 = False and rerun the code, please? |
Tornike | Hi, Doing Depth Estimation Task with U2NET.I read the Paper but still don’t get it.What are the mid_channels? why they use it?and why they use that in every conv Layer after first Conv.class RSU7(nn.Module):#UNet07DRES(nn.Module):
def __init__(self, in_ch=3, mid_ch=12, out_ch=3):
super(RSU7,self).__init__(... | ptrblck | I don’t know what is mentioned in the paper, but based on the posted code snippet it seems to be an architecture choice which would simplify the model creation by defining the input, mid, and output channels only. |
Mole_m7b5 | Hi,I’m testing different Dataloader parameter settings as I recently found out that fornum_workers > 0to to actual aid in loading speed on windows you need to setpersistent_workers = True. For this I’m using the below code.class Dset(torch.utils.data.Dataset):
def __init__(self, index_dict_fp, labels, X_filepath, ... | ptrblck | It seems you might be running intothis issueand the linked post refers tothis postwhich explains the limitation of Windows to fork processes. |
coincheung | Hi,When we train the models, in the backward pass, we compute not only graident of model paramters but also tensors. For example, if there is a linear layer:y = x * wWherewis the model parameter, andxis the input tensor. If we compute backward pass, we should compute not only graident ofw, but also graident ofx.What if... | ptrblck | The parameter gradient should be averaged as the data gradient (in x) depends on the input data.
Since you are training with a different batch on each GPU you wouldn’t need to synchronize the data gradient unless I’m missing something in your use case. |
Diogo20Mata | So, I’m trying to train a DistilBert model and the gradients are either not being calculated or stored, since, when I print the gradients within a training loop they are always zero. Consequently the weights are not being updated.optimizer = optim.Adam(network.parameters(), lr=0.0001)
loss_fn = nn.CrossEntropyLoss().to... | ptrblck | nn.CrossEntropyLoss expects raw logits as the model output, so remove the F.softmax in your forward method and check, if this would yield non-zero gradients. |
Najeh_Nafti | How can I save best model weights to continue training the model after stopping because of limited GPU resources? | ptrblck | You could iterate the parameters and print their .grad attribute:
loss.backward()
for name, param in model.named_parameters():
print('{}, {}'.format(name, param.grad)) |
vadimkantorov | I’m thinking of using autocast for speeding up processing of frozen backbone. If I use autocast context manager in forward, will it every time spend time on conversion of model weights?How do I ensure it does conversion of model parameters fp32->fp16 exactly once?My alternative is to manually convert frozen backbone’s ... | ptrblck | Yes, autocast uses caching internally unless you manually disable it and the checks can be foundhere.
It’ll be done automatically for you if the parameter is found in the cache (which won’t be the case if e.g. you’ve modified it). |
BouzidiImen | I am trying to access weights in a model that when loaded I find these keys:dict_keys([‘optimizer_state_dict’, ‘epoch’, ‘scaler_state_dict’, ‘best’, ‘curriculum_config’, ‘encoder_state_dict’, ‘decoder_state_dict’])This is a screenshot of he output I have:image1376×118 5.18 KBI would really appreciate your help.Thannk y... | ptrblck | I’m not familiar with your use case, but based on the output it seems you might be working on a sequence prediction task? If so, is each sample supposed to predict a word/token etc.?
In case you are using another repository as your code base, I would probably check if this repo might already implem… |
mkarn3yru | Below is the training function I am writing, yet, there is this error: ‘NoneType’ object has no attribute ‘parameters’. I don’t really know how to solve itdef train(net, train_loader, test_loader, logger):
# TODO: Define the SGD optimizer here. Use hyper-parameters from cfg
optimizer = optim.SGD(net.pa... | ptrblck | It seems you are passing the net argument as a None so check where net is created and that it holds a valid nn.Module object.
My guess would be that you might be using a convenient function to create the model and might have forgotten to return the model itself. E.g. this would break with the same … |
AlphaBetaGamma96 | Hi All,I was wondering if there’s an equivalent toregister_bufferfor custom optimizers? I’m currently building a custom optimizer and I want to be able to save some floats (which are used within the optimization process)Some methods within the class don’t useself.param_groupsso is there a way to save attributes within... | ptrblck | You should be able to add your custom buffers to the corresponding param_group via:
# setup
lin = nn.Linear(1, 1)
optimizer = torch.optim.Adam(lin.parameters(), lr=1e-3)
# dummy training
out = lin(torch.randn(1, 1)).backward()
optimizer.step()
# check param_group
print(optimizer.param_groups[0])
… |
bingqing_liu | Exception ignored in: <function _MultiProcessingDataLoaderIter.__del__ at 0x7f231e2bd8b0>
Traceback (most recent call last):
File "/home/a09/software/anaconda3/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 1328, in __del__
self._shutdown_workers()
File "/home/a09/software/anaconda3/lib/pytho... | ptrblck | You might be running into a similar issue as describedherewhich seems to point to a bad interaction between tqdm and Python’s multiprocessing module. |
dnv | Hello I am currently learning from the Transfer learning tutorial provided on the Pytorch webside.I ran into this error while trying to train the model.https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.htmlRuntimeError Traceback (most recent call last)in5 model_ft.fc = nn.L... | ptrblck | The raised error points towards an invalid index in the target:
IndexError: Target 2 is out of bounds.
In a multi-class classification using nn.CrossEntropyLoss the model output is expected to have the shape [batch_size, nb_classes] while the target should have the shape [batch_size] and contain c… |
Evan_Vogelbaum | I have k classes, for each of which I have trained a model. I would like to create a new model whose architecture is identical and whose parameters are theweightedaverage of the corresponding parameters of each of my k models according to some specified distribution p (e.g. [0.1, 0.2, 0.7] for k=3).My goal is to constr... | ptrblck | To simply average the parameters of multiple models you could usethis approach. However, based on your description you would like to calculate the gradients for the parameters in the original models, so using the averaged state_dict wouldn’t work.
Instead I think the right approach would be to cre… |
Jim_Thompson | Looking for guidance around the use ofBatchNorm1dand how its use affect parameter updating.Are there are any guidelines on how to useBatchNorm1d?The reason I’m asking is that it appears when I useBatchNorm1d, some model parameters are not updated during the backward pass.Here is a minimal example that illustrates the i... | ptrblck | Thanks for the great code and the interesting question!
Based on your output (and my runs) it seems that the bias of the preceding linear layer is not updated.
While the check claims so, you could check the gradients of the bias parameter and would see that these gradients are indeed really small: … |
asdas_casxc | I am using PIL first to convert a saved image to grayscale then resize and convert to a tensor object using the following code:gray_image = ImageOps.grayscale(img)
resize = T.Compose([
T.Resize((36,64)) # height, width
,T.ToTensor()
])However, when i plot it usin... | ptrblck | If your tensor doesn’t contain a color channel dimension the colormap is undefined and matplotlib will use its default one.
In case the tensor represents a real grayscale image, it would have a color channel size of 3 where all channels are equal.
This code shows the behavior:
x = torch.randint(0… |
Trinayan_Baruah | Hi,I was just implementing a simple 2d batchnorm and wanted to use channels last format. When I use the code as pasted below, my GPU profiler NSight shows the forward kernels using the channels last format as indicated by their names. But the backward uses the basic batchnorm_backward_reduce kernel instead of what is e... | ptrblck | Yes, that’s right.
No, if you add another layer (e.g. nn.Conv2d) you would see the channels-last kernels again. The issue with your code would be the reduction, which would drop the memory layout, if I’m not mistaken. |
ADONAI_TZEVAOT | I have a tensor x and a parameter tensor R. I want to store the matrix multiplication of x and R into z and also make sure that z does not require any gradients. How do I do that? Please help.....
z = x @ self.R
..... | ptrblck | Wrapping the operation into a no_grad() context would work:
R = nn.Parameter(torch.randn(1, 1))
x = torch.randn(1, 1)
with torch.no_grad():
z = x @ R
print(z.grad_fn)
> None |
thecho7 | I want to create a tensor having specific size like the below,# a: (B, N, 2) = (2, 3, 2)
a = torch.LongTensor([[[2, 1], [2, 2], [3, 3]], [[2, 0], [3, 2], [1, 2]]])
K = 5
# The expected tensor has the size of (B, K, K) = (2, 5, 5)
# For the first batch,
result[0] = torch.LongTensor([[0, 0, 0, 0, 0],
... | ptrblck | Directly indexing the result tensor should work:
a = torch.LongTensor([[[2, 1], [2, 2], [3, 3]], [[2, 0], [3, 2], [1, 2]]])
K = 5
out = torch.zeros(a.size(0), K, K)
out[torch.arange(out.size(0)).unsqueeze(1), a[:, :, 0], a[:, :, 1]] = 1.
print(out)
> tensor([[[0., 0., 0., 0., 0.],
[0., … |
ZHAOBO_XU | Hi there! I am using an autoencoder structure in my project. After I trained the net, how can I use the trained decoder part to generate some reconstructed images? Is it possible to create two ‘forward’ function within the network class, like one for the whole and another for the decoder alone? | ptrblck | Yes, it would be possible to split the forward passes and call them separately:
# original forward
def forward(self, x):
out = self.forward_encoder(x)
out = self.forward_decoder(out)
return out
and later call model.forward_decoder(input) to call the decoder only.
However, since you ar… |
StrausMG | Hi! I have an environment where I cannot upgrade CUDA from 11.1 to 11.3. Can I still use PyTorch 1.10 despite the fact that it was built with CUDA 11.3? As far as I understand, the answer is “yes” and the biggest risk I take is that torch 1.10 uses some kernels missing in 11.3 (which will cause explicit error that I wi... | ptrblck | If you are installing the pip wheels or conda binaries, then note that they are shipping with their own CUDA runtime (statically linked in the pip wheels, dynamically via cudatoolkit in the conda binaries).
Your local CUDA toolkit will be used, if you are building from source or custom CUDA extensi… |
valgi0 | Hi there,I have a very newby question …I have a torch tensor of float values as:torch.tensor([[1., 2., 3.], [1., 3., 2.]])From it, I want to create a mask vector of 0 and 1 where 1 is the max value of the row:torch.tensor([[0,0,1],[0,1,0]])I can use the indices returned by torch.max(dim=-1,…) iterate over them and writ... | ptrblck | Using the indices of torch.max sounds like a good idea, but you wouldn’t have to iterate them and could use them directly:
x = torch.tensor([[1., 2., 3.], [1., 3., 2.]])
y = torch.zeros_like(x)
y[torch.arange(y.size(0)), x.argmax(dim=1)] = 1.
print(y)
> tensor([[0., 0., 1.],
[0., 1., 0.]]… |
Omama | I have two Bert models. I detached the classifier layer and kept the pre_classifier and drop out layers. Then I created an ensamble that has the classifier layer.So the output of the two BERT models will be concatenated on the ensamble, then will be input to the classifier layer.The problem is that I’m getting errors a... | ptrblck | If you store the outputs, load them afterwards and train the classifier, this might not be an ensemble model training anymore, since you would only train the classifier (but it also depends on your definition of ensemble).
If that’s your use case, then you could either detach() the outputs from bo… |
bingqing_liu | i want to ask which one is better in the aspect of speed.device=torch.device("cuda")
class fc_layer(nn.Module):
def __init__(self):
super(fc_layer,self).__init__()
self.linear1=nn.Linear(emb_size,emb_size)
def forward(self,x):
y=self.linear1(x)
a=np.ones((2,3))
a=torch.te... | ptrblck | Will use two copies: when creating the tensor (as you are not using from_numpy) and the data transfer to the GPU
Only the transfer
Will create the tensor on the device directly, so I would use this approach.
Of course you won’t notice a significant difference given the current shapes, but I assume… |
x1290148 | I spent a lot of time converting tensor to mat.My algorithm time is only 20ms, while the conversion takes 80ms.cv::Mat tensor2Mat(torch::Tensor &i_tensor)
{
int height = i_tensor.size(0), width = i_tensor.size(1);
i_tensor = i_tensor.to(torch::kCPU);
cv::Mat o_Mat(cv::Size(width, height), CV_32F, i_tensor.data_ptr()... | ptrblck | Pushing a CUDATensor to the CPU is a synchronizing operation in the default setup and will thus accumulate the time unless you manually synchronize the code.
You could try to use the non_blocking option, but would still need to wait until the data transfer is done and based on your code you are dir… |
zzzhhh | When I tried to import PyTorch in python, it crashed with a segfault error:image988×198 6.98 KB“Segmentation fault (core dumped)” is all I have about the issue. Since the sys admin is very disagreeable, I have to figure out what the problem is myself. But I really don’t know what the cause of the crash could be.This th... | ptrblck | Based on the backtrace it seems that numpy’s libopenblas creates the seg fault. Did you install numpy with the PyTorch wheels? If not, install it or update to the latest PyTorch release, as recently we’ve foundthis issue, which might be related. |
asi212 | An error occurs while trying to compute loss in the classification head. To the best I can tell, my input data is in the structure required by the torch vision RetinaNet. However, I still get this error that prevents me from training.I’ve replaced the example minimally below. The error message you receive should be “in... | ptrblck | I think the error is raised in the unexpected target containing ones (so two classes):
labels = torch.LongTensor(np.ones(len(bboxes), dtype=int))
while the model is initialized with num_classes=1. Change it to num_classes=2 and it should work. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.