user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
mahmoodn
Hi,I don’t know what has happened that my current PyTorch installation (from a year ago) doesn’t use GPU anymore. Apparently, it says the CUDA-11.6 is no longer supported. That should happen if I have updated the installation which as far as I remember, I didn’t do that.$ python3 -c "import torch; print(torch.__version...
ptrblck
Your driver is too old as it shipped with CUDA 11.6 while the PyTorch binary you have installed uses CUDA 12.1 dependencies. Either install the PyTorch binary with CUDA 11.8 dependencies or update your NVIDIA driver to a compatible version with CUDA 12.
DrJellybean
I created a dataset that loads a single data sample at a time on demand (1 sample consists of multiple images), and I have a data loader with a small batch size. When I try to show just the first few batches of my dataset, the loader keeps trying to iterate through my entire dataset instead of pulling out just the few ...
ptrblck
Could you post a minimal and executable code snippet reproducing the issue?
StrausMG
Theofficial docssay thatfunctorchis deprecated andtorch.funcshould be used instead.However,functorchhas recently received new features likefunctorch.dimandfunctorch.einops(as of PyTorch 2.1) that are not a part oftorch.func. So I am a bit confused: what is the current relation betweenfunctorchandtorch.func? If I find f...
ptrblck
I don’t see any recent commits to the main branch of pytorch/functorch as seenhereso would stick to the docs and use torch.func in recent PyTorch versions.
sandy_floren
I’m interested in computing gradients of my model outputs w.r.t. its inputs more efficiently, and I came across thistutorial. Unfortunately, when testing out the codeexactly as it is written in the tutorial, I get anAssertionErrorwhen checking that the gradients computed with function transforms are close to the naive ...
ptrblck
I would disable TF32 if FP32 thresholds are used as describedhere.
abidmeeraj
I am training a Transformer Encoder-Decoder based model for Text summarization. The code works without any errors but uses only 1 GPU when checked with nvidia-smi. However, I want to run it on all the available GPUs (I can access as many as I want). I wrapped my model in Dataparallel.Here’s how I have wrapped the model...
ptrblck
In your provided code snippets you are using the deprecated nn.DataParallel module first, but are then skipping it by accessing the internal .module. Call the model directly and let DataParallel handle the data splits as well as model copies before it calls the forward.
waliston
Hi,I have the following code:class LeNet5(nn.Module): def __init__(self, num_classes, grayscale=False): super(LeNet5, self).__init__() self.grayscale = grayscale self.num_classes = num_classes if self.grayscale: in_channels = 1 else: in_channels = 3 # features layers self.layer = {} self.la...
ptrblck
Use nn.ModuleDict instead of a plain Python dict to properly register the modules.
maximilianmordig
Is it possible to obtain the number of activations in a model for a given input (assuming that the size only depends on the shapes and not the actual values in the input tensor) without initializing the weights/buffers?Here is an example that initializes the weights?I tried doing this with fake mode, but it seems not a...
ptrblck
@albanDjust recently shared how to measure memory usage via TorchDispatchModehere. Applied to your model I see: import torch import torch.nn as nn from torch.utils._pytree import tree_map_only from torch.utils._python_dispatch import TorchDispatchMode from torch._subclasses.fake_tensor import Fak…
waliston
I usedtrain_dataset, val_dataset = torch.utils.data.random_split(dataset=train_val_dataset, lengths=[train_size, val_size])Then I verified:len(train_dataset)and it gives 54000.But when I verified:train_dataset.dataset.data.shapeit gives 60000.Why would it happen?thanks
ptrblck
random_split creates Subsets, which use their internal indices to sample from the original dataset as seenhere. You are accessing the internal and original dataset, which was not manipulated.
shahnawaz
If we split a batch of data into multiple gpus, will it be mathematically equivalent (in terms of learned weights) to using whole batch in single gpu?Following are the assumptions for both experimentsusing same seedno batch normexactly same data in the batchfor the sake of simplicity, let assume we are doing just singl...
ptrblck
Yes, the default loss reduction is computing the mean by summing the gradient and dividing by the batch size. Assuming the batch size is equal on all GPUs, the result will be the same.
saluei
SIFT and SURF are examples of algorithms that OpenCV calls “non-free” modules. These algorithms are patented by their respective creators, and they are free to use in academic and research settings and installed with this command:pip install opencv-contrib-pythonHowever after installation, using SURF algorithm cause th...
ptrblck
Your question seems to be unrelated to PyTorch, so I would recommend to post it in an OpenCV discussion board or their GitHub repository. Based on the error message I guess you might need to rebuild OpenCV with the mentioned option to enable these patented algorithms as the public version doesn’t s…
jiversivers
I am doing some model training on a remote cluster that has a GPU (my local machine does not, which makes debugging slow and tricky). I have tested that my code creates DataLoaders as expected locally, but when I send the job off, I get the following error and traceback/home/jdivers/nsclc/jobs/big_comet_w_atlases/ /hom...
ptrblck
It seems the remote machine might have issues creating the dataset in the first place as seen in these warnings: /home/jdivers/.conda/envs/dl_env/lib/python3.12/site-packages/torch/utils/data/dataset.py:449: UserWarning: Length of split at index 0 is 0. This might result in an empty dataset. warn…
maycaj
Thanks everyone for the help! Basically, my model works, but I cannot run torchinfo. It seems there is an issue with setting the value of nn.Linear( in_features = 2560 …). I have done so manually to fix another error, and ideally, I think it would be better to assign this value dynamically. This results in a matrix mul...
ptrblck
The issue is unrelated to torchinfo as the model execution itself already fails with a shape mismatch: x = torch.randn(1, 128, 520, 696) out = model_0(x) # RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x226200 and 2560x1)
Danny_Kim
Hello,I am experiencing issues applying Precision 16 in PyTorch Lightning.I am optimizing the Generator and Discriminator usingnet_G_Aandnet_D_A, and optimizingpatchNCELossusingnet_F_A.I have confirmed on documents that manual backward is essential when using multi-optimizers, and the code runs without issues with prec...
ptrblck
And indeed@sally2’s answer sounds plausible, but is confusing. E.g. doesn’t make sense since the GradScaler will scale down its scaling factor automatically if overflows in the gradient calculation is detected. Since you are describing an issue where the loss itself is already a NaN, changing t…
MonojitSarkar
My gpu is pretty old. And the latest pytorch gpu has stopped support for it.However I am still willing to use older versions of pytorch if that can make my gpu work?Can someone offer me some advice on it? Or can I use the latest pytorch gpu version along with gpu?Note: My gpu already supports cuda, but latest pytorch g...
ptrblck
This topicis related and based on the response it seems torch==1.2.0 works for your Kepler GPU.
Sourav_Saini
from tqdm import tqdm import torch.nn.functional as F import os best_val_loss = 1e+6 model.train() for epoch in range(num_epochs): loss_train = 0 for data in tqdm(tokenized_dataset, desc=f"training epoch = {epoch}"): # data['input_ids'].shape = (variable, 512) probs = torch.tensor(0.0).to(Dev...
ptrblck
You are also accumulating the computation graphs by adding probs += prob including all intermediate forward activations needed to compute the gradients in the backward pass. Since you are running OOM in this loop you might want to reduce the number of iterations or call backward() inside the loop …
ala_baccar
Hi,I created a detector with nn.ModuleList which contains many DNN networks each has 2 hidden layers and one output layers, and the forward function is as follows: each dnn in the nn.Modulelist takes the output of its previous dnn and gives new prediction which will be given to the next dnn in the nn.ModuleList, but wh...
ptrblck
No, creating a new tensor will detach it. Setting the .requires_grad attribute to True afterwards won’t reattach the tensor, so you would have to use torch.stack or torch.cat to concatenate tensors as seen in my example. EDIT: also numpy arrays are not tracked by Autograd so the torch.from_numpy te…
nlgranger
There is a function in pytorch to break down a tensor into individual variables along a given dim. I can’t remember its name!Something equivalent tox, y, z = a.moveaxis(d, 0).
ptrblck
You might be looking for torch.chunk or torch.split: x = torch.randn(3, 2) a, b, c = x.chunk(chunks=3, dim=-0) print(a, b, c) # tensor([[-1.4919, 2.4972]]) tensor([[ 0.4858, -1.2359]]) tensor([[0.4699, 0.3722]])
fredbutbetter
I am trying to speed up my pytorch training by following the advice from here:Cpu faster than gpu?@mattinjersey, it seems to me that the difference between your code and@ptrblck’s code is that the latter only measures the time for computation on the GPU, it does not account for the data transfer time (data transfer hap...
ptrblck
The __getitem__ method expects to use CPUTensors and fails in the img.numpy() callhere. You could override the __getitem__ with your custom logic and transform the CUDATensors directly (i.e. remove the Image.fromarray(img.numpy()) call.
Dylen
I have built this model with pytorch and I have trained it many times adjusting layers, batch size, learning rate, but for some reason, when I test it with a single batch the outputs, no matter the inputs, are always the same values.Here is my model:class model(nn.Module): def __init__(self): super().__init...
ptrblck
Did you try to remove the last batchnorm layer and to return the raw logits instead?
babak_abad
I wrote a program in python using pytorch. My problem is:mymodelreturnstuple instead of tensor. How can I make/force my model to return tensor?this my code:import torch from torch import nn import numpy as np from torch.optim import Adam x = np.linspace(0, 1, 50).reshape((-1, 1)).astype('float32') y = np.power(x, 2).r...
ptrblck
Remove the comma after model(inp):
Tlotlo_Oepeng
import math class MyIterableDataset(torch.utils.data.IterableDataset): def __init__(self, start, end): super(MyIterableDataset).__init__() assert end > start, "this example code only works with end >= start" self.start = start self.end = end def __iter__(self): worker_in...
ptrblck
No, I doubt the error is raised by Python itself, as it would be unaware of Jax. Your code is missing the import torch statement, and after adding it I do not see any warning on my system but only this output: worker_info is none [tensor([3]), tensor([4]), tensor([5]), tensor([6])] After installi…
aaronzzz
I’m trying to apply transform on images however I keep getting all 1.0 value when image was transformed.Code to replicate the issue:import numpy as npfrom PIL import Imagefrom torchvision import transformstrans = transforms.Compose([transforms.ToTensor()])img=“yourpath/tan_0001_new_MelSpec.jpg”demo = Image.open(img)dem...
ptrblck
I cannot reproduce any issue using your image and see the expected transformed output: trans = transforms.Compose([transforms.ToTensor()]) img = PIL.Image.open("/home/pbialecki/Downloads/test01.jpeg") print(np.unique(img, return_counts=True)) # (array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, …
gonzrubio
I’m experiencing an issue with reproducibility in PyTorch Lightning.Despite settingdeterministic=True,pl.seed_everything(42)andworkers=True, I’m getting different validation losses for the same epoch when changing the number of epochs in the trainer.For example, when I set the number of epochs to 1, I get a validation ...
ptrblck
I don’t know where the epochs are set, but you could check if it changes the number of validation runs etc. If so, you could then check if running a validation loop calls into the PRNG and is thus changing future random numbers.
songsong0425
Hi, I tried to usetorch.unravel_indexto find the original indices from the flattened tensor, but there was an error as below:--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[61], line 1 ----> 1 torch.unravel_i...
ptrblck
It works for me: torch.unravel_index Out[40]: <function torch.functional.unravel_index(indices: torch.Tensor, shape: Union[int, Sequence[int], torch.Size]) -> Tuple[torch.Tensor, ...]> using torch==2.4.0.dev20240506+cu124.
111414
Background:I have a deep network with 20 layers, where both the input and intermediate feature maps have very few channels. Here’s a simplified example:import torch from torch import nn model = nn.Sequential(*[nn.Conv2d(2, 2, 3, padding=1) for _ in range(20)]).cuda() x = torch.rand(16, 2, 64, 64).cuda() while True: ...
ptrblck
Since your input shapes are static you could apply CUDA Graphs to your workflow as explainedheremanually or via torch.compile.
ekrx
I’m encountering an issue where even though I have pin_memory=True set in my DataLoader, the data remains on the CPU during training. My CUDA GPU is available (torch.cuda.is_available() returns True).train = MyDataSet() # Instance of an IterableDataset train_loader = DataLoader(dataset=train, batch_size=batch_size, pre...
ptrblck
Using pin_memory=True will use page-locked host memory and will not move the data behind your back. You still need to move the data to the device.
henrique
Is there any way, plan or timeline to support pytorch-cuda=12 for GH200?FollowingStart Locally | PyTorchwe just get PackagesNotFoundErrorand pytorch-cuda=11 installs cuda 11.8 plus pytorch_cpu from conda_forge, which is not really usableWe can use the NGC containers or install it from source but conda/mamba is still th...
ptrblck
The binaries are already being build in CI runs, e.g.here(scroll down, download the corresponding Python version, and pip install the wheel locally), and the CI job integration allowing a pip install from the nightly index is WIP e.g.here(latest update from 5 mins ago, so we are actively working…
Niharjyoti_Sarangi
I am trying to do a sanity check of my implementation of 2D convolution in PyTorch.I am doing the following :B, C, H, W = 64, 3, 32, 32 x = torch.arange(B*C*H*W).view(B, C, H, W) # construct an image of shape (64,3,32,32) x = torch.tensor(x,dtype=torch.float32) C_out, K = 8, 5 stride = 1 # Get conv2d layer from pytor...
ptrblck
The first comparison looks alright as the relative error is in the expected range (~1e-7) for float32. You can use integer weights to verify it: with torch.no_grad(): conv.weight.copy_(torch.randint(-1, 1, (conv.weight.nelement(),)).view_as(conv.weight)) The unfold approach is wrong andthis p…
Rajveer_B
Is it possible to use PyTorch DataLoader for data loading and TF as the training backend?
ptrblck
This should theoretically be possible unless the multiprocessing usage in the DataLoader conflicts somehow with TF (I would assume it should show a warning).
Jonezia
Hello.I have a scenario where I am running multiple runs where I create a new model, train it for a number of epochs in a loop, and then test the trained model after all these epochs. I am running multiple runs to gather averaged statistics. I would like to deallocate all unnecessary memory between each run to ensure t...
ptrblck
Based on the screenshot it seems the allocations in questions have an approx. size of ~15MB. If so, you could try to clear the cuBLAS workspace via torch._C._cuda_clearCublasWorkspaces() and check if this memory is related to it.
ekrx
I’m using a generator wrapped on a IterableDataset then passed to a DataLoader. The data is being read at demand from the disk because there are thousands of files. So the IterableDataset has some logic to keep track of the open files and the cursors of each file and some funky compurations. If I want to create multipl...
ptrblck
Thedocsshow an example using the worker_info inside the __iter__ to avoid having duplicate data returned from all workers.
SystemLord
I wish to create a model which uses a resnet as part of the architectureIt will eventually have other layers, but I’ve put together a quick prototype:class CombinedModel(torch.nn.Module): def __init__(self): super(CombinedModel, self).__init__() self.resnet = torch.hub.load('pytorch/vision:v0.10.0'...
ptrblck
No, all properly registered submodules will automatically receive the .train(), .eval(), and .to() calls and you can double check it: model = CombinedModel() print(model.resnet.training) # True model.eval() print(model.training) # False print(model.resnet.training) # False
mattiasospetti
I know there are several other questions about this, but obviously none of them helped.I have the following:-NVIDIA 960M (cc=5.0)-pytorch: 2.1.1-Cuda: 11.8However,YOLOv5 2023-12-12 Python-3.9.5 torch-2.1.1+cu118 CUDA:0 (NVIDIA GeForce GTX 960M, 2048MiB) 024-05-22 11:42:51.0616616 [E:onnxruntime:, sequential_executor.c...
ptrblck
The error seems to be raised by ONNXRuntime so you might want to check their GPU architecture support.
Pietro_Willi
Hi,In a binary classification task I am using AveragePrecision from torchmetrics as my loss function:device = torch.device("cuda" if torch.cuda.is_available() else "cpu") transformer.to(device) optimizer = torch.optim.Adam(transformer.parameters(), lr=lr) loss = AveragePrecision(task="binary", average="micro") train_pl...
ptrblck
AveragePrecision is not differentiable as indicatedhereand is also explicitly using a torch.no_grad() contexthereassuming I’ve found the correct line of code.
hzhuang
Hi everyone,I used the fine-tune model from unsloth, and I got this error. It ran ok for the first few loop, but it show up this errors after 2 mins.RuntimeError: CUDA error: device-side assert triggeredCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrec...
ptrblck
The stacktrace is unfortunately still wrong. Did you export this env variable in your terminal? If so, check if any embedding layers are used as their input is often containing indices which are out of the valid range.
vhrn
I’m trying to install torch_sparse in my environment with:pip install torch_sparseAt first the installation could not find cuda.h, but following thistopicI’ve set the CUDA_HOME variable to my environment directory. After that I get the error message below (end of message), complaining about not finding nvcc. I’ve searc...
ptrblck
I would recommend installing a full CUDA toolkit locally, instead of the conda pieces, if you want to build this library from source.
OverLordGoldDragon
The benchmark tutorial (below), and the function’s docs state that the default isnum_threads=1, which doesn’t make much sense on a GPU. Is it only referring to the CPU, and doesbenchmarkuse all GPU threads?torch.get_num_threads()also returns the CPU count.https://pytorch.org/tutorials/recipes/recipes/benchmark.html
ptrblck
From thedocs: torch.get_num_threads() →intReturns the number of threads used for parallelizing CPU operations So yes, the threads setting refers to CPU-only workloads. The benchmark util. won’t specify or change the device and your code is responsible to use the GPU or CPU.
sabiha_afroz
I want to measure the torch operation execution time.device = "cuda:0" add_1 = torch.randn(1, 64, 1, 1).to(device) with_stack=True, with profile(activities=[ProfilerActivity.CUDA, ProfilerActivity.CPU], record_shapes=True, profile_memory=True) as prof: with record_function("operation"): rsqrt = torch.ops.a...
ptrblck
I don’t know how the built in profiler measures the time, but note that warmup iterations would be needed and you should take the mean or median runtime over multiple iterations. I get approx. the same result for a manual profiling, using CUDA events, and torch.utils.benchmark.Timer: nb_iters = 100…
M_T1
I have as minimal python code as I could manage follows:import torch import torch.nn as nn import torch.nn.functional as F class AC(nn.Module): def __init__(self, state_dim, action_dim, action_std_init, device): super(AC, self).__init__() self.device = device # Actor network ...
ptrblck
Check via LD_DEBUG=libs which cuBLAS libs are loaded and make sure they are the same.
divinho
I want to train a model where some modules are in bf16 and others in float32.If the model is in bf16, then it seems to me usingtorch.autocast(enabled=False)for the relevant modules is not enough as the weights will still be in bf16.But I can’t just iterate through the named_modules() and change the dtype because.to()cr...
ptrblck
That’s not the case for nn.Modules as the to() operation will be applied recursively to all registered submodules, parameters, and buffers. model = models.resnet18() for name, module in model.named_modules(): if "bn" in name: module.double() print([(name, p.dtype) for name, p…
Varun1
I am new to model and deep learning training , In my training section i am trying to find the loss of the segmentation of the image , so in here before cross entropy loss calculation i have used interpolate to downsize the image which came out of the model,Here the size of the image from the model which came out is (5,...
ptrblck
As already described, nn.CrossEntropyLoss is used for multi-class classification and segmentation use cases. The output is expected to have the shape [batch_size, nb_classes, *] containing logits while the target is expected to have the shape [batch_size, *] containing class indices in the range [0…
black0340
import torch.nn.functional as F import torch.nn as nn from modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d from torchsummary import summary def conv_bn(inp, oup, stride, BatchNorm): return nn.Sequential( nn.Conv2d(inp, oup, 3, stride, 1, bias=False), BatchNorm(oup), nn.ReLU...
ptrblck
The summary output might not be aware of the reuse of the layer and might thus print it again. You could double check if the expected number of parameters is returned from model.named_parameters().
singleroc
shotage of GPU memoryWhen copy a CPU tensor to GPU,ega = torch.ones(100000).cuda() # 100000 * 4 bytes GPU memory required b = torch.ones(100000).fill_(2) a.data = b.cuda() # 200000 * 4 bytes GPU memory required,but I only have 100000 * 4 bytes GPU memory for the programNew gpu buffer is allocated fora.data = b.cuda(...
ptrblck
Use an inplace copy: a.copy_(b).: a = torch.randn(1024**2 * 5, device="cuda") print(torch.cuda.memory_allocated() / 1024**2) # 20.0 print(torch.cuda.max_memory_allocated() / 1024**2) # 20.0 print(torch.cuda.memory_reserved() / 1024**2) # 20.0 b = torch.randn(1024**2 * 5) a.copy_(b) print(torch.cud…
Soumya_Kundu
def train_model(model, criterion, optimizer, scheduler, num_epochs=25): since = time.time() # Create a temporary directory to save training checkpoints with TemporaryDirectory() as tempdir: best_model_params_path = os.path.join(tempdir, 'best_model_params.pt') torch.save(model.state_dict()...
ptrblck
Your code uses a loop switching between train and val which then resets the running_loss and running_corrects: for phase in ['train', 'val']: ... running_loss = 0.0 running_corrects = 0
SecretAsianMan92
I am trying to utilize the GloVe word embedding for my RNN in DJL however after looking around one of the developers said “DJL uses PyTorch C++ API, it only support TorchScript model. You need trace your model.” I have a feeling when the dev mentions model in this context I think he is talking about a saved nn model af...
ptrblck
Of course and I did not have the impression you are trying to offload your work. The glove embedding is a tensor, not a model. It just contains the data and you would have to create the model separately to be able to trace it.
SecretAsianMan92
Hello, I am new to python and pytorch. I am trying to use the DJL library to train an RNN to classify documents but I am missing a word embedding. I found the GloVe Word Embedding and I have downloaded it to my system as a .zip that contains the .txt file. However, when I direct DJL to load this word embedding it is th...
ptrblck
You could use e.g. pandas to transform the text file to the desired numpy arrays and then convert them to tensors. However, you would still need to know what the target .pt is supposed to contain as e.g. strings are not a valid PyTorch dtype.
woongjoonchoi
I would like to try multi-GPU training, but I wonder if I can get good results without understanding synchronization and concurrency.
ptrblck
It’s hard to tell what’s “essential”, but I would claim you can certainly benefit from Operating System knowledge as well as understanding asynchronous execution in DL.
ymin2570
Through the response inthis post, I’ve identified the issue in my code.The errorRuntimeError: element 0 of variables does not require grad and does not have a grad_fnoccurred because I was recreating a tensor “out” in my custom function, detached from the computational graph.My model and implemented function are struct...
ptrblck
If you are creating a new tensor it does not have a gradient history and previous operations don’t affect this tensor in any way. I don’t think the actual backward computation is the issue in your use case but the lack of a computation graph. Since the tensor is created as a new leaf tensor not v…
hshreeshail
I wanted to look at the source code oftorch.cuda.caching_allocator_alloc(). I followed the link which led me to the function declarationdef _cuda_cudaCachingAllocator_raw_alloc(size: _int, cuda_stream: _int)in the file:python3.9/site-packages/torch/_C/__init__.pyiThis file consists has a comment above the function decl...
ptrblck
You can check the codeon GitHubas not the entire (compiled) code is shipped in the binaries.
Diazepam
Dear developers:So sorry to bother you again and I have trouble in thepytorch/libtorch-cxx11-builde.I havn’t find any document about this docker image and I tried to build my applications on it, so I pull the docker image:docker pull pytorch/libtorch-cxx11-builder:cuda121And I tried to find libtorch:# Enter the contain...
ptrblck
This container is a builder image used in the pytorch/builder repository to build the binaries.
Mohammed_Alruqimi
I have this function to generate a Levy stochastic jump path implemented by numpy.np.random.seed(4) #generate the merton jump def merton_jump_paths_numpy( T, r, sigma, lam, m, v, steps, Npaths): size=(steps,Npaths) dt = T/steps poi_rv = np.multiply(np.random.poisson( lam*dt, size=size), ...
ptrblck
Recreating new tensors will detach them and the original parameters won’t be trained. Use the parameters directly to create the computation graph properly.
npatsakula
Hello everyone!C++ libtorch X86 Darwin binary available for 2.2.3 but not for 2.3.0. Should I create an issue for this?https://download.pytorch.org/libtorch/cpu/libtorch-macos-x86_64-2.3.0.zip
ptrblck
I believe Mac + x86 is deprecated but@malfetcan confirm it.
songsong0425
Greetings. I have a question about the GPU memory usage in the PyTorch.When I ran theGATmodel using pytorch and torch_geometric, I countered the cuda out-of-memory problem every time.Although I use the large knowledge graph (105.43MB) and the 9 types of datasets for the training, validation, and test, I think it is wei...
ptrblck
The memory usage goes down in the third epoch which does not point towards a memory leak.
sagger
Hi, I’ve been tryingthese tutorialsbut always getting zero loss on first (and every) epoch unlike what the tutorial shows. I don’t know what I’m doing wrong. There are a few posts here on zero loss but I was unable to apply them to my case. Minimum test code is:# model: import torch import torch.nn.functional as F cla...
ptrblck
nn.CrossEntropyLoss is used for multi-class classification use cases. Your model is using a single output by default and I’m unsure what len(self.targetColumns) is. If it’s also 1 your model outputs logits for a single class only and thus cannot be wrong.
weight_theta
Currently trying to use pytorch data parallel to up batchsize as shown in code, but get 1) RuntimeError: Caught RuntimeError in replica 1 on device 5. and 2) RuntimeError: cuDNN error: CUDNN_STATUS_EXECUTION_FAILED.**Anyone who has worked with dataparallel before and had similar issues ? **Code:device = torch.device('...
ptrblck
Yes, your explanation is correct. In addition DDP uses a DistributedSampler to make sure each rank only loads and processes its corresponding samples to avoid duplications. This was not needed in the (deprecated) DP approach since only a single process was loading all samples.
Mahdi_Zaferanchi
Normally,optimizer.step()andoptimizer.zero_grad()are called after the backward pass for the entire model is done. This means that all the optimizer state will be in memory at the same time.My question is, if we have a sequential stack of modules, is it possible to have a separate optimizer for each module and callstep(...
ptrblck
You can take a look atthis tutorial.
TeDataPro
Hello,I am training a model on 2 GPUs. In theget_itemof my custom dataloader, pre-processing is done on GPU to increase speed.When I set num_workers to 0, the memory usage of my 2 GPUs are the same : 22k/32k.However, When I set num_workers=2 with the following code:trainloader = DataLoader(train, batch_size=4, shuffle=...
ptrblck
If you want to use a worker per GPU, you could use the worker ID and call torch.cuda.set_device with it to load the sample on the specified device. The common approach is to let the CPU load the samples and to move the batch to the GPU inside the training loop.
602389789
Hello everyone!It is said that bfloat16 is only supported on GPUs with compute capability of at least 8.0, which means nvidia V100 should not support bfloat16.But I have test the code below on a V100 machine and run successfully.a = torch.randn(3,3,dtype=torch.bfloat16,device="cuda") b = torch.randn(3,3,dtype=torch.bfl...
ptrblck
Creating tensors with bfloat16 might be supported on older architectures, but the actual compute kernels would not be.
nbusser
Hi everyoneI want to implement an early stopping mechanic to my DNN. Thus, I have to calculate the validation loss for each epoch.I use@torch.no_grad()during the validation loss calculation to avoid any gradient computation that would alter the training.Here is my training loop:def main(): training_dataset = torch....
ptrblck
Not necessarily, as you could also observe noise creating by additional calls to the pseudorandom number generator. You could check how sensitive your training is to the seed.
Osama_Abu_Hamdan
Greetings,I have this codeimport torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms from torch.cuda.amp import GradScaler, autocast from torch.nn.parallel import DistributedDataParallel from torch.optim.lr_scheduler import StepLR from tor...
ptrblck
bfloat16 computations are supported on Ampere or newer GPU architectures (i.e. compute capability >= 8.0).
cmf1997
hey everyone:I am doing a binding affinity predicting model,firstly, my dataset load the training data,and conduct some precessing In thegetitem() function,where it return a data-dependent var tf_xclass MyDataset(Dataset): def __init__(): ... def __getitem__(self, idx): ... # the tf_x is...
ptrblck
You could try to batch samples according to their length or you could also pad them.@vdwshares some great resourcesherefrom the NLP domain, which deals with similar challenges.
Ashvinee
Hi, all!I’m trying to setup the conda environment from[link]on my machine.Below is my machine specification from nvidia-smi command output.±----------------------------------------------------------------------------+| NVIDIA-SMI 525.147.05 Driver Version: 525.147.05 CUDA Version: 12.0 ||-------------------------------...
ptrblck
Install the current stable or nightly PyTorch binary with CUDA 11.8 or 12.1 and it should work.
songsong0425
Hi, I need your help in debugging the error.As you can see in the title, I countered the RuntimeError during the backward process.By following the suggestions such as.clone(),inplace=Falsein leaky_relu(), it always returned the same error.Please see my code and let me know how should I fix it.class MyModel(torch.nn.Mod...
ptrblck
One of the differences is that your first approach appends the loss to tr_loss and I don’t see where this list is cleared or recreated. Appending the losses will try to backpropagate through all iterations and would cause the issue. Recreate tr_loss after the backward pass or check if you really wan…
jxlin
My model implementation isclass CNNRegressionModel(nn.Module): def __init__(self, image_size): super(CNNRegressionModel, self).__init__() self.image_size = tuple(image_size) self.conv1 = nn.Conv2d(in_channels=self.image_size[0], out_channels=24, kernel_size=3, stride=1, padding=1) self.pool1 = nn.MaxP...
ptrblck
These shapes do not match and I would guess some of your input images have an additional alpha channel, which you could remove e.g. by indexing image via image = image[:3] in the __getitem__.
ala_baccar
Hi,I am training a classification neural network but the loss function is barely changing at each epoch, I checked the gradients of my network params and I found them to be 0 or e-05,e-10… I have tried normalization, decreasing hidden layers, changing activation functions but still no improvements, and I don’t think it...
ptrblck
nn.CrossEntropyLoss expects raw logits so remove the self.softmax usage and pass the output of self.output to the criterion.
Abhishek_Gupta
Lets consider the below codemodel1 = torchvision.models.resnet18(num_classes = 7)I am going to use torchvision Resnet18 model. I am in doubt whther these model contains Batch Normalization layer or not.
ptrblck
You can print the model and would see it contains batchnorm layers: model = torchvision.models.resnet18(num_classes = 7) print(model) ResNet( (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_…
dkz
In the multi-GPU dataloader, if I set drop_last=False and the last batch of data cannot be evenly distributed to each GPU, what will PyTorch do?
ptrblck
The DistributedSampler will drop the tail of the samples as seenhere.
opengpu
cdp_simple_quicksort function from here made the Cuda-context consumed 50MB more than not compiled cdp_simple_quicksort…WHY 50MB so much?github.comNVIDIA/cuda-samples/blob/master/Samples/3_CUDA_Features/cdpSimpleQuicksort/cdpSimpleQuicksort.cu/* Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. * * Redistr...
ptrblck
The issue doesn’t seem to be related to PyTorch, so you might want to ask in the NVIDIA discussion board.
111357
As the title said. If no, how to export a model that can be runed on GPU.import torch from torch.export import export class ToyModule(torch.nn.Module): def __init__(self): super().__init__() self.fc1 = torch.nn.Linear(10, 10) self.fc2 = torch.nn.Linear(10, 10) self.fc3 = torch.nn.L...
ptrblck
Thanks for updating the code! Based on the new code it should work fine exporting the model on the CPU and loading and running it on the GPU: torch.export.save(exported_program, "test.pt") m = torch.export.load("test.pt") print(m) m.module()(*[e.cuda() for e in example_args]) # RuntimeError: Expe…
vindy
Hi all,Use case:I am training a model with image data for a semantic segmentation task. I have a requirement to batch data using ratios of combinations of classes. For example: my batch should have 75% of patches containing classes 0 1 and 2, and 25% of classes containing 0 and 1. Hence, I pre-batched my data.I want to...
ptrblck
The DistributedSampler commonly used in DDP will duplicate samples to make them evenly divisible as seenhere. I don’t know if this would fit your requirement, but might be a valid approach instead of dropping samples.
_Stelk
The task at work is to make a CNN model to do some classification task on images. Also, I should be able to view the feature maps after making a classification on an image i.e the images obtained after applying convolution or pooling operations. Below is how I defined my CNN class:class ConvNet(nn.Module): def __init...
ptrblck
self.architecture is a plain Python dict and will thus not properly register the modules. Use nn.ModuleDict and it should work.
Praskand
It gives ValueError: The provided filenamehttps://github.com/k.../blob/master/yolovXn.ptdoes not exist.
ptrblck
Your URL is invalid as is contains the placeholder ... in it.
GoldenalCheese
I want to index a tensorxsimultaneously using two axes, with shifted indices. Here is a for loop I wrote to satisfy my purpose. How can I efficiently implement it in pytorch, removing the for loop?a,b, s1,c,t,d = 2,4,5,10,6,7 x = torch.rand(a,b,s1,c,t,d) x_new = torch.zeros(a,b,s1,c,t,d) for i in range(c): index = ...
ptrblck
The same approach fromyour previous questionusing torch.compile can also be used here: ------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ …
btjanaka
I am running transformers from the HuggingFace transformers library and encountering issues with large GPU cache size. When running on a 3090, my max memory usage (torch.cuda.max_memory_allocated()) is 7GB, while the maximum allocated memory allocated (torch.cuda.max_memory_reserved()) is 12GB. This seems alright. Howe...
ptrblck
You can use torch.cuda.set_per_process_memory_fraction(fraction, device=None) to set the max allowed memory. The root cause for the increased cache usage is unclear since you are unable to share the model or any information.
MTMD
When developing custom CUDA kernels, it is common to get a pointer to the GPU memory and pass it to the kernel as shown below.kernel<<<num_block, num_threads>>>(tensor.contiguous().data_ptr<float>())Wheretensoris a tensor that is passed from Python side. The problem is, GPU kernels are asynchronous. So, how do we know ...
ptrblck
The CUDACachingAllocator checks if the block requested to be freed (or rather moved to the cache) is in use and if so will record an event as seenhere.
Tanmay_Pani
Hi, I recently started using the C++ API, and need to standardize my tabular data similar to the python “sklearn.preprocessing.StandardScaler”. I did figure out the “map” utility that uses “torch::data::transforms” object, and atleast on paper, the torch::data::transforms::Normalize<> seems to be what I want. But apply...
ptrblck
I believe your guess is correct and the expected use case were images. Note that this transformation was added ~6 years ago inthis PRand I don’t know if the C++ API is maintained anymore, so you might want to implement a custom transformation without the unsqeeze calls.
HantigC
I have the following piece of code.device = torch.device("cuda:0") amt = 316377 depth, width, height = 1379, 280, 85 colors = torch.randn(amt, 3, dtype=torch.float32, device=device) mask = torch.rand((amt,), device=device) < 0.95 above_amt = mask.sum() x_idx = torch.randint(0, depth, (above_amt,), dtype=torch.long,...
ptrblck
The issue is caused by creating duplicates as seen here: import torch device = "cpu" amt = 316377 depth, width, height = 1379, 280, 85 colors = torch.randn(amt, 3, dtype=torch.float32, device=device) mask = torch.rand((amt,), device=device) < 0.95 above_amt = mask.sum() x_idx = torch.randint(0…
Rhett-Ying
I am wondering how torch lib is built, especially which OS is used for build package for linux platform to make it most widely compatible with users’ linux distribution.This is also about what the minimum versions ofglibc,gccand other basic dependencies are.Build upon docker image such asubi8,ubuntu 20.04to support var...
ptrblck
The current CPU and CUDA binaries should use CentOS7 as the base as seenhere.
grid_world
For CIFAR-10 data augmentations using torchvision transforms. torchvision version: ‘0.15.2+cu117’ and torch version: 2.0.1+cu117strength = 0.2 color_jitter = transforms.ColorJitter( brightness = 0.8 * strength, contrast = 0.8 * strength, saturation = 0.8 * strength, hue = 0.2 * strength ) rand_color_jitter = t...
ptrblck
No, according to thedocs: img (PIL Image or Tensor) – Image to be cropped and resized. You can thus add: image = PIL.Image.fromarray(image) to your __getitem__ before passing the image to the transformations or you could transform it to a tensor in CHW layout and remove the ToTensor transfor…
msv
If I define my net like this:class Net(): def __init__ self.block = nn.Sequential(...) def forward x0 = self.block(inputs[0]) x1 = self.block(inputs[1])Will the learnables of self.block be shared among input 0 and 1, or will each call to self.block in the forward function automatically upscale ...
ptrblck
self.block is reused in your approach and so will be its trainable parameters. PyTorch’s Autograd creates a computation graph capturing both operations, won’t create new parameters, but will just reuse them.
CDhere
Hi! I’m trying out TF32 and mixed precision training. Can they be used at the same time? Namely, is setting the flags like this ok when I enable mixed precision training, or should I actually set them back toFalse?torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = TrueThanks!
ptrblck
You can keep TF32 enabled and would use it for convs and matmuls outside of the amp.autocast region.
Mamora
I have a network like this:c, h, w = input_dimself.online = nn.Sequential(nn.Conv2d(in_channels=c, out_channels=32, kernel_size=8, stride=4), nn.ReLU(), nn.Conv2d(in_channels=32, out_channels=64, kernel_size=4, stride=2), nn.ReLU(), nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1), nn.ReLU(), nn.Flat...
ptrblck
Based on the error message the first nn.Conv2d layer raises the error since c=315 is set. Since you are using 3 input channels, set in_channels=3 and it should work. If you are still running into this issue, your images might be in channels-last memory format. In this case you would need to permute …
Mihai_M
Hi all,I’m slightly struggling with implementing a hook function within my SNN. I’m looking to call on a function at every epoch which modifies a layer’s voltages (in this example),layer[3]given another layer’s voltages and weights,layer[0]The custom function unfolds the tensors in an array and does some computation th...
ptrblck
I don’t fully understand why forward hooks are used, but I assume you are using the forward activation for the actual manipulation? It also seems you want to directly manipulate the weight attribute of a layer based on this computation? Could you give a small example of the actual manipulation and…
xgbj
Hello everyone, we recently encountered an issue where our distributed storage system became very slow during a training process. As a result, the training speed decreased to one-fifth of its usual speed. From the monitoring data, it is evident that the main cause of this slowdown is the increased time taken for data l...
ptrblck
NCCL communications use HW resources and are thus showing a high GPU utilization even if the current process is only waiting.
tungyen
Hello, I am now working on implementing the PointNet Model for 3D point cloud Segmentation. However, I encountered some problems in loss function. Here is my data shape for each batch:image735×80 6.17 KBwhere 4 is batch size, and 1500 is the point number for each point cloud, and 4 in the ouput is class number.However,...
ptrblck
Your output has an invalid shape and should be [batch_size, nb_classes, additional_dim], so [4, 4, 1500] in your case. You can permute the tensor to swap dim1 and dim2.
Ali_H_Ahmad
Hi…I am facing the following error:RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!After I checked everything, it turns out that the problem is here:relative_position_bias.relative_attention_bias.weight: cpuEverything else is correctly on the GPU.I tried hard ...
ptrblck
self.relative_attention_bias = nn.Embedding(self.num_buckets, self.num_heads) seems to be properly registered, but I don’t fully understand the forward pass in this __init__ method: self.biases = self.relative_position_bias(config.max_token_len, config.max_token_len).to(self.embed_layer.token_embed…
ViktorPavlovA
Hello.I have jetson xavier nx. I have already install version of torch-2.1.0a0+41361538.nv23.06-cp38-cp38-linux_aarch64.whl with using thisguide. But i don’t found correct version of torchvision. it must be 0.15.1 but what’s the name of the branch ? I guess i try wrong branch…Thank you!
ptrblck
This older PyTorch release shipped withthis torchvision tagand your link shows how to build it from source.
XZJIsme
Can PyTorch move a tensor along with its computational graph from GPU to CPU, and then move it back to GPU for backpropagation? For instance,ais originally on GPU 0, and after computing withb, we getc. Then, I obtainc.sum()and movecto the CPU to free up memory. Next, I movedfrom the CPU to GPU 0, and continue computing...
ptrblck
The to() operation is differentiable, but won’t move intermediates to the target device. To save memory via CPU offloading you might want to usethese hooks.
thomas-woehrle
Hi,my question is whether it is possible to load parameters into a model, such that they are still in the computation graph of the result of the forward function of said model.Let’s say for exampleimport torch import torch.nn as nn from torch.autograd import grad class SimpleNet(nn.Module): def __init__(self): s...
ptrblck
You might want to trytorch.func.functional_call, which allows you to: Performs a functional call on the module by replacing the module parameters and buffers with the provided ones.
pyt
Hi, I have a computer with ubuntu 20.04, CUDA 11.4 and NVIDIA drivers 470.I don’t have the permissions to update it. Which version of Pytorch could I install without having to update the drivers and CUDA?According to this posthttps://discuss.pytorch.org/t/which-pytorch-version-2-0-1-support-cuda-11-4/190446I can’t inst...
ptrblck
Yes, since the PyTorch binaries ship with their own CUDA 11.8 runtime and would use the NVIDIA driver from your system which should be compatible with 11.8.
Bom_Bahadur_thapa
def forward(self, enc_input, enc_input_ext, dec_input, target=None, teacher_forcing_ratio=0.5): enc_output, enc_hidden = self.encoder(enc_input) dec_hidden = enc_hidden batch_size, seq_len = dec_input.size() outputs = torch.zeros(batch_size, seq_len, self.vocab_size).to( enc...
ptrblck
This indexing operation fails: attn_dist_extended[b, vocab_idx] += attention_weighted[b, idx] so you should check the shapes of the used tensors as well as the min/max values of the index tensors. Based on the stacktrace this operation should be called in final_dist = self.get_final_distribution(…
Fabrice_Auzanneau
HelloI’m trying to load a model that I saved using:torch.save(model, filename)The model was saved on a Nvidia A100 GPU, using Python 3.8.10Then I transferred thepthfile to my PC, where I want to open it. On this PC I have Python 3.10.9. I run the following command:model = torch.load(file).to('cpu')and I get this error ...
ptrblck
Saving the entire model is not recommended since you would have to restore the same code structure on the target system and can run into these issues. Save the state_dict instead and recreate the model object before loading its state_dict. This won’t avoid having to port the code but would relax th…
francescogrillea
I’m trying to run torch on top of GPUs of a server which i’m root. Drivers seems installed correctly:> nvcc --version < nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2023 NVIDIA Corporation Built on Wed_Nov_22_11:03:34_PST_2023 Cuda compilation tools, release 12.3, V12.3.107 Build cuda_12.3.r12.3/compiler.33...
ptrblck
PyTorch binaries do not support ARM + CUDA yet, but we are working on itIn the meantime, please use the NGC containers.
aolValentin
Hi,I am new to PyTorch and Deep Learning in general. I created this class and I try to run something.class StudentModel(nn.Module): def __init__(self, num_classes=k): super(StudentModel, self).__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1) self.relu1 = nn.ReLU()...
ptrblck
Correct the in_features of self.fc1 and it should work: self.fc1 = nn.Linear(16384 , 128)
learner13
Hi all,I’ve been working on a basic model for some time now - it’s a multi-classification problem with images (10). Details are below:Target = One Hot Encoding || 10 possible outcomes > numbers 0-9Images are 28x28. They have been normalised with /255 to give a float32 between 0-1.Training Data is shape [60000, 28, 28] ...
ptrblck
For a multi-class classification use case I would recommend using nn.CrossEntropyLoss instead of nn.MSELoss. You would also remove the nn.Softmax at the end of your model as raw logits are expected.
chandler-bing
Hi, everyone, I encountered a very simple but weird BUG!import torch m = torch.load(f'./gate_linear.pt',map_location='cpu') print(m) #Linear(in_features=1024, out_features=2816, bias=False) x1 = torch.load(f'./x1.pt',map_location='cpu') x2 = torch.load(f'./x2.pt',map_location='cpu') print(x1.size(),x2.size()) #torch....
ptrblck
Different algorithms can be used for different input and weight shapes and bitwise-identical outputs are not guaranteed. Neither of these results is more accurate and should show a similar error to a wider dtype.
Elchuko
I need to classify some behavioral data that comes from a CSV file. I’m using pandas to clean the data and Conv1d for classifying. The pandas dataframe has shape of (14029, 123).The issue appears when I’m trying to feed the data into the model. As far as I understand, I need the shape of the data to be (batch_size, 1, ...
ptrblck
unsqueeze the missing channel dimension before feeding the data to the model.
pytorchuser101
I want to use hooks to extract the output of every convolutional layer in a CNN. What would be a more efficient way than registering every convolutional layer manually ?I was thinking of running a for loop with all conv layer names, but even that may require some manual hardcoding the names.
ptrblck
You could iterate all modules and check for their type via e.g.: model = models.resnet18() for name, module in model.named_modules(): if isinstance(module, nn.Conv2d): print(f"registering hook for {name}") module.register_forward_hook(lambda m, input, output: print(output.shape…
dangmanhtruong1995
Hi everyone, I have this following model created by using nn.Sequential, however when I used torchsummary, I noticed that right after the pooling layer, the number of parameters is very high compared to other layers. I don’t know why it is that way. Here is the output:Sequential( (0): Conv2d(3, 64, kernel_size=(3, 3)...
ptrblck
This is expected as the next conv layer has 64*64*7*7=200704 (+64 bias) trainable weights.
Jonson
image872×116 4.55 KBThese snippets are intorch.utils.cpp_extension.py::_get_cuda_arch_flags. And the latest supported arch is sm_86.
ptrblck
PyTorch 1.13 released with CUDA 11.6 and 11.7, which did not support Hopper architectures. Update to any recent stable or nightly binary and it’ll work.