user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Fei_Liu | (The documentation looks way too high level and I didn’t find much useful by search engine.)Is it that pin to a specific device (e.g.'cuda:0') is faster (for later data transfers to device) than a general pin if I know which device it’s going to? Also Is this equivalent toTensor.pin_memory(device)? (It appears thatTens... | ptrblck | Fromthis topicit’s a placeholder for other backends which might support pinned memory. |
Sart | I’m facing this error while training my model :AttributeError: ‘list’ object has no attribute ‘relu2_2’Code :for epoch in range(1, epochs+1):transformer.train()print(‘No of Epochs:’, epoch)for batch_i, (images, _) in enumerate(train_loader):optimizer.zero_grad()images_original = images.to(device)generated = transformer... | ptrblck | Based on the error message it seems:
features_transformed = vgg(generated)
returns a list which then raises the error in:
l2_loss(features_transformed.relu2_2, ...)
so check the forward method of your vgg definition and make sure an object is returned which contains the relu2_2 attribute. |
nima_pw | Hi,I’ve saved my model train and validation accuracy usingwith open( )... as f , f.close()in.txtformat. The output is like this:tensor(0.3494, device='cuda:0', dtype=torch.float64)
tensor(0.4721, device='cuda:0', dtype=torch.float64)
tensor(0.5966, device='cuda:0', dtype=torch.float64)
tensor(0.7131, device='cuda:0', ... | ptrblck | Since you’ve stored the data as strings you could use regex to match the actual floating point value and transform it into a float literal. |
Cyber_punk | The typical Pytorch training loop is:for epoch in range(n_epochs):
# Training
for data in train_dataloader:
input, targets = data
optimizer.zero_grad()
output = model(input)
train_loss = criterion(output, targets)
train_loss.backward()
optimizer.step()
# Validation
with torch.no_grad():
for input, t... | ptrblck | Yes, no_grad will disable the gradient calculation and will reduce the memory usage by deleting intermediate activations directly, which would be needed for the backward pass otherwise.
Since you are never calling backward() during the validation phase no_grad() is an optional optimization. |
RaulPPelaez | The following MRE results in an unexpected error:stream = torch.cuda.Stream(-1)
torch.cuda.synchronize()
try:
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph, stream=stream):
torch.cuda.synchronize()
except RuntimeError as e:
print(e)
torch.cuda.synchronize... | ptrblck | OK, I see. Unfortunately, the error looks like a valid CUDA assert and might thus corrupt the CUDA context so cannot be recovered. |
shrbrh | Can anyone please tell me what version of Pytorch is compatible with A100-PCIE-40GB with CUDA capability sm_80. I have tried installing different versions but keep getting the same error: “RuntimeError: CUDA error: no kernel image is available for execution on the device.CUDA kernel errors might be asynchronously repor... | ptrblck | Yes, you would need to update the PyTorch binary and install one with CUDA 11, as the currently installed older one uses 10.2 as I’ve already guessed. |
ThibautChataing | Hello,I’m working on a supervised deep learning model. The loss used should be different depends on the class of the input.For example : If X_0 is the input vector and its from the class 0, resp X_1 from the class 1. The used loss for X_0 will be L_0 and the one for X_1 will be L_1.Now we are in a training session. Ins... | ptrblck | I would claim it depends on the used reductions in the loss functions and how the losses are masked in the second approach.
E.g. if you are calculating the mean losses in L_0 and L_1 I would expect to see a difference since the number of samples would differ. However, I also wouldn’t know how you a… |
timgianitsos | In an initializer to annn.Module, I usually get the same behavior depending on whether I append the submodules to annn.ModuleList, or whether I append them to a regular python list while registering manually withself.add_module.However, I notice a discrepancy when I try to run experiments on multiple GPUs. The followin... | ptrblck | Yes, my expectation would be that both APIs should yield the same results and if a supported module depends on one particular way of registering a parameter I would see it as a bug. |
Neoxion | I wrote a simple CUDA matrix multiplication kernel:template <typename scalar_t>
__global__ void matmul_cuda_kernel(
const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits> a,
const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits> b,
torch::PackedTensorAccessor<scalar_t,2,torch... | ptrblck | PyTorch uses float32 as the internal compute type for float16 inputs and outputs while it seems you are also using a float16 compute/accumulation type. |
SutthidaMint | I use VGG19 for train model but I’m curious that I should use which one and what is differentmodel.features.eval()for param in model.features.parameters():param.requires_grad = Falsewith torch.no_grad():example# fix the weight of convolution layers
model.features.eval()
# modify classifier
model.classifier = torch.nn.... | ptrblck | This sets the model in evaluation mode, which changes the behavior of some layers but does not freeze trainable parameters. After calling model.eval() e.g. dropout layers will be disabled and batchnorm layers will use their running stats to normalize the input activation.
These lines of code wi… |
peony | I have this code to fine-tune a resnet50 model to my task:import torch
import torch.nn as nn
from torch.nn.functional import normalize
import torchvision.models as models
from torchvision import transforms, utils
from torchvision.models import resnet50
import torch.nn.functional as F
class resnet(nn.Module):
def ... | ptrblck | Flatten the activation via x = x.view(x.size(0), -1) in case you have now completely removed the view operation. |
Ramzes_III | Hello, I’m complitely new in Pytorch and here is my trouble.I create a Dataset withImageFolderSplit indices with sklearntrain_test_splitMake 2 Subsets.Make new MyDataset class likeherebecause I want make different transforms.Create 2 DataLoadersWhen I’m trying to take 1 sample from DataLoader(withnext(iter(DataLoader))... | ptrblck | Based on your description it seems you might be running into issues with the DataLoader so I would recommend trying to iterate the DataLoader object directly to see if this would work (I would assume it would also hang) and then trying to isolate the issue further by e.g. setting the num_workers to 0… |
Mona_Jalal | I installed CUDA 11.7 but not sure why I get this error or how to fix it? I got the command from official pytorch website for older versions(oneposeplus) mona@ard-gpu-01:~$ pip install -U torch==1.13.0+cu117 torchtext==0.14.0 --extra-index-url https://download.pytorch.org/whl/cu117
Looking in indexes: https://pypi.org/... | ptrblck | You are trying to install older torch, torchvision, and torchtext releases with Python==3.11, which was just recently added.
Downgrade Python to e.g. 3.10 and it should work. |
kabbas570 | Hello PyTorch Community!I want to return a SimpleITK.SimpleITK.Image from my data loader as my model needs it at some stage, I am getting following error.TypeError: default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found <class ‘SimpleITK.SimpleITK.Image’>with this codedef __getitem__(... | ptrblck | Wouldn’t it be possible to return the transformed image as a tensor with all needed metadata together?
At one point you would still need to transform the image, so I’m unsure why not in the __getitem__ method to avoid the error. |
sree_harsha | Hello,I’m trying to run the ‘FlashAttention’ variant of the F.scaled_dot_product_attention.Config = namedtuple(‘FlashAttentionConfig’, [‘enable_flash’, ‘enable_math’, ‘enable_mem_efficient’])’self.cuda_config = Config(True, False, False)with torch.backends.cuda.sdp_kernel(**self.cuda_config._asdict()):x = F.scaled_dot_... | ptrblck | Could you check if you are seeing the same issue in the recent nightly binary, please? |
Megh_Bhalerao | Hello, I want to set the transform attribute of a Dataset object once I have already instantiated the object - I try to do that using the setattr method of python, but it does not work - below is a minimum working example.import torch
import numpy as np
from torch.utils.data import Dataset
import torchvision.transforms... | ptrblck | It it inherited from Dataset but this base class also doesn’t define the transform attribute as seen inits definition. |
AleTL | Hello!I have noticed that, even though I am actively fixing the seed, there are small differences between runs when the I multiply two tensors. More specifically, I have located a run in which I perform an element wise multiplication of two tensors and, in one run, the multiplication oftorch.sigmoid(torch.tensor(0.0000... | ptrblck | You are most likely seeing the expected small errors caused by the limited floating point precision and a potentially different order of operations in the used operators.
Take a look at theReproducibility docsto see how deterministic algorithms could be enabled (which could be slower, but should … |
AleTL | Hello!I want my dataloader to return me a list of size 3, in which each element is likewise a list, in the following form:[[tensor1, tensor2], [tensor3, tensor4], [tensor5, tensor6, tensor7]]
tensor1.shape = tensor3.shape
tensor2.shape = tensor4.shape
tensor1.shape != tensor2.shape
tensor5.shape != tensor6.shape != ten... | ptrblck | Your approach seems to work for me:
class MyDataset(Dataset):
def __init__(self):
pass
def __len__(self):
return 10
def __getitem__(self, index):
tensor1 = torch.randn(2)
tensor2 = torch.randn(3)
tensor3 = torch.randn(2)
tensor4 … |
gram | I built a small modelclass TinyVGG(nn.Module):
def __init__(self,input_features,
output_features,
hidden_units,
len_classes) -> None:
super().__init__()
self.conv_relu_layer_1 = nn.Sequential(
nn.Conv2d(in_channels=input_features,
... | ptrblck | loss += loss_fn(...) will accumulate the loss tensor with all its history and thus will also keep the computation graph alive. Calling loss.backward() will then try to backpropagate through all iterations and will raise the error since intermediate activations from previous iterations were already f… |
raining_day513 | I want to know when PyTorch will allocate GPU memory for all the gradients of a givennn.Module. It seems that all these gradients are set toNonebefore training, and they will be set during the backward pass.Setting toNoneor not, it seems that PyTorch already allocate GPU memory for all of them. Is this claim correct?Ho... | ptrblck | No, that’s wrong as PyTorch will not allocate memory for non-existing objects. |
phphuc | Hi everyone,I am currently working with a dataset over 200,000 images in 4K resolution. I wonder if I should manually resize image (copy dataset but smaller size) before training or I could just use Resize in module Transform.Thank you in advance.P/s: I’m rather new to PyTorch. I hope to receive your all explanations. | ptrblck | Both would work and I would claim it depends on your use case and in particular if you want to randomly crop the images before resizing them etc.
I would not expect to see a huge overhead of resizing the images on the fly, but this would also depend on your system. |
Haalum | I have two loss functions, one is a custom with both forward() and backward() calledMyMSELoss. Another loss function is directly from PyTorchmseloss.I want to do a weighted sum of the losses to getcombinedloss. When I multipliedtorch_mseby 2, both the loss and gradients are changed accordingly but for themy_mse, they d... | ptrblck | You are not using grad_output in your custom backward method, which will be scaled, and are thus not seeing any effect of the incoming gradient. |
Arturas_Druteika | I new to Pytorch so I decided to start with cats vs dogs dataset. The problem which I don’t understand is that for some reason no matter how I change my model my loss doesn’t decrease below 0.69. Loss reaches this number after first epoch and after that no matter how many epochs it is not changing (in 10 epochs it reac... | ptrblck | The loss calculation for nn.BCELoss looks wrong, as this criterion expects the model outputs to be probabilities provided via a sigmoid activation, while you are applying torch.max on it.
Besides that the code looks alright and I cannot find anything obviously wrong.
I think you’ll find some posts… |
vthieb | Hi everyone,I know the issue has sometimes been raised, but I couldn’t solve my problem with other posts.I’m trying to run an experiment with a basic 2-layer MLP. I load a dataset, perform training for a few epochs, and then I want to use the model. However, the error:RuntimeError: CUDA error: an illegal memory access ... | ptrblck | I don’t know which PyTorch release you are using but in case it’s an older one: could you update to the latest stable or nightly release and check if you would still run into this error?
If so, could you post a minimal and executable code snippet to reproduce the issue? |
velenos14 | I cannot move a tensor created on the GPU to the CPU in libtorch.I do:auto options_for_Psi_spec = torch::TensorOptions().dtype(torch::kComplexDouble).device(torch::kCUDA, 0);
torch::Tensor Psi_spec = torch::zeros( {100, 32, 65}, options_for_Psi_spec );
Psi_spec.to(torch::kCPU);
std::cout << Psi_spec.device() << std::en... | ptrblck | The to() operation is not an inplace operation for tensors so you would need to re-assign the result. |
The_Snail | Hi,I am getting this error when trying to run my model training on cloud machine:File "/anaconda/envs/azureml_py38/lib/python3.8/site-packages/torch/nn/functional.py", line 2438, in batch_norm
return torch.batch_norm(
RuntimeError: cuDNN error: CUDNN_STATUS_EXECUTION_FAILEDThe code is running fine in the local mach... | ptrblck | Could you update PyTorch to the latest stable or nightly release and check if you would still see the issue? |
AlexB | I’m trying to use autograd to find the gradient of a function I’ve written as:import numpy as np
import torch
import matplotlib.pyplot as plt
from AFutilsPhaseMag import getParams
# get shared sim parameters (these don't change w/in a run in this test)
[f0, rho, tht, x, y, fi] = getParams()
# def varaibles
# want t... | ptrblck | I don’t see any usage of a in any calculation unless I’m missing it, so it’s expected to see None gradients for it as the loss doesn’t depend on it. |
Arupreza | My model:# Fully connected neural network with one hidden layer
class GRU_Model(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, num_classes):
super(GRU_Model, self).__init__()
self.num_layers = num_layers
self.hidden_size = hidden_size
self.gru = nn.GRU(input_size... | ptrblck | Could you update to the latest stable or nightly release and check if you are still running into this error? |
Jie_Zhang | tensor A:shape (1024 128 3)tensor B: shape (1024 10)(the value in tensor B is index number of A at dimension 1)tensor C:shape (1024 10 3)how can I get tensor C from A with index B | ptrblck | This should work:
A = torch.randn(1024, 128, 3)
B = torch.randint(0, 128, (1024, 10))
C = A[torch.arange(A.size(0)).unsqueeze(1), B]
print(C.shape)
# torch.Size([1024, 10, 3]) |
Brando_Miranda | @ptrblck@albanDapologies for the direct ping. Unsure who to ping.I am facing this issue too but I know this should not be happening. All weights should be being used.Is it possible to improve the error message and display the name of the weights causing this issue? It would help me to even start where to debug this.My ... | ptrblck | I think the failure in your code is expected as you are passing a view of a (with a valid .grad_fn) as the input to torch.autograd.grad. a.view(-1) is thus also not a leaf tensor anymore. |
aure_bnp | Hi evreyone, I have an issue when running this coe`class GraphSAGE(torch.nn.Module):definit(self, in_feats: int, h_feats: int, num_classes: int, aggregator:list = [‘mean’, ‘mean’]):super(GraphSAGE, self).init()self.conv1 = SAGEConv(in_feats, h_feats, aggregator[0])self.conv2 = SAGEConv(h_feats, num_classes, aggregator[... | ptrblck | That is correct since argmax is not a differentiable operation. Calling .requires_grad_() on the result won’t re-attach it to the computation graph. |
NullPointer | Hi, I’m trying to run a project within a conda env. I have a rtx 3070ti installed in my machine and it seems that the initialization function is causing issues in the program.Error:File "sTrain.py", line 37, in <module> torch.cuda.set_device(gpuid) ... | ptrblck | It seems you’ve installed a new driver while an older CUDA toolkit was still installed.
Try to compile CUDA examples and execute them to make sure your setup is working fine.
If that’s not the case, uninstall the driver and CUDA toolkit and reinstall it. |
Adamits | I am getting an error when I try to compute model FLOPs with the torchevalmodule_summary.Specifically, the issue seems to be thatmodule_summarycalls the forward function on every submodule of my model (seehere), unpacking the provided args and passing them through.Since one of my submodules is annn.LSTMthat I pass aPac... | ptrblck | I would recommend posting this issue in the torcheval GitHub repository to track and fix it, as it’s still in its alpha stage. |
jS5t3r | I would like to shuffle my data (without dataloader).Is there a function like infrom sklearn.model_selection import train_test_split? | ptrblck | I would probably just use train_test_split directly to split the data indices and create Subsets using these shuffled and split indices. |
core-not-dumped | I want to replace the parameters inside a model with a custom nn.Module layer that I created. Below is a very simplified example of the code I desire.Code:import torch
import torch.nn as nn
class change_to_layer(nn.Module):
def __init__(self):
super().__init__()
self.w = nn.Parameter(torch.randn(100, 100))
... | ptrblck | You could delete the parameter first via del model.scale before assigning the new module to this attribute. |
biock | When I run the official demo of PyTorchDistributedDataParalleltraining (“elastic_ddp.py” fromInitialize DDP with torch.distributed.run/torchrun), I found redundant model copies were created on GPU:0.Are there any solutions to avoid creating extra copies? Thanks!Environment:PyTorch: 1.12.1Python: 3.9.7cuda: 11.6Run the ... | ptrblck | You could set the device via torch.cuda.set_device(rank) and use torch.cuda.current_device or the rank to move the model and data to the corresponding device. |
TheMountain | Hi!I’m trying to make my own nn.Module where the input and outputs are both 2D grayscale images. Each 2D output pixel (ignoring batches for now) will copy a pixel in the input 2D image, according to a provided lookup tensor of 2D co-ordinates. So, for example, this snippet would rotate the corner pixels (the ones wit... | ptrblck | Direct indexing should work:
input_image[coords_to_look_up[:, :, 0], coords_to_look_up[:, :, 1]] |
Jan_Spiegel | Hi all,I have translated the brain MRI scans here:figsharebrain tumor datasetThis brain tumor dataset contains 3064 T1-weighted contrast-inhanced images with three kinds of brain tumor. Detailed information of the dataset can be found in readme file.into a pickle dataset containing 3,064 OpenCV RGB images. My pickle da... | ptrblck | The issue is raised by ToPILImage as you are passing a numpy array in an unsupported dtype to it:
transforms = transforms.ToPILImage()
# works
x = torch.randint(0, 256, (3, 224, 224)).byte()
img = transforms(x)
# works
x = torch.randn(3, 224, 224)
img = transforms(x)
# fails
x = np.random.randn(… |
GeoffreyChen777 | Hi, suppose we have two losses, I tried to sum these losses first and then do the backward / backward them one by one. I think that the gradients wrt a layer should be equal. But I found that it is different.cudnn.deterministic = True
cudnn.benchmark = False
torch.manual_seed(2)
torch.set_printoptions(precision=16)
a... | ptrblck | The first difference would be expected and caused by the limited floating point precision.
In your second model you are also comparing the absolute errors instead of the relative ones. Since the gradients have already a huge magnitude:
grad_l1_1.abs().max()
tensor(5.4373049958400000e+11, device='c… |
_Malte | Hey thereI have to split the EfficientNet-b4 model w.r.t. it’s stages. In table 1 of theoriginal paper, you can find the individual stages of the EfficientNet. I am curious whether my approach is correct or will lead to wrong results.Here is a code snippet:import torch
import torch.nn as nn
from torchvision.models impo... | ptrblck | Missing functional API calls sound wrong and would change the output.
I would thus recommend setting the model into .eval() mode and comparing its outputs with the original model to see if anything else causes numerical mismatches. |
noahw31 | Hello everybody. I want to train a Network and my data is of following nature:I have multiple measurement results stored in np.arrays, these measurements are indpenedent from each other and should not be mixed up, however they should all be used for training. The data is sequential, meaning we have to maintain the temp... | ptrblck | This might not be trivial since the DataLoader will just index the ConcatDataset in order as seen here:
dataset1 = TensorDataset(torch.arange(10).float())
dataset2 = TensorDataset(torch.arange(1, 11).float() * 10)
dataset3 = TensorDataset(torch.arange(1, 11).float() * 100)
dataset = torch.utils.d… |
annada | Consider the tensors,x = tensor([[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.]])
y = tensor([0., 0.])I want to batchedtorch.hstackto output something like,torch.stack([torch.hstack((i, y)) for i in x])which outputs,tensor([[1., 1., 0., 0.],
[1., 1., 0., 0.],
... | ptrblck | Concatenating tensors will not break the computation graph as seen here:
x = torch.tensor([[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.]], requires_grad=True)
y = torch.tensor([0., 0.], requires_grad=True)
z = torch.cat((x… |
AlphaBetaGamma96 | TL;DRIs there anyway to getgradcheckto work for multiple samples?Hi All,I’ve been usingtorch.autograd.gradcheckto validate a customtorch.autograd.Functionobject I’ve written, however, I’d like to test the accuracy of the backward method for multiple samples via finite-difference.Thetorch.autograd.gradcheckmethod checks... | ptrblck | You are already executing the gradcheck inside vmap which will directly return a bool value while a function is expected.
Besides that also tensors should be returned so more changes are needed.
Also, I’m using an internal attribute to unwrap the tensor inside vmap, which I assume could easily bre… |
raining_day513 | As title. During the backward pass, those tensors thatrequire_gradientwill be set so that their gradient can be used by the optimizer later on. Now I’m interested in whether or not an optimizer will deallocate the GPU memory of these gradients. | ptrblck | Yes, optimizer.zero_grad() will use set_to_none=True by default in newer PyTorch versions and will thus delete the .grad tensors to be able to reuse this memory. |
Ivan_Sizykh | After I restarted docker container with torch based application torch.cuda.is_available() freezes there, not letting to start application over. Not only it never returns anything inside container now, but also on outside as well in different environments.CUDA Version: 12.0. OS Ubuntu 20.04. Container image: pytorch/pyt... | ptrblck | The errors sound like driver issues and I would recommend reinstalling them and updating PyTorch to the latest version if possible. |
Ali_Youssef | Hello everyone!I was wondering is it possible to save a list or a PIL image to GPU memory without converting it to a tensor?My problem is, I save my entire trainign data on RAM, which is okay; however, RAM is not enough to store validation data as well.What I had before is, I was saving all data to RAM or cda and apply... | ptrblck | No, since PIL.Images use numpy to store their data which does not support GPUs. You would thus need to transform the data to a tensor (e.g. via torch.from_numpy) and could move it to the GPU afterwards. |
Sravan_nani | I’m facing challenge working on NLP application, where I can provide batch size at max 2 due to memory issue (I’m using 8 gb GPU).I want to increase my batch size because model is not converging well with small batch size.My question is instead of using the gradient accumulation, can i use the following procedure ?“”"“... | ptrblck | Since you are scaling the losses during gradient accumulation the gradients should be the same at the end. However, some layers use the batch size for their computation, such as batchnorm layers which calculate the stats from the incoming activation tensor, which would show different behavior in the… |
NagisaKaworuAdam | I’m new to PyTorch low level stuff.When using nn.Conv2d, I guess, there should be some low level CUDA code for doing the real convolution operations, right? Where to find them in the PyTorch or somewhere else?I have implemented some optimized convolution operations in CUDA (C++) and I am trying to replace my code into ... | ptrblck | Your code looks good. One minor suggestion: don’t use the deprecated .data attribute but initialize the parameter in a with torch.no_grad() guard using methods from the torch.nn.init namespace. |
KedirAli | I had trained PyTorch pretrained mobilnet-v2 model using image and meta-data. it worked well on training, validation and test data and i saved the best checkpoint. later on, model inferencing i get the above TypeError. I am expecting someone who can suggest the cause of the error and the possible solution.here is the m... | ptrblck | As the error message explains, you are passing a tuple to the forward method (as the first argument), while tensors are expected. Unwrap the tuple or pass the tensors via:
preds = model(img, meta_data)
and it should work. |
JWageM | Tensors have a function: register_hook.register_hook(hook)[SOURCE]Registers a backward hook.The description says that everytime a gradient with respect to the tensor is computed the hook will be called.My question: what are hooks used for?Kind regards,Jens | ptrblck | You could pass a function as the hook to register_hook, which will be called every time the gradient is calculated.
This might be useful for debugging purposes, e.g. just printing the gradient or its statistics, or you could of course manipulate the gradient in a custom way, e.g. normalizing it som… |
Lukas_Schroth | Hi all,I am currently facing the following problem:Given a list of inital values and a list of corresponding learning rates (sizes not know before), I want to pass the values to an optimizer with the corresponding lr specified in the lists. I cannot just create a single tensor and slice it when passing to the optimizer... | ptrblck | That’s not the case since the list would only store the tensor with its metadata while the actual internal data of the tensor would still be on the GPU.
I also don’t fully understand your use case as it seems you would initialize the optimizer only once, so even a slow loop shouldn’t matter compar… |
CNN0909 | I am a little bit confused as to how to calculate the train and valid_loss, searching the forums I think this might be the correct answer but I am still posting this qeustion as a kind of sanity check.I first define my loss function, which has the default value reduction = “mean”criterion = nn.CrossEntropyLoss()Then I ... | ptrblck | Yes, your approach looks correct as you are scaling the losses with the actual sample size in the current batch. Afterwards you are dividing it by the number of samples in the entire dataset to avoid a potential bias in these loss and accuracy calculations. |
sirius777coder | I want to download pytorch with cuda=11.7. I find not only pip install but also conda install will download the cudatoolkit.The pip comand ispip install torch==1.13.1+cu117 torchvision==0.14.1+cu117 torchaudio==0.13.1 --extra-index-url https://download.pytorch.org/whl/cu117The conda comand is :conda install pytorch==1.... | ptrblck | I’m not sure I understand the question completely, but both binaries ship with their CUDA dependencies and allow you to execute PyTorch code directly without installing a full CUDA toolkit locally. You would only need to install the NVIDIA drivers. |
abhisek | Consider the followingpytorchmodel:class MyModel(nn.Module):
def __init__(self. layer1: nn.Module, layer2: nn.Module):
self.l1 = layer1
self.l2 = layer2
def forward(self, x):
return self.l2(self.l1(x))With pre-trainedlyr1andlyr2if I instantiatemodel = MyModel(layer1=lyr1, layer2=lyr... | ptrblck | Assuming lyrx are already properly initialized with the pretrained weights your code should work fine.
Loading the state_dict afterwards again would not be needed if it was already done. |
Amin1091 | Hi,I have two trained models with the same architecture and different performances. I want to construct a new model by taking the weighted average of their states (s1, s2, s1+s2=1) and calculate the gradients of the new model’s loss with respect to s1 and s2. Here’s my current approach:Create a simple model:import torc... | ptrblck | You might be able to use the functional_call approach as explainedhere. |
Sreetama_Das | Hi, I am sorry for repeating this issue which has been posted here many time before. I am getting the following error:File "/home/sd/anaconda3/lib/python3.10/site-packages/torch/nn/modules/conv.py", line 459, in _conv_forward
return F.conv2d(input, weight, bias, self.stride,
RuntimeError: cuDNN error: CUDNN_STATUS_... | ptrblck | I would uninstall all PyTorch and nvidia-* packages and install a single binary with the desired CUDA version. Alternatively, you could also create a new and empty virtual environment and install PyTorch there. |
Niraja | I am working on different image sizes. I am getting this error.image922×762 12.6 KBI have print the size of images. How should I debug this error. Thank you in advance | ptrblck | The error is now raised from the mean subtraction since you are creating a grayscale image with a single channel while the mean and std are defined with 3 values.
Use transforms.Grayscale(num_output_channels=3) or a single value for the stats in Normalize and it should work. |
rhwang | Here’s a code example.import torch
import torch.cuda.nvtx as nvtx_cuda
A = torch.rand(size=(1024*4, 1024*4), device="cuda")
B = torch.rand(size=(1024*4, 1024*4), device="cuda")
C = torch.rand(size=(1024*4, 1024*4), device="cuda")
D = torch.rand(size=(1024*4, 1024*4), device="cuda")
E = torch.rand(size=(1024*4, 1024*4)... | ptrblck | torch.nonzero() causes a host-device synchronization as described in thedocsas, I believe, the size of the output tensor has to be computed on the host first since its data-dependent. |
HermitSun | I met an unexpected memory allocation intorch.cuda.memory_snapshot()when I ran the following code:import torch
W = torch.rand(1000, 10).cuda()
b = torch.rand(10).cuda()
X = torch.rand(1000).cuda()
y = X @ W + b
print(torch.cuda.memory_snapshot())SinceWrequests 1000 * 10 * 4B = 40000B,brequests 10 * 4B = 40B,Xrequests... | ptrblck | This behavior looks expected as we are allocating a cuBLAS workspace.
You could delete it via torch._C._cuda_clearCublasWorkspaces() and rerun the memory snapshot again.
Also@eqypointed out that e.g. removing the cuBLAS workspace via:
import os
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":0:0"
be… |
vanto | OverviewI am trying to train a model that can have a rather complex loss function that does operations using the output of the model. The easiest way to do these operations is to use the internal machinery of a second model to compute the loss. This causes the pytorch to lose the gradients.Is there a way to have pytorc... | ptrblck | The tensor is detached since you are copying the intermediate activation into the weight in a no_grad context.torch.func.functional_callshould work as seen here:
# create a basic model
class Linear(nn.Module):
def __init__(self):
super().__init__()
self.l = nn.Linear(1, 1, bi… |
Junxuan_Chen | Suppose I have a module combined some submodule, like:class Comb(nn.Module):
def __init__(self, encoder, decoder):
super(Comb, self).__init__()
self.encoder = encoder
self.decoder = decoderWhen distribute training, I warp the module with DDP:comb = DDP(comb)
raw_comb = comb.moduleNow in trai... | ptrblck | Yes, if you are accessing the internal .module the DDP wrapper won’t be used and you would execute the raw model on each device separately. |
Mohamed_Farag | Hi,I have a question I loaded the data in two different ways from numpy array, however there is a one which consumes more GPU memory compared to the another oneFirst method:X_train = torch.from_numpy(X_train).cuda() # transform to torch tensor
y_train = torch.from_numpy(y_train).cuda()
X_val = torch.from_numpy(X_val).... | ptrblck | The allocated and used memory will be the same, but the cache might be different (and thus also the peak memory usage) as you are potentially moving the float64 tensors to the GPU first and are transforming them to float32 afterwards in the first example while you are directly using the (deprecated)… |
Mohamed_Farag | Hi,I am new to Pytorchand I want to load the dataset usingTensorDataset()train_dataset = TensorDataset(X_train, y_train)
test_dataset = TensorDataset(X_val, y_val)how to add transforms to this method? as I have already checked the normal dataset class and it was working normally.Thanks | ptrblck | TensorDataset doesn’t accept transformations and will just index the passed tensors.
If you want to apply transformations on these tensors you could create a custom Dataset, e.g. via:
class MyDataset(Dataset):
def __init__(self, data, target, transform=None, target_transform=None):
sel… |
Fnu_Ankur | I am training two networks at a time.network 1: 3 Linear layers; fc1, fc2, fc3network2: 3 Linear Layers + 2 additional matrices.Requires_grad = True for all the parameters of network 1network 2 copies all the parameters from network 1 using load_state_dict(…, strict=False), all the parameters(weights and bias) of netwo... | ptrblck | Your code will raise this error directly:
RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed).
since you are trying to call backward twice using q_pred.
Using loss_dqn.backward(retain_graph=True) fixes this error b… |
Mohamed_Farag | Hi,I am having a problem now, I am running my code on google colab with 12 GB Ram, I have images stored at numpy files and I want to transfer them to tensors, but the ram is crashing.This is my code:X_train, X_val, y_train, y_val = train_test_split(X,y, test_size = 0.10, random_state = 87, stratify = y)
X_train = torc... | ptrblck | These calls torch.from_numpy(X_train).float() will create a new copy on the host if the tensor is not already in float32 and will thus increase the memory usage.
Would it be possible to directly load the numpy arrays in their desired dtype?
Alternatively, you might want to move the tensor to the G… |
gerald-ftk | I’ve been trying to train a RetinaNet on the SKU110K dataset. The first issue I encountered is that theretinanet_resnet50_fpn_v2()function throws the following error when num_classes=2:model = retinanet_resnet50_fpn_v2(weights='DEFAULT', score_thresh=0.35, num_classes=2).to(device)
ValueError: The parameter 'num_class... | ptrblck | I would again refer to the linked tutorial since the PennFudanDataset also returns target with a variable number of bounding boxes:
dataset = PennFudanDataset('PennFudanPed', transforms=None)
for img, target in dataset:
print(target["boxes"].shape)
torch.Size([2, 4])
torch.Size([1, 4])
torch.… |
respect.yojic | Hello! Does somebody know what is this error means ‘RuntimeError: Expected input_lengths to have value at most 144, but got value 190 (while checking arguments for ctc_loss_cpu)’? I tried to implement conformer model and 144 - model dimension, but I can’t understand what is 190 number because I didn’t use this number.t... | ptrblck | I guess the input_length contains the length of 190 and raises the error.
Using the example from the docs reproduces it:
# works
# Target are to be padded
T = 50 # Input sequence length
C = 20 # Number of classes (including blank)
N = 16 # Batch size
S = 30 # Target sequence l… |
zhengyang_xu | I would like to use heat maps for pixel classification tasks. Currently, I have a classification heat map with predicted results, with dimensions (batch_num, C, H, W), as well as a ground truth heat map with dimensions (batch_num, C, H, W). At the same time, I want each pixel to have different levels of attention in di... | ptrblck | F.cross_entropy is used for a multi-class classification or segmentation use case where each sample or pixel is assigned to a single class only.
The output, if reduction='none' is used, will be the loss value for each sample or pixel location and thus no channel or class dimension is used. Note tha… |
YadneshD | My keras summary model shows that it has a add layer to sum few layers. Screenshot in drive link below -drive.google.comScreenshot from 2021-10-28 17-25-56.pngGoogle Drive file.I am a beginner and I don’t know how to implement the add layer in PyTorch. Actually I need to sum few layers convolution layers with previous ... | ptrblck | You can directly add PyTorch tensors in your forward without the need to use a layer:
def forward(self, x):
out1 = self.layer1(x)
out2 = self.layer1(x)
out3 = self.layer1(x)
out = out1 + out2 + out3
...
Alternatively, you could also create a custom nn.Module, pass the inputs to… |
KamikaziZen | Hello, I am writing a custom function that inherits fromtorch.autograd.Function. This function uses some parameter(likepdropfor dropout, for example) which is needed to compute gradients.class DummyFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, input, p):
ctx.save_for_backward(input)... | ptrblck | Wouldn’t storing p in the ctx via ctx.p = p work (assuming p is not a tensor)? |
LouisBao | When I training my custom model and fine-tuning the pretrained resnet50 with using torchvision.datasets.ImageFolder, I have underfitting/overfitting during training and get good 98% accuracy on validation. If I use torchvision.datasets.ImageFolder to load the test folder, i get very good prediction and confusion matrix... | ptrblck | How are you defining the targets in your manual approach and did you compare the class indices to what ImageFolder returns? |
retr00h | I’m creating a CNN to classify images from the MNIST dataset. I successfully created a class that extendstorch.nn.Moduleand a training function, however, i have to create a dataloader withbatch_size = 1, because when increasing the size I get the following error:---------------------------------------------------------... | ptrblck | The error is raised since your view operation is wrong and creates a 3D tensor while you want to create a 4D input in the shape [batch_size, channels, height, width].
Use img = img.view(img.size(0), 1, 28, 28) or just remove the view operation as the img tensor is already in the right shape.
Also,… |
Lost_Wanderer | Dear PyTorch community,today I encountered a bug which baffled me for quite a while. It’s related to saving the trained model weights, but I don’t know how to fix it, so that’s why I’m asking here.I’m implementing Transformer from scratch in PyTorch. I first wrote the code for the lowest layers of the Transformer, such... | ptrblck | PyTorch will save all parameters recursively from all submodules if these are properly registered.
I don’t know how TransformerInstance or any of its internal submoduels are defined and registered, but would guess that e.g. encoderBlocks might be a plain Python list instead of the required nn.Modul… |
ZhangJ | I used the codeCRNNand add horovod to do distributed training.when the dataset images about 1000w, the batchsize is 128, and used 6 V100, everything is ok.But when I add dataset, and the images about 1900w, the batchszie is also 128, this error happens when the network forwards the conv layer.I noticed somebody said d... | ptrblck | As you’ve already mentioned, the cudnn error might be raised, if you are in fact running out of memory.
Try to reduce the batch size until the use case fits in your GPU memory and let us know, if you still encounter a cudnn error. |
Devipriya_Raju | I have x of shape [32,16,16,16]. I am trying to use nn.UpSample() to make x of shape [32,32,32,32]. But i keep getting [32,16,32,32]. Can anybody please help on this? | ptrblck | nn.Upsample interpolates the spatial dimensions, not the channel or batch dims.
Since you explicitly also want to upsample the channel dimension (dim1) you could unsqueeze an additional dim before upsampling the input and squeezeit afterwards:
x = torch.randn(32, 16, 16, 16)
up = nn.Upsample(scale… |
pylearn | In my network, one computation only applies partially to a tensor/parameter. For example, square the 1st element of parameter w.I used two methods. The forward computations of these two methods are correct, but the gradients are different. Method 2 should be correct since it is just regular computation. Hence, Method 1... | ptrblck | Recreating a new tensor detaches the passed tensors from the computation graph and creates a new leaf tensor without a gradient history. Operations on self.v will thus not be backpropagated to self.w. |
ElijahZh | Hi,I am trying to add an item to the loss function. The item’s required_grad = False.Here is the structure:pred, x = net(input)loss = nn.MSELoss()(pred, target) + custom_function(x)The item: custom_function(x) is “required_grad=False”I know the during the grad process, this item is not going to help with gradient. But ... | ptrblck | No, adding a constant to a function will not change it’s derivative and thus gradients:
x = torch.randn(1)
w = torch.randn(1, requires_grad=True)
target = torch.ones(1)
out = x * w
loss = F.mse_loss(out, target)
print(loss)
# tensor(1.0523, grad_fn=<MseLossBackward0>)
loss.backward()
print(w.grad)… |
jayashprasad | def __init__(self, arg):
super(Net, self).__init__()
hidden_layer_dimension = arg
print(data.num_node_features,hidden_layer_dimension)
self.float()
self.conv1 = GCNConv(data.num_node_features, hidden_layer_dimension)
self.conv2 = GCNConv(hidden_layer_dimension, data.num_c... | ptrblck | int64 represents long in C/C++ and also PyTorch. |
Vinayaka_Hegde | Hi, I have a quick question. I just wanted to know which is the first version of pytorch that has thepre_backward_hookfeature enabled? I’ve tried usingv1.12.0but that doesn’t have thepre_backward_hookfeature.FYI :[nn] module: full_backward_pre_hook by kshitij12345 · Pull Request #86700 · pytorch/pytorch · GitHubwas the... | ptrblck | You would need to use 2.0.0 as the linked PR was merged on Oct 13, 2022 while PyTorch 1.13.0 was released Oct 28, 2022 and thus won’t contain this PR. |
richardatpytorch | I am using UNet in hub (U-Net for brain MRI | PyTorch) for the depth estimation task. I have no clue what is going wrong with this errorRuntimeError: only batches of spatial targets supported (3D tensors) but got targets of size: : [64, 1, 256, 256]Some context on my case: I am using pytorch lightning as a trainer and ... | ptrblck | The shape mismatch is raised in nn.NLLLoss so check thedocsand make sure the model output and target have the expected shapes.
I would guess you might need to squeeze dim1 in the target but since you didn’t explain the use case it’s just my guess. |
vthieb | Hi everyone!I recently tried to use a public repo that you can find here:USADI have an issue when using thetrainingfunction. I first create my own train and val loaders that I give as arguments:training(epochs, model, train_loader, val_loader, opt_func=torch.optim.Adam)It raises an errorTypeError: 'DataLoader' object i... | ptrblck | You are most likely passing the wrong number of arguments to this function and the DataLoader objects is mapped to the opt_func argument thus raising this error. |
sbht_sbht | Hello there! I am trying to train a model for segmentation for the first time. I found this way to load the model and the following loss function:from torchvision.models.segmentation.deeplabv3 import DeepLabHead
def createDeepLabv3(outputchannels=2):
"""DeepLabv3 class with custom head
Args:
outputchan... | ptrblck | Based on the error messages it seems the input to DiceBCELoss.forward is a dict while a tensor is expected.
Note that deeplabv3_resnet101 will indeed return a dict containing out and aux keys so you might want to index the out tensor before passing it to the loss function. |
nathan345345 | Error message:IndexError Traceback (most recent call last)
<ipython-input-57-83c130993917> in <cell line: 5>()
3 get_ipython().system('rm -rf /content/models')
4 get_ipython().system('mkdir /content/models')
----> 5 train_losses, val_losses = train()
6 torch.cuda.empty_... | ptrblck | The classifiers defined in your model:
self.s_classifier = nn.Linear(256, 6)
self.r_classifier = nn.Linear(256, 163)
self.o_classifier = nn.Linear(256, 45)
output logits for 6, 163, 45 classes, respectively, while the targets contain class indices outside of the supported numbers of c… |
r00bi | I want to reduce a tensor with shape of (32,32,26, 40,10) to (32,32,512). Basically, I want to keep the batch size and sequence length, and embed the last three dimension to 512.How can I do this reduction using conv3d?Thanks! | ptrblck | I don’t know how you are interpreting the input data, but I guess you are treating the channel dimension in dim1 as the “sequence length”?
3D convolutions expect an input in the shape [batch_size, channels, depth, height, width].
I don’t think using a plain nn.Conv3d would work directly as you are… |
lisyuan | Hi everyone,I recently watch some code style for scaling gradient values without scaling loss value, but I am confusing about it. I implemented a simple example code myself below.torch.manual_seed(0)
x = torch.randn(2, 3, requires_grad=True)
y = 5
z = 2 * x
z_backward = z * y
z_new = z.detach() + (z_backward - z_backw... | ptrblck | The advantage of
z_new = z.detach() + (z_backward - z_backward.detach())
is that you will get z as the forward output and will use z_backward to calculate the gradients in the backward pass.
In the foward pass z_backward is cancelled due to the subtraction and only z.detach() will define the val… |
charlio23 | I am using torch.distributions.MultivariateNormal with large batches since I am working with long sequential data. For large batches, a runtime error from CUDA is thrown when computing the log_prob. Here is a snippet to reproduce the issue.import torch
cov = torch.eye(3).to('cuda:1')
means = torch.randn(540000,3).to('c... | ptrblck | Thanks for forwarding the issue! I can reproduce it in 2.0.0+cu118 and we’ll look into it. |
aarmbruster | I have a pytorch model, the forward pass looks roughly like the followingdef forward(self, x):
# following two encoders could be run in parallel
lidar_features = self.lidar_encoder(x['pointcloud'])
camera_features = self.camera_encoder(x['images'])
# need to sync here
combined_features = torch... | ptrblck | Both modules will be scheduled on the same CUDA stream and will thus run sequentially. You could use custom CUDA streams and synchronize the code manually and check if any performance improvements would be seen. Note that you might not see any overlaps if a) your CPU is too slow to schedule the kern… |
armal | I currently have a 2 tensors of size ([N, D]) and ([N, D, D]). The first one represents a N means and the second represents N covariance matrices. Currently I am having to create N different Multivariate Gaussians in a for loop and then evaluating the log probability of some data which has size ([X, D]) on each MV Gaus... | ptrblck | Wouldn’t this directly work using MultivariateNormal:
loc = torch.stack((torch.zeros(2), torch.ones(2)+100., torch.ones(2)+1000.))
m = torch.distributions.multivariate_normal.MultivariateNormal(loc, torch.eye(2)[None])
m.sample()
# tensor([[-8.6749e-02, -1.2250e-01],
# [ 1.0310e+02, 1.0090… |
richardatpytorch | Forgive me if I misunderstand this operator. Here is the transform that I am applying:output_size = 256
color_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Resize((output_size, output_size), antialias=True),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
... | ptrblck | transforms.Normalize subtracts the provided mean value from the tensor and divides by std to create a normalized sample. The values are calculated in a way to create a zero-mean and unit-variance output. The actual values are not bound to [mean-std, mean+std] as seen in this example:
x = torch.rand… |
zisisnotzis | I’m implementing a reversible convolution layer, so that forward pass does not need to savex.I have the inverse function already implemented. I’m wondering how do I reuse the original implementation of conv backward, without “re-implementing” it in python, but providectxmanually this time.Or is there any way to add “ho... | ptrblck | You could call the backward methods via:
torch.nn.grad.conv2d_input
<function torch.nn.grad.conv2d_input(input_size, weight, grad_output, stride=1, padding=0, dilation=1, groups=1)>
torch.nn.grad.conv2d_weight
<function torch.nn.grad.conv2d_weight(input, weight_size, grad_output, stride=1, padding… |
ralzq01 | I found matmul result is inconsistent with partitioned-matmal result using torch APIs/Consider the matmul calculation: Z = XY, which can be partitioned by Z = [X1 X2][Y1 // Y2] = X1Y1 + X2Y2, where X is partitioned by the second dimension and Y is partitioned by the first dimension. The results need to be reduced to ge... | ptrblck | Yes, numerical mismatches due to the limited floating point precision can be caused by a difference in the operation order as seen also in this small example:
x = torch.randn(100, 100)
s1 = x.sum()
s2 = x.sum(0).sum(0)
s3 = x[torch.randperm(x.size(0))].sum()
print(s1 - s2)
# tensor(-5.7220e-06)
pri… |
S_M | Hi all, when I trained renset50 with cross entropy loss in Google Colab I got this error:RuntimeError: CUDA out of memory. Tried to allocate 128.00 MiB (GPU 0; 14.75 GiB total capacity; 13.25 GiB already allocated; 126.81 MiB free; 13.51 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try se... | ptrblck | Take a look atthese docsto learn more about how to use torch.amp. |
netty | Many of the Pytorch tutorials seem to show a combination of tracing (torch.jit.trace) and scripting (torch.jit.script)However it seems like if all the code in a givennn.Module(even if it contains other modules) is compatible with Torchscript, then do you only need a single line to convert, ie:torch.jit.script(my_net_in... | ptrblck | Yes, you wouldn’t need to script submodules assuming no special conditions or tracing has to be used and should directly be able to script the model via torch.jit.script. |
Will_Z | I used this command to start distributed training: torchrun --standalone --nnodes=1 --nproc-per-node=2 train.pyHere is the first a few lines of error message:master_addr is only used for static rdzv_backend and when rdzv_endpoint is not specified.
WARNING:torch.distributed.run:
*****************************************... | ptrblck | This is correct, but you can search for the same issues here and will find some similar topics where “something”, e.g. in the data loading, changed and caused the issue without the user realizing it.
The nn.Embedding layer expects inputs containing values in [0, num_embeddings-1]. Check the word_… |
mzimmer | Suppose I have a couple of models given as state_dicts and instead of optimizing them further, I’d like for every batch to average these models (their weights!) with a weighting coefficient such as 0.1model_1 + 0.4model_2 +…However, I do not intend to optimize model_i further, I rather like to perform forward- and back... | ptrblck | That’s a good idea and I believe torch.nn.utils.parametrize could be provide a good approach for this use case:
import torch
import torch.nn as nn
import torch.nn.utils.parametrize as parametrize
class Average(nn.Module):
def __init__(self, w1, w2):
super().__init__()
self.w1 … |
HelixPiano | Hello everyone,I have a question about the way pytorch handles indices.My memmap file is really huge (~70Gb). I want to train my CNN on a certain subset of this memap which contains around half the data points which are not evenly distributed through the data set. I don’t want to create a second memmap file because thi... | ptrblck | Your workflow describes whattorch.utils.data.Subsetdoes and sounds reasonable. |
marcomixer99 | I have a big-image-encoder and a lot of (more than 200K) high resolution images. I want to save all the image-embeddings. I tried with TensorDataset but when i check if it was the same to load a saved-pre-calculated embedding or forrward the same image i see a little difference in the representation. In particular:torc... | ptrblck | A different order of operations can cause small, but expected, numerical differences as seen e.g. in this small example using sum:
x = torch.randn(100, 100)
s1 = x.sum()
s2 = x.sum(0).sum()
print((s1 - s2).abs().max())
# tensor(1.5259e-05)
If you want to get deterministic results you would have t… |
georgicd | Hello, I am having an issue with my data not being loaded in the same order all the time. As a result I am not getting the same accuracies every time. My code is the following:import numpy as np
import torch
from torch.utils.data import SubsetRandomSampler
import random
from sklearn.model_selection import train_test_sp... | ptrblck | Seeding the code and using generators will guarantee to create the same sequence of random values created by the pseudorandom number generator. It will not force the DataLoader and/or sampler to return exactly the same samples in all epochs.
If you want to force exactly the same order in all epochs… |
netty | Trying to convert my model for usage in a C++ application.I have a model file I cannot change, but trying to patch the Pytorch code to be torchscript compatible, but still use the same model weights.I have simplified the issue I’m seeing into a small example script here.Indexing into annn.ModuleListrequires a type hint... | ptrblck | I cannot reproduce the issue and get:
TypeError: <class '__main__.MyEncoderModuleInterface'> is a built-in class
running your code in 2.0.0.
After removing MyEncoderModuleInterface from submodule: MyEncoderModuleInterface = self.layers[i] I get:
RuntimeError:
Expected integer literal for index.… |
niccolot | Hello, it is my first post here and i hope i’m in the right place to ask. When i try to run the example code for thetorch_geometric.nnradious_graphi get an error:File "C:\Users\nico_\AppData\Local\Programs\Python\Python38\lib\site-packages\torch_geometric\nn\pool\__init__.py", line 210, in radius_graph
return torch... | ptrblck | The error is raised by torch_cluster.radius_graph as torch_cluster is apparently set to None.
At the top of the script you can see that import torch_cluster is used in a try ... except blockhereand will be set to None if the import fails.
Since all methods in this file seems to depend on torch_c… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.