user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
mghtyclu | Hi,Context: I need to use an old CUDA version (10.0) on a recent RTX30XX GPU. I am trying to build a container image for this purpose as the system uses CUDA 11.7. Since PyTorch support for the newer GPUs has only been added in recent versions I cannot find readily available images that combine CUDA10.0 and PyTorch >=1... | ptrblck | This won’t be possible since your Ampere GPU needs CUDA>=11.1. |
vivian528899 | Hi All,There is no error when I trained my code on GPU and used thedtype=torch.float16.But when I run my code on CPU, I got the errorRuntimeError: “tanh” “_vml_cpu” not implemented for ‘Half’I assume becausetorch.halfisn’t supported bytorch.tanhon CPU?Is there any method can dotanhindtype=torch.float16?Thank you! | ptrblck | Yes, you are right and the float16 support on CPU is sparse as no speedups are expected, if I’m not mistaken. The default mixed-precision dtype on the CPU would be bfloat16. |
Koramajin | I got a problem with the CUDA kernel of torch.nn.CrossEntropyLoss. It fails in its forward function caused by an illegal memory access. I posted myissuein github. Hope it will get reponsed quickly.For large input tensors currently, I divide the input tensor to multiple segments and call multiple times of F.cross_entro... | ptrblck | Yes, GitHub issues are seen and it seems to be a duplicate ofCUDA Illegal memory access on CrossEntropyLoss with large batch size, cu113, torch 1.12.1 · Issue #85005 · pytorch/pytorch · GitHub |
Takumi3 | hi, I have a problem.I want to try deep learning with Transformer_encoder. But I got error message like below.RuntimeError: CUDA error: device-side assert triggeredI want to have any suggestions.I’m putting code here.class Encoder(nn.Module):
def __init__(self, num_embeddings, embedding_dim, num_layers):
su... | ptrblck | My guess might be right and the indexing in the embedding layer self.em1 fails so make sure the input contains valid values in [0, num_embeddings-1]. |
cbd | When “for i, data in enumerate(dataset):” called, dataloader call one image at time and do pre processing in “getitem” one image at time and create batch of 8 image in “data”. How can i track the number of the image in current process in “getitem”?For example in first batch when first image process, i need number 1. Wh... | ptrblck | If you are not shuffling the dataset, you could just use the index in __getitem__. However, I don’t know what exactly your use case is and how multiple workers and shuffling should be handled. You might be able to create a custom sampler, which could pass this additional information to the __getitem… |
bryan123 | cfg = {‘VGG11’: [64, ‘M’, 128, ‘M’, 256, 256, ‘M’, 512, 512, ‘M’, 512, 512, ‘M’],‘VGG13’: [64, 64, ‘M’, 128, 128, ‘M’, 256, 256, ‘M’, 512, 512, ‘M’, 512, 512, ‘M’],‘VGG16’: [64, 64, ‘M’, 128, 128, ‘M’, 256, 256, 256, ‘M’, 512, 512, 512, ‘M’, 512, 512, 512, ‘M’],‘VGG19’: [64, 64, ‘M’, 128, 128, ‘M’, 256, 256, 256, 256, ... | ptrblck | No, the nn.Sequential container will not use more memory than calling layers manually.
Note that you are storing additional features in the forward pass (along with the computation graph), which will of course increase the memory usage, so the OOM might be expected. |
pepper8362 | Hi,I find the forward pass result of the same data can be different with different batch size. Specifically, I run the code below:import torch
import torch.nn as nn
import numpy as np
from torch.utils.data import Dataset, DataLoader
class SimpleNetwork(nn.Module):
def __init__(self):
super().__init__()
... | ptrblck | This is expected due to the limited floating point precision, as different algorithms can use a different order of operations. For float32 you would usually expect a rel. error of ~1e-6, but it also depends on the number of accumulations etc.
You would also expect to see the same on the CPU as it’s… |
prashp | Let’s say I have 2 image folder datasets and I want to concatenate them.The first dataset has 100 images with 2 equal classes: “Dog” and “Cat” with class indices 0 and 1The second dataset has 120 images with 3 equal classes: “Dog”, “Cat” and “Pig” with class indices 0, 1 and 2When I concatenate the two datasets with to... | ptrblck | ConcatDataset will not create a mapping, but just index the passed Datasets.
Each Dataset should make sure to yield the “right” labels.
E.g. in your second use case, you should make sure that dataset1 only yields samples with the class labels 0 and 1 (dog and cat), while dataset2 should only yield… |
Jegp | I’m extracting a pointer for the underlying memory on the GPU for a tensor with bytes like so:auto opt = options_buffer = torch::TensorOptions()
.dtype(torch::kUInt8)
.device(torch::DeviceType::CUDA)
.memory_format(c10::MemoryFormat::Contiguous);
auto buffer = to... | ptrblck | Yes, you need to either access the device array in a kernel or would need to copy it back to the CPU.
I don’t think this should have ever worked as it’s expected behavior in CUDA. PyTorch did not add any memory protection etc.
E.g. look atthis simple examplewhich:
allocates host and device mem… |
sammlapp | Hi, this is a basic understanding question: how can I make a DataLoader start preparing the next batch while a model runs .forward() and .backward() on the previous batch?When we write a loop to train or run inference with a PyTorch model, we loop over a DataLoader to get the next batch of samples, then run model.forwa... | ptrblck | Yes, if multiple workers are used they will prepare the next batch and won’t wait until the training loop finished. Once the queue is full, the workers will wait as@nivekdescribed and you can change the behavior via the prefetch_factor.
Here is a small example:
class MyDataset(Dataset):
def… |
Rexedoziem | What is the difference between embedding layers and linear layers, and how it works in nlp? | ptrblck | Yes, you can use the output of embedding layers in linear layers as seen here:
num_embeddings = 10
embedding_dim= 100
emb = nn.Embedding(num_embeddings, embedding_dim)
output_dim = 5
lin = nn.Linear(embedding_dim, output_dim)
batch_size = 2
x = torch.randint(0, num_embeddings, (batch_size,))
out… |
Jeet | I would like to know that which distribution does PyTorch follows now for the default initalisation of the weights and the biases? For example when I write something like -self.neural=nn.Sequential(nn.Linear(in_features,4))I need the mathematical formulation of the initalisation. | ptrblck | The parameters are initialized in the reset_parameters method of the corresponding layer. For nn.Linear you can find the methodhere:
def reset_parameters(self) -> None:
# Setting a=sqrt(5) in kaiming_uniform is the same as initializing with
# uniform(-1/sqrt(in_features), 1/sqr… |
magnusderrote | Everywhere I read, people say just passretain_graph=Trueto solve my issue, but I’d like to know what is under the hood. For example, theloss.backward()below doesn’t need to pass in anyretain_graphclass Mnist_Logistic(nn.Module):
def __init__(self):
super().__init__()
self.lin = nn.Linear(784, 10)
... | ptrblck | Which is unfortunately generally wrong.
Do not pass retain_graph=True to any backward call unless you explicitly need it and can explain why it’s needed for your use case.
Usually, it’s used as a workaround which will cause other issues afterwards. The mechanics of this argument were explained we… |
georgeyiasemis | ProblemRunning a torch.distributed process on multiple 4 NVIDIA A100 80G gpus usingNCCLbackend hangs. This is not the case for backendgloo.nvidia-smiinfo:+-----------------------------------------------------------------------------+
| NVIDIA-SMI 470.103.01 Driver Version: 470.103.01 CUDA Version: 11.4 |
|-----... | ptrblck | Was NCCL working before on this node?
If not, could you check if disabling IOMMU helps as describedhereas it could also cause a hang? |
zhengyang_xu | Hi, Im a begineer in pytorch. As we all know, we should not use view() or reshape() to swap dimensions of tensorsDo not use view() or reshape() to swap dimensions of tensorsbecause it can make wrong in computing gradient.but how can I flatten a matrix to a vector. I have already triedtorch.flattenbut it still said it’... | ptrblck | You can still use view of flatten, but should be careful about the expected output. In the linked post@vdwexplains that permute is the right operator to permute the axes and that view would interleave the data.
This issue is not related to the usage or permute or view and is often caused by a w… |
ran_ran1 | I am new here and I’m new to using the torch library for autoencodersI want to implement a pre-written code with the same dataset used. There are no errors, but it is not executed. When I track the execution it seems that it is stuck in this loop(for batch_idx, (batch_data, batch_index) in enumerate(zip(input_trainLoad... | ptrblck | If you are using multiprocessing in your DataLoaders, try to use the main process only for debugging via num_workers=0 and see if your code doesn’t hang anymore. |
hitbuyi | I want to know whether Pytorch gives any information if the weights doesn’t fit the model | ptrblck | Yes, PyTorch will raise shape mismatch errors and will fail if additional or unexpected keys are found in the state_dict unless you specify strict=False while loading the state_dict. |
flummery | I’m trying to break down the error I’m getting from the loss function. My train function is below:model = model.to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=LR)
criterion = nn.CrossEntropyLoss()
for epoch in range(2):
for idx, (img, label) in enumerate(train_dl):
print(img.shape, label.sha... | ptrblck | Your output in the shape [32, 64, 27, 5] indicates a multi-class segmentation using 64 classes. For this use case the target should have a shape of [32, 27 ,5] containing class indices in the range [0, 63].
If you are not working on a segmentation but a multi-class classification as the target shap… |
joohyunglee | I want to train an encoder, which contains batch-normalization layers, with two different losses. I use all the samples from the minibatch to computeloss1, whereas I can only use a portion of samples within a mini-batch to computeloss2(due to the heavy computation burden ofloss2). *More specifically, theloss2is a varia... | ptrblck | I don’t think you should expect to see any problems besides the obvious limitations that the gradients from loss2 would only be calculated based on the indexed features while the rest will be ignored, but this seems to fit your use case. |
SouthTorch | This is the first time I define my own datasetI want to define a dataset, each entry of which is one image associated with a value.When I define the dataset, should I define the self.samples as an array of:one string containing the image disk path, and one floating valueorthe real image RGB value matrix and one floatin... | ptrblck | The __getitem__ function is called then the Dataset is indexed either directly:
x, y = dataset[index]
or from the DataLoader by e.g. iterating it:
for data, target in loader:
...
Internally the DataLoader will use the sampler to create indices and index the internal Dataset with it.
Yes, … |
uyoung | I am trying to run DDP or DP with two A100 gpus on server, but whenever the machine accesses the computed loss, the process freezes infinitely. I have to exit the process with ctrl+z and manually kill the process.I made a simple script which trains resnet18 on CIFAR-10, with or without DP.The script runs smoothly when ... | ptrblck | Check ifIOMMUis enabled and disable it to avoid hangs. |
joohyunglee | Somehow,kornia.augmentation.RandomGaussianBlurunderwith torch.cuda.amp.autocast():converts the datatype from float to half. Is this expected? How can I disable the data type conversion? Thank you ahead. | ptrblck | You might need to transform the inputs to float32 if they are already in float16 as described in thedocs.
Also, your current code snippet does not show any nested autocast context which is disabling it as I’ve previously suggested, so unsure why you are not using this approach. |
renken | Hi, i want to define anactivation function with 2 trainable parameters, k and c, which define the function.I want my neural net to calibrate those parameters aswell during the training procedure. Do you have an idea on how i can manage to do that in few lines? I am really new on pytorch.Here is my code for the moment, ... | ptrblck | You can create a custom nn.Module and define both parameters as trainable. Something like this could work:
class MyActivation(nn.Module):
def __init__(self):
super().__init__()
self.c = nn.Parameter(torch.tensor(0.5))
self.k = nn.Parameter(torch.tensor(0.25))
… |
pepper8362 | Hi,Do torch.stft and torch.istft support autograd? Is there a way to back-propagate through them?Thanks | ptrblck | Yes, Autograd is able to backpropagate through these methods as seen in this small example:
input = torch.randn(16, requires_grad=True)
out = torch.stft(input, 10)
out.mean().backward()
print(input.grad)
# tensor([-3.5224e-02, 1.5741e-01, -6.3721e-02, 1.5741e-01, -2.8497e-02,
# 1.4815e-… |
bryan123 | class Net(nn.Module):definit(self):super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def get_features(self, x):
x =... | ptrblck | It’s unclear where the error is raised and how this model should be replaced with a VGG16 model, so could you explain your use case a bit more and post a code snippet which raises the current error? |
nestiank | Hello,I am using CUDA 11.4 for my NVIDIA T4 GPU from AWS.(That’s what my nvidia-smi says. I have cudatoolkit==11.1.1.)I need to use nightly build of PyTorch, but there are binaries supporting cu102, cu116, cu117.I know that using cu113 binaries with cu114 GPU is possible (as back-supported),but I am not sure about if u... | ptrblck | Yes, you can use the binaries with a newer CUDA 11.6 runtime and an older driver installed on your system. |
sapiosexual | I am training vision CNN model (MoViNetA2 to be specificthisparticular implementation). This model has 4.1M parameters which ends up into 16.5 MB of model size. For training I use Tensors size of (4, 3, 50, 224, 224) which consume around 122MB. Howevertorch.cuda.memory_summary()reports over 16GB GPU memory allocated be... | ptrblck | You might be forgetting the intermediate activations, which need to be stored for the gradient computation.This postdescribes a similar use case for a ResNet. |
Fei_Liu | I want to ship a.sofile for client usage (same platform). The client does not have LibTorch installed. Can I somehow pack all the depended libraries into one single library for client usages? Thanks! | ptrblck | I think the first step is to check which libs you exactly want and which one should be statically linked. If I understand your use case correctly, you don’t want to ask the user to install e.g. MKL, but want to provide it. Besides shipping the library in your installation (and dynamically linking to… |
AP_M | When I run the code, getting the error as:AttributeError: 'list' object has no attribute 'values'AttributeError Traceback (most recent call last)
<ipython-input-37-66115a52c5d6> in <module>
23 optimizer.zero_grad()
24
---> 25 output = model(X_tr)
26 optimizer.zero_... | ptrblck | Make sure to pass a dict to this method, not a list. |
haoran-hash | After i read the Pytorch docs, i think it’s not.But what about this situation ?op1output a Tensoroutput1(dtype=torch.float16). The next operationop2is FP32 type, so it needstorch.float32input. Now, doesop2need to convertoutput1dtype totorch.float32? | ptrblck | No, autocast does not convert everything to float16, as it’s numerically not stable enough for a lot of use cases. You could perform if via directly calling model.half() and wouldn’t need autocast for it.
Yes, the transformations are done when needed. |
Ken_Zheng | Hello, I have ten python pickle files, such 1.pkl ~ 10.pkl, every pickle file larger than 10GB,whth the RAM limited, How can I:Load 1.pkl in dataset,training complete, thenLoad 2.pkl in dataset, continue training…Load 10.pkl in dataset, continue trainingEpoch endHow can I achieve this? Thank you | ptrblck | You could implement exactly the logic you’ve described:
create a custom Dataset accepting a path to the pkl file
use a loop iterating all 10 paths
create a new Dataset using the current path
train your model inside the loop |
ysleer | hello.No matter how much I think about it, I ask a question because there is something I don’t understand.We trained with the training code and saved the weights.When I called the stored weights as demo code and looked at the output, the result was completely different.I don’t know why.So as an additional experiment, w... | ptrblck | I would recommend to use a static input (e.g. torch.ones) and compare the outputs of both approaches.
If these outputs are already different, the model’s parameters and/or buffer might not have been loaded correctly or the model has some randomness in its operations (e.g. dropout is used when you’v… |
Diego | When I try to run PyTorch using the latest docker image (nvcr.io/nvidia/pytorch:22.08-py3) it breaks onimport torchgiving the following stacktrace:Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/mnt/home/.local/lib/python3.8/site-packages/torch/__init__.py", line 811, in <module>
... | ptrblck | It’s working for me:
Status: Downloaded newer image for nvcr.io/nvidia/pytorch:22.08-py3
=============
== PyTorch ==
=============
NVIDIA Release 22.08 (build 42105213)
PyTorch Version 1.13.0a0+d321be6
...
root@99ec9b88acce:/workspace# python
Python 3.8.13 | packaged by conda-forge | (default, M… |
builder173 | I’m working on visualizing the convolutions in my model. I use the following approach to add forward hooks to each module. These hooks record the input and output to two dicts.node_out = {}
node_in = {}
#function to generate hook function for each module
def get_node_out(name):
def hook(model, input, output):
no... | ptrblck | No, your hooks look correct.
Yes, you could disable inplace layers, since they are changing the activations inplace.
In your case, the output of batchnorm will be changed by the ReLU(inplace=True) layer directly, so that the output of batchnorm and the input/output of the relu layer are all the … |
Alphonsito25 | Hi.I would like to split my dataset between training and test, but I don’t want it to be done randomly, like:torch.utils.data.random_split(dataset, [train_size, val_size])This is because I want to perform several trainings under the same conditions (test images always the same in each training).Is there a pytorch funct... | ptrblck | Here is an example:
dataset = TensorDataset(torch.arange(10))
train_dataset = torch.utils.data.Subset(dataset, indices=torch.arange(5))
val_dataset = torch.utils.data.Subset(dataset, indices=torch.arange(5, 10))
for d in train_dataset:
print(d)
for d in val_dataset:
print(d) |
tsp_t | I’m trying to reduce memory usage by usingautocastat methodforwardonly for some modules inside the model.However, in a situation where the model is Dataparalleled, doesn’t performance decrease occur even if I do not specify that autocast is performed on a specific device liketorch.autocast("cuda", torch.float16)?I want... | ptrblck | No, the device_type argument in autocast doesn’t care about the actual device with its ID (so cuda:0, cuda:1 etc.) but only about the type (cuda vs. cpu). |
josmi9966 | I find it hard to understand which NVIDIA GPUs will work with which versions of PyTorch and under which OS.For a project, somebody wants to purchase a laptop that has RTX A2000 built in and I am wondering which PyTorch versions this card would work with? Would it work under Ubuntu 22.04? Under Windows?If the spec shows... | ptrblck | You might want to checkCUDA - Wikipediaas it shows the compute capabilities for (all) GPUs.
Yes, it’s an Ampere GPU with cc=8.6 and is supported.
No, I don’t think there is a mapping and we keep the min. cc=3.7 to support old K80 cards, which are still used in Colab if I’m not mistaken.
Ever… |
Sam_Lerman | As the question asks, if I’m loading data directly onto CPU, and myDataset’s__getitem__only indexes an initialized array — after having loaded it from disk in the__init__method — is there still an advantage to using more than one worker withnum_workers > 1? | ptrblck | I would claim it depends on your system, but would not expect to see a huge speedup if at all. Using too many workers could also slow down your data loading due to the simple indexing operation and the overhead from multiprocessing. In the end, you should profile different approaches for your system… |
exponential | I have 3 GPUs (80GB each) on my virtual machine, however for some reason pytorch only uses one of the GPUs.Please see minimal reproduction of my codeimport os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0, 1, 2"
from torch import nn
device = torch.device('cuda' if torch.cuda.is_a... | ptrblck | nn.DataParallel creates an imbalance on the GPUs and while your seem to be quite large, the other devices could still be used.
You can add debug print statements to the forward method of the model and check the current device of the input tensor via print(x.device) to check which GPU the inputs use… |
Haalum | Hi,I have two pre-trained classification models. I want to create a third model byremoving the classification layers from the pre-trained models and freezing all the other layers, thenconcatenating the features from these two models and finallyadding a new classification head [fine-tune this layer only].So I’m going to... | ptrblck | You could create copies, but this will of course increase the memory usage and you would need to execute each model separately, so it’s quite wasteful.
The better approach would be to use e.g. forward hook to get the desired forward activation from the original model during a single forward pass, a… |
Huimin_LU | Hello everyone! I’m new here.I’m an undergraduate student doing my research project.I’m not a native English speaker, so apologies to my weird grammar.My research topic is about wind power prediction using an LSTM-NN and its application in the power trading. I used only the time-series date of wind power as parameters,... | ptrblck | The error is most likely raised by using a list for the price_label assuming these are the weights:
def weighted_mse_loss(input, target, weight):
return (weight * (input - target) ** 2)
x = torch.randn(10, 10, requires_grad=True)
y = torch.randn(10, 10)
weight = torch.randn(10, 1).tolist()
lo… |
timosy | I’m useing ViT via vit_pytorch, a model is below,ViT(
(to_patch_embedding): Sequential(
(0): Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1=16, p2=16)
(1): Linear(in_features=768, out_features=1024, bias=True)
)
(dropout): Dropout(p=0.1, inplace=False)
(transformer): Transformer(
(layers): M... | ptrblck | Yes, the linear layer maps the 768 features from the input activation (i.e. the output of the Rearrange module) to 1024 features:
Linear(in_features=768, out_features=1024, bias=True)
I don’t know how the image is related to these output features, but assuming the features were created from an … |
David1 | I am trying to train adeeplabv3_resnet50model on a custom dataset, but get the errorValueError: Expected more than 1 value per channel when training, got input size torch.Size([1, 256, 1, 1])when trying to do the forward pass. The following minimal example produces this error:import torch
import torchvision
model = to... | ptrblck | The stacktrace points to a batchnorm layer, which gets an activation in the shape of [1, 256, 1, 1] and tries to normalize the input by calculating its mean and std. Since you are passing a single sample and the input activation to this batchnorm layer has a single pixel, the stats calculation will … |
Skyworker | Because the GPU memory used for forward propagation during training is very large, but there is no such high GPU memory during actual deployment. Is there any way to reduce the video memory usage by an order of magnitude during deployment?Batch size is already 1.The main reason for the large memory usage is because the... | ptrblck | No, you shouldn’t use it during training as it will disable the gradient calculation as previously explained. Wrap the forward pass of the entire model in the guard during inference:
# inference
model.eval()
with torch.no_grad():
out = model(x) |
spacemeerkat | Outline of the issueI’ve made an autoencoder which takes in batches of tensors of shape (5,1,64,64). The model is trained to minimise the reconstruction loss as standard, but also the spread across the embedding values for each batch.I’m using a fairly simple network as shown below with 3 convolutional layers and a sin... | ptrblck | Besides the zeroed out “embedding” tensor, which is the output of the last linear layer and a relu, you are also passing intermediate tensors to the decoder:
output = self.decoder(embeddings, ind1, s1, ind2, s2, ind3, s3)
which could allow it to reconstruct the input. |
MartinZhang | Hi, today I try to use the torch.fx.passes.graph_drawer to get a vision of graphmodulelike this:model = torch.load('graph_model_resnet50.pt') # this is a graphModule from torch.fx.symbolic_trace
from torch.fx import passe
passes.graph_drawer(model, 'renset50')but there will a error about:TypeError: 'module' object i... | ptrblck | This code works for me and creates an svg file:
import torch
import torchvision.models as models
from torch.fx import passes, symbolic_trace
model = models.resnet18()
model = symbolic_trace(model)
g = passes.graph_drawer.FxGraphDrawer(model, 'resnet50')
with open("a.svg", "wb") as f:
f.write(… |
bryan123 | How can I add dropout layers after every convolution layer in DenseNet201 pretrained if I want to keep the value of its parameters (weights/Biases)? (FYI, I wanted to add dropout layers between the convolutional layers in order to quantify MC-Dropout uncertainty during prediction). | ptrblck | You can add the dropout layers wherever you think it would work and my code snippet is just one example how to add it before one conv layer.
If you want to use the pretrained model from torchvision use:
model = models.densenet201(pretrained=True)
otherwise if you want to load a state_dict that yo… |
Benison_Sam | My Setup:GPU: Nvidia A100 (40GB Memory)RAM: 500GBDataloader:pin_memory = truenum_workers = Tried with 2, 4, 8, 12, 16batch_size = 32Data Shape per Data unit: I have 2 inputs and a target tensortorch.Size([-1, 3024]), torch.Size([1, 768]), torch.Size([1, 3792])I am trying to use the data loader to predict, but I am gett... | ptrblck | The error points to an OOM on the host not the GPU and it seems you are running out of pinned memory. Could you check if your system limits this resource and set pin_memory=False as a debugging step to check if if would solve the issue? |
samlk | Hi, I’m trying to make images which will fool model, but I have some problem with this code. In the second iteration I getTypeError: unsupported operand type(s) for -: 'Tensor' and 'NoneType'Why is the grad NoneType even if it’s working for the first time?X_fooling = X.clone()
X_fooling.requires_grad_()
loss_f = torch.... | ptrblck | You are replacing the leaf variable:
X_fooling = X.clone()
X_fooling.requires_grad_()
with a non-leaf:
X_fooling = X_fooling - X_fooling.grad
I’m unsure if you want to recreate the leaf variable, but you could use:
X_fooling.detach().requires_grad_()
to recreate the leaf variable. |
gpas | Hi,I had to use tensorrt but the tensor unfold operation was not supported and the output of the converted model was rubbish.So , I wrote the unfold with simple operations (forum thread) but it is extremely slow.Do you think python’s for loops is causing this? | ptrblck | Yes, a nested loop could create a large overhead compared to a single operation. |
Anna_Inberg | Good afternoon,I’m a newbie in PyTorch, building a binary classification model based on 2 inputs: images and numeric data.Here’s the custom dataset code and the model as well:class FaceLandmarksDataset(Dataset):
"""Face Landmarks dataset."""
def __init__(self, data_frame, root_dir, transform=None):
"""... | ptrblck | The print statements in the fit method look correct and I don’t know why they wouldn’t show up. Could you add more debug print statements e.g. at the beginning of the fit method and make sure it’s shown? |
ritwik.m07 | I was working with cross entropy loss for a sequence labeling problem. Just like pixel-level classification, sequence labeling predicts the class for every token in the sequence.I read inthe documentation of cross entropy lossthat there is a separate format for such fine-grained classification.Let us stick to class pro... | ptrblck | The main reason would be for convenience and to avoid code duplication, which could add errors to user code. The same applies for e.g. weighted losses, as you could simply multiply the unreduced loss with a weight tensor and reduce it afterwards. However, would you remember that the reduction would … |
MartinZhang | Hi , I can’t understand about the args of aten::lstm functionHow to match the args of aten::lstm and torch.nn.LSTM()Thanks.ps:I am not found the api doucment about aten::lstm.Library API — PyTorch master documentation | ptrblck | You can specify the options via LSTMOptions and create an LSTM layer via e.g.:
auto lstm_opt = LSTMOptions(1, 1).num_layers(1).batch_first(false).bidirectional(false);
LSTM lstm{lstm_opt); |
top.g | I have an imbalanced dataset, and I’m trying to give custom weights toCrossEntropyLoss. However, I’m not sure whether I should give higher weights to minority classes and lower weights to majority classes, or vice versa. What I understand is that the higher the weights the larger the penalization, but I found in thisst... | ptrblck | You would increase the weight for the minority class for add a penalty to the training for a wrong classification of it.This postexplains it with an example. |
Lafith_Mattara | My dataset is of variable input size, ie. WxHx128 with fixed channel size. Since the dataloader expect fixed size for stacking I wrote a custom collate_fn. My collate function will create a list of tensors as the input, but I cannot give that list into the model giving this error:Epoch: 1
0%| ... | ptrblck | Using single samples would work. Alternatively, you could resize or pad the inputs to create a single batch containing all samples. |
ArshadIram | idx = np.where(label.cpu().numpy() == np.array([0]*data.cpu().shape[0]))[0]I am tyring to perform elementwise comparison. However, getting the error.DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
idx = np.where(label.cpu().numpy() == np.array([0]*data.cpu().shape[0]))[0]
<... | ptrblck | The DeprecationWarning is raised by numpy not PyTorch while the “Out of memory” error is raised by PyTorch if your GPU is running out of memory.
Try to decrease the memory usage by e.g. reducing the batch size. |
alyeko | I have a ResNet 9 model, implemented in Pytorch which I am using for multi-class image classification. My total number of classes is 6. Using the following code, from torchsummary library, I am able to show the summary of the model, seen in the attached image:INPUT_SHAPE = (3, 256, 256)#inputshape of my imageprint(summ... | ptrblck | Most likely Conv2d-1 would be the input layer to the model, but I don’t know how exactly summary creates the order of modules.
E.g. using the order of module initialization could be wrong, since you can use any order to initialize the modules in the __init__ method and use another order in the forw… |
alyeko | I have two models whose performance I am comparing, a ResNet-9 model and a VGG-16 model. They are being used for image classification. Their accuracies on the same test set are:ResNet-9 = 99.25% accuracyVGG-16 = 97.90% accuracyresnet9-tv-losses4223×4155 341 KBVGG16-tv-losses4223×4180 395 KBHowever from their loss curve... | ptrblck | It could be expected as the loss is not only reflecting the number of correctly classifier examples but also the “confidence” of these predictions. You could thus compare the logits (or probabilities) of both models and see if the ResNet’s predictions are “smoother” but still correct. |
AP_M | I am trying to replicate SimCLR model with linkGoogle Colabusing my dataset and model. When I execute using my model, it gives the error as below. Not able to understand where is the problem.RuntimeError Traceback (most recent call last)
<ipython-input-34-4b3055af976b> in <module>
4 ... | ptrblck | torch.save would accept any valid path with a (new) file name. Make sure the directories exist as torch.save will not recursively create them. |
ProteinGuy | TLDR:A simple (single hidden-layer) feed-forward Pytorch model trained to predict the functiony = sin(X1) + sin(X2) + ... sin(X10)substantially underperforms an identical model built/trained with Keras. Why is this so and what can be done to mitigate the difference in performance?In training a regression model, I notic... | ptrblck | You are broadcasting the prediction and target tensors which will cause a wrong loss calculation, since the output of your model has the shape [batch_size, 1] while the target has the shape [batch_size].
Since you are using a custom loss function defined as:
def mean_squared_error(ytrue, ypred):
… |
A_Ferrato | I’m trying to train a model composed by a CNN and a LSTM but during the training phase there are no weights update. I have read posts in this forum for days but I cannot figure out what is wrong with my code.Here it is my model:from coral_pytorch.layers import CoralLayer
class Net(nn.Module):
def __init__(self):
... | ptrblck | In your current code you are checking the parameters at index1 and compare its updates:
a = list(model.parameters())[1].clone()
loss.backward(retain_graph=True)
optimizer.step()
b = list(model.parameters())[1].clone()
print(torch.equal(a,b))
Later you are al… |
Fhunmie | I am getting this replicas error today.Setup:Machine : HPC cluster, GPU queue, Single node.pytorch 1.10.2Number of GPU devices available: 2Names of GPU devices: [‘Tesla V100-PCIE-16GB’, ‘Tesla V100-PCIE-16GB’]The model training was working well with ddp on 1 gpu .But gives this error with multiple gpuRuntimeError: re... | ptrblck | Each process will run the script you are launching. Assuming your data loading is in the main method, each process is expected to load and process its own Dataset. This is also the reason why a DistributedRandomSampler is used, which avoids sample duplication.
Make sure that each rank sees the full… |
AiDi_Arman | Hello, I’m very new in Pytorch, what is the difference between torch.rand(size=(3,4)) and torch.rand(3,4))I don’t really understand the “size” means, I checked Docs but still not… please help, thanks. | ptrblck | There is no difference, since the first argument is the size arg and the name can thus be skipped.
Both will return a tensor with the size [3, 4] containing random values drawn from a uniform distribution in [0, 1):
torch.rand(size=(3,4))
# tensor([[0.7919, 0.7024, 0.1932, 0.8998],
# [0.58… |
calwritescode | Since I have a problem with vanishing gradients while training my model I added a writer to monitor the models gradientsfor name, param in self.model.named_parameters():
self.writer.add_histogram(f"{name}.grad", param.grad, iteration)this lead toValueError("The histogram is empty, please file a bug report.")even af... | ptrblck | I guess trying to create a histogram from a single value fails (which would be expected) so you might need to check if the gradient contains multiple values. |
truongan-github | Hello everybody, I’m training VGG16 model, when I load input data from CIFAR10/100. This is happen through model.for inputs, targets in trainloader:
if torch.cuda.is_available() and gpu:
data, target = data.cuda(), target.cuda()
# Load the inputs and targets
optimizer.zero_g... | ptrblck | Maybe your learning rate is too large as the current training diverges and the loss explodes which eventually creates the NaN output and loss. |
kristianeschenburg | HelloI have a single node, with 8 GPUs, and am interested in usingDistributedDataParallel(DDP) to distribute data processing across GPU devices. I have two functions (I’m basing these partly off ofthis demo:def main(local_world_size, local_rank, args):
# These are the parameters used to initialize the process grou... | ptrblck | You can create the Dataset with its corresponding DistributedSampler in each rank in the train method and just iterate it. Once the samples are loaded you can directly push it to the GPU using the same rank argument. |
seankala | I’m currently using PyTorch to train a neural network. The dataset that I’m using is a binary classification dataset with a large number of 0’s.I decided to try and use theweightparameter of PyTorch’s cross-entropy loss. I calculated the weights viasklearn.utils.class_weight.compute_class_weightand got weight values of... | ptrblck | Most likely you are passing the class_weights as float64 as this is the default dtype in numpy which raises the error as seen here:
x = torch.randn(2, 2, requires_grad=True)
y = torch.randint(0, 2, (2,))
criterion = nn.CrossEntropyLoss()
loss = criterion(x, y) # works
weight = torch.tensor([0.1, … |
Luca_Pamparana | I have 2 pytorch tensors say as follows:x = torch.Tensor([float('nan'), 2.0, 5.0, 6.0])
y = torch.Tensor([float('nan'), float('nan'), 3.0, 4.0])I want to filter both the arrays where entries that are NAN in either of the two arrays are filtered out i.e. in this case,filtered_x = [5., 6.]
filtered_y = [3., 4.]Just wonde... | ptrblck | tensor.is_finite should work:
x = torch.Tensor([float('nan'), 2.0, 5.0, 6.0])
y = torch.Tensor([float('nan'), float('nan'), 3.0, 4.0])
idx = x.isfinite() & y.isfinite()
out = torch.stack((x[idx], y[idx]))
print(out)
# tensor([[5., 6.],
# [3., 4.]])
I don’t know if this method is availabl… |
talhaanwarch | Hi, I am trying to use Pearson loss function instead of MSE.Here is the loss functionclass Neg_Pearson_Loss(nn.Module):
#https://stackoverflow.com/a/19710598/11170350
def __init__(self):
super(Neg_Pearson_Loss,self).__init__()
return
def forward(self, X, Y):
assert not torc... | ptrblck | You could be dividing by a zero stddev and might want to move the 1e-5 eps value into the denominator. |
JamesDickens | I went through this tutorial here:https://pytorch.org/tutorials/intermediate/ddp_tutorial.htmlMy setup is a single multi-gpu machine.I am wondering, does the optimizer need to be changed in anyway to account for themultiple processes?Also should optimizer.step() only be called by the process at rank 0? | ptrblck | No, you don’t need to change the usage of the optimizer and each rank should call the step() function in DDP, not only rank0. |
Minxiangliu | I am newbie in LSTM, and I want to clarify some concepts. I know that LSTM has a good effect on time series data, and I want to try to build an LSTM model. I will not use LSTMCell here, because there may be places I don’t understand about cells.I would like to ask ifRun1andRun2in the following code are equivalent:data ... | ptrblck | Don’t use torch.equal as floating point numbers will create small errors due to their limited precision.
I still get the same outputs for num_layers=2:
out1, h1 = Run1()
out2, h2 = Run2()
print((out1[:, -1] - out2).abs().max())
# tensor(2.9802e-08, grad_fn=<MaxBackward1>)
print((h1 - h2).abs().m… |
RHB1996 | Hello all,I have been dealing with an error.At first, I saved the weights of a trained model as follows:torch.save(model.state_dict(), 'final_model.pth')Then try to load the ‘pth’ file for evaluation by the following code:device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using {device} device")
model = Co... | ptrblck | Your model works fine in my environment and based on the error message it seems you are trying to pass a str to the first conv layer, while a tensor is expected.
Could you check the type of x inside the forward method and make sure it’s a valid tensor? |
Fuzhiyuan | I meet this problem when i used thisloss_function=nn.CrossEntropyLoss()
loss2 = (1 - weight) * loss_function( student_result, torch.squeeze(label,dim=1))student_result shape is 4,7,128,128,128label shape is 4,1,128,128,128both of them in GPUstudent_result comes from model final layer which only has a Conv3d() that ch... | ptrblck | The current error now changed to:
RuntimeError: CUDA error: device-side assert triggered
which is raised e.g. if you are passing invalid target tensors to nn.CrossEntropyLoss:
criterion = nn.CrossEntropyLoss()
output = torch.randn(10, 10, device='cuda', requires_grad=True)
target = torch.randint… |
Moss-And-Bone | Hello,I am a student who has some limited experience with keras, and for a new project recently decided to learn how to use pytorch to implement my models. I’m a beginner with both, so apologies in advance for my inexperience, I am doing my best to follow tutorials, but my limited experience combined with most examples... | ptrblck | You are passing the padding="same" argument to the stride of the conv layer:
(0): Conv1d(32, 32, kernel_size=(11,), stride=('s', 'a', 'm', 'e'))
Use nn.LazyConv1d(out_channels, kernel_size, padding=padding) and it should work. |
Ioan | The output of the network has a certain loss, however, I want to scale down the loss before propagating. (multitask learning)Isloss = loss * weight # weight can be 0.5 for example
loss.backward()same aslogits.data.backward(grad * weight) | ptrblck | Yes, loss scaling should also scale the gradients as seen in this small example:
model = models.resnet152()
x = torch.randn(2, 3, 224, 224)
loss1 = model(x).mean()
# standard
loss1.backward(retain_graph=True)
grads1 = [p.grad.clone() for p in model.parameters()]
# scale up
model.zero_grad()
loss… |
Megh_Bhalerao | Hello,Different optimization algorithms such as ADAM, Adagrad, RMSProp adapt their step size according to the gradients, for example adagrad accumulated the gradient L2 norm and the learning rate is scaled according to that, and RMSProp does an exponential moving average with a momentum parameter to accumulate the L2 n... | ptrblck | You can check the state_dict of the optimizer and see the internal tracking stats:
model = nn.Linear(2, 2, bias=True)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
out = model(torch.randn(1, 2))
out.mean().backward()
optimizer.step()
print(optimizer.state_dict())
# {'state': {0: {'ste… |
Angelina_Robert | Hi,Just wondering if any one could help with the following error:ratio=6label_sample_dict= {0: 61, 1: 28, 2: 21, 3: 6, 4: 4, 5: 4, 6: 1, 7: 3}for label, samples in label_sample_dict:self.samp_queue[label] = [Queue(maxsize=samples*ratio), samples]Error: for label, samples in label_sample_dict:TypeError: cannot unpack... | ptrblck | Since label_sample_dict is a Python dict iterating it should return the key while you are trying to get two return values. I guess the unpacking then fails. Try to use for key in label_sample_dict and use the key to access the value. |
GillesBa | I’m using pytorch/TensorRT for real time inference, this means that I’m taking an image directly from the camera followed by processing the image (rescaling etc) and then finally inference. I found the numpy/opencv processing pretty slow so I wanted to do this on GPU as either way I would have to copy the image to GPU.... | ptrblck | I think you are hitting the issue since you are passing the image in a channels-last memory layout, while PyTorch expects channels-first.
While this would generally work, your approach would resize the image in the channel dimension and thus increase the memory usage massively:
print(torch.cuda.me… |
raining_day513 | I need to show that some technique called gradient checkpointing can really save GPU memory usage during backward propagation. When I see the result using pytorch_memlab there are two columns on the left showingactive_bytesandreserved_bytes. In my testing, while active bytes read3.83G, the reserved bytes read9.35G. So ... | ptrblck | The reserved memory would refer to the cache, which PyTorch can reuse for new allocations.
Based on the stats you are seeing it seems that some peak memory usage might have been larger, but PyTorch is able to release it and push it back to the cache, so that it can reuse it the next time it needs m… |
Hazrat | I am unable to find a solution to this error:—> 92 image = T.ToTensor(image)93 if not self.long_mask:94 mask = T.ToTensor(mask)TypeError:init() takes 1 positional argument but 2 were given | ptrblck | You have to create the transformation object first before calling it or you could use the functional API directly:
transforms.ToTensor(image) # wrong
# TypeError: __init__() takes 1 positional argument but 2 were given
# create the object first
transform = transforms.ToTensor()
out = transform(ima… |
MartinPerry1 | I have a batched tensor [B, C, H, W], where B is batch, C is a number of channels, H and W are dimensions. I have an array with indices and I would like to read values at those indices from input tensor and write them to another tensor.For example:two tensors A (source) and B (target)
B = 1
C = 3
H, W = 64
indicesRea... | ptrblck | A direct assignment might work:
B = 1
C = 3
H, W = 64, 64
indicesRead = torch.tensor([[0, 0], [13, 15], [32, 43]])
indicesWrite = torch.tensor([[7, 5], [1, 1], [4, 4]])
a = torch.randn(B, C, H, W)
b = torch.zeros(B, C, H, W)
b[:, torch.arange(C).unsqueeze(1), indicesWrite[:, 0], indicesWrite[:, … |
Angelina_Robert | Hi,The following code works fine, however, if I change the label values it shows the error.class_samples={}labels=[0, 1, 2 ,3]sample_count=[10, 20, 30, 40]for labl in labels:class_samples[labl]= sample_count[labl]print (’ Class Samples: ', class_samples)#OUTPUT: Class Samples: {0: 10, 1: 20, 2: 30, 3: 40}If I change... | ptrblck | Indexing sample_count with labl won’t work as you need indices in [0, len(sample_count)].
Use the index create by enumerate:
for idx, labl in enumerate(labels):
class_samples[labl]= sample_count[idx]
print(' Class Samples: ', class_samples)
or create the dict directly as:
dict(zip(labels, sa… |
clarissesimoes | Hi there.Thetorch.utils.data documentationsays thatWhennum_workers > 0, each worker process will have a different copy of the dataset object, so it is often desired to configure each copy independently to avoid having duplicate data returned from the workers.However, on this othertopic, @ptrblcksays thatIf you use mult... | ptrblck | Each worker will hold a reference to an own Dataset.
Now, if you are using a lazy loading approach in the Dataset, the actual copy will be small, since basically only the Dataset object itself and everything in its __init__ will be copied in each worker, which is usually just a reference to a tran… |
Lin1 | Hello everyone,I have implemented a c++ preprocessor with pybind11. The c++ preprocessor is imported by a customized dataset wraped by torch.utils.data.Dataloader. One of the preprocessor’s member function is then called ingetitemfor generating feature/label for further training. It works fine.Based on this preprocesso... | ptrblck | Since you are trying to re-initialize a CUDA context, you would need to use the "spawn" start method as describedhere. |
Konstantin_Lebeda | Hello! How can I add functions, different for every neuron, between two layers of fully connected NN? Is it possible?class PolyNet(torch.nn.Module):
def __init__(self):
super(PolyNet, self).__init__()
self.fc1 = torch.nn.Linear(1, 4, bias=False)
# something here?
self.fc2 = torch.nn... | ptrblck | I assume “neuron” means a specific output activation in this use case.
If so, you can directly apply the method on it and concatenate the results afterwards.
Depending on your actual use case, something like this would work:
class PolyNet(torch.nn.Module):
def __init__(self):
super(Po… |
William_Ravenscroft | I’m trying to transform a tensor from this structure:[[[
[1,2,3,4,5,6,7,8,9,10,11,12],
[99,98,97,96,95,94,93,92,91,90,98,97]
]]](shape 1 x 1 x 2 x 12)to this structure[[[
[[1,2,3,4,5],
[3,4,5,6,7],
[5,6,7,8,9],
[7,8,9,10,11]],
[[99,98,97,96,95],
[97,96,95,94,93],
[9... | ptrblck | unfold should work:
out = t.unfold(dimension=3, size=5, step=2)
print(out)
# tensor([[[[[ 1, 2, 3, 4, 5],
# [ 3, 4, 5, 6, 7],
# [ 5, 6, 7, 8, 9],
# [ 7, 8, 9, 10, 11]],
# [[99, 98, 97, 96, 95],
# [97, 96, 95, 94, 93],
# … |
Ziyu_Huang | Hi! I am interested in the exact meaning of grad_fn=. Thank you!!! | ptrblck | The simple explanation is: during the forward pass PyTorch will track the operations if one of the involved tensors requires gradients (i.e. its .requires_grad attribute it set to True) and will create a computation graph from these operations. To be able to backpropagate through this computation gr… |
simeonkpy | Hello,I am new to PyTorch, and I followed a tutorial to implement a Deep Q RL algorithm. The code worked fine, and I wanted to improve it by having a non-fixed number of layer in the NN algorithm, but I have an error that I don’t understand.Here is the class of the network, the commented functions are the original ones... | ptrblck | This inplace operation:
qNext[terminalBatch] = 0.0
might be causing the issue. Could you try to comment it out and see if this would fix the issue? |
el_samou_samou | Hi,The coordinate convention for the index in the grid sample is a bit surprising to me. Indeed, it seems to correspond to the standard tensor indexing coordinate but in reverse order.Here is a code sample to observe what I am saying:import torch
a = torch.rand(1, 1, 4, 3)
b = torch.nn.functional.grid_sample(a, torch.... | ptrblck | Introducing backwards compatibility breaking changes are not easily accepted, but you should discuss it with the code owner by creating a GitHub issue and describing your idea.
The camera coordinate system is defined by having the origin in the “top left” corner and using positive values for the … |
Vedant_Roy | I’m trying to understand howreduce_scatterworks in Pytorch. So far, I have found the following code snippet:class AllGatherFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, tensor: torch.Tensor, reduce_dtype: torch.dtype = torch.float32):
ctx.reduce_dtype = reduce_dtype
output =... | ptrblck | These docsmight be helpful as they visualize communication patterns. |
walle_autoscale | Hi, I tested Vit-large on NVIDIA A100 GPU with Pytorch1.12, the results are listed below:TF32 enabletorch.backends.cuda.matmul.allow_tf32=True
torch.backends.cudnn.allow_tf32=Truetime used per iter averaged is 1s.autocastwith autocast(enabled=amp_enable):
pred = model(images)
loss = loss_fn(pred, labels... | ptrblck | Thanks for sharing it! I cannot reproduce the issue using the torch==1.12.1+cu116 binaries and get:
time used: 13.615819454193115
----train with fp32----
time used: 11.712484359741211
----train with autocast----
time used: 2.4270553588867188
----train with tf32----
time used: 3.359715700149536
on … |
Donglin | Dear community,I build pytorch from the source following instructions fromgithub webpageusing latest pytorch (commit 7c20ad3dfae18c5e262c59e09c2b6079ec7fc69f). The build was successful and pytorch python API is able to detect CUDA devices.However, thereis no libtorch_cuda_cpp.so available under …lib/python3.8/site-pac... | ptrblck | Note that your source build isn’t missing these libraries, but should create a single libtorch_cuda.so lib instead of the split libraries.
However, if you really want to split them (we needed to use it to avoid linker errors due to the size of the lib), use BUILD_SPLIT_CUDA=ON python setup.py insta… |
Arupreza | I tried to add an early stop but it’s not running, please help me silver this error.CreatData = []X = Concatnated[:, :446]y = Concatnated[:,446]strat_time = 0timestamp = 10length = len(Concatnated)for i in range(int(abs(length/10-1))):CreatData.append((X[strat_time:timestamp, :446], y[timestamp]))strat_time = strat_tim... | ptrblck | inputs is in this case still wrong and you would either need to change the in_channels of the first layer to 64 or fix the input to use a single channel. |
kalo | I know the init process takes more time on machines with more GPUs, but since we are calling the Pytorch script from external scripts it is kind of a bottleneck for our process.See the basic example below:import torchcuda0 = torch.device(‘cuda:0’)cuda1 = torch.device(‘cuda:1’)cuda2 = torch.device(‘cuda:2’)cuda3 = torch... | ptrblck | You would need to build PyTorch with CUDA 11.7 (or install the nightly binaries) to see the effect. Installing the CUDA toolkit 11.7 on your system with a PyTorch binary using another CUDA runtime (e.g. 11.6) will not work. You should also see a reduction in memory of the CUDA context size and could… |
Arupreza | I shift my data and model on GPU but still it gives this error.RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! (when checking argument for argument target in method wrapper_nll_loss_forward)model = ConvNet().to(device)criterion = nn.CrossEntropyLoss()optimize... | ptrblck | You are pushing the labels tensor to the GPU and assign it to targets here:
sets, targets = sets.to(device), labels.to(device)
However, later you are using labels (the CPU tensor) which yields this error:
loss = criterion(outputs, labels)
Use targets or reassign labels to itself. |
joohyunglee | I would like to include transform mechanism within the loss function. However, it looks like that gradient won’t flow back through transforms. Is there a way to make gradient flow back through a set oftorchvision.transforms? I will usetransforms.RandomResizedCrop()andtransforms.RandomHorizontalFlip(). | ptrblck | korniaprovides differentiable transformations, so you could check it.
CC@edgarriba |
timosy | If we use RGB and set 32 as out_channels, feature of R is extracted with 12 filters?nn.Conv2d(in_channels=RGB, out_channels=32, kernel_size=3, padding=1), | ptrblck | Sorry, I don’t fully understand the use case. If you are re-initializing new conv layers, the results would always differ unless you are properly seeding the code, setting the filter weights and bias manually to defined values, or are loading a state_dict. If you want to split the filters to work on… |
demmzy419 | Hi Guys,Posted a query some days ago regarding memory issues I ran into during classification:Memory Issues while Classifying ImagesI think I’ve been able to fix it but ran into another issue.Here’s my code:num_classes = 8
learning_rate = 1e-3
batch_size = 4
num_epochs = 50
mean=[0.5, 0.5, 0.5]
std=[0.5, 0.5, 0.5]
tr... | ptrblck | The return statement is inside the loop, so you might want to move it outside of it. |
CallMeMisterOwl | I’ve created a customDatasetclass that inherits from the pytorch-geometricDatasetclass. As shown in the officialwebsite, one can modify the__init__()function of the custom dataset.Example:class MyDataset(InMemoryDataset):
def __init__(self, root, data_list, transform=None):
self.data_list = data_list
... | ptrblck | That’s not the case and you can verify that your __init__ method is called by adding a simple print statement. Note that your StringdbDataset has a typo and uses __int__ instead of __init__, so you should fix it in case you also have the same typo in your code.
In any case, this works:
class MyDa… |
blackbirdbarber | Found somedeep dream codeact_value = model.forward(X_Variable, end_layer)
diff_out = object(act_value, guide_features)
act_value.backward(diff_out)As I checked themodel.forwardshould not have the second parameter. Just the one input tensor.Can someone explain me the third line. Sinceact_valueshould be t... | ptrblck | The user defines a custom MyResNet which accepts two input arguments in its forward as seenhere:
class MyResnet(models.resnet.ResNet):
def forward(self, x, n_layer=3):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
layers = [sel… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.