user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
crissallan
Hi, I notice that nn.Conv2d’s backward pass is around 2~3 times faster than the nn.Conv3d’s. Why it is like that?The condition of my experiments is below:nn.Conv2d with a (3, 3) kernel process a tensor in shape [Batch * Time, in_channel, Height, Width].nn.Conv3d with a(1, 3, 3) kernel process a tensor in shape[Batch, ...
ptrblck
Blocking launches would synchronize all calls, so I wouldn’t use it. A proper way would be to thethe benchmark utils.which will add warmup iterations and needed synchronizations for you.
sag21
When I verifympssupport using a recommended Python script:import torchif torch.backends.mps.is_available():mps_device = torch.device(“mps”)x = torch.ones(1, device=mps_device)print (x)else:print (“MPS device not found.”)I get output the following output:tensor([1.], device=‘mps:0’)But when I use the same script in Jupy...
ptrblck
You are most likely using a different virtual environment in your Jupyter notebook, so make sure the same env is used with the same PyTorch binary. You can check the installed PyTorch release e.g. via print(torch.__version__).
Ahmed_Khaled
I got an error that is almost the one solved hereKernel size can't greater than actual input sizethe solution, as provided, is to lower the kernel size to 1 (to make it lower than the input size).How can I do this with the pretrained wav2vec (WAV2VEC2_ASR_BASE_960H) model?
ptrblck
Yes, you can fine-tune specific layers only as described in e.g.this tutorial.
ernest-s
I have a one-dimensional tensora = torch.tensor([0,2,3,4]).From this tensor, I want to create another two-dimensional tensor which looks like this:tensor([[1, 1, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0...
ptrblck
torch.blog_diag should also work: a = torch.tensor([0,2,3,4]) blocks = [] for a_ in a: tmp = torch.ones(a_, a_) blocks.append(tmp) torch.block_diag(*[b for b in blocks]) # tensor([[1., 1., 0., 0., 0., 0., 0., 0., 0.], # [1., 1., 0., 0., 0., 0., 0., 0., 0.], # [0., 0., 1., 1…
Noanemo
Hello everyone. I’m having a slight issue with implementing a custom loss function. So have I looked at the other posts related to my similar problem and have double checked the loss function itself of detaching operations but I think I have got rid of all of them and have switched them up to torch functions. However, ...
ptrblck
You are mixing multiple PyTorch installations: [pip3] torch==2.0.1 ... [conda] pytorch 1.12.1 cuda112py39hb0b7ed5_201 conda-forge Uninstall both and reinstall only the one you want to use to avoid library conflicts.
MartinZhang
what’s the aten::ScalarImplicit?where can I find the reference documentation about it.thanks.
ptrblck
I don’t think this class is publicly documented but you could check its implementationherewhich calls intocheckImplictTensorToNumand then returns the .item() of the passed tensor, so its scalar value.
Padmaksha_Roy
Hi Team, I have a loss function where I am calculating the loss over multiple domains and summing it up to form the final loss, and for each epoch, I am doing gradient descent on it. Can you plz let me know if the implementation is correct?def train_AE():for epoch in range(epochs): train_loss = 0 losses = [] ...
ptrblck
Yes, taking the mean of the final loss would also work as it would just scale the loss and thus gradients.
RKnowledge
Hi!I wanted to ask if it’s a good practice or if there are better ways to free memory when using a Dataloader with a huge dataset.For the same model, the same batch size I’m able to train on a smaller dataset so I’d like to know if there are any ways to leverage the bigger dataset.Thank you!
ptrblck
Yes, your explanation makes sense and a variable input shape will also cause different memory requirements. A large sequence length in one batch could increase the memory usage significantly and could yield an out of memory error. You could try to check the min/max sequence lengths and maybe clip th…
Salman_Abbasi
HiI have one question about the regression and classification loss. I have trained a network which outputs denoised data and its corresponding events picked in binary(0 or 1). At the moment I am using only MSE loss and then set some threshold criteria for binary data, to convert to 0 or 1.Is it possible that I have two...
ptrblck
Yes, you can calculate and sum different losses, which can then be used to compute the gradients and train the model.
JBoRu
I’m confused about the doc of torch.renorm and can you tell me what use of renorm and how the example in doc as follows compute.>>> x tensor([[ 1., 1., 1.], [ 2., 2., 2.], [ 3., 3., 3.]]) >>> torch.renorm(x, 1, 0, 5) tensor([[ 1.0000, 1.0000, 1.0000], [ 1.6667, 1.6667, 1.6667], ...
ptrblck
No, I don’t think it’s a bug and it seems you are using the dim argument wrong in renorm: x = torch.randn(3, 3) x.norm(p=2, dim=1) # tensor([1.2906, 2.8629, 1.7181]) torch.renorm(x, p=2, dim=0, maxnorm=2).norm(p=2, dim=1) # tensor([1.2906, 2.0000, 1.7181]) x = torch.randn(3, 3) * 5 x.norm(p=2, dim…
Shraban_Chatterjee
I have a densenet121 model from pytorchDenseNet((features): Sequential((conv0): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)(norm0): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)(relu0): ReLU(inplace=True)(pool0): MaxPool2d(kernel_size=3, stride=2, paddi...
ptrblck
They are not the same since you are missingthese functional API calls.
Arnit_Panda
Can someone guide me the proper installation of cuda, tensorflow and pytorch from beginning with proper compatible versions for my local machine. And which python-version, so that its packages should be compatible with cuda, torch and tensorflow.±-------------------------------------------------------------------------...
ptrblck
You would need to reduce the batch size or use a smaller model to reduce the memory usage. Alternatively, you could also check torch.utils.checkpoint to trade compute for memory.
AKT_TARAFDER
code segment is the following:use_Mixed=True with torch.autograd.detect_anomaly(): graph=graph.to(device) input_feature_dim = feature.size(1) #print(input_feature_dim) net = gnn.GCN(input_feature_dim, args.dim, args.category) net.to(device) weight_decay=5e-4) optimiz...
ptrblck
You are only printing a subset of the logits, so it’s not a proper verification. Use e.g. torch.isfinite(logits).all() as a check.
Sam_Lerman
Are the indices generated in the main process and sent to the workers one by one or does each worker have its own Sampler that it iterates through independently?
ptrblck
The DataLoader should use one sampler which then sends the indices to each worker. If each worker would have a custom sampler they could load duplicated samples or the sampler would need to have multiprocessing capabilities, which is not the case.
thorstenwagner
Hi,I constantly run into an exception when I try to get DistributedDataParallel working.This is how I setup the both:self.model.to(self.rank) self.model = torch.nn.parallel.DistributedDataParallel(self.model, device_ids=[self.rank]) print("Compiling: Reduced overhead") self.model = torch.compile(self.model, mode="reduc...
ptrblck
Are you using the nightly binaries? If not, could you try these and check if you would run into the same issue still?
kjp4155
Hi, I would like to make some modification to the PyTorch source code for my research.The problem is, it takes 15~20min to build the whole source code on my 32-core machine. This is annoying when I make small changes in the C++ code and see the effect.I wonder how the other developers deal with such long build time.Are...
ptrblck
After a full rebuild python setup.py develop should only build all changed files and modules depending on it.This sectionof the contributing guide has more tips such as using ccache etc.
Spencerfonbuena
I am reading through the paper “Crossformer: Transformer Utilizing Cross-Dimension Dependency for Multivariate Time Series Forecasting”As part of their architecture, they merge together time series through the encoder, so as to attend to more coarse levels of time data. In their github, they do it in the following man...
ptrblck
I’m also unsure why the loop with the cat is used as reshape will not break the computation graph so should be fine to use.
Spencerfonbuena
I am using WandB to track pytorch machine learning projects. I am using an Nvidia A100 GPU hosted with Vultr. I don’t know if this is a question for this forum, but I figured that it would at least be down the alley of the people on the pytorch forums.On the WandB system reports, it shows that I am using 90% of the GPU...
ptrblck
I’m not familiar with wandb, but if I understand your question correctly you want to offload data to the CPU to be able to utilize these cores. In that case you could usethese functionsto offload data to the host to save memory and could move it manually via to("cpu") and execute any CPU layers on…
ArshadIram
Hi, I’m having the issue. I’m trying to use multiple webcams using different threads it works for about 1 minute without lag and with detections on GPU but then crashes with the exact same error. I then have to restart the entire development environment to run it again as it won’t let me run without a restart of the ap...
ptrblck
Could you run your workload via compute-sanitizer python script.py args and see if any issues are reported? Also, are you able to reproduce the issue without any cam usage in pure PyTorch?
wadewang
I tried to achieve the same result with torch.nn.Conv1d using torch.nn.Conv2d for fun, I think conv1d is a subclass of conv2d, just make the input tensor height as 1 and kernel height as 1, but the test code tells me their results are not same:import torch input_for_conv2d = torch.randn(8, 6, 1, 100) input_for_conv1d =...
ptrblck
Set the bias to False or copy it too and it should work.
Phungie
Hi there. I’m gonna keep my explanation short, since I have lots of code to present.I am trying to develop a new autoencoder architecture, but I am having trouble managing the forward/backward pass size of my model. I’m gonna explain with these test codes:Imagine we have the two following modules. one returns only the ...
ptrblck
You would need to explain what these sizes mean and how they were calculated. Checking the max. allocated memory fits my understanding as seen here: import torch import torch.nn as nn class testNet1(nn.Module): def __init__(self, dim_in=3, dim_inner=5, dim_out=3): super().__init__() …
anass_017
I have a small model with 900K in wightscompiled_model = torch.compile(net_model,backend="inductor",mode="max-autotune")When I compile the model using max_autotune model, he is giving me this warning :[WARNING] not enough SMs to use max_autotune_gemm mode and i don't know how to exploit thi feature.PS: I’m working on ...
ptrblck
The warning seems to be raisedhere, which assumes your GPU needs at least 80 SMs for this mode, which seems to be a hard-coded limitation in torch.compile.
pabloruizp
I am trying to progressively increase the lr using a lr_scheduler but it is not possible due to their implementation:class ConstantLR(_LRScheduler): def __init__(self, optimizer, factor=1.0 / 3, total_iters=5, last_epoch=-1, verbose=False): if factor > 1.0 or factor < 0: raise ValueError('Consta...
ptrblck
I think a LambdaLR object should work: model = nn.Linear(1, 1) optimizer = torch.optim.SGD(model.parameters(), lr=1.) factor = 2. scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda epoch: (epoch+1) * factor, last_epoch=- 1, verbose=False) for epoch in range(10): print(optimizer.p…
cpt.nemo
Hey folks,I am new to transfer learning, and I am working on a segmentation task using PT/ MONAI. I downloaded some pre-trained weights and now, I’d like to use them to freeze some layers on those weights and update the weihts of the remaining layers. My goal is to compare, if a fully frozen network (except final conv ...
ptrblck
Your code looks correct assuming you have checked the pattern matching. The model loading code also looks correct as you would see an error if the state_dict doesn’t match the model architecture.
asr-pub
Hello, now I am pretraining a HuBERT model, I have found that when the loss getting smaller, but increasingly frequent occurrences of gradient overflow, leading to a decreasing loss_scale.My understanding is that when the loss becomes smaller and smaller, it indicates that the model has converged. So why would gradient...
ptrblck
You could unscale the gradients manually to inspect them to see which ones are overflowing. Unscaling Infs or NaNs will of course keep these invalid values but it should give you an idea where in the model the gradients start to overflow.
Sam_Lerman
I create an instance of a torchvision ImageNet validation-set DataLoader calledimagenet_val.I then try to make an iterator for it:iter(imagenet_val).And get this trace:File "/u/slerman/u1/conda/envs/Sam/lib/python3.11/site-packages/torch/utils/data/dataloader.py", line 441, in __iter__ return self._get_iterator() ...
ptrblck
Check how many file handles can be used via ulimit -n and increase this value if needed.
bigtuna
For each layer of my model, I have a list of tensors corresponding to permutations for some experiments I’m running. These permutations are randomly generated at initialization. I realized that since I stored them in a regular python list, they were not saved when I saved and loaded the model stat dict. I would like to...
ptrblck
For non-floating point tensors you should register them as a buffer as seen here: class MyModel(nn.Module): def __init__(self): super().__init__() self.register_buffer("my_buffer", torch.randint(0, 10, (10,))) m = MyModel() print(m.state_dict()) # OrderedDict([('my_buff…
Phungie
I am planning to buy a new CPU and I was wondering if pytorch is compatible with AMD Ryzen CPUs. I have read in some threads that pytorch does not work well with AMD cpus but they are all from 3 years ago. I want to know if those issues have been solved or they are still a problem.
ptrblck
Not for the functionality of CPU operations, but for their performance as the fallback might be slower than MKL. However, you would need to profile it in the end to get a proper comparison as I’m just speculating. It thus depends on your point of view if you think a potentially slower execution pat…
nibtehaz
Hi, I am training a custom Vision Transformer model on ImageNet. I am using 4 V100 GPUs. Although my GPU utilization is high the power being consumed by the GPU is quite small. Is this normal?Capture903×577 30.5 KBInitially the training is quite fast, but with time the GPU power usage falls and the training becomes slo...
ptrblck
You could check if your GPUs are reducing their clocks as they might otherwise overheat. If so, you might want to check the cooling solution and improve it. Also, you could profile your use case (e.g. via Nsight Systems) to see if the GPUs might be bottlenecked by other code parts and might be wait…
caesar025
As far as I understand, using PyTorchs native AMP performs (part) of themodel trainingin half precision. Does it at the same time also make sense to force thedataset(e.g. ImageNet) to be in half-precision for additional speed-ups or is that already happening automatically as well when using AMP?
ptrblck
Native AMP’s autocast will transform data to a lower-precision dtype (float16 or bfloat16 depending on the used setup) for eligible operations for you. There is no need to manually transform data or any input to this dtype.
lzm2256
I think the two closely related functionstorch.varandtorch.meanshould have the same output shape, but this is not true. Is there any reason for this?a = torch.randn(4,3) a.var(1, True).shape # (4) a.mean(1, True).shape # (4,1)Apparently var is ignoring thekeepdimsargument.
ptrblck
That’s not the case and you should explicitly specify the keepdim argument which works fine: a.var(1, keepdim=True).shape # torch.Size([4, 1]) a.mean(1, keepdim=True).shape # torch.Size([4, 1]) In your current code the True argument in var would be passed to correction instead of keepdim as seen …
HaydenL
Why am I getting some tensors in my decoder portion of my VAE model being greater than 1. For example one recreation of an image from the decoder has a max of tensor(1.0000002384).I found this out after having trouble using matplotlib and getting warnings saying that my tensors were not in range of [0,1]. I don’t under...
ptrblck
Check if antialias=True is causing it. Besides that I wouldn’t know where these small numerical errors might be coming from.
No_Yeah
Hi I am to trying to reduce some layers of squeezenetmodel = models.squeezenet1_1(pretrained=False) PruneModels=[] PruneModels.append(model) PruneAcc=[] PruneLoss=[] bnum=[] name = (f'{model.__class__.__name__}') while PruneModels: model = PruneModels.pop() accs = [] torch.cuda.empty_cache() if name =...
ptrblck
Changing the in_channels after initializing the module won’t work as seen here: conv = nn.Conv2d(384, 1, 3, 1, 1) print(conv.weight.shape) # torch.Size([1, 384, 3, 3]) conv.in_channels = 512 print(conv.weight.shape) # torch.Size([1, 384, 3, 3]) print(conv) # Conv2d(512, 1, kernel_size=(3, 3), str…
Joao_Vitor_Valadares
Hello, I’m trying to build a Generator for my GAN and this is what it looks like:class Generator(nn.Module): def __init__(self, latent_size, init_resolution=8, resolution=256, channels=3): super(Generator,self).__init__() #resolution = self.resolution #channels = self.channels self....
ptrblck
Thanks for the code! Remove the * in *args and it should work.
mshooter
Hi everyone,I am trying to access values using torch.gatherI have a tensor of shape [B,K,64,64] and a tensor which represents the 2D indices [B,K,2]The resulting tensor should be [B,K,1]
ptrblck
Direct indexing should work: B, K = 2, 3 x = torch.randn(B, K, 64, 64) idx = torch.randint(0, 64, (B, K, 2)) out = x[torch.arange(x.size(0)).unsqueeze(1), torch.arange(x.size(1)), idx[:, :, 0], idx[:, :, 1]] print(out.shape) # torch.Size([2, 3])
arogozhnikov
Hi,I have such a simple method in my modeldef get_normal(self, std): if <here I need to know which device is used> : eps = torch.cuda.FloatTensor(std.size()).normal_() else: eps = torch.FloatTensor(std.size()).normal_() return Variable(eps).mul(std)To work efficiently, it...
ptrblck
Yes, although it might be a bit misleading in some special cases. In case your model is stored on just one GPU, you could simply print the device of one parameter, e.g.: print(next(model.parameters()).device) However, you could also use model sharding and split the model among a few GPUs. In tha…
caronzh03
Hi,I have 4x A100 GPUs on a single machine.With PyTorch2.0.0+cu117and nvidia driver version of515.105.01installed, the following is working as expected:>>> torch.cuda.is_available() TrueHowever, when I was trying to run a simpletorch.zeros([1]).cuda()command, it kept throwing Runtime errors at cuda init stage:File "~/....
ptrblck
Thanks for the update. In that case disable MIG or specify the UUID in CUDA_VISIBLE_DEVICES.
JakobHavtorn
In trying to implement data-dependent initialisation for weight-normalisation, I’ve run into a confusing behaviour with parameter initialization.I’ve boiled it down to a minimal example. Let’s say that for a linear layer I do the following:Initialize the bias to 0.0.Run the first forward pass.Initialize the bias to 1.0...
ptrblck
I can’t reproduce the issue and get the expected results: cpu -0.06411010026931763 0.5944567918777466 0.9358899593353271 0.5944567918777466 cuda:0 -0.06415127217769623 0.5944625735282898 0.9358487129211426 0.5944625735282898
J_B_28
Hello,I am wondering why the memory is not being released after inference, the following is my code (transformer is imported from huggingface):@torch.no_grad() def inference(self, hidden_state, mask, id): self.eval() print("begin_max", torch.cuda.max_memory_allocated("cuda:4")/ 1024 / 1024) ...
ptrblck
The increase in memory usage is expected since you are performing differentiable operations on the output of the model via x. Deleting hidden_state and pooled_output won’t change it since x still refers to the computation graph and holds references to these tensors. Also neither gc.collect nor empt…
gengala
Consider the following:layer = nn.Conv1d(64, 64, kernel_size=1, groups=4)This layer represents 4 linear layers that run in parallel, where each of them processes vectors of 16 dimensions and returns vectors of the same dimensionality.Now, suppose that we want each of this layers to process the same inputx = torch.randn...
ptrblck
Since you are just repeating the input a plain nn.Conv1d using in_channels=16 would yield the same results as your grouped conv: layer = nn.Conv1d(64, 64, kernel_size=1, groups=4, bias=False) x = torch.randn(1, 16, 1) x_ = x.repeat(1, 4, 1) out_ = layer(x_) conv = nn.Conv1d(16, 64, 1, bias=False)…
jagandecapri
I have a 3D tensor as followinga = torch.tensor([ [ [ 1, 2, 3], [ 4, 5, 6] ], [ [ 7, 8, 9], [10, 11, 12] ] ])I would like to select the first row of the first matrix and the second row of the second matrix within the 3D tensor to give the...
ptrblck
Direct indexing will work: a[[0, 1], [0, 1]] # tensor([[ 1, 2, 3], # [10, 11, 12]])
yiftach
Consider the following code:import torch x = torch.arange(100, device='cuda').reshape(50, 2) y = torch.empty(100, device='cuda').reshape(50, 2) for i, batch in enumerate(x): y[i] = batch ** 2My basic knowledge is that CUDA operations run asynchronously on the GPU, and that operations like.item()orprint()require a s...
ptrblck
Your code shouldn’t synchronize the code and you can double check it by adding torch.cuda.set_sync_debug_mode("warn") to your code.
Dawid
Hi,I’m trying to recreate ViT from scratch. Firstly I wanna do Patches class and when I’m trying to see result… I get something weird.Here is a link for images for more explanation:https://imgur.com/a/DNgNFHLHere is my code:import numpy as np import matplotlib.pyplot as plt import torch import torch.nn.functional as F ...
ptrblck
Using unfold is the right approach and works for me: img = PIL.Image.open(PATH) x = transforms.ToTensor()(img) y = x.unfold(1, 100, 100).unfold(2, 100, 100) y = y.contiguous().view(y.size(0), -1, 100, 100) y = y.permute(1, 0, 2, 3).contiguous() print(y.shape) fig, axarr = plt.subplots(8, 8) axarr…
PromiX
Hi Forum!I decided to build pytorch on GTX660 graphics card (don’t ask why, I don’t know).I got the idea from thearticle.What I used:NVIDIA Driver474.30-desktop-win10-win11-64bit-international-dch-whqlcuda 10.2cuda_10.2.89_441.22_win10.exe2 updates (cuda_10.2.1_win10 and cuda_10.2.2_win10)cudnn 8.7.0cudnn-windows-x86_6...
ptrblck
Try to build an older PyTorch release as the current main branch bumped the C++ standard to C++17, which CUDA<11 did not support. I’m unsure if this could be related, but might otherwise fail at a later build step.
ptrblck
I don’t know how exactly you are loading your dataset, butthis tutorialmight be a good starter.In general you should pass inputs as[batch_size, channels, height, width]tonn.Conv2dlayers while you are using[batch_size=1, channels=6000, height=1, width=301].Based on your description it seems you are also trying to pass a...
ptrblck
Assuming you are one-hot encoding the labels you could also see them as a probability where 1 indicates the active class and 0 the inactive one. Here is a small example: # create class labels y = torch.randint(0, 2, (5,)) print(y) # tensor([0, 1, 0, 0, 1]) # create one-hot encoded tensor labels …
Jacfger
This is an extended discussion ofhttps://github.com/pytorch/pytorch/issues/4031.In that discussion, it is possible to find all process that reads /dev/nvidiaX and weren’t actually doing anything by manually checking the process id. However, when there’re multiple GPU, every processes open all /dev/nvidia (e.g. 0-7) eve...
ptrblck
I would recommend asking this question in the NVIDIA discussion board as it seems to be more driver-related.
OMnia
I’ve created a custom dataset that allows me to read in images from a single folder and add the labels separately:class SingleFolderImage(Dataset): def __init__(self, base_path, label_dict, transform=None): self.base_path = base_path self.image_paths = [str(f) for f in Path(self.base_path).glob('*')] self...
ptrblck
Your DataLoader expects to receive valid tensors to be able to create a batch of all received samples. If some of them contain None objects, the error will be raised as seen here: class MyDataset(Dataset): def __init__(self): self.data = torch.arange(10) def __len__(self): …
amiasato
Hello everyone, I’m having a weird issue on installing thetorchaudiopackage from thepytorchconda channel for Pytrhon 3.10. In my current environment.Using miniconda, I create a new environment with Python 3.10 and try to install the 0.13.1 version oftorchaudio:conda create python=3.10 -n test conda activate test conda ...
ptrblck
You should stick to the install instructions fromhere, which shows the install command as: conda install torchaudio==0.13.1 pytorch-cuda=11.7 -c pytorch -c nvidia which works properly for me: The following packages will be downloaded: ... torchaudio-0.13.1 | py310_cu117 …
nobody
I meet fp16 overflow in forward, so i change some module(not all) to fp32, it works well but slow. I try to modify fp32 to bf16 in order to speedup it, but it cause the fp16 overflow in backward.I don’t quick understand autograd mechnism, why I change the dtype used for forward function will cause the fp16 overflow in ...
ptrblck
The backward pass will match the dtypes used in the forward pass. I.e. if you are using bfloat16 in the forward, the backward will also use bfloat16 and not float16.
sroyyors
Hi,I have a 200 X 200 matrix stored in a tensor and I want to print all the rows and columns. When I use cout or output to file using “<<”, I get outputs in sets of 6 columns. That is all 200 rows of the columns 1-6 are printed, followed by all 200 rows of the columns 7-12 are printed and so on.Is it possible to have a...
ptrblck
You could try to call directlystd::ostream& print(std::ostream& stream, const Tensor & tensor_, int64_t linesize)with the specified linesize argument.
H1dd3n_Squ1d
I am still relatively new to building NNs and I am currently trying to build a CNN - GRU model.My model:class DNN(nn.Module): def __init__(self): super(DNN, self).__init__() self.conv_block = nn.Sequential( nn.Conv2d( in_channels = 1, #Number of input channels; sp...
ptrblck
No, I’m asking about the actual values of the target as these are out of bounds as seen here: criterion = nn.CrossEntropyLoss() batch_size, nb_classes = 16, 10 device = "cuda" output = torch.randn(batch_size, nb_classes, device=device, requires_grad=True) target = torch.randint(0, nb_classes, (bat…
aquorio15
This is my custom dataloader which will take input features of shape (feature_length, 39)import torch torch.cuda.empty_cache() import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.utils.data as Data import scipy.io as sio import numpy as np import os import shutil PYTORCH_NO_CU...
ptrblck
The error is raised in: for (x,y) in zip(pri,post): op1.append(torch.arange(x,y)) in the torch.arange call, which seems to get unexpected inputs. Check x and y and make sure these are valid values
AlphaBetaGamma96
Hi All,Let’s say I have a Tensor of shape[batch_size, num_input]where I have 2 classes for my input data. How could I get the indices for each of the classes?batch_size=100 num_input=4 data = torch.randint(0,2,size=(batch_size,num_input)) #fake data has 0 and 1 as the two classes.Let’s say I had one example that was[...
ptrblck
Yes, that’s possible with a direct comparison: x = torch.tensor([0, 1, 1, 0]) idx0 = x == 0 idx1 = x == 1 x[idx0] # tensor([0, 0]) x[idx1] # tensor([1, 1])
spacemeerkat
I have a PyTorch model with a custom forward pass that involves applyingtorch.fft.irfft2to the real component of a complex input tensor.I’m wondering whether this operation breaks the gradient tracking through the network during training. Below I have a simple example where when I printoutput.grad, I’m consistently get...
ptrblck
You are receiving a warning, which you shouldn’t ignore: 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…
Fei_Liu
Taking this code snippet as an example:model = Model() ddp_model = DDP(model) optimizer = optim.Adam(model.parameters()) # instead of ddp_model.parameters() output = ddp_model(...) # forward call loss_fn(output).backward() # backward optimizer.step() # This runs on `model.parameters()` (instead of `ddp_model.pa...
ptrblck
Generally, I would of course stick to the example usage, as it would be used in other code bases and tested. I don’t have an example which would show a breaking behavior, but I also don’t know how all bells and whistles of DDP would interact with your approach. In particular, I don’t know if the “na…
Pluginer_Gunpowder
import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import torch.nn.functional as F def tg(str): return [ord(s) for s in str] class QAModel(nn.Module): def __init__(self, vocab_size, embedding_dim, hidden_dim): super(QAModel, self).__init__() self.emb...
ptrblck
Check the shapes of the model output and target in your code and make sure they match the expected shapes given in my code snippets and docs. E.g. if the target has an additional dimension, you could squeeze it.
aswamy
var = torch.tensor([float('nan'), 1.0]) torch.where(var == float('nan')) gives wrong output?(tensor([], dtype=torch.int64),)
ptrblck
You could use torch.isnan: torch.where(torch.isnan(var)) # (tensor([0]),)
zhongqiu1245
Hello!Thank you for your amazing job!I used pytorch to handle some image problems, follow this code:if __name__ == "__main__": img_path = './data/SIDD_Val_and_GT_Benchamrk/val/noisy/00017.PNG' # 256, 256, 3 s1 = time.time() img = cv2.imread(img_path, -1) #1 s2 = time.time() img = cv2.cvtColor(img,...
ptrblck
CUDA operations are executed asynchronously, so you would need to synchronize the code via torch.cuda.synchronize() or use GPU timers to properly profile the code. The very first call into any CUDA operation will initialize the CUDA context and will thus be slow. A proper profile thus also needs w…
Humza_Sami
Hello PyTorch community,I’m encountering an issue with GPU memory allocation while training a GPT-2 model on a GPU with 24 GB of VRAM. Despite having a substantial amount of available memory, I’m receiving the following error:OutOfMemoryError: CUDA out of memory. Tried to allocate 64.00 MiB (GPU 0; 23.68 GiB total capa...
ptrblck
In your calculation you are ignoring the intermediate forward activations, which need to be stored in order to compute the gradients. Based on the model architecture these activations could larger than the model parameters.
Tm4
I work with videos (input shape [batch,channels,frames,height,width]) and I designed a video classification model in which I used pretrained ResNet50 that extract features from each frame separately (2D convolution) and then the model stacks the extracted features from all the frames. I trained my model on a video clas...
ptrblck
The file extension won’t matter as you can use any name you want. You can load your state_dict via model.load_state_dict(torch.load(PATH_TO_STATE_DICT)).
AlphaBetaGamma96
Hi All,This is a probably stupid question, but if I’ve installed the latest stable pytorch 2.0 with CUDA 11.8, but I’m running them on GPUs that have CUDA 12.0, will this negatively affect performance at all? I’ve installed via conda for reference, but I’m just wondering how this will affect performance, if at all?Than...
ptrblck
Your locally installed CUDA toolkit won’t be used unless you build PyTorch from source or a custom CUDA extension, since the PyTorch binaries (pip wheels and conda binaries) ship with their own CUDA dependencies.
skandermoalla
Where do we find documentation on whether an operation such ascuda_tensor.item(),cuda_tensor.numel(),cuda_tensor.to("cpu"), is blocking or not? (CUDA semantics — PyTorch 2.0 documentation).Thanks!
ptrblck
You can set torch.cuda.set_sync_debug_mode(mode) to “warn” or “error” and execute the desired line of code.
ElToto
I am unable to make thescaled_dot_product_attentionfunction numerically stable, so that itreturns the same values as a manual implementation of attention.I provide a colab snippet that shows the problem.One time i calculate attention manually and one time I usescaled_dot_product_attention.Even withwith torch.backends.c...
ptrblck
Yes, your error is still in the expected range. Could you explain where the hard limit of 1e-7 comes from?
wi-sh
torch.argmaxtorch.argmax(input, dim, keepdim=False) → LongTensor Parameters: input (Tensor) – the input tensor. dim (int) – the dimension to reduce. If None, the argmax of the flattened input is returned. keepdim (bool) – whether the output tensor has dim retained or not. Ignored if dim=None...
ptrblck
The aliasing should be performed in python_arg_parser.cpphere: // Default arg name translations for compatibility with NumPy. // // Example: // ```python // t = torch.randn(10,10) // torch.sum(a=t, axis=0, keepdim=True) // ``` // // A vector is necessary, because we might need to try multiple valu…
Sa96
I want to load pre-trained weights for a SwinV2 transformer and later load the weights into another Swin with modified architecture as below:import timm import torch n_class =8 img_size= 224 mlp_ratio=2 depths=[2,2,6,2] num_heads=[3, 6, 12, 24] window_size=7 qkv_bias=True drop_rate=0.2 attn_drop_rate=0 drop_path_rate=...
ptrblck
As the error messages explain you are running into a shape mismatch error after manipulating the model architecture and thus also the shape of the trainable parameters. You won’t be able to load the pretrained parameters as long as their shape differs and thus potentially also the number of element…
peony
I would like to ask the difference between batch size in data loader and num_samples in Weighted Random Sampler.I used to assign num_samples asnum_samples=len(sample_weights)and my dataloader batch size is 16. Then after about 50 epochs, I changed my num_samples to num_samples=16 and the training accuracy went down, t...
ptrblck
The num_samples argument in WeightedRandomSampler defines the number of samples drawn in each epoch, while the batch_size in the DataLoader defines the number of samples drawn in each iteration.
HaydenL
It seems that I get errors unless I put my tensors on cpu instead of my cuda device? Should I be putting my tensors on cpu for matplotlib?
ptrblck
matplotib expects numpy arrays as its input, which are only supported on the CPU.
whatisslove7
Hello, I try to implement my own neural machine translition model with Flash Attention (use scaled_dot_product_attention from torch.nn.functional)I have two troubles with it:When I wanna use dtype=torch.float16, I have the following error:RuntimeError: "baddbmm_with_gemm" not implemented for 'Half'When I try to use dev...
ptrblck
Thank you! It seems you are running into known limitation as you are using the SDPA backend manually. E.g. I see: UserWarning: Expected query, key and value to all be of dtype: {Half, BFloat16}. Got Query dtype: float, Key dtype: float, and Value dtype: float instead. Using an autocast context m…
Nerrror
Hey,I have a couple of custom torch.autograd.functions that perform some bigger computations within the .forward and .backward methods. For visualization, it would be very nice to plot some of the intermediate results which are computed in the forward and backward methods. So far, whenever I was doing some calculations...
ptrblck
Your approach looks correct since it seems you need to access the intermediates in the backward call. If you would only want to plot the data or weight gradients you should be able to use backward hooks. However, these hooks wouldn’t allow you to access the intermediates.
aditya_dhaulakhandi
I’m using the deeplab Mobilnet pre-trained model for semantic segmentation where I have 4 classes. The prediction of my model is [batch_size,num_classes, H, W] and to calculate the loss I have made my ground truth of the same dimension having 4 binary masks and using the CrossEntropyLoss function.I want to know which c...
ptrblck
Yes, you are defining the order of the targets and the model doesn’t have any knowledge which class corresponds to which index as it just tries to learn the mapping between the input and the target. If you define that e.g. the background class corresponds to class0 (and thus also the 0-th channel o…
Anirudh_G
I am using the onecyclelr along with mixed precision trainingmodel = SwinNet().to(params['device']) criterion = nn.BCEWithLogitsLoss().to(params['device']) optimizer = torch.optim.AdamW(model.parameters(), lr=params['lr']) scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, ...
ptrblck
The step method of the GradScaler expects an optimizer object, not a scheduler, so remove this line of code.
pylearn
What is the purpose oftorch.neg,torch.square, andtorch.sqrt?Based on the doc, they are just regular operations. That is, the following lines are exactly the same.[torch.neg(x), torch.square(x), torch.sqrt(x)][x.neg(), x.square(), x.sqrt()][-x, x**2, x**-0.5]Which one should I use?
ptrblck
You can use whichever function name better suits you and some methods have aliases as different users have different preferences.
codingGoose
In thetransfer learning tutorialthe function for training the model (train_model) performswith torch.set_grad_enabled(phase == 'train')for the calculation of outputs and loss for every mini-batch. I am wondering if an alternative approach would be to perform_ = torch.set_grad_enabled(phase == "train")before the loop fo...
ptrblck
Yes, enabling or disabling the gradient calculation globally should also work unless you depend on the default behavior (enabled gradient calculation) somewhere else in the code, which I don’t think is the case.
No_Yeah
Hi I am trying to install new graphic card to PC but struggling to do itHere is the graphic card NVIDIA Geforce Xpseems well recognized in the PCin NVIDIA site it says its compute capability is 6.1from official (https://developer.nvidia.com/cuda-gpus)so in the below site, I have downloaded CUDA toolkit 10.0from officia...
ptrblck
That’s not the case and your TitanXP with compute capability 6.1 is still supported in the latest CUDA 12 release. I’m unsure where you have seen this information about the limited support. Install the latest release as already mentioned and it will work.
Surya_Narayanan
image1920×956 127 KBEvery time I run my script, the script trains fine, but during validation, runs OOM after the same number of batches. Why would this be happening in the middle of the loop?
ptrblck
Check if the memory usage increases during the training or validation and if so make sure to avoid storing tensors to e.g. a list which are still attached to a computation graph. PS: it’s always better to post code snippets instead of screenshots.
mahuichao
Hello everyone, recently I am learning the source code of pytorch. From python to the c/c++ implementation, and I saw one quantized layer goes to oneDNN library.I have thought pytorch use caffe2 as it’s c/c++ implementation, so why there is a oneDNN?bz this library is faster? bz this library support onnx better?thanks ...
ptrblck
PyTorch uses different backends to accelerate its workloads such as e.g. cuDNN for NVIDIA GPUs and oneDNN for Intel CPUs. Caffe2 was merged into the PyTorch backend a while ago to share common backend implementations but is deprecated now.
peony
I want to do backward pass when the output is the logit 4. This is the relevant part of my code:if output[:, 4] == True:output[:, 4].backward()The if condition is not working, the rest is ok. Any ideas for me how to write this condition? Thank you in advance
ptrblck
Do you want to check if the logit for class4 has the largest value and thus class4 would be predicted? If so, use torch.argmax to check for the predicted class and use it then as a condition.
medaix
import torch from torch.utils.data import SequentialSampler, BatchSampler, DataLoader def data_loader(dataset, indices_subset, batch_size=5, drop_last=False): pin_memory = torch.cuda.is_available() return DataLoader(dataset, sampler=BatchSampler(SequentialSampler(indices_subset), ...
ptrblck
The error seems to be raised as the channel dimension is missing. What is the shape of each sample when you iterate the dataset (not the DataLoader) as I guess the channel dim might already be missing there. In this case you could simply unsqueeze it in the Dataset.__getitem__ or inside the DataLoa…
AntreasAntoniou
I’ve been trying to use FSDP in my research, and while reading the tutorial atGetting Started with Fully Sharded Data Parallel(FSDP) — PyTorch Tutorials 2.0.1+cu117 documentation. I came across the following linessampler1 = DistributedSampler(dataset1, rank=rank, num_replicas=world_size, shuffle=True) sampler2 = Distri...
ptrblck
The samplers are added to the train/test_kwargs: train_kwargs = {'batch_size': args.batch_size, 'sampler': sampler1} test_kwargs = {'batch_size': args.test_batch_size, 'sampler': sampler2} cuda_kwargs = {'num_workers': 2, 'pin_memory': True, 'shuf…
Sumesh_Sankar
how to freeze a set of weights of a network
ptrblck
Set their .requires_grad attribute to False.
Surya_Narayanan
image960×798 174 KBIt seems that wrapping my classes inDataParallel(model), I see there’s an imbalance between the allocated memory on each GPU. Is there a way to balance them more? It seems this imbalance is making it more likely to cause OOM errors
ptrblck
This is expected as it’s a known drawback of nn.DataParallel which is one of the reasons why we recommend using DistributedDataParallel instead.
hugoo
Hi,Small questionWhich loss is correctly calculated? The train_loss or the avg_loss?This is the code:# Training for epoch in range(epochs): model.train() correct = 0 loss_total = 0 y_true = [] y_pred = [] train_loss = 0.0 for i in train_val_loader: #LOADING THE DATA IN A BATCH data, ta...
ptrblck
Both losses would be correct if the number of samples is divisible by the batch size without a remainder. The train_loss would be correct in all cases as it uses the real number of samples. The issue with avg_loss is that it uses the number of batches to normalize the loss, which could contain a dif…
Snowy
Hello,I am trying to convert some code that involves conditional batch normalization from Tensorflow to Pytorch. In TF, you can call tf.nn.batch_normalization() which accepts the input, mean, variance, scale, and shift (gamma and beta). However, in Pytorch if I call torch.nn.functional.batch_norm, it does not have any ...
ptrblck
The mean and var will be calculated from the input activation and I don’t know why you want to calculate it beforehand. Every other parameter is accepted as an argument where weight and bias correspond to gamma and beta, respectively.
Error0229
I have both python3.6 and python3.9 installed in my machine.For some reason I need to use some package only available in python3.9And I have torch 1.9.0 installed in python3.6 andtorch.cuda.is_available()return trueNow I install same torch version in python3.9 but torch cannot collect cuda this time.details abouttorch....
ptrblck
No, ARM wheels are built for Mac M1/M2, if I’m not mistaken, which do not support CUDA. I don’t think ARM wheels with CUDA support are built at the moment, but funny enough we were just discussing it and I will check what would be needed to enable it.
ellie-misaki
I have a question regarding the installation mechanism of PyTorch and the differences it has compared to TensorFlow. I have noticed that TensorFlow can be easily installed from PyPI using the commandpip install tensorflow, regardless of whether it is the CPU or CUDA version. However, PyTorch seems to have a different a...
ptrblck
PyTorch’s install commands differ for the non-default binaries while the default ones (currently 2.0.1+cu117) are installed via a simple pip install torch command. This command will download all necessary CUDA runtime dependencies and will allow you to directly execute any PyTorch workload on your …
Minxiangliu
I am currently using torchrun for training(this), and when running the script, I encountered an error with exitcode -7. I couldn’t find any relevant information about this error internet, and there is no explanation of the code’s meaning in torch documentation either. The error message is not clear enough to understand...
ptrblck
Signal 7 (SIGBUS) is a bus error describedherewhich usually indicates “that a process is trying to accessmemorythat theCPUcannot physically address”.
Origin
class Mass(nn.Module):definit(self):super().init()self.weights = nn.Parameter(torch.tensor(2e-2))def jacobian(self, q1,q2):f1 = torch.tensor([[self.weightstorch.cos(q1)],[self.weightstorch.sin(q1)]], requires_grad=True)f1.sum().backward()Jv1 = q1.gradreturn Jv1input1 = torch.tensor([[0.5]], requires_grad=True)input2 = ...
ptrblck
You are detaching the input tensors from the computation graph by creating a new tensor: f1 = torch.tensor([[self.weightstorch.cos(q1)],[self.weightstorch.sin(q1)]], requires_grad=True) Replace the torch.tensor creation with e.g. torch.cat or torch.stack and it should work.
Surya_Narayanan
I am facing an issue where my memory usage is exploding, and I can’t explain why. Here is what my code looks likemodes = torch.randn(num_models, 1, 512, 30522).to(device) for epoch in range(num_epochs): model.train() for batch_ix, batch in enumerate(train_dataloader): batch = {k: v.to(device) for k, v...
ptrblck
I don’t think you are missing anything and I can also reproduce the increased memory usage. However, I needed to jump on another issue and didn’t debug the issue yet. So far I would blame the Accuracy method and would use a manual implementation.
Caio_Nogueira
I installedPytorchandcudatoolkitin an Anaconda environment via the instructions provided in the official documentationhere. However the output totorch.cuda.is_available()is still False. However, Pytorch seems to be detecting CUDA correctly as it outputsthe correct version (11.8) when I promptpython -m torch.cuda.versio...
ptrblck
Assuming the correct PyTorch binary was installed the output could indicate a driver issue and you might need to reinstall the NVIDIA driver.
Nanlalalalalal
Hi,I hope to transfor data from cpu to gpu in the current stream, and synchronize the current stream.So I wonder which stream will be synchronized when ‘.cuda()’ is called? The current stream? or it just act as torch.cuda.synchronize()?
ptrblck
The copy kernel should use the current stream as seenherein copy_kernel_cuda.
Hyeonuk_Woo
I have a tensor A with shape of (32,200,50,2), and tensor B with shape of (32,100,100,128).Tensor A is integer tensor. The lower bound of tensor A is 0 and upper bound of tensorA is 99. Therefore tensor A can be used as index tensor for tensor B.From tensor A and tensor B, I want to generate tensor C with shape of (32,...
ptrblck
Direct indexing should work: A = torch.randint(0, 100, (32, 200, 50, 2)) B = torch.randn(32, 100, 100, 128) C=torch.zeros(*A.shape[:-1], B.shape[-1]) for b in range( A.shape[0]): for i in range(A.shape[1]): for j in range(A.shape[2]): C[b, i, j, :]= B[b, A…
shrbrh
Hello. I have a model with the following layers:Sequential( (0): Linear(in_features=256, out_features=256, bias=True) (1): Conv2d(256, 256, kernel_size=(3, 3...
ptrblck
This error is again expected since the output of the linear layer will have the shape [batch_size, *, out_features] while the nn.Conv2d layer expects the channel dimension to be in dim1. You would thus need to permute the output again.
Alex_F
Hello!I am currently trying to track layer activations as part of a project I’m working on.Previously I had no issues with using the register_forward_hooks method for convolutional layers in AlexNet. I am now trying to reuse this code for a transformer layer in ViT_b32 but the activations dict is left empty. Below is a...
ptrblck
Your code is not executable as e.g. model_layers is undefined and it’s also not properly formatted. However, it seems you want to access the NonDynamicallyQuantizableLinear layer, which is only used for error handling in the MultiHeadAttention layer. This code works for me: activation = {} def ge…
pylearn
I defined a custom autograd function. It is very long. I want to convert the long computation into a few helper functions, so that it is more readable, and maybe the gradient/jacobian of the helper functions can be used directly?The original implementationclass customFunc(torch.autograd.Function): @staticmethod ...
ptrblck
I’m unsure which class state you are referring to as you would use the ctx object, wouldn’t you? class customFunc(torch.autograd.Function): @staticmethod def forward(ctx, x, data, option): # save data and option to be used in helper functions ctx.data = data ctx.opt…
Aml_Hassan
Hi there,I tried to build my own loss function, but I’m facing a problem as the loss.grad =None, although the loss.requires_grad = True.here’s my loss function:def recall_prec(y_true, y_pred, gamma=1,beta=1): #y_pred_bin = torch.where(y_pred >= 0.5, torch.ones_like(y_pred), torch.zeros_like(y_pred)) #y_pred.req...
ptrblck
NaN is corresponding to “Not a number” while None is indicating the attribute wasn’t set so you need to be clear what exactly is returned. It also works for me using retain_grad in this small code snippet: lin = nn.Linear(10, 10) x = torch.randn(1, 10) out = lin(x) loss = out.mean() loss.retain_g…
leah
Hi there,I’m new to pytorch. I wanna create an uninitialized tensor as one of parameters in my model. I haven’t gone to the process of training or backpropagation yet. I just simply created a tensor with torch.empty() but got nan values by chance.Here is the code and result. I sometimes got nan values inside the tensor...
ptrblck
You should never use uninitialized memory as it can contain invalid data as already seen in your example. torch.empty is a fast way to initialize memory but requires you to fill it afterwards. E.g. it can be useful to preallocate a tensor which the result will be written to later. You should however…
bornexmachina
I am sitting on an anomaly detection task and I had the following idea.Assume I have 3 classes and each of them could have an anomalous sample. Then, I would train with 4 classes, the last one reserved for the anomaly. But in my training data I would never actually have any data on the class 4.Now during inference, I w...
ptrblck
This might be a good idea but I don’t think the model will automatically classify every “unknown” as class4 assuming it was never trained to output this label. Yes, it would technically work since you don’t need to use all logit outputs.
Viktor_Todosijevic
So I want to evaluate my regression model that has predictions and targets of the shape (batch_size, 236) and I pass this into torchevals r2_scorefrom torcheval.metrics.functional import r2_score score = r2_score(predictions, targets).item()And I get -inf which is definitely not what I was expecting. I was using this s...
ptrblck
-inf would be expected if the target is constant for imperfect predictions. From the sklearn.metrics.r2_scoredocs: In the particular case when y_true is constant, the score is not finite: it is either NaN (perfect predictions) or -Inf (imperfect predictions). To prevent such non-finite numbers t…
peony
I followed this tutorial to implement grad-camhttps://medium.com/@stepanulyanin/grad-cam-for-resnet152-network-784a1d65f3to a subset of a dataset of multiple images. Here is the relevant parts of my training code:Here is the subset:dataset_test = VOC_ocv( voc_folder, year='2007', image_set='test', ...
ptrblck
You would have to pass valid tensors to the model instead of the map.
Fei_Liu
Suppose the original tensors in the dataset is not pinned. Then thepin_memory=Truesetting only (automatically) adds a pin operation for each of the tensors loaded from the dataset on the fly for that specific iteration (after collation, I believe). Isn’t that equivalent to these sequential steps?:pin an unpinned CPU te...
ptrblck
That’s not that case as pinned memory would allow you to trigger a non-blocking data transfer which won’t be possible otherwise. Take a look atthis descriptionI’ve posted in an issue for more details about the internals and how async copies are used. Using pinned host memory won’t initialize a …