Dataset Viewer
Auto-converted to Parquet Duplicate
user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
timtravs
Hi,I had several working CNN models earlier this year, but these have now stopped working on the GPU of my machine recently and instead give a RuntimeError. PyTorch is installed on this machine via conda-forge. Although PyTorch was updated on this machine to v2.7.1 a few weeks ago, I downgraded back to v2.6.0 but the m...
ptrblck
You could try to use an older PyTorch build using an older cuDNN version or alternatively disable cuDNN for your workload on the Pascal GPU using torch.backends.cudnn.enabled = False.
ptrch_c_m
I have implemented theforward()which does the forward pass of the model.I have to define also another function,some_function(), in the model, that does some other processing first, and then does a forward pass of the model. I have seen that forward is almost never called manually, becausemodel.__call__()has some extra ...
ptrblck
Calling forward explicitly will skip the hook registration and might cause unexpected behavior. I would thus recommend sticking to the __call__ op making sure all hooks are properly fired (if any are used).
anthonycodes
I’m not necessarily looking to solve this issue as I’m mostly just learning but while training a small model of mine I noticed that loss will start pretty low, then increase, and then drop at the start of the next epoch.I’ve done some googling but was curious if anyone else has encountered this and if so what the commo...
ptrblck
Are you shuffling your data properly or are you using the same order in every epoch?
jhonsip
Hey everyone,I want to install just the basic Nvidia drivers without all the extra stuff. I found a tool calledNVIDIA clean install—is it safe and reliable?Also, are there any better or easier tools out there?Main goal is keeping things clean and making sureOBS with NVENC still works.Thanks!
ptrblck
I’m not familiar with this tool and don’t know who built it. If you want to install the NVIDIA drivers only, I’m wondering why theNVIDIA Driver install pagewould not work?
songh11
Is there any way to make the results consistent across different platforms? When I run the same model on 4090 and L20 with the same input, the results are different. Is there a way to solve this problem?
ptrblck
No, there is no guarantee to create bitwise identical results on different setups and platforms.
ayoubft
torchvision.transforms.v2.Composewith paired transforms likeRandomHorizontalFlipandRandomVerticalFlipapplies only to the image, not to the mask.Expected behavior: when using paired transforms and passing a tuple(image, mask), both should be flipped identically.Observed: only the image is flipped; the mask is unchanged....
ptrblck
This is expected behavior in the transforms.v2 API according to thedocs: If there is noImageorVideoinstance, only the first puretorch.Tensorwill be transformed as image or video, while all others will be passed-through. Here “first” means “first in a depth-wise traversal”. You could use t…
00krishna
I updated my Pytorch installation last night, but now I am getting a message:UserWarning:Found GPU1 NVIDIA GeForce GTX 1080 which is of cuda capability 6.1.PyTorch no longer supports this GPU because it is too old.The minimum cuda capability supported by this library is 7.5.My current Cuda version is 12.9. I am running...
ptrblck
Install either any older binaries (<=2.7.1) or our current binaries built with CUDA 12.6.
Eyzzle
Hello everyone, hope you are doing great.I have a question I imagine to be fairly simple, yet I could not find a direct answer. I am doing forecasting of a single value y, using multiple features X.Before passing data to my model, I normalize all my features, including the target valuey(that we shall cally,scaled).My m...
ptrblck
One of the main differences in computing the loss using the (un)scaled data could be the gradient magnitude, which could be handled by reducing/increasing the learning rate. Depending on your use case you might want to compute the “unscaled loss” by unscaling the model output and target to compute …
vasigorc
Hello! I have a 1 year old laptop from System 76 that shipped with POP!_OS 22.04 which is a fork of the same Ubuntu version:cat /etc/os-release NAME="Pop!_OS" VERSION="22.04 LTS" ID=pop ID_LIKE="ubuntu debian" PRETTY_NAME="Pop!_OS 22.04 LTS" VERSION_ID="22.04" HOME_URL="https://pop.system76.com" SUPPORT_URL="https://su...
ptrblck
Your NVIDIA driver is not properly installed and you might need to reinstall it. We have also seen other topics here where users ignored the request to reboot the system after upgrading the driver, so you might also want to make sure your laptop was rebooted already.
sad_robot
I noticed that the default torch.optim.Adam() optimizer has a weight_decay=0 hyper parameter, yet torch.optim.AdamW is a separate implementation (why not replace the original?). Additionally torch.optim.RAdam() optimizer has a weight_decay=0 and a decoupled_weight_decay=False hyper parameter.Both of these design choice...
ptrblck
A lot of defaults are kept for backward compatibility reasons and you would sometimes see that higher-level API libs are changing these to the current SOTA usage. I haven’t checked the details here but this could also be the case for potentially sub-optimal arguments used in these optimizers.
ening
codesmodel = MllamaForConditionalGeneration.from_pretrained(MODEL_NAME,attn_implementation=“sdpa”,device_map=“cpu”,torch_dtype=torch.float32,)optim = AdamW(model.parameters(), lr=1e-5)model.to(“cuda:0”)QuestionsIn the codes above, I createmllamamodel on cpu and use its parameters to create optimizer, then move model to...
ptrblck
Parameters are moved inplace so creating the optimizer before moving the model should be fine. This simple code snippet also shows it: model = torch.nn.Linear(10, 10) optimizer = torch.optim.Adam(model.parameters()) print([p.device for p in optimizer.param_groups[0]['params']]) # [device(type='cpu…
Wznnnnn
Hello exeryone!When usingdeepspeedtraining job, I get this error:[rank0]: torch.distributed.DistBackendError: NCCL error in: /pytorch/torch/csrc/distributed/c10d/ProcessGroupNCCL.cpp:3368, unhandled cuda error (run with NCCL_DEBUG=INFO for details), NCCL version 2.25.1 [rank0]: ncclUnhandledCudaError: Call to CUDA func...
ptrblck
Could you test the 2.8.0RC binaries or any nightly (with CUDA 12.9) as this should have been fixed already in NCCL 2.27.x?
emerth
Installing Pytorch on fresh Debian 12.11.After installing Debian I made and sourced a python virtual environment that I named pytorch2.7_cuda12.8. Having failed the install I did clean the pip caches before running the attempt posted below.I am getting an error that appears to stem from this line in the below quoted ou...
ptrblck
Try to update pip as the same error messages are related to old pip releases.
Eldalier
Hello,I’m trying to implement torch.compile in my program, but I’m encountering reproducibility issues with this script using PyTorch 2.7.1:import os from functools import partial import torch from torch.nn import MultiheadAttention from torch.testing import assert_close os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096...
ptrblck
I can reproduce this larger error, but get the expected numerical mismatches after disabling dropout. I don’t know if random operations are guaranteed to return the same outputs as I would guess the mask sampling differs.
Shmu26
Issue:PyTorch not supporting CUDA compute capability 12.0 (sm_120), required for the NVIDIA GeForce RTX 5060.Goal:I want to use my RTX 5060 GPU with PyTorch in a local development setup (translation model fine-tuning and semantic search). I’m willing to test nightlies or custom builds.System Info:GPU: NVIDIA GeForce RT...
ptrblck
You are using an old PyTorch binary (version 2.5.1) with CUDA 12.1 instead of the latest stable release (version 2.7.1) with CUDA 12.8 as required. This is true since PyTorch 2.5.1 as well as CUDA 12.1 were released before the Blackwell launch and thus do not support future Hardware.
catalyst
Hi,I’m trying to write a policy net for REINFORCE, but I’m running into abackward()variable versioning issue. A (relatively) small reproducible snippet is:import torch.nn.functional as F import numpy as np import random import torch K = 4 G = K**2 // 4 + 1 MAX_EPISODE_LEN = 2 NUM_EPISODES = 1 class PolicyNetA(torch....
ptrblck
You are trying to call backward on a created computation graph (coming from policy_proba_dists) with already updated trainable parameters.This postdescribes the issue trying to use stale forward activations in more details. In your case, the weight of the conv layer was already updated and thus c…
TerrenceZhangX
Hi, I’m testing torch 2.7.1 matmul performance with cuda 12.6 on H100 GPU. Surprisingly the matmul is calling nvjet kernel instead of sm90_xmma kernel with torch 2.6.0.Does anyone know why this behaviour is happening?Thanks a lot for the kind help!
ptrblck
This is expected as cuBLAS selects the fastest kernel for the given workload via its heuristics.
dkleine
I recently ran intothis discussionreferencing the difference in the assignment ofmy_model.to(device)andmy_tensor.to(device). While currently the model will be movedin-placeto the device, tensors must be assigned to the same variable to be moved to the device (my_tensor = my_tensor.to(device)).I have searched this forum...
ptrblck
To resolve the inconsistency, you could make sure to always assign the return value for to() calls as: model = model.to(device) tensor = tensor.to(device) will also work. I see the inplace definition w.r.t. the actual data and memory. I.e. I expect an inplace operation to process the already al…
mw-v
Hi everyone,I’m currently maintaining two separate training loops for my PyTorch model: one standard (float32) and one using automatic mixed precision (AMP) withtorch.amp.To simplify my codebase, I would like to merge them into a single training loop using theenabledflag for bothtorch.amp.GradScalerandtorch.autocast.He...
ptrblck
Yes, this should be the case if you properly pass the enabled argument to GradScaler and autocast. E.g.scale()will just return the passed outputs and will be a no-op,step()will just call optimizer.step() is it’s not enabled, etc.
sabi-ant
Hi all,I’m trying to buildPyTorch v2.3.1 from sourceon aWSL2 Ubuntu 22.04 environmentwith the following setup:Any way to build pytorch 2.3.1 with cuda 12.9?Cause it seems latest pytorch incompatible with some modules(TI QAT wrapper module) I need to use in my project, I need pytorch 2.3.1.System Configuration:OS:WSL2 (...
ptrblck
No, I would not recommend trying to build old PyTorch releases with newer CUDA toolkits as needed changes might not have landed as can be seen in your error message.
5had3z
I’m stalling on any kind of barrier between two GPUs in a minimal example with the nvidia pytorch containernvcr.io/nvidia/pytorch:25.03-py3and there’s nothing really jumping out at me in the NCCL logs to a layman like me. I saw anolder postthat they had problems with the driver, is this probably the case for me? I init...
ptrblck
Disable IOMMU as describedhere.
evilroach
I’m using Lightning to train my model.Lightning has a nice feature i.e. every time it runs, it creates a sub-dir in./lightning_logs, and nams them likeversion_0,version_1,version_2…I want to utilize these strings to identify my prediction result sets when saving them into DB, but I don’t know How to get these version s...
ptrblck
This might be a great question for theLightning forum. Based onthis questionit seems you could change or get the version from the logger.
evilroach
I’m coding a multi-task classification model, with my customized loss func.While the number of classes of each task are same, each label variables havedifferentclass weights buffers. So I instanciated loss_func objs for every label var respectively, and let them to hold their own weights buffer, by means ofregister_buf...
ptrblck
I’m not sure if I understand the question correctly, but register_buffer will register the buffer to the object itself in the same way trainable parameters are registered. E.g. while every nn.Linear module defines trainable parameter via self.weight they will not share these weights as the individu…
Guillaume_Jeanneret
Hi all,I have a conceptual question regarding how to best use DistributedDataParallel (DDP) in a setup involving two models.Suppose I have twonn.Moduleinstances:model1andmodel2. I want to train all parameters inmodel2, but only a subset of parameters inmodel1. The remaining parameters inmodel1should remain frozen. Plea...
ptrblck
I would stick to the linked post explaining that frozen parameters will be skipped in DDP’s communication. You would thus have to set the .requires_grad attributes of all frozen parameters to False first before creating the DDP instance.
David-G
I’ve been struggling to solve computer hard shutdown issue. When I run any application that calls PyTorch and Cuda, as the main LLM is about to load into vram, my computer just shuts off. It is as if is some overload protection is triggered and it just hard crashes, but motherboard has power i.e. network adapter still ...
ptrblck
This sounds like a system issue and often an underspec’s PSU can cause sudden reboots.
basavyr
I want to have a method that will take the weight of aconv2dlayer, typically in the shapeC_out, C_in, H, W, whereC_outrepresents the output channels,C_inrepresents the input channels, whileHandWare the dimensions of filters (kernels).As an example, consider a weight:w = torch.randint(0, 5, (4, 1, 3, 3)) tensor([[[[3, 3...
ptrblck
If I understand your use case correctly you want to permute the rows of all kernels randomly without mixing them between kernels. I think your code is fine as it’s clearly showing your implementation and I don’t know if this is currently a bottleneck in your code. However, you could try to use tor…
torch_newbie
My linter is always complaining aboutimport torch.nn as nnand tells me to change it tofrom torch import nn. Is there a difference between the 2?
ptrblck
Purist might see a difference (and please post these). I would use whichever approach you like.
Jiawen_Niu
Here is a simplified program that doesn’t work properly and throws the following error:#include <torch/torch.h> #include <torch/csrc/distributed/c10d/ProcessGroupNCCL.hpp> #include <torch/csrc/distributed/c10d/FileStore.hpp> #include <c10/cuda/CUDAStream.h> // For CUDAStreamGuard and getStreamFromPool #include <c10/cud...
ptrblck
Did you try to initialize the allocator via c10::cuda::CUDACachingAllocator::init?
iliasslasri
Hello everyone,I have one question. Does multiple similar forwards with different inputs/outputs trigger multiple builds of the computational graph knowing that the graph is exactly the same, if yes, how much this affect the memory usage?Thanks!
ptrblck
Yes, different forward passes will create different computation graphs, which will store the different intermediate forward activations (which are needed for the gradient computation in the backward pass). The increase in device memory depends on the model architecture and the size of forward activa…
yuwei_geng
Hi,I have some problems of the neural nework models.There is a trained CNN models and i need to repeated use this model. Here is the code.self.CNN.eval()with torch.no_grad():for i in range(self.TestSteps):aa = time.time()initial = self.CNN(initial)bb = time.time()print(bb - aa)The computational cost for each loop is 0....
ptrblck
Yes, since your initial profiling is wrong and is not measuring the GPU kernel execution time. The kernels were never as fast as your profile showed since you were not waiting for the GPU to complete its execution. Instead you were measuring the Python, C++, backend, etc. overhead to launch the k…
vfdff
I try to create a simpleMlp modelwithout train, and then usetorch.saveto save the model parameters (they are random values which can be checked by print(param_tensor,‘\t’,model.state_dict()[param_tensor])), so in fact, I only save a lots of random values, and it is not a tuned parameters?PS: I also try to open the save...
ptrblck
Yes, saving the state_dict directly after initializing the model will save it’s initial random values, which were not trained yet.
andy_sherlock
I have a Weriod OOM problem when I use 2 gpu like CUDA_VISIBLE_DEVICES=4,5.But, when I use CUDA_VISIBLE_DEVICES =4,5,6,7, it seems to work well. And I check the memory usage like this below, which showed that the total usage of gpu 4,5,6,7 is less than 40G*2=80G.Does this mean that I can use 2 gpu like CUDA_VISIBLE_D...
ptrblck
It’s unclear what your use case is and what’s causing the OOM. PyTorch’s DDP will create a balanced memory usage assuming you are using the same local batch size while the legacy DP approach uses an imbalanced memory usage and is thus not recommended (besides also increasing the communication need)…
mahmoodn
HiThe following set of commands, according to the official page, to install PyTorch 2.6 in a virtual environment fail.[m@login02 llama2-70b]$ python3 -m venv pt26-cu124 [m@login02 llama2-70b]$ source ./pt26-cu124/bin/activate (pt26-cu124) [m@login02 llama2-70b]$ export CUDA_HOME=/scratch/m/cuda-toolkit/12.4.0 (pt26-cu...
ptrblck
Python 3.6 is not supported anymore as our current binaries require Python >= 3.9. From the install instructions: NOTE: Latest PyTorch requires Python 3.9 or later.
mahmoodn
Hi,Any idea on why I can not remove the torch package via conda?[mn@login02 llama2-70b]$ conda activate pt26-cuda126-py312-gcc13 (pt26-cuda126-py312-gcc13) [mn@login02 llama2-70b]$ conda list | grep torch torch 2.6.0+cu126 pypi_0 pypi torchaudio 2.6.0+cu126 ...
ptrblck
pip uninstall torch -y should work.
SudakshK
Hi,I have been working on an application where I need to partly freeze the layers and I do this by masking gradients to zero in each epoch for particular weights.Thus I removed gradient clipping while training vit-b-16 model on imagenet, as it always changed my gradeints which need to be 0. It turned out that the gradi...
ptrblck
I don’t think this would be directly possible without workarounds of creating custom trainable and frozen weights in custom modules. Given that gradient clipping should not change gradients with a value of zero you should be able to just apply it on the entire parameter. If you want to compute e.g…
sputteringPytorch
Hi,I’m a beginner with Pytorch and I’m having trouble installing. I’m using Ubuntu 20.04, I’ve got a Nvidia Quadro M2200 graphics card and I’ve installed cuda 12.8 (its the only version of Cuda I can get to work…). Ubuntu comes with Python 3.8.10, so as per the pytorch install instructions I have downloaded python 3.9....
ptrblck
It’s deprecated so if you are building from source it could still work, but I would recommend sticking to an older CUDA release, which supported it properly. Yes, you don’t need to install a CUDA toolkit locally as the PyTorch binary ships with its own CUDA runtime dependencies.
liao_zhang
Given the code fragment below, I freeze the weights of the neural network usingmodel.fc1.requires_grad_(False)andmodel.fc2.requires_grad_(False).If I useloss = criterion(outputs, y_batch)to calculate the loss, the training is fine. Why does it not cause the errorRuntimeError: element 0 of tensors does not require grad ...
ptrblck
Your input still requires gradients, so X_train.grad will receive valid gradients. Use X_train = torch.randn(num_samples, input_size) and it will fail with the expected error message.
Marcus_Wong
[ToTensor — Torchvision main documentation]([v2.ToTensor()] [DEPRECATED] Use v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)]) instead.)v2.Compose([v2.ToTensor()]) is return a TensorBut v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)]) is return a ImageAre there steps missing?
ptrblck
The second transformation will return atorchvision.tv_tensors._image.Imageas seen here: transform = v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)]) image = torchvision.transforms.ToPILImage()(torch.randn(3, 224, 224)) out = transform(image) print(type(out)) # <class 'torchvision…
u7122029
I decided to make my own implementation of batch normalisation in the class below:class MyBatchNorm1d(nn.Module): def __init__(self, features, eps=1e-5, momentum=0.1): super().__init__() self.features = features self.eps = eps self.momentum = momentum self.weight = nn.Parame...
ptrblck
I’ve written a manual implementation a while ago which should match the PyTorch implementation and can be foundhere.
laro
When using binary classification model:When training a deep model, at each training step, the model receives a batch (i.e batch of size 32 samples).Let’s assume that in each training batch there are always 16 samples with label ‘0’ and 16 samples with label ‘1’.Does it matter how those samples are arranged in the batch...
ptrblck
No and no. The sample order inside the batch won’t matter unless you treat it as a sequence inside your model (and thus as a sequence dimension, not a batch dimension). The overall shuffling of the dataset still matters, i.e. the batches in each epoch should be created via random sampling.
lilill
Forgive me for asking what may seem like a silly question.When I measure time using instrumentation, I only get a few milliseconds. Here’s my measurement method:start_event = torch.cuda.Event(enable_timing=True) end_event = torch.cuda.Event(enable_timing=True) start_event.record() // module end_event.record() torch.c...
ptrblck
I would recommend sticking to a visual profiler to get a full overview of the execution timeline. Nsight systems or the native PyTorch profiler would be some options. You can use nvtx markers inside your code to mark regions which would show up in nsys.
songsong0425
Hi, I’m not sure it is appropriate for this forum, but I have a problem with the archival.When I tried to use theretrieval_evalfrom torcheval, I couldn’t run it because it didn’t exist in the package.https://pytorch.org/torcheval/main/generated/torcheval.metrics.functional.retrieval_recall.htmlimage1438×199 8.22 KBDoes...
ptrblck
retrieval_recall was added in Nov. 2023 inthis PR. However, it seems the wheels were not published to PyPI after Aug. 2023 as seenhereso you might need to build from source.
Nyx
Hello,In the following code, I define a simple CNN model composed of:CNN(256 out-channels, 5x5 kernel) → ReLU → Flatten()when I run the model with a sample of input data, torch.cuda.memory_allocated() shows 1.8Gb allocated, is that normal? if not why is it so high? what am I doing wrong?the code:(PS cfg is a config fil...
ptrblck
The memory usage is expected as already the output tensor consumes almost all of the used memory: print(output.nelement() * output.element_size() / 1024**3) # 1.876953125
KFrank
Hello All!I am under the impression that the “nvidia driver” and “cuda” are two separate things.How do the two work together?Would there be a use case where somebody uses the “nvidia driver” but not “cuda”?I ask because after upgrading a laptop to ubuntu 24.04 (and reinstalling pytorch),pytorch no longer had cuda suppo...
ptrblck
Yes, these are two separate things if we are talking about the NVIDIA Driver and the CUDA Toolkit. CUDA itself could mean both: the driver as well as the toolkit. While the NVIDIA Driver is making sure your system can properly communicate with and use your GPU, the CUDA Toolkit ships with math lib…
chenghua_wang
I would like to know if torch provides the functionality to manually request memory in advance. This is because when multiple processes share a GPU, it could lead to memory allocation conflicts and cause crashes, potentially evicting a process that has already computed a significant amount of data. I’m curious if a tor...
ptrblck
Yes, you can allocate and delete a tensor at the beginning of your script manually and PyTorch will move the allocated device memory to its cache via torch.empty(size, device="cuda"). A better approach might be to limit the available memory per process viatorch.cuda.set_per_process_memory_fraction.…
tinywisdom
I have a simple model file as follows:import torch import torch.nn as nn import torch.fx as fx class CustomTracer(fx.Tracer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def is_leaf_module(self, module, name): return isinstance(module, CustomModule) class CustomModu...
ptrblck
Your model does not even produce the same outputs in Eager mode: model = my_model_function() x = torch.randn(1, 3, 24, 24) out1 = model(x) out2 = model(x) torch.testing.assert_allclose(out1, out2) # Mismatched elements: 36863 / 36864 (100.0%) # Greatest absolute difference: 7.237934112548828 at in…
ankita1
self.model = self.model.to(self.device)File “/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py”, line 1145, in toreturn self._apply(convert)File “/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py”, line 797, in _applymodule._apply(fn)File “/usr/local/lib/python3.10/dist-packages/torch/...
ptrblck
Often device asserts are triggered by failing indexing operations so check if e.g. an embedding layer received an invalid input or any other indexing fails.
davidhkw
Hi, I am new to using pytorch and I have a question about installation.In the guide, I have to choose the Cuda version I want to install (Compute Platform) where I can choose CUDA 11.8, CUDA12.4 or CUDA 12.6. As I check my cuda version, I have CUDA 12.7. Which one should I choose when installing the pytorch library?ima...
ptrblck
PyTorch binaries ship with their own CUDA runtime dependencies and you would only need to install an NVIDIA driver. Since your driver is new enough you can install any PyTorch binary and I would recommend sticking with the latest, i.e. CUDA 12.6.3 unless you have a Blackwell GPU which requires CUDA …
saff
Hi everyone,I have a huge dataset (we’re talking about trillions and trillions of samples here). The samples are read from multiple files and are then streamed into the dataloaders. For my implementation, I’ve used an iterable dataset then called the dataloader.From my understanding, if you use an iterable dataset then...
ptrblck
Yes, if you use the lazy loading approach described before no data will be preloaded and only the needed sample for the current batch will be loaded into memory (times the batch size, number of workers, and prefetch factor but these are details). Yes, you won’t need to apply any custom shuffling si…
michibaum
I am running an official docker (holoscan) container on the nvidia clara with ubuntu 20.04LTS.I installed PyTorch with:pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu126Then I tried running my code which returns/home/holoscan/.local/lib/python3.10/site-packages/torch/cuda/__in...
ptrblck
PyTorch binaries for ARM with CUDA dependencies support Hopper and Blackwell architectures. If you have valid use cases to add more architectures please create a feature request or build from source in the meantime.
iliasslasri
Hey all,Referring to topics likeHow could I fix the random seed absolutely. I couldn’t find any resources talking about the effects of fixing all seeds and goingtorch.backends.cudnn.enabled=False torch.backends.cudnn.deterministic=True. Does this affect performance of training at all ?import torch import torch.nn as nn...
ptrblck
I assume performance means training speed here. Yes, disabling cuDNN or selecting deterministic algorithms could slow down your code.
Dmitr
Hi! i have one more problem with AI moels. Now python complains about that i don’t have access to huggingface repository. I don’t know why it happens, i run models locally.I have next error:OSError: None is not a local folder and is not a valid model identifier listed on 'https://huggingface.co/models' If this is a pri...
ptrblck
Check your env variables as I assume these are not set: import os MMIX_MODEL_PATH = os.getenv('MMIX_MODEL_PATH') print(MMIX_MODEL_PATH) # None
hunan-rostomyan
I’m following alongWhat is torch.nnreally?tutorial. There’s a setup part in the beginning where they define:weights = torch.randn(784, 10) / math.sqrt(784) weights.requires_grad_()I thought I might as well just rewrite that as:weights = torch.randn(784, 10, requires_grad=True) / math.sqrt(784) assert weights.requires_g...
ptrblck
A division is a differentiable operation and this weights is not a leaf tensor anymore. If you try to access its grad attribute you will see a warning explaining you are trying to access the gradient of a non-leaf.
Geremia
I’m training a NN withConv1dlayers using DataLoader. Mustdata_loader’sbatch_size= # ofin_channelsof first Conv1d layer? In my case, if it isn’t, I get matrix size mismatch errors.Also, are there any tutorials on how to design convolutional NNs in PyTorch. I’m having trouble getting thein_channels andout_channels to be...
ptrblck
No, the batch size does not need to match the number of input channels of the first convolution as the nn.Conv1d layer expects input in the shape [batch_size, channels, seq_len]. If the shape mismatch is raised on the first linear layer, make sure the incoming input activation has the expected num…
ytesfai
Hi,I have a Linear/GRU NN implementation that will eventually be in an embedded system. As such I need the inference to be done with float16. I tried performing the test with model.half() but I got the following error:*** RuntimeError: “compute_indices_weights_linear” not implemented for ‘Half’I read some discussions i...
ptrblck
If you are indeed seeing this issue on the CPU, then your concern might be valid and you would need to either use a GPU for float16 support or you could try to use bfloat16 instead on the CPU or GPU.
Kapil_Rana
from torchvision.models import swin_v2_b,swin_t, swin_bmodel = swin_b(weights=“Swin_B_Weights”)It gives errorKeyError: ‘Swin_B_Weights’
ptrblck
This should work: from torchvision.models import swin_v2_b,swin_t, swin_b, Swin_B_Weights model = swin_b(weights=Swin_B_Weights.IMAGENET1K_V1)
Sourabh_Yadav
in nvidia-smi I have cuda 12.8.From Pytorch, I have downloaded 12.6 One and I have the latest Nvidia drivers also. I am on Win 11 PC , intel chip v100 2x-32Gb→ Also if somewhere in some env I install torch version 12.4 / 11.8 will my CUDA 12.8 mess things up?→ Is cuDNN also required if I am working with LLMs?
ptrblck
Your locally installed CUDA toolkit won’t be used as PyTorch binaries ship with their own CUDA runtime. The driver requirements are explainedhere.
dachosen1
I’m comparing the results of NLLLoss and CrossEntropyLoss and I don’t understand why the loss for NLLLoss is negative compared to CrossEntropyLoss with the same inputs.import torch.nn as nn import torch label = torch.tensor([3, 0, 1, 1, 4]) output = torch.tensor([[0.5073, 0.4838, 0.5053, 0.4839, 0.5183], [0.50...
ptrblck
nn.CrossEntropyLoss uses F.log_softmax and F.nll_loss internally, so there wouldn’t be a difference in using the latter ops explicitly.
Geremia
How do I implement (overload?)>>for tensors?
ptrblck
You are using int values, where the bitshift operation is properly defined. It’s unclear to me what the expected result of a bitshift on floating point numbers is. If you really want to shift the bits, view the tensor in an integer format, shift it, and view it back: x = torch.tensor(1.25) y = x.v…
EIFY
Hi, has anyone seen this error in the last 3 months or so running a compiled pytorch model with multi-GPU?[rank0]: File "/usr/lib/python3/dist-packages/torch/_dynamo/variables/builder.py", line 529, in _wrap [rank0]: if has_triton(): [rank0]: File "/usr/lib/python3/dist-packages/torch/utils/_triton.py", line 37, in has...
ptrblck
To launch torchrun on multiple devices you would use torchrun --nproc_per_node==8 ... which will then correspond to the --local-rank argument inside your script as describedhere. In your approach you are launching your script with torchrun only and are not using the --local-rank at all, so again u…
hiru
I am training a vit usingnn.DataParalleland I want to remove the effect when testing. Since I am calculating few matrices based on the predictions, I want the output to be in a single tensor and in a one gpu. Is there any way for mw to turn off the effect of nn.DataParallel? or does the model.eval() handel it without a...
ptrblck
model.eval() won’t help, but you could use the internal .module to skip the data parallel wrapping via out = model.module(input).
Amit_Sur
I am trying to applying following transformations to training image and bounding boxest = v2.Compose( [ v2.ToImage(), v2.RandomHorizontalFlip(), v2.RandomVerticalFlip(), v2. Resize((448, 448)), v2.ToDtype(torch.float32, scale=True), v2.SanitizeBoundingBoxes() ] )#...
ptrblck
If I understand your use case correctly, the bounding boxes are normalized in [0, 1] for the original canvas size of [500, 375]. You are then scaling them with img_w/h, which I assume is set to 500 and 375, respectively. The transformation resizes these bounding boxes to a desired canvas size of […
c-earth
I am trying to reproduce a previous work that used pytorch 1.4.0+cu100, and torch_sparse 0.6.1. However, after I run the model, the error messageOSError: libcusparse.so.10.0: cannot open shared object file: No such file or directoryis produced under one of torch_sparse function. I thought that pytorch is shipped with c...
ptrblck
I don’t know if torch_sparse depends on a locally installed CUDA toolkit, but installing the version you’ve mentioned together with torch==1.4.0+cu101 fails directly with: python -c "import torch; import torch_sparse" ... OSError: libcudart.so.10.0: cannot open shared object file: No such file or d…
yhl3051
#https://github.com/miki998/3d_convolution_neural_net_MNET/blob/master/3DpytorchConv_example.ipynb #importing the libraries import pandas as pd import numpy as np from tqdm import tqdm import os import seaborn as sns import pickle #for reading and displaying images from skimage.io import imread import matplotlib.pypl...
ptrblck
If you want to keep the processes separate for each GPU, you could simple launch 3 scripts in your terminal via CUDA_VISIBLE_DEVICES=X python script.py args where X would correspond to [0 ,1, 2]. TheDDP exampleshows otherwise how multi-processing can be used inside a script to launch a process pe…
hanxix
Hi, i’m working my way through the Dive Into Deep Learning book and found the following code (pasted below or linkedhere). I’m confused on how this function still trains the linear regression model since it calls for loss.backward() after loss.no_grad()?Thank you so much for your help!@d2l.add_to_class(d2l.Trainer) #@...
ptrblck
The code looks indeed a bit confusing: with torch.no_grad(): loss.backward() if self.gradient_clip_val > 0: # To be discussed later self.clip_gradients(self.gradient_clip_val, self.model) self.optim.step() You don’t need to call loss.bac…
iran_boy
I have implemented an object detection model with CNNs in Pytorch with 3 heads: classification, object detection and segmentation, on google collab This model is from a research paper and when I run it, there is no problem and the training time is consistante, but I modified this model by adding a new classification he...
ptrblck
Using retain_graph=True as a workaround for the actual error: RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specif…
Almenon
I installed pytorch but than ran into a “OSError: CUDA_HOME environment variable is not set” error when I tried installing flash attention after that. I’m curious if the cuda toolkit is installed automatically when following pytorch installation steps inStart Locally | PyTorch. If it is installed, where it is installed...
ptrblck
The PyTorch binaries ship with their own CUDA runtime dependencies, but do not install a full CUDA toolkit (for development). Your flash-attn build seems to fail as it’s expecting a full CUDA compiler to build this package from source, as the package ships with asource distributiononly (not whee…
Boltzmachine
I encounter this error when I installtorch_geometricbut I think it is likely an error of pytorchFile "/home/ubuntu/miniconda3/lib/python3.10/site-packages/torch/utils/cpp_extension.py", line 1972, in <listcomp> supported_sm = [int(arch.split('_')[1]) ValueError: invalid literal for int() with base 10: '...
ptrblck
Related issue:cpp_extension.py expects an integer on CUDA_ARCH, failing with Grace Hopper. · Issue #144037 · pytorch/pytorch · GitHubwith my follow up.
ening
I find this problem. When I use fsdp and three gpus to fine-tune llama3 vision model, I find every gpu(fsdp) has a higher memory than others(every gpu in ddp and single gpu). I get OOM error and it happens in _flat_param.py when flattening tensors. What’s more, even I can load model when using fsdp, it has higher memor...
ptrblck
Did you try FSDP2, as it’s supposed to use less memory? From theRFC: We have validated the prototype on Llama-like models, achieving on-par throughput while using less memory.
DawidL
I have the following code (removed some parts for clarity):class Cell(nn.Module): def __init__(self, core_size, conn_size, conn_num): super().__init__() [...] core = torch.Tensor(core_size) self.core = nn.Parameter(core) nn.init.ones_(self.core) def forward(self, x): ...
ptrblck
The torch.mul operation is differentiable and is thus creating a non-leaf tensor. If you explicitly want to set this output as the new value of the trainable parameter self.core, instead of computing its gradient and updating it as is the common use case, you could do so in a no_grad context. Someth…
DawidL
I’m trying to create a dataset of rotated MNIST images as inputs and the angles by which each one was rotated as outputs. Is there a way to do this without unsqueezing and squeezing each one?When I try to do the following:test = transforms.functional.rotate(dataset1.data[0], 90)I get an error:grid_sampler(): expected g...
ptrblck
It’ll work without unsqueezing the raw data if you iterate the tensors: dataset = datasets.MNIST(root=root, download=False, transform=transforms.ToTensor()) data, target = next(iter(dataset)) test = transforms.functional.rotate(data, 90)
rharwood
I recently migrated my project from sk-learn to pytorch, so my implementation might be way off.I am successively training an nn with different hyperparameter values to perform a grid search. During this process I am seeing the R^2 score gradually increase for each combination of hyperparameter values. This is not expec...
ptrblck
You could call the reset_parameters() method on all registered modules. Something like this should work: for module in model.modules(): if hasattr(module, "reset_parameters"): module.reset_parameters() or you could simply recreate the model and optimizer: regr = nn.Sequential( nn.…
m.span
I just came across a curious behaviour when using mixed-precision with HuggingFace (SFTTrainer and PEFT) when training Mistral-7b.The embeddings and layer norms are kept in full precision and therefore the hidden states get silently casted in float32. In their modeling script they therefore cast the states back to half...
ptrblck
Yes, if you don’t specify the dtype in autocast the default will be used: with torch.autocast(device_type="cuda"): print(torch.get_autocast_dtype("cpu")) print(torch.get_autocast_dtype("cuda")) # torch.bfloat16 # torch.float16 with torch.autocast(device_type="cuda", dtype=torch.bfloat16): …
shwgao
In my case, the Pytorch seems ambitious to hold so much memory, and not free it give it back to cuda, I think it’s unreasonable, and I know it’s possible to free it through insert torch API in specific places in our code. But I want to find if there is some other ways to change the way that Pytorch allocate and cache t...
ptrblck
It’s not unreasonable to use a caching mechanism since releasing the memory to the system via cudaFree (and the need to reallocate the memory again via cudaMalloc) using the default memory allocator is synchronizing and expensive. If you don’t want to use the caching mechanism, you can disable it v…
AviZ
How deep is the scope oftorch.no_gradandtorch.inference_mode?At the following code:with torch.no_grad(): y = my_fun(my_tensor)Will it affectmy_fun? Or must I add@torch.no_gradin its definition?What if tensors are generated withinmy_fun?I assume the answertorch.inference_modewill hold for as well.
ptrblck
The context is applied to all methods invoked inside it unless a new context manager is used (at a nested level) changing the behavior.
mikayagoda
Hi everyone,I need to implement the following:Optimize on a perturbation delta (a tensor) that is added to an input to a nerual network in order to create an adversarial example for the model.After that optimize on the model’s weights in order to make it robust to this specific input (the adversarial example).Afterward...
ptrblck
You might be running into a similar issue as describedhere. After one optimizer updates (some) parameters the corresponding forward activations become stale as they were created by the old parameter set. Trying to calculate the gradients with these stale forward activations and the updated paramete…
tylerschuessler
This is the error I have encounteredRuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [20, 80]], which is output 0 of TBackward, is at version 2; expected version 1 instead. Hint: the backtrace further above shows the operation that failed t...
ptrblck
You would need to recompute the forward pass using the generator and its already updated parameters to create the new forward activations. Alternatively, you could also delay the optimizerG.step() call until both backward passes calculated and accumulated the gradients using the same (initial) param…
cwindolf
Hi –So, I’m new to PyTorch, and I’m spending a lot of time in the docs. Recently, I was digging around trying to find out howlog_softmaxis implemented.I started out looking at the source fortorch.nn.LogSoftmax, which is implemented withtorch.nn.functional.log_softmax. OK, so I went to the docs for that and clicked the ...
ptrblck
You’ll find the CPU implementationhere. PS: rgrep is often a useful tool to find the corresponding function. The GitHub search function is often also quite helpful.
Sasika_Amarasinghe
I have a dataset that contains images of brain tumoursl. I want to make a CNN to classify these images.What I have seen is a directory of images which is separated in “train” , “test” folders.However, in this case, the dataset directory structure is as follows.dataset_dir|_____tumor_type_1|_____tumor_type_2|_____tumo...
ptrblck
You could use the torchvision.datasets.ImageFolder class for the datasets, create the splits via torch.utils.data.Subsets, and wrap them in DataLoaders.
aoot
I was wondering what would happen if thenum_featuresspecified fornn.InstanceNorm2dmismatch that of the number of features in the input and thus decided to test it. I learned that thenum_featuresparameter does not really matter as the results remain the same.Why doesn’tnum_featuresmatter? If it doesn’t matter, why is th...
ptrblck
A warning will be raised fromheresince you are using the default affine=False argument. If you use affine parameters, the code will fail with a shape mismatch.
abdul_alotaibi
I have images dataset in two different directoriesTrain_imagesandTest_images. Both directories are organized the same way where images are inside another directory with their associated label.I am loading the images intotrain_dataset = datasets.ImageFolder(root='path/to/dataset/Train_images')andtest_dataset = datasets....
ptrblck
ImageFolder will call intofind_classesto create the class labels and will sort the folders. On the same system and OS you should see the same classes. However, I think I’ve seen differences in sorting between e.g. Linux and Windows, but don’t know if this was an artifact of older Python versions.
JPK314
I am running into a strange issue in my code base. The code is complicated but essentially I was noticing that calling unbind(0) on tensors took longer in one commit vs another, and it was noticeably slowing down performance. The old commit has an average per-call runtime of 8.727e-5, while the new commit has an averag...
ptrblck
I don’t know how you are profiling your code and if you are using a GPU, but note that CUDA operations are executed asynchronously. If you are using host timers you would need to synchronize the code before starting and stopping the host timers.
samm
I faced an issue in the curve of accuracy for training and validation as followScreenshot from 2024-12-13 18-27-141085×624 81 KBthis happened after finished the training the model for 50 epochs and resume the training later to be 70 which means add additional 20 epochs … Does that normal i mean resuming the training fr...
ptrblck
3 images in total is quite a low number of samples. Image augmentation could help, but using augmentation should not cause any data leaks assuming the data splitting is still valid.
Oren_Zeev_Ben_Mordeh
I’ve saved a batch normalization layer (2d) and I only see the weights and bias but not ‘running_mean’, nor the ‘running_var’. I’ve used: torch.save(model.state_dict()…I may doing something funny. I’m not loading those with torch, but with regular Python code, as a dict. Is there a way to figure those out (‘running_mea...
ptrblck
Running stats are buffers, not parameters, which is why they are not returned via .named_parameters(). Use the state_dict directly or make sure to save .named_buffers() as well.
flauron
Hi,I am currently working on a problem of gradient pruning.In the context of convolution computation, during the backpropagation, I need to alter the gradient of the weight (grad_weight) computation by slicing the gradient of the output (grad_output) before doing the actual gradient computation.So to achieve this goa...
ptrblck
These methods will still dispatch to cudnn as seen here: device = "cuda" x = torch.randn(1, 3, 24, 24, requires_grad=True, device=device) w = torch.randn(3, 3, 3, 3, requires_grad=True, device=device) grad_output = torch.randn_like(x) activities = [ProfilerActivity.CPU, ProfilerActivity.CUDA] so…
scott_femto
I am interested in customizing the new torch.export.export_for_training with additional custom operators to add on to the ATen opset.The docstring indicates that this may be possiblepytorch/torch/export/__init__.py at main · pytorch/pytorch · GitHub“The traced graph (1) produces normalized operators in the all ATen ope...
ptrblck
This tutorialmight be a good starter explaining different paths to add custom operators (the first link shows how to add custom ops for torch.compile and torch.export).
yajuvendra
Can anyone kindly help me download PyTorch, which supports sm_87 on aarch64? Right now, I am using the version below.import torchprint(torch.version.cuda)12.2print(torch.cuda.get_arch_list())[‘sm_50’, ‘sm_80’, ‘sm_86’, ‘sm_89’, ‘sm_90’, ‘sm_90a’]
ptrblck
Your Python version might be different as the wheel is built for Python 3.10. If you get stuck, you can use a pre-built container fromhere.
divinho
I’m in a situation where compiling does not work for the whole model, so I’m wrapping each layer withtorch.compile. Because I have (a fixed number of) variable shapes there is a significant amount of compilation time.Each layer is just a transformer layer, I’m wondering if the compilation has to be redone for each laye...
ptrblck
Caching should already be used and you could checkthis docfor more information.
nidheeshg11
I want to use a DeIT model with different tokenizers based on the input type. For example, if my dataset has four types of data, I want to use four different tokenizers, one for each type but one single encoder block. Each batch will have a mix of all types of data. If a sample is of type 0, the forward pass should loo...
ptrblck
Yes, using a list to append activations is fine and you won’t break the computation graph if you create a single tensor via torch.cat or torch.stack from this list. You should not create a new tensor via torch.tensor(list_entries) since this will detach the newly created tensor from the computation…
jhj0517
Hi, Thanks for your work!I’m wondering if this is a typo or if there is no real CUDA 12.4 distribution for Linux when using pip.Currently inStart Locally | PyTorch, there’s no--index-urloption on Linux with CUDA 12.4.torch-cuda-12.4830×383 21 KBUp to CUDA 12.1, it needs to be installed with--index-urlon Linux as well, ...
ptrblck
The default pip install torch wheels always shipped with CUDA runtime dependencies so just copy/paste the command and you’ll see CUDA 12.4 dependencies will be installed too.
adb57
Hello I am trying to install PyTorch 1.7 to use for a Github repo I found quite interesting, however when I run the pip commands found onPrevious PyTorch Versions | PyTorch, it appears the version of PyTorch could not be found. Is there a way to manually download it, or is the repo simply no longer feasible to use?Comm...
ptrblck
A quick search shows PyTorch==1.7 was released in Oct. 2020 while Python==3.11 was released in Oct. 2022, so yes you would need to downgrade your Python version.
Laya1
I trained a Faster RCNN model and evaluated it withtorchmetrics. I had saved a dictionary with model weights in.ptformat along with thetorchmetrics.detection.mapobject after training an object detection model. I now upgraded torchmetrics and the module name has changed frommaptomean_ap. Now when I usetorch.load, I get ...
ptrblck
I assume you have saved the torchmetrics object directly, which might require the same source code during the load process. I don’t know if this object contains a state_dict but if so you should save and restore it instead, as the actual data will be saved only instead of the object.
Aknw_Fen
The results for an operation are as follows:CUDA enabled GPU=T4 calculation does not even finish after many seconds, maybe minutes. Same happens for CPUs.XLA + CUDA enabled GPU is fast, approximately same speed as TPUXLA enabled TPU are very fast.Results and ReproThis can be issued in a Colab Notebook.Remove tensorflow...
ptrblck
CUDA kernels are executed asynchronously, i.e. the host code can run ahead launching kernels while the GPU is busy with the actual kernel execution. If you use host timers and want to measure the real GPU kernel execution time, you would need to synchronize the code before starting and stopping the…
Zhewen_Hu
I am using CUDA graph to train multiple models. I believe the graph captures certain memory spaces, so if I need to train another network using the same graph, I have to use the same memory space of the model and optimizer. My question is how can I create a new model/optimizer in the same memory space, or is there a wa...
ptrblck
If the architecture is equal, try to simply load the state_dict of another model into the captured one and let me know if you are seeing any issues.
End of preview. Expand in Data Studio

Scraped data from pytorch forums, scrapper code can be found here: https://github.com/Arush04/Agent_Cheat/blob/main/scrappers/pytorch_scrapper.py Found the following users with most queries answered:

  1. ptrblck
  2. albanD
  3. KFrank
  4. tom
  5. smth

It has the following columns:
['user_q', 'question', 'user_a', 'answer']

where
user_q is the user name of user who asked question
question is the question asked by user_q
user_a is the user name of user who provided solution
answer is the solution provided by user_a

Downloads last month
9