user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
solidmacaroni
Say I dooutput = model(input)to do a forward pass. Does PyTorch launch a single CUDA kernel for this, or is it possible that multiple kernels are launched for a single forward pass call? Likewise for backward pass, loss calculation and optimizer step. Thank you.
ptrblck
Multiple CUDA kernels will be launched unless the forward pass contains a single operation (unlikely) or unless you’ve used CUDA graphs to capture the entire forward pass as describedhere.
nkkaushal
HiI am running my code which uses torch but I am getting this error“NVIDIA GeForce RTX 3090 Ti with CUDA capability sm_86 is not compatible with the current PyTorch installation. The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_70”I have CUDA version 12.2 (checked using nvidia-smi)nvcc -V :NV...
ptrblck
Same ashere. Your locally installed CUDA toolkit won’t be used and you need to install a PyTorch binary with CUDA>=11.x.
alexp
Hello,if I perform a multiplication between a tensor that is on GPU and a float, does this operation move the tensor to CPU?E.g.scalar = 0.5 t = torch.ones(10, device='cuda') res = t * scalarI see that the resultreswill be on GPU, and alsotdidn’t change device. However, I’m wondering if the operation movestto CPU first...
ptrblck
No, as this would result in terrible performance since you would move potentially large data, execute the operation on the slower CPU, and move the result back. Instead the scalar is passed to the kernel.
GrassWarlock
never used PTorch before and my internet connection is too limited to try cuda 12.2 myself.should i download cuda 12.1 or cuda 12.2 for it?and if it doesn’t, when do you expect PyTorch will support CUDA 12.2?
ptrblck
PyTorch binaries ship with their own CUDA dependencies and your locally installed CUDA toolkit won’t be used unless you build PyTorch from source or a custom CUDA extension.
Epsilon_1
I am following the distributed data parallel (DDP) tutorial on a server with two NVLink’d GPUs. I want to see which PyTorch code leads to NCCL collective calls (Broadcast, Gather etc). Is there a profiler option that lets me do this? So far, I runnsys profile --gpu-metrics-device=all python3 ddp.pyto profile my code an...
ptrblck
Open the profile in nsys-ui and you will see the timeline.
bltzmann
Hi everyone, I’m trying to assign elements from a 6D tensor x, to a 4D tensor y. I would like to optimize this process. I write here the code with for cycles:for r in range(R):for k in range(K):y[r,k,:,:] = x[r,r,k,k,:,:]the dimensions of tensor are:x.size()=(R,R,K,K, N, M)y.size()=(R,K,N,M)How can I do this avoiding e...
ptrblck
Direct indexing should work: R, K, N, M = 2, 3, 4, 5 x = torch.randn(R, R, K, K, N, M) y = torch.zeros(R, K, N, M) # reference for r in range(R): for k in range(K): y[r,k,:,:] = x[r,r,k,k,:,:] # direct indexing z = x[torch.arange(R)[:, None], torch.arange(R)[:, None], torch.arange(K)…
cltexe
I’m trying to extend thisVGGnetwork by adding 2 FC layer but seems like I failed at something. Original one:class VGG(nn.Module): def __init__(self, vgg_name): super(VGG, self).__init__() self.features = self._make_layers(cfg[vgg_name]) self.classifier = nn.Linear(512, 7) def forward(se...
ptrblck
You are currently passing x instead of out to all linear layers.
cltexe
Windows 10 + CUDA 11.1 + pytorch 1.8.0 + vs2019(added to path)+ rtx 3060 + conda.I’m trying to run“projector.py --outdir=out --target=mytargetimg.png–network=https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/ffhq.pkl”in stylegan2ada implementation, but can’t past beyond this error:Loading networks from ...
ptrblck
The error is raised due to a failure in the decoding. You could try to save the file as 'utf-8' or check for any characters, which could yield this error. I think 0x87 would point to acedilla, so maybe you could check all files for this character.
cltexe
I do have a pth file forvgg16asvgg16-397923af.pth. I like to instantiate a new vgg16 model with exact same weights in vgg16-397923af.pth file.vgg16 = models.vgg16()always tries to download weights first, however I don’t want to use any downloads just a reference to the pth file. Is this possible?
ptrblck
That’s not the case as the default argument will randomly initialize the parameters: model = models.vgg16() # no output model = models.vgg16(pretrained=True) # Downloading: "https://download.pytorch.org/models/vgg16-397923af.pth" to ... and will store it in ~/.cache/torch/hub/checkpoints by defau…
MLHafizur
I am trying to construct aConvolutional Autoencodermodel for time series data, Whereembed_size = 32andtime_step = 400, the model constructor is like this:class CNNEncoder(nn.Module): def __init__(self, embedding_size, timestep) -> None: super().__init__() self.conv = nn.Sequential( nn.Co...
ptrblck
The error message points to a shape mismatch in self.fc in CNNEncoder. Set the in_features of the first linear layer to 48 and it should work.
mhmdmuhammad
Hello everyone, I have a validation dataset of approximately 1800 images, and I’ve built this dataset based on the CocoDataset. I’ve loaded this dataset into a PyTorch DataLoader using the following code.batch_size = 32 num_workers = 6 sampler = torch.utils.data.SequentialSampler(data_val) data_loader = DataLoader(dat...
ptrblck
I don’t know what’s causing the hang, but you could try to set the number of workers to zero to check if this would work.
robinho
To create variables x1, x2, …, x10, use:for i in range(1,10):locals()[‘x’+str(i)]Then how to declare these as nonlocal ones to use them as global variables in functions?
ptrblck
Use a dict instead of trying to create variables in different scopes: def fun(): ret = {} for i in range(10): ret["x"+str(i)] = i return ret x = fun() print(x) # {'x0': 0, 'x1': 1, 'x2': 2, 'x3': 3, 'x4': 4, 'x5': 5, 'x6': 6, 'x7': 7, 'x8': 8, 'x9': 9}
spico197
Hi there, I’m just curious why the collective communication library is calledc10d. Is there any direct meaning related to this?Thanks very much ~
ptrblck
I guess the idea was to use it as a common backend for PyTorch and Caffe2 (before it died) in the c10(d) namespace instead of ATen.
egesko
Just as the topic says.
ptrblck
It should be released today.
theory_buff
Hi!I have a GAN-generator setup where I want to compute the loss of a generated image w.r.t. the true image and then backpropagate that loss to update the input vector. The relevant code would look something like this:for epoch in range(100): for img, latent in dataset: gen_img = generator(latent) l...
ptrblck
I don’t think that’s the case since the gradients won’t be included in the next gradient calculation unless you manually add them to the computation graph. To verify it, you could compare a run with and without gradient accumulation using the same inputs and making sure the model is in eval() mode …
trusira
Hi,I have been looking at graph lowering passes in Pytorch 2.x and came across “boxed” functions (throughmake_boxed_func) in AOTAutograd.Can someone explain boxed functions and what is their role in the compilation workflow?Thanks!
ptrblck
Take a look atthis blog postby@ezyangwhere he explains boxed and unboxed functions.
lint_weaver
I’m trying to code the UNet paper, however I’ve come across the issue of implementing the crop when trying to code the decoder.One person did this:class Decoder(nn.Module): def __init__(self, chs=(1024, 512, 256, 128, 64)): super().__init__() self.chs = chs self.upconvs = nn.Modul...
ptrblck
I don’t know what you mean by “effect”, but an interpolation is not producing the same output as a cropping. Both manipulate the spatial size and you can use both to create a smaller output but the values won’t necessarily be equal.
SantaTitular
So I’ve been around the use of complex NNs in pytorch for a while, and I’m trying to implement a custom working version based on some available codeonlinethat works for complex-valued data. The purpose is to build a AE that accepts complex-valued data (EM type of data) and trains the NN accordingly. Unfortunately I can...
ptrblck
Check the dtype of all used tensors in the failing line of code and make sure they are accepted in the linear layer. Also, please don’t tag specific users as it could discourage others to post valid answers.
markuf
Hi, I’m trying to train a model that uses mlagents. After much debugging on this site and stackoverflow, I was able to get everything set up and working. The problem is that as soon as I started training, my GPU wasn’t being fully utilized (much at all). It’s a dynamic range but stays around the 10% range. I’m not real...
ptrblck
That’s not the case as every CUDA 11 release supports your 3090. Where did you get this wrong information from? The PyTorch binaries ship with their own CUDA dependencies and your locally installed CUDA toolkit will be used if you build PyTorch from source or a custom CUDA extension. No, since …
npz7yyk
I am building a machine learning framework and need to understand what is stored for backward. Therefore, I checked out torch.autograd.graph.saved_tensors_hooks for some insights. Here is the code that I ran:import torch.nn as nn import torch class MyModule(nn.Module): def __init__(self, module, name=""): ...
ptrblck
The first weight was not stored since the x input does not require gradients so there is no need to store the weight of the first linear layer for the dgrad calculation. Use x = torch.randn(2, 3, requires_grad=True) and the weight of the first layer will be stored as well.
harsanyidani
There are clearly tensors allocated in my GPU memory. When I turn PYTORCH_NO_CUDA_MEMORY_CACHING enviroment variable back to 0 it works seemingly fine. Is this a bug?I’ve readpytorch documentation on memory managementbut I still don’t understand.
ptrblck
Disabling the caching allocator is a debugging feature and some utils won’t work, such as CUDA Graphs. You could suggest a fix in case you are interested to see the used memory stats.
agostini01
Hi,I am aware that some newer dev python wheels are available here:https://download.pytorch.org/whl/nightly/cpu/torch_nightly.htmlHowever I need a dev version that is more than 2-3 months old (for example:torch==2.0.0.dev20221231, torchvision==0.15.0.dev20221231). Do these older nightly wheels get moved to another serv...
ptrblck
These wheels are still available and you can download them by explicitly specifying the URL. The index is just cleared and keeps a few months of wheels. However, wheels are not deleted themselves, just from the index.
Mohamed_Hassan
I am convering a model containing TransformerEncoder. However I noticed that the outputs I get in PyTorch and onnxruntimes are different.class Model(nn.Module): def __init__(self): super().__init__() trans_enc_layer = nn.TransformerEncoderLayer(d_model=32, ...
ptrblck
You are not calling model.eval() on the PyTorch model before creating the reference output and are thus using the default dropout layer. Check if this would reduce the numerical mismatches.
pylearn
I am using miniconda on a virtual machine. I installed pytorch with cuda=11.8. It works fine. Recently, I found out the cuda version on my VM is only 11.6.Runningnvidia-smiin terminal returns a table containgNVIDIA-SMI 510.73.08 Driver Version: 510.73.08 CUDA Version: 11.6.Since the pytorch I installed is working...
ptrblck
That’s correct since PyTorch binaries ship with their own CUDA dependencies and only need a properly installed NVIDIA driver to run workloads on your GPU. Yes, you would need to install the right driver, but also note that CUDA supports minor version compatibility, allowing you to stick to the sa…
yiftach
Hi,I know that CUDA calls are non-blocking and run asynchronously, such that if I call some operation on the data then unless I perform some operation that requires a sync (.item(), .to() etc) my code can continue to run other lines of code and not wait for the operation to finish.I know (or at least I think I know) th...
ptrblck
Yes, since you added a data-dependent control flow and the host needs to wait before deciding which code path to take. Spin a large enough matmul in a loop.Hereis a recent example I’ve posted in another issue showing how the CPU can run ahead or would be blocked. EDIT: you can also use the (e…
pylearn
I have a large model which involves sigmoid and logsigmoid functions. I am using float64 for better accuracy withtorch.set_default_dtype(torch.float64).Running the same code twice, I got different training results. I printed the loss to see what happened. I found out the losses are the same for the first few hundred it...
ptrblck
Yes, the code could result in small differences due to the limited floating point precision and since floating point operations are not associative. The used algorithm might not be deterministic (you can enable deterministic algorithms on the GPU for a potential performance penalty) and could thus r…
Garvey
I have a vectoraproduced by neural model which need to interact with a huge matrixM. SinceMis large, I have to do the computation in cpu device. In this case, I wonder if the gradient can be retained and backwarded on cuda device.Below is an example. I am looking for solution such thata_cuda.gradhas the same gradients ...
ptrblck
You are ignoring a valid warning: UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the .grad field to be populated for a non-leaf Tensor, use .retain_grad() on the non-leaf…
Crow
My task is to make multi labels classification which I choose CrossEntropyLoss to do so. However, I have to reimplement a CELoss function as the pytorch built-in CELoss only accept a single label tensor as target (shape [batch, ]). Here is the loss part of my code:# using built-in loss function ''' labels[:, 1:] = 0 ...
ptrblck
Replace log_softmax_output = torch.log(F.softmax(logits, dim=-1)) with F.log_softmax for more numerical stability. Besides that you could use nn.BCEWithLogitsLoss for a multi-label classification where each sample belongs to zero, one, or multiple classes.
Ramansh_Sharma
Hi. I just started using PyTorch C++ fully. I set up a simple neural network that can evaluate a given tensor. When evaluating the neural network, the output (which I set to be a scalar, for only one input in this case) is shown as follows:image1502×78 3.89 KBTo test whether this output was a scalar Tensor (or a symbol...
ptrblck
I’m not sure which formats you are comparing, but they are definedherein case you want to check it.
kwkim128
Hi everyone. I am trying to plot the original image, mask and predicted mask from the UNet model, however, I am getting weird images as my output. This is a method I used before, which worked perfectly but for some weird reason, it is not working anymore…Figure 2023-09-13 1508231920×999 165 KBAs shown in the image abov...
ptrblck
Try to use plt.imshow to display images instead of plt.plot as the latter will interpret the array as rows of different signals.
AlphaBetaGamma96
Hi All,I was wondering if it were possible to specify how flattening or reshaping is done via PyTorch in a similar way to how Numpy (here) allows you to pass a “C” or “F” argument which specifies row or column ordering respectively.a = torch.Tensor([[1,2], [3,4]]) a.detach().numpy().flatten('C') #re...
ptrblck
I don’t think PyTorch supports the Fortran- style flattening, but you should be able to transpose the tensor before flattening it if this order is needed.
Kinbote
I have an nvidia docker container with its own system wide cuda and cudnn. I’m trying to create several python environments, each with its own torch install. I was wondering if it’s possible to link these torch installs with the system cuda and cudnn so that I don’t have to download and install cuda and cudnn in each o...
ptrblck
Yes, you can build PyTorch from source which would use your locally installed CUDA toolkit and cuDNN in a new virtual environment.
Prafful_Kumar
Aim: To extract the intermediate features (say from block_num=4) from a pretrained resnet50. Then feed the same extracted feature to the next blocks (In between I have to do some manipulation, but I have not done it here). Even the shape of the block feature is correct that is required for the next layer. I am unable t...
ptrblck
Wrapping submodules into an nn/Sequential container will often fail as you would be missing all functional API calls. For resnet50 you would missthis torch.flatten operationwhich is most likely causing the issue. Either add an nn.Flatten module manually to your nn.Sequential container or derive a…
seberino
Why image datasets need normalizing with means and standard deviations specified like in transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ?Where did those numbers come from and why isn’t this done already in the datasets?Chris
ptrblck
These stats are calculated from the ImageNet dataset, which was used to pretrain classification models in torchvision. You don’t need to use these stats and could also try to use the stats calculated from your custom dataset.
trusira
Hi,What is the status of Dynamo support for NvFuser? I could not find many references/tutorials on the topic and the ones I found seem deprecated and/or use TorchScript as the graph format.Is it possible to use NvFuser with torch.compile?Thanks!
ptrblck
This is correct and the nvFuser support in TorchDynamo was removedhere. As mentioned before nvFuser is also deprecated in TorchScript and NNC is used as the default backend. Note that TorchScript is in “maintenance mode” and I believe won’t get any major updates or fixes anymore. nvFuser develo…
k_ryna
Hello dear community. I’m trying to write a simple classifier that is predicting the letter based on input but it doesn’t see to converge. The loss is still 2.5 after all. I tried changing batch size, number of layers and other parameters but it didn’t change. I’m new to NN and can’t figure out what exactly is wrong. H...
ptrblck
nn.CrossEntropyLoss expects raw logits so remove the nn.Softmax from your model.
abdula2523
Hello community.I’m trying to load and offload the model’s weight from the host(pinned) and GPU and from the GPU and host(pinned), with some multiple Python threads and CUDA streams.But, I’ve got different inference results when transferring the model’s weights(actually layers you know) when migrate concurrently and no...
ptrblck
Yes, this is expected since you need to synchronize the stream before being able to use the CPUTensor after moving it with non_blocking=True. This example illustrates it: import torch import time from statistics import mean def get_cycles_per_ms() -> float: """Measure and return approximate n…
Goldname
I created a transformer model with one encoder layer:class MyModel(nn.Module): def __init__(self): super().__init__() self.encoder_layer = nn.TransformerEncoderLayer(d_model=2, nhead=1, dim_feedforward=2) self.trans = nn.TransformerEncoder(self.encoder_layer, num_layers=1) def forward(se...
ptrblck
Some modules return tuples and your hook is most likely calling .detach() on it directly as it expects a tensor. You could add some logic which checks the type of the input and either calls .detach() on a tensor or unpacks the tuple before calling .detach() on all tensors (or some of them; depending…
Abdullah_Chand
Hi,I am using the following repositoryYOLO-POSE, I am trying to do batched inference on multiple images at a same time. The model is taking similar time for different batch size (upto 6) but after the model computes the results and I need to perform NMS, the time taken was twice or sometime thrice of the model time.On ...
ptrblck
No, since torch.cuda.synchronize() will just wait for the GPU until it finishes its workload. Batched inputs will saturate the GPU better. PyTorch does not use multiprocessing in its backend and modules accept batched inputs by default. In case you are seeing a large CPU overhead in your profile…
ihdffuij
image3629×1250 1.42 MBOs: windows 10
ptrblck
Intel’s GPUs are not supported by CUDA and you would need an NVIDIA GPU.
Sourena_Yadegari
I thought I had a good grasp of automatic differentiation but I cannot make sense of the following snippet I wrote:import torch def f1(t): return t ** 2 def f2(t): return t ** 3 def get_t(): return torch.tensor([1., 2.], requires_grad=True) # case 1 t = get_t() print('grad after initialization', t.grad)...
ptrblck
It would depend on the next operations and you will see your expected results if you reduce the values via .sum() or .mean(). To see the influence of a constant on the norm you could write down the calculation and check the gradients manually: t = get_t() tmp = f1(t) #loss = (tmp**2).sum().sqrt()…
Toucan
Task Description:I’ve constructed a model which is trained in two stages. The first stage is just a regular training loop, and the second is extra training for bias correction. During the second training phase, I created a variable (self.rotated_weight in this case) within the forward() to correct bias.Question:Can th...
ptrblck
Yes, you can create member attributes in the forward, which would be accessible afterwards as seen here: class MyModel(nn.Module): def __init__(self): super().__init__() self.my_param = nn.Parameter(torch.randn(1, 1)) def forward(self, x): self.my_new_tensor = torch…
palguna_gopireddy
I am a basic question.Shouldsoftmaxbe applied after or before Loss calculation. I have seen many threads discussing the same topic aboutSoftmaxandCrossEntropy Loss. But my question is in general, i.e. regarding usingSoftmaxwith any loss function. SoIs it a rule of thumb that softmax if used, it should only be used befo...
ptrblck
It depends on the loss function and where it defines the softmax operation. The issue with F.softmax and nn.CrossEntropyLoss in PyTorch is that nn.CrossEntropyLoss applies F.log_softmax internally and thus no previous F.softmax operation should be used. It’s thus not the user’s choice if and where …
pylearn
Suppose I have a model,modelA. Can I use it as a block/layer in a new model,modelB, by directly assigningmodelAas a layer in the__init__()ofModelB? What are the possible side effect? For example,modelA = nn.Conv2d(20, 20, 5) class ModelB(nn.Module): def __init__(self, modelA): super().__init__() se...
ptrblck
Your approach will work and there is no difference where the submodules were initialized. Creating modelA outside of modelB allows you to use it separately (modelB holds a reference to modelA so will see the changes). This usage would break e.g. DDP, but I don’t see any issues if a) you are nor usin…
Bluegirl123
Hi I am trying to create a diffractive neural network model using pytorch. Although I set the requires_grad=True for the parameters that I want to calculate the gradients, I am unable to get the gradients. It shows the gradients as none type. So I am unable to update the parameters. Can anyone please suggest me the pos...
ptrblck
Could you post a minimal and executable code snippet to reproduce the issue, please?
ADONAI_TZEVAOT
I have 2 classes A and B. How can class B access parameters that are in class A?
ptrblck
Sure, here is a small example: class A(object): def __init__(self, B): self.B = B print(self.B.internal_attribute) class B(object): def __init__(self): self.internal_attribute = 2.8 b = B() a = A(b) # 2.8
Hungreeee
Hi everyone,As the title says, when I use word embeddings, my model output becomes[batch_size, sequence_length, output_size]instead of[batch_size, output_size]. I wonder if this behaviour is expected fromnn.Embedding? How can I obtain the output I desire [batch_size, output_size]?class FeedFoward(nn.Module): def __in...
ptrblck
If you want to get rid of the sequence_length you could just call any reduction on this dimension (e.g. .sum(1), .mean(1), .max(1) etc. of you could use e.g. a linear layer to map the (static) sequence_length to a single value. If depends on your use case and especially if the sequence_length is sta…
palguna_gopireddy
I have designed a model with output nodes(400 in my case)not equal to the number of classes(5 in my case). When I train this model, only first 0 to 4 columns in the output are non-zero, remaining 5 to 400 column values are zero.So when I used_, pred_labels = torch.max(y_predict, 1), it is producing predicted labels in ...
ptrblck
You can slice the output via y_predict[:, :5] to use only the first 5 columns.
vdw
Is there a way to check / decide if 2 network models are identical despite a different implementation. For example, let’s assume I have the following two classesSimpleNet1andSimpleNet2.class SimpleNet1(nn.Module): def __init__(self, vocab_size): super().__init__() self.vocab_size = vocab_size self....
ptrblck
Comparing the outputs is a valid method, but as you’ve already stated you would need to load the state_dict from one model to the other, which might need some manual work especially if the layer names etc. change. Tracing the model is also a good idea and you might be able to use torch.fx for it. …
LunaR
Hi!I’m new at PyTorch and getting “mat1 and mat2 shapes cannot be multiplied (61200x3 and 61200x42)” on “x = self.fc(x)”.My 3000 input tensors had the shape (1, 51, 3) and I want 3000 output tensords each of the shape (1, 42, 3)import torch.nn as nn class Net(nn.Module): def __init__(self): super(Net, sel...
ptrblck
It seems you are forgetting to flatten the activation via: x = x.view(x.size(0), -1) or an nn.Flatten layer before passing it to the self.fc layer. Once this is done you will run into another shape mismatch error since the activation has 24 * 51 * 3 = 3672 features, so set the in_features argument …
Kevin_Dong
I am trying to fine-tune a pre-trained model by freezing different parts of the model. Say the model has an encoder and decoder. If I only want to train the encoder, I can freeze the decoder by settings its Tensor to be requires_grad=False. However, does it block the gradient flow back to the encoder?In practice, I fou...
ptrblck
No, it doesn’t and Autograd is smart enough to backpropagate the gradients to earlier parameters. Autograd will use this attribute to decide if a gradient computation is needed or not. E.g. freezing the parameter will reduce the wgrad kernels as seen inthis example.
Sasika_Amarasinghe
File "train.py", line 26, in <module> MyModel = PretrainedModel(arch_name,hidden_layers, data_dir, epochs, device , learning_rate, manual_seed) File "/home/workspace/ImageClassifier/Model.py", line 62, in __init__ self.flower_classifier = FlowerClassifier(self.input_layer_size, self.output_layer_size, self.hi...
ptrblck
RuntimeError: CUDA error (10): invalid device ordinal is raised if you try to specify a wrong device id as seen e.g. here: x = torch.randn(1).to("cuda:100") # RuntimeError: CUDA error: invalid device ordinal Check which GPU id is used and make sure it’s in [0, nb_gpus-1].
malice
Hello!I’m trying to do something which is possibly a bit silly, involving training multiple things in the same neural net by adhering their loss functions. Here’s an example, in which a CNN learns image classification (on cifar10) and at the same time, a separate tensor, “noisyfriend” is told to decrease its norm:impor...
ptrblck
Your noisy friend is not properly registered as a parameter and will thus not be passed to the optimizer via model.parameters(): print(dict(model.named_parameters()).keys()) > dict_keys(['conv1.weight', 'conv1.bias', 'fc1.weight', 'fc1.bias', 'fc2.weight', 'fc2.bias']) Use self.register_parameter …
koklimabc
I’d recently copied coding from old Ebook and practice to work on pytouch lightning, but it seems to be buggy to me. I’m hope someone could help me on that#!/usr/bin/python import os import torch import torchvision import torchmetrics import pandas as pd import numpy as np import pytorch_lightning as pl from PIL import...
ptrblck
Thanks for the code! It’s still not executable so I removed the unnecessary data loading and Lightning usage. Afterwards I was able to reproduce the issue and the error is caused due to the missing assignment in: output.view(-1, 6 * 16 * 16) use: output = output.view(-1, 6 * 16 * 16) # or better …
Ayush_Singhal
I was just curious about the NNs. So I did a small experiment. I took a simple Linear Layernn.Linear(2 , 2). The training is simplelosses = [] for f , t in zip(fea , tar): preds = layer(f) loss = loss_f(preds , t) losses.append(loss) optim.zero_grad() loss.backward() optim.step()Here the op...
ptrblck
Is wrong as nn.Parameter won’t accept a dtype argument and will fail with: TypeError: Parameter.__new__() got an unexpected keyword argument 'dtype' Fixing this issue properly allows x to be optimized: x = nn.Parameter(torch.rand(2 , 2, dtype = torch.float32)) optim = torch.optim.Adam([x], lr=1…
Mah_Neh
I want to get the network weights as float16, so the network is currentlynn().to(torch.float16)nd, however, I get an error due to the biases being float32 type.This is the errorreturn F.conv2d(input, weight, bias, self.stride, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ RuntimeError: Input type (c10::Half) an...
ptrblck
The second approach can easily fail and diverge, which is why we recommend using amp for mixed-precision training. Depending on the model pure float16 training could still work, but it’s generally less stable.
trusira
I’m usingpytorch,pytorch-cpu 1.6.0 cpu_py38h3369884_1 conda-forgeinstalled through anaconda and I get the following error.>>> import torch >>> torch.nn.HuberLoss() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'torch.nn' has no attribute 'HuberLoss'I can see the HuberL...
ptrblck
nn.HuberLoss was introduces in PyTorch 1.9.0 so you would need to update your installation.
CTZ
Hi,I wondered if it makes a difference to specify torch.no_grad() inside a custom autograd class for the forward and backward functions.Thanks!
ptrblck
No, it shouldn’t make a difference since gradient computation is already disabled in custom autograd.Functions by default: class MyFun(torch.autograd.Function): @staticmethod def forward(ctx, input): print(torch.is_grad_enabled()) ctx.save_for_backward(input) return …
hwaseem04
Consider the following training code for Autoencodersdef train(model, data, epoch, lr=0.001): opt = torch.optim.Adam(model.parameters(), lr) train_loss = [0] * epoch for i in range(epoch): for x, y in data: x = x.to(device) opt.zero_grad() x_hat = model(x) ...
ptrblck
No, these approaches are not the same depending on the tensor shape. As described in thedocsF.mse_loss will calculate mean(L) by default, which would correspond to a division by the number of elements, not the batch size. x = torch.randn(10, 10) x_hat = torch.randn(10, 10) print(F.mse_loss(x_ha…
KUSHAL_JAIN
I have a neural net wherein I define multiple nn.Sequential modules in the__init__(). However, I use only one of them in the forward method based on a condition. Still, for all these modules, the weights and biases are initialized andrequires_gradis alsoTruewhich is expected. I do not actually need the gradients of mod...
ptrblck
I think a conditional creation of the desired “head” module in __init__ sounds like a proper way.
Bartosz_Brzoza
Hi everyone,I have two models, say model_a, model_b.model_b takes as input the output of model_a as well as some other additional input.For each input to model_a there are several (large amount) of additional inputs to model_b.I want to make a gradient step for model_b’s weights for each of the additional inputs while ...
ptrblck
In your current code snippet you are calculating the gradients w.r.t. model_a’s parameters multiple times inside the nested for loop. I.e. loss.backward() is attached to model_b and via enc to model_a. This will raise the error since intermediates in model_a will be freed in the first backward call. …
King4819
Hey guys, I want to ask if there’s a method to copy weights from pretrained ResNet-50 model to pruned model.Now I have the prune cfg, which is the number of remain channels in each layere.g. pruned_cfg = [18, 23, 24, 25, 20, 30, 46, 46, 30, 39, 49, 71, 52, 59, 130,109, 62, 84, 73, 85, 86, 92, 112, 110, 105, 106, 24, 17...
ptrblck
I don’t know if there is an easy way to perform your desired loading and you would most likely need to load each weight separately: model = models.resnet18() mask = torch.tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,…
Mah_Neh
The network should tell if an image is rotated, and how much.The training data is simple and contains faces, and it should be able to tell which of the 90* positions is the image on.The data is all stored are standard upward facing faces, and they are rotated on the fly by a transformation.Before showing the network, t...
ptrblck
I don’t know which criterion you are using, but assuming you treat this use case as a multi-class classification and assuming you are using nn.CrossEntropyLoss, you should remove the softmax as raw logits are expected.
sl5035
I am trying to train a transformer model after extending its vocabulary. The problem is I want to keep the original weights frozen and train only the weights associated with the new vocabulary. I was thinking of doing something like this:processor = processor() # Loading processor model = model() # Loading model for pa...
ptrblck
It’s unclear what exactly happens in your code as neither object definitions are posted nor did you explain what the custom methods perform. If you want to freeze a weight parameter partially, you could zero out its gradients before calling optimizer.step() (which should work for stateless optimize…
KimberleyJensen
Since updating to PyTorch 2.0.0 i had to add return_complex=True to my code but now it causes this error“RuntimeError: permute(sparse_coo): number of dimensions in the tensor input does not match the length of the desired ordering of dimensions i.e. input.dim() = 3 is not equal to len(dims) = 4”Please does anyone know ...
ptrblck
I can reproduce the mentioned error using: module = STFT(10, 10, 10) x = torch.randn(1, 10, 10) Based on thedocsit seems you could restore the 4-dimensional tensor via torch.view_as_real which also seems to fix your error: def __call__(self, x): window = self.window.to(x.device) …
lisyuan
Hi,As far as I understanding, when using thetorch.inference_mode()ortorch.no_grad(),the model will not caculating the gradients and therequires_gradwill beFalse.I write a simple code to reproduce my questionimport torch import torch.nn as nn class Network(nn.Module): def __init__( self, ): supe...
ptrblck
This is expected since the inference_mode context won’t change the .requires_grad attributes of parameters or inputs. The output won’t be attached to a computation graph and no intermediate tensors will be stored, as expected.
Mah_Neh
This is my neural network relevant code snippet:class NeuralNetwork(nn.Module): def __init__(self, input_size:int): super().__init__() self.backbone = SpotRotBackbone() # input to the head calculated from the backbone's structure self.head = SpotRotHead(input_size*input_size*16) ...
ptrblck
Almost all CNNs use it as seenherefor resnet.
gursi261
I am working on a machine translation dataset and the input entries are sorted from the shortest sequence to the longest sequence. I pad them to the max length in each batch using collate_fn.Is there a way to make batch creation unshuffled so that similar length entries end up in the same batch (since the data is sorte...
ptrblck
Take a look at e.g.this postfrom@vdwwhere he shared a similar approach.
toomanyeggs
I’m fairly new to PyTorch, so maybe the answer will be obvious to someone else. I’ve got a custom dataset for object detection that returns batches of images and their objects (dictionaries containing boxes, labels, image_id, area, iscrowd). However, when I instantiate and load the custom dataset (see code below), dupl...
ptrblck
No, normalize won’t overwrite any seeds and you would need to re-seed the PRNG manually. You should not set any seeds repeatedly if you want to get random outcomes. If you get stuck, post a minimal and executable code snippet reproducing the issue, please.
STRE_RING
I am preparing data for an RNN, the data point in the dataset is a list containing 11 RGB images, thus the dimension of “out” in the following is 11 * 3 * 224 * 224:defgetitem(self,index):topk_s = self.tops[index] if self.shuffle: topk_s = random.sample(topk_s,len(topk_s)) out = [] for i in to...
ptrblck
If you are returning a list from the __getitem__ PyTorch will keep it and x as well as data1 will both be lists containing the tensors. If you out = torch.stack(out) the list in __getitem__ the same output shapes seem in my code snippet will be returned.
OlyMitch
Hi all,I am currently working on deploying a uvicorn model inference API to kubernetes, and I am running into a peculiar problem. According totorch.cuda.is_available(), my CUDA is ready to be used (it returns True), however as soon as I try to inference the model, I get an internal server error telling me that there is...
ptrblck
Update to the latest stable or nightly release and check if you would still see the same error. If so, try to rerun your script via compute-sanitizer python script.py args to narrow down which operation fails. If this doesn’t work, post a minimal and executable code snippet reproducing the issue.
smani
image645×607 13.8 KBI want to create a ResNet-18 model with two branches as shown in the above figure, where I replicate the original Layer 4 to create the branches. However, I don’t know how to initialize the weights of these two layers (Layer 4_1 and Layer 4_2) with ImageNet pretrained weights. Could you please help ...
ptrblck
You could manually load all desired parameters by directly accessing the modules. E.g. something like this would work to load the parameters into the two custom layers: model = models.resnet18() sd = model.state_dict() layer4_1 = nn.Conv2d(256, 512, 3, 2, 1, bias=False) # access custom layers an…
Mah_Neh
If we add a conv layer with 64 filters how are they actually optimized differently and do not end up being all the same value?
ptrblck
Since all filters are initialized randomly (with different random weights) the training let’s them converge to different final values. If you would initialize all with the same static value(s), the training might collapse and the final values could be the same.
akskuchi
I need to use torch version<=1.5.0on a system that only has CUDA drivers>=11.Does this mean I have to follow the steps underbuild from source, by cloning the pytorch repo at respective version tags - e.g.,1.5.0?P.s: I’ve looked up the discussion threads and could not find a directly related discussion. Apologies if I m...
ptrblck
I don’t know which GPU you are using but Ampere+ requires CUDA11+ and will fail with older releases.
Nobutaka_Kim
dcgan/ CMakeLists.txt dcgan.cpp Further, I will refer to the path to the unzipped LibTorch distribution as /path/to/libtorch. Note that this must be an absolute path. In particular, setting CMAKE_PREFIX_PATH to something like ../../libtorch will break in unexpected ways. Instead, write $PWD/../../libtorch to get t...
ptrblck
Your first code snippet contains the expected ..: root@fa350df05ecf:/home/build# cmake -DCMAKE_PREFIX_PATH=/path/to/libtorch .. while the second one doesn’t: nobu@LAPTOP-DNCQ5AAC:/mnt/d/computervision/dcgan/build$ cmake -DCMAKE_PREFIX_PATH=/mnt/d/computervision/libtorch CMake Warning: ... Why di…
ptrblck
Read through your code and search for any lines of code which replace modules or parameters directly. Again, PyTorch won’t automatically change your model architecture. In case you are using 3rd party packages, which might perform some network surgery, look through it too. It’s your code so you should know why the mode...
ptrblck
Your code is neither properly formatted nor is it executable since you have a data dependency. In any case, the error is raised since you are mixing up input arguments in the model creation. At first you are using: model_x = tinyvgg1(input=3, hidden=76, output=2).to(device) and later: model = t…
Animesh_Kumar_Paul
X = torch.from_numpy(np.asarray(X, dtype=np.float32)).float() y = torch.from_numpy(y).float()Y has values like this:0.0, 0.06666666666666665, 0.13333333333333336, 0.2, 0.2666666666666667, 0.33333333333333337, 0.4, 0.6, 0.6173913043478261, 0.6347826086956522, 0.6521739130434783, 0.6695652173913043, 0.6869565217391305, 0...
ptrblck
The error is expected since floating point targets should have the same shape as the model outputs as described in the docs and seen in my example. Because the floating point targets represent a “soft-target” for the multi-class classification loss. If you are interested purely in a binary classi…
ChanYalcn
This is going to be a long question. This below is my neural net.class CarBrand(nn.Module): def __init__(self, num_classes): super(CarBrand, self).__init__() # 'in_channels': color channels in images, since images in dataset are greyscaled, in_channels start from 1 self.conv1 = nn.C...
ptrblck
Try: brand_pred = model(images.unsqueeze(1)).
mini-batch
I am trying to do some analysis of the test loss landscape and I’m trying to implement the following basic scheme.Within each epoch:Calculate the weight update based on the full training setMeasure some metrics relating to the test loss function (this uses the weight update from step 1, but shouldn’t alter it)Perform t...
ptrblck
You might be running intothis issue.
otavio-silva
I’m trying to compute derivatives of functions in a TensorFlow-like fashion. Consider the following code:import torch x = torch.linspace(-10., 10, 10000, requires_grad=True) y = x**2 y.backward(torch.ones_like(x)) g = x.gradIt works just fine, withgbeing the gradient, such thatf(x) = x**2andf'(x) = 2x.But if I set the ...
ptrblck
The .to() operation is differentiable and will create a non-leaf tensor as the warning explains. Either specify the device during the creation: x = torch.linspace(-10., 10, 10000, device="cuda", requires_grad=True) y = x**2 y.backward(torch.ones_like(x)) g = x.grad or create a new leaf tensor: x…
dbc111
I’m currently using a UNet for image regression and want to explore data augmentation. However, it appears to me that pytorch transformations (as implemented below) replace the original image in the dataset. Considering that the total amount of data in the dataset stays the same, won’t the model’s performance be simila...
ptrblck
The transformation does not replace the data as it’s applied on the fly for each sample. No, since you are randomly transforming each sample in every iteration. Depending on the used transformations the likelihood to repeat exactly the same random config (for all applied transforms) might go towa…
Caue_Evangelista
Hello dear community,I’m currently working on building an autoencoder in PyTorch that takes an input of shape[batch_size, 1, 21]and aims to map it to a bottleneck dimension of 3 after passing through the encoder. The model architecture involves convolutional and linear layers, and I’m encountering a runtime error that ...
ptrblck
In that case you would need to permute the input activation before applying the linear layer and permute it back afterwards: x = torch.randn([32, 512, 3]) lin = nn.Linear(512, 1) out = lin(x.permute(0, 2, 1)) out = out.permute(0, 2, 1) print(out.shape) # torch.Size([32, 1, 3])
abask61
There are lots of posts on feature visualization. But how do I deactivate a feature map (not filter)?(layer4): Sequential((0): BasicBlock((conv1): Conv2d(256, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=1)(relu): Re...
ptrblck
Multiply the forward activation in the forward method with a mask, which will zero out the desired channel.
abask61
I want to deactivate one filter of a conv layer just before inference.Here’s a partial Resnet model:(layer4): Sequential((0): BasicBlock((conv1): Conv2d(256, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=1)(relu): ReL...
ptrblck
It works for me: model = torchvision.models.resnet18() idx = 1 with torch.no_grad(): model.layer4[1].conv2.weight[idx].zero_() print(model.layer4[1].conv2.weight[idx]) # tensor([[[0., 0., 0.], # [0., 0., 0.], # [0., 0., 0.]], # [[0., 0., 0.], # [0., 0., 0.],…
caesar025
When using the recipe for training with AMP and GradScaler, i.e.:scaler.scale(loss).backward() scaler.step(optimizer) scaler.update()Is the optimizer step performed in full or half precision? And could this lead to issues in regard to very, very small learning rates?
ptrblck
The model parameters are kept in float32 and not transformed to the lower precision dtype. The optimizer thus applies the update on the float32 parameters.
Imahn
Hi,My issue is similar tothis solved one, but I am wondering about why the DataLoader returns a list instead of a tuple.Code for reproducing (PyTorch 2.0.1):from typing import Any, Optional import torch from torch.utils.data import Dataset, DataLoader class ImageDataset(Dataset): def __init__(self, imgs: torch...
ptrblck
The default collate_fn seems to return lists for Sequences as seenhere. If you want to return a tuple you might need to implement a custom collate_fn.
arunppsg
Here is a sample code:#include <torch/torch.h> #include <iostream> int main() { torch::Tensor input = torch::rand({2, 3}); auto size = input.sizes(); // What is sym_size and how is it different from size? auto sym_size = input.sym_sizes(); std::cout << " size " << size << " sym size " << sym_size << std::...
ptrblck
sym_size should correspond to symbolic shape and is used during tracing. Unless you are working on the symbolic tracing this method might not be useful.
Chethan_Chandran
This is my pytorch version and my GPU is “NVIDIA GeForce RTX 4090”When I try to train my model, Kernel dies with the below outputC:\actions-runner_work\pytorch\pytorch\builder\windows\pytorch\aten\src\ATen\native\cuda\IndexKernel.cu:93: block: [62,0,0], thread: [115,0,0] Assertionindex >= -sizes[i] && index < sizes[i] ...
ptrblck
The error message points towards an indexing error and is unrelated to the used PyTorch binary. Narrow down the failing indexing operation and fix it.
algoTrader
Hi,I am training a simple CNN model. During the training I am getting an error message “ValueError: Expected input batch_size (16) to match target batch_size (32).”I am using Python version 3.10.12.This is my model:# Create a convolutional neural network class FashMNISTModelV2(nn.Module): # Model replicated called ...
ptrblck
Your model looks correct and keeps the batch size equal: model = FashMNISTModelV2(1, 10, 10) x = torch.randn(16, 1, 28, 28) out = model(x) # Output shape of conv block1: torch.Size([16, 10, 14, 14]) # Output shape of conv block2: torch.Size([16, 10, 7, 7]) # Output shape of classifier: torch.Siz…
grid_world
For a toy CNN architecture:class LeNet5(nn.Module): def __init__(self): # def __init__(self, beta = 1.0): super().__init__() # Trainable parameter for swish activation function- # self.beta = nn.Parameter(torch.tensor(beta, requires_grad = True)) self.conv1 = nn...
ptrblck
You can either directly manipulate the parameter or you would need to load the manipulated state_dict since you are currently working on a temporary object: model = torchvision.models.resnet18() with torch.no_grad(): model.conv1.weight.copy_(torch.ones_like(model.conv1.weight)) print(model.co…
Lin-Nan
I have run the train.py with ddp. The dataset includes 10 datasets.torchrun --nnodes=1 --nproc_per_node=3 --rdzv_id=100 --rdzv_backend=c10d --rdzv_endpoint=xxxx:29400 cat_train.pyBut when I train about the 26000 iters (530000 train iters per epoch), it shows this:WARNING:torch.distributed.elastic.rendezvous.dynamic_ren...
ptrblck
A SIGKILL is often sent to a process from the OS if it’s running out of memory. Could you check in e.g. dmesg is an out of memory issue was detected and the OS was forced to kill your process?
PARUL_JOSHI
I’m getting Target 1 is out of bounds error and not able to debug the error. Can anyone please help me out with this error. I have also added a snapshot of my model summary.My code :Screenshot 2023-08-04 101105522×528 12.3 KB# Define the loss function (negative log-likelihood) criterion = nn.NLLLoss() # Define the opt...
ptrblck
Your last linear layer outputs a single value, which is wrong in combination with nn.NLLLoss, since this loss function is used for a multi-class classification expecting an output in the shape [batch_size, nb_classes] containing log probabilities. If you are working on a binary classification, init…
Mah_Neh
I read the pytorch docs and wrote a simple network.I don’t understand how to load my data and pass it to the model.Can you give me a minimal example please ? or any snippet to get started ?I do not have labels in a particular format yet, so that does not matter much just now.
ptrblck
This data loading tutorialmight be a good starter.
codingGoose
I noticed that in theWord Embeddings tutorial, the N-Gram Language Modelling example zeroes out the gradient with the following line of code:# Step 2. Recall that torch *accumulates* gradients. Before passing in a # new instance, you need to zero out the gradients from the old # instance model.zero_grad()My understand...
ptrblck
optimizer.zero_grad() is equal to model.zero_grad() if all parameters were passed to the optimizer, which is also the case in this tutorial.
antonl
Hello! I am running into a memory issue that I think I shouldn’t be having with 24 GB of VRAM. I am trying to train Mask R-CNN and find that directly after the first forward call, the allocated memory explodes in size to ~20GB, which I don’t expect since the model is ~200MB and the batch is ~300MB. Then when I callloss...
ptrblck
The model parameter and input size might be tiny compared to the stored intermediates needed for gradient computation. Have a look atthis postshowing an example.
berlin
I’m trying to translate the below 3layer CNN architecture from keras to pytorch. The usage of the model is to predict expression value(input_shape_val) from dna sequence(input_shape_hot). The sequence is one hot encoded. The architecture orignally meant to train the model consecutively CNN (3 layers)-FC (2 layers) with...
ptrblck
The shape mismatch error seems to be raised in your linear layer and based on the error message the in_features value does not match the number of features of its input activation. Assuming you are using 2048 samples each with a feature dimension of 2048, using in_features=2048 in the linear layer …
Caue_Evangelista
Hi, dear community.I’m fairly new in the field of M.L. and I’m trying to build a 1D autoencoder.My data consist of 100 rows with 21 columns. In this scenario, each row is an individual sample.My goal is to create a 1D autoencoder able to map these lines into a 19 collums representation, and after this back to 21 column...
ptrblck
You are initializing the conv layers with the batch_size for their input and output channels, which is wrong. Conv layers should define the in_channels as the number of channels from their input activations and define the out_channels of the output activation (which corresponds to the channels [or …
Abhishek_Gupta
Hello everyone,I am trying data augmentation in Torchvision CIFAR10 dataset. But there is one catch, I can not find probability option, i.e. for example if I applyPadthen it will apply padding to every image, but since it is augmentation this augmentation need to be applied randomly with someProbablityand I cannot find...
ptrblck
Wouldtransforms.RandomApplywork for your use case?
johannes-lee
When using torch.nn.functional.elu and torch.nn.ELU on CPU, performing:slice → ELUandELU → sliceproduce different results. Expected: exactly the same output (same bytes). [slice → clone → ELU] produces the same output as [slice → ELU]The code block below produces the following output on a particular Linux machine:proce...
ptrblck
PyTorch does not guarantee bitwise-identical results for different workloads (even if deterministic settings are used) since different algorithms could be picked. Depending on the order of operations of these algos the results might show the expected errors caused by the limited floating point preci…
lola1
As dataset I am using npz files. One npz file represents one video and contains keypoints (x,y, confidence score). I am trying to build 1D CNN network that will classifies those npz sample to one of the classes. I notices that no matter what I try I am always getting quite the same result. Loss decreases only little bi...
ptrblck
In that case your dataset seems to be quite small as the accuracy and losses are quite noisy, so you might want to increase the number of samples if possible.