{"question":"How does Pytorch Backward functions handle batched inputs?\n\nHi, I am curious as to how Pytorch's backward function handles multiple inputs.\n\nSpecifically, are the losses averaged across inputs in the final layer itself (cross entropy loss, etc.), or are the input specific loss matrixes passed on to previous layers and each layer averages/sums across these losses?\n\nFor ex. For a Input Layer(p neurons)->Linear(q neurons)->CrossEntropy NN, and for a batched input of size \"b\", does the backward differential that reaches the Linear layer have a shape of \"q\" or \"bxq\"?\n\nThe reason for the question is because the implementation of the latter is simpler for the linear layer (dW is a simple outer product). \n\nThanks.","reference_answer":"Hi Siddhanth!\n\nLogically, it is not necessary to have a batch dimension. There are, however, a\nnumber of built-in pytorch layers that do require a batch dimension (but such batch\ndimensions can always have size 1). For example, `Linear` does not require a\nbatch dimension, but `Conv2d` does.\n\nI'm not quite sure what you mean by this, but to clarify: Let's say we had a batch\nof five samples. If we wanted to get rid of the batch dimension, we wouldn't do it\nby somehow aggregating the five samples together -- instead , we would take a\nsingle sample from the batch and run it through the network, doing this five times.\n\nUsing standard terminology, if you have a scalar-valued function of a vector input,\n`f (x_j)`, the gradient is the vector made up of the partial derivatives, `d f / d x_j`.\nIf you have a vector-valued function of a vector input, `f_i (x_j)`, the jacobian is\nthe matrix of partial derivatives, `d f_i / d x_j`. It's just terminology, but in this sense\nthe jacobian is essentially a gradient, but for a vector-valued function.\n\nA layer in a network is a vector-valued function. For example, a `Linear (3, 5)` maps\na vector of length `3` to a vector of length `5`. When you backpropagate through a\n`Linear` its jacobian is never explicitly computed (let alone materialized). Instead,\nautograd implicitly computes the jacobian-vector product of the jacobian for that\n`Linear` layer and the vector that is the gradient of the final scalar loss value with\nrespect to the output of that `Linear`, as computed by the previous steps in the\nbackpropagation. This jacobian-vector product is the gradient of the final scalar loss\nvalue with respect to the input to that `Linear` (which is then passed back on up the\nbackpropagation chain),\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":214837,"url":"https://discuss.pytorch.org/t/how-does-pytorch-backward-functions-handle-batched-inputs/214837","created_at":"2025-01-01T02:18:15.016000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Is this PPO training code wrong?\n\nI saw this training code in 2 different source (a open source project and my former colleague). I always consider it's correct and use it.\n\n```\nratios = torch.exp(torch.clamp(a_logp_new - torch.sum(a_logp[idx], dim=-1), max=4))\nsurr1 = ratios * adv[idx]\nsurr2 = torch.clamp(ratios, 1 - self.clip_ep, 1 + self.clip_ep) * adv[idx]\nactor_loss = - torch.min(surr1, surr2).mean()\n```\n\nbut now, I'm wandering it is wrong when the advantage is negetive.\nassume that clip_ep is 0.1, ratio is 2; when adv is positive, the loss is - 1.1 * adv; when adv is negetive, the loss is -2 * adv.\npositive and negetive adv with same absolute value cause unsymmetrical influence\nand I guess this is the reason cause my Categorical distribution become NAN like this discussion(https://discuss.pytorch.org/t/categorical-distribution-returning-breaking/165343)","reference_answer":"If your advantage is negative, you want to \"push away\" the parameter configuration from that outcome so everything should work fine. The `min` operator ensures that you're taking the most pessimistic estimate.","needs_clarification":false,"thread_id":214871,"url":"https://discuss.pytorch.org/t/is-this-ppo-training-code-wrong/214871","created_at":"2025-01-02T05:13:33.496000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["vmoens"],"answered_by_ptrblck":false} {"question":"Why the gradient values seems to be reversed in Tensor.backward()\n\nI am trying to print the gradient values of 3 tensors but I find the printed gradients do not match my manual calculation, specifically the gradient of a is **swapped** with the gradient of c. Check the code below.\n\n> import torch\n> a = torch.tensor(3.0,requires_grad=True)\n> b = a*2\n> c = b ** 2\n> \n> b.retain_grad()\n> c.retain_grad()\n> c.backward() # Computes the gradient of current tensor wrt graph leaves.\n> print(a.grad) \n> print(b.grad) \n> print(c.grad) \n\nHere is the output:\n> tensor(24.)\n> tensor(12.)\n> tensor(1.)","reference_answer":"> So you’ve calculated dc/da which is the gradient value for c,\n\na.grad actually means dc/da (and c.grad means dc/dc, which is 1)\n\nWhen using .backward() we are doing backprop not forwardprop (which PyTorch also supports https://pytorch.org/tutorials/intermediate/forward_ad_usage.html)","needs_clarification":false,"thread_id":214889,"url":"https://discuss.pytorch.org/t/why-the-gradient-values-seems-to-be-reversed-in-tensor-backward/214889","created_at":"2025-01-02T13:55:38.988000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[6],"answer_authors":["soulitzer"],"answered_by_ptrblck":false} {"question":"Training Time is Increasing per epoch, Can somebody help me?\n\nI 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 head to the backbone of the model 1 and created a second model, since the model 1 was just getting some feature maps and used them via FPN, the backbone is dla34 from timm model in pytorch and the code is this: \n```self.backbone = timm.create_model(model_name, pretrained=True, features_only=True, out_indices=model_out_indices)```\n\nI add some layers to the end of the backbone to make it classify the image while getting the featuremaps, and so the training and validation results are decreasing in a slow rate like these:\n```\n$$TRAIN$$ epoch 0 ====>: loss_cls = 10.37930 loss_reg_xytl = 0.07201 loss_iou = 3.33917 loss_seg = 0.23536 loss_class_cls = 0.13680 Train Time: 00:15:57 \n$$VALID$$ epoch 0 ====>: loss_cls = 3.64299 loss_reg_xytl = 0.06027 loss_iou = 3.27866 loss_seg = 0.21605 loss_class_cls = 0.13394 Val Time: 00:02:51 \n$$TRAIN$$ epoch 1 ====>: loss_cls = 2.90086 loss_reg_xytl = 0.04123 loss_iou = 2.82772 loss_seg = 0.18830 loss_class_cls = 0.13673 Train Time: 00:06:28 \n$$VALID$$ epoch 1 ====>: loss_cls = 2.42524 loss_reg_xytl = 0.02885 loss_iou = 2.43828 loss_seg = 0.16975 loss_class_cls = 0.13383 Val Time: 00:00:21 \n$$TRAIN$$ epoch 2 ====>: loss_cls = 2.51989 loss_reg_xytl = 0.02749 loss_iou = 2.29531 loss_seg = 0.16370 loss_class_cls = 0.13665 Train Time: 00:08:08 \n$$VALID$$ epoch 2 ====>: loss_cls = 2.31358 loss_reg_xytl = 0.01987 loss_iou = 2.15709 loss_seg = 0.15870 loss_class_cls = 0.13372 Val Time: 00:00:20 \n$$TRAIN$$ epoch 3 ====>: loss_cls = 2.45530 loss_reg_xytl = 0.02143 loss_iou = 2.04151 loss_seg = 0.15327 loss_class_cls = 0.13663 Train Time: 00:09:41 \n$$VALID$$ epoch 3 ====>: loss_cls = 2.16958 loss_reg_xytl = 0.01639 loss_iou = 1.93723 loss_seg = 0.14761 loss_class_cls = 0.13373 Val Time: 00:00:21 \n$$TRAIN$$ epoch 4 ====>: loss_cls = 2.28015 loss_reg_xytl = 0.01871 loss_iou = 1.95341 loss_seg = 0.14816 loss_class_cls = 0.13662 Train Time: 00:11:24 \n$$VALID$$ epoch 4 ====>: loss_cls = 2.10085 loss_reg_xytl = 0.01300 loss_iou = 1.72231 loss_seg = 0.14628 loss_class_cls = 0.13366 Val Time: 00:00:20 \n$$TRAIN$$ epoch 5 ====>: loss_cls = 2.26286 loss_reg_xytl = 0.01951 loss_iou = 1.85480 loss_seg = 0.14490 loss_class_cls = 0.13656 Train Time: 00:12:51 \n$$VALID$$ epoch 5 ====>: loss_cls = 2.06082 loss_reg_xytl = 0.01709 loss_iou = 1.70226 loss_seg = 0.13609 loss_class_cls = 0.13360 Val Time: 00:00:21 \n$$TRAIN$$ epoch 6 ====>: loss_cls = 2.10616 loss_reg_xytl = 0.02187 loss_iou = 1.75277 loss_seg = 0.14173 loss_class_cls = 0.13654 Train Time: 00:14:36 \n$$VALID$$ epoch 6 ====>: loss_cls = 1.80460 loss_reg_xytl = 0.01411 loss_iou = 1.64604 loss_seg = 0.13180 loss_class_cls = 0.13360 Val Time: 00:00:20 \n$$TRAIN$$ epoch 7 ====>: loss_cls = 1.95502 loss_reg_xytl = 0.01975 loss_iou = 1.70851 loss_seg = 0.14052 loss_class_cls = 0.13655 Train Time: 00:16:06 \n$$VALID$$ epoch 7 ====>: loss_cls = 1.80424 loss_reg_xytl = 0.01560 loss_iou = 1.69335 loss_seg = 0.13176 loss_class_cls = 0.13355 Val Time: 00:00:20 \n$$TRAIN$$ epoch 8 ====>: loss_cls = 1.90833 loss_reg_xytl = 0.02100 loss_iou = 1.73520 loss_seg = 0.14235 loss_class_cls = 0.13649 Train Time: 00:17:46 \n$$VALID$$ epoch 8 ====>: loss_cls = 1.53639 loss_reg_xytl = 0.01386 loss_iou = 1.68395 loss_seg = 0.13792 loss_class_cls = 0.13350 Val Time: 00:00:21 \n$$TRAIN$$ epoch 9 ====>: loss_cls = 1.61048 loss_reg_xytl = 0.01840 loss_iou = 1.81451 loss_seg = 0.14155 loss_class_cls = 0.13642 Train Time: 00:19:23 \n$$VALID$$ epoch 9 ====>: loss_cls = 1.39604 loss_reg_xytl = 0.01234 loss_iou = 1.69770 loss_seg = 0.14150 loss_class_cls = 0.13345 Val Time: 00:00:20 \n$$TRAIN$$ epoch 10 ====>: loss_cls = 1.58478 loss_reg_xytl = 0.01784 loss_iou = 1.73858 loss_seg = 0.14001 loss_class_cls = 0.13636 Train Time: 00:21:11 \n$$VALID$$ epoch 10 ====>: loss_cls = 1.49616 loss_reg_xytl = 0.01216 loss_iou = 1.60697 loss_seg = 0.13105 loss_class_cls = 0.13335 Val Time: 00:00:20 \n$$TRAIN$$ epoch 11 ====>: loss_cls = 1.59138 loss_reg_xytl = 0.01954 loss_iou = 1.70157 loss_seg = 0.13825 loss_class_cls = 0.13628 Train Time: 00:23:13 \n$$VALID$$ epoch 11 ====>: loss_cls = 1.37387 loss_reg_xytl = 0.01493 loss_iou = 1.72290 loss_seg = 0.14186 loss_class_cls = 0.13325 Val Time: 00:00:20 \n$$TRAIN$$ epoch 12 ====>: loss_cls = 1.56931 loss_reg_xytl = 0.01929 loss_iou = 1.69895 loss_seg = 0.13726 loss_class_cls = 0.13621 Train Time: 00:24:55 \n$$VALID$$ epoch 12 ====>: loss_cls = 1.47095 loss_reg_xytl = 0.01358 loss_iou = 1.64010 loss_seg = 0.12568 loss_class_cls = 0.13314 Val Time: 00:00:21 \n$$TRAIN$$ epoch 13 ====>: loss_cls = 1.47089 loss_reg_xytl = 0.01883 loss_iou = 1.69151 loss_seg = 0.13617 loss_class_cls = 0.13627 Train Time: 00:26:49 \n$$VALID$$ epoch 13 ====>: loss_cls = 1.37469 loss_reg_xytl = 0.01444 loss_iou = 1.57538 loss_seg = 0.13452 loss_class_cls = 0.13308 Val Time: 00:00:20 \n$$TRAIN$$ epoch 14 ====>: loss_cls = 1.39732 loss_reg_xytl = 0.01801 loss_iou = 1.66951 loss_seg = 0.13488 loss_class_cls = 0.13614 Train Time: 00:28:04 \n$$VALID$$ epoch 14 ====>: loss_cls = 1.22657 loss_reg_xytl = 0.01389 loss_iou = 1.66898 loss_seg = 0.14039 loss_class_cls = 0.13286 Val Time: 00:00:21 \n$$TRAIN$$ epoch 15 ====>: loss_cls = 1.30442 loss_reg_xytl = 0.01737 loss_iou = 1.69497 loss_seg = 0.13358 loss_class_cls = 0.13607 Train Time: 00:29:14 \n$$VALID$$ epoch 15 ====>: loss_cls = 1.25604 loss_reg_xytl = 0.01460 loss_iou = 1.65997 loss_seg = 0.12326 loss_class_cls = 0.13268 Val Time: 00:00:20 \n$$TRAIN$$ epoch 16 ====>: loss_cls = 1.32521 loss_reg_xytl = 0.01644 loss_iou = 1.70964 loss_seg = 0.13379 loss_class_cls = 0.13590 Train Time: 00:30:58 \n$$VALID$$ epoch 16 ====>: loss_cls = 1.28813 loss_reg_xytl = 0.01189 loss_iou = 1.62254 l\noss_seg = 0.13013 loss_class_cls = 0.13239 Val Time: 00:00:20\n```\nthe training time is increasing per epoch, I also checked it with ChatGPT and did these modifications but at the end the results were the same, the modifications are:\n\nchanging the optimizer\nchanging the lr scheduler\nfreezing some first layers of the backbone\nchanging the weights of the losses\nremoving some of the losses (loss_class_cls and loss_seg)\nchanging the number of workers and batch_size\nbut the results were exactly the same, the training time keeped increasing (running on gpu on google collab), SO here I desperatly need some suggestions on how to solve this problem.","reference_answer":"Iteration time grows when tensors that still have graph history are kept across iterations, for example by appending each iteration's outputs to a tensor, or by storing embeddings on the device. The backward pass then goes through the graphs of earlier iterations too, so memory and iteration time keep growing. Look for where the graph is reused or extended. Don't use `retain_graph=True` to get past the \"backward through the graph a second time\" error unless you can explain why you need to keep the graph.","needs_clarification":true,"thread_id":214900,"url":"https://discuss.pytorch.org/t/training-time-is-increasing-per-epoch-can-somebody-help-me/214900","created_at":"2025-01-02T17:21:10.454000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,5,6],"answer_authors":["iran_boy","ptrblck"],"answered_by_ptrblck":true} {"question":"RuntimeError: invalid dtype for bias - should match query's dtype #144018\n\nI am training the X-CLIP model using a multi-GPU setup (3 GPUs). However, when I start the training process, I encounter the following error:\n\n\" **RuntimeError: invalid dtype for bias - should match query's dtype** \"\n\nHere is the complete traceback of the error:\n\nUserWarning: torch.utils.checkpoint.checkpoint_sequential: the use_reentrant parameter should be passed explicitly. In version 2.5 we will raise an exception if use_reentrant is not passed. use_reentrant=False is recommended, but if you need to preserve the current default behavior, you can pass use_reentrant=True. Refer to docs for more details on the differences between the two variants.\nwarnings.warn(\n[rank0]: Traceback (most recent call last):\n[rank0]: File \"/data/Hayat_Research_Data/VideoX/X-CLIP/main.py\", line 283, in\n[rank0]: main(config)\n[rank0]: File \"/data/Hayat_Research_Data/VideoX/X-CLIP/main.py\", line 104, in main\n[rank0]: train_one_epoch(epoch, model, criterion, optimizer, lr_scheduler, train_loader, text_labels, config, mixup_fn)\n[rank0]: File \"/data/Hayat_Research_Data/VideoX/X-CLIP/main.py\", line 149, in train_one_epoch\n[rank0]: output = model(images, texts)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1736, in _wrapped_call_impl\n[rank0]: return self._call_impl(*args, **kwargs)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1747, in _call_impl\n[rank0]: return forward_call(*args, **kwargs)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/parallel/distributed.py\", line 1643, in forward\n[rank0]: else self._run_ddp_forward(*inputs, **kwargs)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/parallel/distributed.py\", line 1459, in _run_ddp_forward\n[rank0]: return self.module(*inputs, **kwargs) # type: ignore[index]\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1736, in _wrapped_call_impl\n[rank0]: return self._call_impl(*args, **kwargs)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1747, in _call_impl\n[rank0]: return forward_call(*args, **kwargs)\n[rank0]: File \"/data/Hayat_Research_Data/VideoX/X-CLIP/models/xclip.py\", line 135, in forward\n[rank0]: text_features = self.cache_text(text)\n[rank0]: File \"/data/Hayat_Research_Data/VideoX/X-CLIP/models/xclip.py\", line 125, in cache_text\n[rank0]: self.cache_text_features = self.encode_text(text)\n[rank0]: File \"/data/Hayat_Research_Data/VideoX/X-CLIP/models/xclip.py\", line 97, in encode_text\n[rank0]: x = self.transformer(x)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1736, in _wrapped_call_impl\n[rank0]: return self._call_impl(*args, **kwargs)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1747, in _call_impl\n[rank0]: return forward_call(*args, **kwargs)\n[rank0]: File \"/data/Hayat_Research_Data/VideoX/X-CLIP/clip/model.py\", line 87, in forward\n[rank0]: return self.resblocks(x)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1736, in _wrapped_call_impl\n[rank0]: return self._call_impl(*args, **kwargs)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1747, in _call_impl\n[rank0]: return forward_call(*args, **kwargs)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/container.py\", line 250, in forward\n[rank0]: input = module(input)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1736, in _wrapped_call_impl\n[rank0]: return self._call_impl(*args, **kwargs)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1747, in _call_impl\n[rank0]: return forward_call(*args, **kwargs)\n[rank0]: File \"/data/Hayat_Research_Data/VideoX/X-CLIP/clip/model.py\", line 75, in forward\n[rank0]: x = x + self.attention(self.ln_1(x))\n[rank0]: File \"/data/Hayat_Research_Data/VideoX/X-CLIP/clip/model.py\", line 72, in attention\n[rank0]: return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1736, in _wrapped_call_impl\n[rank0]: return self._call_impl(*args, **kwargs)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/module.py\", line 1747, in _call_impl\n[rank0]: return forward_call(*args, **kwargs)\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/modules/activation.py\", line 1368, in forward\n[rank0]: attn_output, attn_output_weights = F.multi_head_attention_forward(\n[rank0]: File \"/home/hayatullah/anaconda3/envs/VFL/lib/python3.10/site-packages/torch/nn/functional.py\", line 6278, in multi_head_attention_forward\n[rank0]: attn_output = scaled_dot_product_attention(\n[rank0]: RuntimeError: invalid dtype for bias - should match query's dtype\n\n### Versions\n\nPyTorch version: 2.5.1\nIs debug build: False\nCUDA used to build PyTorch: 12.4\nROCM used to build PyTorch: N/A\n\nOS: Ubuntu 22.04.5 LTS (x86_64)\nGCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0\nClang version: Could not collect\nCMake version: version 3.22.1\nLibc version: glibc-2.35\n\nPython version: 3.10.14 (main, May 6 2024, 19:42:50) [GCC 11.2.0] (64-bit runtime)\nPython platform: Linux-6.8.0-45-generic-x86_64-with-glibc2.35\nIs CUDA available: True\nCUDA runtime version: 12.4.131\nCUDA_MODULE_LOADING set to: LAZY\nGPU models and configuration:\nGPU 0: NVIDIA RTX 6000 Ada Generation\nGPU 1: NVIDIA RTX 6000 Ada Generation\nGPU 2: NVIDIA RTX 6000 Ada Generation\n\nNvidia driver version: 550.107.02\ncuDNN version: Could not collect\nHIP runtime version: N/A\nMIOpen runtime version: N/A\nIs XNNPACK available: True\n\nCPU:\nArchitecture: x86_64\nCPU op-mode(s): 32-bit, 64-bit\nAddress sizes: 48 bits physical, 48 bits virtual\nByte Order: Little Endian\nCPU(s): 64\nOn-line CPU(s) list: 0-63\nVendor ID: AuthenticAMD\nModel name: AMD Ryzen Threadripper PRO 5975WX 32-Cores\nCPU family: 25\nModel: 8\nThread(s) per core: 2\nCore(s) per socket: 32\nSocket(s): 1\nStepping: 2\nFrequency boost: enabled\nCPU max MHz: 7006.6401\nCPU min MHz: 1800.0000\nBogoMIPS: 7186.58\nFlags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin brs arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca fsrm debug_swap\nVirtualization: AMD-V\nL1d cache: 1 MiB (32 instances)\nL1i cache: 1 MiB (32 instances)\nL2 cache: 16 MiB (32 instances)\nL3 cache: 128 MiB (4 instances)\nNUMA node(s): 1\nNUMA node0 CPU(s): 0-63\nVulnerability Gather data sampling: Not affected\nVulnerability Itlb multihit: Not affected\nVulnerability L1tf: Not affected\nVulnerability Mds: Not affected\nVulnerability Meltdown: Not affected\nVulnerability Mmio stale data: Not affected\nVulnerability Reg file data sampling: Not affected\nVulnerability Retbleed: Not affected\nVulnerability Spec rstack overflow: Vulnerable: Safe RET, no microcode\nVulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl\nVulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization\nVulnerability Spectre v2: Mitigation; Retpolines; IBPB conditional; IBRS_FW; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected\nVulnerability Srbds: Not affected\nVulnerability Tsx async abort: Not affected\n\nVersions of relevant libraries:\n[pip3] flake8==7.0.0\n[pip3] mypy-extensions==1.0.0\n[pip3] numpy==1.26.4\n[pip3] numpydoc==1.7.0\n[pip3] nvidia-cublas-cu12==12.1.3.1\n[pip3] nvidia-cuda-cupti-cu12==12.1.105\n[pip3] nvidia-cuda-nvrtc-cu12==12.1.105\n[pip3] nvidia-cuda-runtime-cu12==12.1.105\n[pip3] nvidia-cudnn-cu12==9.1.0.70\n[pip3] nvidia-cufft-cu12==11.0.2.54\n[pip3] nvidia-curand-cu12==10.3.2.106\n[pip3] nvidia-cusolver-cu12==11.4.5.107\n[pip3] nvidia-cusparse-cu12==12.1.0.106\n[pip3] nvidia-nccl-cu12==2.20.5\n[pip3] nvidia-nvjitlink-cu12==12.4.127\n[pip3] nvidia-nvtx-cu12==12.1.105\n[pip3] torch==2.5.1\n[pip3] torchaudio==2.4.0\n[pip3] torchvision==0.20.1\n[pip3] triton==3.0.0\n[conda] blas 1.0 mkl\n[conda] cuda-cudart 12.4.127 0 nvidia\n[conda] cuda-cupti 12.4.127 0 nvidia\n[conda] cuda-libraries 12.4.1 0 nvidia\n[conda] cuda-nvrtc 12.4.127 0 nvidia\n[conda] cuda-nvtx 12.4.127 0 nvidia\n[conda] cuda-opencl 12.6.77 0 nvidia\n[conda] cuda-runtime 12.4.1 0 nvidia\n[conda] ffmpeg 4.3 hf484d3e_0 pytorch\n[conda] libcublas 12.4.5.8 0 nvidia\n[conda] libcufft 11.2.1.3 0 nvidia\n[conda] libcurand 10.3.7.77 0 nvidia\n[conda] libcusolver 11.6.1.9 0 nvidia\n[conda] libcusparse 12.3.1.170 0 nvidia\n[conda] libjpeg-turbo 2.0.0 h9bf148f_0 pytorch\n[conda] libnvjitlink 12.4.127 0 nvidia\n[conda] mkl 2023.1.0 h213fc3f_46344\n[conda] mkl-service 2.4.0 py310h5eee18b_1\n[conda] mkl_fft 1.3.11 py310h5eee18b_0\n[conda] mkl_random 1.2.8 py310h1128e8f_0\n[conda] numpy 1.26.4 pypi_0 pypi\n[conda] numpydoc 1.7.0 py310h06a4308_0\n[conda] nvidia-cublas-cu12 12.1.3.1 pypi_0 pypi\n[conda] nvidia-cuda-cupti-cu12 12.1.105 pypi_0 pypi\n[conda] nvidia-cuda-nvrtc-cu12 12.1.105 pypi_0 pypi\n[conda] nvidia-cuda-runtime-cu12 12.1.105 pypi_0 pypi\n[conda] nvidia-cudnn-cu12 9.1.0.70 pypi_0 pypi\n[conda] nvidia-cufft-cu12 11.0.2.54 pypi_0 pypi\n[conda] nvidia-curand-cu12 10.3.2.106 pypi_0 pypi\n[conda] nvidia-cusolver-cu12 11.4.5.107 pypi_0 pypi\n[conda] nvidia-cusparse-cu12 12.1.0.106 pypi_0 pypi\n[conda] nvidia-nccl-cu12 2.20.5 pypi_0 pypi\n[conda] nvidia-nvjitlink-cu12 12.4.127 pypi_0 pypi\n[conda] nvidia-nvtx-cu12 12.1.105 pypi_0 pypi\n[conda] pytorch 2.5.1 py3.10_cuda12.4_cudnn9.1.0_0 pytorch\n[conda] pytorch-cuda 12.4 hc786d27_7 pytorch\n[conda] pytorch-mutex 1.0 cuda pytorch\n[conda] torchaudio 2.4.0 pypi_0 pypi\n[conda] torchtriton 3.1.0 py310 pytorch\n[conda] torchvision 0.20.1 pypi_0 pypi\n[conda] triton 3.0.0 pypi_0 pypi\n\nI would appreciate if anyone who has encountered and resolved this error could share their solution.","reference_answer":"I have resolved the issue ( :slightly_smiling_face:) by using explicit type casting with **torch.autocast(\"cuda\")**. This problem appears to be a potential bug in PyTorch (I believe). When using PyTorch 2 on a CPU instead of CUDA, the error occurs because PyTorch converts the query to torch.bfloat16, which doesn’t match the dtype used for the attention_mask (torch.float32). PyTorch 2 uses a function called scaled_dot_product_attention, which cannot handle mismatched dtypes between the query and the mask.","needs_clarification":false,"thread_id":214902,"url":"https://discuss.pytorch.org/t/runtimeerror-invalid-dtype-for-bias-should-match-querys-dtype-144018/214902","created_at":"2025-01-02T18:43:16.682000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["Hayat_Ullah"],"answered_by_ptrblck":false} {"question":"Handling sparse batches to speed up training\n\nHi everyone,\n\nI’m working on a use case where the input to my model is a tensor of size `(B, K, context_length)`. Here:\n\n* `B` is the batch size,\n* `K` represents different sources of information,\n* `context_length` is the context length\n\nFor any given sample, only a subset of these `K` sources contain meaningful information, while the rest are padded. When the sparsity in `K` is high (i.e., most sources are padded), this leads to inefficiencies in training due to unnecessary computations.\n\n### Proposed Idea\n\nTo address this, I’m thinking of implementing a custom `DataLoader`. The idea is:\n\n1. For each sample, load only the non-padded (dense) parts of the `K` dimension.\n2. While filling a batch, ensure that all sources for a single sample remain together (i.e., no scattering across batches). Continue sampling until the batch is complete.\n\nThe goal is to avoid padded computations.\n\n### Questions\n\n* Has anyone implemented something similar, or is there a built-in PyTorch feature that could help with this?\n* Are there any suggestions or best practices for efficiently implementing such a custom `DataLoader`?","reference_answer":"Thank you for the contribution. The problem can be addressed easily using a **custom Sampler** that shuffles the dataset and composes batches **before the epoch starts**. The batching logic ensures that:\n\n1. **Samples remain coherent**: All sources for a single sample are kept together within the same batch, avoiding scattering across batches.\n2. **Batch size constraints are respected**: The sum of non-zero entries in the `K` dimension across all samples in a batch does not exceed the specified `max_batch_size`.\n\nZero entries can then be removed.","needs_clarification":false,"thread_id":215034,"url":"https://discuss.pytorch.org/t/handling-sparse-batches-to-speed-up-training/215034","created_at":"2025-01-06T15:37:26.418000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["czuczo_morales"],"answered_by_ptrblck":false} {"question":"Use Executorch's Module Extension API on arm64 Mac\n\nI want to run a small MLP in the Executorch runtime (eventually on android, currently on arm64 Mac).\nFor the start I just cloned the Executorch Repo and set everything up.\nI can build and run the `executor_runner` without problems.\nI then started to edit the `executor_runner` so that it matches my needs. \nProblem is, as soon as I start using the Module Extension API, which would ease things, I get the below error when calling Cmake.\nI added the `module.h` to the `targets.bzl` and #included it in the `executor_runner.cpp`. \n\n```\nUndefined symbols for architecture arm64:\n \"executorch::extension::Module::Module(std::__1::basic_string, std::__1::allocator> const&, executorch::extension::Module::LoadMode, std::__1::unique_ptr>)\", referenced from:\n _main in executor_runner.cpp.o\nld: symbol(s) not found for architecture arm64\nc++: error: linker command failed with exit code 1 (use -v to see invocation)\nmake[2]: *** [executor_runner] Error 1\nmake[1]: *** [CMakeFiles/executor_runner.dir/all] Error 2\nmake: *** [all] Error 2\n```\n\nI am new to Executorch and also not a pro in c++ and Cmake. \n\nExecutorch: release/0.4\nMacBook Air M3 (arm64)","reference_answer":"Hi @simonsasse, thanks for the additional context. \n\nSo executor_runner is built in the [root CMakeLists.txt file]( https://github.com/pytorch/executorch/blob/main/CMakeLists.txt#L808-L835), set to ON by default.\n\nAnd Module is built in the root CMakeLists.txt file if [`EXECUTORCH_BUILD_EXTENSION_MODULE=ON`](https://github.com/pytorch/executorch/blob/main/CMakeLists.txt#L692), it is OFF by default.\n\nI think the missing pieces are:\n1. Set `EXECUTORCH_BUILD_EXTENSION_MODULE=ON` in the root CMakeLists.txt, to build the Module library. This will build the targets [`extension_module`, `extension_module_static`](https://github.com/pytorch/executorch/blob/main/extension/module/CMakeLists.txt#L49).\n2. Link `extension_module` or `extension_module_static` as a library to your target, eg., `target_link_libraries({your_target_name} extension_module)`\n\n[See this example](https://github.com/pytorch/executorch/pull/7557). It might be better to create a separate CMakeLists.txt file rather than putting it into the root, but hopefully this helps.","needs_clarification":true,"thread_id":215068,"url":"https://discuss.pytorch.org/t/use-executorchs-module-extension-api-on-arm64-mac/215068","created_at":"2025-01-07T11:43:19.773000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["lucylq"],"answered_by_ptrblck":false} {"question":"The scope of `torch.no_grad` and `torch.inference_mode`\n\nHow deep is the scope of `torch.no_grad` and `torch.inference_mode`?\n\nAt the following code:\n\n```python\nwith torch.no_grad():\n y = my_fun(my_tensor)\n```\n\nWill it affect `my_fun`? Or must I add `@torch.no_grad` in its definition? \nWhat if tensors are generated within `my_fun`?\n\nI assume the answer `torch.inference_mode` will hold for as well.","reference_answer":"The context is applied to all methods invoked inside it unless a new context manager is used (at a nested level) changing the behavior.","needs_clarification":false,"thread_id":215094,"url":"https://discuss.pytorch.org/t/the-scope-of-torch-no-grad-and-torch-inference-mode/215094","created_at":"2025-01-08T04:50:22.062000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"How can I decrease the pytorch confidence to hold too much reserved memory\n\nIn 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 the memory? Or, if it's possible we can add our own memory management logic to the Pytorch backend? \n[image]","reference_answer":"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 via `PYTORCH_NO_CUDA_MEMORY_CACHING=1`.\nTo implement your own allocator you can use the `CUDAPluggableAllocator` as described [here](https://pytorch.org/docs/stable/notes/cuda.html#using-custom-memory-allocators-for-cuda) or a custom [`MemPool`](https://pytorch.org/docs/stable/generated/torch.cuda.MemPool.html#mempool).","needs_clarification":false,"thread_id":215108,"url":"https://discuss.pytorch.org/t/how-can-i-decrease-the-pytorch-confidence-to-hold-too-much-reserved-memory/215108","created_at":"2025-01-08T08:56:12.320000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Is my nn.Sequential starting warm during each gridsearch loop?\n\nI recently migrated my project from sk-learn to pytorch, so my implementation might be way off.\n\nI 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 expected. So I am wondering if the nn's weights are not actually being cleared between iterations. Below is my implementation:\n\n```\nregr = nn.Sequential(\n nn.Linear(6, 20),\n nn.ReLU(),\n nn.Linear(20,20),\n nn.ReLU(),\n nn.Linear(20,20),\n nn.ReLU(),\n nn.Linear(20,20),\n nn.ReLU(),\n nn.Linear(20,1)\n).to(device)\n```\n\n```\nfor hyperparameter in hyperparameters:\n optimizer = torch.optim.Adam(regr.parameters(), lr=0.001)\n for epoch in range(n_epochs):\n loss = custom_loss()\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n```\nI would have expected each new hyperparameter loop to create a new instance of the optimizer object. This may not be the case. What is a better approach?\n\nI have left out some details. I am hoping this is enough but I am happy to provide more code if not.","reference_answer":"You could call the `reset_parameters()` method on all registered modules. Something like this should work:\n```python\nfor module in model.modules():\n if hasattr(module, \"reset_parameters\"):\n module.reset_parameters()\n```\nor you could simply recreate the model and optimizer:\n```python\nregr = nn.Sequential(\n nn.Linear(6, 20),\n nn.ReLU(),\n nn.Linear(20,20),\n nn.ReLU(),\n nn.Linear(20,20),\n nn.ReLU(),\n nn.Linear(20,20),\n nn.ReLU(),\n nn.Linear(20,1)\n).to(device)\noptimizer = torch.optim.Adam(regr.parameters(), lr=0.001)\n```\ninside the `hyperparamters` loop.","needs_clarification":false,"thread_id":215139,"url":"https://discuss.pytorch.org/t/is-my-nn-sequential-starting-warm-during-each-gridsearch-loop/215139","created_at":"2025-01-08T22:25:33.869000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"What is the uplimit of dynamo graph cache?\n\nI am curious about the uplimit of dynamo graph cache. If there are too many graph breaks or too many kinds of guards for full graph, will dynamo save all compiled graph for users?\n\nOn the other hand, if dynamo will discard some graphs by order when cache is full, does that means we always need to recompile the model in some conditions?","reference_answer":"You can bump “torch._dynamo.recompile_limit” and “torch._dynamo.accumulated_recompile_limit” to a higher value if you want compile to support storing a larger number of compiled graphs for a given frame.\n\nAlthough generally the reason that those defaults are set is that:\n\n(1) have an extremely large number of recompiles, you will probably suffer from pretty long compile times\n\n(2) a large number of recompiles can often indicate that there is some code in your model that we might be (unnecessarily) specializing on, that you can fix with some model tweaks.\n\nDo you know what’s causing all of the recompiles you’re seeing? You can diagnose by running with “TORCH_LOGS=recompiles” and dumping the output","needs_clarification":false,"thread_id":215145,"url":"https://discuss.pytorch.org/t/what-is-the-uplimit-of-dynamo-graph-cache/215145","created_at":"2025-01-09T02:26:13.918000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["bdhirsh"],"answered_by_ptrblck":false} {"question":"Can I rotate two dimensional images (e.g. MNIST) without having to unsqueeze each one?\n\nI'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?\n\nWhen I try to do the following:\n```\ntest = transforms.functional.rotate(dataset1.data[0], 90)\n```\nI get an error:\n> grid_sampler(): expected grid to have size 1 in last dimension, but got grid with sizes [1, 28, 28, 2]\n\nThis can be fixed by unsqueezing and squeezing the image\n```\ntest = torch.unsqueeze(dataset1.data[0], 0)\ntest = transforms.functional.rotate(test, 90)\ntest = torch.squeeze(test, 0)\n```\nhowever this seems quite unnecessary and inefficient. Is there a way to avoid this?\n\nI'm also not sure if this type of iterative approach is correct when it comes to creating this type of dataset, but is seems to me that there is no easy way to apply random rotation to all images, while keeping all of the angles saved somewhere (which is where torchvision.transforms.RandomRotation fails for me).","reference_answer":"It'll work without unsqueezing the raw data if you iterate the tensors:\n```python\ndataset = datasets.MNIST(root=root, download=False, transform=transforms.ToTensor())\ndata, target = next(iter(dataset))\n\ntest = transforms.functional.rotate(data, 90)\n```","needs_clarification":false,"thread_id":215191,"url":"https://discuss.pytorch.org/t/can-i-rotate-two-dimensional-images-e-g-mnist-without-having-to-unsqueeze-each-one/215191","created_at":"2025-01-10T07:45:35.119000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Do I need to use nn.Parameter() again when changing a tensor wrapped in nn.Parameter()?\n\nI have the following code (removed some parts for clarity):\n```\nclass Cell(nn.Module):\n def __init__(self, core_size, conn_size, conn_num):\n super().__init__()\n [...]\n core = torch.Tensor(core_size)\n self.core = nn.Parameter(core)\n nn.init.ones_(self.core)\n\n def forward(self, x):\n [...]\n self.core = torch.mul(self.core, x)\n [...]\n```\nThen I try to run it I get an error related to the operation in forward:\n> cannot assign 'torch.FloatTensor' as parameter 'core' (torch.nn.Parameter or None expected)\n\nI'm trying to change the self.core parameter based on the input and keep it stored within the model. Do I need to use torch.nn.Parameter again when adjusting the self.core parameter (e.q. self.core = torch.nn.Parameter(torch.mul(self.core, x)))? Would doing so reset the grad of self.core?","reference_answer":"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. Something like this should work:\n```python\ndef forward(self, x):\n [...]\n out = torch.mul(self.core, x)\n with torch.no_grad():\n self.core.copy_(out)\n [...]\n```\nHowever, make sure this is really what you want since you are creating a trainable parameter but are not using its gradients and would be updating it manually.","needs_clarification":false,"thread_id":215213,"url":"https://discuss.pytorch.org/t/do-i-need-to-use-nn-parameter-again-when-changing-a-tensor-wrapped-in-nn-parameter/215213","created_at":"2025-01-10T14:50:53.511000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"FSDP2 evaluate during training\n\nHi team, I am using the [FSDP2](https://github.com/pytorch/torchtitan/blob/main/docs/fsdp.md) to shard my model.\nWhat is the best practice to evaluate (like calling `eval_forward` for the module) during training here?\n\nI know we can register_forward hooks for `eval_forward` but it might call some unused hooks.\nCan I make it back to non-FSDP module and shard again after I finish the evaluation?","reference_answer":"I have to do some hacky way:\n```\ndef hack_unwrap_the_fsdp(model):\n fs_storage_writer = FileSystemWriter(SAVED_PATH)\n save(\n state_dict=model.state_dict(),\n storage_writer=fs_storage_writer,\n )\n unwrapped_model = ToyModel().cuda()\n fs_reader = FileSystemReader(SAVED_PATH)\n state_dict = unwrapped_model.state_dict()\n load(state_dict, storage_reader=fs_reader)\n unwrapped_model.load_state_dict(state_dict) \n return unwrapped_model\n```\nAnd `unwrapped_model` is not sharded. Not sure if there is better way.","needs_clarification":false,"thread_id":215240,"url":"https://discuss.pytorch.org/t/fsdp2-evaluate-during-training/215240","created_at":"2025-01-11T00:56:52.736000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["XYG_123"],"answered_by_ptrblck":false} {"question":"How to create a DistributedSampler based on my own Sampler\n\nI have implement a `Sampler` when using single GPU. I implement it because I want all samples in a batch are from the same source.\n```\nclass MultiSourceBatchSampler(torch.utils.data.Sampler):\n def __init__(\n self,\n data_source: Dataset,\n # sources: list,\n batch_size: int,\n shuffle: bool = False,\n drop_last: bool = False,\n ):\n self.data_source = data_source\n # self.sources = sources\n self.batch_size = batch_size\n self.shuffle = shuffle\n self.drop_last = drop_last\n\n self._length = -1\n \n def __iter__(self):\n # indices are tuples (source, second_key)\n indices = self.data_source._get_indices()\n if self.shuffle:\n np.random.shuffle(indices)\n indices.sort(key=lambda x: x[0]) #sort by source\n\n batched_indices = []\n buffer = []\n for index in indices:\n if (len(buffer) == self.batch_size) or (len(buffer) > 0 and buffer[0][0] != index[0]):\n batched_indices.append(buffer)\n buffer = []\n buffer.append(index)\n if len(buffer) > 0 and not self.drop_last:\n batched_indices.append(buffer)\n \n if self.shuffle:\n np.random.shuffle(batched_indices)\n yield from batched_indices\n\n def __len__(self):\n if self._length >= 0:\n return self._length\n total = 0\n indices = self.data_source._get_keys(by=self.by)\n indices.sort(key=lambda x: x[0]) #sort by source\n\n buffer = []\n for index in indices:\n if (len(buffer) == self.batch_size) or (len(buffer) > 0 and buffer[0][0] != index[0]):\n total += 1\n buffer = []\n buffer.append(index)\n if len(buffer) > 0 and not self.drop_last:\n total += 1\n self._length = total\n return total\n```\n\nI did not find very detailed documentation about `DistributedSampler`, so I wonder what is the principle if I want to convert my sampler to a DistributedSampler","reference_answer":"A possible general solution:\n```python\nclass DistributedSamplerWrapper(torch.utils.data.distributed.DistributedSampler):\n def __init__(\n self,\n base_sampler,\n num_replicas = None,\n rank = None,\n seed = 0,\n ):\n self.base_sampler = base_sampler\n self.batch_size = base_sampler.batch_size\n shuffle = self.base_sampler.shuffle\n drop_last = self.base_sampler.drop_last\n super().__init__(base_sampler, num_replicas=num_replicas, rank=rank, shuffle=shuffle, seed=seed, drop_last=drop_last)\n\n def __iter__(self):\n base_indices = list(self.base_sampler.__iter__())\n if self.shuffle:\n # deterministically shuffle based on epoch and seed\n g = torch.Generator()\n g.manual_seed(self.seed + self.epoch)\n indices = torch.randperm(len(self.dataset), generator=g).tolist() # type: ignore[arg-type]\n else:\n indices = list(range(len(self.dataset))) # type: ignore[arg-type]\n indices = [base_indices[i] for i in indices]\n \n if not self.drop_last:\n # add extra samples to make it evenly divisible\n padding_size = self.total_size - len(indices)\n if padding_size <= len(indices):\n indices += indices[:padding_size]\n else:\n indices += (indices * math.ceil(padding_size / len(indices)))[\n :padding_size\n ]\n else:\n # remove tail of data to make it evenly divisible.\n indices = indices[: self.total_size]\n assert len(indices) == self.total_size\n\n # subsample\n indices = indices[self.rank : self.total_size : self.num_replicas]\n assert len(indices) == self.num_samples\n\n return iter(indices)\n```\n\nShould be passed as the `batch_sampler` argument.","needs_clarification":false,"thread_id":215244,"url":"https://discuss.pytorch.org/t/how-to-create-a-distributedsampler-based-on-my-own-sampler/215244","created_at":"2025-01-11T01:52:41.394000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["Boltzmachine"],"answered_by_ptrblck":false} {"question":"FSDP memory higher than DDP or single gpu\n\nI 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 memory than ddp.\nIt may be a bug in pytorch?","reference_answer":"Did you try `FSDP2`, as it's supposed to use less memory? From the [RFC](https://github.com/pytorch/pytorch/issues/114299):\n> We have validated the prototype on Llama-like models, achieving on-par throughput while using less memory.","needs_clarification":false,"thread_id":215337,"url":"https://discuss.pytorch.org/t/fsdp-memory-higher-than-ddp-or-single-gpu/215337","created_at":"2025-01-13T18:53:23.073000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"TensorRT: Errors in PTQ Example\n\nI was trying to follow the TensorRT PTQ examples here to implement INT8 quantization using TensorRT:\nhttps://pytorch.org/TensorRT/ts/ptq.html#how-to-create-your-own-ptq-application-in-python\n\nHowever, if I try to use torch_tensorrt.ptq.DataLoaderCalibrator() and torch_tensorrt.ptq.CalibrationAlgo.ENTROPY_CALIBRATION_2, I get following error message: AttributeError: module 'torch_tensorrt' has no attribute 'ptq'.\n\nI found in another place that the ptq module was available under ts (seems to be up-to-date w.r.t. the Github repo), so I also tried:\ntorch_tensorrt.ts.ptq.DataLoaderCalibrator()\nand torch_tensorrt.ts.CalibrationAlgo.ENTROPY_CALIBRATION_2,\nbut the result was the same:\nAttributeError: module 'torch_tensorrt.ts' has no attribute 'ptq'\n\nI am using following versions under Python 3.11:\n * tensorrt 10.3.0\n * torch 2.5.1\n * torch_tensorrt 2.5.0\n * nvidia-modelopt 0.21.1\n\nI think the examples given under https://pytorch.org/TensorRT/ts/ptq.html#how-to-create-your-own-ptq-application-in-python don't refer to the current module structure.\nCan you give me a hint here and possibly update the example?\n\nCheers,\nTim","reference_answer":"The quantization API from TensorRT has been deprecated so this API doesn't really work anymore and will be removed soon. You can use model-opt + the dynamo frontend to do this now. https://pytorch.org/TensorRT/tutorials/_rendered_examples/dynamo/vgg16_ptq.html","needs_clarification":false,"thread_id":215386,"url":"https://discuss.pytorch.org/t/tensorrt-errors-in-ptq-example/215386","created_at":"2025-01-14T17:41:05.390000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["narendasan"],"answered_by_ptrblck":false} {"question":"Slow performance when running TransformerDecoder with low batch size in fp16\n\nHey!\n\nI want to understand why this snippet of code runs slow for batch sizes of 2/4/8 when using fp16, the time it takes for bs=2 on my system is 0.55 sec for no batch version and 2.8 sec for the batched on.\n\n```\nfrom torch import nn\nimport torch\nimport time\nfrom torch.amp import autocast\ndevice = torch.device('cuda')\n\nhidden_dim = 1024\nUSE_FP16 = True\nBS = 2\nTOTAL_INPUT = 250\ndecoder_layer = nn.TransformerDecoderLayer(d_model=hidden_dim,\n dim_feedforward=hidden_dim*4,nhead=8,batch_first=True,)\ntransformer_decoder = nn.TransformerDecoder(decoder_layer, num_layers=3,).to(device)\n\nwith autocast('cuda', enabled=USE_FP16):\n with torch.no_grad():\n memory = torch.rand((1, 1000, hidden_dim), device=device)\n tgt = torch.rand((1, 36, hidden_dim), device=device)\n out = transformer_decoder(tgt, memory)\n s = time.perf_counter()\n for _ in range(TOTAL_INPUT):\n out = transformer_decoder(tgt, memory)\n print(time.perf_counter() - s)\n\n memory = torch.rand((BS, 1000, hidden_dim), device=device)\n tgt = torch.rand((BS, 36, hidden_dim), device=device)\n\n s = time.perf_counter()\n for _ in range(TOTAL_INPUT // BS):\n out = transformer_decoder(tgt, memory)\n print(time.perf_counter() - s)\n```\nThis is also reproduced in google colab\nThanks!","reference_answer":"You add overhead by imposing batch_first. Namely, the model has to internally transpose dimensions and that extra computation make sthe whole thing slower.\n\nhttps://colab.research.google.com/drive/1ez07w-0tnAZWA36OLgHYIXDgMxkRGAfa?usp=sharing","needs_clarification":false,"thread_id":215434,"url":"https://discuss.pytorch.org/t/slow-performance-when-running-transformerdecoder-with-low-batch-size-in-fp16/215434","created_at":"2025-01-15T17:31:51.391000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["JuanFMontesinos"],"answered_by_ptrblck":false} {"question":"Loss.backward() called after torch.nograd()\n\nHi, i'm working my way through the Dive Into Deep Learning book and found the following code (pasted below or linked [here](https://d2l.ai/chapter_linear-regression/linear-regression-scratch.html)). I'm confused on how this function still trains the linear regression model since it calls for loss.backward() after loss.no_grad()?\nThank you so much for your help!\n\n```\n@d2l.add_to_class(d2l.Trainer) #@save\ndef fit_epoch(self):\n self.model.train()\n for batch in self.train_dataloader:\n loss = self.model.training_step(self.prepare_batch(batch))\n self.optim.zero_grad()\n with torch.no_grad():\n loss.backward()\n if self.gradient_clip_val > 0: # To be discussed later\n self.clip_gradients(self.gradient_clip_val, self.model)\n self.optim.step()\n self.train_batch_idx += 1\n if self.val_dataloader is None:\n return\n self.model.eval()\n for batch in self.val_dataloader:\n with torch.no_grad():\n self.model.validation_step(self.prepare_batch(batch))\n self.val_batch_idx += 1\n```","reference_answer":"The forward pass runs outside the `no_grad` block, so the computation graph is built and the intermediate activations needed for gradients are saved. `loss.backward()` and `optim.step()` don't need to run in a `no_grad` context, so that block can be dropped.","needs_clarification":false,"thread_id":215480,"url":"https://discuss.pytorch.org/t/loss-backward-called-after-torch-nograd/215480","created_at":"2025-01-16T15:42:16.612000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,4],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Is cuda installed automatically when following pytorch instlalation directions?\n\nI 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 in https://pytorch.org/get-started/locally/. If it is installed, where it is installed? \n\nIf it's not installed, some feedback is it would be helpful to mention that you need to install it separately. \n\nThanks for making pytorch!","reference_answer":"The PyTorch binaries ship with their own CUDA *runtime* dependencies, but do not install a full CUDA toolkit (for development).\nYour `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 a [source distribution](https://pypi.org/project/flash-attn/2.7.3/#files) only (not wheels).","needs_clarification":false,"thread_id":215493,"url":"https://discuss.pytorch.org/t/is-cuda-installed-automatically-when-following-pytorch-instlalation-directions/215493","created_at":"2025-01-16T23:05:37.427000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Training converges on cpu but never on gpu\n\nHi,\nfor the script below my training always converges on CPU and solves the environment. However if I switch DEVICE to cuda it actually never converges.\n\nmy python env: torch 2.5.1, torchrl 0.6.0, tensordict 0.6.2\n\nWhat I tried so far:\n* I also tried running the code on the nightly version of torchrl and the behaviour stayed the same.\n* I verified that my gpu is working correctly, I also was able to run the torchrl PPO Tutorial successfully on gpu.\n* i ran the scripts on my workplaces gpu server as well as on a separate windows laptop using torchrl-nightly and the behaviour still persists\n\nThis leads me to conclude that I have some hidden bug in my script or did not use torchrl correctly. I would be really thankful for any pointer on what to look at.\n\nNote: I also posted this on the torchrl github under discussion, but hope that it maybe finds more attention here.\n```\nimport logging\nimport time\n\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom tensordict.nn import TensorDictSequential as TDSeq\n\nfrom torchrl.collectors import SyncDataCollector\nfrom torchrl.data import LazyTensorStorage, ReplayBuffer\nfrom torchrl.envs import GymEnv, TransformedEnv, StepCounter, RewardSum, Compose\nfrom torchrl.modules import EGreedyModule, QValueActor\nfrom torchrl.objectives import DQNLoss, SoftUpdate\n\nlogging.basicConfig(level=logging.INFO)\nmy_logger = logging.getLogger(__name__)\n\nENV_NAME = \"CartPole-v1\"\nDEVICE = \"cuda\"\n\nINIT_RND_STEPS = 5_120\nFRAMES_PER_BATCH = 128\nBUFFER_SIZE = 100_000\n\nGAMMA = 0.98\nOPTIM_STEPS = 10\nBATCH_SIZE = 128\n\nSOFTU_EPS = 0.99\nLR = 0.02\n\nclass Net(nn.Module):\n def __init__(self, obs_size: int, n_actions: int) -> None:\n super().__init__()\n self.net = nn.Sequential(\n nn.Linear(obs_size, 128),\n nn.ReLU(),\n nn.Linear(128, n_actions),\n )\n\n def forward(self, x):\n orig_shape_unbatched = len(x.shape) == 1\n if orig_shape_unbatched:\n x = x.unsqueeze(0)\n\n out = self.net(x)\n\n if orig_shape_unbatched:\n out = out.squeeze(0)\n return out\n\ndef make_env(env_name: str):\n return TransformedEnv(\n GymEnv(env_name),\n Compose(\n StepCounter(),\n RewardSum()\n )\n )\n\nif __name__ == \"__main__\":\n env = make_env(ENV_NAME)\n n_obs = env.observation_spec[\"observation\"].shape[-1]\n n_act = env.action_spec.shape[-1]\n\n net = Net(n_obs, n_act).to(device=DEVICE)\n agent = QValueActor(net, spec=env.action_spec)\n policy_explore = EGreedyModule(env.action_spec)\n agent_explore = TDSeq(agent, policy_explore)\n\n collector = SyncDataCollector(\n env,\n agent_explore,\n frames_per_batch=FRAMES_PER_BATCH,\n init_random_frames=INIT_RND_STEPS,\n device=DEVICE,\n )\n exp_buffer = ReplayBuffer(storage=LazyTensorStorage(BUFFER_SIZE))\n\n loss = DQNLoss(value_network=agent, action_space=env.action_spec, delay_value=True)\n loss.make_value_estimator(gamma=GAMMA)\n target_updater = SoftUpdate(loss, eps=SOFTU_EPS)\n optimizer = optim.Adam(loss.parameters(), lr=LR)\n\n total_count = 0\n total_episodes = 0\n t0 = time.time()\n for i, data in enumerate(collector):\n exp_buffer.extend(data)\n max_length = exp_buffer[\"next\", \"step_count\"].max()\n max_reward = exp_buffer[\"next\", \"episode_reward\"].max()\n if len(exp_buffer) > INIT_RND_STEPS:\n for _ in range(OPTIM_STEPS):\n optimizer.zero_grad()\n sample = exp_buffer.sample(batch_size=BATCH_SIZE)\n sample = sample.to(DEVICE)\n\n loss_vals = loss(sample)\n loss_vals[\"loss\"].backward()\n optimizer.step()\n\n agent_explore[1].step(data.numel())\n target_updater.step()\n\n total_count += data.numel()\n total_episodes += data[\"next\", \"done\"].sum()\n\n if i % 10 == 0:\n my_logger.info(f\"Step: {i}, max. count / epi reward: {max_length} / {max_reward}.\")\n\n if max_length > 200:\n t1 = time.time()\n my_logger.info(f\"SOLVED in {t1 - t0}s!! MaxLen: {max_length}!\")\n my_logger.info(f\"With {max_reward} Reward!\")\n my_logger.info(f\"In {total_episodes} Episodes!\")\n break\n```","reference_answer":"The policy was not fully on CUDA: the exploration module stayed on the CPU. The collector sends everything to CUDA, and a bug made it lose track of the original tensors. The simplest fix is to move the exploration policy to the device: `agent_explore = agent_explore.to(device)`.\n\nIf you don't do that, use the latest changes from GitHub (not the nightly build) and call `collector.update_policy_weights_()` just after your model update:\n\n```python\n[...]\n total_count += data.numel()\n total_episodes += data[\"next\", \"done\"].sum()\n\n if i % 10 == 0:\n my_logger.info(f\"Step: {i}, max. count / epi reward: {max_length} / {max_reward}.\")\n collector.update_policy_weights_()\n```\n\nThe `update_policy_weights_()` call only fixes the problem when the collector's device is `cpu`. With `device=\"cuda\"` the run still does not converge, so use the `.to(device)` fix.","needs_clarification":false,"thread_id":215547,"url":"https://discuss.pytorch.org/t/training-converges-on-cpu-but-never-on-gpu/215547","created_at":"2025-01-18T10:19:06.051000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4,5,6],"answer_authors":["ozhicha","vmoens"],"answered_by_ptrblck":false} {"question":"\"input types can't be cast to the desired output type Long\"\n\nI'm trying to make a NN learn to play the [CartPole-v1](https://www.gymlibrary.dev/environments/classic_control/cart_pole/) game from gymnasium, and I followed a similar setup to the one in this tutorial:\nhttps://pytorch.org/tutorials/intermediate/reinforcement_ppo.html , only changing a few parameters to make it work with the cart pole game and not the original double pendulum. \nI get this error, probably due to my setup of collector: \n```\nC:\\programming\\zoomino 8\\blockblastpy\\.venv3.12\\Lib\\site-packages\\tensordict\\_td.py:2663: UserWarning: An output with one or more elements was resized since it had shape [1000, 2], which does not match the required output shape [1000, 1]. This behavior is deprecated, and in a future PyTorch release outputs will not be resized unless they have zero elements. You can explicitly reuse an out tensor t by resizing it, inplace, to zero elements with t.resize_(0). (Triggered internally at C:\\actions-runner\\_work\\pytorch\\pytorch\\builder\\windows\\pytorch\\aten\\src\\ATen\\native\\Resize.cpp:35.)\n new_dest = torch.stack(\nTraceback (most recent call last):\n File \"C:\\programming\\zoomino 8\\blockblastpy\\rl\\torchrl\\collectors\\collectors.py\", line 1225, in rollout\n result = torch.stack(\n ^^^^^^^^^^^^\n File \"C:\\programming\\zoomino 8\\blockblastpy\\.venv3.12\\Lib\\site-packages\\tensordict\\base.py\", line 633, in __torch_function__\n return TD_HANDLED_FUNCTIONS[func](*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"C:\\programming\\zoomino 8\\blockblastpy\\.venv3.12\\Lib\\site-packages\\tensordict\\_torch_func.py\", line 666, in _stack\n out._stack_onto_(list_of_tensordicts, dim)\n File \"C:\\programming\\zoomino 8\\blockblastpy\\.venv3.12\\Lib\\site-packages\\tensordict\\_td.py\", line 2663, in _stack_onto_\n new_dest = torch.stack(\n ^^^^^^^^^^^^\nRuntimeError: torch.cat(): input types can't be cast to the desired output type Long\n```\nHere's my code:\n```py\n\nimport torch\nfrom torch import nn\nfrom torchrl.collectors import SyncDataCollector\nfrom torchrl.envs import (Compose, DoubleToFloat, StepCounter,\n TransformedEnv)\nfrom torchrl.envs.libs.gym import GymEnv\nfrom torchrl.modules import Actor\n\nis_fork = multiprocessing.get_start_method() == \"fork\"\ndevice = (\n torch.device(0)\n if torch.cuda.is_available() and not is_fork\n else torch.device(\"cpu\")\n)\nnum_cells = 256 # number of cells in each layer i.e. output dim.\nframes_per_batch = 1000\n# For a complete training, bring the number of frames up to 1M\ntotal_frames = 50_000\n\nbase_env = GymEnv(\"CartPole-v1\", device=device)\nenv = TransformedEnv(\n base_env,\n Compose(\n DoubleToFloat(),\n StepCounter(),\n ),\n)\n\nactor_net = nn.Sequential(\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(1, device=device), # Ensure correct output size\n nn.Sigmoid()\n)\npolicy_module = Actor(\n module=actor_net,\n in_keys=[\"observation\"],\n out_keys=[\"action\"],\n spec=env.action_spec\n)\ncollector = SyncDataCollector(\n env,\n policy_module,\n frames_per_batch=frames_per_batch,\n total_frames=total_frames,\n split_trajs=False,\n device=device,\n)\n\nfor i, data in enumerate(collector):\n print(i)\n```\n\nI'm very new to PyTorch and I've tried to understand the cause of the error, but couldn't.","reference_answer":"Sigmoid maps your action from [-inf; inf] to [0, 1]\nWhat you want is an action that is either 0 or 1 (if you're using categorical specs) or [0, 1] / [1, 0] if you're using one-hot (the default).\n\nI edited your script to map the sigmoid to a binary 0 / 1 value, and also made sure the env was using categorical specs and not one hot\n```python\nimport multiprocessing\n\nimport torch\nfrom tensordict.nn import TensorDictSequential as Seq\nfrom torch import nn\n\nfrom torchrl.collectors import SyncDataCollector\nfrom torchrl.envs import (Compose, DoubleToFloat, StepCounter,\n TransformedEnv)\nfrom torchrl.envs.libs.gym import GymEnv\nfrom torchrl.modules import Actor\n\nis_fork = multiprocessing.get_start_method() == \"fork\"\ndevice = (\n torch.device(0)\n if torch.cuda.is_available() and not is_fork\n else torch.device(\"cpu\")\n)\nnum_cells = 256 # number of cells in each layer i.e. output dim.\nframes_per_batch = 1000\n# For a complete training, bring the number of frames up to 1M\ntotal_frames = 50_000\n\nbase_env = GymEnv(\"CartPole-v1\", device=device, categorical_action_encoding=True)\nenv = TransformedEnv(\n base_env,\n Compose(\n DoubleToFloat(),\n StepCounter(),\n ),\n)\n\nactor_net = nn.Sequential(\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(1, device=device), # Ensure correct output size\n nn.Sigmoid()\n)\npolicy_module = Seq(\n Actor(\n module=actor_net,\n in_keys=[\"observation\"],\n out_keys=[\"action\"],\n spec=env.action_spec,\n ),\n lambda td: td.set(\"action\", (td.get(\"action\")[0] > 0.5).int())\n)\n\ncollector = SyncDataCollector(\n env,\n policy_module,\n frames_per_batch=frames_per_batch,\n total_frames=total_frames,\n split_trajs=False,\n device=device,\n)\n\nfor i, data in enumerate(collector):\n print(i)\n\n```","needs_clarification":false,"thread_id":215572,"url":"https://discuss.pytorch.org/t/input-types-cant-be-cast-to-the-desired-output-type-long/215572","created_at":"2025-01-19T02:39:45.989000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["vmoens"],"answered_by_ptrblck":false} {"question":"Unexpected behavior when using torch.autograd.functional.jacobian with multiple inputs/outputs neural network\n\nI’m implementing a neural network to solve ODEs. I want to encode several points at once and get several results of the ODE (one result per corresponding input) at the same run.\nCurrently I’m running a toy model where I try to get `u(x)=sin(x)` according to the loss function: `du_dx - cos(x)`.\n\nThe network structure is:\n\n[details=\"network structure\"]\n```\nclass NetworkClass(nn.Module):\n def __init__(self, n_nodes=8):\n super().__init__()\n self.fc_in = nn.Linear(n_nodes, n_nodes)\n self.activation = nn.Tanh()\n self.q_layer = nn.Linear(n_nodes, n_nodes)\n self.activation_2 = nn.Tanh()\n self.fc_out = nn.Linear(n_nodes, n_nodes)\n\n def forward(self, inputs):\n out_fc_in = self.fc_in(inputs.unsqueeze(0))\n out_activation = self.activation(out_fc_in)\n out_q_layer = self.q_layer(out_activation.squeeze(0).squeeze(0))\n out_activation_2 = self.activation_2(out_q_layer)\n out_fc_out = self.fc_out(out_activation_2).squeeze(0).squeeze(0)\n return out_fc_out\n\n```\n[/details]\n\nThe gradients:\n[details=\"gradients\"]\n```\nfor epoch in range(self.epochs):\n u_out_arr = []\n d_u_dx_arr = []\n loss_single_batch_arr = []\n loss_single_batch_no_beta_arr = []\n self.opt.zero_grad(set_to_none=False)\n collocation_points = torch.reshape(self.collocation_points, [self.n_points//self.n_nodes, self.n_nodes])\n u_out = self.model(collocation_points)\n u_out_arr.append(u_out) # for plotting and derivative calculation check\n d_u_dx = torch.zeros(self.n_points)\n for i in range(self.n_batches):\n jac_func = jacobian(self.model, collocation_points[i], create_graph=True, strict=True)\n d_u_dx[i*self.batch_size:(i+1)*self.batch_size] = torch.diag(jac_func, 0)\n d_u_dx_arr.append(d_u_dx)\n loss= self.loss_fn(collocation_points, u=torch.flatten(u_out), d_u_dx=d_u_dx,\n target_fn=self.target_fn_dict)\n loss.backward()\n loss_single_batch_arr.append(loss)\n\n self.opt.step()\n```\n[/details]\n\nWhen computing derivatives using jacobian (only the diagonal because I need each output's derivative with respect to the corresponding input):\n\n* With `in_out_size=1`: derivatives correctly correspond to spatial derivatives\n* With `in_out_size=n_nodes`: derivatives don't match expected spatial derivatives\n\nQuestion: Why does increasing input/output dimensions affect the derivative computation? \n\nAlso, I've found that when adding the term of the original_function_loss to the loss_fn in that manner, when beta weights the loss to the original only (beta =1) or the derivative only (beta = 0) or somewhere in between, enables the network to get the accurate results (which is not surprising) by beta as small as 1e-7 (which is very surprising!):\n```\npde_loss_1 = d_u_dx - target_fn[\"d_u_dx\"](torch.flatten(collocation_point))\noriginal_function_loss = u - target_fn[\"u\"](torch.flatten(collocation_point))\nmse_loss = torch.mean(self.beta * original_function_loss ** 2 + (1 - self.beta) * pde_loss_1 ** 2)\n```\n\nresults for the two cases (without the beta):\n[image]\n\nThanks in advance!","reference_answer":"Hi Ziv!\n\nIf I understand correctly what you are asking, when `in_out_size` is\ngreater than one, the various values along the `n_nodes` dimension\nare mixed together -- multiple time with non-linearities -- so the\ndependence of the, say, first output value on the the first input value\nis not the same as it would have been if `n_nodes` had been one.\nSo even though you only look at the diagonal values of the jacobian,\neven the diagonal values of the jacobian depend on `n_nodes`.\n\nFurthermore -- more trivially -- the weights in the `Linears` are generated\nrandomly and even the \"same\" weight value will differ when using\ndifferent values of `n_nodes`, so the different weight values will lead\nto different values of the jacobian elements.\n\nIf this is not really what you are asking about, please you post a simplified\n(e.g., no need for any loop over epochs), fully-self-contained, runnable\nexample script that shows the differing derivative values, together with\nthe output you get when you run it.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":215580,"url":"https://discuss.pytorch.org/t/unexpected-behavior-when-using-torch-autograd-functional-jacobian-with-multiple-inputs-outputs-neural-network/215580","created_at":"2025-01-19T09:33:34.505000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Problem in Backpropagation through a sample in Beta distribution in pytorch\n\nSay I have obtained some **alphas** and **betas** as parameters from a neural network which will be parameters of the Beta distribution. Now, I sample from the Beta distribution and then calculate some loss and back-propagate via the samples obtained. Is it possible to do that? given that after the sampling process I do **.requires_grad_(True)** to the sample and then compute the loss? This surely works, but it looks like the loss is not converging, is there any other way to do this in Pytorch?\n\nSay, I get the following variables via some neural network:\n\n```python\nmu, sigma, pred = model.forward(input)\n```\nWhere say, **mu** is the (batch_size x 30) shaped tensor, similarly **sigma** is (batch_size x 30) shaped tensor. I compute the **alphas** and **betas** using the **mu** and **sigma** obtained from a Neural Network (both of the same shape (batch_size x 30)), and then sample it via a beta distribution as follows:\n\n```\ndef sample_from_beta_distribution(alpha, beta, eps=1e-6):\n\t# Clamp alpha and beta to be positive\n\talpha_positive = torch.clamp(alpha, min=eps)\n\tbeta_positive = torch.clamp(beta, min=eps)\n \n\t# Create a Beta distribution\n\t# This will automatically broadcast to handle the batch dimension\n\tbeta_dist = torch.distributions.beta.Beta(alpha_positive, beta_positive)\n \n\t# Sample from the distribution\n\t# This will return samples of shape [38, 30]\n\tsamples = beta_dist.sample()\n \n\treturn samples\n```\n\nHere, I take the **samples** which is of the same shape as (batch_size x 30), perform some operations on it, and then calculate the loss. I expected the gradient to propagate through this, but looks like the loss is not converging. \n\nAny leads would help. Please note, this is not as simple as the reparameterization trick in the standard Normal distribution.","reference_answer":"Looks like ```.rsample()``` is doing the trick here, which is keeping the computational graph alive...","needs_clarification":false,"thread_id":215599,"url":"https://discuss.pytorch.org/t/problem-in-backpropagation-through-a-sample-in-beta-distribution-in-pytorch/215599","created_at":"2025-01-19T16:54:31.198000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Jimut123"],"answered_by_ptrblck":false} {"question":"Torch_sparse cannot find cuda lib file from pytorch\n\nI 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 message \n\nOSError: libcusparse.so.10.0: cannot open shared object file: No such file or directory\n\nis produced under one of torch_sparse function. I thought that pytorch is shipped with cuda dependencies, or is it not true for the older pytorch versions. So, I'm not sure what is the problem with my set up.","reference_answer":"torch_sparse loads libcudart.so directly, and the wheel doesn't ship it. The PyTorch binaries ship their own CUDA runtime with a SHA value in its name (`libcudart-.so.10.1`), so this older release appears to need a locally installed CUDA toolkit. You can install CUDA 10.0 alongside your 11.8 toolkit and create the `/usr/local/cuda` symlink to the version you want to use.","needs_clarification":false,"thread_id":215733,"url":"https://discuss.pytorch.org/t/torch-sparse-cannot-find-cuda-lib-file-from-pytorch/215733","created_at":"2025-01-22T21:56:45.806000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4,6],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Gradcheck fails for custom activation function\n\nI am implementing this activation function:\n```\nclass EOActivation(Function):\n '''\n Electro-optic activations as described in - \n {Williamson, Ian AD, et al. \"Reprogrammable electro-optic nonlinear \n activation functions for optical neural networks.\" IEEE Journal of \n Selected Topics in Quantum Electronics 26.1 (2019): 1-12.}\n '''\n @staticmethod\n def forward(Z: Tensor,\n alpha: Tensor,\n g: Tensor,\n phi_b: Tensor) -> Tensor:\n '''\n Forward-pass of EO nactivation function\n Z: tensor, Input tensor\n alpha: tensor, parameter 'alpha'\n g: tensor, parameter 'g'\n phi_b: tensor, parameter 'phi_b'\n '''\n return 1j * torch.sqrt(1 - alpha) * torch.exp(\n -1j*0.5*g*torch.conj(Z)*Z - 1j*0.5*phi_b) * torch.cos(\n 0.5*g*torch.conj(Z)*Z + 0.5*phi_b) * Z\n \n @staticmethod\n def setup_context(ctx, inputs, output):\n '''\n ctx: Context object\n inputs: Inputs are the inputs to forward()\n output: Output tensor of forward()\n '''\n # Save parameters and output of forward for backward pass\n input, alpha, g, phi_b = inputs\n ctx.save_for_backward(input, alpha, g, phi_b)\n \n @staticmethod\n def backward(ctx, grad_Z: Tensor) -> Tensor:\n '''\n ctx: context object\n grad_Z: backpropagated gradient signal from (l+1)th layer\n '''\n # get the parameters and output field computed during forward-pass\n Z, alpha, g, phi_b = ctx.saved_tensors\n zR, zI = Z.real, Z.imag\n # df_dRe - Gradient w.r.t. real part of the input\n df_dRe = torch.sqrt(1 - alpha) * torch.exp((-0.5*1j)*g*(zR - 1j*zI)*(zR + 1j*zI) - (\n 0.5*1j)*phi_b) * (zR*g*(zI - 1j*zR) * torch.sin(0.5*(zR**2)*g + 0.5*(\n zI**2)*g + 0.5*phi_b) + ((zR**2)*g + 1j*zR*zI*g + 1j) * torch.cos(\n 0.5*(zR**2)*g + 0.5*(zI**2)*g + 0.5*phi_b))\n #df_dIm - Gradient w.r.t. imaginary part of the input\n df_dIm = torch.sqrt(1 - alpha) * torch.exp((-0.5*1j)*g*(zR - 1j*zI)*(zR + 1j*zI) - (\n 0.5*1j) * phi_b) * (zI*g*(zI - 1j*zR) * torch.sin(0.5*(zR**2)*g + 0.5*(\n zI**2)*g + 0.5*phi_b) + (zR*zI*g + 1j*(zI**2)*g - 1) * torch.cos(\n 0.5*(zR**2)*g + 0.5*(zI**2)*g + 0.5*phi_b))\n # Return the gradient and 'None' for parameters in forward()\n return (grad_Z*df_dRe).real - 1j*(grad_Z*df_dIm).real, None, None, None\n```\nwhere alpha, g and phi_b are constant parameters initialized as tensors with \"requires_grad=False\". The function is applied in a layer class whose forward() looks like this:\n```\ndef forward(self, Z: Tensor) -> Tensor:\n '''\n Z: Input tensor from (l-1)th layer\n Z_out: Output tensor after forward propagation (activation)\n '''\n Z = EOActivation.apply(Z, self.alpha, self.g, self.phi_b) \n if self.photodetect:\n Z = Z.square()\n if self.bias is not None:\n Z = Z + self.bias.unsqueeze(0)\n\n return Z\n```\nlet's say \"photodetect\" and \"bias\" are always \"False\".\n\nMy problem is that the activation does not work as expected. When used as part of a neural network, it fails to learn. I am compraing the equations with another [implementation](https://github.com/Xoreus/neuroptica/blob/b0b4fad56af6002c3d852583be86393901c00dd3/neuroptica/nonlinearities.py#L153) and the calculations seem to be correct. My gradcheck output looks like this:\n[image]\nLooks like there is a sign mismatch. Can anyone please tell me if I am missing any properties in my implementation? Or if I need to take any additional care for handling the gradients?","reference_answer":"After going through pytorch's gradient computations I see that the gradient that should be returned by this layer is not:\n```\n(grad_Z*df_dRe).real - 1j*(grad_Z*df_dIm).real\n```\nbut,\n```\ntorch.conj(grad_Z) * 0.5 * (df_dRe + 1j * df_dIm) + grad_Z * 0.5 * torch.conj(df_dRe - 1j * df_dIm)\n```\n\nHowever, as the function used in forward computation is derivable and as it can be written using only pytorch ops, a custom backward implementation is not really necessary in this case.","needs_clarification":false,"thread_id":215759,"url":"https://discuss.pytorch.org/t/gradcheck-fails-for-custom-activation-function/215759","created_at":"2025-01-23T10:56:32.694000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["anirudh_puligandla"],"answered_by_ptrblck":false} {"question":"Restarting a distributedDataParallel\n\nI know this is a weird use case, but I need to reset my DDP in the middle of a training run. ie. I call \n```\nmodel = myModel()\nmodel = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True)\n...\nmodel = model.module\n...\nmodel = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True)\n```\n\nWhen I do this I get the error:\n```\nRuntimeError: Tensors must be CUDA and dense\n```\nI have read that this is when tensors are sparse, but I don't believe any of them are. I changed the second call to:\n```\n foundOne = False\n for name, param in model.named_parameters():\n if param.is_sparse:\n print(name)\n foundOne = True\n print('Found a sparse parameter: %d' % foundOne)\n model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True)\n```\nand it does not find any sparse tensors. This also appears to not work even with only a single GPU, though the code runs properly with regular DataParallel or no DataParallel and just sending to(cuda).","reference_answer":"Turns out error that said two possible things was the other thing. :man_facepalming:\n\nProblem solved by adding \n\n```\nmodel = model.to('cuda')\n```\n\nBefore the second call to DDP.","needs_clarification":false,"thread_id":215799,"url":"https://discuss.pytorch.org/t/restarting-a-distributeddataparallel/215799","created_at":"2025-01-24T01:56:22.157000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["pytorcher"],"answered_by_ptrblck":false} {"question":"ImportError while installing mamba-ssm\n\nI am trying to install mamba-ssm package through `pip install mamba-ssm` but I got the following error:\n```\nImportError: /tmp/pip-build-env-wl_dvsa4/overlay/lib/python3.12/site-package/torch/lib/../../nvidia/cusparse/lib/libcusparse.so.12: symbol __nvJitLinkComplete_12_4 version libnvJitLink.so.12 not defined in file libnvJitLink.so.12 with link time reference\n```\nThe last import before the error: `from torch._C import *`, even tho the same import works fine when I call it separately.\nThen I tried to install it through downloading the github package and running the setup.py file, but I got another error (older version of GCC, you need GCC 9 or newer). \n\nmy setup contains the following:\nx86 PC with nvidia titan GPU\nubuntu 18.04\ncudatoolkit 12.0\npython 3.12\npytorch 2.5.1\npytorch-cuda 12.1\n\nI am really lost now, Any Help Would be Appreciated.","reference_answer":"Thank you so much for your help.\n\nI did not intend to install different CUDA libs, I installed CUDA toolkit 12.0, but then there wasn't a similar version for pytorch-cuda, so I installed pytorch-cuda 12.1 instead. For the libcusparse 12.4, it was automatically installed by the `pip install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia`.\nAnyway for future readers, the different CUDA libs was not the problem in my case, I solved the problem by updating the GCC and G++ libs in my ubuntu OS from 7.5. into 9.0 using the following commands:\n```\nsudo add-apt-repository ppa:ubuntu-toolchain-r/test\nsudo apt update\nsudo apt install gcc-9\nsudo apt install g++-9\nsudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 60 --slave /usr/bin/g++ g++ /usr/bin/g++-9\n```\nthen I installed the mamba-ssm package locally by downloading the GitHub repo and opening a terminal in the same folder and `python setup.py install` command.\n\nI hope this post helps.","needs_clarification":false,"thread_id":215907,"url":"https://discuss.pytorch.org/t/importerror-while-installing-mamba-ssm/215907","created_at":"2025-01-26T22:42:26.991000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["Omaralmaqtari"],"answered_by_ptrblck":false} {"question":"`torch.nn.functional.conv2d` 8 times slower in torch 2.5.1 compared to 2.3.1\n\nHey everyone, I am noticing that in torch 2.5.1 when I run the following snippet the exact same operation takes around 8 times slower compared to torch 2.3.1 when everything else in my environment remains the same:\n\n```\nimport torch\nimport torch.nn.functional as F\nimport time\nprint(torch.__version__)\n# prints the following\n# 2.5.1+cu124\n\nprint(\"torch.backends.cudnn.deterministic = \", torch.backends.cudnn.deterministic)\nprint(\"torch.backends.cuda.matmul.allow_tf32 = \", torch.backends.cuda.matmul.allow_tf32)\nprint(\"torch.backends.cudnn.allow_tf32 = \", torch.backends.cudnn.allow_tf32)\nprint(\"torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = \", torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction)\n# prints the following\n# torch.backends.cudnn.deterministic = False\n# torch.backends.cuda.matmul.allow_tf32 = False\n# torch.backends.cudnn.allow_tf32 = True\n# torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction = True\n\ntorch.cuda.synchronize()\nmyconv_start = time.time()\nwith torch.no_grad():\n out = F.conv2d(torch.rand(75, 1, 572, 572).cuda(), torch.rand(1, 1, 51, 51).cuda(), padding=0).cpu()\ntorch.cuda.synchronize()\nmyconv_time = time.time() - myconv_start\nprint(f\"myconv_time = {myconv_time:0.2f} seconds\")\nout.shape\n# prints the following\n# myconv_time = 4.89 seconds\n# torch.Size([75, 1, 522, 522])\n```\nMy CUDA is as follows: `Driver Version: 550.90.07, CUDA: 12.4` and I am using a L4 GPU.\n\nThe exact same code runs in 0.65 second on average when I run it in torch `2.3.1+cu121` version in the same exact environment.","reference_answer":"Resolved it by upgrading to a higher cuDNN. Reference here: https://github.com/pytorch/pytorch/issues/146096","needs_clarification":false,"thread_id":216011,"url":"https://discuss.pytorch.org/t/torch-nn-functional-conv2d-8-times-slower-in-torch-2-5-1-compared-to-2-3-1/216011","created_at":"2025-01-29T03:27:00.031000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["navidsam"],"answered_by_ptrblck":false} {"question":"Decomposition to Aten IR\n\n@bdhirsh \n\nTrying to understand how the decomposition of `torch.nn.functional.linear` is traced.\n\nExample code:\n```python\nimport torch\nfrom torch._inductor.decomposition import select_decomp_table\nfrom torch.fx import GraphModule\nfrom torch.fx.experimental.proxy_tensor import make_fx\n\ndevice = \"cuda\"\nx = torch.randn(10, 10).to(device)\ny = torch.randn(10, 10).to(device)\n\ng: GraphModule = make_fx(torch.nn.functional.linear, select_decomp_table(), tracing_mode=\"real\")(x, y)\ng.print_readable()\n```\nThis prints\n```\nclass (torch.nn.Module):\n def forward(self, arg0_1: \"f32[10, 10]\", arg1_1: \"f32[10, 10]\"):\n # No stacktrace found for following nodes\n permute: \"f32[10, 10]\" = torch.ops.aten.permute.default(arg1_1, [1, 0]); arg1_1 = None\n mm: \"f32[10, 10]\" = torch.ops.aten.mm.default(arg0_1, permute); arg0_1 = permute = None\n return mm\n```\nI've tried to step through the code using `pdb` but still can't figure out how the decomposition of `linear` is happening:\n- where is the mapping of `linear` to `permute` and `mm`?\n- if there is no direct mapping, how can I determine where along the trace these registered ops are being called?\n\nNoticed that something similar is called during the pregrad passes that `inductor` runs to normalize the IR into something more amenable for downstream passes.\n\nAlso related are the [AOTAutograd](https://github.com/pytorch/workshops/tree/master/ASPLOS_2024/aot_autograd.pdf) slides from ASPLOS 2024. On slide 23, it is mentioned that AOTAutograd handles \"operator decomposition\" among other Pytorch framework related functions that occur at the C++ level, and it does this through `__torch_dispatch__`. \n\nWhere / how does this call back to Python happen after the dispatching, autograd, and decomposition work is handled in C++?\n\nThanks!\n\n-Jerome","reference_answer":"`aten.linear` is decomposed inside the dispatcher, in C++, before the op reaches `__torch_dispatch__`. It decomposes into `aten.matmul` and `aten.transpose` (https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/Linear.cpp#L111). `aten.matmul` decomposes into `aten.mm`, `aten.baddbmm`, or a few other ops (https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/LinearAlgebra.cpp#L1995). The autograd engine has no derivative formula for linear, so it decomposes the op into primitives that have formulas.\n\nThe Python callback is `__torch_dispatch__`. Every ATen op that runs passes through it, including ops executed in C++ by the autograd engine. `make_fx` uses it to record each op into an FX graph, and AOTAutograd calls `make_fx`.","needs_clarification":false,"thread_id":216033,"url":"https://discuss.pytorch.org/t/decomposition-to-aten-ir/216033","created_at":"2025-01-29T20:08:06.353000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,4],"answer_authors":["bdhirsh"],"answered_by_ptrblck":false} {"question":"Torch compile: optimizer.step Generates Excessive Warning Messages\n\nI'm experiencing an issue with excessive warning messages when using `torch.compile()` with optimizer step function.\n\nWhile compiling the optimizer step provides a significant speed improvement during training (particularly with AdamW), I'm encountering challenges when using it with a learning rate scheduler.\n\nFollowing the approach outlined in this [discussion](https://dev-discuss.pytorch.org/t/compiling-the-optimizer-with-pt2/1669/6) and the official [PyTorch tutorial](https://pytorch.org/tutorials/recipes/compiling_optimizer_lr_scheduler.html), I've wrapped the learning rate with a tensor to prevent recompilations. However, this results in thousands of warning messages being generated, such as:\n\n```python\n('Grad tensors [\"L['self'].param_groups[394]['params'][0].grad\"] will be copied during cudagraphs execution. If using cudagraphs and the grad tensor addresses will be the same across runs, use torch._dynamo.decorators.mark_static_address to elide this copy.',)\n```\n\nThese warnings appear even when running the simple linear network example from the official tutorial.\n\nIs there a recommended way to:\n\n1. Prevent these warnings from occurring?\n2. Suppress these specific warning messages?\n3. Handle this situation differently?\n\nAny guidance would be greatly appreciated.","reference_answer":"Mark the gradients as static addresses. Call `torch._dynamo.decorators.mark_static_address` on each `.grad` attribute of the parameters, not on the parameters themselves. This is the recommended way to remove the warning. To check it is safe, print `p.grad.data_ptr()` on each iteration and confirm the address stays the same. This is generally safe across iterations.\n\nThe gradients don't exist before the first backward pass, and `mark_static_address` can't be called inside the compiled optimizer step, because it can't be traced. A newer change makes this warning appear only when `TORCH_LOGS=\"perf_hints\"` is set.","needs_clarification":false,"thread_id":216067,"url":"https://discuss.pytorch.org/t/torch-compile-optimizer-step-generates-excessive-warning-messages/216067","created_at":"2025-01-30T17:44:14.537000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[5,7,8,9],"answer_authors":["cora-codes","mlazos"],"answered_by_ptrblck":false} {"question":"Is there an out-of-place equivalent to boolean indexing assignment?\n\nIs there an out-of-place equivalent to boolean indexing assignment `A[M] = B`?\n\nFor example:\n\n```python\nimport torch\n\nA = torch.arange(10)\nM = A % 2 == 0\nB = torch.full_like(A, 10)[M]\n\n# Can I do this out of place?\nA[M] = B\n\n# is there a function like C = foo(A, M, B)\n# note that A and B don't have the same shape, so I can't use torch.where\n```","reference_answer":"Answering my own question a few months later because I figured it out. There is indeed two options:\n\n* [torch.index_put](https://pytorch.org/docs/stable/generated/torch.Tensor.index_put.html)\n* [torch.scatter](https://pytorch.org/docs/stable/generated/torch.scatter.html)\n\nExample with `torch.index_put()`:\n\n```\nA = torch.arange(10)\nM = A % 2 == 0\nB = torch.full_like(A, 10)[M]\n\nindices = M.nonzero().squeeze(-1)\n\nC = A.index_put((indices,), B)\n```","needs_clarification":false,"thread_id":216107,"url":"https://discuss.pytorch.org/t/is-there-an-out-of-place-equivalent-to-boolean-indexing-assignment/216107","created_at":"2025-01-31T23:57:19.054000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["fouronnes"],"answered_by_ptrblck":false} {"question":"Question about the Extending PyTorch tutorial\n\nHi, I’m reading the \"Extending PyTorch\" tutorial and have the following questions:\n\n1. In the document, it says:\n\n> `Tensor` arguments that track history (i.e., with `requires_grad=True`) will be converted to ones that don’t track history before the call, and their use will be registered in the graph.\n\nDoes this happen implicitly, or do I need to do this manually? I see in the examples below when passing parameters into `forward()`, there is no line to disable the gradient tracking. However, further down, it says:\n\n> Inputs to `backward`, i.e., `grad_output`, can also be tensors that track history. So if `backward` is implemented with differentiable operations, (e.g., invocation of another custom [`Function`](https://pytorch.org/docs/stable/autograd.html#torch.autograd.Function)), higher-order derivatives will work.\n\nThis is confusing because I don’t understand if I need to disable tracking manually, why isn't it done in the example? And if this is done implicitly, how can I enable tracking for a tensor?\n\n2. There’s an example code below that I don’t fully understand the intention of:\n\n```python\nclass MyCube(torch.autograd.Function):\n @staticmethod\n def forward(x):\n # We wish to save dx for backward. In order to do so, it must\n # be returned as an output.\n dx = 3 * x ** 2\n result = x ** 3\n return result, dx\n\n @staticmethod\n def setup_context(ctx, inputs, output):\n x, = inputs\n result, dx = output\n ctx.save_for_backward(x, dx)\n\n @staticmethod\n def backward(ctx, grad_output, grad_dx):\n x, dx = ctx.saved_tensors\n # In order for the autograd.Function to work with higher-order\n # gradients, we must add the gradient contribution of `dx`,\n # which is grad_dx * 6 * x.\n result = grad_output * dx + grad_dx * 6 * x\n return result\n\n# Wrap MyCube in a function so that it is clearer what the output is\ndef my_cube(x):\n result, dx = MyCube.apply(x)\n return result\n```\n\nWhy do we need to return the sum of the first and second-order derivatives? What does this mean?\n\n3. It seems the documentation isn’t written in a very detailed or easy-to-understand way (or maybe I missed something, if so, please explain and forgive me). Even though I’ve referred to many other sources, I still feel there are many components that aren’t explained but are included as examples (or explained as if they are obvious), for example: [In this line](https://pytorch.org/docs/stable/notes/extending.html#:~:text=error.%0A%20%20%20%20%20%20%20%20if%20ctx.-,needs_input_grad,-%5B0%5D%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20grad_input), why is `needs_input_grad` used even though it hasn’t been initialized? Is it automatically assigned a value based on something else? \nWhich additional sources should I read to better understand these points?\n\nThanks","reference_answer":"1. \n\n> Does this happen implicitly, or do I need to do this manually?\n\nThe disabling of gradient tracking is done implicitly for you in the scope of forward\n\n> puts to `backward` , i.e., `grad_output` , can also be tensors that track history.\n\nThe above refers to forward, but this refers to the backward pass. It is possible for computation to be enabled, if you are trying to compute higher-order gradients\n\n2. \n\nYou can think of dx as just some random output to that function. If someone ended up using dx in the computation of the final loss, the backward function should properly backprop the gradient computation back to x.\n\n3. \n\n> Is it automatically assigned a value based on something else?\n\nThat is correct. needs_input_grad and other things on ctx are provided for you and have been preinitialized to have some quantities that may be useful during backward.","needs_clarification":false,"thread_id":216124,"url":"https://discuss.pytorch.org/t/question-about-the-extending-pytorch-tutorial/216124","created_at":"2025-02-01T17:17:21.108000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["soulitzer"],"answered_by_ptrblck":false} {"question":"Applying transformation to bounding boxes is not producing proper result\n\nI am trying to applying following transformations to training image and bounding boxes\n```\nt = v2.Compose(\n [\n v2.ToImage(),\n v2.RandomHorizontalFlip(),\n v2.RandomVerticalFlip(),\n v2. Resize((448, 448)),\n v2.ToDtype(torch.float32, scale=True),\n v2.SanitizeBoundingBoxes()\n ]\n)\n```\n```\n# Apply transformations\n if self.transforms:\n # The coordinates are relative to 1,\n # scale them according to the image height and width\n # As this is required by the transforms\n print(box_coords)\n box_coords[:, [0, 2]] *= img_w\n box_coords[:, [1, 3]] *= img_h\n print(box_coords)\n img, box_coords = self.transforms(img, box_coords)\n print(box_coords)\n # Change the coordinates back to relative to 1 value\n box_coords[:, [0, 2]] /= img_w\n box_coords[:, [1, 3]] /= img_h\n print(box_coords)\n\n```\nBut I am not getting correct bounding boxes after the transformation. \nHere is the output of those `print` statements that I have used for debugging.\n```\nBoundingBoxes([[0.4040, 0.4230, 0.3707, 0.1140],\n [0.3907, 0.4840, 0.2320, 0.1760],\n [0.2293, 0.5170, 0.3573, 0.2660],\n [0.6773, 0.6340, 0.3147, 0.4520]], format=BoundingBoxFormat.CXCYWH, canvas_size=(500, 375))\nBoundingBoxes([[151.5000, 211.5000, 139.0000, 57.0000],\n [146.5000, 242.0000, 87.0000, 88.0000],\n [ 86.0000, 258.5000, 134.0000, 133.0000],\n [254.0000, 317.0000, 118.0000, 226.0000]], format=BoundingBoxFormat.CXCYWH, canvas_size=(500, 375))\nBoundingBoxes([[180.9920, 189.5040, 166.0587, 51.0720],\n [175.0187, 216.8320, 103.9360, 78.8480],\n [102.7413, 231.6160, 160.0853, 119.1680],\n [303.4453, 284.0320, 140.9707, 202.4960]], format=BoundingBoxFormat.CXCYWH, canvas_size=(448, 448))\nBoundingBoxes([[0.4826, 0.3790, 0.4428, 0.1021],\n [0.4667, 0.4337, 0.2772, 0.1577],\n [0.2740, 0.4632, 0.4269, 0.2383],\n [0.8092, 0.5681, 0.3759, 0.4050]], format=BoundingBoxFormat.CXCYWH, canvas_size=(448, 448))\n```\nOriginal image with the bounding boxes:\n[image]\n\nOutput after transformation:\n[image]","reference_answer":"The boxes are normalized to [0, 1] relative to the original image, so scale them to pixels with the original width and height before the transform. After the transform, normalize them with the new height and width (448 x 448 here), not with the original width and height.","needs_clarification":false,"thread_id":216126,"url":"https://discuss.pytorch.org/t/applying-transformation-to-bounding-boxes-is-not-producing-proper-result/216126","created_at":"2025-02-01T18:00:17.089000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["Amit_Sur","ptrblck"],"answered_by_ptrblck":true} {"question":"Error in official document code?\n\nI'm following the tutorial [here](https://pytorch.org/docs/stable/notes/extending.html#:~:text=class%20MyCube(torch.autograd.Function)%3A) and use the code:\n\n```\nclass MyCube(torch.autograd.Function):\n @staticmethod\n def forward(x):\n # We wish to save dx for backward. In order to do so, it must\n # be returned as an output.\n dx = 3 * x ** 2\n result = x ** 3\n return result, dx\n\n @staticmethod\n def setup_context(ctx, inputs, output):\n x, = inputs\n result, dx = output\n ctx.save_for_backward(x, dx)\n\n @staticmethod\n def backward(ctx, grad_output, grad_dx):\n x, dx = ctx.saved_tensors\n # In order for the autograd.Function to work with higher-order\n # gradients, we must add the gradient contribution of `dx`,\n # which is grad_dx * 6 * x.\n result = grad_output * dx + grad_dx * 6 * x\n return result\n\n# Wrap MyCube in a function so that it is clearer what the output is\ndef my_cube(x):\n result, dx = MyCube.apply(x)\n return result\n\nx = torch.tensor(2.0, requires_grad=True)\ny, dx = my_cube(x) # y = x^3, dx = 3x^2\n```\n\nBut I got this error:\n\n```\nFile \"H:\\code\\lab\\lab.py\", line 33, in \n y, dx = my_cube(x) # y = x^3, dx = 3x^2\n File \"H:\\code\\lab\\lab.py\", line 29, in my_cube\n result, dx = MyCube.apply(x)\nTypeError: MyCube.forward() takes 1 positional argument but 2 were given\n```","reference_answer":"The example has a bug in its last line. `y, dx = my_cube(x)` unpacks two values, but `my_cube` returns only `result`. Make `my_cube` return both values:\n\n```python\ndef my_cube(x):\n result, dx = MyCube.apply(x)\n # return result\n return result, dx # return a tuple containing both result and dx\n```\n\nWith that change the example runs on PyTorch 2.6.0, and should work on any recent version.","needs_clarification":false,"thread_id":216146,"url":"https://discuss.pytorch.org/t/error-in-official-document-code/216146","created_at":"2025-02-02T09:21:45.638000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Replace torch.rfft() code (PyTorch 1.6)\n\nI want to use a repository that was built with PyTorch 1.6, with newer versions of PyTorch (preferably the latest). This repository uses \n\n`torch.rfft()`\n\nwhich was deprecated to `torch.fft.rfft` in later PyTorch versions.\n\nThe snippet of code that I want to replace is\n\n```\nv = torch.cat([x[:, ::2], x[:, 1::2].flip([1])], dim=1)\nVc = torch.fft.rfft(v, 1, onesided=False)\n```\n\nwhere `x` is a two dimensional tensor. In the comments around that piece of code, it is written that\n\n> Discrete Cosine Transform, Type II (a.k.a. the DCT)\n\nI switched `torch.rfft()` with `torch.fft.rfft` but then I get the error \n\n`TypeError: fft_rfft() got an unexpected keyword argument 'onesided'`\n\nDoes anyone know the exact equivalent of this code to the current PyTorch version?\n\nAdditionally, I have also found this line of code\n\n`v = torch.irfft(V, 1, onesided=False)`\n\nwhich also needs an update.\n\nThank you in advance.","reference_answer":"I found the equivalent code for that line. Since `oneseded=False`, the corresponding function to use is `torch.fft.fft`. Additionally, since PyTorch supports complex values, to produce the same output with that of the deprecated version, `torch.view_as_real` must be used. Below is the equivalent code of `Vc = torch.fft.rfft(v, 1, onesided=False)`\n\n```\nVc = torch.fft.fft(v)\nVc = torch.view_as_real(Vc)\n```","needs_clarification":false,"thread_id":216169,"url":"https://discuss.pytorch.org/t/replace-torch-rfft-code-pytorch-1-6/216169","created_at":"2025-02-03T09:19:15.576000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrch_c_m"],"answered_by_ptrblck":false} {"question":"Torch.compile: Generated Triton kernel seems wrong\n\nMy original code:\n```\nimport torch\n\ndef square(x):\n x = torch.square(x)\n if x.sum() > 0:\n x = x-1\n return torch.square(x)\n\nopt_square = torch.compile(square)\nopt_square(torch.randn(10000, 10000).cuda())\n```\n\ngenerated triton kernel:\n```\n@triton.jit\ndef triton_(in_ptr0, out_ptr0, xnumel, XBLOCK : tl.constexpr):\n xnumel = 100000000\n xoffset = tl.program_id(0) * XBLOCK\n xindex = xoffset + tl.arange(0, XBLOCK)[:]\n xmask = xindex < xnumel\n x0 = xindex\n tmp0 = tl.load(in_ptr0 + (x0), xmask)\n tmp1 = 1.0\n tmp2 = tmp0 - tmp1\n tmp3 = tmp2 * tmp2\n tl.store(out_ptr0 + (x0), tmp3, xmask)\n''', device_str='cuda')\n```\n\nThat is, for given input:\n```\ntorch: (x**2-1)**2\ntriton: (x-1)**2\n```","reference_answer":"The generated code is not wrong. `torch.compile` generates several files and kernels for this function, and the kernel being read is only one of them. The compiled and eager results match: on a 3090 with a current nightly build, the maximum difference between them is 0.","needs_clarification":false,"thread_id":216192,"url":"https://discuss.pytorch.org/t/torch-compile-generated-triton-kernel-seems-wrong/216192","created_at":"2025-02-04T01:04:20.319000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,5],"answer_authors":["Shihab_Shahriar","ptrblck"],"answered_by_ptrblck":true} {"question":"RuntimeError: \"rshift_cpu\" not implemented for 'Float'\n\nHow do I implement (overload?) `>>` for tensors?","reference_answer":"You are using `int` values, where the bitshift operation is properly defined.\nIt'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:\n```python\nx = torch.tensor(1.25)\ny = x.view(torch.int32)\nprint(y)\n# tensor(1067450368, dtype=torch.int32)\nprint(np.binary_repr(y.numpy()))\n# 111111101000000000000000000000\n\ny = y << 1\nprint(y)\n# tensor(2134900736, dtype=torch.int32)\nprint(np.binary_repr(y.numpy()))\n# 1111111010000000000000000000000\n\nz = y.view(torch.float32)\nprint(z)\n# tensor(2.5521e+38)\n```\nbut make sure this is really what you want @Geremia","needs_clarification":false,"thread_id":216200,"url":"https://discuss.pytorch.org/t/runtimeerror-rshift-cpu-not-implemented-for-float/216200","created_at":"2025-02-04T03:36:02.472000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Cannot install pytorch with Given Pip command SSL error\n\nwhen running the command from the Pytorch website i get an error during install\n\n```\nWARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1007)'))': /whl/cu118/torch/\nCould not fetch URL https://download.pytorch.org/whl/cu118/torch/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='download.pytorch.org', port=443): Max retries exceeded with url: /whl/cu118/torch/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1007)'))) - skipping\nERROR: Could not find a version that satisfies the requirement torch (from versions: none)\nERROR: No matching distribution found for torch\n```\n\nI believe this is due to a security block from my company. is there any other way to install pytorch with cuda support? I am able to install pip packages without errors if im not trying to access a URL.\nEG: pip install numpy\nthrows no errors\n\npython version 3.10.11\ntorch 2.6.0\ncuda 11.8\nwindows 11","reference_answer":"In that case there isn't much one can do there. Trying talking to them and ask adding download.pytorch.org to the list of exceptions. Or perhaps there is a corporate proxy sever one can configure to allow access to more web-sites.\n\nYou can try building from source or installing anaconda package, whenever it becomes available.","needs_clarification":false,"thread_id":216272,"url":"https://discuss.pytorch.org/t/cannot-install-pytorch-with-given-pip-command-ssl-error/216272","created_at":"2025-02-05T14:29:14.668000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["malfet"],"answered_by_ptrblck":false} {"question":"Linear constraints on trainable network parameters\n\nI am defining additional trainable parameters (besides the weights and biases) as `nn.ParameterDict(...)`. Lets denote these additional parameters as `X`. \n\nDuring training, the linear inequality constraint `A*X > 0` must be satisfied at every epoch. Otherwise, I may not be able to calculate a loss.\n\nAre there built-in solution approaches to handle this? I am using the Adam optimizer, but could also switch to a different one.\n(Note: I would like to avoid introducing a loss term for the constraint vialation since I already have some loss terms which I have to weigh appropriately)","reference_answer":"Nothing is built in for this. Reimpose the constraint after every optimizer step by projecting `X` back onto the feasible set, modifying `X` in place under `torch.no_grad()`:\n\n```python\n...\nloss = Loss_function (output, X)\nloss.backward()\noptimizer.step()\nwith torch.no_grad():\n V = (A @ X).min (torch.zeros (1))\n X.sub_ (torch.linalg.lstsq (A, V.unsqueeze (-1)).solution.squeeze())\n```\n\nThis gives the X closest to the current X that satisfies `A @ X >= 0`. It assumes `A` has shape `[m, n]` with `m < n`. If you need `A @ X` strictly greater than zero, replace the constraint with `A @ X > eps` for a small positive `eps`. A loss penalty does not keep the constraint satisfied at each step.","needs_clarification":false,"thread_id":216334,"url":"https://discuss.pytorch.org/t/linear-constraints-on-trainable-network-parameters/216334","created_at":"2025-02-06T21:23:59.485000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,4],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Why does IterableDataset and DataLoader cause issues with training metrics?\n\nI'm using a custom IterableDataset and DataLoader to train my model due to the large amount of data - since I can't store it all in memory at once.\n\nMy data consists of multiple files such that each file has thousands and thousands of examples. \nI have set up my training loop and found that whenever I run an epoch I get the same training accuracy and training loss for every epoch. The same also applies for the validation. Why does that happen?\n\nI'm starting to think that the issue is with the shuffling of the dataset. I do know that the DataLoader does automatic shuffling but this doesn't apply for IterableDatasets. So to accomodate for that, I've created a BatchShuffleDataSet which is also a custom iterabledataset for batch shuffling.\n\nThis is my DatasetClass:\n```\nclass ProtobufIterableDataset(IterableDataset):\n def _init_(self, data_folder, scaling=False):\n self.data_folder = data_folder\n self.scaling = scaling\n\n super()._init_()\n \n if scaling:\n scaler_path = \"scalers.npz\"\n # Load the data once and store as class attribute instead of instance attribute to avoid BadZipFile error\n if not hasattr(ProtobufIterableDataset, 'scaler_data'):\n ProtobufIterableDataset.scaler_data = dict(np.load(scaler_path))\n\n def _iter_(self):\n # Worker Split Based on Number of Examples in Each File so sharding at example level\n worker_info = torch.utils.data.get_worker_info()\n \n if worker_info is not None:\n worker_id = worker_info.id\n num_workers = worker_info.num_workers\n \n # Get list of all files\n for file in sorted(os.listdir(self.data_folder)):\n with open(os.path.join(self.data_folder, file), 'rb') as f:\n cache_data = cache_state_pb2.CacheStateProto()\n cache_data.ParseFromString(f.read())\n \n # Each worker takes every nth example\n for i, example in enumerate(cache_data.proto_examples):\n if i % num_workers == worker_id:\n processed_example = self.process(example)\n yield processed_example\n else:\n print(\"Single Worker Mode\")\n for file in os.listdir(self.data_folder):\n with open(os.path.join(self.data_folder, file), 'rb') as f:\n cache_data = cache_state_pb2.CacheStateProto()\n cache_data.ParseFromString(f.read())\n \n for example in cache_data.proto_examples:\n processed_example = self.process(example)\n yield processed_example\n```\nThis is my Batch Shuffler Class:\n```\n# Batch Shuffler Class\nclass BatchShuffleDataset(IterableDataset):\n def _init_(self, dataset, batch_size):\n super()._init_()\n self.dataset = dataset\n self.batch_size = batch_size\n\n def _iter_(self):\n batch = []\n dataset_iter = iter(self.dataset)\n for item in dataset_iter:\n batch.append(item)\n if len(batch) == self.batch_size:\n random.shuffle(batch)\n for shuffled_item in batch:\n yield shuffled_item\n batch = []\n if batch:\n random.shuffle(batch)\n for shuffled_item in batch:\n yield shuffled_item\n```\nHere is my training file:\n```\nimport torch\nfrom torch.utils.data import DataLoader\nfrom new_data_loader import ProtobufIterableDataset, BatchShuffleDataset\nfrom model import SimpleModel\nimport torch.optim as optim\nimport torch.nn as nn\nfrom tqdm import tqdm\n\n# Constants\nBATCH_SIZE = 32\nSHUFFLE_BUFFER_SIZE = 1000\nNUM_WORKERS = 4\n\n# Load Training Data\ntrainingDataset = ProtobufIterableDataset('training_examples', scaling=True)\ntrainingDataset = BatchShuffleDataset(trainingDataset, batch_size=SHUFFLE_BUFFER_SIZE)\ntrainingDataLoader = DataLoader(trainingDataset, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS)\n\n# Load Validation Data\nvalidationDataset = ProtobufIterableDataset('validation_examples', scaling=True)\nvalidationDataset = BatchShuffleDataset(validationDataset, batch_size=SHUFFLE_BUFFER_SIZE)\nvalidationDataLoader = DataLoader(validationDataset, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS)\n\n# Training Setup\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel = SimpleModel().to(device)\n \n\nepochs = 10\nlearning_rate = 0.001\ncrossEntropyLoss = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=learning_rate)\n\ndef train(model, trainingDataLoader, validationDataLoader, optimizer, criterion, device, epochs=10):\n \"\"\"\n Training function with improved metric calculations, compatible with IterableDataset\n \"\"\"\n # Create outer progress bar for epochs\n epoch_pbar = tqdm(range(epochs), desc='Training Progress', position=0)\n \n for epoch in epoch_pbar:\n # Training Phase\n model.train()\n running_train_loss = 0.0 # Running loss for the current epoch\n epoch_train_correct = 0 # Total correct predictions for the epoch\n epoch_train_samples = 0 # Total samples processed in the epoch\n \n # Create progress bar for training batches\n train_pbar = tqdm(trainingDataLoader, \n desc=f'Training Epoch {epoch+1}/{epochs}',\n position=1, \n leave=False)\n \n # For every batch\n for batch_idx, (set_features, access_features, cache_features, labels) in enumerate(train_pbar, 1):\n # Combine features\n cache_features_flat = cache_features.reshape(-1, 17*9)\n combined_features = torch.cat([set_features, access_features, cache_features_flat], dim=1)\n \n # Move to device\n combined_features = combined_features.to(device)\n labels = labels.to(device)\n \n # Zero gradients\n optimizer.zero_grad()\n \n # Forward pass\n outputs = model(combined_features)\n loss = criterion(outputs, labels)\n \n # Backward pass\n loss.backward()\n optimizer.step()\n \n # Update running loss\n batch_size = labels.size(0)\n running_train_loss += loss.item() * batch_size\n \n # Calculate accuracy\n predicted = outputs.argmax(dim=1)\n true_labels = labels.argmax(dim=1)\n batch_correct = (predicted == true_labels).sum().item()\n \n # Update totals\n epoch_train_samples += batch_size\n epoch_train_correct += batch_correct\n \n # Calculate current accuracy\n current_accuracy = 100 * epoch_train_correct / epoch_train_samples\n current_loss = running_train_loss / epoch_train_samples\n \n # Update training progress bar with moving averages\n train_pbar.set_postfix({\n 'loss': f'{current_loss:.4f}',\n 'acc': f'{current_accuracy:.2f}%',\n 'samples': epoch_train_samples\n })\n \n # Store final training metrics\n final_train_loss = current_loss\n final_train_accuracy = current_accuracy\n \n # Validation Phase\n model.eval()\n running_val_loss = 0.0\n epoch_val_correct = 0\n epoch_val_samples = 0\n \n # Create progress bar for validation batches\n val_pbar = tqdm(validationDataLoader, \n desc=f'Validation Epoch {epoch+1}/{epochs}',\n position=1, \n leave=False)\n \n with torch.no_grad():\n for batch_idx, (set_features, access_features, cache_features, labels) in enumerate(val_pbar, 1):\n # Combine features\n cache_features_flat = cache_features.reshape(-1, 17*9)\n combined_features = torch.cat([set_features, access_features, cache_features_flat], dim=1)\n \n # Move to device\n combined_features = combined_features.to(device)\n labels = labels.to(device)\n \n # Forward pass\n outputs = model(combined_features)\n loss = criterion(outputs, labels)\n \n # Update running loss\n batch_size = labels.size(0)\n running_val_loss += loss.item() * batch_size\n\n \n # Calculate accuracy\n predicted = outputs.argmax(dim=1)\n true_labels = labels.argmax(dim=1)\n batch_correct = (predicted == true_labels).sum().item()\n \n # Update totals\n epoch_val_samples += batch_size\n epoch_val_correct += batch_correct\n \n # Calculate current accuracy\n current_accuracy = 100 * epoch_val_correct / epoch_val_samples\n current_loss = running_val_loss / epoch_val_samples\n \n # Update validation progress bar\n val_pbar.set_postfix({\n 'loss': f'{current_loss:.4f}',\n 'acc': f'{current_accuracy:.2f}%',\n 'samples': epoch_val_samples\n })\n \n # Store final validation metrics\n final_val_loss = current_loss \n final_val_accuracy = current_accuracy\n \n # Update epoch progress bar with final metrics\n epoch_pbar.set_postfix({\n 'train_loss': f'{final_train_loss:.4f}',\n 'train_acc': f'{final_train_accuracy:.2f}%',\n 'val_loss': f'{final_val_loss:.4f}',\n 'val_acc': f'{final_val_accuracy:.2f}%'\n })\n \n # Print final statistics for the epoch\n print(f'\\nEpoch {epoch+1}/{epochs}:')\n print(f'Training Loss: {final_train_loss:.4f}, '\n f'Training Accuracy: {final_train_accuracy:.2f}%')\n print(f'Validation Loss: {final_val_loss:.4f}, '\n f'Validation Accuracy: {final_val_accuracy:.2f}%\\n')\n \n\n \n# test train function\ntrain(model, trainingDataLoader, validationDataLoader, optimizer, crossEntropyLoss, device, epochs=epochs)\n```","reference_answer":"I was applying the softmax function before passing it to the CrossEntropyLoss. Which has been causing this issue.","needs_clarification":false,"thread_id":216360,"url":"https://discuss.pytorch.org/t/why-does-iterabledataset-and-dataloader-cause-issues-with-training-metrics/216360","created_at":"2025-02-07T12:27:54.150000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["saff"],"answered_by_ptrblck":false} {"question":"Bizarre InternalTorchDynamoError with locally and formerly working code\n\nHi, has anyone seen this error in the last 3 months or so running a compiled pytorch model with multi-GPU?\n\n```\n[rank0]: File \"/usr/lib/python3/dist-packages/torch/_dynamo/variables/builder.py\", line 529, in _wrap\n[rank0]: if has_triton():\n[rank0]: File \"/usr/lib/python3/dist-packages/torch/utils/_triton.py\", line 37, in has_triton\n[rank0]: return is_device_compatible_with_triton() and has_triton_package()\n[rank0]: File \"/usr/lib/python3/dist-packages/torch/utils/_triton.py\", line 33, in is_device_compatible_with_triton\n[rank0]: if device_interface.is_available() and extra_check(device_interface):\n[rank0]: File \"/usr/lib/python3/dist-packages/torch/utils/_triton.py\", line 23, in cuda_extra_check\n[rank0]: return device_interface.Worker.get_device_properties().major >= 7\n[rank0]: File \"/usr/lib/python3/dist-packages/torch/_dynamo/device_interface.py\", line 191, in get_device_properties\n[rank0]: return caching_worker_device_properties[\"cuda\"][device]\n[rank0]: torch._dynamo.exc.InternalTorchDynamoError: IndexError: list index out of range\n\n[rank0]: from user code:\n[rank0]: File \"/usr/lib/python3/dist-packages/torch/_dynamo/external_utils.py\", line 40, in inner\n[rank0]: return fn(*args, **kwargs)\n\n[rank0]: Set TORCH_LOGS=\"+dynamo\" and TORCHDYNAMO_VERBOSE=1 for more information\n```\nThe same code was running fine last October-November on the same type of instance and still runs fine last week on my local machine. I have tried changing the version of PyTorch (2.4.1, 2.5.1, 2.6.0) and triton (3.2.0, 3.1.0, 3.0.0, and the last 2.x) but none of that helped. `torch.cuda.is_available()` and `torch.cuda.device_count()` look fine and simple test code (e.g. https://gist.github.com/EIFY/dee8c28e1f5c7d78388020abd36a627e) also works fine. What other libraries/drivers might contribute to this?\n\nThe error is probably very environment specific but the exact steps to reproduce on a [Lambda](https://lambdalabs.com/) 8x A100 (40 GB SXM4) instance is as follows:\n \n```\npip3 install --upgrade requests\npip3 install wandb\npip3 install schedulefree\n\ngit clone https://github.com/EIFY/mup-vit.git\ncd mup-vit\nNUMEXPR_MAX_THREADS=116 torchrun main.py --fake-data --batch-size 4096 --log-steps 100\n```","reference_answer":"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 described [here](https://github.com/pytorch/pytorch/blob/91dfa829811dacadf77ecf082ae4cd5957ff2508/torch/distributed/run.py#L44-L61).\nIn your approach you are launching your script with `torchrun` only and are not using the `--local-rank` at all, so again unsure how this should have ever worked.\nAlternatively, you can also use a multiprocessing approach inside your script which will spawn the processes there as described in [this tutorial](https://pytorch.org/tutorials/intermediate/dist_tuto.html).","needs_clarification":false,"thread_id":216382,"url":"https://discuss.pytorch.org/t/bizarre-internaltorchdynamoerror-with-locally-and-formerly-working-code/216382","created_at":"2025-02-07T21:26:52.681000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Confused between CUDA versions\n\nin nvidia-smi I have cuda 12.8.\nFrom 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\n-> Also if somewhere in some env I install torch version 12.4 / 11.8 will my CUDA 12.8 mess things up?\n-> Is cuDNN also required if I am working with LLMs?","reference_answer":"Your locally installed CUDA toolkit won’t be used as PyTorch binaries ship with their own CUDA runtime. The driver requirements are explained [here](https://docs.nvidia.com/deploy/cuda-compatibility/#minor-version-compatibility).","needs_clarification":false,"thread_id":216424,"url":"https://discuss.pytorch.org/t/confused-between-cuda-versions/216424","created_at":"2025-02-09T15:17:10.599000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Calling autograd.Function in autograd.Function\n\nI find myself needing to manually implement gradient checkpointing for several custom autograd functions. This involves manually “merging” a few `autograd.Function` instances into a new `autograd.Function`. How can I achieve this? I would like to reuse each of the forward and backward functions for the nested `autograd.Function`, and each of these functions might save different data.","reference_answer":"Yes, that should work.\n\n```python\nclass CustomFunction(torch.autograd.Function):\n\n @staticmethod\n def forward(ctx, *args, **kwargs):\n # Creating separate context objects\n ctx_hack1 = torch.autograd.function.FunctionCtx()\n ctx_hack2 = torch.autograd.function.FunctionCtx()\n ctx_hack3 = torch.autograd.function.FunctionCtx()\n\n # Some operations...\n out = SomeOtherFunction.forward(ctx_hack1, *args)\n out = AnotherFunction.forward(ctx_hack2, out, *args)\n\n # Context hacks\n ctx.save_for_backward(*ctx_hack1.to_save, *ctx_hack2.to_save)\n ctx.sub_contexts = (ctx_hack1, ctx_hack2, ctx_hack3)\n ctx_hack1.to_save = None\n ctx_hack2.to_save = None\n\n return out\n\n @staticmethod\n def backward(ctx, *args, **kwargs):\n # ...\n```","needs_clarification":false,"thread_id":216485,"url":"https://discuss.pytorch.org/t/calling-autograd-function-in-autograd-function/216485","created_at":"2025-02-10T18:51:08.185000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[3,4],"answer_authors":["HanGuo97","soulitzer"],"answered_by_ptrblck":false} {"question":"How does autograd merges 'parallel paths'?\n\nI'm trying to manually compute the gradients of the loss function at the top:\n\n[image]\n\nThe loss is the combination of a L1 loss and L_{dssim} loss and both are function of my model's prediction y(θ).\n\nTherefore I have two ways of using the Chain Rule to calculate dL/dθ. As I have highlighted in blue. Which I imagine to be two parallel paths in the computational graph.\n\nHow do I combine them? -- Or better, how does PyTorch do so I can replicate it?","reference_answer":"The total gradient is the sum of the gradients from each of the paths","needs_clarification":false,"thread_id":216527,"url":"https://discuss.pytorch.org/t/how-does-autograd-merges-parallel-paths/216527","created_at":"2025-02-11T11:19:47.819000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["soulitzer"],"answered_by_ptrblck":false} {"question":"Exporting function with size value as args using executorch\n\nHi all, I'm working on exporting a model containing a function with 3 args indicating the size of output tensors. The model looks something like the following:\n\n```\nclass Module(nn.Module):\n def forward(self, x: torch.Tensor, y: torch.Tensor, z: torch.Tensor):\n return torch.full((x.item(), y.item(), z.item()), 1)\n\n# export + to_edge_transform_and_lower, the exported program is called edge_program...\n\nedge_program.to_executorch()\n```\n\nThe `.to_executorch()` call on the last row triggers the following error:\n\n```\nTraceback (most recent call last):\n File \"/home//workspace/convert_litert/pte_tryout.py\", line 200, in \n executorch = multi_entry_points_edge_program.to_executorch()\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/program/_program.py\", line 93, in wrapper\n return func(self, *args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/program/_program.py\", line 1364, in to_executorch\n new_gm_res = p(new_gm)\n ^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/torch/fx/passes/infra/pass_base.py\", line 44, in __call__\n res = self.call(graph_module)\n ^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/pass_base.py\", line 576, in call\n result = self.call_submodule(graph_module, tuple(inputs))\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/pass_base.py\", line 662, in call_submodule\n res = super().call_submodule(graph_module, inputs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/pass_base.py\", line 539, in call_submodule\n interpreter.run(*inputs_data)\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/torch/fx/interpreter.py\", line 167, in run\n self.env[node] = self.run_node(node)\n ^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/pass_base.py\", line 379, in run_node\n return super().run_node(n)\n ^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/torch/fx/interpreter.py\", line 230, in run_node\n return getattr(self, n.op)(n.target, args, kwargs)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/pass_base.py\", line 611, in call_function\n return self.callback.call_operator(\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/passes/spec_prop_pass.py\", line 96, in call_operator\n meta[\"spec\"] = pytree.tree_map(make_spec, op(*args_data, **kwargs_data))\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/torch/utils/_pytree.py\", line 991, in tree_map\n return treespec.unflatten(map(func, *flat_args))\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/torch/utils/_pytree.py\", line 830, in unflatten\n leaves = list(leaves)\n ^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/passes/spec_prop_pass.py\", line 23, in make_spec\n return TensorSpec.from_tensor(x)\n ^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/tensor.py\", line 173, in from_tensor\n spec = cls(\n ^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/tensor.py\", line 144, in __init__\n self.dim_order: Tuple[bytes] = dim_order_from_stride(self.stride)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/executorch/exir/tensor.py\", line 71, in dim_order_from_stride\n if s == 0:\n ^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/torch/__init__.py\", line 740, in __bool__\n return self.node.bool_()\n ^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/torch/fx/experimental/sym_node.py\", line 574, in bool_\n return self.guard_bool(\"\", 0)\n ^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/torch/fx/experimental/sym_node.py\", line 512, in guard_bool\n r = self.shape_env.evaluate_expr(self.expr, self.hint, fx_node=self.fx_node)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/torch/fx/experimental/recording.py\", line 263, in wrapper\n return retlog(fn(*args, **kwargs))\n ^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/torch/fx/experimental/symbolic_shapes.py\", line 6303, in evaluate_expr\n return self._evaluate_expr(\n ^^^^^^^^^^^^^^^^^^^^\n File \"/disk1/python311-executorch/lib64/python3.11/site-packages/torch/fx/experimental/symbolic_shapes.py\", line 6493, in _evaluate_expr\n raise self._make_data_dependent_error(\ntorch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode: Could not guard on data-dependent expression Eq(u19*u20, 0) (unhinted: Eq(u19*u20, 0)). (Size-like symbols: u20, u19)\n```\n\nAfter browsing the [Dynamic shapes manual](https://docs.google.com/document/d/1GgvOe7C8_NVOMLOCwDaYV1mXXyHMXY7ExoewHqooxrs/edit?tab=t.0) and [Dealing with GuardOnDataDependentSymNode errors handbook](https://docs.google.com/document/d/1HSuTTVvYH1pTew89Rtpeu84Ht3nQEFTYhAX3Ypa_xJs/edit?tab=t.0#heading=h.44gwi83jepaj), I realized that this error is caused by that the data-dependent shape `(x.item(), y.item(), z.item())` is bad for ExecuTorch exporting because there is no value constraint on them. \n\nSo I guess one solution could be transforming the exported graph before the `.to_executorch()` call to add some constraint to the Nodes derived from the three args. But I don't know whether I'm on the right track, or is there a better way of resolving this?","reference_answer":"I've found a solution to this error. The following data-dependent error message:\n```\ntorch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode: Could not guard on data-dependent expression Eq(u19*u20, 0) (unhinted: Eq(u19*u20, 0)). (Size-like symbols: u20, u19)\n```\nindicates that the exported program will fail when `Eq(u19*u20, 0)` (i.e. the multiplication of u19 (the IR node of x) and u20 (the IR node of y) equals zero). And I need to explicitly ensure this will not happen. \n\nTherefore, the solution to this is to add a `torch._check_value` as a constraint hint in the `Module`:\n\n```\nclass Module(nn.Module):\n def forward(self, x, y, z):\n ...\n torch._check(x.item() * y.item() != 0)\n ...\n```\nAfter adding this assertion, one needs to add the corresponding `torch._check` to other calculations of the values if other guards are triggered.","needs_clarification":false,"thread_id":216543,"url":"https://discuss.pytorch.org/t/exporting-function-with-size-value-as-args-using-executorch/216543","created_at":"2025-02-11T15:45:04.384000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["111309"],"answered_by_ptrblck":false} {"question":"Gradient computation with PyTorch autograd with 1th and 2th order derivatives does not work\n\nI am having a weird issue with PyTorch's autograd functionality when implementing a custom loss calculation on a second order differential equation. In the code below, predictions of the neural network are checked if they satisfy a second order differential equation. This works fine. However, when I want to calculate the gradient of the loss with respect to the predictions, I get an error indicating that there seems to be no connection between loss and u in the computational graph.\n\n> RuntimeError: One of the differentiated Tensors appears to not have\n> been used in the graph. Set allow_unused=True if this is the desired\n> behavior.\n\nThis doesn't make sense because the loss is directly dependent and calculated with the prior derivatives that originate from u. Deriving the loss with respect to u_xx and u_t works, deriving to u_x does NOT. We verified that ```.requires_grad``` is set to ```True``` for all variables (```X```, ```u```, ```u_d```, ```u_x```, ```u_t```, ```u_xx```).\n\nWhy does this happen, and how to fix this?\n\n**Main code:**\n\n # Ensure X requires gradients\n X.requires_grad_(True)\n\n # Get model predictions\n u = self.pinn(X)\n\n # Compute first-order gradients (∂u/∂x and ∂u/∂t)\n u_d = torch.autograd.grad(\n u,\n X,\n grad_outputs=torch.ones_like(u),\n retain_graph=True,\n create_graph=True, # Allow higher-order differentiation\n )[0]\n\n # Extract derivatives\n u_x, u_t = u_d[:, 0], u_d[:, 1] # ∂u/∂x and ∂u/∂t\n\n # Compute second-order derivative ∂²u/∂x²\n u_xx = torch.autograd.grad(\n u_x,\n X,\n grad_outputs=torch.ones_like(u_x),\n retain_graph=True,\n create_graph=True,\n )[0][:, 0]\n\n # Diffusion equation (∂u/∂t = κ * ∂²u/∂x²)\n loss = nn.functional.mse_loss(u_t, self.kappa * u_xx)\n\n ## THIS FAILS\n # Compute ∂loss/∂u\n loss_u = torch.autograd.grad(\n loss,\n u,\n grad_outputs=torch.ones_like(loss),\n retain_graph=True,\n create_graph=True,\n )[0]\n\n # Return error on diffusion equation\n return loss\n\n**Model:**\n\n ==========================================================================================\n Layer (type:depth-idx) Output Shape Param #\n ==========================================================================================\n Sequential [1, 1] --\n ├─Linear: 1-1 [1, 50] 150\n ├─Tanh: 1-2 [1, 50] --\n ├─Linear: 1-3 [1, 50] 2,550\n ├─Tanh: 1-4 [1, 50] --\n ├─Linear: 1-5 [1, 50] 2,550\n ├─Tanh: 1-6 [1, 50] --\n ├─Linear: 1-7 [1, 50] 2,550\n ├─Tanh: 1-8 [1, 50] --\n ├─Linear: 1-9 [1, 1] 51\n ==========================================================================================\n Total params: 7,851\n Trainable params: 7,851\n Non-trainable params: 0\n Total mult-adds (M): 0.01\n ==========================================================================================\n Input size (MB): 0.00\n Forward/backward pass size (MB): 0.00\n Params size (MB): 0.03\n Estimated Total Size (MB): 0.03\n ==========================================================================================\n\n**What we have already tried:**\n\nReverted to an older PyTorch version (tested on 2.5.0, and 1.13.1). Same issue.\n\nPutting ```.requires_grad_(True)``` after every variable assignment. This did not help.\n\nWe also tried to replace the tensor slicing by multiplying with zero/one vectors without results. We though this slicing might disturb the computational graph breaking the connection to u.\n\n # Extract derivatives\n u_x, u_t = u_d[:, 0], u_d[:, 1] # ∂u/∂x and ∂u/∂t\n \n # Extract derivatives alternative\n u_x = torch.sum(\n torch.reshape(torch.tensor([1, 0], device=u_d.device), [1, -1]) * u_d,\n dim=1,\n keepdim=True,\n )\n u_t = ...\n\nThanks for your help!","reference_answer":"Hi woutr!\n\nYou could also say that the prior derivatives originate from `X`, rather than from `u`.\n\nConsider `y = x**2`. In \"ordinary calculus\" you would typically say that\n`dy / dx = 2 * x`, so that `dy / dx` depends on `x`. You would not typically say\nthat `dy / dx = 2 * sqrt (y)`, although this is in a sense true. Pytorch's autograd\n(appropriately) takes the \"ordinary calculus\" view that `dy / dx` depends on `x`, but\nnot directly on `y`.\n\n(As a blunter example, consider `y = x**2` and `z = exp (x)` (so that `x = log (z)`).\nAlthough `dy / dx = 2 * x` could be expressed as `dy / dx = 2 * log (z)`, you\nwould not expect autograd to know how to differentiate `dy / dx` with respect to `z`.\nYou would have to do that yourself \"by hand.\")\n\nConsider this illustrative script based loosely on your code:\n\n```python\nimport torch\nprint (torch.__version__)\n\na = torch.tensor ([1.234], requires_grad = True)\nb = a**2\n\ndb_da = torch.autograd.grad (b, a, create_graph = True)\n\nd_db_da_da = torch.autograd.grad (db_da, a, create_graph = True) # works\nprint ('d_db_da_da:', d_db_da_da)\n\n# d_db_da_db = torch.autograd.grad (db_da, b, create_graph = True) # would fail\n\nd_db_da_db = torch.autograd.grad (db_da, b, create_graph = True, allow_unused = True) # runs, but None\nprint ('d_db_da_db:', d_db_da_db)\n```\n\nHere is its output:\n\n```text\n2.6.0+cu126\nd_db_da_da: (tensor([2.], grad_fn=),)\nd_db_da_db: (None,)\n```\n\nWithout knowing what is inside of `self.pinn()`, it's hard to know what you are trying\nto do or why.\n\nOne thought: Going back to single-variable calculus, you could say that:\n\n```text\nd (dy / dx) / dy = (d (dy / dx) / dx) / (dy / dx)\n```\n\nwhere both terms on the right-hand side can be computed with autograd.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":216580,"url":"https://discuss.pytorch.org/t/gradient-computation-with-pytorch-autograd-with-1th-and-2th-order-derivatives-does-not-work/216580","created_at":"2025-02-12T13:12:01.888000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Too many compile workers and huge RAM consumption\n\nWith 4 GPU and 3 dataloader workers per GPU, I end up with 4 x (1 + 3) x 32 = 512 compile worker processes that use ~400MB each, leading to a 200GB RAM consumption.\n* 4 GPU\n* 1 main process + 3 dataloader workers\n* 32 compile worker process each\n\nWhy ? Can I specify the number of workers created ? Can I disable the compile workers in the dataloader workers ?\n\nNote : I have torch2.5.1 and I use torch.compile() with no extra params (=the default ones)","reference_answer":"So, the problem occurs when my `DataLoader` imports a file with a decorated function:\n\n```\n@torch.compile\ndef do_something(A, B):\n return A + B\n```\n\nA simple workaround to avoid creating 32 compile processes in each `DataLoader` worker is:\n\n```\ndef do_something(A, B):\n @torch.compile\n def _do_something(A, B):\n return A + B\n return _do_something(A, B)\n```\n\nWhen `do_something()` is called, it will compile as expected. If it's not called, no compile processes are created.\nThat would be nice to not have to do that.","needs_clarification":false,"thread_id":216645,"url":"https://discuss.pytorch.org/t/too-many-compile-workers-and-huge-ram-consumption/216645","created_at":"2025-02-13T20:28:01.922000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["PierreId"],"answered_by_ptrblck":false} {"question":"'Tensor.data_ptr()' not visible from TorchScript\n\nHi all,\n\nWhen I try to compile a TorchScript module that includes use of the spconv library, I get an error claiming that:\n\n> 'Tensor' boject has no attribute or method 'data_ptr'.\n\nI believe this is because 'data_ptr' is defined in a parent class of Tensor - 'TensorBase'. Since TorchScript doesn't do inheritence, it can't find this method.\n\nI've tried asserting that the tensor is an instance of torch.BaseTensor (or torch._C.BaseTensor). That fails, claiming that that type can't be found.\n\nCan anyone think of a way to make this work?","reference_answer":"I found a solution.\n\nYou can use `torch.library.custom_op` to register the operation. It does not show up by default because it is a call into C++.\n\nExample:\n\n```\n@torch.library.custom_op(\"mylib::data_ptr\", mutates_args=())\ndef data_ptr(tensor: torch.Tensor) -> int:\n return tensor.data_ptr()\n\n@data_ptr.register_fake\ndef _(_: torch.Tensor) -> int:\n return 0\n```\n\nYou then change every instance of `tensor.data_ptr()` to `data_ptr(tensor)`.","needs_clarification":false,"thread_id":216655,"url":"https://discuss.pytorch.org/t/tensor-data-ptr-not-visible-from-torchscript/216655","created_at":"2025-02-14T03:23:48.725000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Avi_Chapman"],"answered_by_ptrblck":false} {"question":"Inference with float16\n\nHi, \n\nI 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: \n\n*** RuntimeError: \"compute_indices_weights_linear\" not implemented for 'Half'\n\nI read some discussions in this regard pointing out that float16() is not supported in a CPU as it wouldn't much speedup. However in my case I want to test with float16 to make sure there is no performance degradation when I port my network to embedded environment with all float16. Is there any way for me to do this other than moving to a CUDA for my inference test?\n\nThanks\nYohannes","reference_answer":"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.","needs_clarification":false,"thread_id":216695,"url":"https://discuss.pytorch.org/t/inference-with-float16/216695","created_at":"2025-02-14T21:52:59.904000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Built-in 0-1 loss function?\n\nPyTorch have a built-in 0-1 loss function?\n\n[Goodfellow et al. p. 102](https://www.deeplearningbook.org/contents/ml.html#pf7):\n\n>The 0-1 loss on a particular example is 0 if it is correctly classified and 1 if it is not.\n\nA custom 0-1 loss function could easily be implemented:\n```python\nclass ZeroOneLoss(torch.nn.Module):\n def __init__(self):\n super(ZeroOneLoss, self).__init__()\n\n def forward(self, input, target):\n if input.equal(target):\n return torch.tensor(0., requires_grad=True)\n else:\n return torch.tensor(1., requires_grad=True)\n```","reference_answer":"Hi Geremia!\n\nNo.\n\nA 0-1 loss function would not be (usefully) differentiable. That is, after backpropagation,\nthe gradients computed for a model's parameters would all be zero (hence giving the\noptimizer no information about how to modify those parameters to reduce the loss).\n\nThis `if-else` construct is not differentiable. Setting `requires_grad = True` for the\nreturn value doesn't fix this.\n\n(You could write a soft loss that is close to one when `input` and `target` are nearly\nequal, but is close to zero when `input` and `target` differ significantly.)\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":216747,"url":"https://discuss.pytorch.org/t/built-in-0-1-loss-function/216747","created_at":"2025-02-16T16:14:21.754000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"RuntimeError: Given groups=1, weight of size [128, 3, 3, 3], expected input[1, 1, 512, 512] to have 3 channels, but got 1 channels instead\n\nI have problem with AI models.\nMy code:\n\nimport torch\nimport numpy as np\nfrom PIL import Image\nfrom diffusers import StableDiffusionInpaintPipeline\nimport cv2\nimport os\nfrom dotenv import load_dotenv\nfrom segment_anything import sam_model_registry, SamPredictor\n\nload_dotenv()\nREV_ANIMATED_MODEL_PATH = os.getenv('REV_ANIMATED_MODEL_PATH')\nKANDINSKY_MODEL_PATH = os.getenv('KANDINSKY_MODEL_PATH')\nVAE_MODEL_PATH = os.getenv('VAE_MODEL_PATH')\nSAM_MODEL_PATH = os.getenv(\"SAM_MODEL_PATH\")\nMODEL_TYPE = \"vit_b\"\nCHECKPOINT_PATH = 'sam_vit_b_01ec64.pth'\nSDV5_MODEL_PATH = os.getenv('SDV5_MODEL_PATH')\nimg = 'inpaint-example.png'\n\n#mask generation function\ndef mask_generator(img):\n image = cv2.imread(img)\n image_rgb = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n\n sam = sam_model_registry[MODEL_TYPE ](checkpoint=CHECKPOINT_PATH)\n sam.to(device='cuda')\n mask_predictor = SamPredictor(sam)\n mask_predictor.set_image(image_rgb)\n input_point = np.array([[250, 250]])\n input_label = np.array([1])\n masks, scores, logits = mask_predictor.predict(\n point_coords=input_point,\n point_labels=input_label,\n multimask_output=False,\n )\n mask = masks.astype(float) * 255\n mask = np.transpose(mask, (1, 2, 0))\n _, bw_image = cv2.threshold(mask, 100, 255, cv2.THRESH_BINARY)\n cv2.imwrite('mask.png', bw_image)\n\n#inpainting function\ndef inpaint(init_img, mask):\n init_image = Image.open(init_img)\n mask_image = Image.open(mask)\n pipe = StableDiffusionInpaintPipeline.from_pretrained(\n SDV5_MODEL_PATH,\n use_safetensors=True,\n torch_dtype=torch.float32\n ).to('cpu')\n negative_prompt = 'ugly'\n prompt = \"a grey cat sitting on a bench, high resolution\"\n image = pipe(prompt=prompt,\n negative_prompt=negative_prompt,\n image=init_image,\n mask_image=mask_image\n ).images[0]\n image.save('output.png')\n\nmask_generator(img)\ninpaint(img, 'mask.png')\n\nAnd i can see this problem in terminal: RuntimeError: Given groups=1, weight of size [128, 3, 3, 3], expected input[1, 1, 512, 512] to have 3 channels, but got 1 channels instead\n\nCan anyone help?","reference_answer":"Ah. Much better. 🙂 Try this:\n\n```\n\ndef inpaint(init_img, mask):\n init_image = Image.open(init_img).convert('RGB') #<<<\n mask_image = Image.open(mask).convert('RGB') #<<<\n\n pipe = StableDiffusionInpaintPipeline.from_pretrained(\n SDV5_MODEL_PATH,\n use_safetensors=True,\n torch_dtype=torch.float32\n ).to('cpu')\n\n negative_prompt = 'ugly'\n prompt = \"a grey cat sitting on a bench, high resolution\"\n image = pipe(prompt=prompt,\n negative_prompt=negative_prompt,\n image=init_image,\n mask_image=mask_image\n ).images[0]\n image.save('output.png')\n```\n\nThat will do the same thing, except for a PIL image object.","needs_clarification":false,"thread_id":216781,"url":"https://discuss.pytorch.org/t/runtimeerror-given-groups-1-weight-of-size-128-3-3-3-expected-input-1-1-512-512-to-have-3-channels-but-got-1-channels-instead/216781","created_at":"2025-02-17T15:36:50.990000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[8],"answer_authors":["J_Johnson"],"answered_by_ptrblck":false} {"question":"Redefining model with fewer parameters → out of memory (OOM)?\n\nWhy when I redefine my model to have fewer parameters and retrain (after training once before) does PyTorch sometimes through an OOM error?\n\nIn other words: How do I tune model hyperparameters without running into OOM errors?\n\nDo I have to reset the computational graph / saved gradients in the dataset's tensors? If so, how?","reference_answer":"When I make too big of a model and training throws an OOM error when passing an batch to it, I have to `del model` and run\n```python\ngc.collect()\ntorch.cuda.empty_cache()\n```","needs_clarification":false,"thread_id":216793,"url":"https://discuss.pytorch.org/t/redefining-model-with-fewer-parameters-out-of-memory-oom/216793","created_at":"2025-02-17T23:50:52.267000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Geremia"],"answered_by_ptrblck":false} {"question":"CrossEntropyLoss doesn't move the weight to same device\n\nIt appears that for CrossEntropyLoss, `.to()` doesn't copy the `weight` to the same device. Would be great to know is this by-design or a bug that is fixed on newer releases?\n\nMinimum example from the usage doc:\n```\n>>> loss = nn.CrossEntropyLoss(weight=torch.FloatTensor([1, 2, 3])).cuda()\n>>> input = torch.randn(3, 5, requires_grad=True).cuda()\n>>> target = torch.empty(3, dtype=torch.long).random_(5).cuda()\n>>> output = loss(input, target)\n```\n\nIt will throw the following exception:\n```\nRuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0!\n```\n\nLooking at the `_WeightedLoss` module, `weight` parameter is registered into the buffer. I assume it should be copied to same device when `.to()` is called from the loss module?\n[image]","reference_answer":"Hi Glen!\n\nIt works for me on version 2.6.0:\n\n```text\n>>> import torch\n>>> print (torch.__version__)\n2.6.0+cu126\n>>> \n>>> ce = torch.nn.CrossEntropyLoss (weight = torch.ones (3))\n>>> \n>>> ce.weight\ntensor([1., 1., 1.])\n>>> list (ce.buffers())\n[tensor([1., 1., 1.])]\n>>> _ = ce.cuda()\n>>> ce.weight\ntensor([1., 1., 1.], device='cuda:0')\n>>> \n>>> input = torch.randn (3, device = 'cuda')\n>>> target = torch.tensor (1, device = 'cuda')\n>>> ce (input, target)\ntensor(0.3248, device='cuda:0')\n```\n\n`weight` is a `buffer` of the `Module` `CrossEntropyLoss`, so it is expected to work.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":216873,"url":"https://discuss.pytorch.org/t/crossentropyloss-doesnt-move-the-weight-to-same-device/216873","created_at":"2025-02-19T07:56:45.910000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"PyTorch install doesn't support cuda 12.6 sm_75\n\nI am running an official docker (holoscan) container on the nvidia clara with ubuntu 20.04LTS.\n1. I installed PyTorch with: ```pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu126```\n2. Then I tried running my code which returns\n```\n/home/holoscan/.local/lib/python3.10/site-packages/torch/cuda/__init__.py:235: UserWarning: \nQuadro RTX 6000 with CUDA capability sm_75 is not compatible with the current PyTorch installation.\nThe current PyTorch install supports CUDA capabilities sm_50 sm_80 sm_86 sm_89 sm_90 sm_90a.\nIf you want to use the Quadro RTX 6000 GPU with PyTorch, please check the instructions at https://pytorch.org/get-started/locally/\n```\n```\nnvidia-smi\nFri Feb 21 10:01:21 2025 \n+---------------------------------------------------------------------------------------+\n| NVIDIA-SMI 535.183.01 Driver Version: 535.183.01 CUDA Version: 12.6 |\n|-----------------------------------------+----------------------+----------------------+\n| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|=========================================+======================+======================|\n| 0 Quadro RTX 6000 Off | 00000000:09:00.0 On | Off |\n| 33% 34C P5 38W / 260W | 795MiB / 24576MiB | 2% Default |\n| | | N/A |\n+-----------------------------------------+----------------------+----------------------+\n \n+---------------------------------------------------------------------------------------+\n| Processes: |\n| GPU GI CI PID Type Process name GPU Memory |\n| ID ID Usage |\n|=======================================================================================|\n+---------------------------------------------------------------------------------------+\n```\n```\nnvcc --version\nnvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2024 NVIDIA Corporation\nBuilt on Fri_Jun_14_16:44:37_PDT_2024\nCuda compilation tools, release 12.6, V12.6.20\nBuild cuda_12.6.r12.6/compiler.34431801_0\n```\n```\npython\nPython 3.10.12 (main, Jul 29 2024, 16:56:48) [GCC 11.4.0] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import torch\n>>> print(torch.cuda.get_arch_list())\n['sm_50', 'sm_80', 'sm_86', 'sm_89', 'sm_90', 'sm_90a']\n```\nHas the sm_75 support been removed?\n\n* I tried the same with an earlier version: ```pip install torch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 --index-url https://download.pytorch.org/whl/cu124```, which returns the same arguments:\n ```\n print(torch.cuda.get_arch_list())\n ['sm_50', 'sm_80', 'sm_86', 'sm_89', 'sm_90', 'sm_90a']\n ```\n\n* I also tried another version: ```pip install torch==2.0.1 --index-url https://download.pytorch.org/whl/cu118```, which gives me this error when trying to run my code:\n ```\n [error] [gxf_wrapper.cpp:100] Exception occurred for operator: 'optimizeData' - AssertionError: Torch not compiled with CUDA enabled\n \n At:\n /home/holoscan/.local/lib/python3.10/site-packages/torch/cuda/__init__.py(239): _lazy_init\n /workspace/volumes/data/ba_hyperspectral_segmentation/move_to_holohub/holohub/applications/biopsy_app_cupy/optimisation_helicoid.py(395): optimize_single_b_torch_np\n /workspace/volumes/data/ba_hyperspectral_segmentation/move_to_holohub/holohub/applications/biopsy_app_cupy/optimisation_helicoid.py(431): helicoid_optimisation_ti_parallel_torch_np\n /workspace/volumes/data/ba_hyperspectral_segmentation/move_to_holohub/holohub/applications/biopsy_app_cupy/biopsy_application.py(362): compute\n \n [error] [entity_executor.cpp:596] Failed to tick codelet optimizeData in entity: optimizeData code: GXF_FAILURE\n [warning] [greedy_scheduler.cpp:243] Error while executing entity 53 named 'optimizeData': GXF_FAILURE\n [info] [greedy_scheduler.cpp:401] Scheduler finished.\n [error] [program.cpp:580] wait failed. Deactivating...\n [error] [runtime.cpp:1649] Graph wait failed with error: GXF_FAILURE\n [warning] [gxf_executor.cpp:2241] GXF call GxfGraphWait(context) in line 2241 of file /workspace/holoscan-sdk/src/core/executors/gxf/gxf_executor.cpp failed with 'GXF_FAILURE' (1)\n [info] [gxf_executor.cpp:2251] Graph execution finished.\n [error] [gxf_executor.cpp:2259] Graph execution error: GXF_FAILURE\n Traceback (most recent call last):\n File \"/workspace/volumes/data/ba_hyperspectral_segmentation/move_to_holohub/holohub/applications/biopsy_app_cupy/biopsy_application.py\", line 527, in \n main()\n File \"/workspace/volumes/data/ba_hyperspectral_segmentation/move_to_holohub/holohub/applications/biopsy_app_cupy/biopsy_application.py\", line 520, in main\n app.run()\n File \"/workspace/volumes/data/ba_hyperspectral_segmentation/move_to_holohub/holohub/applications/biopsy_app_cupy/biopsy_application.py\", line 362, in compute\n errors, coef_list, scattering_params, errors_scatter = helicoid_optimisation_ti_parallel_torch_np(t1, b, M, x)\n File \"/workspace/volumes/data/ba_hyperspectral_segmentation/move_to_holohub/holohub/applications/biopsy_app_cupy/optimisation_helicoid.py\", line 431, in helicoid_optimisation_ti_parallel_torch_np\n results = optimize_single_b_torch_np(range(b.shape[0]), b, [b_t1]*b.shape[0], [a_t1]*b.shape[0], [M]*b.shape[0], [x]*b.shape[0], [current_x]*b.shape[0], [left_bound]*b.shape[0], [right_bound]*b.shape[0])\n File \"/workspace/volumes/data/ba_hyperspectral_segmentation/move_to_holohub/holohub/applications/biopsy_app_cupy/optimisation_helicoid.py\", line 395, in optimize_single_b_torch_np\n b_i = torch.as_tensor(b_i, device='cuda')\n File \"/home/holoscan/.local/lib/python3.10/site-packages/torch/cuda/__init__.py\", line 239, in _lazy_init\n raise AssertionError(\"Torch not compiled with CUDA enabled\")\n AssertionError: Torch not compiled with CUDA enabled\n ```\n torch.cuda.get_arch_list() returns an empty list:\n ```\n >>> import torch\n print(torch.>>> print(torch.cuda.get_arch_list())\n []\n ```\n\nWhich PyTorch version do I have to use, and if it is an older one doesn't this reduce performance?\n\nThis might be related to https://discuss.pytorch.org/t/pytorch-1-6-tesla-t4-with-cuda-capability-sm-75-is-not-compatible/91003 but the used versions are a lot older than the ones I want to use.","reference_answer":"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.","needs_clarification":false,"thread_id":216986,"url":"https://discuss.pytorch.org/t/pytorch-install-doesnt-support-cuda-12-6-sm-75/216986","created_at":"2025-02-21T11:23:47.455000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"OSError: None is not a local folder and is not a valid model identifier listed on 'https://huggingface.co/models'\n\nHi! 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.\n\n**I have next error:**\n```\nOSError: None is not a local folder and is not a valid model identifier listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a token having permission to this repo with `token` or log in with `huggingface-cli login`.\n```\nCode\n```\nimport torch\nfrom controlnet_aux import CannyDetector\nfrom diffusers import StableDiffusionControlNetPipeline, ControlNetModel\nfrom diffusers.utils import load_image, make_image_grid\nimport os\n\nMMIX_MODEL_PATH = os.getenv('MMIX_MODEL_PATH')\nIP_ADAPTER_PATH = os.getenv('IP_ADAPTER')\nCANNY_MODEL_PATH=os.getenv('CANNY_MODEL')\n\nimg1 = 'C:\\\\image-4.png'\nimg2 = 'C:\\\\image-3.png'\n\ncontrolnet = ControlNetModel.from_pretrained(\n CANNY_MODEL_PATH,\n torch_dtype=torch.float16\n #varient=\"fp16\"\n)\n\npipe = StableDiffusionControlNetPipeline.from_pretrained(\n MMIX_MODEL_PATH,\n controlnet=controlnet,\n torch_dtype=torch.float16)\n\npipe.load_ip_adapter(\n IP_ADAPTER_PATH,\n subfolder=\"models\",\nweight_name=\"ip-adapter_sd15.bin\"\n)\n\nip_adap_img = load_image(img2)\nimg = load_image(img1).resize((768, 768))\n\ncanny = CannyDetector()\ncanny_img = canny(img, detect_resolution=512, image_resolution=768)\n\nprompt = \"\"\"(photorealistic:1.2), raw, masterpiece, high quality, 8k, girl wearing hoodie, headphones, hands in pocket\"\"\"\nnegative_prompt = \"low quality, ugly, mutated\"\n\npipe.set_ip_adapter_scale(0.5)\n\nimages = pipe(prompt = prompt,\n negative_prompt = negative_prompt,\n height = 768,\n width = 768,\n ip_adapter_image = ip_adap_img,\n image = canny_img,\n guidance_scale = 6,\n controlnet_conditioning_scale = 0.7,\n num_inference_steps = 20\n ).images[0]","reference_answer":"Check whether the environment variables are set. If they are not, `os.getenv` returns `None`:\n```python\nimport os\n\nMMIX_MODEL_PATH = os.getenv('MMIX_MODEL_PATH')\nprint(MMIX_MODEL_PATH)\n# None\n```\nCall `load_dotenv()` before reading the variables.","needs_clarification":false,"thread_id":216993,"url":"https://discuss.pytorch.org/t/oserror-none-is-not-a-local-folder-and-is-not-a-valid-model-identifier-listed-on-https-huggingface-co-models/216993","created_at":"2025-02-21T15:04:50.224000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["Dmitr","ptrblck"],"answered_by_ptrblck":true} {"question":"Deep Conv1d NN & DataLoader: Must batch_size = in_channels of first Conv1d layer?\n\nI'm training a NN with `Conv1d` layers using DataLoader. Must `data_loader`'s `batch_size` = # of `in_channels` of first Conv1d layer? In my case, if it isn't, I get matrix size mismatch errors.\n\nAlso, are there any tutorials on how to design convolutional NNs in PyTorch. I'm having trouble getting the `in_channel`s and `out_channel`s to be the correct sizes.","reference_answer":"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]`.\n\nIf the shape mismatch is raised on the first linear layer, make sure the incoming input activation has the expected number of features (after fattening).","needs_clarification":false,"thread_id":217011,"url":"https://discuss.pytorch.org/t/deep-conv1d-nn-dataloader-must-batch-size-in-channels-of-first-conv1d-layer/217011","created_at":"2025-02-22T01:49:19.023000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Grad is None confusion in the \"what is torch.nn\" tutorial\n\nI'm following along [What is torch.nn *really*?](https://pytorch.org/tutorials/beginner/nn_tutorial.html) tutorial. There's a setup part in the beginning where they define:\n\n```py\nweights = torch.randn(784, 10) / math.sqrt(784)\nweights.requires_grad_()\n```\n\nI thought I might as well just rewrite that as:\n\n```python\nweights = torch.randn(784, 10, requires_grad=True) / math.sqrt(784)\nassert weights.requires_grad == True\n```\n\nEverything that followed was fine until this loop:\n\n```python\nlr = 0.5 # learning rate\nepochs = 2 # how many epochs to train for\n\nfor epoch in range(epochs):\n for i in range((n - 1) // bs + 1):\n start_i = i * bs\n end_i = start_i + bs\n xb = x_train[start_i:end_i]\n yb = y_train[start_i:end_i]\n pred = model(xb)\n loss = loss_func(pred, yb)\n\n loss.backward()\n with torch.no_grad():\n weights -= weights.grad * lr\n bias -= bias.grad * lr\n weights.grad.zero_()\n bias.grad.zero_()\n```\n\nwhere I got:\n\n```txt\nTypeError Traceback (most recent call last)\n in ()\n 21 with torch.no_grad():\n 22 print((weights.requires_grad, bias.requires_grad))\n---> 23 weights -= weights.grad * lr\n 24 bias -= bias.grad * lr\n 25 weights.grad.zero_()\n\nTypeError: unsupported operand type(s) for *: 'NoneType' and 'float'\n```\n\nTurns out that when I use the original definition:\n\n```py\nweights = torch.randn(784, 10) / math.sqrt(784)\nweights.requires_grad_()\n```\n\nthis error is avoided, but I can't figure out **why**? I know it's got something to do with this division by sqrt of 784 because this also works:\n\n```py\nweights = torch.randn(784, 10, requires_grad=True) # No division\n```\n\nThanks in advance for any feedback.","reference_answer":"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.","needs_clarification":false,"thread_id":217061,"url":"https://discuss.pytorch.org/t/grad-is-none-confusion-in-the-what-is-torch-nn-tutorial/217061","created_at":"2025-02-23T21:17:11.536000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [], which is output 0 of PermuteBackward, is at version 3; expected version 0 instead\n\nSome help please. I am facing the problem that the model cannot be trained. I have tried many methods but still cannot solve the problem.\n\n```\nTraceback (most recent call last):\n File \"tools/train.py\", line 196, in \n main()\n File \"tools/train.py\", line 185, in main\n train_model(\n File \"/home/boot/STU/workspaces/zjf/ViTPose/mmpose/apis/train.py\", line 200, in train_model\n runner.run(data_loaders, cfg.workflow, cfg.total_epochs)\n File \"/home/boot/STU/workspaces/zjf/mmcv/mmcv/runner/epoch_based_runner.py\", line 127, in run\n epoch_runner(data_loaders[i], **kwargs)\n File \"/home/boot/STU/workspaces/zjf/mmcv/mmcv/runner/epoch_based_runner.py\", line 51, in train\n self.call_hook('after_train_iter')\n File \"/home/boot/STU/workspaces/zjf/mmcv/mmcv/runner/base_runner.py\", line 307, in call_hook\n getattr(hook, fn_name)(self)\n File \"/home/boot/STU/workspaces/zjf/mmcv/mmcv/runner/hooks/optimizer.py\", line 36, in after_train_iter\n runner.outputs['loss'].backward()\n File \"/home/boot/anaconda3/envs/vitpose/lib/python3.8/site-packages/torch/tensor.py\", line 245, in backward\n torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)\n File \"/home/boot/anaconda3/envs/vitpose/lib/python3.8/site-packages/torch/autograd/__init__.py\", line 145, in backward\n Variable._execution_engine.run_backward(\nRuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [64, 144, 28, 28]], which is output 0 of PermuteBackward, is at version 3; expected version 0 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!\n```\nUsing \"torch.autograd.set_detect_anomaly(True)\" to checkout.\n```\n[W python_anomaly_mode.cpp:104] Warning: Error detected in CudnnConvolutionBackward. Traceback of forward call that caused the error:\n File \"tools/train.py\", line 196, in \n main()\n File \"tools/train.py\", line 185, in main\n train_model(\n File \"/home/boot/STU/workspaces/zjf/ViTPose/mmpose/apis/train.py\", line 200, in train_model\n runner.run(data_loaders, cfg.workflow, cfg.total_epochs)\n File \"/home/boot/STU/workspaces/zjf/mmcv/mmcv/runner/epoch_based_runner.py\", line 127, in run\n epoch_runner(data_loaders[i], **kwargs)\n File \"/home/boot/STU/workspaces/zjf/mmcv/mmcv/runner/epoch_based_runner.py\", line 50, in train\n self.run_iter(data_batch, train_mode=True, **kwargs)\n File \"/home/boot/STU/workspaces/zjf/mmcv/mmcv/runner/epoch_based_runner.py\", line 29, in run_iter\n outputs = self.model.train_step(data_batch, self.optimizer,\n File \"/home/boot/STU/workspaces/zjf/mmcv/mmcv/parallel/distributed.py\", line 53, in train_step\n output = self.module.train_step(*inputs[0], **kwargs[0])\n File \"/home/boot/STU/workspaces/zjf/ViTPose/mmpose/models/detectors/base.py\", line 104, in train_step\n losses = self.forward(**data_batch)\n File \"/home/boot/STU/workspaces/zjf/mmcv/mmcv/runner/fp16_utils.py\", line 98, in new_func\n return old_func(*args, **kwargs)\n File \"/home/boot/STU/workspaces/zjf/ViTPose/mmpose/models/detectors/top_down.py\", line 138, in forward\n return self.forward_train(img, target, target_weight, img_metas,\n File \"/home/boot/STU/workspaces/zjf/ViTPose/mmpose/models/detectors/top_down.py\", line 145, in forward_train\n output = self.backbone(img)\n File \"/home/boot/anaconda3/envs/vitpose/lib/python3.8/site-packages/torch/nn/modules/module.py\", line 889, in _call_impl\n result = self.forward(*input, **kwargs)\n File \"/home/boot/STU/workspaces/zjf/ViTPose/models/dilateformer.py\", line 452, in forward\n x = self.forward_features(x)\n File \"/home/boot/STU/workspaces/zjf/ViTPose/models/dilateformer.py\", line 441, in forward_features\n x = stage(x)\n File \"/home/boot/anaconda3/envs/vitpose/lib/python3.8/site-packages/torch/nn/modules/module.py\", line 889, in _call_impl\n result = self.forward(*input, **kwargs)\n File \"/home/boot/STU/workspaces/zjf/ViTPose/models/dilateformer.py\", line 331, in forward\n x = blk(x)\n File \"/home/boot/anaconda3/envs/vitpose/lib/python3.8/site-packages/torch/nn/modules/module.py\", line 889, in _call_impl\n result = self.forward(*input, **kwargs)\n File \"/home/boot/STU/workspaces/zjf/ViTPose/models/dilateformer.py\", line 138, in forward\n x = x + self.drop_path(self.attn(self.norm1(x)))\n File \"/home/boot/anaconda3/envs/vitpose/lib/python3.8/site-packages/torch/nn/modules/module.py\", line 889, in _call_impl\n result = self.forward(*input, **kwargs)\n File \"/home/boot/STU/workspaces/zjf/ViTPose/models/dilateformer.py\", line 90, in forward\n qkv = self.qkv(x)\n File \"/home/boot/anaconda3/envs/vitpose/lib/python3.8/site-packages/torch/nn/modules/module.py\", line 889, in _call_impl\n result = self.forward(*input, **kwargs)\n File \"/home/boot/anaconda3/envs/vitpose/lib/python3.8/site-packages/torch/nn/modules/conv.py\", line 399, in forward\n return self._conv_forward(input, self.weight, self.bias)\n File \"/home/boot/anaconda3/envs/vitpose/lib/python3.8/site-packages/torch/nn/modules/conv.py\", line 395, in _conv_forward\n return F.conv2d(input, weight, bias, self.stride,\n (function _print_stack)\n```\n\nIt seems that the error occurred in File\"/home/boot/STU/workspaces/zjf/ViTPose/models/dilateformer.py\", line 90, in forward\nwhich is \"qkv = self.qkv(x)\" in function forward\nHowever, I can't fix the error in this code\n```\nclass MultiDilatelocalAttention(nn.Module):\n \"Implementation of Dilate-attention\"\n\n def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None,\n attn_drop=0.,proj_drop=0., kernel_size=3, dilation=[1, 2, 3]):\n super().__init__()\n self.dim = dim\n self.num_heads = num_heads\n head_dim = dim // num_heads\n self.dilation = dilation\n self.kernel_size = kernel_size\n self.scale = qk_scale or head_dim ** -0.5\n self.num_dilation = len(dilation)\n assert num_heads % self.num_dilation == 0, f\"num_heads{num_heads} must be the times of num_dilation{self.num_dilation}!!\"\n self.qkv = nn.Conv2d(dim, dim * 3, 1, bias=qkv_bias)\n self.dilate_attention = nn.ModuleList(\n [DilateAttention(head_dim, qk_scale, attn_drop, kernel_size, dilation[i])\n for i in range(self.num_dilation)])\n self.proj = nn.Linear(dim, dim)\n self.proj_drop = nn.Dropout(proj_drop)\n\n def forward(self, x):\n B, H, W, C = x.shape\n x = x.permute(0, 3, 1, 2)# B, C, H, W\n \"\"\"\n Only here grad disapear\n \"\"\"\n print('x before reshape:', x._version)\n qkv = self.qkv(x).reshape(B, 3, self.num_dilation, C//self.num_dilation, H, W).permute(2, 1, 0, 3, 4, 5)\n #num_dilation,3,B,C//num_dilation,H,W\n print('qkv:', qkv._version)\n x = x.reshape(B, self.num_dilation, C//self.num_dilation, H, W).permute(1, 0, 3, 4, 2)\n print('x after reshape:', x._version)\n # num_dilation, B, H, W, C//num_dilation\n for i in range(self.num_dilation):\n x[i] = self.dilate_attention[i](qkv[i][0], qkv[i][1], qkv[i][2])# B, H, W,C//num_dilation\n print('x after qkv:', x._version)\n x = x.permute(1, 2, 3, 0, 4).reshape(B, H, W, C)\n x = self.proj(x)\n x = self.proj_drop(x)\n return x\n\n```","reference_answer":"The error comes from an in-place write into a tensor that autograd is tracking, such as `x[i] = ...`. Writing into a tensor with indexing is an in-place modification, so it changes a tensor that backward still needs. To locate it, compare `x.shape` and `x._version` around the suspect line with the version number in the error message. Remove the in-place write.\n\nThe allow-mutation context manager (`torch.autograd.graph.allow_mutation_on_saved_tensors`) only hides this error; it does not fix it.","needs_clarification":false,"thread_id":217071,"url":"https://discuss.pytorch.org/t/runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation-torch-cuda-floattensor-which-is-output-0-of-permutebackward-is-at-version-3-expected-version-0-instead/217071","created_at":"2025-02-24T03:04:56.489000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["KFrank","Zhouker"],"answered_by_ptrblck":false} {"question":"Fixing seeds affects performance?\n\nHey all,\nReferring to topics like [How could I fix the random seed absolutely](https://discuss.pytorch.org/t/how-could-i-fix-the-random-seed-absolutely/45515). I couldn't find any resources talking about the effects of fixing all seeds and going`torch.backends.cudnn.enabled=False torch.backends.cudnn.deterministic=True`. Does this affect performance of training at all ?\n\n```\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport random\nimport my_model\nimport my_dataset\n\ntorch.manual_seed(123)\ntorch.cuda.manual_seed(123)\nnp.ranom.seed(123)\nrandom.seed(123)\ntorch.backends.cudnn.enabled=False\ntorch.backends.cudnn.deterministic=True\n\ndef train():\n...\n\nif __name__ == '__main__':\n train()\n```","reference_answer":"I assume performance means training speed here. Yes, disabling cuDNN or selecting deterministic algorithms could slow down your code.","needs_clarification":false,"thread_id":217176,"url":"https://discuss.pytorch.org/t/fixing-seeds-affects-performance/217176","created_at":"2025-02-26T09:47:31.341000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Import torchvision fails on NVIDIA jetson orin nano\n\nHello,\n\nI am trying to install pytorch and torchvision on my nvidia jetson orin nano. I have referred this guide : https://docs.nvidia.com/deeplearning/frameworks/install-pytorch-jetson-platform/index.html#benefits\n\nDevice : NVIDIA Jetson Orin Nano\nJetpack : 5.1.3\nPython : 3.8\nPytorch : 2.0.0\ntorchvision : 0.15.1 (also tried 0.15.2)\n\nHere are the flags during compilation of torchvision:\n\nBuilding wheel torchvision-0.15.1\nCompiling extensions with following flags:\n FORCE_CUDA: False\n DEBUG: False\n TORCHVISION_USE_PNG: True\n TORCHVISION_USE_JPEG: True\n TORCHVISION_USE_NVJPEG: True\n TORCHVISION_USE_FFMPEG: True\n TORCHVISION_USE_VIDEO_CODEC: True\n NVCC_FLAGS: \nFound PNG library\nBuilding torchvision with PNG image support\n libpng version: 1.6.37\n libpng include path: /usr/include/libpng16\nRunning build on conda-build: False\nRunning build on conda: False\n\ntorchvision is installed correctly but, when i run import torchvision, to verify the installation, I get the below error:\n\n$python -c \"import torchvision; print(torchvision.__version__)\"\nTraceback (most recent call last):\n File \"\", line 1, in \n File \"/home/chandorkar/.local/lib/python3.8/site-packages/torchvision-0.15.1-py3.8-linux-aarch64.egg/torchvision/__init__.py\", line 6, in \n from torchvision import datasets, io, models, ops, transforms, utils\n File \"/home/chandorkar/.local/lib/python3.8/site-packages/torchvision-0.15.1-py3.8-linux-aarch64.egg/torchvision/datasets/__init__.py\", line 1, in \n from ._optical_flow import FlyingChairs, FlyingThings3D, HD1K, KittiFlow, Sintel\n File \"/home/chandorkar/.local/lib/python3.8/site-packages/torchvision-0.15.1-py3.8-linux-aarch64.egg/torchvision/datasets/_optical_flow.py\", line 13, in \n from .utils import _read_pfm, verify_str_arg\n File \"/home/chandorkar/.local/lib/python3.8/site-packages/torchvision-0.15.1-py3.8-linux-aarch64.egg/torchvision/datasets/utils.py\", line 22, in \n import requests\n File \"/home/chandorkar/.local/lib/python3.8/site-packages/requests-2.32.3-py3.8.egg/requests/__init__.py\", line 43, in \n import urllib3\n File \"/home/chandorkar/.local/lib/python3.8/site-packages/urllib3-2.3.0-py3.8.egg/urllib3/__init__.py\", line 14, in \n from . import exceptions\n File \"/home/chandorkar/.local/lib/python3.8/site-packages/urllib3-2.3.0-py3.8.egg/urllib3/exceptions.py\", line 26, in \n _TYPE_REDUCE_RESULT = tuple[typing.Callable[..., object], tuple[object, ...]]\nTypeError: 'type' object is not subscriptable","reference_answer":"So it looks like urllib3 2.3.0 removed support for python 3.8\n\nlink to changelog:\nhttps://urllib3.readthedocs.io/en/stable/changelog.html\n\nPotential solutions:\n- downgrading your urllib3<2\n- upgrading your python version to >3.8\n\nThis was all I could find at the moment. Hope this helps!","needs_clarification":false,"thread_id":217199,"url":"https://discuss.pytorch.org/t/import-torchvision-fails-on-nvidia-jetson-orin-nano/217199","created_at":"2025-02-26T18:34:09.423000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["mycul"],"answered_by_ptrblck":false} {"question":"Finding issue for high memory bandwidth between CPU and GPU\n\nI have implemented some models for generating text with LSTM layers etc., mostly according\nto the typical encoder-decoder scheme and autoregressive training. Now, training one of the more complex models produced the issue of relatively constant GPU VRAM usage of about 30 percent, but the bandwidth of data being copied from CPU to GPU or backwards is at about 40GB/s.\n\nIn the training loop, I copy the batches to the GPU and do the computations (forward step etc.).\nAll layers and tensors are initialized directly on the GPU.\nThe result is a horribly slow training, and I am unsure where this overhead of copying comes from, because I do not use a single explicit copying from GPU to CPU in the code, nor do I get errors that tell me that not all tensors are on the same device.\n\nDoes anyone have any idea how to identify the issue and / or what the reason may be?\n\nThank you in advance","reference_answer":"The issue was, that a function call copied once per forward step all tensors etc. from the GPU to the CPU and back again, which led to a bandwidth usage of 40 GB/s between GPU and CPU. THis slowed down the training process. Effectively, I overlooked that I used \"any\" instead of \"torch.any\", the former being executed on the CPU, the latter on GPU. Now its fixed and training is lightening fast. Is there a method to alert users with e.g. a warning when between pytorch operations, one is using a pythonic function that copies back to CPU? I just did not find the error due to the fact that I wasn't aware of the copying process that happened under the hood.","needs_clarification":false,"thread_id":217227,"url":"https://discuss.pytorch.org/t/finding-issue-for-high-memory-bandwidth-between-cpu-and-gpu/217227","created_at":"2025-02-27T11:23:48.124000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["MLangner"],"answered_by_ptrblck":false} {"question":"Which cuda version to choose when installing pytorch\n\nHi, I am new to using pytorch and I have a question about installation.\n\nIn 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? \n[image]\n\nThanks so much.","reference_answer":"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 12.8.","needs_clarification":false,"thread_id":217257,"url":"https://discuss.pytorch.org/t/which-cuda-version-to-choose-when-installing-pytorch/217257","created_at":"2025-02-27T23:48:45.348000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Gradient of loss (that depends on gradient of network) with respect to parameters\n\nI'm trying to compute the gradient of my loss function with respect to my model parameters in PyTorch. \n\nThat is, let `u(x; θ)` be the model, where `x` is the input (in `R^n`) and `θ` are the model parameters. I'm trying to compute `du/dθ`.\n\nFor a \"simple\" loss function, this is not a problem, but my loss function depends on the gradient of the model with respect to its inputs (i.e., `du/dx`). When I attempt to do this, I'm met with the following error message: `One of the differentiated Tensors appears to not have been used in the graph. Set allow_unused=True if this is the desired behavior.`\n\nHere is a minimal example to illustrate the issue:\n\n```\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import grad\n\nmodel = nn.Sequential(nn.Linear(1, 10), nn.Tanh(), nn.Linear(10, 1))\n\ndef loss1(x, u):\n return torch.mean(u)\n\ndef loss2(x, u):\n d_u_x = grad(u, x, torch.ones_like(u), retain_graph=True, create_graph=True)[0]\n return torch.mean(d_u_x)\n\nx = torch.randn(10, 1)\nx.requires_grad_()\nu = model(x)\n\nloss = loss2(x, u)\nd_loss_params = grad(loss, model.parameters(), retain_graph=True)\n```\n\nIf I change the second to last line to read `loss = loss1(x, u)` things work as expected.\n\nUpdate: it appears to be working if I set `bias=False` for the `nn.Linear`s. OK, that makes some sense since the bias is not trainable. But that begs the question, how do I extract only the trainable parameters to use in the gradient computation?","reference_answer":"The error happens because the bias of the last `Linear` only adds a constant to the output, so autograd leaves it out of the graph used to compute the derivative. Passing `allow_unused=True` stops the error, but the gradients for unused parameters are then `None`. To get zeros instead, also pass `materialize_grads=True`:\n\n```python\nd_loss_params = grad(loss, model.parameters(), retain_graph=True, allow_unused=True, materialize_grads=True)\n```","needs_clarification":false,"thread_id":217275,"url":"https://discuss.pytorch.org/t/gradient-of-loss-that-depends-on-gradient-of-network-with-respect-to-parameters/217275","created_at":"2025-02-28T09:24:45.922000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["KFrank","bwehlin"],"answered_by_ptrblck":false} {"question":"Loading donut transformers model getting error\n\nself.model = self.model.to(self.device)\nFile “/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py”, line 1145, in to\nreturn self._apply(convert)\nFile “/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py”, line 797, in _apply\nmodule._apply(fn)\nFile “/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py”, line 797, in _apply\nmodule._apply(fn)\nFile “/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py”, line 797, in _apply\nmodule._apply(fn)\n[Previous line repeated 1 more time]\nFile “/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py”, line 820, in _apply\nparam_applied = fn(param)\nFile “/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py”, line 1143, in convert\nreturn t.to(device, dtype if t.is_floating_point() or t.is_complex() else None, non_blocking)\nRuntimeError: CUDA error: device-side assert triggered\nCompile with TORCH_USE_CUDA_DSA to enable device-side assertions.\n\nmy code is\nclass Donut:\ndef init(self):\nself.processor = DonutProcessor.from_pretrained(“naver-clova-ix/donut-base-finetuned-docvqa”)\nself.model = VisionEncoderDecoderModel.from_pretrained(“naver-clova-ix/donut-base-finetuned-docvqa”)\nself.device = “cuda” if torch.cuda.is_available() else “cpu”\nself.model.to(self.device)\n\ntorch version :- torch==2.0.1+cu118\ntorchaudio==2.0.2+cu118\ntorchvision==0.15.2+cu118\nNvidia Driver :- Driver Version: 550.144.03 CUDA Version: 12.4","reference_answer":"Device-side asserts are often triggered by failing indexing operations, so check that the inputs to operations such as an embedding layer are valid. In this case, the cause was a mismatch in `max_position_embeddings`.","needs_clarification":false,"thread_id":217284,"url":"https://discuss.pytorch.org/t/loading-donut-transformers-model-getting-error/217284","created_at":"2025-02-28T11:32:05.605000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["ankita1","ptrblck"],"answered_by_ptrblck":true} {"question":"How can I use an iterable dataset and dataloader for ML training?\n\nHi everyone, \nI 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.\n\nFrom my understanding, if you use an iterable dataset then that means you need to take care of the shuffling? And we need to shuffle the data in each epoch to do so, to avoid overfitting.\n\nI'm confused about how should I initalize the dataset and dataloader before training. Do I make a call to the dataset and dataloader in each epoch? How does the sequence go? Also do I need an dataset shuffler to shuffle the data in that case?","reference_answer":"Lazy loading is the standard approach, so data that doesn't fit in memory does not by itself require an iterable dataset. With a map-style dataset, store only the paths to your samples and load each sample by its index in `__getitem__`. No data is preloaded this way; only the samples needed for the current batch are loaded into memory, multiplied by the batch size, number of workers and prefetch factor. You don't need a custom shuffler, because the DataLoader shuffles the indices when `shuffle=True`. Create the dataset and the DataLoader once, before the loop over the epochs. The ImageNet example in the PyTorch repository shows this.","needs_clarification":true,"thread_id":217290,"url":"https://discuss.pytorch.org/t/how-can-i-use-an-iterable-dataset-and-dataloader-for-ml-training/217290","created_at":"2025-02-28T13:11:51.034000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4,6,8],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Handling varying in_channels in Conv1D layer\n\nI am training a convolutional neural network in pytorch. I'm training it on data in the form of [n, 3] where 'n' can be any number. The first layer in my network is a Conv1d layer that operates over the 'n' portion of the input tensor. How can I define my model's architecture so that it accepts varying number of in_channels in the first conv layer, because during testing 'n' might change, the reason for that is because I'm working with 3D data, and my model is classifying 3D Models based upon their vertices (having the shape [n, 3]), and during testing the shape of the vertices might change.\n\nIn Keras I don't have to worry about the in_channels of a convolutional layer, how can I implement a similar logic in PyTorch.\n\nFollowing is my architecture, it's learning brilliantly, but during testing on different 3d models, the shape [n, 3] changes, how do I fix this? Note padding is not an option, because it can distort the shape of the vertices. Also, FYI my input tensor during training is a packed tensor, meaning that I pack all the vertices of each 3D model in my batch into one [n, 3] tensor (and that is a requirement).\n\n```\nclass ClassificationModel(nn.Module):\n # Currently I'm passing 'n' of the training samples as the in_channels\n def __init__(self, in_channels):\n super().__init__()\n\n self._in_channels = in_channels\n \n self._conv_sequential = nn.Sequential(\n nn.Conv1d(in_channels=self._in_channels, out_channels=4096, kernel_size=3, stride=1, padding=\"same\"),\n nn.Tanh(),\n nn.Conv1d(in_channels=4096, out_channels=2048, kernel_size=3, stride=1, padding=\"same\"),\n nn.Tanh(),\n nn.Conv1d(in_channels=2048, out_channels=1024, kernel_size=3, stride=1, padding=\"same\"),\n nn.Tanh(),\n nn.Conv1d(in_channels=1024, out_channels=512, kernel_size=3, stride=1, padding=\"same\"),\n nn.Tanh(),\n nn.Conv1d(in_channels=512, out_channels=256, kernel_size=3, stride=1, padding=\"same\"),\n nn.Tanh(),\n nn.Conv1d(in_channels=256, out_channels=64, kernel_size=3, stride=1, padding=\"same\"),\n nn.Tanh(),\n nn.Conv1d(in_channels=64, out_channels=16, kernel_size=3, stride=1, padding=\"same\"),\n nn.Tanh(),\n nn.Conv1d(in_channels=16, out_channels=2, kernel_size=3, stride=1, padding=\"same\"),\n nn.Tanh(),\n )\n \n self._linear_sequential = nn.Sequential(\n nn.Linear(in_features=3, out_features=1),\n )\n\n def forward(self, mesh: pytorch3d.structures.Meshes):\n vertices = mesh.verts_packed()\n\n output: torch.Tensor = self._conv_sequential(vertices)\n output: torch.Tensor = self._linear_sequential(output)\n\n \n return F.sigmoid(output)\n```","reference_answer":"Perhaps I'm unclear, but why aren't you just flattening it? \n\nFrom what you've described, here is what I would suggest doing:\n1. Reshape the (B, n, 3) into (B, 1, n*3);\n2. Change the stride to 3(unless there's some significance to the order of vertices). \n3. The out_channels of the first layer can be whatever you want.\n4. After all convolutions are applied and before the feedforward network, use [nn.AdaptiveAvgPool1d](https://pytorch.org/docs/stable/generated/torch.nn.AdaptiveAvgPool1d.html).","needs_clarification":false,"thread_id":217333,"url":"https://discuss.pytorch.org/t/handling-varying-in-channels-in-conv1d-layer/217333","created_at":"2025-03-02T07:07:46.387000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["J_Johnson"],"answered_by_ptrblck":false} {"question":"Using buffers in ParallelEnvs / MultiSyncCollectors\n\nHi, I've been moving a custom environment from dynamically sized to statically known observation sizes and I came across unexpected behavior in how the input and output TensorDicts in `_step()` are behaving. \n\nWhat is the expected convention for how `next = _step(td)` should read and write its observations? Am I doing anything wrong? \n\nBased the documentation I expected the following:\n- \"td\" contains the observations from the last output in the trajectory\n- \"next\" should be this last output \n\nI observe this when running \"use_buffers=False\" (or with dynamically sized input as this also disables the buffers). \n\nBut when running with \"buffers=True\" every step is reading from the initial reset. \n\nI created a minimal example that only takes in and increments the last observations. \n\n```\nTesting ParallelEnv\n========================================\nNo buffers (expected behavior)\nInput: tensor(1)\nOutput: tensor(2)\nInput: tensor(2)\nOutput: tensor(3)\nInput: tensor(3)\nOutput: tensor(4)\n========================================\nBuffers (unexpected behavior)\nInput: tensor(1)\nOutput: tensor(2)\nInput: tensor(1)\nOutput: tensor(2)\nInput: tensor(1)\nOutput: tensor(2)\n```\n\nCode to reproduce:\n```\nimport torch\nfrom typing import Optional\nfrom torchrl.envs import EnvBase\nfrom torchrl.data import Composite, TensorSpec, Unbounded, Binary, Bounded\nfrom torchrl.envs import check_env_specs\nfrom tensordict import TensorDict\n\nclass TestEnv(EnvBase):\n def __init__(self, seed: int = 0, device=\"cpu\"):\n super().__init__(device=device)\n\n self.observation_spec = self._create_observation_spec()\n self.action_spec = self._create_action_spec()\n self.reward_spec = self._create_reward_spec()\n self.done_spec = Binary(shape=(1,), device=self.device, dtype=torch.bool)\n\n def _create_observation_spec(self) -> TensorSpec:\n obs = Unbounded(shape=(1,), device=self.device, dtype=torch.int64)\n comp = Composite(value=obs)\n comp = Composite(observation=comp)\n return comp\n\n def _create_action_spec(self) -> TensorSpec:\n out = Bounded(\n shape=(1,),\n device=self.device,\n dtype=torch.int32,\n low=torch.tensor(0, device=self.device),\n high=torch.tensor(4, device=self.device),\n )\n out = Composite(action=out)\n return out\n\n def _create_reward_spec(self) -> TensorSpec:\n return Unbounded(shape=(1,), device=self.device, dtype=torch.float32)\n\n def _get_observation(self, v) -> TensorDict:\n obs = TensorDict(value=torch.tensor([0], device=self.device, dtype=torch.int64))\n obs[\"value\"][0] = v + 1\n obs = TensorDict(observation=obs)\n return obs\n\n def _step(self, td: TensorDict) -> TensorDict:\n print(\"Input: \", td[\"observation\"][\"value\"][0])\n out = self._get_observation(td[\"observation\"][\"value\"][0])\n print(\"Output: \", out[\"observation\"][\"value\"][0])\n out.set(\"reward\", torch.tensor([1], device=self.device, dtype=torch.float32))\n out.set(\"done\", torch.tensor([False], device=self.device, dtype=torch.bool))\n return out\n\n def _reset(self, td: Optional[TensorDict] = None) -> TensorDict:\n obs = self._get_observation(0)\n\n return obs\n\n def _set_seed(self, seed: Optional[int] = None):\n rng = torch.manual_seed(seed)\n self.rng = rng\n\ndef make_env():\n return TestEnv()\n\nif __name__ == \"__main__\":\n from torchrl.envs import ParallelEnv\n\n print(\"Testing ParallelEnv\")\n print(\"========================================\")\n print(\"No buffers\")\n workers = 1\n penv = ParallelEnv(\n workers,\n [make_env for _ in range(workers)],\n use_buffers=False,\n )\n r = penv.rollout(3)\n\n print(\"========================================\")\n print(\"Buffers\")\n\n workers = 1\n penv = ParallelEnv(\n workers,\n [make_env for _ in range(workers)],\n use_buffers=True,\n )\n r = penv.rollout(3)\n\n```\n\nAlso is there a way to write to the preallocated memory \"in place\" to avoid temporary allocations for new observations at each step (before they are copied into the buffers)?","reference_answer":"Updating here in case anyone runs into a similar issue. This behavior has been fixed in newer versions of TorchRL (>[0.7.2](https://github.com/pytorch/rl/releases/tag/v0.7.2)).","needs_clarification":false,"thread_id":217363,"url":"https://discuss.pytorch.org/t/using-buffers-in-parallelenvs-multisynccollectors/217363","created_at":"2025-03-03T01:46:14.179000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["wlruys"],"answered_by_ptrblck":false} {"question":"Can Multi-Channel Outputs in U-Net Represent Multiple Time Steps for Rainfall Prediction?\n\nHello everyone,\n\nI'm currently encountering an issue while using U-Net. My input consists of multi-channel grid data derived from various meteorological features, and the output is a 7-hour future rainfall prediction map. Each grid point is represented as either 1 or 0, indicating whether the accumulated rainfall in that grid exceeds 40 mm.\n\nInitially, I planned to train 7 separate models, each responsible for predicting rainfall at a specific future time step. However, ChatGPT suggested an alternative approach: using a single model with 7 output channels, where each channel corresponds to a different future time step.\n\nThis leads me to a question.\n\nU-Net is typically used for semantic segmentation, where multiple channels represent different semantic categories.\n\nDoes this approach make sense, or would training separate models be more effective? I'd appreciate any insights!","reference_answer":"Well... From my point of view, training a single model should be a better choice in most cases...\n\nYou could interpret your model as two parts: encoder (i.e. all layers except for the last layer) and classifier (i.e. the last layer). Training a single model is somehow equivalent to training a shared encoder and 7 separated classifiers ---- less parameters (i.e. no need for 7 encoders), more parallelization (i.e. one forward pass for all, not 7 forward passes).\n\nMoreover, generally speaking, you cannot assume your future predictions are not correlated to each other. With a shared encoder, your model could capture correlations between different future predictions (i.e. features that are useful for all predictions). If you could safely assume that all future predictions are independent, you could, in theory, achieve similar or the same accuracy with separated models, but generally speaking, I would recommend starting with a single model.\n\nP.S.\nExperiments are always recommended. If you are uncertain and you have enough time, get your hands dirty and try it :)","needs_clarification":false,"thread_id":217366,"url":"https://discuss.pytorch.org/t/can-multi-channel-outputs-in-u-net-represent-multiple-time-steps-for-rainfall-prediction/217366","created_at":"2025-03-03T03:50:16.496000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Naming-isDifficult"],"answered_by_ptrblck":false} {"question":"Memory used by `autograd` when `torch.scatter` is involved\n\nI am trying to implement gradient computation (fine-tuning) for large context LLMs in the presence of sparse inference and KV caching. In this context, the following arises.\n\nDenote KV cache buffer content by `cache_t` which has (simplified) shape `(batch, cache_len)`, where `cache_len` is the number of slots in the cache, and `batch` is everything else, e.g. batch size, embedding dimension. A large context is processed sequentially, which means that during multi-head attention (MHA), `cache_t` is mapped to `cache_(t+1)` by writing KV content for new tokens into the cache, overwriting previous content. This is done as\n\n```\ncache_(t+1) = torch.scatter(cache_t, -1, index, new_kv)\n```\nwhere `index` maps to positions to be overwritten, and `new_kv` is the new content.\n\nThe new content `new_kv` has shape `(batch, new_len)`, where `new_len` is much smaller than `cache_len`. And then, `cache_t` takes part in MLA computations being the key and value tensors the query tensor for the t-th sequential step is interacting with. If you know token-by-token generation, this would correspond to `new_len = 1`, but when the whole input is given (during training), we can choose `new_len > 1`.\n\nMy question is: If the computation graph looks like this, what memory does `autograd` store during the forward pass in training mode? Say there are `T` sequential steps.\n\n- It could be simple, but wasteful: `autograd` stores all `cache_t`, so `T` times `batch * cache_len`.\n- It could be a little more difficult, but use less memory: `autograd` stores the first `cache_0`, but then only two tensors of size `batch * new_len` for each `t`, namely `new_kv` and the content that is overwritten, so `torch.gather(cache_t, -1, index)`. Obviously, I can obtain `cache_(t+1)` from `cache_t` if I know these two. This would be one time `batch * cache_len` plus `T` times `2 * batch * new_len`.\n\nCan somebody help me?","reference_answer":"`scatter` is linear in `cache_t`, so autograd does not need to save `cache_t` for the scatter's backward pass.\n\nBut if `cache_t` is then used in linear or conv operations, those operations still save their inputs to compute weight gradients, so those activations are stored.\n\nFor general activation memory, use activation checkpointing: https://pytorch.org/docs/stable/checkpoint.html","needs_clarification":false,"thread_id":217387,"url":"https://discuss.pytorch.org/t/memory-used-by-autograd-when-torch-scatter-is-involved/217387","created_at":"2025-03-03T15:57:44.285000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,5],"answer_authors":["soulitzer"],"answered_by_ptrblck":false} {"question":"How to preserve computational graph while initializing a network with weights\n\nSo I want to train a meta network whose output is the weights of another network.\n\nFor example, suppose `generated_weights` denotes the weights generated by the meta network, I tried using the following code to inject those weights into another network:\n\n```python\nfor name, param in backbone.named_parameters():\n param.data.copy_(generated_weights[name][0])\n```\n\nHowever, when I was using this to train and printed out the weights, I observed that the weights didn't change at all, which means the backprop or the optimizer didn't work for some reason, and I suspect that the operation `.copy_` doesn't preserve the computational graph?\n\nI have no idea how to accomplish this task. Really appreciate any help.\n\n`train.py`:\n\n```python\nimport tqdm\nimport math\nimport torch\nimport numpy as np\nfrom torch import nn\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import ListedColormap\nfrom model.backbone import Backbone\nfrom model.metanet import MetaNet\nfrom torch.func import functional_call\n\ndef gen_data(task='A'):\n N = 1000\n x_min, x_max = -4, 4\n y_min, y_max = -4, 4\n resolution = 100 # Resolution of the grid\n\n # Create the grid\n x = np.linspace(x_min, x_max, resolution)\n y = np.linspace(y_min, y_max, resolution)\n X, Y = np.meshgrid(x, y)\n\n # Checkerboard pattern\n length = 4\n if task == 'A':\n checkerboard = np.indices((length, length)).sum(axis=0) % 2\n else:\n checkerboard = np.indices((length, length)).sum(axis=0) % 3\n\n # Sample points in regions where checkerboard pattern is 1\n sampled_points = []\n while len(sampled_points) < N:\n # Randomly sample a point within the x and y range\n x_sample = np.random.uniform(x_min, x_max)\n y_sample = np.random.uniform(y_min, y_max)\n \n # Determine the closest grid index\n i = int((x_sample - x_min) / (x_max - x_min) * length)\n j = int((y_sample - y_min) / (y_max - y_min) * length)\n \n # Check if the sampled point is in a region where checkerboard == 1\n if checkerboard[j, i] == 1:\n sampled_points.append((x_sample, y_sample))\n\n return sampled_points\n\nmodel = Backbone(layers=5, channels=512)\nmetanet = MetaNet(model)\noptim = torch.optim.AdamW(list(metanet.parameters()) + list(model.parameters()), lr=1e-4)\ncriterion = nn.MSELoss()\ndevice = torch.device(\"cpu\")\nmodel.to(device)\nmetanet.to(device)\n\nnum_epochs = 1000\n\nfor epoch in tqdm.tqdm(range(num_epochs)):\n optim.zero_grad()\n\n task = np.random.choice(['A', 'B'])\n if task == 'A':\n task_info = torch.tensor([[1.0, 0.0]], device=device)\n else:\n task_info = torch.tensor([[0.0, 1.0]], device=device)\n\n data_points = np.array(gen_data(task), dtype=np.float32)\n train_x = torch.tensor(data_points, device=device)\n # target = train_x.clone()\n\n generated_weights = metanet(task_info)\n for name, param in model.named_parameters():\n print(generated_weights[name][0])\n param.data.copy_(generated_weights[name][0])\n\n training_steps = 100\n batch_size = 64\n pbar = tqdm.tqdm(range(training_steps))\n\n for i in pbar:\n x1 = train_x[torch.randint(train_x.size(0), (batch_size,))]\n x0 = torch.randn_like(x1)\n target = x1 - x0\n t = torch.rand(x1.size(0))\n xt = (1 - t[:, None]) * x0 + t[:, None] * x1\n pred = model(xt, t) # also add t here\n loss = ((target - pred)**2).mean()\n loss.backward()\n optim.step()\n optim.zero_grad()\n pbar.set_postfix(loss=loss.item())\n```\n\n`backbone.py`:\n\n```python\nimport torch \nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\n\nclass Block(nn.Module):\n def __init__(self, channels=512):\n super().__init__()\n self.ff = nn.Linear(channels, channels)\n self.act = nn.ReLU()\n\n def forward(self, x):\n return self.act(self.ff(x))\n \nclass Backbone(nn.Module):\n def __init__(self, channels_data=2, layers=5, channels=512, \n channels_t=512):\n super().__init__()\n self.channels_t = channels_t\n self.in_projection = nn.Linear(channels_data, channels)\n self.t_projection = nn.Linear(channels_t, channels)\n self.blocks = nn.Sequential(*[\n Block(channels) for _ in range(layers)\n ])\n self.out_projection = nn.Linear(channels, channels_data)\n\n def gen_t_embedding(self, t, max_positions=10000):\n t = t * max_positions\n half_dim = self.channels_t // 2\n emb = math.log(max_positions) / (half_dim - 1)\n emb = torch.arange(half_dim, device=t.device).float().mul(-emb).exp()\n emb = t[:, None] * emb[None, :]\n emb = torch.cat([emb.sin(), emb.cos()], dim=1)\n if self.channels_t % 2 == 1:\n emb = F.pad(emb, (0, 1), mode='constant')\n return emb\n \n def forward(self, x, t):\n x = self.in_projection(x)\n t = self.gen_t_embedding(t)\n t = self.t_projection(t)\n x = x + t\n x = self.blocks(x)\n x = self.out_projection(x)\n return x\n \n```\n\n`metanet.py`:\n\n```python\nimport torch \nimport torch.nn as nn\nimport torch.nn.functional as F\nimport math\nfrom model.backbone import Backbone\n\nclass ResidualBlock(nn.Module):\n \"\"\"\n A simple residual block that adds the input to the output.\n \"\"\"\n def __init__(self, input_dim):\n super().__init__()\n self.fc = nn.Linear(input_dim, input_dim)\n self.act = nn.ReLU()\n\n def forward(self, x):\n return x + self.act(self.fc(x))\n\nclass MetaNet(nn.Module):\n \"\"\"\n Meta network for generating target weights for the Backbone network,\n given the input task info, which is a one-hot vector.\n \"\"\"\n def __init__(self, backbone: nn.Module, task_info_dim=2, hidden_dim=128):\n \"\"\"\n Args:\n backbone: An instance of Backbone whose weights will be generated.\n task_info_dim: Dimensionality of the one-hot task info vector.\n hidden_dim: Dimensionality of the hidden layer in the meta-network.\n \"\"\"\n super().__init__()\n self.backbone = backbone\n total_params = sum(p.numel() for p in backbone.parameters())\n self.residual = ResidualBlock(task_info_dim)\n self.meta_fc1 = nn.Linear(task_info_dim, hidden_dim)\n self.meta_act = nn.ReLU()\n self.meta_fc2 = nn.Linear(hidden_dim, total_params)\n\n def forward(self, task_info):\n \"\"\"\n Args:\n task_info: A tensor of shape (batch_size, task_info_dim)\n representing one-hot encoded task information.\n Returns:\n A dictionary mapping each parameter name (as in backbone.named_parameters())\n to a tensor of generated weights with shape (batch_size, *parameter.shape).\n \"\"\"\n # Generate a flattened vector of all weights\n x = self.residual(task_info)\n x = self.meta_act(x)\n x = self.meta_fc1(x)\n x = self.meta_act(x)\n x = self.meta_fc2(x) # shape: (batch_size, total_params)\n\n generated_params = {}\n start = 0\n # Split and reshape the flattened vector to match each Backbone parameter.\n for name, param in self.backbone.named_parameters():\n num_params = param.numel()\n # Slice out the piece for this parameter.\n param_vector = x[:, start:start+num_params]\n start += num_params\n # Reshape so that each task in the batch gets a parameter tensor\n generated_params[name] = param_vector.view(-1, *param.shape)\n return generated_params\n```","reference_answer":"`.data` can stop autograd from tracking the computation, so don't write into `param.data`. To run the backbone with the generated weights and keep the graph intact, use `torch.func.functional_call`:\n\n```python\ngen_weights = {name: w[0] for name, w in generated_weights.items()}\npred = functional_call(backbone, gen_weights, (x, t))\n```","needs_clarification":false,"thread_id":217388,"url":"https://discuss.pytorch.org/t/how-to-preserve-computational-graph-while-initializing-a-network-with-weights/217388","created_at":"2025-03-03T16:08:29.829000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["Charley_Xiao","KFrank"],"answered_by_ptrblck":false} {"question":"Model output drastically different after upgrade\n\nWe are trying to upgrade our target system from Ubuntu 18.04 to Ubuntu 24.04. In this process, torch, torchvision, and torchaudio versions are upgraded, among other packages. \n\nWe are seeing mostly similar model output. But every once in a while, the label and confidences completely change. I'm not looking for a solution, but rather a place to start debugging. Is it possible that the change in torch.save/load methods could cause this? This was my first thought. And is my first path to debugging.\n\nAre there other things that could contribute to such large changes in model outputs? \nThank you for your time.","reference_answer":"I found that torchaudio.load() is returning different data on the same mp3 file. I'm going to cross post in the torchaudio section.\n\nEdit: Found the issue. For future reference: https://discuss.pytorch.org/t/loading-mp3-file-using-torchload/133545?u=gnodab","needs_clarification":false,"thread_id":217399,"url":"https://discuss.pytorch.org/t/model-output-drastically-different-after-upgrade/217399","created_at":"2025-03-03T22:03:00.527000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["gnodab"],"answered_by_ptrblck":false} {"question":"Finetuning of MaskRCNN generates no predictions (no boxes, no masks)\n\nI am finetuning a MaskRCNN (using the torchvision implementation, the one at https://pytorch.org/vision/main/models/mask_rcnn.html) to perform instance segmentation of wires (powerline wires for example). However, after training, even though training loss goes down and validation loss also goes down, when evaluating I discover my model is not predicting any masks, independently of the image.\n\nEvaluation code looks something like this (and the print statements at the bottom always print 0.0, and when inspecting the raw model output it really does not contain any predicted boxes/masks)\n\n```\ndef eval(\n val_dataset,\n model,\n device: str = \"cuda\" if torch.cuda.is_available() else \"cpu\",\n batch_size: int = 8,\n) -> float:\n val_dl = DataLoader(\n val_dataset,\n batch_size=batch_size,\n shuffle=False,\n collate_fn=coco_collate_fn,\n num_workers=4,\n )\n boxes_per_img = 0.0\n masks_per_img = 0.0\n NUM_IMGS = len(val_dataset)\n with torch.no_grad():\n model.eval()\n for i, (imgs, targets) in enumerate(tqdm(val_dl, total=len(val_dl), position=1)):\n imgs, targets = map_to_device(imgs, targets, device) # move to gpu\n preds = model(imgs, targets)\n boxes_per_img += sum(len(p[\"boxes\"]) for p in preds) / NUM_IMGS\n masks_per_img += sum(len(p[\"masks\"]) for p in preds) / NUM_IMGS\n model.train()\n print(f\"(Validation) Boxes per image: {boxes_per_img}\")\n print(f\"(Validation) Masks per image: {masks_per_img}\")\n```\n\nDoes anyone know why this could happen? I would expect segmentation/detection errors but not zero predictions. I thought it could be class imbalance (wires are thin objects, but there is at least one in every image) and changed some model parameters to oversample positive regions, but it did not change the result.\n\n```\n # Load a pre-trained model\n model = torchvision.models.detection.maskrcnn_resnet50_fpn_v2(\n weights=torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights.COCO_V1,\n weights_backbone=torchvision.models.ResNet50_Weights.IMAGENET1K_V2,\n )\n in_features = model.roi_heads.box_predictor.cls_score.in_features\n model.roi_heads.box_predictor = torchvision.models.detection.faster_rcnn.FastRCNNPredictor(in_features, 1) # only one class: wire\n # Increase the positive sample fraction to oversample wires\n model.roi_heads.box_sampler_batch_size_per_image = 768 # Default is 512\n model.roi_heads.box_positive_fraction = 0.8 # Default is 0.25\n```","reference_answer":"I found the problem.\n\nI did not see the description of the `num_classes` parameter of the `torchvision.models.detection.mask_rcnn.MaskRCNN` class, and thought that it should be the number of classes excluding background. However the description says the following:\n\n```\n num_classes (int): number of output classes of the model (including the background).\n If box_predictor is specified, num_classes should be None.\n```\n\nSo I needed to use `num_classes=2` instead of 1 in my code (I guess using 1 resulted in only background, no predictions). Using `num_classes=1` lead to multiple issues (for example, the `fastrcnn_loss` returning both box classification and box regression loss equal to 0.0, the first due to the use of the cross_entropy function and the second because of the line `sampled_pos_inds_subset = torch.where(labels > 0)[0]` that samples only from non-zero classes).\n\nI also changed the numeric id of my labels in my dataset of wires from 0 to 1, though I am not sure if it made any difference.\n\nNow it seems to be converging more normally, and generating many bounding boxes on evaluation.","needs_clarification":false,"thread_id":217412,"url":"https://discuss.pytorch.org/t/finetuning-of-maskrcnn-generates-no-predictions-no-boxes-no-masks/217412","created_at":"2025-03-04T01:50:09.476000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["Igor_Borja"],"answered_by_ptrblck":false} {"question":"Change tensor values by index lower than some value\n\nHi all, \n\nI'm new and have a simple problem I cannot solve. I have a (2,n) tensor of logits and I would like to do a topk selection. I've been reading [this link](https://www.packtpub.com/en-us/learning/how-to-tutorials/exploring-token-generation-strategies?srsltid=AfmBOoo_z6FRUAwDJnZ2MbChTXW7SN67Ua3OtLYGyM6RUJb8BayQNFUq) to implement what I want. The code works when the logits are a 1d but not when they're (2,n).\nI can't figure out how to modify the code accordingly. \n\nThere is a very similar post on this forum using the cumsum but is not what I want. My minimal code is:\n\n```\nlogits = torch.tensor([[ 0.0333, 0.5174, 0.4797],[-0.0644, -0.5815, -0.7552]])\nprint(logits)\ntopk_values, topk_indices = torch.topk(logits, 2)\nlast = topk_values[:,-1].unsqueeze(dim=-1)\nprint(last)\nprint(topk_indices)\nlogits[logits < topk_values[-1]] = float('-inf')\n```\nbut I'm getting the following error: \n\n```\nRuntimeError: The size of tensor a (3) must match the size of tensor b (2) at non-singleton dimension 1\n```\n\nCould you please help me to understand what's going on and how to solve it?\n\nThank you!","reference_answer":"The shapes don't broadcast. `logits` has trailing size 3, but the threshold has trailing size 2. Add a trailing singleton dimension to the threshold so it broadcasts across each row:\n\n`last = topk_values[:,-1].unsqueeze(dim=-1)`\n\nThen mask the values below it:\n\n```python\nlogits[logits < last] = float('-inf')\n```","needs_clarification":false,"thread_id":217421,"url":"https://discuss.pytorch.org/t/change-tensor-values-by-index-lower-than-some-value/217421","created_at":"2025-03-04T07:58:39.301000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[1,2],"answer_authors":["KFrank","isg"],"answered_by_ptrblck":false} {"question":"Question on quantize_per_channel and dequantize\n\nI'd like to use low-level quantization of a tensor `x` of shape `(num_channels, blocksize)`. I know how to use `MovingAveragePerChannelMinMaxObserver` to obtain the quantisation params.\n\nI also understand how to use `torch.quantize_per_channel` then, to get `q_x`. From the docs, the quant params see to somehow be attached to `q_x`.\n\nBut I'd now (for other reasons) like to store quantisation params separately from `q_x.int_repr()`.\n\nEven though this is not documented anywhere, I suspect that `torch.dequantize` would do the right thing when applied to `q_x`. But in my case, I store `q_x.int_repr()` plus the quantisation params separately. What is a good way to dequantize then, given I have the internal representation and the parameters? How can I safely get a \"quantized tensor\" (i.e., like output of `quantize_per_channel`) from its parts?","reference_answer":"Use the internal function `torch._make_per_channel_quantized_tensor`. It works, but it is undocumented. For background on quantized tensors, see https://github.com/pytorch/pytorch/wiki/Introducing-Quantized-Tensor.","needs_clarification":false,"thread_id":217527,"url":"https://discuss.pytorch.org/t/question-on-quantize-per-channel-and-dequantize/217527","created_at":"2025-03-06T17:00:16.030000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["mseeger"],"answered_by_ptrblck":false} {"question":"CPU and GPU inference differences\n\nI'm running the following script that creates a pytorch model, runs inference on CPU and GPU. I get differences as high as 2e-4. Is this expected with float32?\n\n```\nimport torch\nfrom monai.networks.nets import VarAutoEncoder\n\nmodel.eval()\ninput = torch.ones((1,6,64,64))\nrecon, mu, logvar, _ = model(input)\n\ndevice = torch.device('cuda:0')\nmodel = model.to(device)\ninput = input.to(device)\nrecon_gpu, mu_gpu, logvar_gpu, _ = model(input)\n\ndiff = mu_gpu.detach().cpu().numpy() - mu.detach().numpy()\nprint(f'diff: {diff}')\n```\n\n```\ndiff: [[-7.45356083e-05 -3.43009830e-04 1.75867230e-04 -1.16109848e-04\n -4.17232513e-05 2.66432762e-05 -1.32430345e-04 -1.16214156e-04\n -5.60581684e-05 2.44081020e-04 -9.73343849e-05 2.08556652e-04\n 1.40473247e-04 -1.85698271e-04 -2.05576420e-04 4.55528498e-05\n 1.46627426e-04 2.26497650e-06 -1.25408173e-04 -1.09910965e-04]]\n```","reference_answer":"Hi Chait!\n\nDifferences at this level don't surprise me. (As an aside, without knowing the typical\nscale of `mu`, we don't actually know how large `diff` is *relative* to the size of `mu`, so\nI am assuming that `mu` is roughly of order one.)\n\nYour cpu and gpu computations could easily be performing various arithmetic operations\nin mathematically equivalent, but numerically different orders, thereby leading to differing\nround-off error. A single float32 operation would typically have a round-off error on the\norder of 1e-7. But such round-off errors accumulate with further computation. It wouldn't\nsurprise me for the output of a reasonably deep model (lots of layers) to end up with cpu\nand gpu accumulated round-off errors that differ on the order of 1e-4.\n\nYou might try converting your model to `double()` (`torch.float64`) and see if `diff`\nshrinks by several (about nine) orders of magnitude.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":217633,"url":"https://discuss.pytorch.org/t/cpu-and-gpu-inference-differences/217633","created_at":"2025-03-09T19:54:53.685000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Get different results after JIT compilation optimization\n\nI have a simple model file as follows:\n```python\nimport torch\nimport torch.nn as nn\nimport torch.fx as fx\n\nclass CustomTracer(fx.Tracer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def is_leaf_module(self, module, name):\n return isinstance(module, CustomModule)\n\nclass CustomModule(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, x):\n conv = nn.Conv2d(3, 64, 3, padding=1)\n return conv(x)\n\ndef utility_function(x):\n return torch.relu(x)\n\nclass UtilityClass:\n def __init__(self):\n pass\n\n def method(self, x):\n bn = nn.BatchNorm2d(x.size(1))\n return bn(x)\n\nclass MyModel(nn.Module):\n def __init__(self):\n super().__init__()\n self.custom_module = CustomModule()\n self.utility_class = UtilityClass()\n\n def forward(self, x):\n x = self.custom_module(x)\n x = utility_function(x)\n x = self.utility_class.method(x)\n return x\n\ndef my_model_function():\n return MyModel()\n```\nI get my model like this:`model_function = getattr(model_module, \"my_model_function\")`.\n\nI use two methods to derive the results of the model:\n+ `output_original = model(input)`\n+ ```python jit_model = torch.jit.trace(model, input) output_jit = jit_model(input)```\n\nand get this output:\n```\nMismatched elements: 3211246 / 3211264 (100.0%)\nGreatest absolute difference: 60.796468168497086 at index (0, 22, 5, 223) (up to 1e-05 allowed)\nGreatest relative difference: 19350106.104020353 at index (0, 16, 223, 168) (up to 1e-05 allowed)\n```\nWhy this happened?","reference_answer":"Your model does not even produce the same outputs in Eager mode:\n```python\nmodel = my_model_function()\nx = torch.randn(1, 3, 24, 24)\nout1 = model(x)\nout2 = model(x)\n\ntorch.testing.assert_allclose(out1, out2)\n# Mismatched elements: 36863 / 36864 (100.0%)\n# Greatest absolute difference: 7.237934112548828 at index (0, 11, 11, 19) (up to 1e-05 allowed)\n# Greatest relative difference: 49341.4609375 at index (0, 50, 23, 10) (up to 0.0001 allowed)\n```\nso I would probably focus on this first before digging into the deprecated `jit.trace` util.\n\nThe differences are most likely caused by the module creation in the `forward` pass, so move them into the `__init__` of the parent class.","needs_clarification":false,"thread_id":217663,"url":"https://discuss.pytorch.org/t/get-different-results-after-jit-compilation-optimization/217663","created_at":"2025-03-10T13:31:09.616000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"In-API way of catching `torch._C._LinAlgError`\n\nHello,\n\nIs there an in-API way of catching `torch._C._LinAlgError` -- risen upon [`torch.linalg.inv_ex`](https://pytorch.org/docs/stable/generated/torch.linalg.inv_ex.html) failure on singular matrices when `check_errors=True`?\n\nThanks!\n\nEdit: I should precise that I also get a `mypy` error when trying to use it as is.\n```\nerror: Module has no attribute \"_LinAlgError\" [attr-defined]\n```","reference_answer":"I found `torch.linalg.LinAlgError`!\n```pycon\n>>> torch.linalg.LinAlgError is torch._C._LinAlgError\nTrue\n```","needs_clarification":false,"thread_id":217672,"url":"https://discuss.pytorch.org/t/in-api-way-of-catching-torch-c-linalgerror/217672","created_at":"2025-03-10T14:56:03.878000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ego-thales"],"answered_by_ptrblck":false} {"question":"How to request sufficient memory in advance\n\nI 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 torch program can manually pre-allocate a sufficient block of memory for use.","reference_answer":"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\")`.\nA better approach might be to limit the available memory per process via [`torch.cuda.set_per_process_memory_fraction`](https://pytorch.org/docs/stable/generated/torch.cuda.set_per_process_memory_fraction.html).","needs_clarification":false,"thread_id":217738,"url":"https://discuss.pytorch.org/t/how-to-request-sufficient-memory-in-advance/217738","created_at":"2025-03-12T10:59:10.496000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"How to calculate Jacobians for a batch\n\nHello, I want to calculate Jacobian matrices for a batch of data.\n\nI have `x` (batch_size, 3) and calculated `y` (batch_size, 3). I need a Jacobian matrix of shape (batch_size, 3, 3)\n\nI tried the following code:\n\n```\nimport torch\n\nx = torch.randn(1024, 3, requires_grad=True) # a batch of coordinates\ny = torch.sin(x) # calculated y in forward pass\n\ngrads = []\nfor i_dim in range(y.shape[1]):\n y_i = y[:, i_dim]\n ones = torch.ones_like(y_i)\n # `torch.autograd.grad` seems to implicitly add dimensions up.\n # So I separately calculate grad for every dim of `y`\n # But this still fails.\n grad = torch.autograd.grad(y_i, x, grad_outputs=ones, create_graph=True, retain_graph=True, is_grads_batched=True)[0]\n grads.append(grad)\n\ngrad = torch.cat(grad, dim=1)\n\nprint(grad.shape)\n```\n```\nRuntimeError: If `is_grads_batched=True`, \nwe interpret the first dimension of each grad_output as the batch dimension. \nThe sizes of the remaining dimensions are expected to match the shape of corresponding output, \nbut a mismatch was detected: grad_output[0] has a shape of torch.Size([]) and output[0] has a shape of torch.Size([1024]). \nIf you only want some tensors in `grad_output` to be considered batched, consider using vmap.\n```\n\nI think `outputs` and `grad_output` have already the same shape. Why is this error raised?\n\nBTW, I tried `torch.func.jacrev()`, but I need to calculate `y` beforehand, not in the closure of `jacrev()`. My code has been written this way.","reference_answer":"Hi Windows!\n\nYes, but because the \"samples aren't independent,\" you can't sum over the batch\ndimension of your output `y`. You will have to have `autograd.grad()` perform 3072\nbackward passes using `is_grads_batched = True`. Also, technically speaking, you\nwill not be keeping full jacobian matrices, but rather selecting out just the desired\nsubmatrices of the jacobian matrices (which will be computed in full).\n\nHere is an example:\n\n```python\nimport torch\nprint (torch.__version__)\n\n_ = torch.manual_seed (2025)\n\nfc = torch.nn.Linear (1024 * 3, 1024 * 3) # connect all inputs to all outputs\n\nx = torch.randn (1024, 3, requires_grad = True) # a batch of coordinates\n\ny = fc (x.flatten()).sigmoid().reshape (1024, 3) # all elements depend on all elements\n\ngrad_outputs = torch.eye (1024 * 3).reshape (1024 * 3, 1024, 3)\nbatch_grad = torch.autograd.grad (y, x, grad_outputs = grad_outputs, is_grads_batched = True)[0]\nprint ('batch_grad.shape =', batch_grad.shape)\n\n# select out the 3x3 \"jacobian\" matrices I think you want\nbatch_grad = batch_grad.reshape (1024, 3, 1024, 3).diagonal (dim1 = 0, dim2 = 2).permute (2, 0, 1)\nprint ('batch_grad.shape =', batch_grad.shape)\n```\n\nAnd here is its output:\n\n```text\n2.6.0+cu126\nbatch_grad.shape = torch.Size([3072, 1024, 3])\nbatch_grad.shape = torch.Size([1024, 3, 3])\n```\n\nYou can package your call to model as a function (that refers to some \"global\" variables)\nand pass it to `jacrev()`:\n\n```python\n# x1 = whatever ...\n# x2 = whatever ...\n# mask1 = whatever ...\n# mask2 = whatever ...\n\ndef applyModelToX1 (x_one):\n out1, _ = model (x_one, x2, mask1, mask2)\n return out1\n\nfullJacobian = torch.func.javrev (applyModelToX1) (x1)\n\n# snip out submatrices of fullJacobian, as desired\n```\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":217805,"url":"https://discuss.pytorch.org/t/how-to-calculate-jacobians-for-a-batch/217805","created_at":"2025-03-13T13:07:58.421000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Torch::full two overloads\n\nHello all,\n\nin datasets.cpp in pytorch_cpp-master/utils is the line (473)\n```\ntorch::Tensor class_id = torch::full({}, (long int)this->class_ids.at(idx), torch::TensorOptions().dtype(torch::kLong));\n```\nI am not able to compile this with VS2019.\n\nNeither\n```\nat::Tensor torch::full(at::IntArrayRef,const c10::Scalar &,c10::TensorOptions)\n```\nnor\n```\nat::Tensor torch::full(at::IntArrayRef,const c10::Scalar &,c10::optional,c10::TensorOptions)\n```\nis hit. What is the correct cast at which argument?\n\nMany thanks for your help.","reference_answer":"```\nauto options = torch::TensorOptions().dtype(torch::kLong);\nint val = (long int)this->class_ids.at(idx);\n\ntorch::Tensor class_id = torch::full({}, val, options);\n```\nDoes the job.","needs_clarification":false,"thread_id":217809,"url":"https://discuss.pytorch.org/t/torch-full-two-overloads/217809","created_at":"2025-03-13T14:03:27.296000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Dirk10001"],"answered_by_ptrblck":false} {"question":"What is the interplay between the \"nvidia driver\" and \"cuda\"?\n\nHello All!\n\nI am under the impression that the \"nvidia driver\" and \"cuda\" are two separate things.\nHow do the two work together?\n\nWould there be a use case where somebody uses the \"nvidia driver\" but not \"cuda\"?\n\nI ask because after upgrading a laptop to ubuntu 24.04 (and reinstalling pytorch),\npytorch no longer had cuda support (and nvidia-smi was no longer available).\n\n(For context, I install and run pytorch in a conda environment. nvidia-smi runs both\noutside and inside the conda environment.)\n\nI had to first install the nvidia driver (sudo ubuntu-drivers install nvidia:550, outside\nof conda) and then install pytorch (with cuda, inside of conda).\n\nnvidia-smi reports (outside and inside of conda):\n\n> NVIDIA-SMI 550.120 Driver Version: 550.120 CUDA Version: 12.4\n\nRunning pytorch (inside of conda) I get:\n\n```text\n>>> import torch\n>>> torch.__version__\n'2.6.0+cu126'\n>>> torch.version.cuda\n'12.6'\n```\n\nDoes the \"nvidia driver\" automatically come bundled with some version of \"cuda\"?\nWhen, if ever, does the \"CUDA Version: 12.4\" get used? (I assume that when I run\npytorch I am using cuda 12.6.)\n\nMore context: I am only (knowingly) using cuda when I run pytorch.\n\nThanks for any information about how these two pieces of the system work together.\n\nK. Frank","reference_answer":"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. \nWhile the NVIDIA Driver is making sure your system can properly communicate with and use your GPU, the CUDA Toolkit ships with math libraries (cuBLAS, cuSOLVER, cuRAND, etc.) as well as the CUDA compiler toolchain (`nvcc`, `ptxas`, etc.). Installing a CUDA Toolkit locally allows you to build CUDA applications, such as PyTorch. You have certainly seen my comment on a few questions explaining that PyTorch binaries ship with their own CUDA runtime dependencies (i.e. the CUDA runtime, CUDA Math libs, etc.) and users only need to properly install an NVIDIA driver.\nNow, if you download a CUDA Toolkit from e.g. [here](https://developer.nvidia.com/cuda-downloads) it will ship with the NVIDIA driver as well. During the installation you will have an option to install the Toolkit alone or the Driver as well. You can also download the NVIDIA driver separately, which will be of course a smaller package. \n\nYes, if you mean the CUDA Toolkit by \"cuda\". I.e. if you want to mainly run PyTorch applications and don't plan to ever source build any CUDA application or a PyTorch 3rd party library etc., you won't need to install a CUDA toolkit and can depend on the CUDA runtime dependencies which will be installed during the PyTorch binary installation. While running `pip install torch` you will see that `nvidia-*` wheels are pulled into your environment allowing PyTorch to use these.\n\nThis is expected as an OS update would most likely need a driver re-installation as well.\n\nThis is the right approach. You can install the NVIDIA drivers from `apt` or you could also use standalone installers from [here](https://www.nvidia.com/en-us/drivers/). I would strongly advise not to mix these approaches. If you installed the drivers from `apt`, stick to it for driver updates etc.\n\nGreat! As a quick smoke test, you could create a tensor on the GPU making sure PyTorch can also communicate with the device.\n\nYes, as mentioned before the CUDA Toolkit download ships with the NVIDIA driver as well and you have the option to select the installation of it. However, based on your description you have installed the NVIDIA Driver beforehand and the PyTorch binaries afterwards, which is fine and correct. Note that that PyTorch binaries do *not* ship with an NVIDIA Driver so you have to install it beforehand.\n\nI assume you are referring to the \"Driver Version: 550.120 CUDA Version: 12.4\" output of `nvidia-smi`. If so, then note that `nvidia-smi` reports the driver version and the corresponding CUDA toolkit this driver ships with. It does not tell you that a full CUDA toolkit was properly installed (and you can have multiple CUDA Toolkits installed on your system). To check for a locally installed CUDA Toolkit run `nvcc --version` or try to build any CUDA sample from source.\nYou are thus right in assuming PyTorch will use its own CUDA 12.6.3 runtime dependencies during the execution. \n\nAlso, you haven't asked it but just to explain the compatibility a bit more: the NVIDIA Driver is compatible for all minor CUDA updates. I.e. to run any PyTorch binary with CUDA 12.x you need to install any NVIDIA Driver >= 525.60.13 as described in the [Minor Version Compatibility Docs](https://docs.nvidia.com/deploy/cuda-compatibility/#minor-version-compatibility). Once the driver is installed you can simply `pip install` any PyTorch binary (stable, nightly, etc.) you want. \nNVIDIA Drivers are *not* compatible between CUDA major updates. I.e. if you are using a CUDA 11.x driver, you won't be able to run applications compiled and linked against CUDA 12.x dependencies. \n\nLet me know if you have any more questions!","needs_clarification":false,"thread_id":217811,"url":"https://discuss.pytorch.org/t/what-is-the-interplay-between-the-nvidia-driver-and-cuda/217811","created_at":"2025-03-13T14:37:13.997000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Simple CNN model takes too much memory when forward() is called\n\nHello, \nIn the following code, I define a simple CNN model composed of: \nCNN(256 out-channels, 5x5 kernel) -> ReLU -> Flatten()\n\nwhen 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?\n\nthe code:\n(PS cfg is a config file) \n```\nimport cfg\nimport torch\nfrom torch import nn\nimport gc\n\nclass Model(nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.layer1 = nn.LazyConv2d(out_channels=256, kernel_size=5)\n self.layer2 = nn.Flatten()\n self.model = nn.Sequential(self.layer1, nn.ReLU() ,self.layer2)\n\n def forward(self, X):\n\n print(\"Before model call\")\n print(\"torch.cuda.memory_allocated: %fGB\"%(torch.cuda.memory_allocated(0)/1024/1024/1024))\n\n out = self.model(X)\n\n print(\"\\n\\nAfter model call\")\n print(\"torch.cuda.memory_allocated: %fGB\"%(torch.cuda.memory_allocated(0)/1024/1024/1024))\n \n\n return out\n\nmodel = Model()\n\nmodel.to(cfg.DEVICE)\n\ngc.collect()\ntorch.cuda.empty_cache()\n\nX = torch.randn(size=(8, 1, 500, 500)).to(cfg.DEVICE)\n\noutput = model(X)\n```\n\nthe output:\n\n```\nBefore model call\ntorch.cuda.memory_allocated: 0.007451GB\n\nAfter model call\ntorch.cuda.memory_allocated: 1.884429GB\n```","reference_answer":"The memory usage is expected as already the output tensor consumes almost all of the used memory:\n```python\nprint(output.nelement() * output.element_size() / 1024**3)\n# 1.876953125\n```","needs_clarification":false,"thread_id":217883,"url":"https://discuss.pytorch.org/t/simple-cnn-model-takes-too-much-memory-when-forward-is-called/217883","created_at":"2025-03-15T15:07:13.694000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Autograd with mutable custom operator\n\nThe [Custom C++ and CUDA Operators tutorial](https://pytorch.org/tutorials/advanced/cpp_custom_ops.html) says \"Do not return any mutated Tensors as outputs of the operator\". How can I add autograd/backward support for the operator when the outputs are not returned (and so I do not think there will be a corresponding `grad` input to the backward function)?","reference_answer":"It seems that you need to call the `.clone()` method of the mutated inputs and return those. This allows you to return them (and so have corresponding `grad` inputs to the backward function) while also not violating the rule of not returning mutated Tensors (as you are returning clones rather than the actual mutated Tensors).","needs_clarification":false,"thread_id":217953,"url":"https://discuss.pytorch.org/t/autograd-with-mutable-custom-operator/217953","created_at":"2025-03-17T14:11:56.278000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["BeachHut"],"answered_by_ptrblck":false} {"question":"Why doesn't the instrumented execution time match the time captured by nsys?\n\nForgive me for asking what may seem like a silly question.\n\nWhen I measure time using instrumentation, I only get a few milliseconds. Here’s my measurement method:\n```\nstart_event = torch.cuda.Event(enable_timing=True)\nend_event = torch.cuda.Event(enable_timing=True)\n\nstart_event.record()\n// module\nend_event.record()\n\ntorch.cuda.synchronize()\n\nelapsed_time = start_event.elapsed_time(end_event)\nprint(f\"total time: {elapsed_time} ms\")\n```\nHowever, when I look at the timeline captured by nsys, I can see that there’s a 1-second gap just between two batch norm kernel calls.\n[image]\nSince there's a 1-second gap even between two batch norm kernels, the total execution time certainly shouldn't be just a few milliseconds. Why is this happening? Am I misunderstanding the data captured by nsys? Or is there an issue with my measurement method? Or does this measurement method only count the sum of kernel execution times without including idle periods?\n\nAdditionally, could I use the time elapsed between `CUDA profiling initialization` and `CUDA profiling data flush` as my total time (including time for H to D or D to H data transfers)?","reference_answer":"CUDA events only measure the kernel execution time on the GPU. They don't include host overhead, idle time or CPU bottlenecks, so the gaps in your timeline are not counted. To see the full timeline, use a visual profiler such as Nsight Systems or the native PyTorch profiler. You can add NVTX markers to your code to mark regions, and they will show up in nsys.","needs_clarification":false,"thread_id":218025,"url":"https://discuss.pytorch.org/t/why-doesnt-the-instrumented-execution-time-match-the-time-captured-by-nsys/218025","created_at":"2025-03-19T13:41:48.926000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,4],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"How does PyTorch's cross-entropy loss transform logits with a soft probability target vector?\n\nIf I understand correctly, PyTorch's `nn.CrossEntropyLoss()` accepts soft probability target vectors. So, for example, y (the target vector) could be [0.8, 0.2, 0.8]^T, representing an equal (0.8) probability for classes 1 and 3, and a probability of 0.2 for the second class. Obviously, this is not a normalized probability distribution, as it sums to 1.2. Now, x are the raw logits produced by the model; does `nn.CrossEntropyLoss()` still apply a regular (log)softmax to the logits? If so, as I understand it, the logits are transformed to a normalized probability distribution, and will never match the un-normalized soft probability target. If the (log)softmax is not applied, how does the loss function act on the raw logits instead (if at all)? Thank you in advance!","reference_answer":"Hi Nassim!\n\nYes, the `input` consists of unnormalized log-probabilities (contrary to the documentation,\nthey're not really logits) and are treated the same whether or not the \"probabilities\" that\nmake up the soft `target` form a properly-normalized probability distribution. (The values\nin `target` don't even have to be individually proper probabilities between zero and one.\nThey just get plugged into the cross-entropy formula without being checked or normalized.)\n\nThe documentation is silent (as far as I can tell) on this issue, but a quick test shows it to\nbe the case:\n\n```text\n>>> import torch\n>>> torch.__version__\n'2.6.0+cu126'\n>>> _ = torch.manual_seed (2025)\n>>> l = torch.randn (10)\n>>> t = torch.rand (10)\n>>> torch.nn.CrossEntropyLoss() (l, t)\ntensor(15.4764)\n>>> torch.nn.CrossEntropyLoss() (l, 10 * t)\ntensor(154.7643)\n>>> torch.nn.CrossEntropyLoss() (l, 0.1 * t)\ntensor(1.5476)\n>>> torch.nn.CrossEntropyLoss() (l, -t)\ntensor(-15.4764)\n```\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":218037,"url":"https://discuss.pytorch.org/t/how-does-pytorchs-cross-entropy-loss-transform-logits-with-a-soft-probability-target-vector/218037","created_at":"2025-03-19T20:18:01.440000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"PyTorch compatible GPU rental?\n\nWhat are some cloud-based, GPU rental services that support PyTorch?","reference_answer":"https://pytorch.org/get-started/cloud-partners/\nLightning.ai gives \"35 free GPU hours\".","needs_clarification":false,"thread_id":218132,"url":"https://discuss.pytorch.org/t/pytorch-compatible-gpu-rental/218132","created_at":"2025-03-22T04:07:53.404000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["Geremia"],"answered_by_ptrblck":false} {"question":"[pt2e][quant] Quantization of operators with multiple outputs (RNN, LSTM)\n\n**Environment:**\ntorch==2.6.0\nexecutorch==0.5.0\n\n**Description:**\nI'm working on quantization of LSTM module in ExecuTorch using PyTorch 2 Export Quantization mode. I perform Post Training Quantization. The `nn.LSTM` is exported to `lstm.input` Aten operation, for which I have a quantizer. In `torch/ao/quantization/quantize_pt2e.py` in `prepare_pt2e()` model is annotated. The problem is encountered in [torch/ao/quantization/prepare.py#L501-L503](https://github.com/pytorch/pytorch/blob/1eba9b3aa3c43f86f4a2c807ac8e12c4a7767340/torch/ao/quantization/pt2e/prepare.py#L501-L503) in function `_maybe_insert_input_and_output_observers_for_node()`. This code is working only with operation node with 1 output. LSTM has 3 outputs. The `node.meta[\"val\"]` value is a list of FakeTensor here. To quantize recurrent layers, support for multiple outputs is needed.\n\nI've read Quantization docs and noticed support for *Eager Mode Quantization* and *FX Graph Mode Quantization* and even [links to examples](https://pytorch.org/docs/stable/quantization.html#frequently-asked-questions). The issue here is to add observers for multiple outputs.\n\nIs quantization of operation nodes with multiple outputs possible in current PT2E workflow? Are there any further problems or is the limitation of 1 output only because of the progress simply hasn't reached there yet?\n\nPlease @jerryzh168 could you look at this?\n\n**Code to reproduce:**\n(runnable from executorch repo)\n```\nimport torch\n\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Type\n\nfrom torch import fx\nfrom torch import nn\nfrom torch._ops import OpOverload\nfrom torch.ao.quantization.observer import HistogramObserver, MinMaxObserver\nfrom torch.ao.quantization.quantize_pt2e import prepare_pt2e, convert_pt2e\nfrom torch.ao.quantization.quantizer import DerivedQuantizationSpec, Quantizer, SharedQuantizationSpec\nfrom torch.ao.quantization.quantizer.composable_quantizer import ComposableQuantizer\nfrom torch.ao.quantization.quantizer.xnnpack_quantizer_utils import (\n QuantizationAnnotation,\n QuantizationConfig,\n QuantizationSpec,\n)\n\nfrom executorch.backends.cadence.aot.quantizer.utils import (\n find_sequential_partitions_aten,\n is_annotated,\n no_outside_users,\n)\nfrom executorch.backends.cadence.aot.quantizer.utils import get_bias_qparams\n\n@dataclass\nclass PartitionAnchors:\n \"\"\"\n All fields are lists of (node, input_node), where node is from\n the given partition and input_node is an input to the partition.\n\n Quantizer uses inputs, weights and biases for quantization annotation. The others\n field contains tensor inputs that aren't quantized, and the literals fields contains\n is used for other types of input values as well as handling default parameters.\n \"\"\"\n\n inputs: list[tuple[fx.Node, fx.Node]] = field(default_factory=list)\n weights: list[tuple[fx.Node, fx.Node]] = field(default_factory=list)\n biases: list[tuple[fx.Node, fx.Node] | tuple[fx.Node, fx.Node, DerivedQuantizationSpec]] = field(default_factory=list)\n others: list[tuple[fx.Node, fx.Node]] = field(default_factory=list)\n literals: list[tuple[fx.Node, fx.Node]] = field(default_factory=list)\n output: list[tuple[fx.Node] | tuple[fx.Node, SharedQuantizationSpec]] = field(default_factory=list)\n\nclass CustomQuantizationPattern(ABC):\n @abstractmethod\n def partition_types(self) -> list[OpOverload]:\n \"\"\"\n List of types to be passed to find_sequential_partitions_aten.\n \"\"\"\n pass\n\n @abstractmethod\n def get_anchors(\n self, gm: torch.fx.GraphModule, fused_partition: list[fx.GraphModule]\n ) -> Optional[PartitionAnchors]:\n pass\n\nclass LstmInputPattern(CustomQuantizationPattern):\n \"\"\"\n Quantization pattern for Lstm Input quantization. Accepts 3 input nodes.\n\n Basic quantization for all inputs and outputs.\n \"\"\"\n\n def partition_types(self) -> list[Type[OpOverload]]:\n return [torch.ops.aten.lstm.input]\n\n def get_anchors(\n self, gm: fx.GraphModule, fused_partition: list[fx.GraphModule]\n ) -> PartitionAnchors | None:\n lstm_node = fused_partition[0].nodes[-1]\n hidden_state_0, cell_state_0 = lstm_node.args[1][0], lstm_node.args[1][1]\n inputs = [(lstm_node, lstm_node.args[0]), (lstm_node, hidden_state_0), (lstm_node, cell_state_0)]\n weights = [(lstm_node, node) for node in lstm_node.args[2] if \"weight\" in node.target]\n weights_edges = [(x, y) for y, x in weights]\n\n bias_qspec = DerivedQuantizationSpec(\n derived_from=[\n (lstm_node.args[0], lstm_node),\n (hidden_state_0, lstm_node),\n (cell_state_0, lstm_node),\n *weights_edges,\n ],\n derive_qparams_fn=get_bias_qparams,\n dtype=torch.int32,\n quant_min=-(2**31),\n quant_max=2**31 - 1,\n qscheme=torch.per_tensor_affine,\n )\n biases = [(lstm_node, node, bias_qspec) for node in lstm_node.args[2] if \"bias\" in node.target]\n\n return PartitionAnchors(\n inputs=inputs,\n weights=weights,\n biases=biases,\n output=[(lstm_node,), (lstm_node,), (lstm_node,)],\n )\n\nclass CustomAtenQuantizer(Quantizer):\n def __init__(\n self, pattern: CustomQuantizationPattern, quantization_config: QuantizationConfig\n ) -> None:\n super().__init__()\n self.pattern = pattern\n self.quantization_config = quantization_config\n\n def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule:\n fused_partitions = find_sequential_partitions_aten(\n model,\n self.pattern.partition_types(),\n )\n\n input_act_qspec = self.quantization_config.input_activation\n weight_qspec = self.quantization_config.weight\n bias_qspec = self.quantization_config.bias\n output_act_qspec = self.quantization_config.output_activation\n\n for fused_partition in fused_partitions:\n if not no_outside_users(fused_partition):\n continue\n\n anchors = self.pattern.get_anchors(model, fused_partition)\n if not anchors:\n continue\n if is_annotated(\n [\n x[0]\n for x in anchors.inputs\n + anchors.weights\n + anchors.biases\n + anchors.output\n ]\n ):\n continue\n\n for output, *custom_spec in anchors.output:\n # pyre-ignore[16]: no attribute\n output.meta[\"quantization_annotation\"] = QuantizationAnnotation(\n # pyre-ignore[6]: incompatible parameter type\n output_qspec=(custom_spec[0] if custom_spec else output_act_qspec),\n _annotated=True,\n )\n\n def annotate_inputs(\n inputs: list[tuple[fx.Node , fx.Node]] | list[tuple[fx.Node, fx.Node, DerivedQuantizationSpec]],\n spec: Optional[QuantizationSpec],\n ) -> None:\n for node, input_node, *custom_spec in inputs:\n # pyre-ignore[16]: no attribute\n annotation = node.meta.get(\n \"quantization_annotation\",\n QuantizationAnnotation(_annotated=True),\n )\n # pyre-ignore[16]: no attribute\n annotation.input_qspec_map[input_node] = (\n custom_spec[0] if custom_spec else spec\n )\n # pyre-ignore[16]: no attribute\n node.meta[\"quantization_annotation\"] = annotation\n\n annotate_inputs(anchors.inputs, input_act_qspec)\n annotate_inputs(anchors.weights, weight_qspec)\n # pyre-ignore[6]: incompatible parameter type\n annotate_inputs(anchors.biases, bias_qspec)\n return model\n\n def validate(self, model: fx.GraphModule) -> None:\n pass\n\nact_qspec = QuantizationSpec(\n dtype=torch.int8,\n quant_min=-128,\n quant_max=127,\n qscheme=torch.per_tensor_affine,\n is_dynamic=False,\n observer_or_fake_quant_ctr=HistogramObserver.with_args(eps=2 ** -12),\n)\n\nwgt_qspec = QuantizationSpec(\n dtype=torch.int8,\n quant_min=-128,\n quant_max=127,\n qscheme=torch.per_tensor_symmetric,\n is_dynamic=False,\n observer_or_fake_quant_ctr=MinMaxObserver,\n ch_axis=0\n)\n\nclass CustomComposableQuantizer(ComposableQuantizer):\n def __init__(self):\n static_qconfig = QuantizationConfig(\n act_qspec,\n act_qspec,\n wgt_qspec,\n None,\n )\n super().__init__([CustomAtenQuantizer(LstmInputPattern(), static_qconfig),])\n\n def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule:\n for quantizer in self.quantizers:\n quantizer.annotate(model)\n return model\n\n def validate(self, model: torch.fx.GraphModule) -> None:\n return super().validate(model)\n \n \ndef test_lstm_model():\n input_shape = (1, 64)\n model = nn.LSTM(64, hidden_size=16, bidirectional=False, bias=True, num_layers=1)\n random_tensors = (torch.randn(input_shape),)\n calibration_inputs = [random_tensors, random_tensors]\n example_input = (torch.ones(input_shape),)\n\n exir_program_aten = torch._export.capture_pre_autograd_graph(model, example_input)\n\n quantizer = CustomComposableQuantizer()\n\n m = prepare_pt2e(exir_program_aten, quantizer)\n for i, data in enumerate(calibration_inputs):\n m(*data)\n m = convert_pt2e(m)\n\n print(m) # no quantize nodes after lstm.input\n```","reference_answer":"The problem has been resolved, RNNs can be quantized with current PyTorch PT2E quantization flow. Jerry Zhang explained me the principle of one operator output and the role of `getitem` op. The `getitem` ops are required to adhere to the one operator output principle. So no changes in PyTorch PT2E quantization flow are needed. To quantize the outputs in case of operators with multiple outputs such as RNNs, simply annotating the `getitem` nodes instead of the nodes itself is the way to go.\n\nThe annotation of outputs in the first example in `get_anchors()` function would then look like this:\n\n```python\n# The user nodes are getitem nodes\noutputs = [(user, output_qspec) for user in gru_node.users]\n\nreturn PartitionAnchors(\n inputs=inputs,\n weights=weights,\n biases=biases,\n output=outputs,\n)\n```","needs_clarification":false,"thread_id":218207,"url":"https://discuss.pytorch.org/t/pt2e-quant-quantization-of-operators-with-multiple-outputs-rnn-lstm/218207","created_at":"2025-03-24T18:12:14.530000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["roman-janik-nxp"],"answered_by_ptrblck":false} {"question":"Libtorch mpi distribution?\n\nfew days ago, I plan to study libtorch distributed training(MPI backend), and found an example dist-mnist [examples/cpp/distributed/dist-mnist.cpp at main · pytorch/examples · GitHub](https://github.com/pytorch/examples/blob/main/cpp/distributed/dist-mnist.cpp), in which `ProcessGroupMPI` is used for distribution. \n\nWhen I compile the source code, compiler reported two error messages: \n- ```undefined reference to `c10d::ProcessGroupMPI::abort()'``` \n- ```undefined reference to `c10d::ProcessGroupMPI::createProcessGroupMPI(std::vector >)'```\n\nseems that mpi-distribution codes are not compiled in pre-compiled libtorch package, and/or which library I should link?\n\nThanks.","reference_answer":"PyTorch binaries do not include an MPI implementation and you will have to build from source. There are many different implementations you can choose from:\n\nhttps://pytorch.org/tutorials/intermediate/dist_tuto.html#:~:text=nvidia%2Dsmi.-,MPI%20Backend,-The%20Message%20Passing\n\nWhen building you should ensure that this flag USE_MPI=1, https://github.com/pytorch/pytorch/blob/main/setup.py#L91-L92","needs_clarification":false,"thread_id":218215,"url":"https://discuss.pytorch.org/t/libtorch-mpi-distribution/218215","created_at":"2025-03-25T02:29:58.195000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["H-Huang"],"answered_by_ptrblck":false} {"question":"CPU memory usage increases every time I call the train function\n\nEvery time I call the train function, the cpu ram usage keeps increasing. I am training on gpu, the gpu consumption is stable. \nhere is the code: \n```\ndef train_model_memory_optimized(model, train_loader, val_loader, num_epochs=10, lr=0.001, \n lambda_reg=0.01, device='cpu', early_stopping_patience=5,\n accumulation_steps=4, use_mixed_precision=True):\n \"\"\"\n Trains a PyTorch model with validation and memory optimization techniques.\n \n Args:\n model (nn.Module): The PyTorch model to train.\n train_loader (DataLoader): The training data loader.\n val_loader (DataLoader): The validation data loader.\n num_epochs (int, optional): The number of epochs to train for. Defaults to 10.\n lr (float, optional): The learning rate. Defaults to 0.001.\n lambda_reg (float, optional): L2 regularization strength. Defaults to 0.01.\n device (str, optional): The device to use for training ('cpu' or 'cuda'). Defaults to 'cpu'.\n early_stopping_patience (int, optional): Number of epochs to wait before early stopping. Defaults to 5.\n accumulation_steps (int, optional): Number of steps to accumulate gradients. Defaults to 1.\n use_mixed_precision (bool, optional): Whether to use mixed precision training. Defaults to True.\n \n Returns:\n tuple: (best_model_state_dict, dict_metrics) where dict_metrics contains training history\n \"\"\"\n # Initialize model and optimization\n model = model.to(device)\n optimizer = optim.Adam(model.parameters(), lr=lr)\n criterion = nn.CrossEntropyLoss()\n \n # Initialize gradient scaler for mixed precision\n scaler = GradScaler() if use_mixed_precision and device.startswith('cuda') else None\n \n # Initialize tracking variables\n best_val = 0\n best_model_state_dict = None\n patience_counter = 0\n # history = {\n # 'train_loss': [],\n # 'val_accuracy': [],\n # 'val_precision': [],\n # 'val_recall': [],\n # 'val_f1': []\n # }\n \n for epoch in range(num_epochs):\n # Training phase\n model.train()\n total_loss = 0\n num_batches = 0\n \n for batch_idx, (inputs, targets) in enumerate(train_loader):\n inputs, targets = inputs.to(device), targets.to(device)\n \n # Mixed precision training\n if use_mixed_precision and device.startswith('cuda'):\n with autocast():\n outputs = model(inputs)\n loss = criterion(outputs, targets)\n # Scale loss for gradient accumulation\n loss = loss / accumulation_steps\n \n # Scales loss and calls backward()\n scaler.scale(loss).backward()\n \n # Step with gradient accumulation\n if (batch_idx + 1) % accumulation_steps == 0:\n scaler.step(optimizer)\n scaler.update()\n # More efficient than zero_grad()\n for param in model.parameters():\n param.grad = None\n else:\n outputs = model(inputs)\n loss = criterion(outputs, targets)\n # Scale loss for gradient accumulation\n loss = loss / accumulation_steps\n loss.backward()\n \n # Step with gradient accumulation\n if (batch_idx + 1) % accumulation_steps == 0:\n optimizer.step()\n # More efficient than zero_grad()\n optimizer.zero_grad(set_to_none=True)\n \n total_loss += loss.item() * accumulation_steps\n num_batches += 1\n \n # Explicitly delete intermediate tensors\n del inputs, outputs, targets, loss\n \n avg_train_loss = total_loss / num_batches\n # history['train_loss'].append(avg_train_loss)\n \n # Validation phase\n if val_loader:\n model.eval()\n correct = 0\n total = 0\n \n # More memory-efficient tracking of predictions\n all_targets = torch.tensor([], dtype=torch.long, device='cpu')\n all_predictions = torch.tensor([], dtype=torch.long, device='cpu')\n \n with torch.no_grad():\n for inputs, targets in val_loader:\n inputs, targets = inputs.to(device), targets.to(device)\n \n # For validation, always use full precision\n outputs = model(inputs)\n predictions = outputs.argmax(dim=1)\n \n correct += (predictions == targets).sum().item()\n total += targets.size(0)\n \n # Move to CPU before concatenating\n all_targets = torch.cat([all_targets, targets.cpu()])\n all_predictions = torch.cat([all_predictions, predictions.cpu()])\n \n # Explicitly delete tensors\n del inputs, outputs, targets, predictions\n \n # Calculate metrics (convert to numpy only once)\n val_accuracy = correct / total\n all_targets_np = all_targets.numpy()\n all_predictions_np = all_predictions.numpy()\n precision, recall, f1, _ = precision_recall_fscore_support(\n all_targets_np, \n all_predictions_np, \n average='weighted', \n zero_division=0\n )\n \n # Update history\n # history['val_accuracy'].append(val_accuracy)\n # history['val_precision'].append(precision)\n # history['val_recall'].append(recall)\n # history['val_f1'].append(f1)\n \n # Print progress\n print(f\"Epoch {epoch+1}/{num_epochs}\")\n print(f\"Train Loss: {avg_train_loss:.4f}\")\n print(f\"Val Accuracy: {val_accuracy:.4f}\")\n print(f\"Precision: {precision:.4f}, Recall: {recall:.4f}, F1: {f1:.4f}\")\n print(\"-\" * 50)\n \n # Clear unnecessary variables\n del all_targets, all_predictions, all_targets_np, all_predictions_np\n \n # Model checkpoint (save state_dict instead of whole model)\n if val_accuracy > best_val:\n best_model_state_dict = model.state_dict().copy()\n best_val = val_accuracy\n patience_counter = 0\n else:\n patience_counter += 1\n \n # Early stopping check\n if patience_counter >= early_stopping_patience:\n print(f\"Early stopping triggered after epoch {epoch+1}\")\n break\n \n # Free memory\n torch.cuda.empty_cache()\n gc.collect()\n \n return best_model_state_dict```","reference_answer":"I think I solved the problem. The set the persisntent dataloader hyperparameters to this and the ram usage seems to have stabilized. I think the persistent_workers flag was contributing to the increased memory footprint.\n```\nloader_kwargs = {\n 'batch_size': batch_size,\n 'num_workers': 0,\n 'pin_memory': True,\n 'persistent_workers': False,\n\n }\n```","needs_clarification":false,"thread_id":218229,"url":"https://discuss.pytorch.org/t/cpu-memory-usage-increases-every-time-i-call-the-train-function/218229","created_at":"2025-03-25T09:14:17.322000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["sakibbai"],"answered_by_ptrblck":false} {"question":"Does it make sense to mix the labels in each batch?\n\nWhen using binary classification model:\n\n* When training a deep model, at each training step, the model receives a batch (i.e batch of size 32 samples).\n* Let's assume that in each training batch there are always 16 samples with label '0' and 16 samples with label '1'.\n\n1. Does it matter how those samples are arranged in the batch?\n2. Is there a difference if the 16 labels with \"0\" appear first and then with \"1\" **vs** mix of all 32 samples?","reference_answer":"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.","needs_clarification":false,"thread_id":218230,"url":"https://discuss.pytorch.org/t/does-it-make-sense-to-mix-the-labels-in-each-batch/218230","created_at":"2025-03-25T09:27:24.079000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Why does not my code cause the error 'element 0 of tensors does not require grad and does not have a grad_fn'\n\nGiven the code fragment below, I freeze the weights of the neural network using `model.fc1.requires_grad_(False)` and `model.fc2.requires_grad_(False)`.\nIf I use `loss = criterion(outputs, y_batch)` to calculate the loss, the training is fine. Why does it not cause the error `RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn`?\nI think it should cause the error since all layers of the neural network have been frozen.\n\n```\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, TensorDataset\n\n# Define a simple neural network\nclass SimpleNet(nn.Module):\n def __init__(self, input_size, hidden_size, output_size):\n super(SimpleNet, self).__init__()\n self.fc1 = nn.Linear(input_size, hidden_size)\n self.fc2 = nn.Linear(hidden_size, output_size)\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.fc2(x)\n return x\n\ninput_size = 3\nhidden_size = 3\noutput_size = 3\nbatch_size = 16\nnum_epochs = 1\nlearning_rate = 0.01\nnum_samples = 1000 \nX_train = torch.randn(num_samples, input_size, requires_grad = True) \ny_train = torch.ones((num_samples, output_size))\ndataset = TensorDataset(X_train, y_train)\ndataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)\n\nmodel = SimpleNet(input_size, hidden_size, output_size)\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=learning_rate)\n\nfor epoch in range(num_epochs):\n total_loss = 0\n for batch_idx, (X_batch, y_batch) in enumerate(dataloader):\n optimizer.zero_grad()\n outputs = model(X_batch)\n loss = criterion(outputs, y_batch)\n print(loss._grad_fn)\n loss.backward() \n optimizer.step() \n \n if (batch_idx + 1) % 10 == 0:\n print(f'Batch [{batch_idx + 1}/{len(dataloader)}], Loss: {loss.item():.4f}')\n model.fc1.requires_grad_(False)\n model.fc2.requires_grad_(False)\n \nprint(\"Training complete!\")\n```","reference_answer":"Your input still requires gradients, so `X_train.grad` will receive valid gradients.\nUse `X_train = torch.randn(num_samples, input_size)` and it will fail with the expected error message.","needs_clarification":false,"thread_id":218268,"url":"https://discuss.pytorch.org/t/why-does-not-my-code-cause-the-error-element-0-of-tensors-does-not-require-grad-and-does-not-have-a-grad-fn/218268","created_at":"2025-03-26T02:15:00.792000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)]) return Image instead of Tensor?\n\n[https://pytorch.org/vision/main/generated/torchvision.transforms.v2.ToTensor.html#:~:text=v2.ToTensor%20is%20deprecated%20and%20will%20be%20removed%20in,scale%3DTrue%29%5D%29.%20Output%20is%20equivalent%20up%20to%20float%20precision.]([v2.ToTensor()] [DEPRECATED] Use v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)]) instead.)\n\nv2.Compose([v2.ToTensor()]) is return a Tensor\nBut v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)]) is return a Image\n\nAre there steps missing?","reference_answer":"The second transformation will return a [`torchvision.tv_tensors._image.Image`](https://pytorch.org/vision/main/generated/torchvision.tv_tensors.Image.html#torchvision.tv_tensors.Image) as seen here:\n```python\ntransform = v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])\nimage = torchvision.transforms.ToPILImage()(torch.randn(3, 224, 224))\nout = transform(image)\nprint(type(out))\n# \n```\nIf you want to access the internal tensor use the `.data` attribute as shown in the docs.","needs_clarification":false,"thread_id":218276,"url":"https://discuss.pytorch.org/t/v2-compose-v2-toimage-v2-todtype-torch-float32-scale-true-return-image-instead-of-tensor/218276","created_at":"2025-03-26T07:52:32.296000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Segmentation fault when calling .backward() after moving data to GPU (PyTorch + CUDA 12.1)\n\nHi everyone,\nI'm running into a segmentation fault (core dumped) error while training a model using PyTorch on a CUDA-enabled GPU.\nI'm not sure what's going wrong, and would really appreciate any guidance.\n\nMy Environment\nGPU: 2× NVIDIA GeForce RTX 4060 Ti\nDriver Version: 550.120\nCUDA Version (Driver-side): 12.4\ncuDNN Version: 8902\nPyTorch Version: 2.2.0+cu121\nPython: 3.10.12\nCUDA available: True\nDetected CUDA from PyTorch: 12.1\nHost OS: Ubuntu 24.04\nDocker Image: nvidia/cuda:12.4.1-runtime-ubuntu22.04\nKernel: Linux 6.8.0-55-generic x86_64 with glibc 2.35\nRunning inside Docker: Yes\n\n**The Problem**\nDuring training, the script suddenly crashes with a segmentation fault.\nThe crash does not happen at a specific line every time — sometimes it happens in .backward(), sometimes while creating a tensor on GPU using .to(device).\nIt usually occurs after a few training batches, not at the very beginning.\n\nHere’s a simplified version of the code:\n```python\ndef train_test_ht_sl(model, train_data, test_data, head_list, tail_list):\n import datetime\n model.scheduler.step()\n print('start training: ', datetime.datetime.now())\n model.train()\n total_loss = 0.0\n slices = train_data.generate_batch(model.batch_size)\n\n for i, j in zip(slices, np.arange(len(slices))):\n model.optimizer.zero_grad()\n targets, scores = forward(model, i, train_data)\n\n # targets = torch.from_numpy(np.array(targets)).long().to('cuda:1')\n targets = torch.tensor(targets).long().to(device)\n loss = model.loss_function(scores, targets - 1)\n loss.backward() # <- crash sometimes happens here\n```\n```python\t\t\ndef forward(model, i, data):\n alias_inputs, A, items, mask, targets = data.get_slice(i)\n\n alias_inputs = torch.tensor(alias_inputs, dtype=torch.long, device=device)\n items = torch.tensor(items, dtype=torch.long, device=device)\n mask = torch.tensor(mask, dtype=torch.long, device=device)\n\n A_np = np.stack(A)\n A = torch.tensor(A_np, dtype=torch.float, device=device) # <- or here\n\n hidden = model(items, A)\n\n get = lambda i: hidden[i][alias_inputs[i]]\n seq_hidden = torch.stack([get(i) for i in torch.arange(len(alias_inputs)).long()])\n\n return targets, model.compute_scores(seq_hidden, mask)\n```\n\n**Error excerpt**\n```python\nTraining Progress: 20%|██ | 6/30 [16:14<1:04:58, 162.43s/it]\nFatal Python error: Segmentation fault\n\nCurrent thread 0x00007... (most recent call first):\n \n\nThread 0x00007...:\n File \"/usr/lib/python3.10/threading.py\", line 324 in wait\n ...\n File \"/usr/lib/python3.10/site-packages/torch/autograd/__init__.py\", line 266 in backward\n ```\n **My Question**\nI'm still new to CUDA programming and PyTorch internals, so I’m not sure:\nWhy might this segmentation fault occur?\nAm I doing something wrong when moving data to the GPU?\nIs there a safer or more proper way to handle tensors before calling .backward()?\nAny help or explanation would be really appreciated. Thank you in advance!","reference_answer":"**Update (Resolved):**\nAfter investigating low-level stability issues, I changed several **BIOS settings** that control CPU–GPU interaction and power states. Specifically:\n\n* Limited **C-states** (disabled deep sleep states)\n\n* Disabled **P-states/Turbo Boost**\n\n* Disabled **Resizable BAR**\n\n* Disabled **Above 4G Decoding**\n\n* Set **PCIe Generation** to a fixed higher value\n\nThese changes stabilized the PCIe/CPU–GPU communication and eliminated the segmentation fault crashes.\n\nIn summary: **Power-state restrictions and memory mapping options improved GPU–CPU stability, while increasing PCIe Gen optimized performance.**","needs_clarification":false,"thread_id":218309,"url":"https://discuss.pytorch.org/t/segmentation-fault-when-calling-backward-after-moving-data-to-gpu-pytorch-cuda-12-1/218309","created_at":"2025-03-27T04:04:55.735000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[8],"answer_authors":["Syngyeon"],"answered_by_ptrblck":false} {"question":"[Solved] Maskrcnn_benchmark + sm_90 (or Cuda > 11.8 or torch > 1.10 )\n\nSo I have working maskrcnn_benchmark working with torch==1.10.0+cu111.\n\nNow I shift to NVIDIA H100 which are sm_90.\n\nsm_90 requires CUDA 11.8 which is supported on torch 1.13.0 onwards. \ntorch 1.13.0 (or any other torch >1.11) have removed which mean I have to patch the \n`maskrcnn_benchmark/csrc/cuda/` with `` following steps here : https://github.com/pytorch/pytorch/issues/72807\n\nBut once I do all of this I get \n```\nmaskrcnn_benchmark/csrc/cuda/deform_pool_kernel_cuda.cu(245): error: no instance of overloaded function \"atomicAdd\" matches\n the argument list \n argument types are: (c10::Half *, c10::Half) \n detected during instantiation of \"void DeformablePSROIPoolBackwardAccKernel(int, const scalar_t *, const scalar_t *, int, scalar_t, int, int, int, int, int, int, scalar_t \n*, scalar_t *, const scalar_t *, const scalar_t *, const scalar_t *, int, scalar_t, int, int, int, int, int) [with scalar_t=c10::Half]\" \n(347): here \n```\n\nWhat do I do now :/","reference_answer":"[UPDATE] After some chatgpt \n```\n\n#include \n#include \n\ntemplate \n__device__ void atomicAddHalf(scalar_t* address, scalar_t val) {\n if constexpr (std::is_same::value) {\n atomicAdd(reinterpret_cast<__half*>(address), __double2half(val));\n } else if constexpr (std::is_same::value) {\n atomicAdd(reinterpret_cast<__half*>(address), __float2half(val));\n } else {\n atomicAdd(reinterpret_cast<__half*>(address), static_cast<__half>(val));\n }\n}\n```\nreplace `atomicAdd` with `atomicAddHalf` \n\nAlso in `setup.py` \n\n```\nextra_compile_args[\"nvcc\"] = [\n '-arch=sm_90',\n \"-DCUDA_HAS_FP16=1\",\n \"-D__CUDA_NO_HALF_OPERATORS__\",\n \"-D__CUDA_NO_HALF_CONVERSIONS__\",\n \"-D__CUDA_NO_HALF2_OPERATORS__\",\n ]\n```\nThe build is successful. Now the code is compatible with even torch 2.4 as well which doesn't require explicit `'-arch=sm_90'` argument","needs_clarification":false,"thread_id":218350,"url":"https://discuss.pytorch.org/t/solved-maskrcnn-benchmark-sm-90-or-cuda-11-8-or-torch-1-10/218350","created_at":"2025-03-27T23:49:09.573000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Priyank_Pathak"],"answered_by_ptrblck":false} {"question":"Will doing two times forward and backward work fine?\n\nI recently find that code like the following doesn't work well for ddp (broadcast_buffers=True)\n\n```python\nloss1 = L1(model(x1), y1)\nloss2 = L1(model(x2), y2)\nloss = loss1+loss2\nloss.backward()\noptimizer.step()\noptimizer.zero_grad()\n```\n\nSomeone recommend using another wrapper to do something like the following\n\n```\nclass Wrapper():\n def __init__(self, model):\n self.model = model\n def forward(self, x1, x2, y1, y2):\n loss1 = L1(self.model(x1), y1)\n loss2 = L1(self.model(x2), y2)\n loss = loss1+loss2\n return loss\n\nloss = wrapper(x1,x2,y1,y2)\n\nloss.backward()\noptimizer.step()\noptimizer.zero_grad()\n```\n\nI don't want to use the wrapper because my actual code is more complicated to implement a wrapper like the above.\nBut if I change the code to\n\n```\n# L1 represents L1 loss; model represents my model\nloss1 = L1(model(x1), y1)\nloss1.backward()\n\nloss2 = L1(model(x2), y2)\nloss2.backward()\n\noptimizer.step()\noptimizer.zero_grad()\n```\n\nDoes the code work equally to the code using wrapper?","reference_answer":"Hi Chener!\n\nYes, your third version where you call `.backward()` twice, is mathematically the same\nas your first two versions where you sum the two losses and then call `.backward()`\nonce. (It could well have slightly different numerical round-off error.)\n\nWhen you call `.backward()` twice (with no intervening `.zero_grad()`) the two gradients\nget accumulated into the `.grad` properties of the various parameters. But the sum of the\ngradients is the gradient of the sum, so you get the same result as summing the losses and\ncalculating the gradient of the sum with a single call to `.backward()`.\n\nDepending on your use case and the amount of memory you have, you could combine\nyour inputs, `x1` and `x2`, into a single batch tensor, `x_both`, and, likewise, combine\nyour targets into a single batch tensor, `y_both`, and perform a single forward and\nbackward pass:\n\n```python\nloss_both = L1 (model (x_both), y_both)\nloss_both.backward()\noptimizer.step()\noptimizer.zero_grad()\n```\n\nAssuming that your loss function, `L1()`, uses (the equivalent of) `reduction = 'sum'`\n(or nearly equivalently, `reduction = 'mean'`), this will be mathematically equivalent\nto your three versions.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":218388,"url":"https://discuss.pytorch.org/t/will-doing-two-times-forward-and-backward-work-fine/218388","created_at":"2025-03-29T03:56:38.060000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Torch.compile() causes RuntimeError: element 0 of tensors does not require\n\nHi,\n\nIn the second torch.autograd.grad() for second derivative (d2y_dx2 in the below example) I got the RuntimeError:element 0 of tensors does not require grad and does not have a grad_fn.\nI don't get what the error means.The error happens only when torch.compile() is applied to ScalarNet. Any explanation will be appreciated!\n\n```\ninput_scalar = torch.randn(1, device=device, requires_grad=True)\n\n# Define the module\nclass ScalarNet(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.seq = torch.nn.Sequential(\n torch.nn.Linear(1, 5), torch.nn.Tanh(), torch.nn.Linear(5, 1)\n )\n\n def forward(self, x):\n # Ensure input has feature dim\n if x.ndim == 1:\n x = x.unsqueeze(-1)\n return self.seq(x).squeeze(-1) # Squeeze output back to scalar per batch item\n\nnet_scalar = ScalarNet().to(device)\n\n# Compile the module\ntry:\n print(\"Compiling scalar model...\")\n compiled_net_scalar = torch.compile(net_scalar)\n print(\"Compilation successful.\")\nexcept Exception as e:\n print(f\"Scalar model compilation failed: {e}\")\n compiled_net_scalar = net_scalar # Fallback\n\n# Compute derivatives using the compiled module\ntry:\n # First derivative\n y = compiled_net_scalar(input_scalar)\n # Ensure grad_outputs matches y shape (should be (1,) if input_scalar is (1,))\n grad_output_y = torch.ones_like(y)\n dy_dx = torch.autograd.grad(\n y, input_scalar, grad_outputs=grad_output_y, create_graph=True\n )[0]\n print(\"First derivative computed.\")\n\n # Second derivative\n # Ensure grad_outputs matches dy_dx shape (should be (1,))\n grad_output_dydx = torch.ones_like(dy_dx)\n # Use retain_graph=False if this is the last grad call needing this graph segment\n d2y_dx2 = torch.autograd.grad(\n dy_dx, input_scalar, grad_outputs=grad_output_dydx, create_graph=False\n )[0]\n print(\"Second derivative computed successfully!\")\n print(f\"d2y/dx2 = {d2y_dx2.item()}\")\n\nexcept Exception as e:\n print(f\"\\n--- ERROR during second derivative test ---\")\n print(e)\n import traceback\n\n traceback.print_exc()\n\n```","reference_answer":"Never mind. I can solve the problem by adding fullgraph=True.","needs_clarification":false,"thread_id":218417,"url":"https://discuss.pytorch.org/t/torch-compile-causes-runtimeerror-element-0-of-tensors-does-not-require/218417","created_at":"2025-03-30T14:45:18.160000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Joeyoung"],"answered_by_ptrblck":false} {"question":"`nodes.Batcher` on multiple outputs\n\nI am using `nodes.Batcher` on a node with multiple outputs.\n\n```\nfrom torchdata.nodes import Batcher, IterableWrapper, Loader, Mapper\n\nnode = IterableWrapper(range(16))\nnode = Mapper(node, map_fn=lambda x: (x, x**2))\nnode = Batcher(node, batch_size=4)\nloader = Loader(node)\nprint(list(loader))\n```\nThis results in batches of tuples (`[(0, 0), (1, 1), (2, 4), (3, 9)]`) instead of tuples of batches. What am I doing wrong here?","reference_answer":"I am missing a call to `default_collate` after batching.","needs_clarification":false,"thread_id":218482,"url":"https://discuss.pytorch.org/t/nodes-batcher-on-multiple-outputs/218482","created_at":"2025-04-01T09:22:26.477000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["pascal"],"answered_by_ptrblck":false} {"question":"Selective gradient clipping\n\nHi,\nI 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.\nThus 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 gradients were exploding and I recieved nan loss. How can I avoid this, while keeping gradient from not exploding and also freeze the grads. Is it possible to selectively apply grad clipping on particular weights?","reference_answer":"I don't think this would be directly possible without workarounds of creating custom trainable and frozen weights in custom modules.\nGiven that gradient clipping should not change gradients with a value of zero you should be able to just apply it on the entire parameter. \nIf you want to compute e.g. the `norm` of the trainable part only, you could use [`torch.nn.utils.clip_grads_with_norm_`](https://pytorch.org/docs/stable/generated/torch.nn.utils.clip_grads_with_norm_.html#torch.nn.utils.clip_grads_with_norm_) and pass the pre-calculated `total_norm` to this call.","needs_clarification":false,"thread_id":218493,"url":"https://discuss.pytorch.org/t/selective-gradient-clipping/218493","created_at":"2025-04-01T14:14:39.526000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Pytorch Cuda returns Error 500: named symbol not found\n\nDear community,\nI try to train a simple model in a docker container deployed on my local machine. I use the following docker image for my development container: pytorch/pytorch:2.6.0-cuda12.6-cudnn9-runtime\n\nWhenever I try to use my gpu (nvidia rtx 4090) (by typing\"\npython -c \"import torch; print(torch.cuda.is_available())\"), I get the symptom as described below:\n\n```\nRuntimeError: Unexpected error from cudaGetDeviceCount(). Did you run some cuda functions before calling NumCudaDevices() that might have already set an error? Error 500: named symbol not found\n```\n\nWhat steps did I take:\n* nvidia-smi returns correct driver and cuda version (VM):\n```\n+-----------------------------------------------------------------------------------------+\n| NVIDIA-SMI 570.133.07 Driver Version: 572.83 CUDA Version: 12.8 |\n|-----------------------------------------+------------------------+----------------------+\n| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|=========================================+========================+======================|\n| 0 NVIDIA GeForce RTX 4090 On | 00000000:01:00.0 Off | Off |\n| 0% 36C P8 10W / 450W | 1248MiB / 24564MiB | 2% Default |\n| | | N/A |\n+-----------------------------------------+------------------------+----------------------+\n```\n* nvidia-smi Host:\n```\n+-----------------------------------------------------------------------------------------+\n| NVIDIA-SMI 572.83 Driver Version: 572.83 CUDA Version: 12.8 |\n|-----------------------------------------+------------------------+----------------------+\n| GPU Name Driver-Model | Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|=========================================+========================+======================|\n| 0 NVIDIA GeForce RTX 4090 WDDM | 00000000:01:00.0 Off | Off |\n| 0% 37C P8 11W / 450W | 1226MiB / 24564MiB | 0% Default |\n| | | N/A |\n+-----------------------------------------+------------------------+----------------------+\n```\n\n* nvcc --version (VM) returns:\nnvcc: NVIDIA (R) Cuda compiler driver\nCopyright (c) 2005-2023 NVIDIA Corporation\nBuilt on Mon_Apr__3_17:16:06_PDT_2023\nCuda compilation tools, release 12.1, V12.1.105\nBuild cuda_12.1.r12.1/compiler.32688072_0\n\nTherefore the gpu seems to be correctly recognized by the container.\n\nFurthermore I tried the following:\n* Updating nvidia drivers on host with reboot after installation\n* different pytorch docker images (2.3.1; 2.5.1; 2.6) devel and runtime\n* Manual removal and reinstall of pytorch in VM\n\nFurther Setup Details:\nWindows 11 24H2\nNvidia RTX4090\nDocker Desktop Engine v26.0.0\n\nI do not know what else to do in order to make pytorch work with my gpu. Any help is appreciated. I'll gladly give more details if needed.\n\nThank you in advance!","reference_answer":"After many attempts, I have found the solution: \n**I needed to upgrade the Docker Desktop version** \n\nFor future reference - the following configuration works for me:\n* Docker Engine v28.0.4 with Docker Desktop 4.40.0 (187762)\n* Docker image: pytorch/pytorch:2.6.0-cuda12.6-cudnn9-runtime\n* nvidia driver version: 572.83; Cuda-version: 12.8\n\nThere is no need to install any additional cuda framework on the host nor on the client. I didn't need to install any nvidia-ctk (container-toolkit) as well.\n\nThank you for your great support nevertheless!","needs_clarification":false,"thread_id":218501,"url":"https://discuss.pytorch.org/t/pytorch-cuda-returns-error-500-named-symbol-not-found/218501","created_at":"2025-04-01T18:36:39.157000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[8],"answer_authors":["torch_fan"],"answered_by_ptrblck":false} {"question":"Is there a faster way to compute the jacobian than autograd.functional.jacobian?\n\nGiven a big model, a vector-valued function f:R^n -> (f_1, f_2,...,f_m) with n>>m and m>1. Now I need grad(f_i) w.r.t. to ONE SINGLE input x and I need it for every f_i. I can do that very easily just by using *autograd.functional.jacobian*\n\n```\njacobianMatrix = functional.jacobian(myFunction, x)\n```\nAnd from here on I can access all the needed gradients for f_i.\n\nMy question is, if there maybe is a faster method to do exactly that. I am aware of *torch.func* and *jacrev* and its vectorization capabilities but in my case where I just use one single input instance, *jacrev* seems a little bit slower and seemingly has a big memory footprint.\n\nOn the other hand I could use *autograd.grad* and just compute the jacobian^T vector product and use the unitvectors as *grad_outputs* to extract the gradients from the jacobian. I tested this version too and it is slower than just to compute the full jacobian.\n\n**Is there maybe another method I could try?**\n\nWhy can I only compute gradients w.r.t. one instance? I don't know the other inputs in advance, because input1 is calculated from the gradients w.r.t. input0 and therefore vectorization won't help me in this case.","reference_answer":"Hi Stev!\n\nOkay, I think I understand now.\n\nYou said that the dimensionality of your input, n, is much greater than the dimensionality\nof your output, m. Therefore you want to use regular \"reverse-mode\" autograd, rather\nthan forward-mode autograd.\n\n`autograd.functional.jacobian()` (with `vectorize = True` and the default value for\n`strategy` of `'reverse-mode'`) should be the fastest approach. Note that the documentation\nsuggests that [jacrev()](https://pytorch.org/docs/2.6/generated/torch.func.jacrev.html) is \"less experimental,\" but the two should be doing basically the same\nthing under the hood, namely using a loop to perform a separate backward pass for each\nelement of the output, but with that loop \"vectorized\" using `vmap()`.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":218647,"url":"https://discuss.pytorch.org/t/is-there-a-faster-way-to-compute-the-jacobian-than-autograd-functional-jacobian/218647","created_at":"2025-04-05T18:39:29.382000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Right way to insert QuantStub and DeQuantStub in eager mode quantization\n\nI note many examples of eager mode quantization only insert QuantStub and DeQuantStub once to the beginning and end of the whole network, like [this tutorial on quantization aware training](https://pytorch.org/tutorials/advanced/static_quantization_tutorial.html#model-architecture) and the [torchvision resnet model](https://github.com/pytorch/vision/blob/main/torchvision/models/quantization/resnet.py). What is the different between inserting QuantStub/DeQuantStub only once to the whole model and inserting a pair of QuantStub/DeQuantStub to each submodule? Which way is better for eager mode quantization? Thank you for your help!","reference_answer":"A single QuantStub at the model input and a single DeQuantStub at the output is the usual choice when every operator in the model is quantized. It is typically more performant.\n\nA QuantStub/DeQuantStub pair around each submodule leaves that submodule unquantized. The extra q/dq ops make the model slower than the original, but this layout can be used to simulate the accuracy impact of quantization when there are no quantized operators implemented.\n\nScale and zero point are decided from the `qconfig` attached to each module. Conv-bn-relu fusion is not automatic in eager mode, so call `fuse_modules` yourself. Later versions of quantization do these steps automatically.\n\nTo see what happens during eager mode quantization, read `prepare` (https://github.com/pytorch/pytorch/blob/77407b38a994c4a4de14b2253d81d2fed17cc36d/torch/ao/quantization/quantize.py#L335) and `convert` (https://github.com/pytorch/pytorch/blob/77407b38a994c4a4de14b2253d81d2fed17cc36d/torch/ao/quantization/quantize.py#L616) in `torch/ao/quantization/quantize.py`.","needs_clarification":false,"thread_id":218666,"url":"https://discuss.pytorch.org/t/right-way-to-insert-quantstub-and-dequantstub-in-eager-mode-quantization/218666","created_at":"2025-04-06T15:53:04.268000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4,6,7],"answer_authors":["jerryzh168"],"answered_by_ptrblck":false} {"question":"QAT model is not performing as expected when compared to the original model\n\nI'm trying to perform QAT utilizing MobileNetV2 with the goal of converting it into TFLite. However, after training the model, I run a bench-marking script to compare its performance to the original model and see that the performance deprecates greatly.\n\nHere are the important code snippets:\n```\nfrom torchvision import models\nfrom torch.ao.quantization.quantize_pt2e import prepare_qat_pt2e\nfrom torch.ao.quantization.quantizer.xnnpack_quantizer import XNNPACKQuantizer, get_symmetric_quantization_config\n\nmodel = models.mobilenet_v2(weights='DEFAULT')\n\nexample_inputs = (next(iter(dataloader))[0].to(device),)\nmodel = torch.export.export_for_training(model, example_inputs).module()\nquantizer = XNNPACKQuantizer().set_global(get_symmetric_quantization_config(is_qat=True))\n\nmodel = prepare_qat_pt2e(model, quantizer)\n\ntrain_model(model)\n```\n\nI only included what I thought was relevant since I didn't want to add confusion with all of my helper functions\n\n```\ndef train_model(model):\n\n for phase in ['train', 'val']:\n is_train = phase == 'train'\n\n if is_train:\n torch.ao.quantization.move_exported_model_to_train(model)\n else:\n # Switch to evaluation mode to perform inference\n torch.ao.quantization.move_exported_model_to_eval(model)\n\n data_loader = train_loader if is_train else val_loader\n\n running_loss = 0.0\n total_samples = 0.0\n predictions, ground_truths, probabilities = [], [], []\n\n with tqdm(total=len(data_loader), desc=f\"{phase.capitalize()} Epoch {epoch + 1}/{epochs}\") as pbar:\n for inputs, labels in data_loader:\n inputs, labels = inputs.to(device), labels.to(device)\n \n # Zero gradients only during training\n if is_train:\n optimizer.zero_grad()\n \n # Enable gradients only in training phase\n with torch.set_grad_enabled(is_train): \n\n model = model.to(device)\n model_logits = model(inputs)\n\n soft_loss = compute_distillation_loss(model_logits)\n\n label_loss, probs, preds = compute_loss_and_predictions(model_logits, labels, criterion)\n \n # Compute weighted combination of the distillation and cross entropy losses\n loss = soft_target_loss_weight * soft_loss + ce_loss_weight * label_loss\n\n # Backward pass and optimizer step in training phase\n if is_train:\n loss.backward()\n optimizer.step()\n \n # Update progress bar with average loss so far\n pbar.set_postfix(loss=f\"{running_loss / total_samples:.4f}\")\n pbar.update(1)\n```\n`quantized_model = convert_pt2e(model, fold_quantize=False)`\n\n### Actual vs expected behavior:\n\nI would expect that the quantized model has better performance than the original model but it does not.\n\n| | Original | QAT |\n|--------|--------|--------|\n| Model Size (MB) | 9.1899 | 11.1504 |\n| Inference Time (sec/sample) | 0.002896 | 0.011141 |\n| Throughput (samples/sec) | 345.29 | 89.76 |\n| Energy per Sample (Joules) | 0.3436 | 1.350853 |\n| Throughput per Watt (samples/sec/W) | 2.91 | 0.74 | \n\nThis is even stranger since if I switch to FX Graph QAT, I get the expected behavior. However, I need to use Export quantization since I want to use the ai-edge-torch API to convert my model to TFLite.\n\n | | Original | QAT |\n|--------|--------|--------|\n| Model Size (MB) | 9.1899 | 2.3465 |\n| Inference Time (sec/sample) | 0.002896 | 000250 |\n| Throughput (samples/sec) | 345.29 | 4003.28 |\n| Energy per Sample (Joules) | 0.3436 | 0.0271 |\n| Throughput per Watt (samples/sec/W) | 2.91 | 36.85 | \n\nAdditionally, when I print the resulting QAT model I get the following:\n```\nGraphModule(\n(features): Module(\n(0): Module(\n (1): Module()\n)\n(1): Module(\n (conv): Module(\n (0): Module(\n (1): Module()\n )\n (2): Module()\n )\n)\n(2): Module(\n (conv): Module(\n (0): Module(\n (1): Module()\n )\n (1): Module(\n (1): Module()\n )\n (3): Module()\n )\n)\n(3): Module(\n...\n```\nI would think that it would be more similar to the resulting QAT model from FX Graph quantization which leads me to believe that it is not training correctly. The FX Graph is added below:\n\n```\nGraphModule(\n (features): Module(\n (0): Module(\n (0): QuantizedConv2d(3, 32, kernel_size=(3, 3), stride=(2, 2), scale=0.22475136816501617, zero_point=113, padding=(1, 1))\n (2): ReLU6(inplace=True)\n )\n (1): Module(\n (conv): Module(\n (0): Module(\n (0): QuantizedConv2d(32, 32, kernel_size=(3, 3), stride=(1, 1), scale=0.36381739377975464, zero_point=112, padding=(1, 1), groups=32)\n (2): ReLU6(inplace=True)\n )\n (1): QuantizedConv2d(32, 16, kernel_size=(1, 1), stride=(1, 1), scale=0.5194709300994873, zero_point=139)\n )\n )\n...\n```","reference_answer":"yeah this is expected for pt2e flow, since it's not the final model you'll use, the produced model can be further lowered to some backends like xnnpack, please check https://pytorch.org/tutorials/prototype/pt2e_quant_ptq.html#convert-the-calibrated-model-to-a-quantized-model for more details.\n\nyou can convert this format to tflite, but will need to write some converters.\n\nand check out https://pytorch.org/executorch/stable/tutorials/export-to-executorch-tutorial.html#lowering-to-edge-dialect for lowering the quantized model to executorch","needs_clarification":false,"thread_id":218736,"url":"https://discuss.pytorch.org/t/qat-model-is-not-performing-as-expected-when-compared-to-the-original-model/218736","created_at":"2025-04-06T23:31:19.415000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["jerryzh168"],"answered_by_ptrblck":false} {"question":"ERROR: Could not find a version that satisfies the requirement torch (from versions: none)\n\nHi,\n\nI'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.5 with pip 20.0.2 and I'm using a virtual environment to use python 3.9.\n\nOn the pytorch \"start locally\" page, the only way to use 12.8 appears to be to use the preview nightly build, and the install command it generates is:\n\n```pip3 install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu128```\n\nWhen I run this in my terminal however, it says:\n\n```\nLooking in indexes: https://download.pytorch.org/whl/nightly/cu128\nERROR: Could not find a version that satisfies the requirement torch (from versions: none)\nERROR: No matching distribution found for torch\n```\n\nIf i go manually to https://download.pytorch.org/whl/nightly/cu128 however, I can see torch! Can anyone advise what the likely cause of the commands failure is? I'm a bit confused.\n\nThanks!","reference_answer":"Maxwell GPUs such as the Quadro M2200 are deprecated in CUDA 12.8, so PyTorch binaries built with CUDA 12.8 do not support them. Install a PyTorch binary built with an older CUDA version instead, such as 11.8, 12.4 or 12.6. You don't need to install CUDA separately, because the PyTorch binary ships with its own CUDA runtime dependencies. Building from source could still work, but an older CUDA release is the recommended route.","needs_clarification":false,"thread_id":218843,"url":"https://discuss.pytorch.org/t/error-could-not-find-a-version-that-satisfies-the-requirement-torch-from-versions-none/218843","created_at":"2025-04-07T21:21:50.654000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,4],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Nuclei segmentation with variable nuclei classes per patch/image\n\nI need to perform nuclei segmentation. There are total 5 nuclei classes. However, some patches contain only 2, 3, or 4 nuclei classes, while some contain all 5 classes. Lets say there is a patch A with only 3 nuclei classes -- class A, C, and E. In this case, how do I create labelled and binary masks? Since each colour represents a particular nuclei class, should I use a black mask for class B and D? \n\nThank you.","reference_answer":"Hi Kountay!\n\nLet me assume that each pixel in an image is in exactly one class (including background).\nLet me also assume that your existing binary masks respect this, that is, if a given pixel\nis `1` in the binary mask for class A, it is `0` for the binary class for class B, and so on. For\nconvenience, let me also assume that your binary masks are already pytorch tensors of\ntype `long`.\n\nYou could then do something like the following:\n\n```python\nmulticlassMask = torch.zeros (H, W, dtype = torch.long)\nif maskExists ('A'): multiclassMask += 1 * maskA\nif maskExists ('B'): multiclassMask += 2 * maskB\nif maskExists ('C'): multiclassMask += 3 * maskC\nif maskExists ('D'): multiclassMask += 4 * maskD\nif maskExists ('E'): multiclassMask += 5 * maskE\n```\n(You wouldn't have to follow this particular scheme -- there are lots of ways to accomplish\nthe same thing. For example, if `maskA` doesn't exist, you could simply create one made\nup of all zeros, and then add all five masks together with weights, as above.)\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":218860,"url":"https://discuss.pytorch.org/t/nuclei-segmentation-with-variable-nuclei-classes-per-patch-image/218860","created_at":"2025-04-08T07:06:50.516000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Torch.compile emits double backward error even when the corresponding function is disabled\n\nHi,\n\nI'm trying to compile my model and use its output to calculate divergence.\n\nI'm aware that double backward is not compatible with torch.compile. Thus, I separated the forward and the divergence calculation and even put torch.compiler.disable on the latter. No luck so far, though.\n\nCould someone please explain why torch.compile is trying to compile the div function below even when its supposed to be disabled?\n\n```\nclass Foo:\n def __init__(self):\n self.model = torch.nn.Linear(5, 5)\n self.data = [torch.rand(5, requires_grad=True) for _ in range(5)]\n\n @torch.compile\n def foor(self, i):\n output = self.model(self.data[i])\n return output\n\n@torch.compiler.disable\ndef div(foo, output):\n (dx,) = torch.autograd.grad(\n output,\n foo.data[1],\n grad_outputs=torch.ones_like(output),\n create_graph=True,\n )\n (dx2,) = torch.autograd.grad(\n dx,\n foo.data[1],\n grad_outputs=torch.ones_like(dx),\n create_graph=True,\n )\n return dx2\n\nif __name__ == \"__main__\":\n foo = Foo()\n # warmup\n o1 = foo.foor(0)\n\n output = foo.foor(1)\n\n dx2 = div(foo, output)\n```\n\nError message:\n```\nTraceback (most recent call last):\n File \"/main/torch_autograd/test.py\", line 55, in \n dx2 = div(foo, output)\n ^^^^^^^^^^^^^^^^\n File \"/nnvenv/lib/python3.11/site-packages/torch/_dynamo/eval_frame.py\", line 745, in _fn\n return fn(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^^^\n File \"/main/torch_autograd/test.py\", line 39, in div\n (dx2,) = torch.autograd.grad(\n ^^^^^^^^^^^^^^^^^^^^\n File \"/nnvenv/lib/python3.11/site-packages/torch/autograd/__init__.py\", line 496, in grad\n result = _engine_run_backward(\n ^^^^^^^^^^^^^^^^^^^^^\n File \"/nnvenv/lib/python3.11/site-packages/torch/autograd/graph.py\", line 823, in _engine_run_backward\n return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/nnvenv/lib/python3.11/site-packages/torch/autograd/function.py\", line 307, in apply\n return user_fn(self, *args)\n ^^^^^^^^^^^^^^^^^^^^\n File \"/nnvenv/lib/python3.11/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py\", line 1728, in backward\n raise RuntimeError(\nRuntimeError: torch.compile with aot_autograd does not currently support double backward\n```","reference_answer":"Your torch.compile decorator is indeed only wrapping your forward code. But if your inputs require grad, and grad mode is enabled, torch.compile traces out the backward graph ahead of time whether or not you have the context manager wrapping the code where you actually invoke backward later. \n\nIt's not possible today to run forward in compile but backward in a non-compiled way (in eager). In order to run the backward in eager, the autograd graph needs to be built every iteration, and that won't happen if you ran the forward compiled graph. \n\nThere are also advantages to considering the two graphs jointly, e.g. to optimize what is saved between them. \n\n> How come this operation (double backward) is something that `torch.compile` doesn’t natively support?\n\nThere were some efforts to do it a while back, but it was hard to do / not highest priority thing at the time, and was dropped. Feel free to comment on/ upvote the issue on double backward + compile.","needs_clarification":false,"thread_id":218952,"url":"https://discuss.pytorch.org/t/torch-compile-emits-double-backward-error-even-when-the-corresponding-function-is-disabled/218952","created_at":"2025-04-10T14:19:33.800000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["soulitzer"],"answered_by_ptrblck":false} {"question":"Uninstalling torch package\n\nHi,\nAny idea on why I can not remove the torch package via conda?\n\n```\n[mn@login02 llama2-70b]$ conda activate pt26-cuda126-py312-gcc13\n(pt26-cuda126-py312-gcc13) [mn@login02 llama2-70b]$ conda list | grep torch\ntorch 2.6.0+cu126 pypi_0 pypi\ntorchaudio 2.6.0+cu126 pypi_0 pypi\ntorchvision 0.21.0+cu126 pypi_0 pypi\n(pt26-cuda126-py312-gcc13) [mn@login02 llama2-70b]$ conda remove torch\nCollecting package metadata (repodata.json): done\nSolving environment: failed\n\nPackagesNotFoundError: The following packages are missing from the target environment:\n - torch\n\n```","reference_answer":"`pip uninstall torch -y` should work.","needs_clarification":false,"thread_id":218955,"url":"https://discuss.pytorch.org/t/uninstalling-torch-package/218955","created_at":"2025-04-10T19:34:40.532000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Not able to install PyTorch via pip\n\nHi\nThe following set of commands, according to the official page, to install PyTorch 2.6 in a virtual environment fail.\n```\n[m@login02 llama2-70b]$ python3 -m venv pt26-cu124\n[m@login02 llama2-70b]$ source ./pt26-cu124/bin/activate\n(pt26-cu124) [m@login02 llama2-70b]$ export CUDA_HOME=/scratch/m/cuda-toolkit/12.4.0\n(pt26-cu124) [m@login02 llama2-70b]$ export PATH=$CUDA_HOME/bin:$PATH\n(pt26-cu124) [m@login02 llama2-70b]$ export LD_LIBRARY_PATH=$CUDA_HOME/lib64:$LD_LIBRARY_PATH\n(pt26-cu124) [m@login02 llama2-70b]$ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124\nCollecting torch\n Could not find a version that satisfies the requirement torch (from versions: )\nNo matching distribution found for torch\n```\nAny way to fix that?","reference_answer":"Python 3.6 is not supported anymore as our current binaries require Python >= 3.9.\nFrom the install instructions:\n> **NOTE:** Latest PyTorch requires Python 3.9 or later.","needs_clarification":false,"thread_id":218970,"url":"https://discuss.pytorch.org/t/not-able-to-install-pytorch-via-pip/218970","created_at":"2025-04-11T11:54:04.410000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Model input shape doesnt match\n\nHello i am new to the topic of training a NN on my own so this might be a easy error, but i can't fix it.\n\nI have the following code\n```\nclass ClassConditionedUned(nn.Module):\n def __init__(self, num_ela=8, class_emb_size=4):\n super().__init__()\n self.class_emb = nn.Sequential(\n nn.Linear(num_ela, 32),\n nn.ReLU(),\n nn.Linear(32, class_emb_size)\n )\n self.model = UNet1DModel(\n sample_size=512,\n in_channels=1+class_emb_size,\n out_channels=1,\n layers_per_block=1, \n block_out_channels = (32, 32, 64), \n down_block_types = (\"DownBlock1DNoSkip\", \"DownBlock1D\", \"AttnDownBlock1D\"),\n up_block_types = (\"AttnUpBlock1D\", \"UpBlock1D\", \"UpBlock1DNoSkip\"), \n )\n \n def forward(self, x, t, ela_vec):\n bs, ch, h = x.shape\n class_cond = self.class_emb(ela_vec) # Map to embedding dimension\n class_cond = class_cond.view(bs, -1, 1).expand(-1, -1, h)\n net_input = torch.cat((x, class_cond), 1)\n print(net_input.shape)\n return self.model(net_input, t).sample\n\nmodel = ClassConditionedUned()\nx = torch.randn(1, 1, 512)\nt = torch.randint(0, 1000, (1,))\nela_vec = torch.rand(1, 8) # normalisierte ELA-Vektoren\n\nwith torch.no_grad():\n out = model(x, t, ela_vec)\n```\nand i get the error: \n\n out = model(x, t, ela_vec)\n ^^^^^^^^^^^^^^^^^^^^\nRuntimeError: Given groups=1, weight of size [32, 5, 1], expected input[1, 21, 512] to have 5 channels, but got 21 channels instead\n\nwhat am i doing wrong?\n\nThank you in advance!","reference_answer":"I fixed the error by changing in_channels \n```\nin_channels=1+class_emb_size+16,\n```\naccording to \n[https://github.com/huggingface/diffusers/issues/2967#issuecomment-1500800012](https://github.com/huggingface/diffusers/issues/2967#issuecomment-1500800012)\nthe timestep embedding gets concatenated on top of the 5 input channels.","needs_clarification":false,"thread_id":218986,"url":"https://discuss.pytorch.org/t/model-input-shape-doesnt-match/218986","created_at":"2025-04-12T10:05:57.752000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["lukasnol"],"answered_by_ptrblck":false} {"question":"Unexpected Extra GPU Memory Usage in PyTorch (Beyond CUDA Context and Memory Pool)\n\nHi all,\n\nRecently I’ve been trying to understand the details of GPU memory usage in PyTorch. I know that PyTorch maintains an internal memory pool, so it’s expected that the reserved GPU memory is larger than the actually allocated memory. However, I’ve observed that even when accounting for the memory pool, the GPU memory usage reported by `nvidia-smi` is still much higher than expected.\n\nHere’s what I did:\n\nI created a very small tensor in PyTorch (shape = 2×2, dtype = float32) and moved it to the GPU. I recorded the GPU memory usage using `nvidia-smi` and `torch.cuda.memory_summary()` before and after the operation. Surprisingly, `nvidia-smi` showed that this small tensor transfer resulted in over 800 MB of GPU memory usage. That seems excessive. Meanwhile, `torch.cuda.memory_summary()` indicated that PyTorch itself had not allocated any significant amount of memory.\n\nHere is my Pytorch code\n```python\nimport torch\nimport subprocess\n\ndef get_gpu_memory():\n result = subprocess.check_output(['nvidia-smi', '--query-gpu=memory.used',\n '--format=csv,nounits,noheader'])\n memory_per_gpu = [int(x) for x in result.decode('utf-8').strip().split('\\n')]\n return memory_per_gpu[0]\n\n# chean cache\ntorch.cuda.empty_cache()\nbefore_memory = get_gpu_memory()\nprint(torch.cuda.memory_summary(abbreviated=True))\nsubprocess.run([\"nvidia-smi\", \"-i=0\"], check=True)\n\n# do data transfer\nwith torch.no_grad():\n torch.randn(2, 2).cuda()\n\n# measure gpu memory usage\nafter_memory = get_gpu_memory()\nprint(f\"Memory increase after operations: {after_memory - before_memory} MB\")\n\n# clean cache and measure again\ntorch.cuda.empty_cache()\nafter_empty_cache = get_gpu_memory()\nprint(torch.cuda.memory_summary(abbreviated=True))\nsubprocess.run([\"nvidia-smi\", \"-i=0\"], check=True)\nprint(f\"Memory after empty_cache: {after_empty_cache} MB\")\nprint(f\"Persistent overhead: {after_empty_cache - before_memory} MB\")\n```\n\nAnd the output is\n[details=\"Python Pytorch output\"]\n```\n|===========================================================================|\n| PyTorch CUDA memory summary, device ID 0 |\n|---------------------------------------------------------------------------|\n| CUDA OOMs: 0 | cudaMalloc retries: 0 |\n|===========================================================================|\n| Metric | Cur Usage | Peak Usage | Tot Alloc | Tot Freed |\n|---------------------------------------------------------------------------|\n| Allocated memory | 0 B | 0 B | 0 B | 0 B |\n|---------------------------------------------------------------------------|\n| Active memory | 0 B | 0 B | 0 B | 0 B |\n|---------------------------------------------------------------------------|\n| Requested memory | 0 B | 0 B | 0 B | 0 B |\n|---------------------------------------------------------------------------|\n| GPU reserved memory | 0 B | 0 B | 0 B | 0 B |\n|---------------------------------------------------------------------------|\n| Non-releasable memory | 0 B | 0 B | 0 B | 0 B |\n|---------------------------------------------------------------------------|\n| Allocations | 0 | 0 | 0 | 0 |\n|---------------------------------------------------------------------------|\n| Active allocs | 0 | 0 | 0 | 0 |\n|---------------------------------------------------------------------------|\n| GPU reserved segments | 0 | 0 | 0 | 0 |\n|---------------------------------------------------------------------------|\n| Non-releasable allocs | 0 | 0 | 0 | 0 |\n|---------------------------------------------------------------------------|\n| Oversize allocations | 0 | 0 | 0 | 0 |\n|---------------------------------------------------------------------------|\n| Oversize GPU segments | 0 | 0 | 0 | 0 |\n|===========================================================================|\n\nMon Apr 14 10:59:55 2025 \n+-----------------------------------------------------------------------------+\n| NVIDIA-SMI 520.61.05 Driver Version: 520.61.05 CUDA Version: 11.8 |\n|-------------------------------+----------------------+----------------------+\n| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|===============================+======================+======================|\n| 0 NVIDIA GeForce ... Off | 00000000:1A:00.0 Off | N/A |\n| 30% 27C P8 28W / 350W | 2MiB / 24576MiB | 0% Default |\n| | | N/A |\n+-------------------------------+----------------------+----------------------+\n \n+-----------------------------------------------------------------------------+\n| Processes: |\n| GPU GI CI PID Type Process name GPU Memory |\n| ID ID Usage |\n|=============================================================================|\n| No running processes found |\n+-----------------------------------------------------------------------------+\nMemory increase after operations: 828 MB\n|===========================================================================|\n| PyTorch CUDA memory summary, device ID 0 |\n|---------------------------------------------------------------------------|\n| CUDA OOMs: 0 | cudaMalloc retries: 0 |\n|===========================================================================|\n| Metric | Cur Usage | Peak Usage | Tot Alloc | Tot Freed |\n|---------------------------------------------------------------------------|\n| Allocated memory | 0 B | 512 B | 512 B | 512 B |\n|---------------------------------------------------------------------------|\n| Active memory | 0 B | 512 B | 512 B | 512 B |\n|---------------------------------------------------------------------------|\n| Requested memory | 0 B | 16 B | 16 B | 16 B |\n|---------------------------------------------------------------------------|\n| GPU reserved memory | 0 B | 2048 KiB | 2048 KiB | 2048 KiB |\n|---------------------------------------------------------------------------|\n| Non-releasable memory | 0 B | 2047 KiB | 2047 KiB | 2047 KiB |\n|---------------------------------------------------------------------------|\n| Allocations | 0 | 1 | 1 | 1 |\n|---------------------------------------------------------------------------|\n| Active allocs | 0 | 1 | 1 | 1 |\n|---------------------------------------------------------------------------|\n| GPU reserved segments | 0 | 1 | 1 | 1 |\n|---------------------------------------------------------------------------|\n| Non-releasable allocs | 0 | 1 | 1 | 1 |\n|---------------------------------------------------------------------------|\n| Oversize allocations | 0 | 0 | 0 | 0 |\n|---------------------------------------------------------------------------|\n| Oversize GPU segments | 0 | 0 | 0 | 0 |\n|===========================================================================|\n\nMon Apr 14 10:59:57 2025 \n+-----------------------------------------------------------------------------+\n| NVIDIA-SMI 520.61.05 Driver Version: 520.61.05 CUDA Version: 11.8 |\n|-------------------------------+----------------------+----------------------+\n| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|===============================+======================+======================|\n| 0 NVIDIA GeForce ... Off | 00000000:1A:00.0 Off | N/A |\n| 30% 29C P2 101W / 350W | 826MiB / 24576MiB | 0% Default |\n| | | N/A |\n+-------------------------------+----------------------+----------------------+\n \n+-----------------------------------------------------------------------------+\n| Processes: |\n| GPU GI CI PID Type Process name GPU Memory |\n| ID ID Usage |\n|=============================================================================|\n| 0 N/A N/A 430253 C python 824MiB |\n+-----------------------------------------------------------------------------+\nMemory after empty_cache: 826 MB\nPersistent overhead: 826 MB\n```\n[/details]\n\nI suspected that part of the memory usage might come from CUDA context initialization. To test this, I wrote a minimal C++ program using the CUDA Driver API to perform the same task. The C++ version consumed around 255 MB of GPU memory, which I assume corresponds to the CUDA context overhead.\n\nHere is my CUDA C++ code\n\n```cpp\n#include \n#include \n#include \n#include \n#include \n#include \n\n// print GPU 0 memory usage\nclass GPUMemoryMonitor {\npublic:\n GPUMemoryMonitor() {\n cudaGetDeviceCount(&deviceCount);\n }\n\n void printAllGPUMemoryUsage(const std::string& label = \"\") {\n if (!label.empty()) {\n std::cout << \"===== \" << label << \" =====\" << std::endl;\n }\n\n for (int i = 0; i < 1; i++) {\n printGPUMemoryUsage(i);\n }\n\n if (!label.empty()) {\n std::cout << std::string(label.length() + 12, '=') << std::endl;\n }\n }\n\n void printGPUMemoryUsage(int deviceId) {\n size_t free, total;\n cudaSetDevice(deviceId);\n cudaMemGetInfo(&free, &total);\n\n double usedMB = (total - free) / 1024.0 / 1024.0;\n double totalMB = total / 1024.0 / 1024.0;\n double percentUsed = 100.0 * (total - free) / total;\n\n std::cout << \"GPU \" << deviceId << \": \"\n << std::fixed << std::setprecision(2) << usedMB << \" MB / \"\n << totalMB << \" MB (\"\n << percentUsed << \"%) used\" << std::endl;\n }\n\nprivate:\n int deviceCount;\n};\n\nint main() {\n GPUMemoryMonitor memMonitor;\n memMonitor.printAllGPUMemoryUsage(\"Initial GPU Memory State\");\n\n cudaError_t cudaStatus;\n int deviceId = 0;\n\n int deviceCount;\n cudaStatus = cudaGetDeviceCount(&deviceCount);\n if (cudaStatus != cudaSuccess || deviceCount == 0) {\n std::cerr << \"No CUDA devices found: \" << cudaGetErrorString(cudaStatus) << std::endl;\n return 1;\n }\n\n cudaSetDevice(deviceId);\n\n cudaStream_t stream;\n cudaStatus = cudaStreamCreate(&stream);\n if (cudaStatus != cudaSuccess) {\n std::cerr << \"cudaStreamCreate failed: \" << cudaGetErrorString(cudaStatus) << std::endl;\n return 1;\n }\n\n memMonitor.printAllGPUMemoryUsage(\"After Stream Creation\");\n\n const size_t numElements = 2 * 2;\n const size_t sizeInBytes = numElements * sizeof(float);\n\n std::vector h_data(numElements);\n\n float* d_data = nullptr;\n cudaStatus = cudaMalloc((void**)&d_data, sizeInBytes);\n if (cudaStatus != cudaSuccess) {\n std::cerr << \"cudaMalloc failed: \" << cudaGetErrorString(cudaStatus) << std::endl;\n cudaStreamDestroy(stream);\n return 1;\n }\n\n memMonitor.printAllGPUMemoryUsage(\"After Device Memory Allocation\");\n\n cudaStatus = cudaMemcpyAsync(d_data, h_data.data(), sizeInBytes, cudaMemcpyHostToDevice, stream);\n if (cudaStatus != cudaSuccess) {\n std::cerr << \"cudaMemcpyAsync failed: \" << cudaGetErrorString(cudaStatus) << std::endl;\n cudaFree(d_data);\n cudaStreamDestroy(stream);\n return 1;\n }\n\n memMonitor.printAllGPUMemoryUsage(\"After cudaMemcpyAsync\");\n\n cudaStatus = cudaStreamSynchronize(stream);\n if (cudaStatus != cudaSuccess) {\n std::cerr << \"cudaStreamSynchronize failed: \" << cudaGetErrorString(cudaStatus) << std::endl;\n cudaFree(d_data);\n cudaStreamDestroy(stream);\n return 1;\n }\n\n memMonitor.printAllGPUMemoryUsage(\"After Stream Synchronization\");\n\n cudaFree(d_data);\n memMonitor.printAllGPUMemoryUsage(\"After cudaFree\");\n\n cudaStreamDestroy(stream);\n memMonitor.printAllGPUMemoryUsage(\"After Stream Destroy\");\n\n return 0;\n}\n```\n\nAnd the output is\n\n[details=\"C++ CUDA output\"]\n```\n===== Initial GPU Memory State =====\nGPU 0: 254.75 MB / 24268.31 MB (1.05%) used\n====================================\n===== After Stream Creation =====\nGPU 0: 254.75 MB / 24268.31 MB (1.05%) used\n=================================\n===== After Device Memory Allocation =====\nGPU 0: 258.75 MB / 24268.31 MB (1.07%) used\n==========================================\n===== After cudaMemcpyAsync =====\nGPU 0: 258.75 MB / 24268.31 MB (1.07%) used\n=================================\n===== After Stream Synchronization =====\nGPU 0: 258.75 MB / 24268.31 MB (1.07%) used\n========================================\n===== After cudaFree =====\nGPU 0: 254.75 MB / 24268.31 MB (1.05%) used\n==========================\n===== After Stream Destroy =====\nGPU 0: 254.75 MB / 24268.31 MB (1.05%) used\n================================\n```\n[/details]\n\nSo, after subtracting the CUDA context overhead (~255 MB, according to the C++ program), PyTorch still seems to be using about 600 MB of additional GPU memory that I cannot account for.\n\nHere are my questions:\n\n- Is this additional GPU memory usage by PyTorch expected or normal?\n- Is there any way to trace or profile the source of GPU memory allocations? I tried using the NVIDIA Nsight suite but couldn’t get detailed memory allocation information.\n- Is there any documentation or explanation for this extra ~600 MB of memory usage? I haven’t been able to find anything.\n\nAny help or insights would be greatly appreciated. Thank you in advance!","reference_answer":"The roughly 260 MB shown by nvidia-smi after creating a small CUDA tensor is expected. It covers the CUDA context, the lazily loaded CUDA kernels and PyTorch's allocations. PyTorch binaries built with CUDA 11.7+ use lazy module loading, which loads only the kernels that are needed.\n\nThe extra ~600 MB on the original setup (PyTorch 2.1.0+cu118, driver 520.61.05) could not be reproduced, and it persisted with PyTorch 2.6.0. Upgrading to a newer NVIDIA driver (550.90.07) brought usage down to about 260 MB.","needs_clarification":false,"thread_id":219042,"url":"https://discuss.pytorch.org/t/unexpected-extra-gpu-memory-usage-in-pytorch-beyond-cuda-context-and-memory-pool/219042","created_at":"2025-04-14T03:13:22.149000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,5],"answer_authors":["MrAru","ptrblck"],"answered_by_ptrblck":true} {"question":"OOM problem when using Multiple GPU with CUDA_VISIBLE_DEVICES\n\nI have a Weriod OOM problem when I use 2 gpu like CUDA_VISIBLE_DEVICES=4,5.\n\nBut, 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. \n\nDoes this mean that I can use 2 gpu like CUDA_VISIBLE_DEVICES=4,5 to work well ?\n\nBy the way, I also don't understand why the memory allocated is not in an average for each gpu in the picture. Maybe it is the machanism of pytorch?\n\nThanks for your help in advance! \n\n[image]","reference_answer":"Set `device_map` to `auto` instead of `gpu` when loading the models.","needs_clarification":false,"thread_id":219067,"url":"https://discuss.pytorch.org/t/oom-problem-when-using-multiple-gpu-with-cuda-visible-devices/219067","created_at":"2025-04-14T14:57:13.935000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4],"answer_authors":["andy_sherlock"],"answered_by_ptrblck":false} {"question":"Does we save a random parameters if no train for model\n\nI try to create a simple **Mlp model** without train, and then use **torch.save** to 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?\n\nPS: I also try to open the saved data **mlp-simple1.pth** by vim, but it only shows a bunch of garbled characters.\n\n```\nz00443407@llvm:~/source/test/simple_mlp$ cat save_model1.py \nimport torch\nfrom torch import nn\nimport torch_mlir\n\nname : str\nclass MlpModel(torch.nn.Module):\n def __init__(self):\n super(MlpModel, self).__init__()\n self.net = nn.Sequential(nn.Flatten(),\n nn.Linear(784, 256),\n nn.ReLU(),\n nn.Linear(256, 10))\n\n def forward(self, x):\n return self.net(x)\n\n# 保存模型\nmodel = MlpModel()\ndef save_model():\n path = \"./mlp-simple1.pth\"\n for param_tensor in model.state_dict():\n print(param_tensor,'\\t',model.state_dict()[param_tensor].size())\n # print(param_tensor,'\\t',model.state_dict()[param_tensor]) # Random value\n torch.save(model.state_dict(), path)\n\nsave_model()\n```","reference_answer":"Yes, saving the `state_dict` directly after initializing the model will save it's initial random values, which were not trained yet.","needs_clarification":false,"thread_id":219241,"url":"https://discuss.pytorch.org/t/does-we-save-a-random-parameters-if-no-train-for-model/219241","created_at":"2025-04-19T04:02:39.034000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Autograd independently on entries of a single tensor\n\nHello,\n\nI am trying to do a computation which follows the following pattern:\n```python\noutput = torch.zeros((len,), device=...)\nfor i in range(len):\n output[i] = do_computation_on(output[:i])\n```\nTo maintain compatibility with autograd (i.e., avoiding the `one of the variables needed for gradient computation has been modified by an inplace operation` message), it is necessary to use `output[:i].clone()`.\n\nIn the interest of optimizing memory usage, I would like to avoid this call to `clone()` as it is clearly conceivable to implement the above pattern without any cloning: just maintain a list of singleton tensors and do the computation that way instead of using a single tensor to maintain the whole list, but this clearly sacrifices memory contiguity (cache-friendliness) and slicing properties I'd like to keep.\n\nIs there any way to maintain a list of independent variables (in the eyes of autograd) which are still contiguous in GPU memory? And if so, are there any drawbacks to such an approach?\n\nAny help is greatly appreciated.\n\nP.S.: I tried to do the above using `.chunk()` (as it returns a tuple of sub-tensors), and it seems PyTorch was one step ahead of me as this does not work either:\n`RuntimeError: A view was created in no_grad mode and is being modified inplace with grad mode enabled. This view is the output of a function that returns multiple views. Such functions do not allow the output views to be modified inplace. You should replace the inplace operation by an out-of-place one.`","reference_answer":"Hi Danimator!\n\nI don't believe that there is any way to do what your want.\n\nAt a higher level, bear in mind that a `Tensor` not only contains values, but also other\nstuff. In your particular case, you need the connections to the computation graph that\nautograd builds and uses.\n\nI believe (but am not sure) that you could build a list of singleton tensors whose contained\nvalues were contiguous in memory (by manipulating the tensors' storage appropriately), but\nI don't see how you could control the placement of the tensors' other data, so you would lose\nthe full version of cache-friendliness that you probably want. Furthermore, pytorch wouldn't\nknow that the data values were contiguous in memory, so I don't see how you could keep\nany built-in slicing functionality.\n\n(Also, just to be clear, autograd acts on whole tensors, not on elements of tensors. So to\nperform the computation you describe in a way compatible with autograd would seem to\nrequire singleton tensors -- even if they were assembled into larger aggregate tensors later.)\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":219258,"url":"https://discuss.pytorch.org/t/autograd-independently-on-entries-of-a-single-tensor/219258","created_at":"2025-04-20T01:24:04.665000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Qint8 Activations in PyTorch\n\nHelp please!\nI am currently working on a project where I need to deploy a PyTorch-based neural network model onto an FPGA for inference. My goal is to quantize the model so that both the activations and weights are within the range of -128 to 127 (8-bit precision)\n\nSo far, I have experimented with both `fbgemm` and `qnnpack` for quantization:\n\n1. **Activation Quantization**: I encountered an issue where I was unable to convert the activations to integer values in the range of -128 to 127. When I doing the inference on my computer, it say the `conv` layers do not support `qint8` as input.\n2. **QNNPACK Compatibility**: I also tried using QNNPACK for inference, but faced a limitation where QNNPACK does not support the `conv3d_unpack` operation.\n\nDoes PyTorch itself offer any features that could support the qint8 activations?\nOr would I need to explore other frameworks or toolchains?","reference_answer":"1. yeah activation only supports quint8\n2. I see, it's possible that qnnpack does not support conv3d, but we are moving away from it\n\nhere is our new stack: https://pytorch.org/docs/main/quantization.html#prototype-pytorch-2-export-quantization please take a look at the tutorials attached in the end, this allows for extensions to any backends. available in 2.4 and later I think, we are also moving this to torchao: https://github.com/pytorch/ao our single repository for pytorch native quantization and sparsity","needs_clarification":false,"thread_id":219267,"url":"https://discuss.pytorch.org/t/qint8-activations-in-pytorch/219267","created_at":"2025-04-20T13:21:52.095000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["jerryzh168"],"answered_by_ptrblck":false} {"question":"Increase computational cost while repeating use the trained CNN models\n\nHi,I have some problems of the neural nework models. \nThere is a trained CNN models and i need to repeated use this model. Here is the code.\n self.CNN.eval()\n with torch.no_grad():\n for i in range(self.TestSteps):\n aa = time.time()\n initial = self.CNN(initial)\n bb = time.time()\n print(bb - aa)\nThe computational cost for each loop is 0.002s but after a few loops, the computational cost increase to 0.3s. \n0.0029914379119873047\n0.0009975433349609375\n0.0019941329956054688\n0.0025336742401123047\n0.0010161399841308594\n0.001994609832763672\n0.0009975433349609375\n0.003017902374267578\n0.001968860626220703\n0.0015769004821777344\n0.001043081283569336\n0.002002239227294922\n0.17526578903198242\n0.3638777732849121\n0.35142970085144043\n0.3363661766052246\n0.3505854606628418\n0.3499774932861328\n0.41155457496643066\n0.35362887382507324\n0.3807251453399658\nCould anyone can help me to figure out this problem, I really appreciate your help.","reference_answer":"Yes, since your initial profiling is wrong and is not measuring the GPU kernel execution time.\n\nThe 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 kernel(s) as well as implicit synchronizations. \nAs mentioned before: CUDA kernels are executed asynchronously so you would need to synchronize host timers before starting and stopping them or you could use CUDA events to measure the execution time on the device. \n\nIf you want to measure the GPU kernel execution time with host timers you need to synchronize the code. Otherwise your profiling is wrong and misleading.","needs_clarification":false,"thread_id":219353,"url":"https://discuss.pytorch.org/t/increase-computational-cost-while-repeating-use-the-trained-cnn-models/219353","created_at":"2025-04-22T19:54:52.554000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[6],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Multiple forwards and comp graph building\n\nHello everyone,\nI 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?\n\nThanks!","reference_answer":"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 activations which need to be stored.\n\nHere is a simple example using a `ResNet50`:\n```python\nimport torch\nimport torchvision.models as models \n\nprint(torch.cuda.memory_allocated() / 1024**2)\n# 0.0\n\ndevice = \"cuda\"\nmodel = models.resnet50().to(device)\nx = torch.randn(1, 3, 224, 224, device=device)\n\nprint(torch.cuda.memory_allocated() / 1024**2)\n#98.30224609375\n\nout1 = model(x)\nprint(torch.cuda.memory_allocated() / 1024**2)\n# 189.58642578125\n\nout2 = model(x)\nprint(torch.cuda.memory_allocated() / 1024**2)\n# 271.33935546875\n```\n\nCalling `backward` will free the intermediate forward activations, but the first `backward` call will also create the `grad` attributes which will use memory.","needs_clarification":false,"thread_id":219364,"url":"https://discuss.pytorch.org/t/multiple-forwards-and-comp-graph-building/219364","created_at":"2025-04-23T07:53:57.039000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"How to perform distributed communication (NCCL) using LibTorch?\n\nFor example, in the Python API, there are interfaces like torch.distributed.allreduce, but I couldn’t find similar interfaces in the LibTorch C++ API.\n\nThank you for all the responses.","reference_answer":"In cpp, there are APIs inside ProcessGroupNCCL which directly calls into nccl API, is this something you are looking for?","needs_clarification":false,"thread_id":219558,"url":"https://discuss.pytorch.org/t/how-to-perform-distributed-communication-nccl-using-libtorch/219558","created_at":"2025-04-28T16:18:26.591000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["fduwjj"],"answered_by_ptrblck":false} {"question":"Training FasterCNN: target boxes have wrong dimensions\n\nI'm trying to train a model which should predict a bounding box around a hand. When I try to run the code I get the error message: `Expected target boxes to be a tensor of shape [N, 4], got torch.Size([8, 1, 4]).` This issue has already been discussed [here](https://discuss.pytorch.org/t/in-training-loop-typeerror-string-indices-must-be-integers-not-str/197269) but I did not follow whether or not he actually opened a new issue as stated.\n\n```python\ndef resize_image_and_bbox(img, bboxes, new_height, new_width):\n original_width, original_height = img.size\n \n height_factor = original_height / new_height\n width_factor = original_width / new_width\n\n transform = transforms.Compose([\n transforms.Resize((new_height, new_width)),\n transforms.ToTensor()\n ]) \n img_as_tensor = transform(img)\n\n # Scale x coordinates\n bboxes[:, [0, 2]] = bboxes[:, [0, 2]] / width_factor\n # Scale y coordinates\n bboxes[:, [1, 3]] = bboxes[:, [1, 3]] / height_factor\n\n return img_as_tensor, bboxes\n\nclass CustomDataset(Dataset):\n def __init__(self, root_dir):\n self.root_dir = root_dir\n self.class_lbl = \"hand\"\n self.label_paths = []\n self.label_paths += glob.glob(os.path.join(root_dir, \"labels\", \"VOC\", \"*.xml\"))\n\n def __len__(self):\n return len(self.label_paths)\n\n def __getitem__(self, index):\n tree = ET.parse(self.label_paths[index])\n root = tree.getroot()\n img_path = os.path.join(self.root_dir,\"images\", root.find(\"path\").text.split(\"\\\\\")[-1])\n img = PIL.Image.open(img_path)\n # img = decode_image(img_path, ImageReadMode.RGB).numpy(force=True)\n xmin = float(root.find(\"object/bndbox/xmin\").text)\n ymin = float(root.find(\"object/bndbox/ymin\").text)\n xmax = float(root.find(\"object/bndbox/xmax\").text)\n ymax = float(root.find(\"object/bndbox/ymax\").text)\n\n labels = torch.tensor([1])\n bboxes = torch.tensor([[xmin, ymin, xmax, ymax]], dtype=torch.float32)\n\n img_as_tensor, bboxes = resize_image_and_bbox(img, bboxes, IMAGE_HEIGHT, IMAGE_WIDTH)\n\n print(bboxes)\n\n target = {}\n target[\"boxes\"] = bboxes\n target[\"labels\"] = labels\n\n return img_as_tensor, target\n\n# Set up the optimizer\nparams = [p for p in model.parameters() if p.requires_grad]\noptimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005)\n# Learning rate scheduler\nlr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1)\n# Train the model\nfor epoch in range(EPOCHS):\n model.train()\n train_loss = 0.0\n\n # Training loop\n for images, targets in dataloaders[\"train\"]:\n images = list(image.to(device) for image in images)\n targets = {k: v.to(device) for k, v in targets.items()}\n\n # Zero the gradients\n optimizer.zero_grad()\n\n # Forward pass\n loss_dict = model(images, [targets])\n losses = sum(loss for loss in loss_dict.values())\n\n # Backward pass\n losses.backward()\n optimizer.step()\n train_loss += losses.item()\n\n # Update the learning rate\n lr_scheduler.step()\n print(f'Epoch: {epoch + 1}, Loss: {train_loss / len(dataloaders[\"train\"])}')\nprint(\"Training complete!\")\n```","reference_answer":"I actually managed to solve this by writing a custom collate function\n\n```python\ndef custom_collate_fn(batch):\n # Separate images and targets from the batch\n images, targets = zip(*batch)\n \n # Stack the images into a tensor (shape: [batch_size, C, H, W])\n images = torch.stack(images, dim=0)\n \n # Now, we need to maintain the structure: List of dictionaries with \"boxes\" and \"labels\"\n batched_targets = []\n \n for target in targets:\n target_dict = {}\n target_dict[\"boxes\"] = target[\"boxes\"]\n target_dict[\"labels\"] = target[\"labels\"]\n batched_targets.append(target_dict)\n \n return images, batched_targets\n```","needs_clarification":false,"thread_id":219565,"url":"https://discuss.pytorch.org/t/training-fastercnn-target-boxes-have-wrong-dimensions/219565","created_at":"2025-04-28T18:41:24.040000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["lavaLamp"],"answered_by_ptrblck":false} {"question":"MPS Deployment Target Mismatch\n\nHi all. I am are building PyTorch from source with MPS support and am having a problem with the Deployment Target\nSome context:\nIm using LibTorch to run inference in C++.\nMy minimum deployment target is currently 11.\n\nMy build works correctly on all systems 11 and up as expected for CPU usage, and I also have no problem checking for MPS availability on any system as well.\nThe problem Im having right now is that inference with MPS only seems to work correctly on the same Mac OSX that PyTorch was built on. Eg, I am building on 15.1 and it works correctly on my own system, but If I attempt to use this build on MacOS 14 it will not work.\nBelow is the error I see when trying this:\n```\nRuntimeError: Failed to created pipeline state object, error: Error Domain=AGXMetalG14X Code=3 \"Function kernel_index_offsets_32 has a deployment target (0x00020007) which is incompatible with this OS (0x00020006).\" UserInfo={NSLocalizedDescription=Function kernel_index_offsets_32 has a deployment target (0x00020007) which is incompatible with this OS (0x00020006).}\n```\n\nMy question is, is it possible to build PyTorch with MPS so that it can be deployed on a MacOS different from the one built on and if so, how can this be done?\nIm already setting CMAKE arguments related to the deployment target, but maybe Im missing something critical.\n```\nCMAKE_OSX_DEPLOYMENT_TARGET\n\n```\n\nAny help appreciated, thanks all.","reference_answer":"For anyone who finds this issue in the future, it looks like Ive managed to solve the problem. After digging around for a while I managed to figure out how these problem kernels are being built.\nIn Metal.cmake:\n```\nfunction(metal_to_air SRC TARGET FLAGS)\n add_custom_command(COMMAND xcrun metal -c -mmacosx-version-min=12.3 ${SRC} -o ${TARGET} ${FLAGS} ${METAL_CFLAGS}\n DEPENDS ${SRC}\n OUTPUT ${TARGET}\n COMMENT \"Compiling ${SRC} to ${TARGET}\"\n VERBATIM)\nendfunction()\n```\nI've added `-mmacosx-version-min=12.3`. Without this the deployment target is the OS you are building on (or SDK being built with?)\nThis suits my needs, but I think it should be the case that when building PyTorch the normal CMAKE arguments for minimum deployment target should make their way here somehow. I might make a fork later of some actual fix, but for now this will do the trick for me.","needs_clarification":false,"thread_id":219575,"url":"https://discuss.pytorch.org/t/mps-deployment-target-mismatch/219575","created_at":"2025-04-29T03:02:48.386000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Olek"],"answered_by_ptrblck":false} {"question":"Get loss, gradient and hessian in one go\n\nCurrently I do this:\n\n```\nfrom collections.abc import Sequence\nimport torch\n\ndef jacobian(input: Sequence[torch.Tensor], wrt: Sequence[torch.Tensor], create_graph=False):\n flat_input = torch.cat([i.reshape(-1) for i in input])\n return torch.autograd.grad(\n flat_input,\n wrt,\n torch.eye(len(flat_input), device=input[0].device, dtype=input[0].dtype),\n retain_graph=True,\n create_graph=create_graph,\n allow_unused=True,\n is_grads_batched=True,\n )\n\ninput = torch.randn(3, requires_grad=True)\nloss = (input**2).mean()\ngrad = torch.autograd.grad(loss, input, create_graph=True)\nhessian = jacobian(grad, [input])\n```\n\nHowever as I understand the most efficient way of computing hessian is https://pytorch.org/docs/stable/generated/torch.func.hessian.html\n\nBut my trouble is that when I use it, I do this:\n```\ndef fn(x): return x.pow(2).mean()\nloss = fn(input)\ngrad = torch.autograd.grad(loss, input)\nhessian = torch.func.hessian(fn)(input)\n```\n\nDoesn't hessian then need to re-evaluate the function value and the gradients again even though I have already computed them? My function might be quite expensive. What would be the best solution to calculating hessian?","reference_answer":"Hi Ivan!\n\nI believe that you are correct about this. I am not aware of any pre-packaged pytorch\n`hessian` functionality that also gives you access to the `loss` and `grad` it would have\ncomputed under the hood.\n\nSo I do believe that `func.hessian()` does require duplicative computation in your use\ncase.\n\nOn the other hand, if your `grad` consists of `n` components, computing the hessian\n(e.g., with `func.hessian()`) requires `n` autograd passes (in addition to the first autograd\npass used to compute `grad`). So the duplicative computation may well be relatively\ninsignificant.\n\nIt is also conceivable that `func.hessian()` contains some minor internal efficiencies\nthat are sufficient to overcome the cost of the unnecessary computation.\n\nNote that if your function is expensive, it is also likely the first-derivative backward pass\nfor `grad` and the second-derivative backward passes for `hessian` will be expensive.\nSo, again, the cost of the `n` second-derivative backward passes may dominate the\noverall cost, with cost of the redundant computation of `loss` and `grad` being relatively\nminor.\n\nIf the cost of `hessian` is important to your use case, it would probably make sense to\ntime both approaches.\n\nBest.\n\nK. Frank.","needs_clarification":false,"thread_id":219601,"url":"https://discuss.pytorch.org/t/get-loss-gradient-and-hessian-in-one-go/219601","created_at":"2025-04-29T16:53:14.779000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"What’s the Best Way to Debug FSDP When Hitting a C++ Backend Error?\n\nHello,\n\nI’m currently working on adding MPI backend support for both FSDP1 and FSDP2 as part of an effort to contribute to PyTorch’s distributed training stack. During testing, I encountered an error in FSDP2 during the backward pass. I would appreciate any advice on how to investigate this issue further — especially regarding debugging techniques for distributed code involving C++ internals.\n\n## Environment and Reproduction\n\nHere is the code I used:\n\n
\n code \n\n```python\nimport os\nimport time\nimport argparse\nimport dataclasses\n\nimport torch\nfrom torch import nn\nimport torch.distributed as dist\nfrom torch.distributed.fsdp import fully_shard\nimport torch.optim as optim\n\nclass SimpleModel(nn.Module):\n def __init__(self):\n super(SimpleModel, self).__init__()\n self.sequential0 = nn.Linear(512, 1024)\n self.sequential1 = nn.Linear(1024, 1024)\n self.sequential2 = nn.Linear(1024, 512)\n self.last = nn.Linear(512, 10)\n\n def forward(self, x):\n x = torch.relu(self.sequential0(x))\n x = torch.relu(self.sequential1(x))\n x = torch.relu(self.sequential2(x))\n return self.last(x)\n\ndef fsdp_training(local_rank: int):\n rank = dist.get_rank()\n world_size = dist.get_world_size()\n device = torch.device('cuda', local_rank)\n\n model = SimpleModel().to(device)\n fully_shard(model)\n\n if rank == 0:\n print(model)\n\n optimizer = optim.AdamW(model.parameters(), lr=0.01)\n input_data = torch.randn(2, 512).to(device)\n target = torch.randint(0, 10, (2,)).to(device)\n\n print(f\"Rank {rank}/{world_size}: Start training\")\n model.train()\n num_epochs = 10\n for epoch in range(num_epochs):\n optimizer.zero_grad()\n output = model(input_data)\n loss = nn.CrossEntropyLoss()(output, target)\n loss.backward()\n optimizer.step()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='FSDP Training')\n parser.add_argument(\n '--backend', type=str, choices=['mpi', 'nccl', 'ucc', 'gloo'], default='mpi',\n help='Backend to use for training'\n )\n args = parser.parse_args()\n\n local_rank = int(os.getenv(\"LOCAL_RANK\", 0))\n if args.backend == 'mpi':\n local_rank = int(os.getenv(\"OMPI_COMM_WORLD_RANK\", 0))\n torch.cuda.set_device(local_rank)\n\n print(\"local_rank\", local_rank, \"backend\", args.backend)\n if args.backend == 'mpi':\n dist.init_process_group(backend=\"mpi\")\n else: # nccl, ucc, gloo\n dist.init_process_group(backend=args.backend, init_method=\"env://\")\n\n fsdp_training(local_rank)\n \n dist.destroy_process_group()\n```\n\n
\n\nHere's the launcher command I ran.\n`OMP_NUM_THREADS=1 mpirun -n 2 -- python3 test_fsdp2_mpi.py --backend mpi`\n\nThen, I encounter the following error on both rank 0 and 1:\n\n```python\n[rank0]: Traceback (most recent call last):\n[rank0]: File \"/app/pytorch_tests/src/training/test_fsdp2_mpi.py\", line 81, in \n[rank0]: fsdp_training(local_rank)\n[rank0]: File \"/app/pytorch_tests/src/training/test_fsdp2_mpi.py\", line 52, in fsdp_training\n[rank0]: loss.backward()\n[rank0]: File \"/app/pytorch/torch/_tensor.py\", line 648, in backward\n[rank0]: torch.autograd.backward(\n[rank0]: File \"/app/pytorch/torch/autograd/__init__.py\", line 354, in backward\n[rank0]: _engine_run_backward(\n[rank0]: File \"/app/pytorch/torch/autograd/graph.py\", line 824, in _engine_run_backward\n[rank0]: return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass\n[rank0]: File \"/app/pytorch/torch/distributed/fsdp/_fully_shard/_fsdp_state.py\", line 297, in _root_post_backward_final_callback\n[rank0]: fsdp_param_group.post_backward()\n[rank0]: File \"/app/pytorch/torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py\", line 445, in post_backward\n[rank0]: ) = foreach_reduce(\n[rank0]: File \"/app/pytorch/torch/utils/_contextlib.py\", line 116, in decorate_context\n[rank0]: return func(*args, **kwargs)\n[rank0]: File \"/app/pytorch/torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py\", line 421, in foreach_reduce\n[rank0]: dist.reduce_scatter_tensor(\n[rank0]: File \"/app/pytorch/torch/distributed/c10d_logger.py\", line 81, in wrapper\n[rank0]: return func(*args, **kwargs)\n[rank0]: File \"/app/pytorch/torch/distributed/distributed_c10d.py\", line 4416, in reduce_scatter_tensor\n[rank0]: work.wait()\n[rank0]: IndexError: map::at\n```\n\n- OS: Ubuntu22.04\n- Pytorch: v2.8.0a0+git6120cc8\n- MPI: Open MPI v5.0.7rc2\n\n## My question: How to Debug This Effectively?\n\n**How do PyTorch developers or contributors typically debug such errors from internal C++ script?**\n\nI’m trying to investigate this issue, but since FSDP is triggered from Python and the error happens in the C++ backend, it’s difficult to debug. Debugging with gdb is usually straightforward in pure C++, but at least in my case, I’m having trouble using it effectively in this hybrid case.\n\nAny insight or guidance would be greatly appreciated!\n\nThanks.","reference_answer":"I was able to identify the cause of the IndexError using gdb, so I’m sharing the steps here for reference.\n\n---\n\n### 1. Run the script directly without mpirun\n\n```\nOMP_NUM_THREADS=1 python3 test_fsdp2_mpi.py --backend mpi\n```\n\nThis produced the same `IndexError: map::at` as when using mpirun.\n\n### 2. Launch the script under gdb\n\n```\nOMP_NUM_THREADS=1 gdb --args python3 test_fsdp2_mpi.py --backend mpi\n```\n\nGdb launched correctly, however, the IndexError thrown from the C++ was not caught immediately. It likely did not propagate back to the Python main thread in a way that gdb could catch by default, and it may have been masked or wrapped by the Python runtime or pybind11 interface.\n\n### 3. Set a catchpoint for all C++ exceptions\n\n```\n(gdb) catch throw\nCatchpoint 1 (throw)\n```\n\nThis instructs gdb to break whenever any C++ exception is thrown, regardless of whether it is propagated to Python.\n\nAs a result, the catchpoint triggered when the exception was thrown:\n\n```\nThread 4 \"python3\" hit Catchpoint 1 (exception thrown), 0x00007f308cd914a1 in __cxa_throw()\nfrom /lib/x86_64-linux-gnu/libstdc++.so.6\n```\n\nThen, running bt (backtrace) gave the following:\n\n```\n(gdb) bt\n#0 __cxa_throw\n#1 std::__throw_out_of_range\n#2 std::map::at (c10d::ReduceOp::AVG)\n#3 c10d::ProcessGroupMPI::_reduce_scatter_base(...)\n#4 c10d::ProcessGroupMPI::runLoop()\n...\n```\n\n---\n\nNote: I also tried using `import faulthandler; faulthandler.disable()` and `import signal; signal.signal(signal.SIGSEGV, signal.SIG_DFL)`, but it had no effect on catching the exception.","needs_clarification":false,"thread_id":219646,"url":"https://discuss.pytorch.org/t/what-s-the-best-way-to-debug-fsdp-when-hitting-a-c-backend-error/219646","created_at":"2025-05-01T00:51:08.158000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["nariaki3551"],"answered_by_ptrblck":false} {"question":"[report a bug] I allocated some GPU memory using Torch, and I want to copy data from the CPU to the GPU, but it hasn’t been successful\n\nHere is a simplified program that doesn’t work properly and throws the following error:\n\n```\n\n#include \n#include \n#include \n#include // For CUDAStreamGuard and getStreamFromPool\n#include // For CUDASetDevice, device_count, is_available\n#include // For CUDAGuard\n#include // for std::getenv, std::stoi\n#include \n#include \n#include \n#include // For std::runtime_error, std::exception\n#include // For c10::make_intrusive\n#include // For timeout duration and sleep_for\n#include // For std::this_thread::sleep_for\n#include // For std::remove\n\nint main(int argc, char* argv[]) {\n // Define the size of memory to allocate (e.g., 1KB)\n size_t size_bytes = 1024; // 1 KB\n\n // 1. Prepare data on the CPU\n std::vector cpu_data(size_bytes);\n for (size_t i = 0; i < size_bytes; ++i) {\n cpu_data[i] = static_cast(i % 128);\n }\n char* cpu_ptr = cpu_data.data();\n std::cout << \"CPU data prepared, size: \" << size_bytes << \" bytes.\" << std::endl;\n\n // Check if CUDA is available\n if (!torch::cuda::is_available()) {\n std::cerr << \"Error: CUDA is not available. This test requires CUDA.\" << std::endl;\n return 1; // Exit if CUDA is not available\n } else {\n int device_count = torch::cuda::device_count();\n std::cout << \"CUDA is available. Found \" << device_count << \" GPU device(s).\" << std::endl;\n if (device_count == 0) {\n std::cerr << \"Error: CUDA is available but no GPU devices were found.\" << std::endl;\n return 1;\n }\n }\n\n void* gpu_ptr = nullptr;\n try {\n // (Optional) Set the CUDA device to operate on, default is 0\n c10::cuda::set_device(0);\n c10::DeviceGuard device_guard(c10::Device(c10::kCUDA, 0)); // Ensure subsequent operations are on the specified device\n\n // 2. Allocate GPU memory using CUDACachingAllocator\n std::cout << \"Attempting to allocate \" << size_bytes << \" bytes of GPU memory...\" << std::endl;\n gpu_ptr = c10::cuda::CUDACachingAllocator::raw_alloc(size_bytes);\n std::cout << \"Attempting to copy CPU data to GPU...\" << std::endl;\n cudaError_t cuda_err = cudaMemcpy(gpu_ptr, cpu_ptr, size_bytes, cudaMemcpyHostToDevice);\n if (cuda_err != cudaSuccess) {\n std::cerr << \"Error: cudaMemcpy HostToDevice failed: \" << cudaGetErrorString(cuda_err) << std::endl;\n // Free allocated GPU memory on error\n c10::cuda::CUDACachingAllocator::raw_delete(gpu_ptr);\n return 1;\n }\n std::cout << \"Data successfully copied from CPU to GPU.\" << std::endl;\n\n // (Optional) Add code here to use the GPU memory pointed to by gpu_ptr...\n\n // 4. Free GPU memory\n std::cout << \"Freeing GPU memory...\" << std::endl;\n c10::cuda::CUDACachingAllocator::raw_delete(gpu_ptr);\n gpu_ptr = nullptr; // Set pointer to null to avoid dangling pointer\n std::cout << \"GPU memory has been freed.\" << std::endl;\n\n } catch (const c10::CUDAError& e) {\n std::cerr << \"Caught c10::CUDAError: \" << e.what() << std::endl;\n // In case of exception, try to free memory if it was allocated\n if (gpu_ptr) {\n std::cout << \"Freeing GPU memory in exception handler...\" << std::endl;\n c10::cuda::CUDACachingAllocator::raw_delete(gpu_ptr);\n }\n return 1;\n } catch (const std::exception& e) {\n std::cerr << \"Caught std::exception: \" << e.what() << std::endl;\n // In case of exception, try to free memory if it was allocated\n if (gpu_ptr) {\n std::cout << \"Freeing GPU memory in exception handler...\" << std::endl;\n c10::cuda::CUDACachingAllocator::raw_delete(gpu_ptr);\n }\n return 1;\n }\n\n std::cout << \"Memory allocation and copy test completed successfully.\" << std::endl;\n return 0; // Main function exits normally\n}\n\n```\n```\nCPU data prepared, size: 1024 bytes.\nCUDA is available. Found 7 GPU device(s).\nAttempting to allocate 1024 bytes of GPU memory...\nCaught std::exception: 0 <= device && static_cast(device) < device_allocator.size() INTERNAL ASSERT FAILED at \"../c10/cuda/CUDACachingAllocator.cpp\":2906, please report a bug to PyTorch. Allocator not initialized for device\n```\n\nThe version of libtorch I am using is 2.3.1+cu118.","reference_answer":"Initialize the CUDA caching allocator with `c10::cuda::CUDACachingAllocator::init`.","needs_clarification":false,"thread_id":219713,"url":"https://discuss.pytorch.org/t/report-a-bug-i-allocated-some-gpu-memory-using-torch-and-i-want-to-copy-data-from-the-cpu-to-the-gpu-but-it-hasn-t-been-successful/219713","created_at":"2025-05-03T13:50:45.320000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[3,4],"answer_authors":["Jiawen_Niu","ptrblck"],"answered_by_ptrblck":true} {"question":"Libtorch nightly versions\n\nHello,\non https://pytorch.org/get-started/locally/ it says that one should use the download link https://download.pytorch.org/libtorch/nightly/cu128/libtorch-cxx11-abi-shared-with-deps-latest.zip for the latest nightly release of libtorch.\nHowever, the last CXX11 ABI version is from March 20. All newer versions for Linux are published under a file name like libtorch-shared-with-deps-2.8.0.dev20250507%2Bcu128.zip.\nDoes someone know if the CXX11 ABI variant is discontinued and why it is still recommended on the PyTorch website?\n\nThanks in advance!","reference_answer":"The CXX11 ABI variant is discontinued: PyTorch stopped building binaries with the pre-CXX11 ABI, so use the libtorch download without the `cxx11-abi` tag. The link on the get-started page that includes `cxx11-abi` pointed to an old version and was broken; it has been fixed. The nightly cu129 download is:\n\nhttps://download.pytorch.org/libtorch/nightly/cu129/libtorch-shared-with-deps-latest.zip","needs_clarification":false,"thread_id":219838,"url":"https://discuss.pytorch.org/t/libtorch-nightly-versions/219838","created_at":"2025-05-07T13:52:32.327000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,4,6],"answer_authors":["atalman","juliusgh","ptrblck"],"answered_by_ptrblck":true} {"question":"Apply vectorized random permutations to conv2d weight tensors\n\nI want to have a method that will take the weight of a `conv2d` layer, typically in the shape `C_out, C_in, H, W`, where `C_out` represents the output channels, `C_in` represents the input channels, while `H` and `W` are the dimensions of filters (kernels).\n\nAs an example, consider a weight:\n```python\nw = torch.randint(0, 5, (4, 1, 3, 3))\ntensor([[[[3, 3, 1],\n [3, 4, 2],\n [1, 2, 3]]],\n\n [[[3, 0, 1],\n [3, 1, 3],\n [0, 2, 2]]],\n\n [[[4, 0, 1],\n [2, 4, 3],\n [2, 4, 0]]],\n\n [[[0, 0, 4],\n [2, 2, 1],\n [3, 4, 0]]]])\n```\nFor this weight, I would like to apply **line-wise permutations** for every filter. This means taking each of the four filters, which can be considered as a `3x3` matrix and randomly permute the lines.\n\nI can create this implementation but only through a *naive* `for` loop:\n```python\ndef test_conv():\n w = torch.randint(0, 5, (4, 1, 3, 3))\n\n w_permuted = w.clone()\n for idx, kernel in enumerate(w_permuted):\n # generate random permutation\n key = torch.randperm(kernel.shape[1])\n # permute lines of the current 3x3 kernel with generated indices\n w_permuted[idx] = kernel[:, key]\n\n print(w)\n print(w_permuted)\n```\n\n**Q:** Is there a more elegant approach using PyTorch to generate `w_permuted` in a vectorized approach?\n\nThanks in advance","reference_answer":"If I understand your use case correctly you want to permute the rows of all kernels randomly without mixing them between kernels.\nI 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.\nHowever, you could try to use `torch.gather` as seen here and compare it against your approach:\n```python\nw = torch.arange(4*2*3*3).view(4, 2, 3, 3).to(device)\nw_ = w.clone()\nkey = torch.stack([torch.randperm(w_.shape[2]) for _ in range(w_.shape[0] * w_.shape[1])]).to(device)\ntorch.gather(w_, 2, key.view(4, 2, 3, 1).expand_as(w_))\n```","needs_clarification":false,"thread_id":219841,"url":"https://discuss.pytorch.org/t/apply-vectorized-random-permutations-to-conv2d-weight-tensors/219841","created_at":"2025-05-07T16:18:32.454000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Does flex_attention still require a sequence length of 128 or not?\n\nThis requirement was specified in the original blogpost: https://pytorch.org/blog/flexattention/\n\n\"FlexAttention requires that all sequence lengths be a multiple of 128 – this will be addressed soon.\"\n\nIt is not mentioned in the docs in either torch version 2.5/2.7 though: https://docs.pytorch.org/docs/2.5/nn.attention.flex_attention.html#torch.nn.attention.flex_attention.flex_attention\n\nWhat's the current status? I did not see a mention of it in the recent torch releases.\n\n@Chillee","reference_answer":"This limitation has been addressed since about 2.6 I think.","needs_clarification":false,"thread_id":219846,"url":"https://discuss.pytorch.org/t/does-flex-attention-still-require-a-sequence-length-of-128-or-not/219846","created_at":"2025-05-07T20:17:22.850000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Chillee"],"answered_by_ptrblck":false} {"question":"Just a silly question. Whats the difference between import torch.nn as nn vs from torch import nn?\n\nMy linter is always complaining about `import torch.nn as nn` and tells me to change it to `from torch import nn`. Is there a difference between the 2?","reference_answer":"Purist might see a difference (and please post these). I would use whichever approach you like. ;)","needs_clarification":false,"thread_id":219851,"url":"https://discuss.pytorch.org/t/just-a-silly-question-whats-the-difference-between-import-torch-nn-as-nn-vs-from-torch-import-nn/219851","created_at":"2025-05-07T23:45:48.872000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Get_backend() returns undefined even when NCCL is available\n\nHi,\n\nI'm currently using torchrun to do distributed training.\n\nI use `init_process_group()` without any parameters in my code since it can automatically pick the backend based on the device type of my current environment: [Distributed communication package - torch.distributed — PyTorch 2.7 documentation](https://docs.pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group)\n\nMy current environment has GPUs and I can see it being properly used with NCCL based on the NCCL logs generated by the NCCL_DEBUG env var.\n\n**Problem**: However, `torch.distributed.get_backend()` still returns 'undefined' even when the lazy initialization is done and the use of NCCL is so clear in my code. I also tried to manually put the default process group as its input parameter but it still returns the same. It only returns `nccl` when I explicitly set `init_process_group('nccl')`.\n\n**Question**: Is this an expected behavior? How can I detect which backend torch is using if I use `init_process_group` with no parameter?","reference_answer":"Yes, that's expected -- at init, no backend was tied to the Process Group in your case.\nThe collective works because PyTorch will try to find a backend for the device identified by your tensor. \nThe no-parameter init is more for a case where your program need to perform collectives on multiple device types, e.g. \"cuda\" and \"cpu\". Thus, when `get_backend()` is queried, it does not know one because it is \"floating\".","needs_clarification":false,"thread_id":219886,"url":"https://discuss.pytorch.org/t/get-backend-returns-undefined-even-when-nccl-is-available/219886","created_at":"2025-05-09T10:01:13.685000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["kwen2501"],"answered_by_ptrblck":false} {"question":"How to handle training of few layers with DDP\n\nHi all,\n\nI have a conceptual question regarding how to best use DistributedDataParallel (DDP) in a setup involving two models.\n\nSuppose I have two `nn.Module` instances: `model1` and `model2`. I want to train all parameters in `model2`, but only a subset of parameters in `model1`. The remaining parameters in `model1` should remain frozen. Please note that both models are used in sequentially to compute the loss function. \n\nNaturally, I would wrap `model2` with DDP as follows:\n\n```python\nmodel2 = DDP(model2, ...)\n```\n\nHowever, I am unsure how to ensure proper gradient synchronization across GPUs for the trainable parameters in `model1`. Clearly, if I don’t include `model1` in DDP, its parameters won’t be synchronized.\n\nI see a couple of options:\n\n1) Wrap a `nn.ModuleList` containing only the trainable submodules from both model1 and model2, and pass that into DDP.\n\n2) Wrap both model1 and model2 with DDP independently, making sure to set `requires_grad = False` for the frozen parameters in model1, as suggested in [this post](https://discuss.pytorch.org/t/how-does-distributeddataparallel-handle-parameters-whose-requires-grad-flag-is-false/90736).\n\nAre either of these approaches recommended or is there a better practice for this use case? I’d like to make sure I'm not missing something regarding how DDP handles parameter synchronization and gradient communication when mixing frozen and trainable parameters across multiple modules.\n\nThanks in advance!","reference_answer":"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.","needs_clarification":false,"thread_id":219979,"url":"https://discuss.pytorch.org/t/how-to-handle-training-of-few-layers-with-ddp/219979","created_at":"2025-05-13T08:17:42.196000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"A Simple LSTM stuck into label flipping\n\nHi All,\n\nI am new to machine learning and pytorch. To get accustomed to the code , I am training a simple LSTM on the [amazon review data from kaggle](https://www.kaggle.com/datasets/kritanjalijain/amazon-reviews) for sentiment analysis (target label 1 or 0). The input is character level sequence to the LSTM.\n\nMy training is stuck on label flipping, in each batch either all the predictions are 0 or all the predictions are 1. \nI tried 1 batch overfitting with a batch of 10, but the loss is not getting down to 0.0 or close to 0.0\n\nI tried in device - cpu , mps in my mac, cuda in kaggle. All of them have the same issue.\nI had a simple MLP module and it is able to overfit a batch of 64 from 6th step.\nTo avoid vanishing gradient in the BPTT I filter the inputs/target where input length < 256 chars.\n\nCan you please suggest what I am doing wrong and how to fix it ?\n\nHere is my kaggle notebook - https://www.kaggle.com/code/subhojitdss/amazon-review-2?scriptVersionId=239541002\n\nBelow is my code, \n\n```\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport torch\nimport pandas as pd\n\ndataset_dir = '/Users/subhojit/datasets/amazon_review_polarity_csv'\ndf_train = pd.read_csv(dataset_dir + '/train.csv')\ndf_test = pd.read_csv(dataset_dir + '/test.csv')\n\nreview = df_train.iloc[:, 2].to_numpy()\ntest_review = df_test.iloc[:, 2].to_numpy()\nall_review = np.concatenate((review, test_review))\nc = sorted(list(set(''.join(all_review))))\nchars = c + ['', '', '']\nstoi = {ch:i for i, ch in enumerate(chars)}\nitos = {i:ch for i, ch in enumerate(chars)}\nvocab_size = len(chars)\n\ndf_filtered = df_train[df_train.iloc[:, 2].str.len() < 256]\nx_filtered = df_filtered.iloc[:, 2].to_numpy()\ny_filtered = df_filtered.iloc[:, 0].to_numpy()\n\nn = int(0.9*len(x_filtered))\nxtrain = x_filtered[:n]\nytrain = y_filtered[:n]\nxval = x_filtered[n:]\nyval = y_filtered[n:]\n\nxtest = df_test.iloc[:, 2].to_numpy()\nytest = df_test.iloc[:, 0].to_numpy()\n\nstoi = {ch:i for i, ch in enumerate(chars)}\nitos = {i:ch for i, ch in enumerate(chars)}\nencode = lambda s: [stoi[xi] for xi in s]\ndecode = lambda l: ''.join([itos[li] for li in l])\n\nif torch.backends.mps.is_available():\n device = \"mps\"\nelif torch.cuda.is_available():\n device = \"cuda\"\nelse:\n device = \"cpu\"\n\ndef pad_sequences(sequences):\n pad_index = stoi['']\n max_len = np.max([len(s) for s in sequences])\n padded_seq = np.full((len(sequences), max_len), pad_index, dtype=np.int32)\n for i, seq in enumerate(sequences):\n padded_seq[i, :len(seq)] = seq\n return padded_seq\n\ndef get_batch(batch_size, split='train'):\n data = xtrain if split == 'train' else xval\n target = ytrain if split == 'train' else yval\n idx = np.random.randint(0, len(data), (batch_size,))\n x_sample = [encode(s) for s in data[idx]]\n y_sample = target[idx]\n xpadded = pad_sequences(x_sample)\n xb, yb = xpadded, y_sample\n yb = torch.from_numpy(yb)\n yb = yb - 1\n # yb = torch.nn.functional.one_hot(yb - 1, num_classes=2)\n xb = torch.from_numpy(xb)\n x = xb.to(device, dtype=torch.long)\n y = yb.to(device, dtype=torch.long)\n return x, y\n\nclass LSTMClassifier(nn.Module):\n def __init__(self, vocab_size, embedding_dim, hidden_size, output_size):\n super().__init__()\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n self.lstm = nn.LSTM(\n input_size=embedding_dim,\n hidden_size=hidden_size,\n batch_first=True,\n bidirectional=True\n )\n self.fc = nn.Linear(hidden_size * 2, output_size)\n nn.init.xavier_uniform_(self.fc.weight)\n nn.init.zeros_(self.fc.bias)\n\n def forward(self, x):\n x = self.embedding(x) # (B, T, D)\n output, (hn, cn) = self.lstm(x) # output: (B, T, H)\n last_hidden = output[:, -1, :] # (B, H) <-- last time step\n logits = self.fc(last_hidden) # (B, C)\n return logits\n\nembedding_dim = 32\nhidden_size = 256\noutput_size = 2\nbatch_size = 64\nseq_len = 10\nlearning_rate = 1e-2\nmax_iter = 5000\neval_interval = 500\n\nmodel = LSTMClassifier(vocab_size, hidden_size, output_size, embedding_dim)\n# model = MLPClassifier(vocab_size, embedding_dim, hidden_size, output_size, xb.shape[1])\nmodel = model.to(device)\noptimizer = torch.optim.AdamW(model.parameters(), lr=1e-2)\n\nfor step in range(max_iter):\n xb, yb = get_batch(batch_size)\n logits = model(xb)\n loss = F.cross_entropy(logits, yb)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n with torch.no_grad():\n logits = model(xb)\n probs = torch.softmax(logits, dim=1)\n print(\"Confidence range:\", probs.max(dim=1).values[:10])\n preds = torch.argmax(logits, dim=1)\n print(\"Preds: \", preds.tolist())\n print(\"Targets: \", yb.tolist())\n\n if step % eval_interval == 0:\n print(f\"step {step}: train loss {loss:.4f}\")\n```","reference_answer":"All the padding and extra steps to ignore the passing for calculating the loss comes almost for free using methods provided by PyTorch. You may want to have a look at [`PackedSequence`](https://docs.pytorch.org/docs/stable/generated/torch.nn.utils.rnn.PackedSequence.html), [`pack_padded_sequence`](https://docs.pytorch.org/docs/stable/generated/torch.nn.utils.rnn.pack_padded_sequence.html) and [`pad_sequence`](https://docs.pytorch.org/docs/stable/generated/torch.nn.utils.rnn.pad_sequence.html) for that. It will make your code smaller, cleaner, and less error-prone\n\nI also have to Jupyter notebooks that cover those methods in detail [here](https://github.com/chrisvdweth/selene/blob/master/notebooks/batch_processing_sequence_tasks.ipynb), and go through a practical example [here](https://github.com/chrisvdweth/selene/blob/master/notebooks/text_classification_rnn.ipynb). Maybe useful.","needs_clarification":false,"thread_id":220004,"url":"https://discuss.pytorch.org/t/a-simple-lstm-stuck-into-label-flipping/220004","created_at":"2025-05-13T19:44:43.099000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["vdw"],"answered_by_ptrblck":false} {"question":"Silent bug in doing gradient descent manually\n\nHi, I am doing an experiment mimicking a classic federated learning setting on CIFAR10 with ResNet18 for image classification. I divided the dataset itself into a bunch of training set each for one client. I calculated the full gradient of each client in each epoch (by deep copying the global model and do loss.backward() on each of the mini batch after scaling it.) and then I would like to apply a compressor to the gradient. The compressed gradients for each clients are then averaged and applied to each parameter in a standard gradient descent fashion. However, I find the model fails to learn with no improvements in training losses and accuracy, even if I do not apply the compressor at all (which means I just take the gradients and average them).\n\nHere is my code:\n\n```\ndef get_gradient(model, client_loader, criterion, device, configs):\n model.to(device)\n model.zero_grad()\n model.train()\n\n for inputs, targets in client_loader:\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = model(inputs)\n loss = criterion(outputs, targets)\n\n batch_size = inputs.size(0)\n scaled_loss = loss * (batch_size / len(client_loader.dataset))\n scaled_loss.backward()\n\n gradients = []\n for param in model.parameters():\n if param.grad is not None:\n gradients.append(param.grad.clone().detach())\n else:\n gradients.append(None)\n gradients.append(param.grad.clone().detach())\n return gradients\n\ndef flatten_gradients(grad_list):\n flat = [g.view(-1) for g in grad_list if g is not None]\n return torch.cat(flat)\n \n\ndef unflatten_gradient(flat_tensor, param_shapes):\n grads = []\n offset = 0\n for shape in param_shapes:\n if shape is None:\n grads.append(None)\n else:\n numel = torch.tensor(shape).prod().item()\n grads.append(flat_tensor[offset:offset+numel].view(shape))\n offset += numel\n return grads\n\ndef rand_k_global_compressor(grad_list, k, param_shapes):\n flat_grad = flatten_gradients(grad_list)\n numel = flat_grad.numel()\n if k >= numel:\n compressed_flat = flat_grad\n else:\n indices = torch.randperm(numel, device=flat_grad.device)[:k]\n compressed_flat = torch.zeros_like(flat_grad)\n compressed_flat[indices] = flat_grad[indices] * (numel / k)\n compressed_grad_list = unflatten_gradient(compressed_flat, param_shapes)\n return compressed_grad_list\n \n\ndef train_FedSGD(global_model, criterion, clients, train_loader, test_loader, device, configs, epoch):\n # =================== Client Partial Participation ===================\n num_clients = len(clients)\n num_selected_clients = max(1, int(configs[\"participation_rate\"] * num_clients))\n selected_client_indices = random.sample(range(num_clients), num_selected_clients)\n\n # =================== Get Local Gradients ===================\n client_idx = 0\n client_gradients_list = []\n param_shapes = [p.shape if p.requires_grad else None for p in global_model.parameters()]\n for idx in selected_client_indices:\n client_idx += 1\n \n local_model = copy.deepcopy(global_model)\n client_loader = clients[idx]\n client_gradient = get_gradient(local_model, client_loader, criterion, device, configs)\n\n if configs[\"compression\"]:\n client_gradient = rand_k_global_compressor(client_gradient, configs[\"rand-k\"], param_shapes)\n\n client_gradients_list.append(client_gradient)\n del local_model\n\n # =================== Aggregrating gradients ===================\n averaged_grads = []\n for grads_per_param in zip(*client_gradients_list):\n if grads_per_param[0] is None:\n averaged_grads.append(None)\n else:\n stacked = torch.stack(grads_per_param)\n averaged_grads.append(torch.mean(stacked, dim=0))\n\n # =================== Applying gradients to model ===================\n with torch.no_grad():\n for param, grad in zip(global_model.parameters(), averaged_grads):\n if grad is not None:\n param.data -= configs[\"lr\"] * grad\n\n # =================== Evaluating Training Loss and Test Accuracy ===================\n train_loss = evaluate_train_loss(global_model, train_loader, device)\n test_acc = evaluate_test_acc(global_model, test_loader, device)\n\n # =================== Optionally Save the Gloabl Model ===================\n save_dir = configs.get(\"checkpoint_dir\", \"checkpoints\")\n os.makedirs(save_dir, exist_ok=True)\n \n if (configs[\"epoch_checkpoint\"] >= 1 and epoch % configs[\"epoch_checkpoint\"] == 0) or epoch == configs[\"epochs\"]:\n compression_tag = f\"randk{configs['rand-k']}\" if configs[\"compression\"] else \"fullgrad\"\n checkpoint_path = os.path.join(\n save_dir,\n f\"FedSGD_{compression_tag}_lr{configs['lr']}_epoch{epoch}.pt\"\n )\n torch.save(global_model.state_dict(), checkpoint_path)\n\n return train_loss, test_acc\n```\n\nand I call the following when I try to execute the above functions:\n```\nif __name__ == \"__main__\":\n configs = get_configurations()\n set_seed(configs[\"seed\"])\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n global_model = get_model(model_name=configs[\"model_name\"], is_pretrained=configs[\"is_pretrained\"])\n global_model.to(device)\n global_model.train()\n\n client_loaders_list = get_client_loaders(configs[\"num_clients\"], configs[\"batch_size\"])\n test_loader = get_test_loader(configs[\"dataset_name\"], configs[\"batch_size\"])\n train_loader = get_train_loader(configs[\"dataset_name\"], configs[\"batch_size\"])\n \n criterion = nn.CrossEntropyLoss(reduction='mean')\n\n if configs[\"meta_method\"] == \"FedAvg\":\n train_loss_hist, test_acc_hist = [], []\n for epoch in range(1, configs[\"epochs\"] + 1):\n train_loss, test_acc = train_FedAvg(global_model, criterion, client_loaders_list, train_loader, \n test_loader, device, configs, epoch) \n print(f\"[Epoch {epoch}] | train_loss: {train_loss:.4f} | test_acc: {test_acc['accuracy']:.2f}\")\n train_loss_hist.append(train_loss)\n test_acc_hist.append(test_acc)\n elif configs[\"meta_method\"] == \"FedSGD-Randk\":\n train_loss_hist, test_acc_hist = [], []\n for epoch in range(1, configs[\"epochs\"] + 1):\n train_loss, test_acc = train_FedSGD(global_model, criterion, client_loaders_list, train_loader, \n test_loader, device, configs, epoch)\n print(f\"[Epoch {epoch}] | train_loss: {train_loss:.4f} | test_acc: {test_acc['accuracy']:.2f}\")\n train_loss_hist.append(train_loss)\n test_acc_hist.append(test_acc)\n```\nI have gone through 10 times over the code and try to replace the manual GD step by optimizer.step with SGD but still does not work. Could anyone please help me with locating the main issue here?","reference_answer":"After some time, I found the bug. The bug is when I do GD myself, the parameters in the BatchNorm layer are not updated. To resolve this, we need to update those as well by averaging it over clients or do a forward pass again.","needs_clarification":true,"thread_id":220039,"url":"https://discuss.pytorch.org/t/silent-bug-in-doing-gradient-descent-manually/220039","created_at":"2025-05-14T14:14:15.877000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["hmallysjik"],"answered_by_ptrblck":false} {"question":"visualize model performance\n\nHello pytorch community. I am a beginner, and I have used nn.Sequential and nn.RNN to fit timeseries data I generated in a special form and I obtain different performance (both for mean square error and for mean absolute relative error). I would like to gather a maximum amount of plot ideas to realize either using pytorch packages (any recommendations?) or matplotlib / plotly to show the details of the performance of each model (I might add more in the future) in order to not only get a good idea of how well it performs but also the comparison in performance. Any other metric ideas would be greatly appreciated as well. Thank you.","reference_answer":"Hello @Kenza_Benjelloun \n\nWhen it comes to generating plots to compare metrics of different models, I would recommend the Weights&Biases package. You can follow [this guide](https://docs.wandb.ai/quickstart/) to get started with it.\n\nEssentially, you're can initialize it in your Python script like this:\n```\nrun = wandb.init(\n project=\"timeseries\",\n config={ \n \"model\": \"sequential\"\n },\n)\n```\n\nAnd then you can log data to `wandb`, which can be your metrics:\n```\nwandb.log({\"mse\": mse, \"mae\": mae})\n```\n\n This will automatically generate plots that are viewable in your `wandb` projects online, allowing you to compare results across different models and experiments, combine plots, and watch data being generated in real time.\n\n------\n*Machine Learning Engineer at [RidgeRun.ai](https://www.ridgerun.ai/)*\n*Contact us: [[email]](mailto:[email])*","needs_clarification":false,"thread_id":220072,"url":"https://discuss.pytorch.org/t/visualize-model-performance/220072","created_at":"2025-05-15T12:43:35.557000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["dbrenes"],"answered_by_ptrblck":false} {"question":"More data than neurons with autograd?\n\nIs it possible to use autograd or \"manual\" back propagation when input is larger than number of neurons and/or when input requires processing outside of nn? For example something like this to find average of N numbers that would be output by one neuron:\n```\nimport numpy\nimport torch\nsamples = 5\ndata = numpy.random.default_rng().uniform(0, 1, samples)\nreference = numpy.mean(data)\npred = torch.randn(1, requires_grad = True)\nlr = 0.01\nfor i in range(10):\n\tdistance = torch.tensor(\n\t\tnumpy.pow(pred.item() - reference, 2),\n\t\trequires_grad = True)\n\tdistance.backward(retain_graph = True)\n\tpred.sub_(lr * pred.grad.data)\n\tpred.grad.data.zero_()\n```\nAbove code doesn't work but I'm not sure how to fix it, or if it's even possible with autograd/pytorch.","reference_answer":"The below code is working for me\n\n```python\nimport numpy\nimport torch\nsamples = 5\ndata = numpy.random.default_rng().uniform(0, 1, samples)\nreference = numpy.mean(data)\npred = torch.randn(1, requires_grad = True)\nlr = 0.01\n\nfor i in range(10):\n distance = torch.pow(pred - reference, 2)\n distance.backward()\n pred.data.sub_(lr * pred.grad.data)\n pred.grad.data.zero_()\n```\n\nAm I missing something?","needs_clarification":false,"thread_id":220139,"url":"https://discuss.pytorch.org/t/more-data-than-neurons-with-autograd/220139","created_at":"2025-05-18T18:41:59.744000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["Soumya_Kundu"],"answered_by_ptrblck":false} {"question":"Does `register_buffer` make a obj member or cls member?\n\nI'm coding a multi-task classification model, with my customized loss func.\n\nWhile the number of classes of each task are same, each label variables have **different** class weights buffers. So I instanciated loss_func objs for every label var respectively, and let them to hold their own weights buffer, by means of `register_buffer()`.\n\nNow I need to confirm whether or not `register_buffer()` would create multiple instances with a same name, and we can simply access the correct ones just like accessing a normal member var of every func obj.\n\nIn my example as shown later, although I called `register_buffer` with a same arg value(name='cls_wts') for all instances of `SoftLabelLoss`, in fact each obj has its own member var named 'cls_wts' with different weight values(No global values, No overwrites)?\n\nIf so, I do **NOT** need to find the correct buffer by iterating `model.buffers()` when it computing loss?\n\n**Thanks!!!***\n```\nclass SoftLabelLoss( nn.Module ):\n def __init__( self, class_cnt:int, weights:np.ndarray=None ):\n super().__init__()\n cls_idx = torch.arange( class_cnt, dtype=torch.float32, requires_grad=False )\n cls_idx = cls_idx.unsqueeze( 0 )\n self.register_buffer( name='cls_idx', tensor=cls_idx )\n\n if( weights ):\n cls_wts = torch.tensor( weights, dtype=torch.float32, requires_grad=False )\n self.register_buffer( name='cls_wts', tensor=cls_wts )\n else:\n self.cls_wts = None\n\n def forward( self, logits, target ):\n with torch.no_grad():\n ftgts = target.unsqueeze( 1 ).float() # batch_size * 1\n dists = torch.abs( ftgts - self.cls_idx ) # ( batch_size, class_cnt )\n unnorm = torch.exp( -dists )\n soft_labs = unnorm / unnorm.sum( dim=1, keepdim=True )\n log_probs = F.log_softmax( logits, dim=1 ) # ( batch_size, class_cnt )\n loss = - ( soft_labs * log_probs ).sum( dim=1 ) # ( batch_size, )\n if( self.cls_wts ):\n loss *= self.cls_wts[target]\n return loss.mean()\n```","reference_answer":"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 individual weight is registered to the instantiated object.","needs_clarification":false,"thread_id":220155,"url":"https://discuss.pytorch.org/t/does-register-buffer-make-a-obj-member-or-cls-member/220155","created_at":"2025-05-19T09:29:30.499000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Model.to(device) vs. tensor.to(device)\n\nI recently ran into [this discussion](https://stackoverflow.com/a/59560101) referencing the difference in the assignment of `my_model.to(device)` and `my_tensor.to(device)`. While currently the model will be moved *in-place* to the device, tensors must be assigned to the same variable to be moved to the device (`my_tensor = my_tensor.to(device)`).\n\nI have searched this forum for similar topics explaining this logic. There a lot of discussions on the specific usage of `.to(device)`, but none that explicitly addresses why PyTorch implements these methods differently for models vs. tensors\n\nFrom my point-of-view, the issue with this logic is when using `my_model.to(device)` along with `my_tensor.to(device)` a device mismatch will occur, without the problem being directly visible. As a developer, you would need to know which objects are tensors or not in the code (especially hard for PyTorch beginners). Also, the logic is inconsistent with other *in-place* methods, for example `.add_()`, that contain an underscore `_` specifically for this reason.\n\nIs there any particular logic or design philosophy behind this decision to have different behaviors for the same method name? For me, it seems counterintuive that `.to(device)` behaves differently on object types. Would it make sense to make the behaviour of `.to(device)` consistent for models and tensors, for example making both `my_model.to(device)` and `my_tensor.to(device)` performed *in-place*?","reference_answer":"To resolve the inconsistency, you could make sure to always assign the return value for `to()` calls as:\n```python\nmodel = model.to(device)\ntensor = tensor.to(device)\n```\nwill also work.\n\nI see the `inplace` definition w.r.t. the actual data and memory. I.e. I expect an inplace operation to process the already allocated memory and perform every operation on values stored in this memory. Moving data from one device to another thus cannot be an inplace operation unless you abstract the memory model and use something like managed memory (which will move memory behind your back to the device).\n\nMy guess is the design was chosen for the sake of simplicity (iterate recursively through all registered modules, parameters, as well as buffers, and move them to the device) and to avoid high memory foot prints. I.e. a naive alternative approach would be to clone the model (2x memory usage) before moving the data to the device.","needs_clarification":false,"thread_id":220160,"url":"https://discuss.pytorch.org/t/model-to-device-vs-tensor-to-device/220160","created_at":"2025-05-19T12:44:55.303000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Weight becomes nan after step but grad is normal\n\nI have a training script where weights are consistently turning into nan. But I don't see how its happening. I set up the following block to debug.\n```\ntemp = convLayer.weight.detach().clone()\noptimizer.step()\nif (convLayer.weight.isnan().any()):\n import pdb; pdb.set_trace()\n```\nwhen the trigger gets flipped I can print:\n```\n(Pdb) convLayer.weight.grad[convLayer.weight.isnan()]\ntensor([-3.3897e-10], device='cuda:0')\n(Pdb) convLayer.weight[convLayer.weight.isnan()]\ntensor([nan], device='cuda:0', grad_fn=)\n(Pdb) temp[convLayer.weight.isnan()]\ntensor([-0.0122], device='cuda:0')\n```\nIt looks like the index of the weights I am looking at is not nan before the optimizer.step, and nan after, but the grad in between is just a normal seeming value. The following is the state of the optimizer.\n```\n(Pdb) optimizer\nRMSprop (\nParameter Group 0\n alpha: 0.95\n capturable: False\n centered: True\n differentiable: False\n eps: 0.01\n foreach: None\n lr: 0.00025\n maximize: False\n momentum: 0\n weight_decay: 0\n)\n\n```","reference_answer":"To get to the bottom of this, we need to consider how [RMSProp](https://docs.pytorch.org/docs/stable/generated/torch.optim.RMSprop.html) is calculated, given the parameters you've changed from the default:\n\nYou've changed the learning rate, alpha, eps, and `centered = True`. In the case of `centered = True`, we have the following terms in the denominator:\n\n√(v - m²) + ε\n\nWhere v is the second moment of the gradients, m is the first moment, and ε is just eps. When v - m² < 0, we gets nans because we're taking the square root of a negative (might still work if you use complex numbers). \n\nThis is occuring because of how you've set α. What α does is it takes the new gradient and makes it more weighted the lower α becomes, giving us the first moment(m above). So let's say we have a large new gradient but small second moment. Lower α increases the likelihood of a square root of a negative number in the denominator. \n\n**Solution:**\nI'd try making α closer to 1(i.e. alpha = 0.999) or setting `centered = False`. See if that resolves the issue.","needs_clarification":true,"thread_id":220179,"url":"https://discuss.pytorch.org/t/weight-becomes-nan-after-step-but-grad-is-normal/220179","created_at":"2025-05-20T03:46:25.169000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[10],"answer_authors":["J_Johnson"],"answered_by_ptrblck":false} {"question":"Premultiplied alpha\n\nWhen you use `torchvision.io.decode_image(..., mode=ImageReadMode.UNCHANGED)`, if the image has premultiplied alpha (ie. [NRGBA in go's image/color](https://pkg.go.dev/image/color#NRGBA)) does it automatically convert to non-premultiplied alpha?","reference_answer":"Short answer, you cannot. \n\nSince pre-multiplied alpha cannot be reliably identified in PNGs, most datasets provide images with non-premultiplied-alpha, where the alpha channel is simply the fourth channel in the RGBA PNG image.\n\nHence, if you load your image with `decode_image(..., mode=UNCHANGED)` , and analyze the loaded tensor's shape, an original RGB image will have 3 channels, and an original RGBA image (non-pre-multiplied-alpha) will have 4 channels. \n\nWith that said, setting `mode=RGB` for a non-pre-multiplied-alpha image would give you a RGB image, with the alpha channel discarded.","needs_clarification":false,"thread_id":220230,"url":"https://discuss.pytorch.org/t/premultiplied-alpha/220230","created_at":"2025-05-21T16:40:18.345000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ajayrkumar"],"answered_by_ptrblck":false} {"question":"Stalling on Simple Distributed Barrier\n\nI'm stalling on any kind of barrier between two GPUs in a minimal example with the nvidia pytorch container `nvcr.io/nvidia/pytorch:25.03-py3` and there's nothing really jumping out at me in the NCCL logs to a layman like me. I saw an [older post](https://discuss.pytorch.org/t/distributed-stuck-in-first-call-to-barrier/207402/4) that they had problems with the driver, is this probably the case for me? I initially used 570.86, and bumped up to 570.124. I'm running on bare metal kubernetes cluster with ubuntu 24.04, so kinda restricted to driver 570, and have to wait for 575 to be published in container form.\n\nEdit: I also started with `nvcr.io/nvidia/pytorch:25.02-py3` and tried the bump to `03` to fix this. My normal training code used to always be fine, and I didn't notice any changes in the DDP training docs.\n\n```bash\ntorchrun --nproc-per-node=gpu --standalone /mnt/user/test-ddp.py\n```\n\n```python\nimport os\nimport torch\nimport torch.distributed as dist\n\nif __name__ == \"__main__\":\n torch.cuda.set_device(f\"cuda:{os.environ.get('LOCAL_RANK', 0)}\")\n dist.init_process_group(backend=\"nccl\")\n\n rank = dist.get_rank()\n print(f\"Rank of the current process: {rank}\")\n \n dist.barrier()\n print(\"All processes have reached the barrier.\")\n\n dist.destroy_process_group()\n\n```\n\n```\nW0528 12:31:53.174000 1 torch/distributed/run.py:763]\nW0528 12:31:53.174000 1 torch/distributed/run.py:763] *****************************************\nW0528 12:31:53.174000 1 torch/distributed/run.py:763] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed.\nW0528 12:31:53.174000 1 torch/distributed/run.py:763] *****************************************\nRank of the current process: 0\nRank of the current process: 1\n[rank1]:[W528 12:31:54.339872954 ProcessGroupNCCL.cpp:4782] [PG ID 0 PG GUID 0 Rank 1] using GPU 1 to perform barrier as devices used by this process are currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. Specify device_ids in barrier() to force use of a particular device, or call init_process_group() with a device_id.\n[rank0]:[W528 12:31:54.349033170 ProcessGroupNCCL.cpp:4782] [PG ID 0 PG GUID 0 Rank 0] using GPU 0 to perform barrier as devices used by this process are currently unknown. This can potentially cause a hang if this rank to GPU mapping is incorrect. Specify device_ids in barrier() to force use of a particular device, or call init_process_group() with a device_id.\nddp-deb-train-0:90:90 [0] NCCL INFO Bootstrap: Using eth0:192.168.19.109<0>\nddp-deb-train-0:90:90 [0] NCCL INFO cudaDriverVersion 12080\nddp-deb-train-0:90:90 [0] NCCL INFO NCCL version 2.25.1+cuda12.8\nddp-deb-train-0:90:90 [0] NCCL INFO Comm config Blocking set to 1\nddp-deb-train-0:91:91 [1] NCCL INFO cudaDriverVersion 12080\nddp-deb-train-0:91:91 [1] NCCL INFO Bootstrap: Using eth0:192.168.19.109<0>\nddp-deb-train-0:91:91 [1] NCCL INFO NCCL version 2.25.1+cuda12.8\nddp-deb-train-0:91:91 [1] NCCL INFO Comm config Blocking set to 1\nddp-deb-train-0:90:105 [0] NCCL INFO NET/Plugin: Loaded net plugin NCCL RDMA Plugin v9 (v9)\nddp-deb-train-0:90:105 [0] NCCL INFO NET/Plugin: Loaded collnet plugin SHARP (v9)\nddp-deb-train-0:90:105 [0] NCCL INFO Plugin Path : /opt/hpcx/nccl_rdma_sharp_plugin/lib/libnccl-net.so\nddp-deb-train-0:90:105 [0] NCCL INFO P2P plugin v9 IBext_v9\nddp-deb-train-0:90:105 [0] NCCL INFO NET/IB : No device found.\nddp-deb-train-0:90:105 [0] NCCL INFO NET/IB : Using [RO]; OOB eth0:192.168.19.109<0>\nddp-deb-train-0:90:105 [0] NCCL INFO NET/IB : No device found.\nddp-deb-train-0:90:105 [0] NCCL INFO NET/IB : Using [RO]; OOB eth0:192.168.19.109<0>\nddp-deb-train-0:90:105 [0] NCCL INFO NET/Socket : Using [0]eth0:192.168.19.109<0>\nddp-deb-train-0:90:105 [0] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.\nddp-deb-train-0:90:105 [0] NCCL INFO Using network Socket\nddp-deb-train-0:90:105 [0] NCCL INFO ncclCommInitRankConfig comm 0x25bb5550 rank 0 nranks 2 cudaDev 0 nvmlDev 0 busId 81000 commId 0x1d0b7e730eb15adf - Init START\nddp-deb-train-0:91:106 [1] NCCL INFO NET/Plugin: Loaded net plugin NCCL RDMA Plugin v9 (v9)\nddp-deb-train-0:91:106 [1] NCCL INFO NET/Plugin: Loaded collnet plugin SHARP (v9)\nddp-deb-train-0:91:106 [1] NCCL INFO Plugin Path : /opt/hpcx/nccl_rdma_sharp_plugin/lib/libnccl-net.so\nddp-deb-train-0:91:106 [1] NCCL INFO P2P plugin v9 IBext_v9\nddp-deb-train-0:91:106 [1] NCCL INFO NET/IB : No device found.\nddp-deb-train-0:91:106 [1] NCCL INFO NET/IB : Using [RO]; OOB eth0:192.168.19.109<0>\nddp-deb-train-0:91:106 [1] NCCL INFO NET/IB : No device found.\nddp-deb-train-0:91:106 [1] NCCL INFO NET/IB : Using [RO]; OOB eth0:192.168.19.109<0>\nddp-deb-train-0:91:106 [1] NCCL INFO NET/Socket : Using [0]eth0:192.168.19.109<0>\nddp-deb-train-0:91:106 [1] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.\nddp-deb-train-0:91:106 [1] NCCL INFO Using network Socket\nddp-deb-train-0:91:106 [1] NCCL INFO ncclCommInitRankConfig comm 0xaa2ec70 rank 1 nranks 2 cudaDev 1 nvmlDev 1 busId e1000 commId 0x1d0b7e730eb15adf - Init START\nddp-deb-train-0:91:106 [1] NCCL INFO RAS client listening socket at ::1<28028>\nddp-deb-train-0:90:105 [0] NCCL INFO RAS client listening socket at ::1<28028>\nddp-deb-train-0:91:106 [1] NCCL INFO Bootstrap timings total 0.001023 (create 0.000037, send 0.000134, recv 0.000426, ring 0.000034, delay 0.000000)\nddp-deb-train-0:90:105 [0] NCCL INFO Bootstrap timings total 0.009177 (create 0.000035, send 0.000137, recv 0.008375, ring 0.000030, delay 0.000000)\nddp-deb-train-0:91:106 [1] NCCL INFO Setting affinity for GPU 1 to ffffffff,ffffffff,00000000,00000000,ffffffff,ffffffff,00000000,00000000\nddp-deb-train-0:90:105 [0] NCCL INFO Setting affinity for GPU 0 to ffffffff,ffffffff,00000000,00000000,ffffffff,ffffffff,00000000,00000000\nddp-deb-train-0:91:106 [1] NCCL INFO comm 0xaa2ec70 rank 1 nRanks 2 nNodes 1 localRanks 2 localRank 1 MNNVL 0\nddp-deb-train-0:90:105 [0] NCCL INFO comm 0x25bb5550 rank 0 nRanks 2 nNodes 1 localRanks 2 localRank 0 MNNVL 0\nddp-deb-train-0:91:106 [1] NCCL INFO Trees [0] -1/-1/-1->1->0 [1] 0/-1/-1->1->-1 [2] -1/-1/-1->1->0 [3] 0/-1/-1->1->-1\nddp-deb-train-0:90:105 [0] NCCL INFO Channel 00/04 : 0 1\nddp-deb-train-0:91:106 [1] NCCL INFO P2P Chunksize set to 131072\nddp-deb-train-0:90:105 [0] NCCL INFO Channel 01/04 : 0 1\nddp-deb-train-0:90:105 [0] NCCL INFO Channel 02/04 : 0 1\nddp-deb-train-0:90:105 [0] NCCL INFO Channel 03/04 : 0 1\nddp-deb-train-0:90:105 [0] NCCL INFO Trees [0] 1/-1/-1->0->-1 [1] -1/-1/-1->0->1 [2] 1/-1/-1->0->-1 [3] -1/-1/-1->0->1\nddp-deb-train-0:90:105 [0] NCCL INFO P2P Chunksize set to 131072\nddp-deb-train-0:90:105 [0] NCCL INFO Check P2P Type intraNodeP2pSupport 1 directMode 0\nddp-deb-train-0:90:110 [0] NCCL INFO [Proxy Service] Device 0 CPU core 237\nddp-deb-train-0:91:109 [1] NCCL INFO [Proxy Service] Device 1 CPU core 109\nddp-deb-train-0:91:111 [1] NCCL INFO [Proxy Service UDS] Device 1 CPU core 219\nddp-deb-train-0:90:112 [0] NCCL INFO [Proxy Service UDS] Device 0 CPU core 75\nddp-deb-train-0:91:106 [1] NCCL INFO threadThresholds 8/8/64 | 16/8/64 | 512 | 512\nddp-deb-train-0:91:106 [1] NCCL INFO 4 coll channels, 4 collnet channels, 0 nvls channels, 4 p2p channels, 2 p2p channels per peer\nddp-deb-train-0:90:105 [0] NCCL INFO threadThresholds 8/8/64 | 16/8/64 | 512 | 512\nddp-deb-train-0:90:105 [0] NCCL INFO 4 coll channels, 4 collnet channels, 0 nvls channels, 4 p2p channels, 2 p2p channels per peer\nddp-deb-train-0:90:105 [0] NCCL INFO CC Off, workFifoBytes 1048576\nddp-deb-train-0:90:105 [0] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v4 symbol.\nddp-deb-train-0:91:106 [1] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v4 symbol.\nddp-deb-train-0:90:105 [0] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v3 symbol.\nddp-deb-train-0:91:106 [1] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v3 symbol.\nddp-deb-train-0:90:105 [0] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v2 symbol, using internal tuner instead.\nddp-deb-train-0:91:106 [1] NCCL INFO TUNER/Plugin: Failed to find ncclTunerPlugin_v2 symbol, using internal tuner instead.\nddp-deb-train-0:90:105 [0] NCCL INFO ncclCommInitRankConfig comm 0x25bb5550 rank 0 nranks 2 cudaDev 0 nvmlDev 0 busId 81000 commId 0x1d0b7e730eb15adf - Init COMPLETE\nddp-deb-train-0:91:106 [1] NCCL INFO ncclCommInitRankConfig comm 0xaa2ec70 rank 1 nranks 2 cudaDev 1 nvmlDev 1 busId e1000 commId 0x1d0b7e730eb15adf - Init COMPLETE\nddp-deb-train-0:90:105 [0] NCCL INFO Init timings - ncclCommInitRankConfig: rank 0 nranks 2 total 0.14 (kernels 0.11, alloc 0.00, bootstrap 0.01, allgathers 0.00, topo 0.01, graphs 0.00, connections 0.00, rest 0.00)\nddp-deb-train-0:91:106 [1] NCCL INFO Init timings - ncclCommInitRankConfig: rank 1 nranks 2 total 0.13 (kernels 0.12, alloc 0.00, bootstrap 0.00, allgathers 0.00, topo 0.01, graphs 0.00, connections 0.00, rest 0.00)\nddp-deb-train-0:90:113 [0] NCCL INFO Channel 00/0 : 0[0] -> 1[1] via P2P/CUMEM\nddp-deb-train-0:90:113 [0] NCCL INFO Channel 01/0 : 0[0] -> 1[1] via P2P/CUMEM\nddp-deb-train-0:90:113 [0] NCCL INFO Channel 02/0 : 0[0] -> 1[1] via P2P/CUMEM\nddp-deb-train-0:90:113 [0] NCCL INFO Channel 03/0 : 0[0] -> 1[1] via P2P/CUMEM\nddp-deb-train-0:91:114 [1] NCCL INFO Channel 00/0 : 1[1] -> 0[0] via P2P/CUMEM\nddp-deb-train-0:91:114 [1] NCCL INFO Channel 01/0 : 1[1] -> 0[0] via P2P/CUMEM\nddp-deb-train-0:91:114 [1] NCCL INFO Channel 02/0 : 1[1] -> 0[0] via P2P/CUMEM\nddp-deb-train-0:91:114 [1] NCCL INFO Channel 03/0 : 1[1] -> 0[0] via P2P/CUMEM\nddp-deb-train-0:91:114 [1] NCCL INFO Connected all rings, use ring PXN 0 GDR 1\nddp-deb-train-0:90:113 [0] NCCL INFO Connected all rings, use ring PXN 0 GDR 1\n```\n\n```\nroot@ddp-deb-train-0:/workspace# nvidia-smi topo -m\n GPU0 GPU1 NIC0 NIC1 CPU Affinity NUMA Affinity GPU NUMA ID\nGPU0 X NODE SYS SYS 64-127,192-255 1 N/A\nGPU1 NODE X SYS SYS 64-127,192-255 1 N/A\nNIC0 SYS SYS X PIX\nNIC1 SYS SYS PIX X \n\nLegend:\n\n X = Self\n SYS = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)\n NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node\n PHB = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)\n PXB = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)\n PIX = Connection traversing at most a single PCIe bridge\n NV# = Connection traversing a bonded set of # NVLinks\n\nNIC Legend:\n\n NIC0: mlx5_0\n NIC1: mlx5_1\n\nroot@ddp-deb-train-0:/workspace# nvidia-smi\nWed May 28 12:37:59 2025 \n+-----------------------------------------------------------------------------------------+\n| NVIDIA-SMI 570.124.06 Driver Version: 570.124.06 CUDA Version: 12.8 |\n|-----------------------------------------+------------------------+----------------------+\n| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|=========================================+========================+======================|\n| 0 NVIDIA RTX 5000 Ada Gene... On | 00000000:81:00.0 Off | Off |\n| 30% 40C P2 73W / 250W | 544MiB / 32760MiB | 100% Default |\n| | | N/A |\n+-----------------------------------------+------------------------+----------------------+\n| 1 NVIDIA RTX 5000 Ada Gene... On | 00000000:E1:00.0 Off | Off |\n| 30% 39C P2 75W / 250W | 544MiB / 32760MiB | 100% Default |\n| | | N/A |\n+-----------------------------------------+------------------------+----------------------+\n \n+-----------------------------------------------------------------------------------------+\n| Processes: |\n| GPU GI CI PID Type Process name GPU Memory |\n| ID ID Usage |\n|=========================================================================================|\n| 0 N/A N/A 90 C /usr/bin/python 534MiB |\n| 1 N/A N/A 91 C /usr/bin/python 534MiB |\n+-----------------------------------------------------------------------------------------+\n```","reference_answer":"Disable IOMMU as described [here](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/troubleshooting.html#pci-access-control-services-acs).","needs_clarification":false,"thread_id":220404,"url":"https://discuss.pytorch.org/t/stalling-on-simple-distributed-barrier/220404","created_at":"2025-05-28T12:45:47.833000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[11],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Symmetric parametrization\n\nHello, \n\nFrom the PyTorch [parametrization tutorial](https://docs.pytorch.org/tutorials/intermediate/parametrizations.html#introduction-to-parametrizations) the symmetric parametrization is implemented as follow:\n```\nclass Symmetric(nn.Module):\n def forward(self, X):\n return X.triu() + X.triu(1).transpose(-1, -2)\n```\nIs there a reason (especially for gradient computation) why this would be preferred to:\n```\nclass Symmetric(nn.Module):\n def forward(self, X):\n return X + X.transpose(-1, -2)\n```","reference_answer":"Hi Octave!\n\nI can't think of any compelling reason -- both should work.\n\nOne thing to note is that the in the original version, the non-symmetric `X` matrix contains\nignored elements -- those in the lower triangle -- while your version contains redundant\nelements (that aren't ignored). Arguably the former could be better.\n\nIn your case, you add two elements together -- one from the upper triangle and one from\nthe lower triangle. So if you (or the optimization step) adds a large value to the upper\nelement and subtracts the same value from the lower element, it would have no effect.\nThis means that you have a directions (a \"mode\") where those elements could drift off\nto `+-inf`, potentially causing problems. (The ignored values in the original approach\ncould also potentially drift off, but that's less likely to happen and less likely to cause\nproblems if they do.)\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":220451,"url":"https://discuss.pytorch.org/t/symmetric-parametrization/220451","created_at":"2025-05-30T12:56:45.653000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"WebDataset Multi-GPU Single-Node\n\nHello,\n\nI'm running single-node, multi-GPU training using data in WebDataset format (~4000 shards, each with 1000 `.flac` files). My goal is to train for `N` epochs, where each epoch consists of `config[\"num_batches_per_epoch\"]` optimizer steps.\n\nHere's what I want to achieve:\n\n* **Continuous sampling** across epochs, wrapping around when all data have been used.\n* **Proper reshuffling** at both the shard and sample levels on every epoch.\n* **Different data per GPU**, using `DistributedSampler`-like behavior.\n* And **most importantly**: ensuring that running the training long enough will eventually sample **all the available data** and not just a subset of them.\n\nHere's the dataset definition I’m currently using:\n\n```python\ntrain_dataset = (\n wds.WebDataset(\n config[\"train_data\"],\n resampled=True,\n shardshuffle=True,\n handler=wds.handlers.warn_and_continue,\n nodesplitter=wds.shardlists.split_by_node,\n )\n .shuffle(config[\"shuffle_buffer_size\"])\n .decode(wds.torch_audio)\n .map(lambda sample: sample[\"flac.flac\"][0])\n .with_epoch(\n config[\"num_batches_per_epoch\"]\n * config[\"batch_size\"]\n // config[\"num_workers\"]\n )\n)\n\ntrain_dataloader = DataLoader(\n train_dataset,\n batch_size=config[\"batch_size\"],\n num_workers=config[\"num_workers\"],\n worker_init_fn=seed_worker,\n pin_memory=(device.type == \"cuda\"),\n)\n```\nIs this the right way to do it?\n\nThanks in advance!","reference_answer":"Yes. WebDataset takes care of splitting the data between processes, so a `DistributedSampler` is not needed. Checking how the utterances are split between processes at each epoch on a small dataset confirmed the setup.","needs_clarification":false,"thread_id":220471,"url":"https://discuss.pytorch.org/t/webdataset-multi-gpu-single-node/220471","created_at":"2025-05-31T05:47:50.151000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[3,4],"answer_authors":["ldellal"],"answered_by_ptrblck":false} {"question":"Second Gradient Computation with autograd yield zeros\n\nHi everyone,\n\nWhen I compute the gradient using `torch.autograd.grad` and then try to compute the second derivative via another call to `autograd.grad`, I unexpectedly get a tensor of **all zeros**. However, if I compute the second derivative using either:\n\n1. The **Jacobian** of the gradient and take its trace (i.e., sum of second partials), or\n2. **Loop through each input component and compute its second derivative individually**,\n\nI get the correct analytical result. The problem is:\n\n* **Using Jacobians**: Although I get the correct result, the model’s loss behaves strangely during training and doesn't converge.\n* **Per-input gradient computation**: This works, but it is **extremely slow**—not feasible for my application.\n\nHas anyone encountered this issue with `autograd.grad` returning zero second derivatives?\n\nHere is a small test case:\n\n```\ndef minimal_test(x):\n xi = x[:, 0, :]\n xj = x[:, 1, :]\n diff = xi - xj\n r = torch.sqrt(torch.sum(diff ** 2, dim=-1) + 1e-10)\n sigma = torch.exp(torch.tensor(0.15))\n k = torch.sigmoid(torch.tensor(0.5))\n phi = torch.pow(sigma / r, 2 / k)\n \n energy = phi.sum(dim=-1)\n return - energy\n\n# Forward pass\nx_t = torch.tensor([[[ 0.4806, -0.5267], [ 0.5513, 0.6484]]], requires_grad=True) # Simplified input, shape (B, N, D)\n\ndef psi(x_t):\n output = minimal_test(x_t)\n gradients = torch.autograd.grad(\n outputs=output, inputs=x_t, grad_outputs=torch.ones_like(output),\n retain_graph=True, create_graph=True,\n )[0]\n return gradients\n\ngradients = psi(x_t)\ngrad_outputs = torch.ones_like(gradients)\ndivergence = torch.autograd.grad(outputs=gradients, inputs=x_t, grad_outputs=grad_outputs, create_graph=True)[0]\nprint(\"Gradients:\", gradients)\nprint(\"Second Gradients (autograd):\", divergence)\n\njac = jacobian(psi, x_t)\n\ndivergence = torch.zeros(x_t.shape[:-1], device=x_t.device) # shape: (B, N)\nfor b in range(x_t.shape[0]):\n for n in range(x_t.shape[1]):\n # Jacobian at point (b, n) is D x D\n J = jac[b, n, :, b, n, :] # shape: (D, D)\n divergence[b, n] = torch.trace(J)\n\nprint(\"Second Gradients (jacobian):\", divergence)\n\ndivergence = torch.zeros(x_t.shape[:-1], device=x_t.device) # shape: (B, N)\nfor b in range(x_t.shape[0]):\n for n in range(x_t.shape[1]):\n for d in range(x_t.shape[2]):\n divergence[b, n] += torch.autograd.grad(\n gradients[b, n, d], x_t, retain_graph=True, create_graph=True,\n )[0][b, n, d]\n\nprint(\"Second Gradients (autograd per input):\", divergence)\n```\n\nThis is the output:\n```\nGradients: tensor([[[-0.1571, -2.6116],\n [ 0.1571, 2.6116]]], grad_fn=)\nSecond Gradients (autograd): tensor([[[0., 0.],\n [0., 0.]]], grad_fn=)\nSecond Gradients (jacobian): tensor([[-7.1409, -7.1409]])\nSecond Gradients (autograd per input): tensor([[-7.1409, -7.1409]], grad_fn=)\n```\n\nP.S. \nSetting any entry in `grad_outputs` to 0 will return a non-zero result, the problem is only when trying to get the full second derivative.","reference_answer":"The second (and probably third, since it gives the same results) time you're computing `divergence`, you start by computing the hessian: `jac = jacobian(psi, x_t)`. This is the jacobian of the gradients with respect to the input, i.e. the hessian. Note that the result will be the same with `hessian = torch.autograd.functional.hessian(minimal_test, x_t)`\n\nThis hessian is of shape [B, N, D, B, N, D], which is why it's so expensive to compute, no matter how you do it.\n\nYou're then computing something which is the trace of parts of the hessian, and using this for divergence.\n\nThe first time you're computing the divergence, however, you're computing directly something that is equal to `hessian.sum(dim=[0, 1, 2])`. This is not the divergence, and I think it's normal for this to be equal to zero in your case.","needs_clarification":false,"thread_id":220563,"url":"https://discuss.pytorch.org/t/second-gradient-computation-with-autograd-yield-zeros/220563","created_at":"2025-06-04T07:44:05.480000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["valerian.rey"],"answered_by_ptrblck":false} {"question":"Torch not enabled with CUDA\n\nI have HP ZBook Fury 16 G10 laptop with a 12 GB NVIDIA RTX 3500 Ada GPU and I have to use this for my AI project which is written in Python language. I have already installed the CUDA Toolkit 12.8 inside the laptop, which easily recognizes the GPU. But when I load the GPU inside the Python program, the pytorch is unable to recognize the GPU. I use Windows 11.\n\nNote: I have restrictions to install anaconda in my system.\n\n[image]\n\nBoth nvcc --version command and nvidia-smi command works and shows cuda version 12.8\n\nI have followed the torch installation commands in the pytorch official website:\n\npip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128 \n\nIt installs torch 2.7.0\n\nHow to enable torch with cuda inside the python environment?","reference_answer":"The installed torch is a CPU-only build, so `torch.version.cuda` is `None`. The pip index was pointing at your company's PyPI repository, and all torch builds in that repository are CPU binaries, so even the CUDA install command installed the CPU build.\n\nUninstall all previously installed PyTorch binaries first. Then install the CUDA build with the install matrix command from pytorch.org, from a network that does not use the company repository.","needs_clarification":false,"thread_id":220565,"url":"https://discuss.pytorch.org/t/torch-not-enabled-with-cuda/220565","created_at":"2025-06-04T08:20:59.925000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4,6,7],"answer_authors":["ptrblck","shaheembacker"],"answered_by_ptrblck":true} {"question":"Vmap mlp ensemble zero grads after update\n\nI'm quite sure I did something wrong, but I'm not really sure what went wrong.\n\nBasically there are no grads on the parameters after the update (optimizer.step()) and the loss doesn't minimize ( I test it using a trivial mapping from a x ~ N(0,1) to y ~ N(0,1) where both are fixed before training) \nthe code I use is: \n```\nimport torch \nimport torch.nn as nn \nfrom torch import vmap \nfrom architectures import mlp \nfrom torch.func import stack_module_state,functional_call\nimport copy \nfrom tqdm import tqdm \nfrom torch import optim \n\nclass network(nn.Module):\n def __init__(self,embedding_size:int,num_modules:int):\n super().__init__() \n self.ensamble_modules = nn.ModuleList([mlp([embedding_size,embedding_size]) for _ in range(num_modules)])\n\n def forward(self,x:torch.Tensor) -> torch.Tensor:\n base_model = copy.deepcopy(self.ensamble_modules[0]).to(device='meta')\n\n ensemble_params, ensemble_buffers = stack_module_state(self.ensamble_modules)\n ensemble_call = lambda ensemble_params, ensemble_buffers,x: functional_call(base_model,(ensemble_params, ensemble_buffers),x)\n\n return vmap(ensemble_call)(ensemble_params, ensemble_buffers,x) \n\nif __name__ == \"__main__\":\n BATCH_SIZE = 1\n EMBEDDING_SIZE = 10\n NUM_MODULES = 4\n x = torch.randn(NUM_MODULES,BATCH_SIZE,EMBEDDING_SIZE)\n y = torch.randn(NUM_MODULES,BATCH_SIZE,EMBEDDING_SIZE)\n net = network(EMBEDDING_SIZE,NUM_MODULES)\n\n optimizer = optim.Adam(net.parameters(),lr=0.001)\n \n for _ in tqdm(range(100000),ascii=True):\n optimizer.zero_grad()\n y_pred = net(x)\n loss = nn.MSELoss()(y_pred,y)\n loss.backward()\n print(loss.item())\n optimizer.step()\n\n```","reference_answer":"`stack_module_state` returns stacked parameters and buffers that are new leaf nodes in the autograd history, unrelated to the original module parameters. They are optimizable and can be passed directly to an optimizer.","needs_clarification":false,"thread_id":220649,"url":"https://discuss.pytorch.org/t/vmap-mlp-ensemble-zero-grads-after-update/220649","created_at":"2025-06-08T14:16:02.200000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[3],"answer_authors":["hal9000"],"answered_by_ptrblck":false} {"question":"Install PyTorch for all users on Ubuntu\n\nI want to install PyTorch that can be shared by all users of a Ubuntu workstation. If I followed the command provided by \"[Start Locally](https://pytorch.org/get-started/locally/)\":\n\n> pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118\n\n, the PyTorch package will be installed to `.local/lib/python3.10/site-packages/`in my own home directory, which cannot be seen by other users. Is there any way to force the installation directory of PyTorch to be in the Ubuntu system (e.g., `/usr/lib/python3/dist-packages'` which is in `sys.path`) so that other users of the Ubuntu system could use PyTorch I installed?\n\nMy system:\n- Python version: 3.10.12\n- pip version: 22.0.2\n- Ubuntu version 22.04.5 LTS","reference_answer":"pip fell back to the per-user site directory because you don't have permission to write to the system directory. Add `sudo -H` before the install command, `pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118`. With `sudo -H`, PyTorch installs to `/usr/local/lib/python3.10/dist-packages`.","needs_clarification":false,"thread_id":220696,"url":"https://discuss.pytorch.org/t/install-pytorch-for-all-users-on-ubuntu/220696","created_at":"2025-06-10T10:38:40.115000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[1,4],"answer_authors":["zzzhhhzzzhhh"],"answered_by_ptrblck":false} {"question":"Cannot build PyTorch 2.3.1 with CUDA 12.9 on WSL2 (Ubuntu 22.04) — Missing nvToolsExt despite cuda-nvtx-12-9 installed\n\nHi all,\n\nI'm trying to build **PyTorch v2.3.1 from source** on a **WSL2 Ubuntu 22.04 environment** with the following setup:\nAny way to build pytorch 2.3.1 with cuda 12.9?\nCause 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.\n\n---\n\n### ✅ System Configuration:\n\n* **OS:** WSL2 (Ubuntu 22.04)\n* **GPU:** NVIDIA RTX 5080\n* **CUDA Driver Version:** 12.9\n* **CUDA Toolkit Version:** 12.9 (installed via APT)\n* **cuDNN:** libcudnn9 installed via APT\n* **MAGMA:** `magma-cuda121` installed via conda\n* **Python:** Conda environment, Python 3.10\n* **GCC:** 11.4\n\nEnvironment variables:\n\n```\nexport CUDA_HOME=/usr/local/cuda-12.9\nexport _GLIBCXX_USE_CXX11_ABI=1\nexport USE_CUDA=1\nexport USE_CUDNN=1\nexport USE_MKLDNN=1\nexport USE_MAGMA=1\nexport USE_NCCL=0\nexport MAX_JOBS=$(nproc)\nexport _GLIBCXX_USE_CXX11_ABI=1\nexport CMAKE_PREFIX_PATH=${CONDA_PREFIX:-\"$(dirname $(which conda))/../\"}\n```\n\n---\n\n### ⚠️ Problem:\n\nWhile building PyTorch 2.3.1 using `python setup.py develop`, the process fails with the following error:\n\n```\nCMake Error at cmake/public/cuda.cmake:70 (message):\n Failed to find nvToolsExt\n```","reference_answer":"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.","needs_clarification":false,"thread_id":220728,"url":"https://discuss.pytorch.org/t/cannot-build-pytorch-2-3-1-with-cuda-12-9-on-wsl2-ubuntu-22-04-missing-nvtoolsext-despite-cuda-nvtx-12-9-installed/220728","created_at":"2025-06-11T14:34:20.749000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Custom autograd.Function for quantized C++ simulator\n\nHello,\n\nI am trying to bypass a classic forward pass of Conv2d. I am working with QuantConv2d in Brevitas which relies on Pytorch implementation of Conv2d layer. In the forward pass the weights are quantized and using these weights, the convolution output is calculated. In the backward pass the updates are performed on floating point weights. \nInstead of regular Pytorch Conv2d implementation, I use my simulator which uses C++ and Numpy arrays to calculate the output. This breaks my computational graph and makes it impossible for the layer to learn. So I am implementing my custom autograd function which looks like this: \n```python\nclass My_Conv2d(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input, quant_kernels, fp_kernels, bias = None, padding = 0, stride = 1, dilation = 1):\n # Save for backward\n ctx.save_for_backward(input, fp_kernels, bias) # save fp_kernels because these are the ones I want to update\n ctx.padding = padding\n ctx.stride = stride\n ctx.dilation = dilation\n\n # Call my simulator\n \n out = F.conv2d(input[0], quant_kernels[0], bias, stride, padding, dilation)\n \n out = acs_conv2(input, quant_kernels, padding,stride, dilation, bias = bias)\n\n out = out + fp_kernels.sum() * 0 # this was suggested to try to connect fp_kernels to the output result for gradient propagation\n if (bias is not None):\n out = out + bias.sum() * 0\n return out\n \n @staticmethod\n def backward(ctx, grad_output):\n input, fp_kernels, bias = ctx.saved_tensors\n padding = ctx.padding\n stride = ctx.stride\n dilation = ctx.dilation\n\n grad_input = grad_weight = grad_bias = None\n \n if ctx.needs_input_grad[0]:\n grad_input = torch.nn.grad.conv2d_input(input.shape, fp_kernels, grad_output, stride, padding, dilation)\n if ctx.needs_input_grad[1]:\n grad_weight = torch.nn.grad.conv2d_weight(input, fp_kernels.shape, grad_output, stride, padding, dilation) \n if bias is not None and ctx.needs_input_grad[2]:\n grad_bias = grad_output.sum((0,2,3))\n\n return grad_input, None, grad_weight, grad_bias, None, None, None\n```\nThis still doesn't solve the problem. The weights are not updated throughout epochs. Could you please give me some guidance and help me see where I am mistaken? Any help or pointers for further reading would be very appreciated, thank you!","reference_answer":"Check that gradients flow through the custom `autograd.Function`: pass inputs that require grad directly to the function and call backward on its outputs. In this case the simulator's outputs did not keep `requires_grad=True`. Also, Brevitas QuantTensors don't propagate gradients by default, so pass only the tensor part of the QuantTensor to the function.","needs_clarification":false,"thread_id":220736,"url":"https://discuss.pytorch.org/t/custom-autograd-function-for-quantized-c-simulator/220736","created_at":"2025-06-11T17:15:25.502000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[3,4],"answer_authors":["orkan99","soulitzer"],"answered_by_ptrblck":false} {"question":"Static build that supports torchscript\n\nI made a custom build of Torch to link into an existing c++ application. This is the simplest build of torch that I could manage. To give you background, this is for a POS model that has already been trained but only needs to be implemented in the c++ program. When loading the model into the program I get the following error ...\nUnknown builtin op: aten::mul.\nCould not find any similar ops to aten::mul. This op may not exist or may not be currently supported in TorchScript.\n:\n File \"\", line 3\n\ndef mul(a : float, b : Tensor) -> Tensor:\n return b * a\n ~~~~~ <--- HERE\ndef add(a : float, b : Tensor) -> Tensor:\n return b + a\n'mul' is being compiled since it was called from 'gelu_0_9'\n File \"\", line 3\n\ndef gelu_0_9(self: Tensor) -> Tensor:\n return torch.gelu(self, approximate='none')\n ~~~~~~ <--- HERE\n\nAs far as I can tell what this means I need to force the entire object file to be linked into my binary. That isn't a problem. The problem is I don't know which library has the aten::mul (and other)_operators in it. The compile I options I am using are as follows...\n\ncmake ../ -DUSE_CUDA=OFF -DUSE_FBGEMM=OFF -DUSE_KINETO=OFF -DUSE_CUPTI_SO=OFF -DUSE_OPENMP=OFF -DUSE_NUMPY=OFF -DB UILD_SHARED_LIBS=OFF -DBUILD_CUSTOM_PROTOBUF=ON -DUSE_NNPACK=ON -DUSE_QNNPACK=OFF -DUSE_PYTORCH_QNNPACK=OFF -DUSE_ XNNPACK=OFF -DUSE_DISTRIBUTED=OFF -DUSE_MKLDNN=OFF -DBUILD_PYTHON=OFF -DBUILD_CAFFE2=OFF -DUSE_NCCL=OFF -DUSE_VALG RIND=OFF -DONNX_ML=OFF -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../../install\n\nSo everything is off. There maybe something I have turned off I need to support torchscript but for the life of me I can't find figure out what it is. Any help with either the compile or which libraries are necessary to make this work would be very helpful. Thank you.","reference_answer":"I figured it out. So for anyone who runs into this issue the first thing you are going to need to do is for the entire libtorch_cpu(or whatever gpu you are using) static library to be loaded into your binary. You can do this with ld using -Wl --whole-archive,. After you do that you will get a ton of linking errors. \n\nNow when you use cmake --install . it quite sadly only puts some of the libraries that you need in the install path. In truth you are going to need nearly all of them. They will be in your cmake build directory/lib/ Here is the order I am linking them (order matters).\n'torch_cpu',\n'torch',\n'c10',\n'protobuf',\n'onnx',\n'onnx_proto',\n'cpuinfo',\n'nnpack', \n'pthreadpool',\n'Caffe2_perfkernels_avx2', \n'Caffe2_perfkernels_avx', \n'sleef', \n'ittnotify'\n\nImportant note on sleef. It is not in the /lib directory. It is however in /sleef/lib so be sure to grab it out of there. With that I have a static cpu build with TorchScript running in a c++ application. Enjoy.","needs_clarification":false,"thread_id":220879,"url":"https://discuss.pytorch.org/t/static-build-that-supports-torchscript/220879","created_at":"2025-06-17T14:43:26.750000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ionilith"],"answered_by_ptrblck":false} {"question":"Can GradScaler and autocast be safely unified with enabled flag for both AMP and non-AMP training\n\nHi everyone,\n\nI'm currently maintaining two separate training loops for my PyTorch model: one standard (float32) and one using automatic mixed precision (AMP) with `torch.amp`.\n\nTo simplify my codebase, I would like to merge them into a single training loop using the `enabled` flag for both `torch.amp.GradScaler` and `torch.autocast`.\n\nHere's my question:\n\nIf I use this pattern:\n\n```python\nscaler = torch.amp.GradScaler(enabled=config.enable_amp)\n\nfor x, y in train_loader:\n with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=config.enable_amp):\n logits = model(x)\n loss = criterion(logits, y)\n\n scaler.scale(loss).backward()\n scaler.step(optimizer)\n scaler.update()\n optimizer.zero_grad()\n```\n\nWhen `config.enable_amp` is `False`, will the behavior be exactly equivalent to standard full-precision training, i.e.:\n\n* `scaler.scale(loss).backward()` → behaves like `loss.backward()`\n* `scaler.step(optimizer)` → behaves like `optimizer.step()`\n* `scaler.update()` → becomes a no-op\n\nIs this the correct and safe way to generalize the training loop for both AMP and non-AMP modes without duplicating logic?\n\nThanks in advance!","reference_answer":"Yes, this should be the case if you properly pass the `enabled` argument to `GradScaler` and `autocast`.\n\nE.g. [`scale()`](https://github.com/pytorch/pytorch/blob/b020971e7806bba39aecf636e59e743911831ad8/torch/amp/grad_scaler.py#L206-L207) will just return the passed `outputs` and will be a no-op, [`step()`](https://github.com/pytorch/pytorch/blob/b020971e7806bba39aecf636e59e743911831ad8/torch/amp/grad_scaler.py#L387-L388) will just call `optimizer.step()` is it's not enabled, etc.","needs_clarification":false,"thread_id":220881,"url":"https://discuss.pytorch.org/t/can-gradscaler-and-autocast-be-safely-unified-with-enabled-flag-for-both-amp-and-non-amp-training/220881","created_at":"2025-06-17T18:43:51.248000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Best way to compute C = A.inv() @ B @ A.inv().T? Linear algebra\n\nWhen we have some n-by-n matrix `A` and we want to compute `A.inv() @ b` for a vector `b`, rather than inverting `A`, we usually use `torch.solve(A, b)`. This returns the result of `A.inv() @ b` without actually inverting `A`, and it is often faster and more numerically stable.\n\nI wonder whether a similar approach exists to computing `A.inv() @ B @ A.inv().T`, where both `A` and `B` are symmetric positive definite.\n\nI tried using `torch.linalg.solve` twice, but this is often slower than inverting `A`. I also tried using the `torch.cholesky_solve`, but this is also slower than just inverting `A`.\n\nIs there something about this problem that makes inverting `A` the best option?\n\nExample code:\n\n```\nimport torch\n\nn_dim = 20\nn_points = n_dim * 50\n\nX1 = torch.randn(n_points, n_dim)\nA = X1.T @ X1\n\nX2 = torch.randn(n_points, n_dim)\nB = X2.T @ X2\n\ndef fun_invert(A, B):\n A_inv = torch.linalg.inv(A)\n return A_inv @ B @ A_inv\n\ndef fun_solve(A, B):\n C = torch.linalg.solve(A, B)\n return torch.linalg.solve(A, C.T).T\n\ndef fun_chol(A, B):\n L = torch.linalg.cholesky(A)\n C = torch.cholesky_solve(B, L)\n return torch.cholesky_solve(C.T, L).T\n\n%timeit fun_invert(A, B)\n%timeit fun_solve(A, B)\n%timeit fun_chol(A, B)\n```","reference_answer":"Hi Daniel!\n\nThe short story is that `cholesky_solve()` beats `inv()` both for larger matrices and when\nrun on the gpu. Presumably the theoretical disadvantage of `inv()` is masked by various\noverheads when the dimensions of the matrices are relatively small.\n\nThis is not surprising. The benefits of using `solve()` instead of `inv()` are reduced when\nyou are solving for \"multiple right-hand sides,\" that is, when your `B` is a matrix rather than\na vector. When you invert `A`, you are solving for the `n` columns of the inverse of `A` and\nyou can formulate this as solving for `n` right-hand sides. So calling `solve()` for `B`, where\n`B` is a square matrix of dimension `n x n` is broadly the same as inverting `A`. But for your\nuse case, you have to call `solve()` twice, whereas you only have to invert `A` once, reusing\nthe result.\n\nAs an aside, I don't think `A` being symmetric positive definite helps for your use case.\nIt does guarantee that `A` is invertible, but I'm not aware of any direct (i.e., non-iterative)\nsolvers that make use of `A` being SPD.\n\nI can reproduce your result of `cholesky_solve()` being slower (when `n` is relatively small).\nIn general, however, `cholesky_solve()` should be faster.\n\nThe harder part of the full cholesky solution is calling `cholesky()` (the decomposition) and\nthis part is called once and reused (sort of like reusing the inverse). You do have to call\n`cholesky_solve()` twice, but this is the easier part of the full cholesky solution.\n\nIt looks to me like inverting `A` wins just due to the vagaries of how the computation for\nsmaller values of `n` interacts with the cpu (and gpu) floating-point pipelines.\n\nI find that I can reproduce your result that inverting `A` is fastest for `n = 20` (your `n_dim`)\nrunning on the cpu, but running with significantly larger `n` (in the example below, `n = 200`)\nand / or on the gpu, the cholesky approach is faster.\n\nI've timed `n = 20` vs. `n = 200` and cpu vs. gpu with a timing script based on your code.\n\nHere is the script:\n\n```python\nimport torch\nprint (torch.__version__)\n\nimport time\n\ntorch.manual_seed (2025)\n\ndevice = 'cpu'\nif torch.cuda.is_available(): device = 'cuda'\nif device == 'cuda':\n print (torch.version.cuda)\n print (torch.cuda.get_device_name())\n\n# n_dim = 20\nn_dim = 200\nn_points = n_dim * 50\nn_batch = 10\n\nprint ('device:', device, ' n_dim:', n_dim)\n\nn_warm = 5\nn_time = 1000\n\n# create batches of SPD A and B\nX1 = torch.randn(n_batch, n_points, n_dim, device = device)\nA = X1.permute (0, 2, 1) @ X1\nX2 = torch.randn(n_batch, n_points, n_dim, device = device)\nB = X2.permute (0, 2, 1) @ X2\n\ndef fun_batch_invert (A, B):\n for a, b in zip (A, B):\n a_inv = torch.linalg.inv (a)\n _ = a_inv @ b @ a_inv\n\ndef fun_batch_solve (A, B):\n for a, b in zip (A, B):\n c = torch.linalg.solve (a, b)\n _ = torch.linalg.solve (a, c.T).T\n\ndef fun_batch_chol (A, B):\n for a, b in zip (A, B):\n l = torch.linalg.cholesky (a)\n c = torch.cholesky_solve (b, l)\n _ = torch.cholesky_solve (c.T, l).T\n\n# time invert\nfor _ in range (n_warm):\n fun_batch_invert (A, B)\nif device == 'cuda': torch.cuda.synchronize()\ntStart = time.time()\nfor _ in range (n_time):\n fun_batch_invert (A, B)\nif device == 'cuda': torch.cuda.synchronize()\ntEnd = time.time()\nprint ('time_inv: {:.4f}'.format (1000 * (tEnd - tStart) / (n_batch * n_time)))\n\n# time solve\nfor _ in range (n_warm):\n fun_batch_solve (A, B)\nif device == 'cuda': torch.cuda.synchronize()\ntStart = time.time()\nfor _ in range (n_time):\n fun_batch_solve (A, B)\nif device == 'cuda': torch.cuda.synchronize()\ntEnd = time.time()\nprint ('time_sol: {:.4f}'.format (1000 * (tEnd - tStart) / (n_batch * n_time)))\n\n# time chol\nfor _ in range (n_warm):\n fun_batch_chol (A, B)\nif device == 'cuda': torch.cuda.synchronize()\ntStart = time.time()\nfor _ in range (n_time):\n fun_batch_chol (A, B)\nif device == 'cuda': torch.cuda.synchronize()\ntEnd = time.time()\nprint ('time_cho: {:.4f}'.format (1000 * (tEnd - tStart) / (n_batch * n_time)))\n```\n\nAnd here is its output for the four different runs:\n\n```text\n2.7.1+cu128\ndevice: cpu n_dim: 20\ntime_inv: 0.0244\ntime_sol: 0.0364\ntime_cho: 0.0341\n\n2.7.1+cu128\n12.8\nNVIDIA RTX 3000 Ada Generation Laptop GPU\ndevice: cuda n_dim: 20\ntime_inv: 0.1210\ntime_sol: 0.1847\ntime_cho: 0.0851\n\n2.7.1+cu128\ndevice: cpu n_dim: 200\ntime_inv: 0.5564\ntime_sol: 0.8801\ntime_cho: 0.4294\n\n2.7.1+cu128\n12.8\nNVIDIA RTX 3000 Ada Generation Laptop GPU\ndevice: cuda n_dim: 200\ntime_inv: 0.4634\ntime_sol: 0.8400\ntime_cho: 0.3604\n```\n\nA couple of comments:\n\nThe cpu timings jump around a lot more than the gpu timings. I imagine this is because\nthere are various \"random\" processes running in the background competing for the cpu.\n\nEmpirically, `n = 200` is still rather small in the context of the gpu. The benefit of the gpu\nbecomes dramatically more pronounced for larger `n`.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":220883,"url":"https://discuss.pytorch.org/t/best-way-to-compute-c-a-inv-b-a-inv-t-linear-algebra/220883","created_at":"2025-06-17T19:59:14.950000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Why does autograd.backward go one edge further than `inputs`?\n\nConsider the following example (REPL pasteable)\n\n```\nimport torch\n\nclass LoggingFn(torch.autograd.Function):\n @staticmethod\n def forward(ctx, x):\n ctx.save_for_backward(x)\n return x * 2\n @staticmethod\n def backward(ctx, grad_output):\n print(\"Backward called on LoggingFn\")\n return grad_output * 2\n\na = torch.tensor(1.0, requires_grad=True)\nb = LoggingFn.apply(a)\nc = LoggingFn.apply(b)\nloss = LoggingFn.apply(c)\n\nloss.backward(inputs=[c])\n\nprint(\"a.grad =\", a.grad)\nprint(\"b.grad =\", b.grad)\nprint(\"c.grad =\", c.grad)\n```\nprints\n```\n>>> loss.backward(inputs=[c])\nBackward called on LoggingFn\nBackward called on LoggingFn\n>>> print(\"a.grad =\", a.grad)\na.grad = None\n>>> print(\"b.grad =\", b.grad)\nb.grad = None\n>>> print(\"c.grad =\", c.grad)\nc.grad = tensor(2.)\n```\n`LoggingFn.backward` is called twice, meaning it backpropogates back to `b`. It was correct to not go all the way back to `a`, but why didn't it stop at `c`? Is this incorrect behavior, or is there a reason to go one edge further than needed?","reference_answer":"The extra backprop shouldn't happen, but it is the current behavior due to the simplicity of the implementation (see the note in the docs). If you have a performance-sensitive use case, file an issue.\n\nTo avoid calling the extra node, call `torch.autograd.grad` instead of `torch.autograd.backward` or `tensor.backward`. The extra node is then not called, but the `.grad` fields have to be accumulated manually.","needs_clarification":false,"thread_id":220886,"url":"https://discuss.pytorch.org/t/why-does-autograd-backward-go-one-edge-further-than-inputs/220886","created_at":"2025-06-17T22:27:04.846000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[3,4],"answer_authors":["soulitzer","valerian.rey"],"answered_by_ptrblck":false} {"question":"TruncatedNormal loc argument\n\nI just discovered the truncated normal distribution and I'm trying to use torchrl TruncatedNormal but I can't find anythin about \"location\" in the paper that introduced this idea and I don't understand torchrl's documentation :\n\n> * **loc** ([*torch.Tensor*]) – normal distribution location parameter\n\nCan someone explain more in detail what that parameter is ? Is it like the *mean* parameter of torch.normal ?","reference_answer":"Hi @ptrblck (and Alice)!\n\nYes, this is correct. `loc` is the same as `mean` (and `scale` is `std`). For the `Normal`\ndistribution (but not other distributions), it's just a different name for the same thing.\n\nIt make sense to use a different name because, for example, the actual mean of an\n(asymmetrically-truncated) `TruncatedNormal` distribution will not be `loc` -- that is\nthe `mean` of the underlying `Normal` distribution -- and the actual standard deviation\nwill not be `scale` -- the `std` of the underlying `Normal` distribution.\n\n`torchrl.modules.TruncatedNormal` follows `torch.distributions.normal.Normal`\nfor which:\n\n> **loc** (*float* *or* *Tensor*) – mean of the distribution (often referred to as mu)\n\n(I believe that`torch.distributions.Normal` uses `loc` and `scale`, rather than `mean`\nand `std`, because there are other distributions in `torch.distributions` for which the\nconventional `loc` and `scale` parameters aren't equal to the mean and standard deviation.\nOn the other hand, `torch.normal()` calls the two parameters `mean` and `std`.)\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":220898,"url":"https://discuss.pytorch.org/t/truncatednormal-loc-argument/220898","created_at":"2025-06-18T09:07:00.537000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Profiling what happens in thread\n\nIs there a way to record what happens in a thread triggered inside the profile block ?\n\nFor instance \n\n``` python\nimport threading\nimport time\n\nimport torch\nfrom torch.profiler import record_function\n\ndef worker():\n for _ in range(20):\n with record_function(\"worker_random\"):\n torch.rand(2048, 2048)\n time.sleep(0.05)\n\nwith torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU]) as p:\n t = threading.Thread(target=worker)\n t.start()\n for _ in range(10):\n with record_function(\"main_thread_empty\"):\n torch.empty(1024, 1024)\n time.sleep(0.1)\n t.join()\np.export_chrome_trace(\"trace.json\")\n```\n\nIn the trace I only see the \"main_thread_empty\" and the profiler as seen in the following screenshot:\n[image]","reference_answer":"Actually found the \"profile_all_threads\" option that can be added, it works well this this, at least for this simple scenario:\n\n```\nimport threading\nimport time\n\nimport torch\nfrom torch.profiler import _ExperimentalConfig, record_function\n\nif __name__ == \"__main__\":\n\n def worker():\n for _ in range(20):\n with record_function(\"worker_random\"):\n torch.rand(2048, 2048)\n time.sleep(0.05)\n\n with torch.profiler.profile(\n activities=[torch.profiler.ProfilerActivity.CPU],\n experimental_config=_ExperimentalConfig(profile_all_threads=True),\n ) as p:\n t = threading.Thread(target=worker)\n t.start()\n for _ in range(10):\n with record_function(\"main_thread_empty\"):\n torch.empty(1024, 1024)\n\n time.sleep(0.1)\n t.join()\n p.export_chrome_trace(\"trace.json\")\n```\n\nWill give\n\n[image]","needs_clarification":false,"thread_id":220919,"url":"https://discuss.pytorch.org/t/profiling-what-happens-in-thread/220919","created_at":"2025-06-19T13:19:33.147000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["Valentin_Thorey"],"answered_by_ptrblck":false} {"question":"Memory bloat in gradient descent model\n\nI'm running into memory bloat issues when backpropagating through this loop-heavy simulation. Even though the code looks simple, the backward pass consumes a *lot* of memory. I'd like to understand if there is a way that I can trim the tree at all or if because I am using ODEs where the current state depends on the previous state this is the most efficient implementation. For context, this model currently utilizes 14gb. When I calculate how much it should be using by hand, accounting for the auto grad nodes, it shouldn't even take 1gb.\n\nAny insight into whether the loop is causing unnecessary graph storage, or how to refactor it to reduce memory overhead, would be much appreciated!\n\n```python\nimport torch\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nimport gc\nfrom torch.cuda.amp import autocast\n\nclass LIF_ODE(nn.Module):\n def __init__(self):\n super().__init__()\n self.dt = 0.0001\n self.tau = 0.02\n self.V_th = 1.0\n self.V_reset = 0.0\n self.V_rest = 0.0\n self.input_current = nn.Parameter(torch.tensor(1.5, dtype=torch.float32))\n\n def forward(self):\n T = 3500000 \n V = torch.zeros(T, dtype=torch.float32)\n spikes = torch.zeros(T, dtype=torch.float32)\n v_t = self.V_rest\n\n for t in range(1, T):\n dv = (-v_t + self.input_current) * (self.dt / self.tau)\n v_t = v_t + dv\n\n if v_t >= self.V_th:\n spikes[t] = 1.0\n v_t = self.V_reset\n\n V[t] = v_t\n\n return spikes\n\ndef main():\n model = LIF_ODE()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01, betas=(0.0, 0.999))\n num_epochs = 1\n target_spikes = torch.tensor(50.0, dtype=torch.float32)\n\n for epoch in range(num_epochs):\n optimizer.zero_grad()\n\n with autocast():\n output = model()\n\n fr = output.sum() / 10 / 3\n loss = (fr - target_spikes) ** 2\n loss.backward()\n optimizer.step()\n\n gc.collect()\n print(f\"Epoch {epoch}: Loss = {loss.item()}\", flush=True)\n\nif __name__ == \"__main__\":\n main()\n```","reference_answer":"The graph grows by a few nodes on every loop iteration, so with 3.5 million iterations the bookkeeping adds up. About 4000 bytes per iteration is a reasonable overhead for PyTorch, which is designed for networks with fewer layers and large tensors rather than millions of layers.\n\nThe output `spikes` does not carry `requires_grad` and is not part of the computation graph. It is also not usefully differentiable, because it depends on a step function of `v_t`. `sigmoid()` can serve as a differentiable approximation to that step, though this does not reduce the size of the graph.\n\nComputing the gradients manually instead of with autograd removed the memory bloat: memory dropped from 14 GB to under 100 MB.","needs_clarification":false,"thread_id":220931,"url":"https://discuss.pytorch.org/t/memory-bloat-in-gradient-descent-model/220931","created_at":"2025-06-20T00:33:08.976000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4,5],"answer_authors":["IsaacBoyd","KFrank"],"answered_by_ptrblck":false} {"question":"PyTorch support for sm_120: NVIDIA GeForce RTX 5060\n\n**Issue:** PyTorch not supporting CUDA compute capability 12.0 (sm_120), required for the NVIDIA GeForce RTX 5060.\n\n**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.\n\n**System Info:**\n- GPU: NVIDIA GeForce RTX 5060 (sm_120)\n- OS: [Windows 11 with Ubuntu 24.04 under WSL2]\n- Python: 3.10.x\n- CUDA Toolkit: 12.1 / 12.6\n- Driver: 550.x / 576.x\n- PyTorch tried: 2.3.1+cu121 and 2.8.0.dev20250618+cu128\n\n**Symptoms:**\n- `torch.cuda.is_available()` = True\n- But tensor operations raise: \n `RuntimeError: CUDA error: no kernel image is available for execution on the device`\n\n**Request:**\nSolution or workaround?\n\nThanks!","reference_answer":"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. \n\nThis 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.","needs_clarification":false,"thread_id":220941,"url":"https://discuss.pytorch.org/t/pytorch-support-for-sm-120-nvidia-geforce-rtx-5060/220941","created_at":"2025-06-20T07:36:30.805000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Torch.matmul calls nvjet_tst kernel in torch 2.7.1\n\nHi, 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. \nDoes anyone know why this behaviour is happening? \nThanks a lot for the kind help!","reference_answer":"This is expected as cuBLAS selects the fastest kernel for the given workload via its heuristics.","needs_clarification":false,"thread_id":220947,"url":"https://discuss.pytorch.org/t/torch-matmul-calls-nvjet-tst-kernel-in-torch-2-7-1/220947","created_at":"2025-06-20T17:12:34.466000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Variable versioning error at backward\n\nHi,\n\nI'm trying to write a policy net for REINFORCE, but I'm running into a `backward()` variable versioning issue. A (relatively) small reproducible snippet is:\n\n```py\nimport torch.nn.functional as F\nimport numpy as np\nimport random\nimport torch\n\nK = 4\nG = K**2 // 4 + 1\n\nMAX_EPISODE_LEN = 2\nNUM_EPISODES = 1\n\nclass PolicyNetA(torch.nn.Module):\n def __init__(self, G: int, KS: int, cnt_iters: int):\n super(PolicyNetA, self).__init__()\n\n self.cnt_iters = cnt_iters\n self.G = G\n\n self.conv_z = torch.nn.ModuleList([torch.nn.Conv3d(in_channels=1, out_channels=G, kernel_size=(G, 1, 1)) for _ in range(cnt_iters)])\n\n # this outputs a (G, G, G) tensor, same as input.\n def forward(self, x: torch.tensor):\n for i in range(self.cnt_iters):\n x_unsq = x.unsqueeze(0).unsqueeze(0)\n\n # casting reshape() instead of view() didn't help.\n # F.relu has inplace set to False by default.\n x = F.relu(self.conv_z[i](x_unsq).view(self.G, self.G, self.G))\n\n return x\n\ndef rollout_episode(pnet, X: torch.tensor):\n policy_proba_dists = []\n\n for t in range(MAX_EPISODE_LEN):\n policy_proba_dist = pnet(X)\n policy_proba_dists.append(policy_proba_dist)\n\n # X should be detached from the current computation graph for the next forward call.\n X = torch.randn(G, G, G).round()\n\n return policy_proba_dists\n\ndef main():\n with torch.autograd.set_detect_anomaly(True):\n pnet = PolicyNetA(G = G, KS = 3, cnt_iters = 2)\n optimizer = torch.optim.Adam(params = pnet.parameters())\n\n for cnt_episode in range(1, NUM_EPISODES + 1):\n X = torch.randn(G, G, G).round()\n policy_proba_dists = rollout_episode(pnet, X)\n\n for t in range(MAX_EPISODE_LEN):\n gain_log_policy_value = -0.1 * torch.log(policy_proba_dists[t][0, 2, 1] + 1e-10)\n\n optimizer.zero_grad()\n gain_log_policy_value.backward()\n optimizer.step()\n\nif __name__ == \"__main__\":\n main()\n```\n\nThe error is: `RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [5, 1, 5, 1, 1]] is at version 2; expected version 1 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient.`\n\nI guess the actual error occurs somewhere inside `Conv3d`, as its final resulting shape is `[1, 5, 1, 5, 5]`.\n\nCasting `reshape` instead of view after the convolution doesn't help.\n\nThe error goes away if we only rollout for one cycle instead of two: `MAX_EPISODE_LEN = 1`.\n\nI may have used `torch.nn.ModuleList` incorrectly, but I'm not sure what would the correct usage be. I tried to have two different `Conv3d` instances, unwrapped by a `ModuleList`, but the error persists.\n\nThank you for your help!","reference_answer":"You are trying to call `backward` on a created computation graph (coming from `policy_proba_dists`) with already updated trainable parameters. [This post](https://discuss.pytorch.org/t/struggling-with-a-runtime-error-related-to-in-place-operations/102222/6?u=ptrblck) describes the issue trying to use stale forward activations in more details.\n\nIn your case, the `weight` of the conv layer was already updated and thus cannot be used in the `backward` call in the second iteration to compute the gradients.","needs_clarification":false,"thread_id":220965,"url":"https://discuss.pytorch.org/t/variable-versioning-error-at-backward/220965","created_at":"2025-06-21T12:51:17.042000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Why the reserved memory is much larger than occupied memory?\n\n[image]\nFor my understanding, the y axis is the occupied memory. The part of the allocated memory that is actually being used to store data at a given moment — like active tensors, gradients, etc. Instead of frequently asking CUDA to allocate and free memory, the allocated memory store data to be used. If I use `torch.cuda.empty_cache()` to delete the cache memory (i.e. the extra part of reserved memory), will it affect the speed?","reference_answer":"Yes, clearing the cache will synchronize your code and free the cached memory (which is also slowing down your code). The next iteration will then use the slow and synchronizing `cudaMalloc` calls (assuming the default caching allocator is used) to allocate the needed memory.","needs_clarification":false,"thread_id":221063,"url":"https://discuss.pytorch.org/t/why-the-reserved-memory-is-much-larger-than-occupied-memory/221063","created_at":"2025-06-25T18:45:20.234000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Call backward() twice does not incur errors\n\n```\nx=torch.rand(2,2,requires_grad=True)\ny=x+2\n# y=x*2\nz=torch.sum(y)\nzz=z*2\nz.backward()\nzz.backward()\n```\ncall backward() twice does not incur errors. However, if i use` y=x*2` rather than `y=x+2`, the error occurs, why?\n```\nx=torch.rand(2,2,requires_grad=True)\n#y=x+2\ny=x*2\nz=torch.sum(y)\nzz=z*2\nz.backward()\nzz.backward()\n```\n[image]","reference_answer":"x * 2 saves a value (2) for backward, and the first time backward happens, this value is cleared\nthis causes the second backward to error unless retain_graph=True\n\nx + 2 does not have the same problem because it doesn't need to save any values in order to compute the backward","needs_clarification":false,"thread_id":221127,"url":"https://discuss.pytorch.org/t/call-backward-twice-does-not-incur-errors/221127","created_at":"2025-06-28T08:18:46.513000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["soulitzer"],"answered_by_ptrblck":false} {"question":"Install failure on Debian 12.11\n\nInstalling Pytorch on fresh Debian 12.11.\nAfter 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. \n\nI am getting an error that appears to stem from this line in the below quoted output.\n\n*Discarding https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl#sha256=04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d (from https://download.pytorch.org/whl/cu128/typing-extensions/): Requested typing-extensions>=4.10.0 from https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl#sha256=04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d (from torch) has inconsistent Name: expected 'typing-extensions', but metadata has 'typing_extensions'*\n\nInitially I ran the command from https://pytorch.org/get-started/locally/ verbatim: it seems to be attempting two minor versions of Pytorch 2.7.\n\nThen I tried same command but specified torch version, first saying 2.7.0, then saying 2.7.1\n\nIs this a conflict between Debian's name for the typing extension and Pytorch's name? Any idea how to resolve?\n\nEdit: interestingly if I attempt to install for CPU and not for CUDA, then the same \"Discarding...\" message is printed but the install succeeds, and I can make use of pytorch in a python session. \n\nLog of the attempt:\n\n```\n(pytorch2.7_cuda12.8) emerth@debian:~$ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128\nLooking in indexes: https://download.pytorch.org/whl/cu128\nCollecting torch\n Obtaining dependency information for torch from https://download.pytorch.org/whl/cu128/torch-2.7.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata\n Downloading https://download.pytorch.org/whl/cu128/torch-2.7.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (29 kB)\nCollecting torchvision\n Obtaining dependency information for torchvision from https://download.pytorch.org/whl/cu128/torchvision-0.22.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata\n Downloading https://download.pytorch.org/whl/cu128/torchvision-0.22.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (6.1 kB)\nCollecting torchaudio\n Obtaining dependency information for torchaudio from https://download.pytorch.org/whl/cu128/torchaudio-2.7.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata\n Downloading https://download.pytorch.org/whl/cu128/torchaudio-2.7.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (6.6 kB)\nCollecting filelock\n Obtaining dependency information for filelock from https://download.pytorch.org/whl/filelock-3.13.1-py3-none-any.whl.metadata\n Downloading https://download.pytorch.org/whl/filelock-3.13.1-py3-none-any.whl.metadata (2.8 kB)\nCollecting typing-extensions>=4.10.0\n Obtaining dependency information for typing-extensions>=4.10.0 from https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl.metadata\n Downloading https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl.metadata (3.0 kB)\nDiscarding https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl#sha256=04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d (from https://download.pytorch.org/whl/cu128/typing-extensions/): Requested typing-extensions>=4.10.0 from https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl#sha256=04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d (from torch) has inconsistent Name: expected 'typing-extensions', but metadata has 'typing_extensions'\nCollecting torch\n Obtaining dependency information for torch from https://download.pytorch.org/whl/cu128/torch-2.7.0%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata\n Downloading https://download.pytorch.org/whl/cu128/torch-2.7.0%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (29 kB)\nERROR: Cannot install torch==2.7.0+cu128 and torch==2.7.1+cu128 because these package versions have conflicting dependencies.\n\nThe conflict is caused by:\n torch 2.7.1+cu128 depends on typing-extensions>=4.10.0\n torch 2.7.0+cu128 depends on typing-extensions>=4.10.0\n\nTo fix this you could try to:\n1. loosen the range of package versions you've specified\n2. remove package versions to allow pip attempt to solve the dependency conflict\n\nERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts\n(pytorch2.7_cuda12.8) emerth@debian:~$ pip3 install torch==2.7.1+cu128 torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128\nLooking in indexes: https://download.pytorch.org/whl/cu128\nCollecting torch==2.7.1+cu128\n Obtaining dependency information for torch==2.7.1+cu128 from https://download.pytorch.org/whl/cu128/torch-2.7.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata\n Using cached https://download.pytorch.org/whl/cu128/torch-2.7.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (29 kB)\nCollecting torchvision\n Obtaining dependency information for torchvision from https://download.pytorch.org/whl/cu128/torchvision-0.22.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata\n Using cached https://download.pytorch.org/whl/cu128/torchvision-0.22.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (6.1 kB)\nCollecting torchaudio\n Obtaining dependency information for torchaudio from https://download.pytorch.org/whl/cu128/torchaudio-2.7.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata\n Using cached https://download.pytorch.org/whl/cu128/torchaudio-2.7.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (6.6 kB)\nCollecting filelock\n Obtaining dependency information for filelock from https://download.pytorch.org/whl/filelock-3.13.1-py3-none-any.whl.metadata\n Using cached https://download.pytorch.org/whl/filelock-3.13.1-py3-none-any.whl.metadata (2.8 kB)\nCollecting typing-extensions>=4.10.0\n Obtaining dependency information for typing-extensions>=4.10.0 from https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl.metadata\n Using cached https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl.metadata (3.0 kB)\nDiscarding https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl#sha256=04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d (from https://download.pytorch.org/whl/cu128/typing-extensions/): Requested typing-extensions>=4.10.0 from https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl#sha256=04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d (from torch==2.7.1+cu128) has inconsistent Name: expected 'typing-extensions', but metadata has 'typing_extensions'\nERROR: Could not find a version that satisfies the requirement typing-extensions>=4.10.0 (from torch) (from versions: 4.4.0, 4.8.0, 4.9.0, 4.12.2)\nERROR: No matching distribution found for typing-extensions>=4.10.0\n(pytorch2.7_cuda12.8) emerth@debian:~$ pip3 install torch==2.7.0+cu128 torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128\nLooking in indexes: https://download.pytorch.org/whl/cu128\nCollecting torch==2.7.0+cu128\n Obtaining dependency information for torch==2.7.0+cu128 from https://download.pytorch.org/whl/cu128/torch-2.7.0%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata\n Using cached https://download.pytorch.org/whl/cu128/torch-2.7.0%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (29 kB)\nCollecting torchvision\n Obtaining dependency information for torchvision from https://download.pytorch.org/whl/cu128/torchvision-0.22.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata\n Using cached https://download.pytorch.org/whl/cu128/torchvision-0.22.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (6.1 kB)\nCollecting torchaudio\n Obtaining dependency information for torchaudio from https://download.pytorch.org/whl/cu128/torchaudio-2.7.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata\n Using cached https://download.pytorch.org/whl/cu128/torchaudio-2.7.1%2Bcu128-cp311-cp311-manylinux_2_28_x86_64.whl.metadata (6.6 kB)\nCollecting filelock\n Obtaining dependency information for filelock from https://download.pytorch.org/whl/filelock-3.13.1-py3-none-any.whl.metadata\n Using cached https://download.pytorch.org/whl/filelock-3.13.1-py3-none-any.whl.metadata (2.8 kB)\nCollecting typing-extensions>=4.10.0\n Obtaining dependency information for typing-extensions>=4.10.0 from https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl.metadata\n Using cached https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl.metadata (3.0 kB)\nDiscarding https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl#sha256=04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d (from https://download.pytorch.org/whl/cu128/typing-extensions/): Requested typing-extensions>=4.10.0 from https://download.pytorch.org/whl/typing_extensions-4.12.2-py3-none-any.whl#sha256=04e5ca0351e0f3f85c6853954072df659d0d13fac324d0072316b67d7794700d (from torch==2.7.0+cu128) has inconsistent Name: expected 'typing-extensions', but metadata has 'typing_extensions'\nERROR: Could not find a version that satisfies the requirement typing-extensions>=4.10.0 (from torch) (from versions: 4.4.0, 4.8.0, 4.9.0, 4.12.2)\nERROR: No matching distribution found for typing-extensions>=4.10.0\n(pytorch2.7_cuda12.8) emerth@debian:~$\n(pytorch2.7_cuda12.8) emerth@debian:~$ pip3\n```","reference_answer":"Try to update `pip` as the same error messages are related to old `pip` releases.","needs_clarification":false,"thread_id":221188,"url":"https://discuss.pytorch.org/t/install-failure-on-debian-12-11/221188","created_at":"2025-07-01T01:56:16.664000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Using system NCCL when building PyTorch from source\n\nI'm trying to build PyTorch from source on an Ubuntu machine in a miniconda environment. \n\nI'm trying to use the existing NCCL libraries installed on the system. I set the USE_SYSTEM_NCCL=1 but it still compiles and links with the NCCL submodule in the PyTorch repository.\n\nI took a look at this issue - https://github.com/pytorch/pytorch/issues/32286 which states that this is expected behavior. Is there any way to configure the build to use the system NCCL despite being built in a conda env? Or should I just build manually without conda? I don't want to mess up any dependencies other users may have since this is a machine accessed by several users.","reference_answer":"I now see that there is a function called git_checkout_nccl() which is called unconditionally in build_pytorch_libs in commit e2d141db that I have checked out. However, the later commits have added a check for the USE_SYSTEM_NCCL and USE_NCCL flags before calling it.\n\nAdditionally setting USE_SYSTEM_NCCL and USE_NCCL in my shell environment instead of in setup.py seems to correctly initialize the variables in my build.\n\nThis seems to have fixed my issue :slight_smile:","needs_clarification":false,"thread_id":221217,"url":"https://discuss.pytorch.org/t/using-system-nccl-when-building-pytorch-from-source/221217","created_at":"2025-07-02T00:13:55.040000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["BigFeetTinyBrain"],"answered_by_ptrblck":false} {"question":"Model seems to peek into target sequence and cheat during training despite using masking\n\nI am using CNN-transformer hybrid architecture to detect handwritten equation and convert them to LaTex strings. All target sequences (the actual LaTex representation of a handwritten equation) are padded/truncated to `maxSeqLen` (max. seqeunce length). \n\nThis is how I generate the target sequence's mask and target sequence's padding mask:\n\n```\ndef generate_tgt_mask(maxSeqLen: int) -> torch.Tensor :\n\tmask = (torch.triu(torch.ones((maxSeqLen, maxSeqLen))) == 1)\n\tmask = mask.transpose(0, 1).float()\n\tmask = mask.masked_fill(mask == 0, float('-inf'))\n\tmask = mask.masked_fill(mask == 1, float(0.0))\n\treturn mask\n\ndef generate_padding_mask(tgt, padTokenIdx = 0) -> torch.Tensor:\n\treturn (tgt == padTokenIdx)\n```\n\nTraining loop snippet:\n```\n\tfor idx, (src, tgt, trainEq, trainFname) in enumerate(trainDataLoader):\n\t\tcurrTrainBatchAcc = 0\n\t\tcurrTrainBatchLoss = 0\n\n\t\ttrainSrc, trainTgt = src.cuda(), tgt.cuda()\n\t\ttgt_padding_mask = generate_padding_mask(trainTgt, tokenizer.vocab['[PAD]']).cuda()\n\t\tmodel.train()\n\t\t\n\t\ttrainPred: torch.Tensor = model(trainSrc, trainTgt, tgt_mask, tgt_padding_mask)\n\n trainLoss = loss_fn(trainPred.view(-1, vocabSize), trainTgt.view(-1))\n\n\t\topt.zero_grad()\n\t\ttrainLoss.backward()\n\t\topt.step()\n\n```\n\nInference code:\n```\nmodel.eval()\nwith torch.inference_mode():\n\ttgt_mask: torch.Tensor = generate_tgt_mask(maxSeqLen).cuda()\n\tfor idx, (src, tgt, eq, fPath) in enumerate(valDataLoader):\n\t\tsrc, tgt = src.cuda(), tgt.cuda()\n\t\t\n\t\tinf_tgt = torch.ones((1, maxSeqLen), dtype=torch.int64).to(device)\n\t\tinf_tgt[:,0] = tokenizer.vocab['[SOS]']\n\t\tinf_tgt[:,1:] *= tokenizer.vocab['[PAD]']\n\n\t\tfor i in range(1, maxSeqLen):\n inf_tgt_padding_mask = generate_padding_mask(inf_tgt, padTokenIdx=0).to(device)\n\t\t\tpred: torch.Tensor = model(src, tgt, tgt_mask, inf_tgt_padding_mask)\n\t\t\tpredToken = torch.argmax(pred.softmax(dim= -1), dim= -1)\n\t\t\tinf_tgt[0,i] = predToken[0,i]\n\t\t\tif(predToken[0,i].cpu() == tokenizer.vocab['[EOS]']):\n\t\t\t\tbreak\n\t\tbreak\n```\n\nI have tried setting the target sequence mask and target sequence padding mask to None, and it still doesn't work. I have also checked the mask generation functions and they seem to be fine as well. **However, when I pass the actual target sequence during inference, the model works fine, and it predicts the sequence properly**. I suspect the model is cheating somehow.\n\nWhy is this happening and what do I do?","reference_answer":"In autoregressive training you need to *shift* things. If your target sequence input is [0,1,2,3] its predictions are [1,2,3,4]. You need to tokenize your target to max length + 1, then pass `tgt[ ..., : -1]` as input and use `tgt[ ..., 1 : ]` as the second argument to your loss function.\n\nThen in your inference code you should start the range at zero instead of one, and do `inf_tgt[0,i+1] = predToken[0,i]`","needs_clarification":false,"thread_id":221224,"url":"https://discuss.pytorch.org/t/model-seems-to-peek-into-target-sequence-and-cheat-during-training-despite-using-masking/221224","created_at":"2025-07-02T09:13:44.619000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Avelina9X"],"answered_by_ptrblck":false} {"question":"Tensor hooks for gradients from each path in the autograd graph\n\nHi all,\n\nI'm working on a project where I need to manipulate gradients as they flow backward through each computational path in a model's computation graph. Currently, I know that PyTorch's `.register_hook` method allows you to manipulate gradients for a tensor during backpropagation, but this hook is only called after gradients from all incoming paths have been summed together.\n\nI'd like to \"hook in\" before this summation step, so that I can observe or modify gradient contributions coming from each computational path (branch) individually, before they are combined at a given node in the graph.\n\nI don't think it's possible to do this with PyTorch's API, if anyone has suggestions that don't involve modifying the C++ internals please let me know. I'm also wondering if anyone has any thoughts on if there would be demand for this kind of feature as an addition to the hook system - would it make sense as a feature request?","reference_answer":"Can you also try gradient edges?\nWriting a minimal example\n\n```\nimport torch\nfrom torch.autograd.graph import get_gradient_edge\n\ndef capture_individual_gradients(tensor, names=None):\n \"\"\"\n Capture gradient contributions from each computational path\n before they're summed.\n \n Args:\n tensor: The tensor to monitor\n names: Optional list of names for each dependent operation\n \n Returns:\n dict: Maps operation names/indices to their gradient contributions\n \"\"\"\n gradients = {}\n \n # Find all operations that depend on this tensor\n dependent_ops = []\n for op in tensor.grad_fn.next_functions if tensor.grad_fn else []:\n if op[0] is not None:\n dependent_ops.append(op)\n \n # Alternative: manually track operations\n def track_operation(output, name=None):\n edge = get_gradient_edge(output)\n \n def hook(grad_inputs, grad_outputs):\n # grad_inputs[0] contains the gradient flowing through this path\n grad_key = name if name else f\"op_{len(gradients)}\"\n gradients[grad_key] = grad_inputs[0].clone() if grad_inputs[0] is not None else None\n \n edge.node.register_hook(hook)\n return output\n \n return gradients, track_operation\n\n# Example usage\na = torch.tensor(5., requires_grad=True)\n\n# Set up gradient capture\ngradients, track = capture_individual_gradients(a)\n\n# Track each operation\nb1 = track(2 * a, \"multiply_by_2\")\nb2 = track(3 * a, \"multiply_by_3\")\nb3 = track(a ** 2, \"square\")\n\n# Compute gradients\nloss = b1 + b2 + b3\nloss.backward()\n\nprint(\"Individual gradients before summation:\")\nfor name, grad in gradients.items():\n print(f\"{name}: {grad}\")\nprint(f\"\\nSummed gradient at 'a': {a.grad}\")\n```","needs_clarification":false,"thread_id":221273,"url":"https://discuss.pytorch.org/t/tensor-hooks-for-gradients-from-each-path-in-the-autograd-graph/221273","created_at":"2025-07-03T20:55:02.371000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["Hamza_Javaid"],"answered_by_ptrblck":false} {"question":"Very slow training with nn.Embedding\n\nI use `nn.Embedding` initialized with GloVe embeddings and I want to further train the embeddings when I fine tune on my task. The GloVe embeddings are a bit more 2.1M, and their dimension is 300. The training becomes extremely slow. I think that this might be due to the size of the `Embedding` table. I don't know if this is relatable, but I have small relatively small sentences (many of them might be less than 15 words). The weights of `Embedding` change only for the words fount in the batch right? Is this very slow training normal?","reference_answer":"Do you really have a vocabulary size of 2.1 million? Or do you load all pretrained vectors into your embedding layer?\n\nYou only need the vectors for the words in your vocabulary? So if you have, say, 100k words/tokens, the input size of the embedding layer only needs to be 100k.\n\nEven if your whole vocabulary is 2.1 million tokens, try considering only the, say, 100k most frequent ones. Due to Zipf's Law, the 100k most frequent tokens probably cover 98% of your dataset.","needs_clarification":false,"thread_id":221336,"url":"https://discuss.pytorch.org/t/very-slow-training-with-nn-embedding/221336","created_at":"2025-07-07T14:32:21.089000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["vdw"],"answered_by_ptrblck":false} {"question":"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\n\nHello exeryone! \nWhen using `deepspeed` training job, I get this error:\n```\n[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\n[rank0]: ncclUnhandledCudaError: Call to CUDA function failed.\n[rank0]: Last error:\n[rank0]: Cuda failure 1 'invalid argument'\n[rank0]:[W708 22:58:33.597508565 ProcessGroupNCCL.cpp:1497] Warning: WARNING: destroy_process_group() was not called before program exit, which can leak resources. For more info, please see https://pytorch.org/docs/stable/distributed.html#shutdown (function operator())\n```\nThis code works fine on a single GPU but gives this error in multi-gpu setup.\nAny suggestions are appreciated.\n\n**Setup**\nTwo RTX 5090 on one machine\n\n**Software**\n`torch == 2.7.0.dev20250310+cu128`\n`deepspeed == 0.17.0`\n\n**Additional Information**\nWhen setting `NCCL_DEBUG=INFO`\n**Log**\n\n```\n[2025-07-08 22:50:26,009] [INFO] [real_accelerator.py:254:get_accelerator] Setting ds_accelerator to cuda (auto detect)\n[2025-07-08 22:50:26,798] [INFO] [comm.py:675:init_distributed] cdb=None\n[2025-07-08 22:50:26,798] [INFO] [comm.py:706:init_distributed] Initializing TorchBackend in DeepSpeed with backend nccl\n[2025-07-08 22:50:27,173] [INFO] [comm.py:675:init_distributed] cdb=None\nYou are using a model of type qwen2 to instantiate a model of type janus_qwen2. This is not supported for all configurations of models and can yield errors.\n[2025-07-08 22:50:27,328] [INFO] [config.py:744:__init__] Config mesh_device None world_size = 2\nYou are using a model of type qwen2 to instantiate a model of type janus_qwen2. This is not supported for all configurations of models and can yield errors.\n[2025-07-08 22:50:27,434] [INFO] [config.py:744:__init__] Config mesh_device None world_size = 2\nautodl-container-cab44f99fc-82aab726:19858:19858 [0] NCCL INFO Bootstrap: Using eth0:172.17.0.8<0>\nautodl-container-cab44f99fc-82aab726:19858:19858 [0] NCCL INFO cudaDriverVersion 12080\nautodl-container-cab44f99fc-82aab726:19858:19858 [0] NCCL INFO NCCL version 2.25.1+cuda12.2\nautodl-container-cab44f99fc-82aab726:19858:19858 [0] NCCL INFO Comm config Blocking set to 1\nautodl-container-cab44f99fc-82aab726:19859:19859 [1] NCCL INFO cudaDriverVersion 12080\nautodl-container-cab44f99fc-82aab726:19859:19859 [1] NCCL INFO Bootstrap: Using eth0:172.17.0.8<0>\nautodl-container-cab44f99fc-82aab726:19859:19859 [1] NCCL INFO NCCL version 2.25.1+cuda12.2\nautodl-container-cab44f99fc-82aab726:19859:19859 [1] NCCL INFO Comm config Blocking set to 1\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO ncclMaxSharedMem 82240 exceeds device/fn maxSharedMem 79856\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO NET/Plugin: Could not find: libnccl-net.so. Using internal network plugin.\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO NET/IB : No device found.\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO NET/IB : Using [RO]; OOB eth0:172.17.0.8<0>\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO NET/Socket : Using [0]eth0:172.17.0.8<0>\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO Using network Socket\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO ncclCommInitRankConfig comm 0xc360500 rank 1 nranks 2 cudaDev 1 nvmlDev 1 busId 5a000 commId 0x2bd6dadc0d6b3c51 - Init START\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO ncclMaxSharedMem 82240 exceeds device/fn maxSharedMem 79856\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO NET/Plugin: Could not find: libnccl-net.so. Using internal network plugin.\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO NET/IB : No device found.\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO NET/IB : Using [RO]; OOB eth0:172.17.0.8<0>\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO NET/Socket : Using [0]eth0:172.17.0.8<0>\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO PROFILER/Plugin: Could not find: libnccl-profiler.so.\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO Using network Socket\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO ncclCommInitRankConfig comm 0xdbcdea0 rank 0 nranks 2 cudaDev 0 nvmlDev 0 busId 49000 commId 0x2bd6dadc0d6b3c51 - Init START\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO RAS client listening socket at ::1<28028>\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO RAS client listening socket at ::1<28028>\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO Bootstrap timings total 0.001394 (create 0.000035, send 0.000088, recv 0.000357, ring 0.000132, delay 0.000000)\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO Bootstrap timings total 0.893562 (create 0.000028, send 0.000097, recv 0.866650, ring 0.000020, delay 0.000000)\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO Setting affinity for GPU 0 to 0fffffff,ffffff00,00000000,000fffff,ffffffff\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO Setting affinity for GPU 1 to 0fffffff,ffffff00,00000000,000fffff,ffffffff\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO comm 0xdbcdea0 rank 0 nRanks 2 nNodes 1 localRanks 2 localRank 0 MNNVL 0\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO Channel 00/04 : 0 1\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO Channel 01/04 : 0 1\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO Channel 02/04 : 0 1\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO Channel 03/04 : 0 1\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO comm 0xc360500 rank 1 nRanks 2 nNodes 1 localRanks 2 localRank 1 MNNVL 0\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO Trees [0] 1/-1/-1->0->-1 [1] -1/-1/-1->0->1 [2] 1/-1/-1->0->-1 [3] -1/-1/-1->0->1\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO P2P Chunksize set to 131072\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO Check P2P Type intraNodeP2pSupport 0 directMode 0\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO Trees [0] -1/-1/-1->1->0 [1] 0/-1/-1->1->-1 [2] -1/-1/-1->1->0 [3] 0/-1/-1->1->-1\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO P2P Chunksize set to 131072\nautodl-container-cab44f99fc-82aab726:19858:20699 [0] NCCL INFO [Proxy Service] Device 0 CPU core 38\nautodl-container-cab44f99fc-82aab726:19859:20701 [1] NCCL INFO [Proxy Service] Device 1 CPU core 6\nautodl-container-cab44f99fc-82aab726:19858:20700 [0] NCCL INFO [Proxy Service UDS] Device 0 CPU core 143\nautodl-container-cab44f99fc-82aab726:19859:20702 [1] NCCL INFO [Proxy Service UDS] Device 1 CPU core 8\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO threadThresholds 8/8/64 | 16/8/64 | 512 | 512\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO 4 coll channels, 4 collnet channels, 0 nvls channels, 4 p2p channels, 2 p2p channels per peer\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO threadThresholds 8/8/64 | 16/8/64 | 512 | 512\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO 4 coll channels, 4 collnet channels, 0 nvls channels, 4 p2p channels, 2 p2p channels per peer\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO CC Off, workFifoBytes 1048576\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO TUNER/Plugin: Could not find: libnccl-tuner.so libnccl-net.so. Using internal tuner plugin.\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO ncclCommInitRankConfig comm 0xdbcdea0 rank 0 nranks 2 cudaDev 0 nvmlDev 0 busId 49000 commId 0x2bd6dadc0d6b3c51 - Init COMPLETE\nautodl-container-cab44f99fc-82aab726:19858:20209 [0] NCCL INFO Init timings - ncclCommInitRankConfig: rank 0 nranks 2 total 34.18 (kernels 34.14, alloc 0.00, bootstrap 0.00, allgathers 0.03, topo 0.01, graphs 0.00, connections 0.00, rest 0.00)\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO TUNER/Plugin: Could not find: libnccl-tuner.so libnccl-net.so. Using internal tuner plugin.\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO ncclCommInitRankConfig comm 0xc360500 rank 1 nranks 2 cudaDev 1 nvmlDev 1 busId 5a000 commId 0x2bd6dadc0d6b3c51 - Init COMPLETE\nautodl-container-cab44f99fc-82aab726:19859:20210 [1] NCCL INFO Init timings - ncclCommInitRankConfig: rank 1 nranks 2 total 34.18 (kernels 33.27, alloc 0.00, bootstrap 0.89, allgathers 0.00, topo 0.01, graphs 0.00, connections 0.00, rest 0.00)\nautodl-container-cab44f99fc-82aab726:19858:20703 [0] NCCL INFO Channel 00 : 0[0] -> 1[1] via SHM/direct/direct\nautodl-container-cab44f99fc-82aab726:19859:20704 [1] NCCL INFO Channel 00 : 1[1] -> 0[0] via SHM/direct/direct\nautodl-container-cab44f99fc-82aab726:19858:20703 [0] NCCL INFO Channel 01 : 0[0] -> 1[1] via SHM/direct/direct\nautodl-container-cab44f99fc-82aab726:19859:20704 [1] NCCL INFO Channel 01 : 1[1] -> 0[0] via SHM/direct/direct\nautodl-container-cab44f99fc-82aab726:19858:20703 [0] NCCL INFO Channel 02 : 0[0] -> 1[1] via SHM/direct/direct\nautodl-container-cab44f99fc-82aab726:19859:20704 [1] NCCL INFO Channel 02 : 1[1] -> 0[0] via SHM/direct/direct\nautodl-container-cab44f99fc-82aab726:19858:20703 [0] NCCL INFO Channel 03 : 0[0] -> 1[1] via SHM/direct/direct\nautodl-container-cab44f99fc-82aab726:19859:20704 [1] NCCL INFO Channel 03 : 1[1] -> 0[0] via SHM/direct/direct\nautodl-container-cab44f99fc-82aab726:19858:20703 [0] NCCL INFO Connected all rings, use ring PXN 0 GDR 1\nautodl-container-cab44f99fc-82aab726:19859:20704 [1] NCCL INFO Connected all rings, use ring PXN 0 GDR 1\n\nautodl-container-cab44f99fc-82aab726:19858:19858 [0] enqueue.cc:1500 NCCL WARN Cuda failure 1 'invalid argument'\n\nautodl-container-cab44f99fc-82aab726:19859:19859 [1] enqueue.cc:1500 NCCL WARN Cuda failure 1 'invalid argument'\nautodl-container-cab44f99fc-82aab726:19858:19858 [0] NCCL INFO group.cc:242 -> 1\nautodl-container-cab44f99fc-82aab726:19858:19858 [0] NCCL INFO group.cc:470 -> 1\nautodl-container-cab44f99fc-82aab726:19859:19859 [1] NCCL INFO group.cc:242 -> 1\nautodl-container-cab44f99fc-82aab726:19858:19858 [0] NCCL INFO group.cc:573 -> 1\nautodl-container-cab44f99fc-82aab726:19859:19859 [1] NCCL INFO group.cc:470 -> 1\nautodl-container-cab44f99fc-82aab726:19858:19858 [0] NCCL INFO enqueue.cc:2229 -> 1\nautodl-container-cab44f99fc-82aab726:19859:19859 [1] NCCL INFO group.cc:573 -> 1\nautodl-container-cab44f99fc-82aab726:19859:19859 [1] NCCL INFO enqueue.cc:2229 -> 1\n[2025-07-08 22:51:01,771] [INFO] [partition_parameters.py:348:__exit__] finished initializing model - num_params = 1, num_elems = 0.31B\n[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\n[rank0]: ncclUnhandledCudaError: Call to CUDA function failed.\n[rank0]: Last error:\n[rank0]: Cuda failure 1 'invalid argument'\n[rank1]: 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\n[rank1]: ncclUnhandledCudaError: Call to CUDA function failed.\n[rank1]: Last error:\n[rank1]: Cuda failure 1 'invalid argument'\n[rank0]:[W708 22:51:02.109986298 ProcessGroupNCCL.cpp:1497] Warning: WARNING: destroy_process_group() was not called before program exit, which can leak resources. For more info, please see https://pytorch.org/docs/stable/distributed.html#shutdown (function operator())\nautodl-container-cab44f99fc-82aab726:19858:20792 [0] NCCL INFO misc/socket.cc:64 -> 3\nautodl-container-cab44f99fc-82aab726:19858:20792 [0] NCCL INFO misc/socket.cc:80 -> 3\nautodl-container-cab44f99fc-82aab726:19858:20792 [0] NCCL INFO misc/socket.cc:828 -> 3\nautodl-container-cab44f99fc-82aab726:19858:20699 [0] NCCL INFO misc/socket.cc:880 -> 3\nautodl-container-cab44f99fc-82aab726:19858:20792 [0] NCCL INFO misc/socket.cc:64 -> 3\nautodl-container-cab44f99fc-82aab726:19858:20792 [0] NCCL INFO misc/socket.cc:80 -> 3\nautodl-container-cab44f99fc-82aab726:19858:20792 [0] NCCL INFO misc/socket.cc:828 -> 3\nautodl-container-cab44f99fc-82aab726:19859:20794 [1] NCCL INFO misc/socket.cc:64 -> 3\nautodl-container-cab44f99fc-82aab726:19858:20699 [0] NCCL INFO misc/socket.cc:880 -> 3\nautodl-container-cab44f99fc-82aab726:19859:20794 [1] NCCL INFO misc/socket.cc:80 -> 3\nautodl-container-cab44f99fc-82aab726:19859:20794 [1] NCCL INFO misc/socket.cc:828 -> 3\nautodl-container-cab44f99fc-82aab726:19859:20794 [1] NCCL INFO misc/socket.cc:64 -> 3\nautodl-container-cab44f99fc-82aab726:19859:20794 [1] NCCL INFO misc/socket.cc:80 -> 3\nautodl-container-cab44f99fc-82aab726:19859:20794 [1] NCCL INFO misc/socket.cc:828 -> 3\nautodl-container-cab44f99fc-82aab726:19859:20701 [1] NCCL INFO misc/socket.cc:880 -> 3\nautodl-container-cab44f99fc-82aab726:19858:20792 [0] NCCL INFO comm 0xdbcdea0 rank 0 nranks 2 cudaDev 0 busId 49000 - Abort COMPLETE\nautodl-container-cab44f99fc-82aab726:19859:20794 [1] NCCL INFO comm 0xc360500 rank 1 nranks 2 cudaDev 1 busId 5a000 - Abort COMPLETE\n```","reference_answer":"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?","needs_clarification":false,"thread_id":221360,"url":"https://discuss.pytorch.org/t/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/221360","created_at":"2025-07-08T15:08:34.273000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Why torch.nn.functional.conv2d is a lot faster when group > 1?\n\nHi\n\nIt seems that torch.nn.functional.conv2d is faster when group > 1 even when the groups are just duplicated.\n\nSo for the following code, n_frames = 2 will produce 2 identical input_field and kernel and use groups = 2 for conv2d. The result should be the same as the n_frames = 1 with two duplicate channels.\n\nFrom my understanding, n_frames = 2 will increase the computation. However, changing the n_frames of the following code from 1 to 2 will actually shorten the time (about 10 times) and also the results are slightly different. Does this mean that group > 1 will compromise the precision?\n\n```\nimport torch\nfrom time import time\ndevice = 'cuda:1'\ntorch.manual_seed(0)\n\ninput_field = torch.rand(1, 1, 1080, 1920, dtype=torch.float32, device=device)\nkernel = torch.rand(1, 1, 100, 100, dtype=torch.float32, device=device)\n\nn_frames = 1\ninput_field = input_field.repeat(1, n_frames, 1, 1)\nkernel = kernel.repeat(n_frames, 1, 1, 1) \n\nstart_time = time()\ntorch.cuda.synchronize(device=device)\nret = torch.nn.functional.conv2d(\n input_field,\n kernel,\n padding='same',\n groups=n_frames,\n )\ntorch.cuda.synchronize(device=device)\nend_time = time()\n\nprint(f\"Time taken for conv2d with groups={n_frames}: {end_time - start_time:.4f} seconds\")\n```\n\nThank you!","reference_answer":"given these results, it seems like most of the overhead time is due to benchmarking for the best kernel\n(as far as I know pytorch doesn't support kernel caching across sessions) which leaves you with two options\n\nif you're willing to give up the best kernel pick I would suggest setting `torch.backends.cudnn.benchmark = False`\n\nor using `torch.backends.cudnn.benchmarck = True` you can run all your tests in one session\n- run once to pick the best kernel and warm up the GPU\n- run each test on it's own (keep in mind that best kernel will persist as long as you're using the same kernel shape, dtype, ...) in an interactive environment \n\neither using a notebook or by starting interactive python last thing in your script `import IPython; IPyhton.embed()`","needs_clarification":false,"thread_id":221385,"url":"https://discuss.pytorch.org/t/why-torch-nn-functional-conv2d-is-a-lot-faster-when-group-1/221385","created_at":"2025-07-09T12:12:29.975000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["Dhia-naouali"],"answered_by_ptrblck":false} {"question":"Does the optimizer have to be created after model is moved to the GPU?\n\n## codes\nmodel = MllamaForConditionalGeneration.from_pretrained(\n MODEL_NAME,\n attn_implementation=\"sdpa\",\n device_map=\"cpu\",\n torch_dtype=torch.float32,\n)\noptim = AdamW(model.parameters(), lr=1e-5)\nmodel.to(\"cuda:0\")\n\n## Questions\nIn the codes above, I create **mllama** model on cpu and use its parameters to create optimizer, then move model to cuda.\nIs this approach feasible?\nWill there be any problems with updating the model parameters?","reference_answer":"Parameters are moved inplace so creating the optimizer before moving the model should be fine.\nThis simple code snippet also shows it:\n```python\nmodel = torch.nn.Linear(10, 10)\noptimizer = torch.optim.Adam(model.parameters())\nprint([p.device for p in optimizer.param_groups[0]['params']])\n# [device(type='cpu'), device(type='cpu')]\n\nmodel.cuda()\nprint([p.device for p in optimizer.param_groups[0]['params']])\n# [device(type='cuda', index=0), device(type='cuda', index=0)]\n```","needs_clarification":false,"thread_id":221397,"url":"https://discuss.pytorch.org/t/does-the-optimizer-have-to-be-created-after-model-is-moved-to-the-gpu/221397","created_at":"2025-07-09T16:20:55.386000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"GAN => maping a random noise to an output space!\n\nHi Guys,\nI've some difficulties grasping the concept; that's why I need your feedback!\n\nI should map a random noise of shape (100, 1, 1) to an image tensor of shape (3, 64, 64). \nThe generator to implement consists of 5 transposed convolutional layers:\n\n # To use is 512, 256, 128, 64, and 3 output channels for these layers.\n # Use a kernel size of 4.\n # Use a padding of 0 in the first transposed convolution and a padding of 1 for \n all subsequent transposed convolutions.\n # Do not use a bias.\n # Use a stride of 1 for the first transposed convolution and a stride of 2 for all subsequent transposed convolutions.\n# Apply batch normalization after each transposed convolutional layer except for the last one.\n# Apply a ReLU activation function after each batch normalization layer. Use the `torch.nn.ReLU` function for this.\n# Apply a hyperbolic tangent function after the last transposed convolutional layer. \nReturn the output after this function.\n\nMy Implementation:\n\nclass Generator(nn.Module):\n def __init__(self):\n super(Generator, self).__init__()\n self.main = nn.Sequential(\n \n #-----------------------------------------------\n # 1.Layer\n #-----------------------------------------------\n nn.ConvTranspose2d(in_channels=100,out_channels=512,\n kernel_size=(4, 4),stride=1,padding=0),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace = True),\n #-----------------------------------------------\n # 2.Layer\n #-----------------------------------------------\n nn.ConvTranspose2d(in_channels=512,out_channels=256,\n kernel_size=(4, 4),stride=2, padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace = True),\n #-----------------------------------------------\n #. 3.Layer\n #-----------------------------------------------\n nn.ConvTranspose2d(in_channels=256,out_channels=128,\n kernel_size=(4, 4),stride=2,padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace = True),\n #-----------------------------------------------\n # 4.Layer\n #-----------------------------------------------\n nn.ConvTranspose2d(in_channels=128,out_channels=64,\n kernel_size=(4, 4),stride=2,padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace = True),\n\n #-----------------------------------------------\n # 5.Layer\n #-----------------------------------------------\n nn.ConvTranspose2d(in_channels=64,out_channels=3*64*64,\n kernel_size=(4, 4),stride=2,padding=1),\n nn.Tanh()\n )\n\ndef forward(self, data):\n return self.main(data)\n \nI want to know if the implementation is correct. Thanks","reference_answer":"almost there, here is a commented version with the needed slight changes\n\n```python\nimport torch \nfrom torch import nn\n\nclass Generator(nn.Module):\n def __init__(self):\n super().__init__()\n \n\n # using a dict for all layers other than the first one, to reduce redundancy\n # it's the same as using `kernel_size=4, stride=2, padding=1, bias=False` in each layer\n sub_seq_kwargs = {\n \"kernel_size\": 4,\n \"stride\": 2,\n \"padding\": 1,\n \"bias\": False\n }\n\n self.main = nn.Sequential(\n # layer 1\n # by default pytorch include a bias for conv layers, so we'll need to set that to False\n nn.ConvTranspose2d(100, 512, kernel_size=4, stride=1, padding=0, bias=False), # => (bs, 512, 4, 4)\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n\n # layer 2\n nn.ConvTranspose2d(512, 256, **sub_seq_kwargs), # => (bs, 256, 8, 8)\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n\n # layer 3\n nn.ConvTranspose2d(256, 128, **sub_seq_kwargs), # => (bs, 128, 16, 16)\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n\n # layer 4\n nn.ConvTranspose2d(128, 64, **sub_seq_kwargs), # => (bs, 64, 32, 32)\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n\n # layer 5\n # in_channels & out_channels only affect the C dim of your tensor\n # so to get a (bs, 3, 64, 64) output we can use out_channels=3\n # spatial dims (height & width) are augmented by the stride & padding of the transposed conv layer\n nn.ConvTranspose2d(64, 3, **sub_seq_kwargs), # => (bs, 3, 64, 64)\n nn.Tanh()\n )\n\n def forward(self, data):\n return self.main(data)\n\ng = Generator()\nprint(g(torch.randn(1, 100, 1, 1)).size())\n```","needs_clarification":false,"thread_id":221398,"url":"https://discuss.pytorch.org/t/gan-maping-a-random-noise-to-an-output-space/221398","created_at":"2025-07-09T16:57:31.255000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Dhia-naouali"],"answered_by_ptrblck":false} {"question":"Dist.all_gather with uneven tensor sizes\n\nThe docs for [torch.distributed.all_gather](https://docs.pytorch.org/docs/stable/distributed.html#torch.distributed.all_gather) state that\n\n> Complex and uneven sized tensors are supported.\n\nbut I can't find any documentation or examples about how to gather unevenly sized tensors. I have a script like this:\n\n```python\nimport torch\n\nif __name__ == '__main__':\n torch.distributed.init_process_group(backend=\"cpu:gloo,cuda:nccl\")\n\n world_size = torch.distributed.get_world_size()\n rank = torch.distributed.get_rank()\n\n # should be [0] for rank 0, [1, 1] for rank 1, [2, 2, 2] for rank 2, etc.\n tensor = torch.ones((rank + 1, )) * rank\n\n # Gather tensors from all ranks\n gathered_tensors = [torch.empty((i + 1, )) for i in range(world_size)]\n torch.distributed.all_gather(gathered_tensors, tensor)\n\n if rank == 0:\n print(f\"Gathered tensors from all ranks\")\n for i, t in enumerate(gathered_tensors):\n print(f\"Rank {i}: {t}\")\n```\n\nWhen I run it with `torchrun --nproc-per-node 42 gather_tensor_test.py`, I get all kinds of fun errors like:\n\n> [rank0]: Traceback (most recent call last):\n[rank0]: File \"/mnt/aged-glade/home/jordan/lab-asr/lab/model/asr_8_rl/all_gather_test.py\", line 14, in \n[rank0]: torch.distributed.all_gather(gathered_tensors, tensor)\n[rank0]: File \"/mnt/aged-glade/home/jordan/.conda/envs/asr/lib/python3.12/site-packages/torch/distributed/c10d_logger.py\", line 81, in wrapper\n[rank0]: return func(*args, **kwargs)\n[rank0]: ^^^^^^^^^^^^^^^^^^^^^\n[rank0]: File \"/mnt/aged-glade/home/jordan/.conda/envs/asr/lib/python3.12/site-packages/torch/distributed/distributed_c10d.py\", line 3728, in all_gather\n[rank0]: work = group.allgather([tensor_list], [tensor])\n[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n[rank0]: RuntimeError: ProcessGroupGloo::allgather: invalid tensor size at index 1 (expected (1), got (2))\n[rank1]: Traceback (most recent call last):\n[rank1]: File \"/mnt/aged-glade/home/jordan/lab-asr/lab/model/asr_8_rl/all_gather_test.py\", line 14, in \n[rank1]: torch.distributed.all_gather(gathered_tensors, tensor)\n[rank1]: File \"/mnt/aged-glade/home/jordan/.conda/envs/asr/lib/python3.12/site-packages/torch/distributed/c10d_logger.py\", line 81, in wrapper\n[rank1]: return func(*args, **kwargs)\n[rank1]: ^^^^^^^^^^^^^^^^^^^^^\n[rank1]: File \"/mnt/aged-glade/home/jordan/.conda/envs/asr/lib/python3.12/site-packages/torch/distributed/distributed_c10d.py\", line 3728, in all_gather\n[rank1]: work = group.allgather([tensor_list], [tensor])\n[rank1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n[rank1]: RuntimeError: ProcessGroupGloo::allgather: invalid tensor size at index 0 (expected (2), got (1))\n...\n\nSo how exactly do we use `dist.all_gather` with uneven tensor sizes?","reference_answer":"I believe this is a GLOO backend limitation, cc. @d4l3k \n\nIt doesn't repro with cuda NCCL backend:\n```\nimport torch\n\nif __name__ == '__main__':\n torch.distributed.init_process_group(backend=\"nccl\")\n\n world_size = torch.distributed.get_world_size()\n rank = torch.distributed.get_rank()\n torch.cuda.set_device(rank)\n\n # should be [0] for rank 0, [1, 1] for rank 1, [2, 2, 2] for rank 2, etc.\n tensor = torch.ones((rank + 1, ), device=\"cuda\") * rank\n\n # Gather tensors from all ranks\n gathered_tensors = [torch.empty((i + 1), device=\"cuda\") for i in range(world_size)]\n torch.distributed.all_gather(gathered_tensors, tensor)\n\n if rank == 0:\n print(f\"Gathered tensors from all ranks\")\n for i, t in enumerate(gathered_tensors):\n print(f\"Rank {i}: {t}\")\n```\nOutput:\n```\nGathered tensors from all ranks\nRank 0: tensor([0.], device='cuda:0')\nRank 1: tensor([1., 1.], device='cuda:0')\nRank 2: tensor([2., 2., 2.], device='cuda:0')\n```","needs_clarification":false,"thread_id":221417,"url":"https://discuss.pytorch.org/t/dist-all-gather-with-uneven-tensor-sizes/221417","created_at":"2025-07-10T17:23:20.173000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["yf225"],"answered_by_ptrblck":false} {"question":"Using CUDA Graphs output during warmup/capture\n\nI'm looking at the [API for CUDA graphs](https://docs.pytorch.org/docs/stable/notes/cuda.html#pytorch-api), is it possible to use `static_output` from the warmup and capture phases? I tried this myself and am able to use the result out of the warmup call (unsurprisingly) but the capture phase seems to not produce the correct return value. Curiously, it seems to spit out a zero tensor but this zero tensor isn't copied correctly to the static output?\n\nMy use case is I have a stateful function that I'd like to turn into a graph. Ideally I'd like to run the warmup and capture phase and be able to utilize the results before replaying the graph, as resetting the state is not ideal, but I haven't been able to figure out why the call in the capture phase does not produce a valid output.\n\nOr perhaps an alternate question: what is the return value in this line?\n\n```\nwith torch.cuda.graph(g):\n static_output = static_input * 2\n```\n\nIt differs from the output returned in the warmup call but it has no actual content...","reference_answer":"Ah, classic. I figured this out right after posting despite spending a few hours on it before. The answer is I need to call `graph.replay()` once after doing the capture. This is [documented](https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#creating-a-graph-using-stream-capture) as the work not actually being performed, and a related question for anyone else in the future: https://stackoverflow.com/questions/71618350/cuda-graph-problem-results-not-computed-for-the-first-iteration","needs_clarification":false,"thread_id":221550,"url":"https://discuss.pytorch.org/t/using-cuda-graphs-output-during-warmup-capture/221550","created_at":"2025-07-15T14:04:07.758000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["kevmo314"],"answered_by_ptrblck":false} {"question":"Autograd function returns tensor views\n\nI have a very simple script\n```\nimport torch\n\nclass PrintTensor(torch.autograd.Function):\n @staticmethod\n def forward(ctx, input_tensor, tag):\n ctx.tag = tag # Store tag as a class attribute instead\n print(\"input_tensor\", input_tensor._base)\n return input_tensor\n\n @staticmethod\n def backward(ctx, grad_output):\n return grad_output, None\n\n# Test code\nmodel = torch.nn.Linear(4,4)\ninp = torch.randn(4, 4)\nprint(inp._base)\noutput = model(inp)\nprint(\"output 1\", output._base)\noutput = PrintTensor.apply(output, \"test\")\nprint(\"output 2\", output._base)\nloss = torch.sum(output)\nloss.backward()\nprint(loss)\n```\nThe output is\n```\nNone\noutput 1 None\ninput_tensor None\noutput 2 tensor([[-0.7352, 0.6865, 0.5382, -0.0586],\n [ 0.8063, -0.1446, 1.1007, -0.0438],\n [ 0.1090, -0.5273, 0.3381, -0.9453],\n [-0.1048, 1.1854, 0.7933, 0.8607]], grad_fn=)\ntensor(3.8586, grad_fn=)\n```\nAfter the autograd function of `PrintTensor` the output tensor becomes a tensor view of other tensor. Could someone help me understand this behavior? Thanks.","reference_answer":"This is expected behavior. If a tensor is returned as-is, it is automatically turned into a view. This allows the custom autograd Function to attach a new grad_fn without overwriting the grad_fn of the input.","needs_clarification":false,"thread_id":221562,"url":"https://discuss.pytorch.org/t/autograd-function-returns-tensor-views/221562","created_at":"2025-07-16T02:48:24.372000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["soulitzer"],"answered_by_ptrblck":false} {"question":"Model loss not decreasing even after increasing learning rate\n\nI'm fairly unfamiliar with pytorch (and ML in general) so please do bear with me. I've written a CNN that takes input 1x64x200 to predict between 7 labels (labelled 0-7). My model is as follows:\n```\nclass Net(nn.Module):\n def __init__(self,dropout):\n super(Net,self).__init__()\n self.conv1=nn.Conv2d(1,32,7,stride=1,padding=3)\n self.conv2=nn.Conv2d(32,16,7,stride=1,padding=3)\n self.conv3=nn.Conv2d(16,8,5,stride=1,padding=2)\n self.conv4=nn.Conv2d(8,16,5,stride=1,padding=2)\n self.conv5=nn.Conv2d(16,4,3,stride=1,padding=1)\n self.pool1=nn.MaxPool2d(2)\n self.pool2=nn.MaxPool2d(4)\n self.fc1=nn.Linear(800,7)\n self.dropout1=nn.Dropout2d(dropout)\n self.batchnorm1=nn.BatchNorm2d(32)\n self.batchnorm2=nn.BatchNorm2d(16)\n self.batchnorm3=nn.BatchNorm2d(8)\n self.batchnorm4=nn.BatchNorm2d(4)\n\n def forward(self,x):\n x=self.conv1(x)\n x=self.batchnorm1(x)\n x=self.dropout1(x)\n x=nn.functional.relu(x)\n\n x=self.conv2(x)\n x=self.batchnorm2(x)\n x=self.dropout1(x)\n x=nn.functional.relu(x)\n x=self.pool1(x)\n\n x=self.conv3(x)\n x=self.batchnorm3(x)\n x=self.dropout1(x)\n x=nn.functional.relu(x)\n\n x=self.conv4(x)\n x=self.batchnorm2(x)\n x=self.dropout1(x)\n x=nn.functional.relu(x)\n\n x=self.conv5(x)\n x=self.batchnorm4(x)\n x=self.dropout1(x)\n x=nn.functional.relu(x)\n x=self.pool2(x)\n\n x=torch.flatten(x,1)\n x=self.fc1(x)\n x=nn.functional.relu(x)\n return x\n \n\ndef train_test(net,epochs,train_loader,test_loader,device):\n criterion=nn.CrossEntropyLoss()\n optimizer=optim.Adam(net.parameters(),lr=3e-3)\n train_acc=[]\n train_loss=[]\n test_acc=[]\n test_loss=[]\n net.to(device)\n for epoch in tqdm.tqdm(range(epochs)):\n net.train()\n running_loss=0.0\n correct,total=0,0\n for i,data in enumerate(train_loader,start=0):\n inputs,labels=data\n inputs=inputs.to(device).float()\n labels=labels.to(device).long()\n \n #train\n optimizer.zero_grad()\n outputs=net.forward(inputs)\n loss=criterion(outputs,labels)\n loss.backward()\n optimizer.step()\n\n running_loss+=loss.item()\n #training accuracy\n _,predicted=torch.max(outputs,1)\n total+=labels.size(0)\n correct+=(predicted==labels).sum()\n train_loss.append(running_loss/len(train_loader))\n train_acc.append(correct/total)\n print(f\"epoch {epoch} --> TRAIN loss: {running_loss/len(train_loader):.5f}, TRAIN accuracy: {correct/total:.2f}\")\n\n #eval on test\n net.eval()\n running_loss=0.0\n correct,total=0,0\n for inputs,labels in test_loader:\n inputs,labels=inputs.to(device).float(),labels.to(device).long()\n outputs=net.forward(inputs)\n loss=criterion(outputs,labels)\n running_loss+=loss.item()\n\n #test acc\n _,predicted=torch.max(outputs,1)\n total+=labels.size(0)\n correct+=(predicted==labels).sum()\n test_loss.append(running_loss/len(test_loader))\n test_acc.append(correct/total)\n print(f\"epoch {epoch} --> TEST loss: {running_loss/len(train_loader):.2f}, TEST accuracy: {correct/total:.2f}\")\n\n return train_loss,train_acc,test_loss,test_acc\n\nbatch_size=150\ntest_data = TensorDataset(X_test, y_test)\ntest_loader = DataLoader(test_data, batch_size=batch_size,\n shuffle=False\n )\n\ntrain_data = TensorDataset(X_train, y_train)\ntrain_loader = DataLoader(train_data,\n batch_size=batch_size,\n drop_last=False,\n shuffle=True\n )\n```\nTraining with a low learning rate (1e-4) leads to training loss oscillating at a high value (around 1.95). Increasing the learning rate, even to 0.1, doesn't decrease the training loss. I can't tell if my model is stuck at a local minima or if there something else fundamentally wrong with my model design or code.\n\nAny help would be greatly appreciated. Thank you!\n\ntraining at learning rate=0.1:\n\n```\n 0%| | 0/50 [00:00 TRAIN loss: 1.97984, TRAIN accuracy: 0.14\n 2%|▏ | 1/50 [00:18<14:43, 18.02s/it]\nepoch 0 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 1 --> TRAIN loss: 1.94591, TRAIN accuracy: 0.14\n 4%|▍ | 2/50 [00:36<14:40, 18.33s/it]\nepoch 1 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 2 --> TRAIN loss: 1.94591, TRAIN accuracy: 0.14\n 6%|▌ | 3/50 [00:54<14:17, 18.24s/it]\nepoch 2 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 3 --> TRAIN loss: 1.94591, TRAIN accuracy: 0.14\n 8%|▊ | 4/50 [01:13<14:01, 18.30s/it]\nepoch 3 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 4 --> TRAIN loss: 1.94591, TRAIN accuracy: 0.14\n 10%|█ | 5/50 [01:31<13:40, 18.24s/it]\nepoch 4 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 5 --> TRAIN loss: 1.94591, TRAIN accuracy: 0.14\n 12%|█▏ | 6/50 [01:50<13:31, 18.43s/it]\nepoch 5 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 6 --> TRAIN loss: 1.94591, TRAIN accuracy: 0.14\n 14%|█▍ | 7/50 [02:08<13:15, 18.51s/it]\nepoch 6 --> TEST loss: 0.49, TEST accuracy: 0.14\n```\ntraining at learning rate=1e-3:\n\n```\n 0%| | 0/50 [00:00 TRAIN loss: 1.94748, TRAIN accuracy: 0.15\n 2%|▏ | 1/50 [00:18<15:06, 18.50s/it]\nepoch 0 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 1 --> TRAIN loss: 1.94572, TRAIN accuracy: 0.14\n 4%|▍ | 2/50 [00:36<14:43, 18.40s/it]\nepoch 1 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 2 --> TRAIN loss: 1.94623, TRAIN accuracy: 0.14\n 6%|▌ | 3/50 [00:54<14:17, 18.25s/it]\nepoch 2 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 3 --> TRAIN loss: 1.94588, TRAIN accuracy: 0.14\n 8%|▊ | 4/50 [01:13<13:59, 18.25s/it]\nepoch 3 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 4 --> TRAIN loss: 1.94597, TRAIN accuracy: 0.14\n 10%|█ | 5/50 [01:31<13:45, 18.35s/it]\nepoch 4 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 5 --> TRAIN loss: 1.94591, TRAIN accuracy: 0.14\n 12%|█▏ | 6/50 [01:50<13:29, 18.40s/it]\nepoch 5 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 6 --> TRAIN loss: 1.94586, TRAIN accuracy: 0.14\n 14%|█▍ | 7/50 [02:08<13:13, 18.46s/it]\nepoch 6 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 7 --> TRAIN loss: 1.94593, TRAIN accuracy: 0.14\n 16%|█▌ | 8/50 [02:27<12:56, 18.49s/it]\nepoch 7 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 8 --> TRAIN loss: 1.94591, TRAIN accuracy: 0.14\n 18%|█▊ | 9/50 [02:45<12:39, 18.53s/it]\nepoch 8 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 9 --> TRAIN loss: 1.94592, TRAIN accuracy: 0.14\n 20%|██ | 10/50 [03:04<12:22, 18.56s/it]\nepoch 9 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 10 --> TRAIN loss: 1.94590, TRAIN accuracy: 0.14\n 22%|██▏ | 11/50 [03:23<12:08, 18.67s/it]\nepoch 10 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 11 --> TRAIN loss: 1.94597, TRAIN accuracy: 0.14\n 24%|██▍ | 12/50 [03:41<11:47, 18.61s/it]\nepoch 11 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 12 --> TRAIN loss: 1.94591, TRAIN accuracy: 0.14\n 26%|██▌ | 13/50 [04:00<11:28, 18.60s/it]\nepoch 12 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 13 --> TRAIN loss: 1.94592, TRAIN accuracy: 0.14\n 28%|██▊ | 14/50 [04:19<11:09, 18.60s/it]\nepoch 13 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 14 --> TRAIN loss: 1.94594, TRAIN accuracy: 0.14\n 30%|███ | 15/50 [04:37<10:50, 18.59s/it]\nepoch 14 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 15 --> TRAIN loss: 1.94588, TRAIN accuracy: 0.14\n 32%|███▏ | 16/50 [04:56<10:29, 18.52s/it]\nepoch 15 --> TEST loss: 0.49, TEST accuracy: 0.14\nepoch 16 --> TRAIN loss: 1.94593, TRAIN accuracy: 0.14\n 34%|███▍ | 17/50 [05:14<10:09, 18.48s/it]\nepoch 16 --> TEST loss: 0.49, TEST accuracy: 0.14\n```","reference_answer":"Hi Slug!\n\nFirst, try getting rid of that final `relu()`. You should be feeding the output of your final\n`Linear` layer directly into your `CrossEntropyLoss` loss criterion.\n\nYour output suggests that you are training for maybe seven or seventeen or fifty epochs.\nTry training for *a lot* longer.\n\n`Adam` is a good optimizer, but I recommend starting with plain-vanilla `SGD`. It can be\nmore stable (even if sometimes slower) and is easier to reason about.\n\nSee if you can overfit on a single batch or a small number of batches.\n\nSome questions:\n\nHow large is your training set? How balanced is your training set? Do each of your seven\nclasses have about the same number of samples?\n\nCould a person looking at your data do a good job of classifying the input samples?\n\nGood luck!\n\nK. Frank","needs_clarification":false,"thread_id":221694,"url":"https://discuss.pytorch.org/t/model-loss-not-decreasing-even-after-increasing-learning-rate/221694","created_at":"2025-07-21T12:02:43.294000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Why would functional and non-functional broadcast use `src` with different semantics?\n\nHi, I am wondering why the `src` means differently in `torch.distributed._functional_collectives.broadcast` and `torch.distributed.distributed_c10d.broadcast`. In functional version, `src` is the local rank inside the group, while in the non-functional version, `src` is a global rank. This is kind of misleading to users that first use functional version.","reference_answer":"Agree that is not ideal, but because `torch.distributed.distributed_c10d.broadcast` is the original collective we can't change it for backwards compatibility reasons. The functional version must always pass in a group so it can use the local rank","needs_clarification":false,"thread_id":221721,"url":"https://discuss.pytorch.org/t/why-would-functional-and-non-functional-broadcast-use-src-with-different-semantics/221721","created_at":"2025-07-22T05:58:18.477000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["H-Huang"],"answered_by_ptrblck":false} {"question":"Continued pre-training large models with FSDP2?\n\nIs there a pattern for doing continued pre-training of large models with FSDP2? I don't see a feature like the \"sync_module_states\" from FSDP1. Is it implicit in FSDP2?","reference_answer":"Use the Distributed Checkpoint APIs (`torch.distributed.checkpoint`). FSDP2 uses DTensors, which DCP can also handle. The FSDP tutorial has a section on the state dict with the DCP APIs: https://docs.pytorch.org/tutorials/intermediate/FSDP_tutorial.html#state-dict-with-dcp-apis. The torchtitan checkpoint example is also recommended: https://github.com/pytorch/torchtitan/blob/f3e2a75e151872b3dc346d3bfa37d121e413242d/torchtitan/train.py#L298","needs_clarification":false,"thread_id":221738,"url":"https://discuss.pytorch.org/t/continued-pre-training-large-models-with-fsdp2/221738","created_at":"2025-07-22T19:49:32.821000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["H-Huang","hpcpony"],"answered_by_ptrblck":false} {"question":"How to use flight recorder in a convenient way?\n\nHi, all!\n\nIs there a more convenient way to use the Flight Recorder?\n\nI followed the example in the documentation at [https://docs.pytorch.org/tutorials/prototype/flight_recorder_tutorial.html](https://docs.pytorch.org/tutorials/prototype/flight_recorder_tutorial.html) and ran into an error when executing `torchfrtrace`:\n\n```\nTraceback (most recent call last):\n File \"/opt/conda/bin/torchfrtrace\", line 5, in \n from tools.flight_recorder.fr_trace import main\nModuleNotFoundError: No module named 'tools.flight_recorder'\n```\n\nAs a workaround, I had to manually copy the `tools/flight_recorder` directory from the PyTorch source code and add it to my `PYTHONPATH`. Is there a more straightforward or convenient way to use the Flight Recorder without having to do this?","reference_answer":"This has been fixed in nightlies. We’re also working on a debug server to make it easier to use","needs_clarification":false,"thread_id":221742,"url":"https://discuss.pytorch.org/t/how-to-use-flight-recorder-in-a-convenient-way/221742","created_at":"2025-07-23T02:14:16.023000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["d4l3k"],"answered_by_ptrblck":false} {"question":"Should we apply un-normalization before computing the loss?\n\nHello everyone, hope you are doing great.\n\nI 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.\nBefore passing data to my model, I normalize all my features, including the target value `y` (that we shall call `y,scaled`).\nMy model then yields a prediction `y_hat,scaled`. It is totally possible for me to un-normalize my prediction into `y_hat`.\n\nThe question is the following: should the loss function used by the optimizer be computed on the scaled or the unscaled data ? \nFor stability, I was assuming I should compute the loss on scaled data : `loss(y,scaled, y_hat,scaled)`. Is this the case ? Does it make any difference if I compute instead `loss(y, y_hat)` ?\n\nThanks in advance!","reference_answer":"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. \nDepending on your use case you might want to compute the \"unscaled loss\" by unscaling the model output and target to compute the error in your target units in case this interpretation is valid.\nE.g. if your model is computing pixel coordinates of keypoints in an image frame it might make sense to train the model to predict normalized outputs in `[-1, 1]` or `[0, 1]`. However, to actually print the predicted points and to compute the error in \"pixel coordinates\" you would unscale them again.","needs_clarification":false,"thread_id":221751,"url":"https://discuss.pytorch.org/t/should-we-apply-un-normalization-before-computing-the-loss/221751","created_at":"2025-07-23T13:38:49.459000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Verifying grad_x after autograd double backprop\n\nIn the process of verifying another piece of code, I need to find `x.grad` after backpropagating a loss function which involves a gradient penalty (obtained by autograd). Here is an example:\n\n```python\nimport torch\nimport torch.nn as nn\n\nx = torch.ones((1, 1, 4, 4)).requires_grad_(True)\nconv = nn.Conv2d(in_channels=x.shape[1], out_channels=1, kernel_size=3, padding=1)\n\ny = conv(x)\n\ngrads = torch.autograd.grad(\n outputs=y.sum(), inputs=x, create_graph=True, only_inputs=True\n)[0]\nloss = grads.sum()\nloss.backward()\nprint(conv.weight.grad) # returns something, as expected\nprint(x.grad) # is None, but should be **something**?\n```\n\nPretty much, my issue/question is shouldn't `x.grad` have some value? It is used as the input to `grads`, which is then used as a loss. \n\nHow do I actually obtain the input gradient for this case (for downstream verification purposes)?","reference_answer":"Hi! `grads` is the gradient of `y.sum()` with respect to `x`, which actually only depends on `conv.weight`. You can see that by fixing the values of `conv.weight` (for example by using `torch.manual_seed(0)` before instantiating it) and varying the values of `x`: you'll observe always the same value for `grads`.\n\nSo, since `grads` is independent of `x`, it's normal to have `x.grad` set to `None` after the call to `loss.backward()`.\n\nNote that if you compute `grads` with respect to the parameters rather than `x`, it will become dependent on the value of `x` (and independent of the value of the parameters), and so `x.grad` will be populated but not `conv.weight.grad`. Maybe this is what you intended to do?\n\n```python\nimport torch\nimport torch.nn as nn\n\nx = torch.ones((1, 1, 4, 4)).requires_grad_(True)\nconv = nn.Conv2d(in_channels=x.shape[1], out_channels=1, kernel_size=3, padding=1)\n\ny = conv(x)\n\ngrads = torch.autograd.grad(outputs=y.sum(), inputs=list(conv.parameters()), create_graph=True, only_inputs=True)[0] # Change in the inputs here\nloss = grads.sum()\nloss.backward()\nprint(conv.weight.grad) # None\nprint(x.grad) # something\n```\n\nLastly, the `only_inputs` parameter of `torch.autograd.grad` is deprecated so you can get rid of it (source: 2nd note of https://docs.pytorch.org/docs/stable/generated/torch.autograd.grad.html#torch-autograd-grad).\n\nI hope this helps! :)","needs_clarification":false,"thread_id":221786,"url":"https://discuss.pytorch.org/t/verifying-grad-x-after-autograd-double-backprop/221786","created_at":"2025-07-24T13:06:12.931000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["valerian.rey"],"answered_by_ptrblck":false} {"question":"Half Precision based training adaptations\n\nHello,\nI Wanted to try a few training recipes in fixed precision\n\n1. looking for documentation on how different modules in a model should be converted correctly\n my current setup just uses `model.half()` or `model.to(torch.float16)` it hasnot thrown any blocking errors, but i would like to setup my code correctly for future use\n2. loss scaling\n 1. current LRs for different highlevel modules are set to a known and stabilised config that works in single precision and mixed precision with `float16`/`bfloat16`\n 1. \\[edit\\] ofc i dont expect to keep these as final lrs in half precision, only using them as a starting point\n 2. when running half precision step 2 features outputs jump to `nan` from early layers\n 3. looking to use a scaler for the lossfunction at this stage but the `amp.GradScaler` returns\n 4. ```bash\n File \".../trainers.py\", line 92, in run_step\n self.scaler.unscale_(self.optimizer)\n File \".../python3.12/site-packages/torch/amp/grad_scaler.py\", line 342, in unscale_\n optimizer_state[\"found_inf_per_device\"] = self._unscale_grads_(\n ^^^^^^^^^^^^^^^^^^^^^\n File \".../python3.12/site-packages/torch/amp/grad_scaler.py\", line 264, in _unscale_grads_\n raise ValueError(\"Attempting to unscale FP16 gradients.\")\n ValueError: Attempting to unscale FP16 gradients.\n \n ```\n 5. ```python\n #scaling code\n self.scaler.scale(loss).backward()\n self.scaler.unscale_(self.optimizer)\n if self.cfg.clip_grad is not None:\n torch.nn.utils.clip_grad_norm_(\n self.model.parameters(), self.cfg.clip_grad\n )\n self.scaler.step(self.optimizer)\n \n # When enable amp, optimizer.step call are skipped if the loss scaling factor is too large.\n # Fix torch warning scheduler step before optimizer step.\n scaler = self.scaler.get_scale()\n self.scaler.update()\n if scaler <= self.scaler.get_scale():\n self.scheduler.step()\n ```\n 6. What would be the correct way to implement loss scaling in such a configuration with any pytorch based modules?","reference_answer":"Hii\n\n`GradScaler` is designed to work in mixed precision training,\n\n`scaler.unscale_(optimizer)` expects model params and grads to be in `float32` to unscale the grads after back propagating a scaled loss\n\nyou’re facing the error cuz your model weights are in `float16` which isn’t supported by `GradScaler`\n\nwhen working fully in half precision you’ll have to handle loss scale / unscale manually (and carefully) to avoid over / under flows, \n\n(no need to unscale grads if your model is fully in half precision tho since everything is already in `float16`)","needs_clarification":false,"thread_id":221996,"url":"https://discuss.pytorch.org/t/half-precision-based-training-adaptations/221996","created_at":"2025-08-02T10:57:16.182000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["Dhia-naouali"],"answered_by_ptrblck":false} {"question":"`torchvision` v2 transforms not applying to both image and mask\n\n`torchvision.transforms.v2.Compose` with paired transforms like `RandomHorizontalFlip` and `RandomVerticalFlip` applies only to the image, not to the mask.\n\nExpected behavior: when using paired transforms and passing a tuple `(image, mask)`, both should be flipped identically.\n\nObserved: only the image is flipped; the mask is unchanged.\n\n```python\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision.transforms.v2 import RandomHorizontalFlip, RandomVerticalFlip, Compose\nfrom torchvision.transforms.v2.functional import pil_to_tensor\nimport matplotlib.pyplot as plt\nfrom PIL import Image, ImageDraw\n\ndef create_triangle_image(size=64):\n img = Image.new(\"RGB\", (size, size), \"black\")\n draw = ImageDraw.Draw(img)\n draw.polygon([(63, 0), (63, 31), (32, 0)], fill=\"white\")\n return img\n\nclass TriangleDataset(Dataset):\n def __init__(self, transform=None):\n pil_img = create_triangle_image()\n self.img = pil_to_tensor(pil_img)\n self.mask = self.img[0].unsqueeze(0) # 1 channel mask\n self.transform = transform\n\n def __getitem__(self, idx):\n if self.transform:\n img_tr, mask_tr = self.transform(self.img, self.mask)\n return img_tr, mask_tr\n\n def __len__(self):\n return 1\n\ntransforms = Compose([\n RandomHorizontalFlip(p=.50),\n RandomVerticalFlip(p=.50),\n])\n\ndataset = TriangleDataset(transform=transforms)\nimg, mask = next(iter(DataLoader(dataset)))\n\n# Plot\nfig, axs = plt.subplots(1, 2, figsize=(6, 3))\naxs[0].imshow(img[0].permute(1, 2, 0), cmap='gray')\naxs[0].set_title(\"Image\")\naxs[1].imshow(mask[0][0], cmap='gray')\naxs[1].set_title(\"Mask\")\nfor ax in axs:\n ax.axis(\"off\")\nplt.tight_layout()\nplt.show()\n```\n\nResults (multiple runs):\n\n[image]\n\n[image]\n\n[image]\n\nHow to fix this?","reference_answer":"This is expected behavior in the `transforms.v2` API according to the [docs](https://docs.pytorch.org/vision/main/auto_examples/transforms/plot_transforms_getting_started.html#what-do-i-pass-as-input):\n\n> If there is no [`Image`](https://docs.pytorch.org/vision/main/generated/torchvision.tv_tensors.Image.html#torchvision.tv_tensors.Image \"torchvision.tv_tensors.Image\") or [`Video`](https://docs.pytorch.org/vision/main/generated/torchvision.tv_tensors.Video.html#torchvision.tv_tensors.Video \"torchvision.tv_tensors.Video\") instance, only the first pure [`torch.Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor \"(in PyTorch v2.7)\") will be transformed as image or video, while all others will be passed-through. Here “first” means “first in a depth-wise traversal”.\n\nYou could use the `tv_tensors` classes instead:\n\n```python\nimg_tv = torchvision.tv_tensors.Image(img)\nmask_tv = torchvision.tv_tensors.Mask(mask)\n\nout1, out2 = transforms(img_tv, mask_tv)\n```","needs_clarification":false,"thread_id":222034,"url":"https://discuss.pytorch.org/t/torchvision-v2-transforms-not-applying-to-both-image-and-mask/222034","created_at":"2025-08-04T09:55:51.514000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"What version of Pytorch is compatible with NVIDIA GeForce GTX 1080\n\nI updated my Pytorch installation last night, but now I am getting a message:\n\n> UserWarning:\n> Found GPU1 NVIDIA GeForce GTX 1080 which is of cuda capability 6.1.\n> PyTorch no longer supports this GPU because it is too old.\n> The minimum cuda capability supported by this library is 7.5.\n\nMy current Cuda version is 12.9. I am running Ubuntu 24.04.\n\nI checked Chatgpt and it was telling me all sorts of things about using using CUDA 11.8 and reducing the versions for a bunch of different packages. That sounded a bit suspicious to me, so I figured I would check.\n\nI consulted the documentation on the pytorch website, but all of the different versions of cuda, and pytorch, and cudatoolkit, etc., are confusing me. And I am worried about doing major surgery on my cuda installations and then putting that whole ecosystem into an unrecoverable state. \n\nCan someone indicate what the correct pytorch version is for a GTX 1080 now? I imagine pytorch 2.5 works with cuda 12.9, as that is what I had before. Sorry if this question is too direct, however I did consult multiple sources before finally posting here. Any suggestions are appreciated.","reference_answer":"Install either any older binaries (<=2.7.1) or our current binaries built with CUDA 12.6.","needs_clarification":false,"thread_id":222056,"url":"https://discuss.pytorch.org/t/what-version-of-pytorch-is-compatible-with-nvidia-geforce-gtx-1080/222056","created_at":"2025-08-04T21:45:55.964000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Reproducibility on different platform\n\nIs 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?","reference_answer":"No, there is no guarantee to create bitwise identical results on different setups and platforms.","needs_clarification":false,"thread_id":222071,"url":"https://discuss.pytorch.org/t/reproducibility-on-different-platform/222071","created_at":"2025-08-05T08:49:45.089000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Efficient dataset saving/loading for large PyG graphs (8000 patients or more)\n\nHi everyone\n\nI am building a large torch_geometric dataset with \\~8,000 object(.pt) , are patients in my case.\nEach patient contains several tensors, producing a Data object (node features, edge indices, and a single target value).\n\nOriginally, I saved each graph as a separate .pt file, so I had \\~2000 files for a smaller test case(around 200 GB). This was easy to load but took too much storage space.\n\nI tried to reduce it, saving batches of 20 graphs into a single compressed file (.pt.xz).\n\nthe reduction of space was drastic ! but loading and training was impossible.\n\nWhat’s the recommended PyTorch/PyG-friendly way to:\n\nStore large datasets of graphs efficiently (compression + batching)?\n\nLoad them quickly in **getitem** without hanging?\n\nKeep global indices consistent after batching?\n\nThank you\n\nany advice is welcome","reference_answer":"After many attempts, I finally found an effective way to compress my dataset without slowing down the training phase. I now save batches of 20 graphs into a single compressed file using LZ4 compression (.pkl) with `joblib.dump`, and later load them with `joblib.load`. This approach drastically reduced the dataset size—from 1TB down to 80GB.\"","needs_clarification":false,"thread_id":222187,"url":"https://discuss.pytorch.org/t/efficient-dataset-saving-loading-for-large-pyg-graphs-8000-patients-or-more/222187","created_at":"2025-08-08T16:26:03.640000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["hadrien_calmet"],"answered_by_ptrblck":false} {"question":"Bug? RMSNorm slower than LayerNorm\n\nHi,\n\nI have replaced nn.LayerNorm with nn.RMSNorm. RMSNorm should be significantly faster I thought.\n\nIn practice this slowed my project down. Now I have written a short script to test, and indeed LayerNorm seems to be much faster. How is this possible? I have entered my specific shapes from my project and the results from the comparison below.\n\nScript to test:\n\n```\nimport torch\nimport time\n\nbatch_size = 1\nseq_len = 14400#57600\nhidden_dim = 384#192\ndevice = \"cuda\" # or \"cpu\"\n\n# Create sample tensors matching your data\nx = torch.randn(batch_size, seq_len, hidden_dim, device=device)\n\n# Initialize both norms\nlayer_norm = torch.nn.LayerNorm(hidden_dim).to(device)\nrms_norm = torch.nn.RMSNorm(hidden_dim).to(device) # or your implementation\n\n# Warmup\nfor _ in range(10):\n _ = layer_norm(x)\n _ = rms_norm(x)\n\n# Benchmark LayerNorm\ntorch.cuda.synchronize()\nstart = time.time()\nfor _ in range(1000):\n out_ln = layer_norm(x)\ntorch.cuda.synchronize()\nln_time = time.time() - start\n\n# Benchmark RMSNorm\ntorch.cuda.synchronize()\nstart = time.time()\n\nfor _ in range(1000):\n out_rms = rms_norm(x)\ntorch.cuda.synchronize()\nrms_time = time.time() - start\n\nprint(torch.__version__)\nprint(f\"LayerNorm: {ln_time:.4f}s\")\nprint(f\"RMSNorm: {rms_time:.4f}s\")\nprint(f\"RMSNorm is {ln_time/rms_time:.2f}x {'faster' if rms_time < ln_time else 'slower'}\")\n```\n\nAnd the results are:\n\n| Shape | LayerNorm | RMSNorm |\n|----|----|----|\n| (1,14400, 384) | 0.0683s | 0.1687s |\n| (1, 57600, 192) | 0.2244s | 0.3555s |\n\nshouldn’t the results be exactly the opposite?\nI am using torch 2.6.0+cu124; but have similar results with torch 2.8. I am running this on a A100","reference_answer":"[This PR](https://github.com/pytorch/pytorch/pull/153666) should improve it.","needs_clarification":false,"thread_id":222330,"url":"https://discuss.pytorch.org/t/bug-rmsnorm-slower-than-layernorm/222330","created_at":"2025-08-13T12:58:30.656000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"What are some common reasons that loss may increase towards the end of an epoch?\n\nI’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.\n\nI’ve done some googling but was curious if anyone else has encountered this and if so what the common culprits are.\n\nSomething like this:\n\n```bash\n--- Epoch 4 ---\nEpoch 4 | Round 0: Loss = 0.1609647423028946 Validation Loss = 0.16069461405277252\nEpoch 4 | Round 100: Loss = 0.7978596687316895 Validation Loss = 0.7975720167160034\nEpoch 4 | Round 200: Loss = 0.6700431704521179 Validation Loss = 0.669928789138794\nEpoch 4 | Round 300: Loss = 2.1349849700927734 Validation Loss = 2.134230613708496\nEpoch 4 | Round 400: Loss = 2.5852344036102295 Validation Loss = 2.5841891765594482\nEpoch 4 | Round 500: Loss = 2.864406108856201 Validation Loss = 2.86250376701355\n--- Epoch 5 ---\nEpoch 5 | Round 0: Loss = 0.09773023426532745 Validation Loss = 0.09760947525501251\nEpoch 5 | Round 100: Loss = 0.4646699130535126 Validation Loss = 0.46453770995140076\nEpoch 5 | Round 200: Loss = 0.4494265019893646 Validation Loss = 0.44930222630500793\nEpoch 5 | Round 300: Loss = 1.3677105903625488 Validation Loss = 1.3674801588058472\nEpoch 5 | Round 400: Loss = 2.0765790939331055 Validation Loss = 2.0757954120635986\nEpoch 5 | Round 500: Loss = 2.258286952972412 Validation Loss = 2.2565605640411377\n--- Epoch 6 ---\nEpoch 6 | Round 0: Loss = 0.0712127760052681 Validation Loss = 0.0711481124162674\nEpoch 6 | Round 100: Loss = 0.2980029582977295 Validation Loss = 0.2978473901748657\nEpoch 6 | Round 200: Loss = 0.2850055694580078 Validation Loss = 0.28492817282676697\nEpoch 6 | Round 300: Loss = 0.9372814893722534 Validation Loss = 0.9373258948326111\nEpoch 6 | Round 400: Loss = 1.617525339126587 Validation Loss = 1.61699640750885\nEpoch 6 | Round 500: Loss = 1.804351806640625 Validation Loss = 1.8027862310409546\n```\n\nAlso seeing now in training with a larger dataset that sometimes loss spikes and then falls off immediately again:\n\n```\n--- Epoch 7 ---\nEpoch 7 | Round 0: Loss = 0.0009140036418102682 Validation Loss = 0.0009111818508245051\nEpoch 7 | Round 100: Loss = 0.00033618774614296854 Validation Loss = 0.0003360148111823946\nEpoch 7 | Round 200: Loss = 0.0008071979973465204 Validation Loss = 0.0008058046805672348\nEpoch 7 | Round 300: Loss = 0.0006388478213921189 Validation Loss = 0.0006378054386004806\nEpoch 7 | Round 400: Loss = 0.00026883321697823703 Validation Loss = 0.0002683177881408483\nEpoch 7 | Round 500: Loss = 0.00016036085435189307 Validation Loss = 0.00016005177167244256\nEpoch 7 | Round 600: Loss = 0.00012482452439144254 Validation Loss = 0.00012471845548134297\nEpoch 7 | Round 700: Loss = 0.0006077916477806866 Validation Loss = 0.0006070979870855808\nEpoch 7 | Round 800: Loss = 0.0002059808321064338 Validation Loss = 0.0002061814011540264\nEpoch 7 | Round 900: Loss = 0.0007044092635624111 Validation Loss = 0.0007117609493434429\nEpoch 7 | Round 1000: Loss = 6.421970465453342e-05 Validation Loss = 6.438294803956524e-05\nEpoch 7 | Round 1100: Loss = 0.00015985441859811544 Validation Loss = 0.00016017867892514914\nEpoch 7 | Round 1200: Loss = 0.0011026774300262332 Validation Loss = 0.0011021472746506333\nEpoch 7 | Round 1300: Loss = 0.0001646105374675244 Validation Loss = 0.0001643123832764104\nEpoch 7 | Round 1400: Loss = 0.00017581842257641256 Validation Loss = 0.00017495454812888056\nEpoch 7 | Round 1500: Loss = 9.868131019175053e-05 Validation Loss = 9.85043661785312e-05\nEpoch 7 | Round 1600: Loss = 5.0628019380383193e-05 Validation Loss = 5.0486214604461566e-05\nEpoch 7 | Round 1700: Loss = 0.00028382311575114727 Validation Loss = 0.0002849879383575171\nEpoch 7 | Round 1800: Loss = 0.0003619095077738166 Validation Loss = 0.0003625099780037999\nEpoch 7 | Round 1900: Loss = 9.860018326435238e-05 Validation Loss = 9.906368359224871e-05\n```","reference_answer":"Check that your data is shuffled properly. If the training data is fed in the same order in every epoch, that is the likely cause of the loss rising toward the end of an epoch. Shuffle the data so that the order changes between epochs.","needs_clarification":false,"thread_id":222387,"url":"https://discuss.pytorch.org/t/what-are-some-common-reasons-that-loss-may-increase-towards-the-end-of-an-epoch/222387","created_at":"2025-08-15T21:07:47.107000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["anthonycodes","ptrblck"],"answered_by_ptrblck":true} {"question":"RTX 5090 Not Detected by PyTorch 2.2.0\n\nPyTorch 2.2.0+cu121 fails to detect NVIDIA GeForce RTX 5090 (32GB) even though the GPU is properly installed and recognized by nvidia-smi.\n\n### **Environment**\n\n* **PyTorch Version**: 2.2.0+cu121\n\n* **GPU**: NVIDIA GeForce RTX 5090 (32GB GDDR7)\n\n* **CUDA Version**: 12.8 (Driver 570.181)\n\n* **OS**: Ubuntu (Linux)\n\n* **Python**: 3.12.3\n\n* **Motherboard**: X870E\n\n### **Reproduction**\n\n```\nimport torch\nprint(f\"CUDA Available: {torch.cuda.is_available()}\") # Returns False\nprint(f\"GPU Count: {torch.cuda.device_count()}\") # Returns 0\n```","reference_answer":"RTX 5090 Working with PyTorch!\n\nPyTorch nightly build with CUDA 12.8 support exists! Tough find and thank you\n\n```\npip install --pre torch --index-url https://download.pytorch.org/whl/nightly/cu128\n```","needs_clarification":false,"thread_id":222399,"url":"https://discuss.pytorch.org/t/rtx-5090-not-detected-by-pytorch-2-2-0/222399","created_at":"2025-08-16T13:09:30.478000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["Pete_Broznak"],"answered_by_ptrblck":false} {"question":"RuntimeError: CUDA error: device-side assert triggered with Llama2\n\nI want to get a list of indexes for text items where the LLM’s output has the same sentiment as the input. However, I’m getting errors in PyTorch and don’t understand why.\n\n/pytorch/aten/src/ATen/native/cuda/Indexing.cu:1369: indexSelectSmallIndex: block: \\[21,0,0\\], thread: \\[1,0,0\\] Assertion srcIndex < srcSelectDimSize failed./pytorch/aten/src/ATen/native/cuda/Indexing.cu:1369: indexSelectSmallIndex: block: \\[21,0,0\\], thread: \\[2,0,0\\] Assertion srcIndex < srcSelectDimSize failed.\n\nRuntimeError Traceback (most recent call last)/tmp/ipykernel_94/921698949.py in ()----> 1 ng_ds_indxs = filter_input_by_output_sentiment(ng_dl, “NEGATIVE”)/tmp/ipykernel_94/4054871963.py in filter_input_by_output_sentiment(dataloader, expected_sentiment)2728 # Generate sequences for the whole batch—> 29 generated_ids = llm.generate(30 input_ids=input_ids,31 attention_mask=attention_mask,\n\n/tmp/ipykernel_94/3559914769.py in generate(self, input_ids, attention_mask, \\*\\*gen_kwargs)6061 with torch.no_grad():—> 62 generated_ids = self.model.generate(63 input_ids=input_ids,64 attention_mask=attention_mask,\n\nRuntimeError: CUDA error: device-side assert triggered\n\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\n\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1 Compile with TORCH_USE_CUDA_DSA to enable device-side assertions.\n\nMy Code:\n\n```python\ntokenizer = AutoTokenizer.from_pretrained(config.model_name_chat)\n\ntokenizer.model_max_length = 32\nif tokenizer.pad_token_id is None:\n tokenizer.pad_token_id = tokenizer.eos_token_id\n\nos.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n\nclass ConceptDataset(torch.utils.data.Dataset):\n def __init__(self, df, tokenizer):\n self.texts = df[\"review\"].tolist()\n self.tokenizer = tokenizer\n \n def __len__(self):\n return len(self.texts)\n\n def __getitem__(self, index):\n text = self.texts[index].strip()\n \n encoded = self.tokenizer(\n text,\n max_length=self.tokenizer.model_max_length,\n padding=\"max_length\",\n truncation=True,\n return_tensors=\"pt\"\n )\n \n return {\n \"ids\": encoded[\"input_ids\"].squeeze(0), # shape: (seq_len)\n \"mask\": encoded[\"attention_mask\"].squeeze(0), # shape: (seq_len)\n }\n\ntrain_pos_ds = ConceptDataset(df_train_pos, tokenizer)\nng_dl = DataLoader(train_ng_ds, batch_size=8, num_workers=workers, pin_memory=True)\n\ncompute_dtype = getattr(torch, \"float16\")\nbnb_config = BitsAndBytesConfig(\n load_in_4bit=True,\n bnb_4bit_quant_type=\"nf4\",\n bnb_4bit_compute_dtype=compute_dtype,\n bnb_4bit_use_double_quant=False,\n)\n\nmodel = AutoModelForCausalLM.from_pretrained(config.model_name_chat, device_map='auto', quantization_config=bnb_config)\n\nsentiment = pipeline(\"sentiment-analysis\", model=\"siebert/sentiment-roberta-large-english\", device=device, truncation=True, framework=\"pt\")\nclear_output()\n\ndef filter_input_by_output_sentiment(dataloader, expected_sentiment):\n\n valid_sentiments = {\"POSITIVE\", \"NEGATIVE\"}\n expected_sentiment = expected_sentiment.upper()\n if expected_sentiment not in valid_sentiments:\n raise ValueError(f\"expected_sentiment must be one of {valid_sentiments}, got '{expected_sentiment}'\")\n \n matching_indexes = []\n global_index = 0\n\n for batch in tqdm(dataloader, total=len(dataloader), desc=\"Filtering by sentiment\"):\n input_ids = batch[\"ids\"].to(device)\n attention_mask = batch[\"mask\"].to(device)\n\n generated_ids = model.generate(\n input_ids=input_ids,\n attention_mask=attention_mask,\n max_new_tokens=50,\n )\n\n batch_texts = []\n for i in range(input_ids.size(0)):\n input_len = input_ids.size(1)\n new_tokens = generated_ids[i][input_len:]\n text = tokenizer.decode(new_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=True)\n batch_texts.append(text)\n\n results = sentiment(batch_texts)\n\n for i, res in enumerate(results):\n if res[\"label\"] == expected_sentiment:\n matching_indexes.append(global_index + i)\n\n global_index += input_ids.size(0)\n\n return matching_indexes\n\nng_ds_indxs = filter_input_by_output_sentiment(ng_dl, \"NEGATIVE\")\n```","reference_answer":"Pass `pad_token_id=tokenizer.eos_token_id` to `model.generate`, and load the LLM with `device_map={\"\": 0}` instead of `device_map='auto'`.","needs_clarification":false,"thread_id":222425,"url":"https://discuss.pytorch.org/t/runtimeerror-cuda-error-device-side-assert-triggered-with-llama2/222425","created_at":"2025-08-17T18:21:31.890000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[3],"answer_authors":["nitay_shlump"],"answered_by_ptrblck":false} {"question":"C++ nn::module Pybind11 unexpected behavior\n\nHi,\n\nI have a mynet.cpp file defined as follows:\n\n```\n/* \nc++ -O3 -Wall -fvisibility=hidden -Winvalid-pch -shared -std=c++17 -fPIC `python3 -m pybind11 --includes` -I../../../extension-cpp-meson-murali/.venv/include/python3.13 -I../../../extension-cpp-meson-murali/.venv/lib/python3.13/site-packages/torch/include -I../../../extension-cpp-meson-murali/.venv/lib/python3.13/site-packages/torch/include/torch/csrc/api/include -D_GLIBCXX_USE_CXX11_ABI=1 '-DPYBIND11_BUILD_ABI=\"_cxxabi1016\"' '-DPYBIND11_COMPILER_TYPE=\"_gcc\"' '-DPYBIND11_STDLIB=\"_libstdcpp\"' -fPIC mynet.cpp -o mynet`python3-config --extension-suffix` -L../../../extension-cpp-meson-murali/.venv/lib/python3.13/site-packages/torch/lib -ltorch -ltorch_cpu -lc10 -ltorch_python\n*/\n\n#include \n#include \n\nusing namespace torch;\n\nstruct NetImpl : public nn::Module {\n NetImpl(int64_t in_sz, int64_t out_sz) :\n lin1(nn::LinearOptions(in_sz, out_sz))\n {\n register_module(\"lin1\", lin1);\n }\n\n torch::Tensor forward(torch::Tensor x) {\n return lin1(x);\n }\n private:\n nn::Linear lin1;\n};\n\nTORCH_MODULE(Net);\n\nPYBIND11_MODULE(mynet, m) {\npy::class_>(m, \"NetImpl\");\n\npy::class_ /* <- specify C++ parent type */>(m, \"Net\")\n .def(py::init())\n .def(\"forward\", [] (Net& n, torch::Tensor x) { n->forward(x);} )\n .def(\"__call__\", [] (Net& n, torch::Tensor x) { n->forward(x);} );\n\n}\n\n```\n\nMy intent is to call the Net module from Python. I compiled it as follow and it compiles fine.\n\n```\n c++ -O3 -Wall -fvisibility=hidden -Winvalid-pch -shared -std=c++17 -fPIC `python3 -m pybind11 --includes` -I../../../extension-cpp-meson-murali/.venv/include/python3.13 -I../../../extension-cpp-meson-murali/.venv/lib/python3.13/site-packages/torch/include -I../../../extension-cpp-meson-murali/.venv/lib/python3.13/site-packages/torch/include/torch/csrc/api/include -D_GLIBCXX_USE_CXX11_ABI=1 '-DPYBIND11_BUILD_ABI=\"_cxxabi1016\"' '-DPYBIND11_COMPILER_TYPE=\"_gcc\"' '-DPYBIND11_STDLIB=\"_libstdcpp\"' -fPIC mynet.cpp -o mynet`python3-config --extension-suffix` -L../../../extension-cpp-meson-murali/.venv/lib/python3.13/site-packages/torch/lib -ltorch -ltorch_cpu -lc10 -ltorch_python\n```\n\nThis is how I am attempting to use it in Python:\n\n```\n python\nPython 3.13.5 (main, Jun 11 2025, 15:36:57) [GCC 11.4.0] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import torch\n>>> from mynet import Net\n>>> net = Net(10,10); x=torch.randn(10)\n>>> y=net(x)\n>>> x\ntensor([-0.0401, -0.1749, -1.1672, -0.1334, 0.6920, -0.4041, 0.3758, 1.1046,\n 2.0517, 1.3911])\n>>> y\n>>>\n```\n\nAs you can see there are no errors. But, nothing is printing for y. How can I make it work?","reference_answer":"The lambdas need a return statement. Both the lambda for `.def(\"forward\", ...)` and the one for `.def(\"__call__\", ...)` call `n->forward(x)` without returning its result.","needs_clarification":false,"thread_id":222530,"url":"https://discuss.pytorch.org/t/c-nn-module-pybind11-unexpected-behavior/222530","created_at":"2025-08-21T00:53:51.534000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[1,2],"answer_authors":["pya"],"answered_by_ptrblck":false} {"question":"How does optmizer work on sample specific parameters?\n\nI am solving a computer vision task and here is the context:\n\n* Assume we have a neural network where all the images will be passed through it during the training.\n* For image *i* there are several (0 to maybe 4) parameters which correspond to this single image. In other words, during training I want these parameters to be optimized as well.\n* The loss function for each image is the average of several constraints that apply to that image. Suppose we have a pool of \\~10 constraints, and an image may be evaluated by any subset of these (this subset is **not random**—it is determined according to the labels available for the image). The average represents the loss value.\n* When I solve the problem mathematically, it is shown that the system is **over-determined / over-constrained**. Meaning, in theory, there should exist an optimal solution to minimize the loss function.\n\n---\n\n### My questions:\n\n1. Is the following a logical and correct way to use the optimizer?\n\n ```python\n optimizer = Adam(parameters=list(model.parameters()) + image_specific_parameters_list, lr=...)\n ```\n\n2. If I evaluate each image according to the loss function (explained above), does the optimizer—upon calling `backward()`—understand that it should only optimize the parameters that correspond to the batch images?\n\n > Note: the model will be updated for all images, but those **image-specific parameters** must be updated only when the model sees those images during training.","reference_answer":"Hi Sepehr!\n\nYes – or at least maybe.\n\nIf you do not use momentum nor weight decay, then then calling `optimizer.step()` will\n\nonly modify parameters that have a non-zero `.grad`. Note that `Adam` *does* use momentum,\n\nso this particular optimizer probably won’t work for you. I would use (or at least start with)\n\n`SGD` (without momentum nor weight decay).\n\nIf indeed your computed loss value only depends on an “image-specific parameter” when\n\nthat particular image contributes to that loss, then calling `loss.backward()` will only\n\npopulate such parameters – those whose images contribute to the loss – with a non-zero\n\n`.grad`.\n\nSo, yes, if done with these points in mind, your scheme should work. Note that you can easily\n\ntest this. Perform a backward pass and optimizer step and check that only the appropriate\n\nimage-specific parameters have in fact been modified.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":222538,"url":"https://discuss.pytorch.org/t/how-does-optmizer-work-on-sample-specific-parameters/222538","created_at":"2025-08-21T08:05:23.190000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Case for calling forward() manually\n\nI have implemented the `forward()` which does the forward pass of the model.\n\nI 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, because `model.__call__()`has some extra code, although that is not when you call `forward()` from within the model, but externally. Should I call `self.forward()` manually from within `some_function()` in this case? What is the recommended way of doing this?","reference_answer":"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).","needs_clarification":false,"thread_id":222547,"url":"https://discuss.pytorch.org/t/case-for-calling-forward-manually/222547","created_at":"2025-08-21T12:21:26.069000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Confusion About LibTorch Binary Naming and ABI on \"Get Started\" Page\n\nHey all,\n\nI'm confused by the LibTorch binary naming and ABI labeling on the PyTorch \"Get Started\" page ([https://pytorch.org/get-started/locally/](https://pytorch.org/get-started/locally/)). When selecting **Linux** and **LibTorch** with **CUDA 12.6**, the page provides the following:\n\n* **Text**: \"Download here (cxx11 ABI)\"\n\n* **URL**: `https://download.pytorch.org/libtorch/cu126/libtorch-shared-with-deps-2.8.0%2Bcu126.zip`\n\nThe flavor text indicates this is a **C++11 ABI** binary, but the filename does **not** include \"cxx11-abi,\" unlike other binaries, such as:\n\n* `https://download.pytorch.org/libtorch/test/cpu/libtorch-cxx11-abi-shared-with-deps-latest.zip` (linked [here](https://dev-discuss.pytorch.org/t/pytorch-2-5-release-branch-cut-for-pytorch-core-is-completed/2452) for example)\n\nThis inconsistency is confusing. I believe in older PyTorch versions, the `libtorch-shared-with-deps` filename typically indicated a **Pre-cxx11 ABI** binary, while `libtorch-cxx11-abi-shared-with-deps` was used for the C++11 ABI. Has the naming convention changed, or is the flavor text on the \"Get Started\" page incorrect? Is the `libtorch-shared-with-deps-2.8.0+cu126.zip` binary truly compiled with the C++11 ABI?\n\nI’m using \\[GCC 9.3, and RL9\\] and would appreciate clarification on:\n\n1. Whether `libtorch-shared-with-deps-2.8.0+cu126.zip` is indeed a C++11 ABI binary.\n\n2. Any recommended steps to confirm the ABI of a LibTorch binary (e.g., via `nm` or a test program).\n\nThanks for any insights or confirmation!","reference_answer":"All of our builds should use the cxx11 ABI now after dropping legacy CUDA 11.8 builds and the file name of our `libtorch` builds should not indicate any ABI tag anymore. You can check it by printing symbols and filtering for e.g. `std::string` which should indicate if cxx11 ABI is used.","needs_clarification":false,"thread_id":222594,"url":"https://discuss.pytorch.org/t/confusion-about-libtorch-binary-naming-and-abi-on-get-started-page/222594","created_at":"2025-08-22T18:56:56.835000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Update gradients based on worst loss in set\n\nHi everyone! I’m still a bit unfamiliar with pytorch so my apologies if this is a dumb question.\n\nI have some data where each datapoint is a set of 10 vectors measuring the state of the same object in different circumstances. In total, the dataset comprises about 20k such sets each relating to a similar (but distinct) object and a label identifying each object as one of 3 classes. \n\nI want to train a simple model to classify of these objects robustly and, in order to do this, I want to compute the cross entropy loss for each vector and update my gradients based on the worst one. I tried doing the following but I think it isn’t computing the gradients before the max() as it isn’t learning at all.\n\n```python\nclass WorstLoss(nn.Module):\n def __init__(self):\n super().__init__()\n self.cross_entropy = nn.CrossEntropyLoss(reduction='none')\n\n def criterion(self, inputs, target):\n loss = self.cross_entropy(inputs, torch.ones(10).long().cuda() * target)\n return loss.max()\n\n def forward(self, inputs, target):\n batched_criterion = torch.vmap(self.criterion)\n return batched_criterion(inputs, target)\n```\n\nIs there a better approach to this? I might be missing something obvious, my apologies if that is the case. Any help would be much appreciated. Thank you for your time!","reference_answer":"Hi! Just to be sure that I understand everything (please correct me if I'm wrong):\n- Parameter `inputs` of criterion is of shape `(10,)`. All of them are obtained independently from a different input vector.\n- Parameter `target` of criterion is a scalar, so `torch.ones(10).long().cuda() * target` is of shape `(10,)`.\n- Parameter `inputs` of forward is of shape `(batch_size, 10)`.\n- Parameter `target` of forward is of shape `(batch_size,)`.\n\nI don't see anything that seems obviously wrong here. As a sanity check, have you tried replacing `loss.max()` by `loss.mean()`? Maybe it's actually the idea of minimizing the worst loss that prevents your model from training. Say that among your 10 vectors, one is always pure noise. It will likely have the worst loss among the 10. Using the worst loss prevents you entirely from training based on any of the other 9 vectors, so you wouldn't learn anything in this scenario.","needs_clarification":false,"thread_id":222598,"url":"https://discuss.pytorch.org/t/update-gradients-based-on-worst-loss-in-set/222598","created_at":"2025-08-22T21:09:49.455000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["valerian.rey"],"answered_by_ptrblck":false} {"question":"Module 'torch.library' has no attribute 'custom_op'\n\nFirst time posting here - the context: \n\nI just wanted to try the below sourcecode from HuggingFace \n\n```\n#%matplotlib inline\n```\n\n```\nimport torch\n```\n\n```\n\n```\n\n```\nfrom diffusers.pipelines import DiffusionPipeline\n```\n\n```\nfrom matplotlib import pyplot as plt \n```\n\n```\nmodel_id = \"\"\n```\n\n```\n\n```\n\n```\nldm = DiffusionPipeline.from_pretrained(model_id)\n```\n\n```\nprompt = \"PastelPusheen\"\n```\n\n```\nimages = ldm([prompt], num_inference_steps=50, eta=0.3, guidance_scale=6)[\"sample\"]\n```\n\n```\nplt.imshow(images[0])\n```\n\nOnce it’s run it threw me this error \n\n`Traceback (most recent call last):`\n`File “/Users/Casey/Desktop/myDevPortFolio/PastelPusheenGenV2/psndf.py”, line 6, in `\n`from diffusers.pipelines import DiffusionPipeline`\n`File “”, line 1075, in _handle_fromlist`\n`File “/Users/Casey/Desktop/myDevPortFolio/PastelPusheenGenV2/my-env/lib/python3.10/site-packages/diffusers/utils/import_utils.py”, line 943, in `**`getattr`**\n`module = self._get_module(self._class_to_module[name])`\n`File “/Users/Casey/Desktop/myDevPortFolio/PastelPusheenGenV2/my-env/lib/python3.10/site-packages/diffusers/utils/import_utils.py”, line 955, in _get_module`\n`raise RuntimeError(`\n`RuntimeError: Failed to import diffusers.pipelines.pipeline_utils because of the following error (look up to see its traceback):`\n`Failed to import diffusers.models.autoencoders.autoencoder_kl because of the following error (look up to see its traceback):`\n\nI don’t understand this - I tried deleting and re-installing pytorch etc but none of them helped. Could anyone point me in the right direction?","reference_answer":"I solve it by updating pytorch to 2.5.0","needs_clarification":true,"thread_id":222610,"url":"https://discuss.pytorch.org/t/module-torch-library-has-no-attribute-custom-op/222610","created_at":"2025-08-23T10:31:35.901000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[6],"answer_authors":["jhon_How"],"answered_by_ptrblck":false} {"question":"RuntimeError for torch.nn.Conv2D on GPU\n\nHi,\n\nI 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 models still would not work.\n\nThese CNN models will run fine on the machine’s CPUs. Also, several fully-connected models will run fine on the CPUs and on the GPU of the same machine.\n\nIt looks to be an issue with torch.nn.Conv2d on the GPU:\n\n```python\n>>> # sample data\n>>> tc = torch.rand(1, 3, 32, 32)\n>>> tg = tc.to(\"cuda\")\n>>> tc\ntensor([[[[0.0561, 0.9214, 0.1704, ..., 0.5051, 0.7754, 0.6535],\n [0.0134, 0.1657, 0.0521, ..., 0.0093, 0.5785, 0.1803],\n [0.5017, 0.2229, 0.7540, ..., 0.7423, 0.1124, 0.1602],\n ...,\n [0.3201, 0.4387, 0.9313, ..., 0.4546, 0.1426, 0.6919],\n [0.8512, 0.6011, 0.8389, ..., 0.5267, 0.1820, 0.7977],\n [0.4766, 0.8551, 0.9409, ..., 0.9309, 0.7472, 0.6058]]]])\n>>> tg\ntensor([[[[0.0561, 0.9214, 0.1704, ..., 0.5051, 0.7754, 0.6535],\n [0.0134, 0.1657, 0.0521, ..., 0.0093, 0.5785, 0.1803],\n [0.5017, 0.2229, 0.7540, ..., 0.7423, 0.1124, 0.1602],\n ...,\n [0.3201, 0.4387, 0.9313, ..., 0.4546, 0.1426, 0.6919],\n [0.8512, 0.6011, 0.8389, ..., 0.5267, 0.1820, 0.7977],\n [0.4766, 0.8551, 0.9409, ..., 0.9309, 0.7472, 0.6058]]]],\n device='cuda:0')\n```\n\nLayers for testing:\n\n```python\n>>> # test layers\n>>> f = torch.nn.Linear(3*32*32, 5000)\n>>> c = torch.nn.Conv2d(3, 5, 3)\n```\n\nLinear layer runs fine on CPUs and GPU:\n\n```python\n>>> f.cpu()\nLinear(in_features=3072, out_features=5000, bias=True)\n>>> f(tc.flatten())\ntensor([ 0.2194, 0.1203, -0.1636, ..., -0.2210, 0.1886, -0.1382],\n grad_fn=)\n>>> \n>>> f.cuda()\nLinear(in_features=3072, out_features=5000, bias=True)\n>>> f(tg.flatten())\ntensor([ 0.2194, 0.1203, -0.1636, ..., -0.2210, 0.1886, -0.1382],\n device='cuda:0', grad_fn=)\n```\n\nConv2d layer runs fine on CPUs, but not on GPU:\n\n```python\n>>> c.cpu()\nConv2d(3, 5, kernel_size=(3, 3), stride=(1, 1))\n>>> c(tc)\ntensor([[[[ 0.0431, 0.3884, 0.4317, ..., 0.1419, 0.0886, 0.2196],\n [ 0.0216, 0.1064, 0.1294, ..., -0.1102, 0.1265, 0.1598],\n [-0.1942, -0.2963, -0.1341, ..., 0.0938, -0.1480, 0.0014],\n ...,\n [ 0.2905, -0.0233, 0.2386, ..., 0.0513, -0.0833, 0.1232],\n [-0.0871, 0.2138, -0.1608, ..., 0.1215, -0.0795, 0.2471],\n [ 0.2254, 0.2198, 0.0156, ..., 0.3266, -0.0789, -0.0808]]]],\n grad_fn=)\n>>> \n>>> c.cuda()\nConv2d(3, 5, kernel_size=(3, 3), stride=(1, 1))\n>>> c(tg)\nTraceback (most recent call last):\n File \"\", line 1, in \n c(tg)\n ~^^^^\n File \"/home/tstravers/software/miniforge3/envs/tester/lib/python3.13/site-packages/torch/nn/modules/module.py\", line 1739, in _wrapped_call_impl\n return self._call_impl(*args, **kwargs)\n ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^\n File \"/home/tstravers/software/miniforge3/envs/tester/lib/python3.13/site-packages/torch/nn/modules/module.py\", line 1750, in _call_impl\n return forward_call(*args, **kwargs)\n File \"/home/tstravers/software/miniforge3/envs/tester/lib/python3.13/site-packages/torch/nn/modules/conv.py\", line 554, in forward\n return self._conv_forward(input, self.weight, self.bias)\n ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/tstravers/software/miniforge3/envs/tester/lib/python3.13/site-packages/torch/nn/modules/conv.py\", line 549, in _conv_forward\n return F.conv2d(\n ~~~~~~~~^\n input, weight, bias, self.stride, self.padding, self.dilation, self.groups\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n )\n ^\nRuntimeError: GET was unable to find an engine to execute this computation\n```\n\nI tried searching for the specific RuntimeError, but I don’t think it’s an out-of-memory issue for this toy Conv2d code (also, I had some larger CNN models running on the same machine earlier this year).\n\nOutput of nvidia-smi:\n\n```bash\n+-----------------------------------------------------------------------------------------+\n| NVIDIA-SMI 575.64.05 Driver Version: 575.64.05 CUDA Version: 12.9 |\n|-----------------------------------------+------------------------+----------------------+\n| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |\n| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |\n| | | MIG M. |\n|=========================================+========================+======================|\n| 0 NVIDIA GeForce GT 1030 Off | 00000000:01:00.0 On | N/A |\n| 41% 42C P8 N/A / 19W | 417MiB / 2048MiB | 0% Default |\n| | | N/A |\n+-----------------------------------------+------------------------+----------------------+\n```\n\nWould appreciate any help or advice on troubleshooting this RuntimeError. Thank you!","reference_answer":"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`.","needs_clarification":false,"thread_id":222649,"url":"https://discuss.pytorch.org/t/runtimeerror-for-torch-nn-conv2d-on-gpu/222649","created_at":"2025-08-25T21:38:43.596000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Avoid OOM due to optimizer state in DDP\n\nI have a model for which gradient computations work fine, but then I get OOM when runnning `optimizer.step()` with Adam. I understand the Adam optimizer state needs much more memory due to first and second deltas and `float32`. But I fail to understand why that is really an issue.\n\nWould it not be very simple to offload this optimizer state to CPU and then do the update computations in blocks of smaller size? The Adam updates are fully separable between parameters, and CPU offloading and doing it in blocks should be highly subdominant to computing gradients.\n\nAm I missing something? Is this implemented somewhere?","reference_answer":"Moving the model back and forth between CPU and GPU in each iteration would cause a large performance regression, since DDP keeps the model on the devices it uses without triggering any copies. DDP clones the model only once at initialization, from rank 0 to all other ranks. After that, each rank uses its own clone, and only the gradients are synchronized. For this use case, you might be interested in [ZeRO-Offload](https://www.deepspeed.ai/tutorials/zero-offload/).","needs_clarification":false,"thread_id":222716,"url":"https://discuss.pytorch.org/t/avoid-oom-due-to-optimizer-state-in-ddp/222716","created_at":"2025-08-28T10:36:26.112000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[3,5],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Important pitfall! Scaling labels in Regression? Labels as dtype long or float32?\n\nMy question is generic in nature but an important pitfall!\n\nDo I need to scale my regression problem’s labels? Can labels be used as torch.long dtype for regression problems or we need to use only float32/float64.\n\nFor those interested in specific context: I played with load_diabetes dataset\n\nfrom the sklearn package. This dataset has all the labels are from 25 - 346 as int type.\n\nWhen I do not scale the labels, my model predicts and outputs values that seems to be in floats\n\nfrom 0 and onwards. So error is huge.\n\nHowever, when I scale the labels, (using MinMaxScaler); I have a scaled output and then I inverse_transform it to get fairly accurate results. So why does the scaling works and non-scaling does not work? Is their a way to get outputs with non-scaled case as values that are in tens or hundreds?\n\n\\*\\*My data is defined as:\n\n# torchifying via dataset class\\*\\*\n\n`class dataset(Dataset):`\n` def __`**`init__`**`(self, input_features, output_labels):`\n` self.input_features = torch.tensor(input_features, dtype= torch.float32).to(device)`\n` self.output_labels = torch.tensor(output_labels, dtype= torch.float32).to(device)`\n` def __`**`len__`**`(self):`\n` return len(self.input_features)`\n` def`**`__getitem__`**`(self,index): # gives complete data for that row`\n` return self.input_features[index], self.output_labels[index]`\n\n## Model\n\n`class MyModel(nn.Module):`\n` def`**`__init__`**`(self):`\n` super(MyModel, self).`**`__init__`**`()`\n` self.first = nn.Linear(X.shape[1], 192) # .shape[1] no. of features`\n` self.first_relu = nn.ReLU()`\n` self.second = nn.Linear(192,96)`\n` self.second_relu = nn.ReLU()`\n` self.third = nn.Linear(96,48)`\n` self.third_relu = nn.ReLU()`\n` self.fourth = nn.Linear(48, 12)`\n` self.fourth_relu = nn.ReLU()`\n` self.fifth = nn.Linear(12, 6)`\n` self.fifth_relu = nn.ReLU()`\n` self.sixth = nn.Linear(6, 1)`\n\n```\n# regression has only one output\n\n def forward(self, xx):\n xx = self.first(xx)\n xx = self.first_relu(xx)\n xx = self.second(xx)\n xx = self.second_relu(xx)\n xx = self.third(xx)\n xx = self.third_relu(xx)\n xx = self.fourth(xx)\n xx = self.fourth_relu(xx)\n xx = self.fifth(xx)\n xx = self.fifth_relu(xx)\n xx = self.sixth(xx)\n return xx\n```\n\n`model = MyModel().to(device) # initialize the class and then give to device`\n`summary(model, input_size = (X.shape[1],))`","reference_answer":"Hi Noob!\n\nThe short story is that you should follow the standard advice and scale your\ndata (input data as well labels).\n\nYou don't *need* to, but you generally want to.\n\nWhy? Because with pytorch's default initializations, a randomly initialized\nmodel will start out making predictions that are, roughly speaking, of order one.\nSo your model not only has to learn the real substance of your problem, it also\nhas to learn to make predictions that are not (roughly speaking) of order one.\nThis can slow training and possibly cause instability in early training.\n\n(If your labels are large compared to the finite-precision or dynamic range of\nfloating-point arithmetic, additional precision / range issues can arise.)\n\nYes, but ...\n\nYour prediction has to be some sort of float (in order for autograd to be able\nto backpropagate). Your loss criterion (typically something like `MSELoss`)\nwill generally upcast the type of your labels to match that of your predictions.\n\nAs a matter of programming style (\"say what you mean\"), I would generally have\nthe type of my labels (what the pytorch documentation usually calls `target`)\nexplicitly match that of the predictions -- but this is just style.\n\nGenerally, no, although you could certainly write a loss criterion that requires\nthe prediction and label types to match.\n\nWhat do you mean by \"error is huge\"?\n\nLet's say that your labels start out of order 100, but you scale them down to\norder 1 and you successfully train your model to give predictions of order 1\nthat achieve a `MSELoss` of, say, 0.3. Now let's say that you don't scale\nyour labels and again successfully train your model. Your predictions will\nnow be of order 100, and let's assume that you're in fact getting the same\npredictions as before, just scaled by a factor of 100. Your `MSELoss` will\nnow get scaled by a factor of 100**2, so will therefore be 3000. Naively\n3000 looks like a big number. Is that what you mean by huge? If so, it's\nnot really huge -- it's the same as before, just scaled up.\n\nOn the other hand, if your unscaled model doesn't train successfully, you\ncould get a `MSELoss` of, say, 1.e7 that would be \"huge\" even relative to\nyour unscaled predictions and labels.\n\nYou should be able to. As mentioned above, unscaled labels could slow training.\nSo start by training longer. Also, unscaled labels could cause instability in\nearly training. So start by training with a small (or very small) learning rate\nuntil you get past such instabilities and your model starts making predictions\ncloser in scale to your predictions. Then you can increase your learning rate\nback up to a more typical value.\n\nNote, however, that if your unscaled labels (and predictions) are a factor of\n100 larger than your scaled values, a `MSELoss` loss value will be 1.e4 times\nlarger (as will the gradients produced by backpropagation). For many optimizers,\ne.g., `SGD`, this will have the same effect as training with the scaled data, but\nusing a learning rate that is, figuratively speaking, 1.e4 times as large.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":222731,"url":"https://discuss.pytorch.org/t/important-pitfall-scaling-labels-in-regression-labels-as-dtype-long-or-float32/222731","created_at":"2025-08-29T06:22:41.424000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Ignore specific GPU with pytorch in Anaconda\n\nFor context, I am trying to get whisperX running locally and followed this guide, installing it in Anaconda (https://www.youtube.com/watch?v=zIvcu8szpxw)\n\nfor a little more context…. my coding is FULLY reliant on instructions (I’m trying to transcribe DnD sessions I am running)\n\nso….\nright now when I try to run the whisperX python code (https://github.com/m-bain/whisperX?tab=readme-ov-file#python-usage-) I am getting the following message before the Kernel dies.\n\n> C:\\\\Users\\\\XXX.conda\\\\envs\\\\whisperx\\\\lib\\\\site-packages\\\\torch\\\\cuda\\_*init*\\_.py:283: UserWarning:\n> Found GPU1 NVIDIA GeForce GTX 1070 which is of cuda capability 6.1.\n> Minimum and Maximum cuda capability supported by this version of PyTorch is\n> (7.0) - (12.0)\n>\n> (followed by some related warnings telling me where to download the correct version, etc)\n\nBesides this 1070 which I am using for it’s additional VRam when playing with LLMs, I have an RTX 3070 installed that does support the correct CUDA version\n\nrunning *nvidia-smi* will list the RTX 3070 as GPU-0 and the 1070 as GPU-1 (which is the way it’s supposed to be)\n\nand lists the current cuda version as 13.0 (trying to install v12.6 as per the torch website gives the response that the requirements are already fulfilled)\n\n---\n\nI can change the python code to\n\n> device = “cpu”\n> compute_type = \"int8\n\nand it will run correctly\n\nhow can I make sure that Torch only tries to run off GPU-0, aka the 3070 while ignoring the 1070 and it’s insufficient CUDA version\n\nno combination of gpu, gpu_0, GPU_0, etc I try to throw into the device = ““ will work….. it will just return\n\n*unsupported device \\[choosen name\\]*\n\nI hope i was able to provide enough information about the problem and what I’m trying to do, but I’m open to answer any questions… within my limited capacity","reference_answer":"I found a solution\n\nwithin the python script, I need these two lines of code, after which it will only see the 3070\n\n`import os`\n`os.environ[“CUDA_VISIBLE_DEVICES”] = “0”`","needs_clarification":false,"thread_id":222746,"url":"https://discuss.pytorch.org/t/ignore-specific-gpu-with-pytorch-in-anaconda/222746","created_at":"2025-08-29T15:35:12.554000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["Asmaron"],"answered_by_ptrblck":false} {"question":"Using multiple Linear layers with ReLU after LSTM layer good practice?\n\nShould I use multiple Linear layers with ReLU after LSTM layer?\n\nBelow example is a model class I wrote, that has statefull LSTM implementation. It seems everything else is working good, except the fact that on average, when I use multiple Linear layers with ReLU, after the LSTM layer, it would give me a worse performance then just using single LSTM and Linear Layer without ReLU.\n\nPlease guide. You can just answer in theory since I know the code; but here I give code so that you can have easy overview:\n\n```python\n\nclass MYLSTM(nn.Module):\n def __init__(self, input_size, hidden_size, batch_size, num_layers=4):\n super(MYLSTM, self).__init__()\n # variables\n self.input_size = input_size # no. of features\n self.hidden_size = hidden_size\n self.batch_size = batch_size # the no. of previous steps in x for future y\n self.num_layers = num_layers\n # model properties\n self.lstm = nn.LSTM(input_size, hidden_size, num_layers,dropout=0.2)\n self.fir = nn.Linear(hidden_size, 32) # 1 is single number as output\n self.sec = nn.Linear(32, 4) # 1 is single number as output\n self.last = nn.Linear(4, 1) # 1 is single number as output\n\n # activation func\n self.relu = nn.ReLU()\n\n def forward(self, input_data, h_0, c_0):\n # we cannot feed input_data directly to lstm without reshaping acc. to pytorch documentation\n sequence_length = len(input_data) # sequence length aka L, basically no. of rows\n if h_0 == None and c_0 == None: # runs only when h_0, c_0 is None which's at beginning of each epoch\n h_0 = torch.zeros(self.num_layers, self.batch_size, self.hidden_size) # num_layers, N, hidden size aka Hcell\n c_0 = torch.zeros(self.num_layers, self.batch_size, self.hidden_size) # num_layers, N, hidden size aka Hcell\n # to keep state values (h_0,c_0), but to detach them from the previous calculations\n h_0 = h_0.detach()\n c_0 = c_0.detach()\n input_lstm = input_data.view(sequence_length, self.batch_size, self.input_size) # L,N, input size aka Hin\n \n # we give our defined inputs in the lstm model as inputs and get lstm_out\n # lstm_out is treated further to get output for feeding to Linear layer\n lstm_out, (h_n, c_n) = self.lstm(input_lstm, (h_0, c_0))\n output = lstm_out.view(sequence_length, self.batch_size, self.hidden_size) # L,N,Hcell\n output = torch.mean(output, dim=1, keepdim=True) # output is 30,5,256(Hcell) shape we mean the 5 results at dim 1 so they all can combine as 1\n input_data = self.fir(output[:,-1,:])\n input_data = self.relu(input_data)\n input_data = self.sec(input_data)\n input_data = self.relu(input_data)\n input_data = self.last(input_data)\n\n return input_data, (h_n, c_n)\n\nmodel = MYLSTM(1,64,batch_size).to(device)\nmodel \n```","reference_answer":"Extra Linear and ReLU layers after the LSTM are not required, but they are fine. The LSTM already compresses information across time steps, so whether a deeper output head helps depends on the task and the data. A claim that performance is worse needs a baseline, and it should say whether training or test performance is meant.\n\nStacking LSTM layers (LSTM → Linear → ReLU → LSTM → Linear → ReLU → Linear) is possible in principle, and it has been used for various problems. Exploring the structure of the input, for example with a bidirectional LSTM for text, may reduce the need for stacked layers. More stacked LSTM layers make the model more prone to vanishing or exploding gradients and to overfitting on small datasets. Transformer-based architectures are also worth considering, since they overcome many of these challenges and parallelize computation like a CNN.","needs_clarification":false,"thread_id":222780,"url":"https://discuss.pytorch.org/t/using-multiple-linear-layers-with-relu-after-lstm-layer-good-practice/222780","created_at":"2025-08-31T10:21:05.755000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,4],"answer_authors":["Arunprakash-A"],"answered_by_ptrblck":false} {"question":"PyTorch not supported\n\nI’m having trouble installing PyTorch. I’ve been trying to get it to work for hours, but it’s not working…\nI get this error:\n\nFound GPU0 NVIDIA GeForce GTX 1080 Ti which is of cuda capability 6.1.\nMinimum and Maximum cuda capability supported by this version of PyTorch is\n(7.0) - (12.0)\n\nI downloaded PyTorch using this command:\n\npip install torch==2.7.1 torchvision==0.22.1 torchaudio==2.7.1 --index-url https://download.pytorch.org/whl/cu118\n\nand in theory, cu118 is supported by my 1080ti.\nThe GTX 1080 Ti has a CUDA compute capability of 6.1\nNVIDIA’s official documentation and support information confirm that the CUDA Toolkit 11.8 supports GPUs with compute capabilities starting at version 3.5. Since 6.1 is greater than 3.5, my GPU is fully supported.","reference_answer":"The error message does not match the support matrix your current PyTorch binary supports:\n\nSo I guess you are using different environments and have installed a new PyTorch binary built with CUDA 12.8+.\n\nMake sure you are installing and using a single PyTorch binary in each environment and uninstall all others.","needs_clarification":false,"thread_id":222789,"url":"https://discuss.pytorch.org/t/pytorch-not-supported/222789","created_at":"2025-08-31T23:34:41.842000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"How does torch.where work in autograd\n\nHi, sorry if the answer is trivial but I can’t seem to get how `autograd` differentiates `torch.where` operations where the mask used by `torch.where` is also derived from an input.","reference_answer":"`condition` is a boolean tensor and never requires grad, so autograd treats it as a constant and does not differentiate with respect to it.\n\nGradients flow only into the inputs that `torch.where` selects, and only if they require grad:\n* where the condition is `True`, the gradient flows into `input`\n* where the condition is `False`, the gradient flows into `other`\n* at positions an input was not selected from, its gradient is zero\n\nSo both `input` and `other` can receive gradients, depending on the mask.","needs_clarification":false,"thread_id":222791,"url":"https://discuss.pytorch.org/t/how-does-torch-where-work-in-autograd/222791","created_at":"2025-08-31T23:51:54.846000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["Arunprakash-A","valerian.rey"],"answered_by_ptrblck":false} {"question":"How to handle binding from c10::cuda::CUDAStream to torch.cuda.Stream\n\nI want to subclass ProcessGroupNCCL to enable communication using a user-specified CUDA stream. \n```cpp\nclass CustomProcessGroupNCCL: public ProcessGroupNCCL {\npublic:\nusing ProcessGroupNCCL::ProcessGroupNCCL;\n \n// Set NCCL stream by device index\nvoid setNcclStreamByDevice(int device_index, const c10::cuda::CUDAStream& stream) {\n std::string key = std::to_string(device_index);\n std::lock_guard guard(mutex_);\n if (ncclStreams_.find(key) != ncclStreams_.end()) {\n ncclStreams_.at(key) = stream;\n } else {\n TORCH_CHECK(false, \"Key not found in ncclStreams_: \", key);\n }\n}\n \n// Get NCCL stream by device index\nc10::cuda::CUDAStream getNcclStreamByDevice(int device_index) {\n std::string key = std::to_string(device_index);\n std::lock_guard guard(mutex_);\n auto it = ncclStreams_.find(key);\n TORCH_CHECK(it != ncclStreams_.end(), \"Key not found in ncclStreams_: \", key);\n return it->second;\n}\n \n// List all available NCCL stream keys\nstd::vector getAvailableStreamKeys() {\n std::lock_guard guard(mutex_);\n std::vector keys;\n for (const auto& pair : ncclStreams_) {\n keys.push_back(pair.first);\n }\n return keys;\n}\n\n// List all available NCCL streams \nstd::unordered_map getAvailableStreams(){\n return ncclStreams_;\n} \n \nprotected:\nstd::mutex mutex_;\n};\n\nPYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {\nm.doc() = \"Custom ProcessGroupNCCL with stream management capabilities\";\n \n// Expose the factory function\nm.def(\"create_custom_nccl_backend\", &c10d::createCustomNCCLBackend,\n \"Create a custom NCCL backend with stream management\",\n py::arg(\"store\"), py::arg(\"rank\"), py::arg(\"size\"), py::arg(\"options\"));\n \n// Expose the CustomProcessGroupNCCL class\npy::class_>(m, \"CustomProcessGroupNCCL\")\n .def(\"set_nccl_stream_by_device\", &c10d::CustomProcessGroupNCCL::setNcclStreamByDevice,\n \"Set NCCL stream by device index\",\n py::arg(\"device_index\"), py::arg(\"stream\"))\n .def(\"get_nccl_stream_by_device\", &c10d::CustomProcessGroupNCCL::getNcclStreamByDevice,\n \"Get NCCL stream by device index\",\n py::arg(\"device_index\"))\n .def(\"get_available_stream_keys\", &c10d::CustomProcessGroupNCCL::getAvailableStreamKeys,\n \"List all available NCCL stream keys\")\n .def(\"get_available_streams\", &c10d::CustomProcessGroupNCCL::getAvailableStreams);\n}\n\n```\nI write a simple python test\n```python\nimport custom_nccl_backend\n\ndef setup_custom_nccl_backend():\n \"\"\"\n Register the custom NCCL backend with PyTorch distributed.\n \"\"\"\n def custom_nccl_backend_creator(store, rank, size, *args):\n # Create default options for ProcessGroupNCCL\n options = torch.distributed.ProcessGroupNCCL.Options()\n # You can customize options here if needed\n # options.timeout = timedelta(seconds=300)\n # options.is_high_priority_stream = False\n \n # Use our custom factory function\n print(\"register args:\", store, rank, size, *args)\n return custom_nccl_backend.create_custom_nccl_backend(\n store, rank, size, options\n )\n \n # Register the custom backend\n dist.Backend.register_backend(\"CUSTOM_NCCL\", custom_nccl_backend_creator\n# main\ndist.init_process_group(\n backend=\"cuda:custom_nccl\", \n rank=rank, \n world_size=world_size\n )\n \n# Get the process group\npg = dist.group.WORLD\nbackend = pg._get_backend(torch.device(f\"cuda:{rank}\"))\n# Create a custom CUDA stream\ndevice = torch.device(f\"cuda:{rank}\")\ntorch.cuda.set_device(device)\ncustom_stream = torch.cuda.Stream(device=device)\nprint(f\"[Rank {rank}] Created custom stream: {custom_stream}\")\n \n# Set the custom stream for this device\nbackend.set_nccl_stream_by_device(rank, custom_stream)\n\n```\n\nIt seems that `c10::cuda::CUDAStream` cannot be converted to and from Python’s `torch.cuda.Stream` . How should I handle this?\n\n```python\n-- Process 0 terminated with the following error:\nTraceback (most recent call last):\n File \"/usr/local/lib/python3.12/dist-packages/torch/multiprocessing/spawn.py\", line 90, in _wrap\n fn(i, *args)\n File \"/mnt/code/wangtianxing.wtx/code/streamer-ttv-7b/csrc/ProcessGroupNCCLCustom/example_usage.py\", line 84, in example_with_custom_streams\n backend.set_nccl_stream_by_device(rank, custom_stream)\nTypeError: set_nccl_stream_by_device(): incompatible function arguments. The following argument types are supported:\n 1. (self: custom_nccl_backend.CustomProcessGroupNCCL, device_index: int, stream: c10::cuda::CUDAStream) -> None\n\nInvoked with: , 0, \n```","reference_answer":"@Aidyn-A answer on github:\n\nThat should be pretty easy to do.\n\nWrite a helper function in python side, in which you will need to pass `stream_id`, `device_index` and `device_type` of `torch.cuda.Stream` object, as it was done here:\n\nhttps://github.com/pytorch/pytorch/blob/80bf883d21ba48898e5fd40a6cbf418fa3ff3f33/torch/cuda/__init__.py#L729-L733\n\nAnd on C++ side utilize the converter to get an object of type `c10::cuda::CUDAStream` like it is done here:\n\nhttps://github.com/pytorch/pytorch/blob/fca2601c9d628e1bd2d75c7318cd22c4e8c832aa/torch/csrc/cuda/Module.cpp#L242-L245","needs_clarification":false,"thread_id":222798,"url":"https://discuss.pytorch.org/t/how-to-handle-binding-from-c10-cudastream-to-torch-cuda-stream/222798","created_at":"2025-09-01T06:44:19.283000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["albanD"],"answered_by_ptrblck":false} {"question":"Random seed closeness\n\nI use these 3 \\`set_determinism(seed);torch.manual_seed(seed);random.seed(seed)\\` to set seed for training Pytorch neural networks, does closeness in the choice of seed value (e.g. 10,11,12) have any differences than choosing seed values that are way different from each other (e.g. 1,101, 9999)?","reference_answer":"Not in any systematic way. Seeds that are numerically close, such as 10 and 11, produce random sequences that are expected to be uncorrelated and approximately orthogonal, the same as seeds that are far apart, such as 10 and 1000. So the closeness of two seeds has no relation to the closeness of the initialized weights, especially in high-dimensional weight space. There is no principle that guarantees nearby seeds give similar starting points.\n\nSimilar losses don't imply similar weights either. The mapping from weights to loss is many-to-one: very different weight vectors can give the same loss, especially in flat regions of the loss surface.","needs_clarification":false,"thread_id":222805,"url":"https://discuss.pytorch.org/t/random-seed-closeness/222805","created_at":"2025-09-01T12:05:29.285000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,4,6],"answer_authors":["Arunprakash-A"],"answered_by_ptrblck":false} {"question":"How to minimize the reserved GPU memory?\n\nHi, always thank you for your valuable comments.\n\nI have a question about the GPU memory usage, especially reserved memory.\n\nWhen I run the RGATConv-based model in the torch_gemoetric, the size of the reserved memory increased rapidly.\n\nI defined the GPU memory screening function as below:\n\ndef print_gpu_usage(note=“”):\nif torch.cuda.is_available():\nallocated = torch.cuda.memory_allocated() / (1024 \\*\\* 2)\nreserved = torch.cuda.memory_reserved() / (1024 \\*\\* 2)\nprint(f\"\\[GPU\\] {note} | Allocated: {allocated:.2f} MB | Reserved: {reserved:.2f} MB\")\nelse:\nprint(“CUDA is not available.”)\n\nAnd inserted the function like this:\n\nmodel.train()\nfor data in tqdm(train_loader):\ntr_loss = [ ]\ndata = data.to(device)\ndata = subgraph_sampling_per_cellline(data)\nprint_gpu_usage(“After loading datasets on the GPU”)\n\nif tr_loss:\nscaler.scale(tr_loss_mean).backward()\nprint_gpu_usage(“After backward”)\nscaler.step(optimizer)\nscaler.update()\nprint_gpu_usage(“After update”)\n\nThen, the result looks weird.\n\n> FOLD 0Data processing…Done\\[GPU\\] After model init | Allocated: 4.60 MB | Reserved: 22.00 MBStarting to train and test model0%| | 0/6410 \\[00:00\n> 0%| | 1/6410 \\[00:00<1:33:09, 1.15it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 162.91 MB | Reserved: 33714.00 MB\\[GPU\\] After forward | Allocated: 9008.47 MB | Reserved: 33714.00 MB\\[GPU\\] After backward | Allocated: 161.62 MB | Reserved: 33714.00 MB\\[GPU\\] After update | Allocated: 161.62 MB | Reserved: 33714.00 MB\n>\n> 0%| | 2/6410 \\[00:01<46:35, 2.29it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 163.68 MB | Reserved: 33714.00 MB\\[GPU\\] After forward | Allocated: 12093.81 MB | Reserved: 52474.00 MB\\[GPU\\] After backward | Allocated: 158.96 MB | Reserved: 61854.00 MB\\[GPU\\] After update | Allocated: 158.96 MB | Reserved: 61854.00 MB\n>\n> 0%| | 3/6410 \\[00:01<33:34, 3.18it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 157.91 MB | Reserved: 61854.00 MB\\[GPU\\] After forward | Allocated: 11848.42 MB | Reserved: 61858.00 MB\\[GPU\\] After backward | Allocated: 164.30 MB | Reserved: 61858.00 MB\\[GPU\\] After update | Allocated: 164.30 MB | Reserved: 61858.00 MB\n>\n> 0%| | 4/6410 \\[00:01<26:08, 4.08it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 165.70 MB | Reserved: 61858.00 MB\\[GPU\\] After forward | Allocated: 15850.53 MB | Reserved: 61858.00 MB\\[GPU\\] After backward | Allocated: 163.28 MB | Reserved: 61858.00 MB\\[GPU\\] After update | Allocated: 163.28 MB | Reserved: 61858.00 MB\n>\n> 0%| | 5/6410 \\[00:01<24:15, 4.40it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 162.42 MB | Reserved: 61858.00 MB\\[GPU\\] After forward | Allocated: 14547.31 MB | Reserved: 61860.00 MB\\[GPU\\] After backward | Allocated: 161.62 MB | Reserved: 61862.00 MB\\[GPU\\] After update | Allocated: 161.62 MB | Reserved: 61862.00 MB\n>\n> 0%| | 6/6410 \\[00:01<22:03, 4.84it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 162.35 MB | Reserved: 61862.00 MB\\[GPU\\] After forward | Allocated: 15718.04 MB | Reserved: 61862.00 MB\\[GPU\\] After backward | Allocated: 166.97 MB | Reserved: 61862.00 MB\\[GPU\\] After update | Allocated: 166.97 MB | Reserved: 61862.00 MB\n>\n> 0%| | 7/6410 \\[00:01<20:58, 5.09it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 166.33 MB | Reserved: 61862.00 MB\\[GPU\\] After forward | Allocated: 15294.10 MB | Reserved: 61862.00 MB\\[GPU\\] After backward | Allocated: 165.38 MB | Reserved: 61864.00 MB\\[GPU\\] After update | Allocated: 165.38 MB | Reserved: 61864.00 MB\n>\n> 0%| | 8/6410 \\[00:02<20:10, 5.29it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 164.57 MB | Reserved: 61864.00 MB\\[GPU\\] After forward | Allocated: 9452.27 MB | Reserved: 61864.00 MB\\[GPU\\] After backward | Allocated: 164.03 MB | Reserved: 61864.00 MB\\[GPU\\] After update | Allocated: 164.03 MB | Reserved: 61864.00 MB\n>\n> 0%| | 9/6410 \\[00:02<18:24, 5.79it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 165.56 MB | Reserved: 61864.00 MB\\[GPU\\] After forward | Allocated: 13367.78 MB | Reserved: 72252.00 MB\\[GPU\\] After backward | Allocated: 159.69 MB | Reserved: 82640.00 MB\\[GPU\\] After update | Allocated: 159.69 MB | Reserved: 82640.00 MB\n>\n> 0%| | 10/6410 \\[00:02<18:23, 5.80it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 158.75 MB | Reserved: 82640.00 MB\\[GPU\\] After forward | Allocated: 12570.48 MB | Reserved: 82640.00 MB\\[GPU\\] After backward | Allocated: 168.32 MB | Reserved: 82640.00 MB\\[GPU\\] After update | Allocated: 168.32 MB | Reserved: 82640.00 MB\n>\n> 0%| | 11/6410 \\[00:02<18:11, 5.86it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 167.36 MB | Reserved: 82640.00 MB\\[GPU\\] After forward | Allocated: 11526.41 MB | Reserved: 82640.00 MB\\[GPU\\] After backward | Allocated: 166.10 MB | Reserved: 82640.00 MB\\[GPU\\] After update | Allocated: 166.10 MB | Reserved: 82640.00 MB\n>\n> 0%| | 12/6410 \\[00:02<17:12, 6.20it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 167.82 MB | Reserved: 82640.00 MB\\[GPU\\] After forward | Allocated: 11734.72 MB | Reserved: 82640.00 MB\\[GPU\\] After backward | Allocated: 168.06 MB | Reserved: 82640.00 MB\\[GPU\\] After update | Allocated: 168.06 MB | Reserved: 82640.00 MB\n>\n> 0%| | 13/6410 \\[00:02<17:08, 6.22it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 167.23 MB | Reserved: 82640.00 MB\\[GPU\\] After forward | Allocated: 10795.68 MB | Reserved: 82640.00 MB\\[GPU\\] After backward | Allocated: 164.24 MB | Reserved: 82640.00 MB\\[GPU\\] After update | Allocated: 164.24 MB | Reserved: 82640.00 MB\n>\n> 0%| | 14/6410 \\[00:02<16:43, 6.37it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 163.03 MB | Reserved: 82640.00 MB\\[GPU\\] After forward | Allocated: 8074.03 MB | Reserved: 82640.00 MB\\[GPU\\] After backward | Allocated: 162.18 MB | Reserved: 82640.00 MB\\[GPU\\] After update | Allocated: 162.18 MB | Reserved: 82640.00 MB\n>\n> 0%| | 15/6410 \\[00:03<15:50, 6.73it/s\\]\\[GPU\\] After loading datasets on the GPU | Allocated: 162.43 MB | Reserved: 82640.00 MB\\[GPU\\] After forward | Allocated: 8811.66 MB | Reserved: 82640.00 MB\\[GPU\\] After backward | Allocated: 160.45 MB | Reserved: 82640.00 MB\\[GPU\\] After update | Allocated: 160.45 MB | Reserved: 82640.00 MB\n\nAs you can see, the reserved memory is much more than the allocated memory.\n\nSince I’m using the large size of the knowledge graph (i.e., heterogeneous graph), it is a critical issue to deal with the GPU memory size.\n\nI guess that the reserved memory evoked the GPU OOM problem.\n\nHow can I minimize the reserved memory? As much as possible, I want to make the reserved GPU memory dynamic.\n\nThank you for reading this question.\n\n—\n\\[Update\\]\n\nWhen I try to use `PYTORCH_NO_CUDA_MEMORY_CACHING=1` like [here](https://discuss.pytorch.org/t/how-can-i-decrease-the-pytorch-confidence-to-hold-too-much-reserved-memory/215108), it returned weird results as below.\n\n```\nFOLD 0\nData processing...\nDone\n[GPU] After model init | Allocated: 0.00 MB | Reserved: 0.00 MB\nStarting to train and test model\n 0%| | 0/6410 [00:00\n train(args) \n File \"/scratch/r902a02/workspace/KG-SLomics_Revision/src_27_RGAT_neg/ForGitHub/NegativeRatio/train_weightedloss_fixmetrics_addMLP_subgraphs_weightededges_AMP.py\", line 102, in train\n scaler.scale(tr_loss_mean).backward()\n File \"/scratch/r902a02/.conda/envs/notebook/lib/python3.10/site-packages/torch/_tensor.py\", line 626, in backward\n torch.autograd.backward(\n File \"/scratch/r902a02/.conda/envs/notebook/lib/python3.10/site-packages/torch/autograd/__init__.py\", line 347, in backward\n _engine_run_backward(\n File \"/scratch/r902a02/.conda/envs/notebook/lib/python3.10/site-packages/torch/autograd/graph.py\", line 823, in _engine_run_backward\n return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass\nRuntimeError: CUDA error: out of memory\nCUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.\nFor debugging consider passing CUDA_LAUNCH_BLOCKING=1\nCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.\n\n```","reference_answer":"If memory is the bottleneck, you can call `torch.cuda.empty_cache()` after each weight update (`scaler.update()`)","needs_clarification":false,"thread_id":222852,"url":"https://discuss.pytorch.org/t/how-to-minimize-the-reserved-gpu-memory/222852","created_at":"2025-09-04T02:40:43.962000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[6],"answer_authors":["Arunprakash-A"],"answered_by_ptrblck":false} {"question":"Choose a random seed that generates median or best validation loss in Latent Diffusion Models?\n\nI’m training a VAE for the later stage (diffusion) of the latent diffusion model framework. I tried a few configurations (e.g. changing the number of resblocks or number of channels), and each of the training loop of one configuration is run 5 times (corresponding to 5 seeds). \n\nQuestion: Which seed should I choose for the model parameters for the later stage (training UNet), the one that achieves the best validation loss or the one has a median validation loss? For reporting the performance of the VAE, we can choose the mean of validation loss across the seeds ([Report model training results among different seeds)](https://discuss.pytorch.org/t/different-seed-lead-to-very-different-test-result-on-the-test-set/67075/5?u=introvert_loner). But for training, we can only choose 1.","reference_answer":"Hi Introvert!\n\nIt depends on what your purpose is.\n\nIf your goal is to have the best trained model to then use to generate stuff,\nchoose the trained model (that happens to have come from some specific seed)\nthat has the best validation loss.\n\nOn the other hand, if you are, say, researching training protocols, it would\nprobably make sense to report the median validation loss (or more generally,\nthe distribution of validation losses) obtained from a series of training runs.\n\nPicking the best model (provided that you don't pick the model that performs\nbest on your so-called test set) is a fully legitimate approach.\n\nBy way of example, suppose you have a function defined on a square and you want\nto find an approximate minimum of that function. A legitimate algorithm would be\nto sample a set of random points from that square, evaluate the function at those\npoints, and keep the lowest value. This generally won't be anywhere near the best\nalgorithm, but it's logically sensible.\n\nElaborating, sample a set of random *starting* points, run some number of\ngradient-descent optimization steps starting with each of the starting points,\nand keep the lowest optimized value. This would also be legitimate and would be\nakin to keeping the best validation loss produced by your five randomly-seeded\ntraining runs.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":222923,"url":"https://discuss.pytorch.org/t/choose-a-random-seed-that-generates-median-or-best-validation-loss-in-latent-diffusion-models/222923","created_at":"2025-09-07T05:33:51.695000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"DataLoader higher number of workers and prefetch factor is worse than num_workers=0 and prefetch_factor=0\n\nI am training a ResNet50 from scratch using ImageNet-1k using DDP and torchrun on an HPC cluster. I use a single node with 4 Tesla V100 GPUs and 2 Intel Xeon CPUs (28 cores in total). I roughly followed the PyTorch reference training code [here](https://github.com/pytorch/vision/blob/main/references/classification/train.py). I realized that the DataLoader is creating a bottleneck on the duration of my training. For this, I experimented with different numbers of workers and prefetch factors, along with varying combinations of the booleans for pin memory, persistent workers, and non-blocking. For simplicity, I used True for all of these booleans when obtaining the results I put here.\n\nIn the first experiment, I used `tqdm` to see the time it takes for each epoch. The best performance is achieved with `num_workers=0` and `prefetch_factor=0`. When `num_workers>0`, the epoch duration increases drastically.\n\n* `num_workers=0` & `prefetch_factor=0` –> epoch duration: \\~46 mins 16 secs\n* `num_workers=4` & `prefetch_factor=2` –> epoch duration: \\~2 hrs 44 min 56 secs\n* `num_workers=4` & `prefetch_factor=4` –> epoch duration: \\~2 hrs 42 min 5 secs\n* `num_workers=16` & `prefetch_factor=4` –> epoch duration: \\~2 hrs 43 min 25 secs\n* `num_workers=24` & `prefetch_factor=4` –> epoch duration: \\~2 hrs 44 min 33 secs\n\nOne interesting observation I had is that, when `num_workers=0` and `prefetch_factor=0`, the batch durations are consistently around 1.05s/it. However, when I set, for example, `num_workers=16` and `prefetch_factor=4`, there are periodically some very long durations per batch (\\~10 secs/it) in between “normal” durations of \\~1 sec/it per batch, as follows:\n\n[details=\"Output of the training code for num_workers=16 and prefetch_factor=4\"]\nBatches: 15%|█▌ | 376/2502 \\[25:54<1:00:34, 1.71s/it\\]\nBatches: 15%|█▌ | 377/2502 \\[25:54<45:12, 1.28s/it\\]\nBatches: 15%|█▌ | 378/2502 \\[25:54<34:27, 1.03it/s\\]\nBatches: 15%|█▌ | 379/2502 \\[25:55<26:55, 1.31it/s\\]\nBatches: 15%|█▌ | 380/2502 \\[25:55<21:40, 1.63it/s\\]\nBatches: 15%|█▌ | 381/2502 \\[25:55<17:59, 1.97it/s\\]\nBatches: 15%|█▌ | 382/2502 \\[25:57<33:07, 1.07it/s\\]\nBatches: 15%|█▌ | 383/2502 \\[25:58<29:44, 1.19it/s\\]\nBatches: 15%|█▌ | 384/2502 \\[25:58<23:37, 1.49it/s\\]\nBatches: 15%|█▌ | 385/2502 \\[27:01<11:20:02, 19.27s/it\\]\nBatches: 15%|█▌ | 386/2502 \\[27:03<8:25:04, 14.32s/it\\]\nBatches: 15%|█▌ | 387/2502 \\[27:04<5:56:13, 10.11s/it\\]\nBatches: 16%|█▌ | 388/2502 \\[27:04<4:12:03, 7.15s/it\\]\nBatches: 16%|█▌ | 389/2502 \\[27:04<2:59:10, 5.09s/it\\]\nBatches: 16%|█▌ | 390/2502 \\[27:04<2:08:09, 3.64s/it\\]\nBatches: 16%|█▌ | 391/2502 \\[27:05<1:32:28, 2.63s/it\\]\nBatches: 16%|█▌ | 392/2502 \\[27:05<1:07:31, 1.92s/it\\]\nBatches: 16%|█▌ | 393/2502 \\[27:05<50:02, 1.42s/it\\]\nBatches: 16%|█▌ | 394/2502 \\[27:06<37:49, 1.08s/it\\]\nBatches: 16%|█▌ | 395/2502 \\[27:06<29:16, 1.20it/s\\]\nBatches: 16%|█▌ | 396/2502 \\[27:06<23:16, 1.51it/s\\]\nBatches: 16%|█▌ | 397/2502 \\[27:06<19:05, 1.84it/s\\]\nBatches: 16%|█▌ | 398/2502 \\[27:16<1:56:50, 3.33s/it\\]\nBatches: 16%|█▌ | 399/2502 \\[27:17<1:27:28, 2.50s/it\\]\nBatches: 16%|█▌ | 400/2502 \\[27:17<1:04:02, 1.83s/it\\]\nBatches: 16%|█▌ | 401/2502 \\[28:03<8:47:53, 15.08s/it\\]\nBatches: 16%|█▌ | 402/2502 \\[28:06<6:38:52, 11.40s/it\\]\nBatches: 16%|█▌ | 403/2502 \\[28:06<4:41:52, 8.06s/it\\]\nBatches: 16%|█▌ | 404/2502 \\[28:06<3:20:00, 5.72s/it\\]\nBatches: 16%|█▌ | 405/2502 \\[28:07<2:22:43, 4.08s/it\\]\nBatches: 16%|█▌ | 406/2502 \\[28:07<1:42:39, 2.94s/it\\]\nBatches: 16%|█▋ | 407/2502 \\[28:07<1:14:36, 2.14s/it\\]\nBatches: 16%|█▋ | 408/2502 \\[28:07<54:59, 1.58s/it\\]\nBatches: 16%|█▋ | 409/2502 \\[28:08<41:15, 1.18s/it\\]\nBatches: 16%|█▋ | 410/2502 \\[28:08<31:39, 1.10it/s\\]\nBatches: 16%|█▋ | 411/2502 \\[28:08<24:55, 1.40it/s\\]\nBatches: 16%|█▋ | 412/2502 \\[28:08<20:13, 1.72it/s\\]\n\n[/details]\n\nIn the second experiment, I used `torch.profiler` to have a more detailed investigation into what causes this increase. While `num_workers=0` and `prefetch_factor=0` has \\~1sec dataloader__next_\\_ calls, `num_workers=4` and `prefetch_factor=2` has occasional \\~10 secs dataloader__next_\\_ calls in between \\~1sec dataloader__next_\\_ calls.\n\nProfiler output for `num_workers=0` and `prefetch_factor=0`(left) and profiler output for `num_workers=4` and `prefetch_factor=2` (right) (as I am allowed to put only 1 image as a new user)\n\n[image]\n\nCould you please help me understand what causes this behaviour? I could also perform more experiments to see what causes this and appreciate any recommendations. Thank you!\n\nExperiment 1: using `tqdm`\n\n```python\nimport torchvision\nfrom torchvision.transforms import v2 as tvt\nimport torch\nimport argparse\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.distributed import init_process_group, destroy_process_group\nimport os\nfrom ModelTraining.source import pytorch_utils as pu\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-pb\", \"--Pinbool\", type=str)\nparser.add_argument(\"-nbb\", \"--Nonblockingbool\", type=str)\nparser.add_argument(\"-nw\", \"--Numworkers\", type=int)\nparser.add_argument(\"-pf\", \"--Prefetch\", type=int)\nparser.add_argument(\"-pw\", \"--Persistent\", type=str)\n\nargs = parser.parse_args()\n \npin_bool = args.Pinbool\nif pin_bool == 'True':\n PINBOOL = True\nelif pin_bool == 'False':\n PINBOOL = False\n \nnonblocking_bool = args.Nonblockingbool\nif nonblocking_bool == 'True':\n NONBLOCKINGBOOL = True\nelif nonblocking_bool == 'False':\n NONBLOCKINGBOOL = False\n \npersistent_workers = args.Persistent\nif persistent_workers == 'True':\n PERSISTENTWORKERS = True\nelif persistent_workers == 'False':\n PERSISTENTWORKERS = False\n \nNUMWORKERS = args.Numworkers\nPREFETCHFACTOR = args.Prefetch\n\nSEED = 42\niteration = 1\n\nNGPUS = 4\nBATCH_SIZE = 128\nEPOCHS = 1\n\nDATASET_SIZE = 1281167 # ImageNet training dataset size\n\nMOMENTUM = 0.9\nLEARNING_RATE = 0.5\nLR_WARMUP_EPOCHS = 5\nLR_WARMUP_DECAY = 0.01\n\nWEIGHT_DECAY = 0.00002\nNORM_WEIGHT_DECAY = 0.0 \n\nLABEL_SMOOTHING = 0.1\nMIXUP_ALPHA=0.2\nCUTMIX_ALPHA=1.0\nRANDOM_ERASE=0.1\n\nRA_SAMPLER = True\nRA_REPS=4\n\nMODEL_EMA = True\nMODEL_EMA_STEPS = 32\nMODEL_EMA_DECAY = 0.99998\n\nVAL_RESIZE_SIZE = 232\nVAL_CROP_SIZE = 224\nTRAIN_CROP_SIZE = 176\n\nworld_size = torch.cuda.device_count()\n\ndef ddp_setup():\n init_process_group(backend=\"nccl\")\n \n\ndef initialize(pinbool, batchsize, numworkers, prefetchfactor, persistentworkers):\n \n gpu_id = int(os.environ[\"LOCAL_RANK\"])\n \n preset_train = pu.ClassificationPresetTrain(\n crop_size=TRAIN_CROP_SIZE,\n interpolation=tvt.functional.InterpolationMode('bilinear'),\n auto_augment_policy='ta_wide',\n random_erase_prob=RANDOM_ERASE,\n ra_magnitude=9, \n augmix_severity=3, \n backend='PIL',\n use_v2=False)\n \n traindata = torchvision.datasets.ImageFolder('/work/imagenet/train/', preset_train)\n trainsampler = pu.RASampler(traindata, shuffle=True, repetitions=RA_REPS, seed=SEED)\n \n num_classes = len(traindata.classes)\n mixup_cutmix = pu.get_mixup_cutmix(mixup_alpha=MIXUP_ALPHA, cutmix_alpha=CUTMIX_ALPHA, num_classes=num_classes) \n\n def collate_fn(batch):\n return mixup_cutmix(*torch.utils.data.dataloader.default_collate(batch))\n \n \n if numworkers > 0:\n \n if prefetchfactor == 0:\n trainloader = torch.utils.data.DataLoader(traindata, batch_size=batchsize, sampler=trainsampler, pin_memory=pinbool, num_workers=numworkers, collate_fn=collate_fn, prefetch_factor=None, persistent_workers=persistentworkers)\n else:\n trainloader = torch.utils.data.DataLoader(traindata, batch_size=batchsize, sampler=trainsampler, pin_memory=pinbool, num_workers=numworkers, collate_fn=collate_fn, prefetch_factor=prefetchfactor, persistent_workers=persistentworkers)\n \n elif numworkers == 0:\n \n trainloader = torch.utils.data.DataLoader(traindata, batch_size=batchsize, sampler=trainsampler, pin_memory=pinbool, num_workers=numworkers, collate_fn=collate_fn, prefetch_factor=None)\n\n model = torchvision.models.resnet50(weights=None)\n \n model.to(gpu_id)\n \n model = DDP(model, device_ids=[gpu_id])\n \n parameters = pu.set_weight_decay(\n model,\n WEIGHT_DECAY,\n norm_weight_decay=NORM_WEIGHT_DECAY,\n custom_keys_weight_decay=None,\n )\n \n criterion = torch.nn.CrossEntropyLoss(label_smoothing=LABEL_SMOOTHING).to(gpu_id)\n optimizer = torch.optim.SGD(parameters, lr=LEARNING_RATE, momentum=MOMENTUM, weight_decay=WEIGHT_DECAY)\n main_lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS - LR_WARMUP_EPOCHS, eta_min=0.0)\n warmup_lr_scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=LR_WARMUP_DECAY, total_iters=LR_WARMUP_EPOCHS)\n lr_scheduler = torch.optim.lr_scheduler.SequentialLR(optimizer, schedulers=[warmup_lr_scheduler, main_lr_scheduler], milestones=[LR_WARMUP_EPOCHS])\n \n return trainloader, model, criterion, optimizer, lr_scheduler\n\ndef train(traindata, model, criterion, optimizer, lr_scheduler, gpu_id, pinbool, numworkers, prefetchfactor, persistentworkers, nonblockingbool, epochs_run = 0):\n \n traindata.sampler.set_epoch(epochs_run)\n \n model.train()\n \n with torch.profiler.profile(\n activities=[\n torch.profiler.ProfilerActivity.CPU,\n torch.profiler.ProfilerActivity.CUDA],\n schedule=torch.profiler.schedule(\n wait=2,\n warmup=2,\n active=12),\n on_trace_ready=torch.profiler.tensorboard_trace_handler('/result_pb'+str(pinbool)+'_nw'+str(numworkers)+'_pf'+str(prefetchfactor)+'_pw'+str(persistentworkers)+'_nbb' +str(nonblockingbool)),\n record_shapes=True,\n profile_memory=True,\n with_stack=True\n ) as p:\n \n for batch_idx, (data, targets) in enumerate(traindata):\n \n if nonblockingbool == True:\n data = data.to(gpu_id, non_blocking=True)\n targets = targets.to(gpu_id, non_blocking=True)\n \n elif nonblockingbool == False:\n data = data.to(gpu_id)\n targets = targets.to(gpu_id)\n \n optimizer.zero_grad()\n \n output = model(data)\n loss = criterion(output, targets)\n \n loss.backward()\n optimizer.step()\n \n p.step()\n \n if batch_idx==18:\n break\n \n lr_scheduler.step()\n \n epochs_run += 1\n \n\ndef main():\n \n ddp_setup() \n \n torch.cuda.manual_seed_all(SEED)\n torch.manual_seed(SEED)\n \n trainloader, model, criterion, optimizer, lr_scheduler = initialize(PINBOOL, BATCH_SIZE, NUMWORKERS, PREFETCHFACTOR, PERSISTENTWORKERS)\n \n torch.cuda.manual_seed_all(SEED)\n torch.manual_seed(SEED)\n \n train(trainloader, model, criterion, optimizer, lr_scheduler, int(os.environ[\"LOCAL_RANK\"]), PINBOOL, NUMWORKERS, PREFETCHFACTOR, PERSISTENTWORKERS, NONBLOCKINGBOOL)\n \n destroy_process_group()\n\nif __name__ == \"__main__\":\n \n main()\n```\n\nExperiment 2: using `torch.profiler`\n\n```python\nimport torchvision\nfrom torchvision.transforms import v2 as tvt\nimport torch\nimport argparse\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.distributed import init_process_group, destroy_process_group\nimport os\nfrom ModelTraining.source import pytorch_utils as pu\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-pb\", \"--Pinbool\", type=str)\nparser.add_argument(\"-nbb\", \"--Nonblockingbool\", type=str)\nparser.add_argument(\"-nw\", \"--Numworkers\", type=int)\nparser.add_argument(\"-pf\", \"--Prefetch\", type=int)\nparser.add_argument(\"-pw\", \"--Persistent\", type=str)\n\nargs = parser.parse_args()\n \npin_bool = args.Pinbool\nif pin_bool == 'True':\n PINBOOL = True\nelif pin_bool == 'False':\n PINBOOL = False\n \nnonblocking_bool = args.Nonblockingbool\nif nonblocking_bool == 'True':\n NONBLOCKINGBOOL = True\nelif nonblocking_bool == 'False':\n NONBLOCKINGBOOL = False\n \npersistent_workers = args.Persistent\nif persistent_workers == 'True':\n PERSISTENTWORKERS = True\nelif persistent_workers == 'False':\n PERSISTENTWORKERS = False\n \nNUMWORKERS = args.Numworkers\nPREFETCHFACTOR = args.Prefetch\n\nSEED = 42\niteration = 1\n\nNGPUS = 4\nBATCH_SIZE = 128\nEPOCHS = 5\n\nDATASET_SIZE = 1281167 # ImageNet training dataset size\n\nMOMENTUM = 0.9\nLEARNING_RATE = 0.5\nLR_WARMUP_EPOCHS = 5\nLR_WARMUP_DECAY = 0.01\n\nWEIGHT_DECAY = 0.00002\nNORM_WEIGHT_DECAY = 0.0 \n\nLABEL_SMOOTHING = 0.1\nMIXUP_ALPHA=0.2\nCUTMIX_ALPHA=1.0\nRANDOM_ERASE=0.1\n\nRA_REPS=4\n\nTRAIN_CROP_SIZE = 176\n\nworld_size = torch.cuda.device_count()\n\ndef ddp_setup():\n init_process_group(backend=\"nccl\")\n \n\ndef initialize(pinbool, batchsize, numworkers, prefetchfactor, persistentworkers):\n \n gpu_id = int(os.environ[\"LOCAL_RANK\"])\n \n preset_train = pu.ClassificationPresetTrain(\n crop_size=TRAIN_CROP_SIZE,\n interpolation=tvt.functional.InterpolationMode('bilinear'),\n auto_augment_policy='ta_wide',\n random_erase_prob=RANDOM_ERASE,\n ra_magnitude=9, \n augmix_severity=3, \n backend='PIL',\n use_v2=False)\n \n traindata = torchvision.datasets.ImageFolder('/work/imagenet/train/', preset_train)\n trainsampler = pu.RASampler(traindata, shuffle=True, repetitions=RA_REPS, seed=SEED)\n \n num_classes = len(traindata.classes)\n mixup_cutmix = pu.get_mixup_cutmix(mixup_alpha=MIXUP_ALPHA, cutmix_alpha=CUTMIX_ALPHA, num_classes=num_classes) \n\n def collate_fn(batch):\n return mixup_cutmix(*torch.utils.data.dataloader.default_collate(batch))\n \n \n if numworkers > 0:\n \n if prefetchfactor == 0:\n trainloader = torch.utils.data.DataLoader(traindata, batch_size=batchsize, sampler=trainsampler, pin_memory=pinbool, num_workers=numworkers, collate_fn=collate_fn, prefetch_factor=None, persistent_workers=persistentworkers)\n else:\n trainloader = torch.utils.data.DataLoader(traindata, batch_size=batchsize, sampler=trainsampler, pin_memory=pinbool, num_workers=numworkers, collate_fn=collate_fn, prefetch_factor=prefetchfactor, persistent_workers=persistentworkers)\n \n elif numworkers == 0:\n \n trainloader = torch.utils.data.DataLoader(traindata, batch_size=batchsize, sampler=trainsampler, pin_memory=pinbool, num_workers=numworkers, collate_fn=collate_fn, prefetch_factor=None)\n\n model = torchvision.models.resnet50(weights=None)\n \n model.to(gpu_id)\n \n model = DDP(model, device_ids=[gpu_id])\n \n parameters = pu.set_weight_decay(\n model,\n WEIGHT_DECAY,\n norm_weight_decay=NORM_WEIGHT_DECAY,\n custom_keys_weight_decay=None,\n )\n \n criterion = torch.nn.CrossEntropyLoss(label_smoothing=LABEL_SMOOTHING).to(gpu_id)\n optimizer = torch.optim.SGD(parameters, lr=LEARNING_RATE, momentum=MOMENTUM, weight_decay=WEIGHT_DECAY)\n main_lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS - LR_WARMUP_EPOCHS, eta_min=0.0)\n warmup_lr_scheduler = torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=LR_WARMUP_DECAY, total_iters=LR_WARMUP_EPOCHS)\n lr_scheduler = torch.optim.lr_scheduler.SequentialLR(optimizer, schedulers=[warmup_lr_scheduler, main_lr_scheduler], milestones=[LR_WARMUP_EPOCHS])\n \n return trainloader, model, criterion, optimizer, lr_scheduler\n\ndef train(traindata, model, criterion, optimizer, lr_scheduler, gpu_id, pinbool, numworkers, prefetchfactor, persistentworkers, nonblockingbool, epochs_run = 0):\n \n traindata.sampler.set_epoch(epochs_run)\n \n model.train()\n \n with torch.profiler.profile(\n activities=[\n torch.profiler.ProfilerActivity.CPU,\n torch.profiler.ProfilerActivity.CUDA],\n schedule=torch.profiler.schedule(\n wait=2,\n warmup=2,\n active=12),\n on_trace_ready=torch.profiler.tensorboard_trace_handler('/result_pb'+str(pinbool)+'_nw'+str(numworkers)+'_pf'+str(prefetchfactor)+'_pw'+str(persistentworkers)+'_nbb' +str(nonblockingbool)),\n record_shapes=True,\n profile_memory=True,\n with_stack=True\n ) as p:\n \n for batch_idx, (data, targets) in enumerate(traindata):\n \n if nonblockingbool == True:\n data = data.to(gpu_id, non_blocking=True)\n targets = targets.to(gpu_id, non_blocking=True)\n \n elif nonblockingbool == False:\n data = data.to(gpu_id)\n targets = targets.to(gpu_id)\n \n optimizer.zero_grad()\n \n output = model(data)\n loss = criterion(output, targets)\n \n loss.backward()\n optimizer.step()\n \n p.step()\n \n if batch_idx==18:\n break\n \n lr_scheduler.step()\n \n epochs_run += 1\n \n\ndef main():\n \n ddp_setup()\n \n torch.cuda.manual_seed_all(SEED)\n torch.manual_seed(SEED)\n \n trainloader, model, criterion, optimizer, lr_scheduler = initialize(PINBOOL, BATCH_SIZE, NUMWORKERS, PREFETCHFACTOR, PERSISTENTWORKERS)\n \n torch.cuda.manual_seed_all(SEED)\n torch.manual_seed(SEED)\n \n train(trainloader, model, criterion, optimizer, lr_scheduler, int(os.environ[\"LOCAL_RANK\"]), PINBOOL, NUMWORKERS, PREFETCHFACTOR, PERSISTENTWORKERS, NONBLOCKINGBOOL)\n \n destroy_process_group()\n\nif __name__ == \"__main__\":\n \n main()\n```","reference_answer":"After changing the code several times and trying out different things, we found out the problem was due to the order of imports in the code, specifically the numpy import. When we removed the numpy import from the first line of our script, the DataLoaders could use more than one CPU. Otherwise, only one CPU was fully used while others stayed mostly idle, regardless of the number of workers specified. \n\nI don’t think this is an environment-specific issue, as I tried it with two different HPCs and observed the same behaviour. Also, I think this is not a new issue, as I found people having similar problems here: https://github.com/pytorch/pytorch/issues/101188\n\nHope this helps if you have a similar problem.","needs_clarification":false,"thread_id":222943,"url":"https://discuss.pytorch.org/t/dataloader-higher-number-of-workers-and-prefetch-factor-is-worse-than-num-workers-0-and-prefetch-factor-0/222943","created_at":"2025-09-08T16:13:58.629000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["soral"],"answered_by_ptrblck":false} {"question":"Installation Candidates\n\nHello.. I am on ubuntu noble 24.04 with python 3.12 on a desktop machine which has a working installation of CUDA13 and a couple of graphics cards. I can’t use pip to install torch without the ‘externally-managed-environment’ error….. and sudo python3-pytorch gives the ‘no installation candidate’ error. Am I doing something wrong? Or do I just have to wait until an installation candidate appears… or is there something else I can safely do in the meantime?","reference_answer":"Install a virtual Python environment and the first error should be gone.","needs_clarification":false,"thread_id":223104,"url":"https://discuss.pytorch.org/t/installation-candidates/223104","created_at":"2025-09-15T13:37:37.967000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Updating tensors that are used in backpropagation but are not network parameters\n\nI am currently trying to reimplement “Deep SVDD” for my own project.\n\nDuring training, I use my network to compute the outputs as usual. To compute the loss, I then use the hypersphere center c and radius R as follows:\n\n```\noutputs = model(data)\ndist = torch.sum((outputs - self.c) ** 2, dim=1)\nscores = dist - self.R ** 2\nloss = self.R ** 2 + (1 / self.nu) * torch.mean(torch.max(torch.zeros_like(scores), scores))\nloss.backward()\noptimizer.step()\n\n```\n\nAfter backpropagating the loss and updating the parameters, I now want to update the radius R. In the original implementation this is done by\n\n```python\nself.R.data = torch.tensor(get_radius(dist, self.nu), device=self.device)\n```\n\nwhere the get_radius function is defined as follows:\n\n```python\ndef get_radius(dist: torch.Tensor, nu: float):\n return np.quantile(np.sqrt(dist.clone().data.cpu().numpy()), 1 - nu)\n```\n\nAfter updating the radius, the processing of the current training batch is done.\n\nNow I am wondering whether this is the proper way to do this. I know that the use of .data can be problematic and can cause issues during backpropagation. I have been reading around about it but I can’t quite wrap my head around it and how to fix it. Would it cause issues in the original implementation and how should I implement it instead to avoid any issues and why?\n\nMore generally, my question is how to properly update the radius in my implementation without causing issues with backpropagation or more generally how to update tensors like the radius?","reference_answer":"You may only have issues if you update in-place a tensor that is referenced in the graph, between the forward pass and the backward pass. This is because a reference to this tensor may be saved in the computation graph, so changing the value stored in the tensor will also change the result of the backpropagation. Since you're updating `self.R` after the graph has been used (after `loss.backward()`), what you're doing should never cause issues. However, it's cleaner to just assign to `self.R` directly rather than `self.R.data` (this way you avoid making an in-place update altogether).\n\nBy the way, since your radius should not require grad, you could compute it in a `torch.no_grad()` context just to be sure that no operation constructing a graph will be executed (which would waste time), and that the obtained tensor does not require grad (which would make the backpropagation waste time at the next iteration).\n\nSo your current implementation should be fine, but a maybe safer approach would be:\n```\nwith torch.no_grad():\n self.R = torch.tensor(get_radius(dist, self.nu), device=self.device)\n```","needs_clarification":false,"thread_id":223208,"url":"https://discuss.pytorch.org/t/updating-tensors-that-are-used-in-backpropagation-but-are-not-network-parameters/223208","created_at":"2025-09-19T14:30:58.278000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["valerian.rey"],"answered_by_ptrblck":false} {"question":"'Show Source' for PyTorch docs\n\nHi, can someone tell me how the ‘Show Source‘ feature on PyTorch docs? Sometimes, it shows me the actual documentation on Github, while other times it just brings me to a bare-bones rst page, as seen here: \n\ntorch.cuda.can\\\\\\_device\\\\\\_access\\\\\\_peer\n====================================\n\n.. currentmodule:: torch.cuda\n\n.. autofunction:: can_device_access_peer\n\nIs there any plan to link things like these to the actual source code on github? I’m willing to help or make sure there is consistency here if so.","reference_answer":"The \"Show Source\" link opens the reStructuredText source file for the page. The \"[source]\" link on a page goes to the actual source code. Some pages have no \"[source]\" link, so \"Show Source\" is the only option there.","needs_clarification":true,"thread_id":223223,"url":"https://discuss.pytorch.org/t/show-source-for-pytorch-docs/223223","created_at":"2025-09-20T16:12:43.777000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4],"answer_authors":["valerian.rey"],"answered_by_ptrblck":false} {"question":"Does torch support custom stream for nccl commucation now?\n\nThere are many discussion and posts saying that torch can't use custom stream for nccl communcation. Since `ProcessGroupNCCL` maintains its internal stream pool for nccl.\nhttps://github.com/pytorch/pytorch/issues/136187\nhttps://github.com/pytorch/pytorch/issues/137390\n\n```cpp\n // The CUDA streams used by NCCL kernels\n std::unordered_map ncclStreams_;\n```\n\nwhen we write code like below, it actually doesn't really use `comm_stream` but as a `dummy compute stream` since nccl will make commucation wait for current stream to ensure input data ready.\n```python\na = some_compute()\nwith torch.cuda.stream(comm_stream):\n dist.allgather(output, a)\n```\n\nBut when I dive into ProcessGroupNCCL. I find torch will choose nccl stream based on whether it's an async op. If it is, torch will use internal stream from `ncclStreams_` which is a map from device to cuda stream. otherwise, it will simply use current cuda stream\n```cpp\ntemplate \nc10::intrusive_ptr ProcessGroupNCCL::collective(\n std::vector& inputs,\n std::vector& outputs,\n Fn fn,\n PreProcess pre,\n PostProcess post,\n OpType opType,\n bool asyncOp,\n const char* profilingTitle,\n bool nanCheck) {\n\n // ....\n\n // in asyncOp=false [default] mode, we use currentStream as ncclStream\n // otherwise, we use separate ncclStream and let it sync on currentStream\n auto ncclStream = asyncOp ? ncclStreams_.at(key)\n : at::cuda::getCurrentCUDAStream(device.index());\n```\n\nThe two statements above seem somewhat contradictory, and I’m very curious which one is correct. Can torch actually customize the stream that NCCL will use?","reference_answer":"The ProcessGroupNCCL code is what is correct, when you do:\n\n```python\nwith torch.cuda.stream(comm_stream):\n dist.allgather(output, a)\n```\n\nThe allgather will happen in the `comm_stream`. If no stream is specified and it is async, then it will use the internal stream.","needs_clarification":false,"thread_id":223234,"url":"https://discuss.pytorch.org/t/does-torch-support-custom-stream-for-nccl-commucation-now/223234","created_at":"2025-09-21T09:26:11.946000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["H-Huang"],"answered_by_ptrblck":false} {"question":"No module named cv2 although opencv has been installed already\n\nI wanted to try the simple code which was supposed to convert text to video like this \n\n```\nimport cv2\nimport numpy as np\n\ncap = cv2.VideoCapture(0) \n#more lines of code follow\n```\n\nI tried moving cv2.so around in my source code folder and everywhere. I tried even uninstalling and re-installing opencv then running this code over and over again. My terminal on VSCode gets terminated by error `No module named cv2` - none of my efforts helped. I am about to bang off my keyboard out of frustration. \n\nCould anyone kindly tell me what went wrong here?","reference_answer":"Run `import sys` and `print(sys.path)` and check whether the OpenCV location is listed. In this case OpenCV wasn't installed in the Docker image, so add `RUN pip install opencv-python-headless` to the Dockerfile. The project folder also had to be added to `sys.path` in the source code with `sys.path.append(r\"/Users/Path/To/MyPytorchProject\")`, using the path to your own project.","needs_clarification":false,"thread_id":223297,"url":"https://discuss.pytorch.org/t/no-module-named-cv2-although-opencv-has-been-installed-already/223297","created_at":"2025-09-24T15:45:34.635000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4,7],"answer_authors":["Arunprakash-A","Casey_KimScripts"],"answered_by_ptrblck":false} {"question":"Models keep overfitting despite using regularization e.t.c\n\nI have tried data augmentation, regularization, penalty loss, normalization, dropout, learning rate schedulers, etc., but my models still tend to overfit. Sometimes I get good results in the very first epoch, but then the performance keeps dropping afterward. In longer trainings (e.g., 200 epochs), the best validation loss only appears in 2–3 epochs.\n\nI encounter this problem not only with one specific setup but also across different datasets, different loss functions, and different model architectures. It feels like a persistent issue rather than a case-specific one.\n\nWhere might I be making a mistake?","reference_answer":"Hi Fatih!\n\nWhen you say that the model is \"learning,\" it's not clear to me whether you\nmean its performance is improving on the training set or on the validation set\n(or maybe some combination of the two).\n\nRegardless, when your training set is *very large* it would become possible for\nyour model to \"learn (almost) everything\" in one or two epochs. Note, \"epoch\"\ngenerally means one pass through your training set, so one or two epochs could\nmean training on a very large number of training examples.\n\nHowever, the way overfitting happens is that the training process sees the same\ntraining example many times so that it has the chance to (figuratively speaking)\n\"memorize\" it. I therefore would not expect to see overfitting over just a few\nepochs.\n\nI could see the improvement in both the training and validation loss slowing\ndown and flattening out as the model learns more or less as much as it can\nabout the problem it is actually trying to solve from the very large training set,\nbut I wouldn't expect the validation loss to start going up because the model has\nnot yet started to learn misleading details of individual examples in the training\nset -- degrading the performance on the validation set -- because it's only seen\nthose individual examples once or twice.\n\nThe only way I could see overfitting occurring after a small number of training\nepochs would be if the \"large\" training set contained many examples that were\nnear duplicates of one another (and were not also near duplicates of examples\nin the validation set) so that, in effect, the training set was not as large as it\nappeared and during training the model was seeing more or less the same example\nmany times instead of just once or twice.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":223329,"url":"https://discuss.pytorch.org/t/models-keep-overfitting-despite-using-regularization-e-t-c/223329","created_at":"2025-09-26T07:50:15.288000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[7],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Torch.linalg.eig parallelisation\n\nHello,\n\nI am using torch for some computations, but am struggeling with improving the performance of my code. I need to get the eigenvalues of some matrizes in the order of magnitude of 6000x6000. It works fine with torch.linalg.eig, but is rather slow, compared to the rest of my computations. If I understand correctly, this is largely because part of the computations need to be performed on CPU.\n\nNow what I don’t understand is, that the .eig function does not seem to parallelize at all. If I hand it a batch of matrices, the calculation takes pretty much exactly the same amount of time, compared to when I call eig for each matrix individually. This is kind of frustrating, as I have plenty of CPU cores as well as RAM and even multiple GPUs available.\n\nAdditionally, I observed a slowdown with to many threads. If I use more than \\~16 threads there is actually a slowdown of the eig calculation. A speedup can only be observed until about 8 threads. Is this to be expected?\n\nI am unsure how to tacle this problem. Would it be best to try to parallelize using DDP? Or Is this not suitable for linalg calculations. Depending on the problem, I will have about 300 of the matrices mentioned, which should all be able to be calculated individually. I would preferre to have gradients available if that is possible with parallelization.\n\nBest","reference_answer":"`torch.linalg.eig` doesn't parallelize over a batch, and none of its backends are parallelized yet. A batched call takes about as long as calling it per matrix. Run the matrices from a thread pool (`concurrent.futures`) instead:\n\n```\ndef poolEig (tb):\n with concurrent.futures.ThreadPoolExecutor(max_workers = 8) as pool:\n futures = [pool.submit (torch.linalg.eig, t) for t in tb]\n return [fut.result() for fut in futures]\n```\n\nWith four 6000x6000 matrices, this took 64.78 s on CPU versus 94.46 s batched, and 42.38 s on CUDA versus 61.81 s batched. If the CPU is not the bottleneck, distributing the matrices across several GPUs with threads should help too. A cuSOLVER-based eig path, reported at about 2x faster on consumer hardware, was in pull request pytorch/pytorch#166715.","needs_clarification":false,"thread_id":223386,"url":"https://discuss.pytorch.org/t/torch-linalg-eig-parallelisation/223386","created_at":"2025-09-29T08:26:02.533000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[6,10,12],"answer_authors":["Johannes99","KFrank"],"answered_by_ptrblck":false} {"question":"Reproducibility of sampling from a subset of logits\n\nHi community,\n\nI’d like to ask about the reason and a solution (if any) to the problem of different results when sampled from the same logits, even under the same rng state. The toy code for this situation is as follows:\n\n```\nimport torch\n\ndef main():\n rng = torch.Generator().manual_seed(42)\n logits = torch.randn(2, 2, 4096, generator=rng)\n logits_gen_state = rng.get_state()\n print(f\"After logits, rng state = {logits_gen_state}\")\n idx1 = torch.multinomial( \n logits.softmax(dim=-1).view(-1, 4096), \n num_samples=1, \n replacement=True, \n generator=rng, \n )\n print(idx1)\n idx1_gen_state = rng.get_state()\n print(f\"After idx1, rng state = {idx1_gen_state}\")\n print(f\"logits gen state != idx1 gen state: {torch.any(logits_gen_state != idx1_gen_state)}\")\n rng.set_state(logits_gen_state)\n idx2 = torch.multinomial( \n logits[0, ...].unsqueeze(0).softmax(dim=-1).view(-1, 4096), \n num_samples=1, \n replacement=True, \n generator=rng, \n ) \n print(idx2)\n idx2_gen_state = rng.get_state()\n print(f\"After idx2, rng state = {idx2_gen_state}\")\n print(f\"logits gen state != idx2 gen state: {torch.any(logits_gen_state != idx2_gen_state)}\")\n print(f\"idx1 gen state != idx2 gen state: {torch.any(idx1_gen_state != idx2_gen_state)}\")\n\nif __name__ == \"__main__\":\n main()\n```\n\nWhat the code snippet above does is that it first uses the same rng for all sampling, and then creates a logits tensor to sample two other indices tensors. For the sampling of the second indices tensor, I only use the first half of the logits tensor. And below is the result:\n\n```\ntensor([[1284],\n [1828],\n [3472],\n [2623]])\nlogits gen state != idx1 gen state: True\ntensor([[1284],\n [1828]])\nlogits gen state != idx2 gen state: True\nidx1 gen state != idx2 gen state: False\n```\n\nSo `idx2` coincides with the first half of `idx1`, which is correct to my expectation. But if I use the second half of the logits tensor to sample:\n\n```\nidx2 = torch.multinomial( \n logits[1, ...].unsqueeze(0).softmax(dim=-1).view(-1, 4096), \n num_samples=1, \n replacement=True, \n generator=rng, \n )\n```\n\nI don’t get the same indices as the second half of `idx1`\n\n```\ntensor([[1284],\n [1828],\n [3472],\n [2623]])\nlogits gen state != idx1 gen state: True\ntensor([[1284],\n [2704]])\nlogits gen state != idx2 gen state: True\nidx1 gen state != idx2 gen state: False\n```\n\nMore generally, sampling from a subset of logits does not guarantee reproducibility even under the same rng state. And this is what I desire for my usecase.\n\nHence, in this post, I’d like to ask about the reason for the discrepancy between the two cases I illustrated above and the solution for reproducibility when sampling from a subset of logits, if any.\n\nReally appreciate your help.\n\nThanks in advance.","reference_answer":"Hi Minh!\n\nThe problem is that the samples that come out \"wrong\" weren't really sampled\nusing the same rng state.\n\nRoughly speaking, every time you generate a random sample, you advance the\nstate of the rng by \"one unit.\"\n\n(Pytorch doesn't *have* to do it this way, but it often does. For example, if\nyou want, say, seven samples, pytorch could, for efficiency reasons, actually\ngenerate eight samples, discarding the last one. If it did it this way, it would\nadvance the rng state by eight units instead of only seven.)\n\nThis generates four samples (because you are generating a batch of four).\nThe first sample is generated using the initial rng state, the second after the\nstate has been advanced once, the third after the state has been advanced\ntwice, and the fourth after the state has been advanced three times.\n\nThat is the, the last two samples -- those corresponding to the \"second half\"\nof your logits -- are generated using \"initial state + 2.\"\n\nHere you are generating two samples for the \"first half\" of the logits starting\nwith the initial state and you get the right answer.\n\nPresumably when you run this chunk of code, it is also preceded by:\n\n```python\n rng.set_state(logits_gen_state)\n```\n\nWhen you do this, you are generating two samples for the \"second half\" of the\nlogits, but starting with the initial state. These will not match the third and\nfourth samples in `idx1` because those were generated with \"initial state + 2\".\n\nIf you advance the rng state properly -- for example by generating two samples\nthat you ignore -- before generating `idx2`, you will get the expected result.\n\nI've modified your code modestly to call the generation of `idx2` twice. The\nfirst time advances the rng state by \"two units\" so that the second call will use\nthe correct state and generate samples that match the second half of `idx1`.\n\nHere is your modified script:\n\n```python\nimport torch\nprint (torch.__version__)\n\ndef main():\n rng = torch.Generator().manual_seed(42)\n logits = torch.randn(2, 2, 4096, generator=rng)\n logits_gen_state = rng.get_state()\n print(f\"After logits, rng state = {logits_gen_state}\")\n idx1 = torch.multinomial( # advances rng state for each of the four samples\n logits.softmax(dim=-1).view(-1, 4096),\n num_samples=1, \n replacement=True, \n generator=rng, \n )\n print(idx1)\n idx1_gen_state = rng.get_state()\n print(f\"After idx1, rng state = {idx1_gen_state}\")\n print(f\"logits gen state != idx1 gen state: {torch.any(logits_gen_state != idx1_gen_state)}\")\n rng.set_state(logits_gen_state)\n idx2 = torch.multinomial( # generates two samples, advancing rng state\n # logits[0, ...].unsqueeze(0).softmax(dim=-1).view(-1, 4096),\n logits[1, ...].unsqueeze(0).softmax(dim=-1).view(-1, 4096),\n num_samples=1, \n replacement=True, \n generator=rng, \n ) \n print(idx2)\n idx2 = torch.multinomial( # generates two more samples with the properly advanced rng state\n # logits[0, ...].unsqueeze(0).softmax(dim=-1).view(-1, 4096),\n logits[1, ...].unsqueeze(0).softmax(dim=-1).view(-1, 4096),\n num_samples=1, \n replacement=True, \n generator=rng, \n ) \n print(idx2)\n idx2_gen_state = rng.get_state()\n print(f\"After idx2, rng state = {idx2_gen_state}\")\n print(f\"logits gen state != idx2 gen state: {torch.any(logits_gen_state != idx2_gen_state)}\")\n print(f\"idx1 gen state != idx2 gen state: {torch.any(idx1_gen_state != idx2_gen_state)}\")\n\nif __name__ == \"__main__\":\n main()\n```\n\nAnd here is its output:\n\n```text\n2.8.0+cu129\nAfter logits, rng state = tensor([42, 0, 0, ..., 0, 0, 0], dtype=torch.uint8)\ntensor([[1037],\n [3152],\n [1221],\n [4032]])\nAfter idx1, rng state = tensor([42, 0, 0, ..., 0, 0, 0], dtype=torch.uint8)\nlogits gen state != idx1 gen state: True\ntensor([[2951],\n [3768]])\ntensor([[1221],\n [4032]])\nAfter idx2, rng state = tensor([42, 0, 0, ..., 0, 0, 0], dtype=torch.uint8)\nlogits gen state != idx2 gen state: True\nidx1 gen state != idx2 gen state: False\n```\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":223454,"url":"https://discuss.pytorch.org/t/reproducibility-of-sampling-from-a-subset-of-logits/223454","created_at":"2025-10-04T10:39:04.237000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Is it normal for compiled model outputs to have different tensor strides?\n\nHello everyone,\n\nI recently compiled my model using `torch.compile`, and I noticed that the results after compilation have some layout differences compared to the original (eager) execution.\n\nWhen I check the outputs using `torch.testing.assert_close`, I sometimes get messages like:\n\n```\nThe values for attribute 'stride()' do not match: (27, 1, 9, 3) != (27, 9, 3, 1)\n```\nor\n```\nThe values for attribute 'stride()' do not match: (1, 2) != (2, 1)\n```\n\nThe numerical values themselves appear identical, but the stride orders differ.\nI’d like to ask: **is this expected or normal behavior after model compilation?**\nDoes the compiler sometimes change the memory layout (e.g., due to optimization or contiguous conversion)?\n\nThanks a lot for your time and for maintaining this great project!","reference_answer":"Yes, this is expected. From the [missing manual](https://docs.google.com/document/d/1y5CRfMLdwEoF1nTk9q8qEu1mgMUuUtvhklPKJ2emLU8/edit?tab=t.0): \n\n> Stride divergence\n> PT2 is not guaranteed to produce tensors with exactly the same stride as the eager variants. This can potentially cause correctness problems (or runtime crashes) outside of the torch.compile region if subsequent code is expecting a specific striding without testing, or is using the limited subset of APIs (mostly torch.as_strided, and also obscure situations involving mutating through .reshape()/.contiguous()) which are sensitive to input of strides.\n>\n> TODO: There is supposed to be a way to fix strides, similar to how we can do this for custom ops.","needs_clarification":false,"thread_id":223469,"url":"https://discuss.pytorch.org/t/is-it-normal-for-compiled-model-outputs-to-have-different-tensor-strides/223469","created_at":"2025-10-05T13:18:30.254000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Varying batch size for pre-trained model changes inference result, even in evaluation mode\n\nWell, here’s hoping this behavior is something obvious…Attempting to extract some features using a pre-trained ResNet50 model, which despite being in evaluation mode, is producing different outputs for the same input, if submitted in a larger batch. Tried a couple different versions 2.5.1 and 2.9.0, came up with a minimum reproducible code, switched to AlexNet to avoid potential issues with batch normalization layers, and dropped GPU-acceleration in case of CUDA derived shenanigans. Any insight into how to fix and why result and result2 are not identical would be greatly appreciated! \n\n```python\nimport torch\nfrom torchvision import models\n\n#Setup deterministic behavior\ntorch.use_deterministic_algorithms(True)\n\n#Set torch seed for consistency\ntorch.manual_seed(0)\n\n#Create batch of random input data\nbatch = torch.randn(32, 3, 224, 224)\n\n#Load model and set to evaluation mode\nmodel = models.alexnet(weights='DEFAULT')\nmodel.eval()\n\n#Obtain result for first image, inferencing only it\nwith torch.no_grad(): result = model(torch.unsqueeze(batch[0], 0)).detach()[0]\n\n#Obtain result for first image, inferencing the whole batch\nwith torch.no_grad(): result2 = model(batch).detach()[0]\n\n#Results should be identical when model is in eval mode...?\nprint('Sum Absolute Difference: ', torch.sum(torch.abs(result-result2)).item())\n\n```","reference_answer":"Small numerical errors caused by the limited floating point precision are expected as these depend on the used algorithm and order of operations used to compute the results. Bitwise identical results are achieved for the same setups which includes the workload with its input shapes when deterministic mode is enabled.","needs_clarification":false,"thread_id":223688,"url":"https://discuss.pytorch.org/t/varying-batch-size-for-pre-trained-model-changes-inference-result-even-in-evaluation-mode/223688","created_at":"2025-10-24T06:48:19.857000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"MultiheadAttention with multiple batch dimensions\n\nFor my use-case, the input dimensions are (N, M, L, E), similar to the expected format in `nn.MultiheadAttention` but with an additional \"batch\" dimension M. This 4D tensor is unfortunately not accepted by `nn.MultiheadAttention`.\n\nHow can I implement self/cross attention to be over the second last dimension in a 4D tensor? I'm hoping for an interface similar to `nn.Linear` which accepts (*, E) dimension tensors. \n\nIdeally, the solution shouldn't involve flattening the N and M dimension into a single dimension as the output must be in a 4D tensor format, unless there is an efficient way to reconstruct the 4D structure from 3D with the appropriate attention masks.","reference_answer":"Would it work for you to just vmap the model's forward pass?\n\n```python\nimport torch\nfrom torch import nn, vmap\n\nN, M, L, E = 6, 4, 20, 8\nmodel = nn.MultiheadAttention(embed_dim=E, num_heads=2, batch_first=True)\n\nquery = torch.randn((N, M, L, E))\nkey = torch.randn((N, M, L, E))\nvalue = torch.randn((N, M, L, E))\n\nattn_output, attn_output_weights = vmap(model)(query, key, value)\n\nprint(attn_output.shape)\nprint(attn_output_weights.shape)\n```\n\nOutput:\n```\ntorch.Size([6, 4, 20, 8])\ntorch.Size([6, 4, 20, 20])\n```","needs_clarification":false,"thread_id":223694,"url":"https://discuss.pytorch.org/t/multiheadattention-with-multiple-batch-dimensions/223694","created_at":"2025-10-24T14:24:33.641000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["valerian.rey"],"answered_by_ptrblck":false} {"question":"Torch distributions and yaml\n\nI’m trying to use yaml file to configure which distributions to use in my project. In order to minimize how much parsing I should write, I use [pyyaml tags](https://pyyaml.org/wiki/PyYAMLDocumentation#yaml-tags-and-python-types). My document looks like this:\n\n```\ntest: !!python/object:torch.distributions.Normal\n loc: 42.0\n scale: 1.0\n```\n\nLoading this document works:\n\n```python\nimport yaml\ntest = yaml.load(open(\"test.yaml\"), Loader=yaml.Loader)\n```\n\nHowever, I can’t use the object:\n\n```python\ntest\nTraceback (most recent call last):\n File \"\", line 1, in \n File \"/home/myuser/conda/envs/test/lib/python3.8/site-packages/torch/distributions/distribution.py\", line 334, in __repr__\n [\n File \"/home/myuser/conda/envs/test/lib/python3.8/site-packages/torch/distributions/distribution.py\", line 335, in \n f\"{p}: {self.__dict__[p] if self.__dict__[p].numel() == 1 else self.__dict__[p].size()}\"\nAttributeError: 'float' object has no attribute 'numel'\n```\n\nIt sounds like the object is not properly initialized.\n\nAny idea what’s going wrong ?","reference_answer":"I found a solution using the following yam file:\n\n```\ntest: !!python/object/apply:torch.distributions.Normal\n - 42.0\n - 1.0\n```\n\nNote the `/apply` at the end and the syntax to pass positional arguments.","needs_clarification":false,"thread_id":223735,"url":"https://discuss.pytorch.org/t/torch-distributions-and-yaml/223735","created_at":"2025-10-28T15:33:43.111000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Mathieu_Dubois"],"answered_by_ptrblck":false} {"question":"How to debug origin of nans in gradient of custom module\n\nHi everyone,\n\nI’m trying to optimize a network with a custom module and architecture, I’ll attach the code below. The nodes have specific behaviour where positive and negative weights have different effects; I modelled this by using two different weight tensors and using a mask for the gradient.\n\nWhen running the code we get that the gradient of parameters has a lot of nans. Note that when printing the full gradient matrix only some columns are nans and not the whole matrix, this makes me feel like the nans propagate from a first error\n```[tensor(0.0267), tensor(0.0106), tensor(nan), tensor(nan), tensor(nan), tensor(nan), tensor(nan), tensor(nan), tensor(nan), tensor(nan), tensor(5.1160e-06), tensor(nan), tensor(4.0687e-06), tensor(nan)]```\n\nI have tried using `torch.autograd.set_detect_anomaly(True)` to debug, and it raises `AddBackward0` at the line `sum_f_in = torch.matmul(x**2, self.weight_in**2)+self.bias_in**2`. But after manually checking there is no overflow error or anything. Even when setting `self.weight_in=0` and `self.bias_in=0` it still raises the same error.\n\nSo I'm lost at what else to try and figure out where the error comes from, any help would be greatly appreciated, thanks!\n\nhere is a code to reproduce the error:\n\n```\nimport torch.nn as nn\nimport torch\ntorch.manual_seed(0)\ntorch.autograd.set_detect_anomaly(True)\nDEVICE = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n\nclass Node(nn.Module):\n #node of the netwrok, take a matrxi with n features in and return one with m features\n def __init__(self, weight, bias):\n super().__init__()\n\n self._c = .015436882530272481\n self._fth = 100.\n self._fmax = 4100\n self._in_a = .03051282\n self._in_b = 35.4594017\n self._out_a = 5.419425e-5\n\n #only weights superior to 0, weight_in are weights<0\n self.weight_ex = nn.Parameter(torch.where(weight>0, weight.abs(), 0))\n self._mask_ex_w = (weight>0).to(DEVICE)#mask for gradient\n self.weight_in = nn.Parameter(torch.where(weight<0, weight.abs(), 0))\n self._mask_in_w = (weight<0).to(DEVICE)\n self.bias_ex = nn.Parameter(torch.where(bias>0, bias.abs(), 0))\n self._mask_ex_b = (bias>0).to(DEVICE)\n self.bias_in = nn.Parameter(torch.where(bias<0, bias.abs(), 0))\n self._mask_in_b = (bias<0).to(DEVICE)\n\n self.set_hook()\n\n def forward(self, x):\n '''Input of shape (batch_dim, time_dim, 2)'''\n\n #reducing inputs\n sum_f_ex = torch.matmul(x**2, self.weight_ex**2)+self.bias_ex**2\n sum_f_in = torch.matmul(x**2, self.weight_in**2)+self.bias_in**2\n f_ex = torch.sqrt(sum_f_ex)\n f_in = torch.sqrt(sum_f_in)\n\n diff = f_ex-self._fth\n xc = self._c*torch.sqrt(torch.where(diff>0, diff, 0))+f_in*self._out_a\n res = torch.where(f_ex>(f_in*self._in_a+self._in_b), xc, 0)\n return res\n\n def set_hook(self):\n #register hooks for gradient masking\n def _hook_ex_w(grad):\n return grad*self._mask_ex_w\n def _hook_in_w(grad):\n return grad*self._mask_in_w\n def _hook_ex_b(grad):\n return grad*self._mask_ex_b\n def _hook_in_b(grad):\n return grad*self._mask_in_b\n\n self.weight_ex.register_hook(_hook_ex_w)\n self.weight_in.register_hook(_hook_in_w)\n self.bias_ex.register_hook(_hook_ex_b)\n self.bias_in.register_hook(_hook_in_b)\n\nclass Network(nn.Module):\n #creatwe the network\n def __init__(self, shapes):\n super().__init__()\n self.all_nodes = nn.Sequential()\n\n for i in range(len(shapes)):\n #build nodes one after the other\n self.all_nodes.append(Node(\n torch.FloatTensor(*shapes[i]).uniform_(-1500, 1500),\n torch.FloatTensor(shapes[i][1]).uniform_(-500, 500)))\n\n #params for sigmoid\n self._decision_line = nn.Parameter(torch.tensor(.7).float())\n self._slope = nn.Parameter(torch.tensor(1.).float())\n\n def forward(self, x):\n _, time_dim, _ = x.shape\n res = self.all_nodes(x)#propagate through node\n out = torch.sum(res, dim=[1, 2])/time_dim#average over time\n return torch.sigmoid(self._slope*(out-self._decision_line))#activation function\n\nif __name__=='__main__':\n #create model and data\n shapes = [[12, 7], [7, 2], [2, 1]]\n data = torch.FloatTensor(32, 210, 12).uniform_(0, 1).to(DEVICE)\n labels = (torch.rand(32)<.5).float().to(DEVICE)\n model = Network(shapes).to(DEVICE)\n loss_fn = nn.BCELoss()\n #run model and propagate loss\n preds = model(data).ravel()\n loss = loss_fn(preds, labels)\n loss.backward()\n print([torch.norm(p.grad.cpu()) for p in model.parameters()])\n```","reference_answer":"Hi! I think the cause of your issue is `torch.sqrt`. Its derivative at `+0.0` is `inf`, at `-0.0` is `-inf` and at negative value is `nan`. So it's likely that some tensor provided to `torch.sqrt` contains some zeros, which results in `inf` values in the gradient, which then turns into `nan` values after further backpropagation.\n\nRunning your example with a small value (`eps`) added to the tensor on which you apply `torch.sqrt` seems to solve the issue:\n```python\n def forward(self, x):\n '''Input of shape (batch_dim, time_dim, 2)'''\n eps = 0.000001\n #reducing inputs\n sum_f_ex = torch.matmul(x**2, self.weight_ex**2)+self.bias_ex**2\n sum_f_in = torch.matmul(x**2, self.weight_in**2)+self.bias_in**2\n f_ex = torch.sqrt(sum_f_ex + eps)\n f_in = torch.sqrt(sum_f_in + eps)\n\n diff = f_ex-self._fth\n xc = self._c*torch.sqrt(torch.where(diff>0, diff, 0) + eps)+f_in*self._out_a\n res = torch.where(f_ex>(f_in*self._in_a+self._in_b), xc, 0)\n return res\n```","needs_clarification":false,"thread_id":223747,"url":"https://discuss.pytorch.org/t/how-to-debug-origin-of-nans-in-gradient-of-custom-module/223747","created_at":"2025-10-29T10:56:33.209000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["valerian.rey"],"answered_by_ptrblck":false} {"question":"OSError: [Errno 36] File name too long\n\nHello, we encountered a ‘file name too long’ bug while using PyTorch compile. The specific error is:\n\n```\nOSError: [Errno 36] File name too long: '/tmp/torchinductor_hadoop-pnc/triton/3/b13585fb327ef97fcb905e2d1fea4abede414a1d70d76544643737e47b9f4dd6/__grp__triton_per_fused__log_softmax__to_copy_abs_add_binary_cross_entropy_with_logits_div_gt_hypot_lt_mean_mse_loss_mul_neg_nll_loss_forward_pow_randint_relu_rsub_sigmoid_smooth_l1_loss_sub_sum_where_68.json.tmp.pid_3437_3b13d3c6-b5ce-4ce1-976a-5d1c7fffeef5'\n```\n\n[details=\"detail error log\" open]\n\\[rank1\\]: Traceback (most recent call last):\n\n\\[rank1\\]: File “/usr/local/lib/python3.11/site-packages/torch/\\_inductor/compile_worker/subproc_pool.py”, line 337, in do_job\n\n\\[rank1\\]: result = job()\n\n\\[rank1\\]: ^^^^^\n\n\\[rank1\\]: File “/usr/local/lib/python3.11/site-packages/torch/\\_inductor/runtime/compile_tasks.py”, line 61, in \\_worker_compile_triton\n\n\\[rank1\\]: kernel.precompile(warm_cache_only=True)\n\n\\[rank1\\]: File “/usr/local/lib/python3.11/site-packages/torch/\\_inductor/runtime/triton_heuristics.py”, line 267, in precompile\n\n\\[rank1\\]: self.\\_precompile_worker()\n\n\\[rank1\\]: File “/usr/local/lib/python3.11/site-packages/torch/\\_inductor/runtime/triton_heuristics.py”, line 296, in \\_precompile_worker\n\n\\[rank1\\]: compile_results.append(self.\\_precompile_config(c))\n\n\\[rank1\\]: ^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\\[rank1\\]: File “/usr/local/lib/python3.11/site-packages/torch/\\_inductor/runtime/triton_heuristics.py”, line 537, in \\_precompile_config\n\n\\[rank1\\]: binary = triton.compile(\\*compile_args, \\*\\*compile_kwargs)\n\n\\[rank1\\]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\\[rank1\\]: File “/usr/local/lib/python3.11/site-packages/triton/compiler/compiler.py”, line 300, in compile\n\n\\[rank1\\]: fn_cache_manager.put_group(metadata_filename, metadata_group)\n\n\\[rank1\\]: File “/usr/local/lib/python3.11/site-packages/triton/runtime/cache.py”, line 105, in put_group\n\n\\[rank1\\]: return self.put(grp_contents, grp_filename, binary=False)\n\n\\[rank1\\]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n\\[rank1\\]: File “/usr/local/lib/python3.11/site-packages/triton/runtime/cache.py”, line 122, in put\n\n\\[rank1\\]: with open(temp_path, mode) as f:\n\n\\[rank1\\]:\n\nOSError: \\[Errno 36\\] File name too long: ‘/tmp/torchinductor_hadoop-pnc/triton/3/b13585fb327ef97fcb905e2d1fea4abede414a1d70d76544643737e47b9f4dd6/\\__grp__triton_per_fused__log_softmax__to_copy_abs_add_binary_cross_entropy_with_logits_div_gt_hypot_lt_mean_mse_loss_mul_neg_nll_loss_forward_pow_randint_relu_rsub_sigmoid_smooth_l1_loss_sub_sum_where_68.json.tmp.pid_3437_3b13d3c6-b5ce-4ce1-976a-5d1c7fffeef5\n\n[/details]\n\nIt appears that when compiling, the names for the generated Triton kernels are concatenated from the names of the fused operators. This can easily result in excessively long filenames when a large number of operators are fused. Are there any methods to resolve this issue?\n\nMy PyTorch version is 2.7.0","reference_answer":"https://github.com/triton-lang/triton/commit/0f18662362a185844775dfcc038395a7dd383983 It appears that this issue is inherent to Triton itself and has been resolved starting from version 3.2.0.","needs_clarification":false,"thread_id":223758,"url":"https://discuss.pytorch.org/t/oserror-errno-36-file-name-too-long/223758","created_at":"2025-10-30T10:43:27.775000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["xgbj"],"answered_by_ptrblck":false} {"question":"Onnx export using Torch gives wrong results\n\nSo i trained a resnet18 on patched images. I run the resnet (.pth) file on my unique test set and get good results. I try to export it to onnx and i get way worse results.\n\nI’ve checked the input tiles and they’re identical, same max and min, same pre processing. I even exported the raw tiles and they were identical. I even looked at the individual pixel values and these were also the same.\n\nNow when i run the image trough the onnx model the export logits are different.\n\n(Same result on both windows and ubuntu\n\nNormally all the files should be here, if something doesn’t work. Be sure to let me know because i changed it a bit so i wouldnt have to upload everything\n\n### **To reproduce**\n\n* uv add onnxruntime\n\n* uv add onnx\n\n* uv pip3 install torch torchvision --index-url [https://download.pytorch.org/whl/cu128](https://download.pytorch.org/whl/cu128)\n\n* uv add onnxscript\n\n* uv add scikit-learn\n\nThen run the export to onnx as follows:\nuv run python export_to_onnx.py --model “resnet18” --weights “./resnet18_best.pth” --output “test.onnx”\n\nThen\nThe root folder should contain 2 subfolders 1.Knot and 0.NoKnot. You can just copy the same image twice\n\nuv run python test_onnx.py --onnx “./test.onnx” --root ./images\n\nI also added 2 images, the first one is without knots and the logits of this image should be\n\\[-3.072449 -2.8448505 -7.6250186 -6.501796 \\] → is like this for .pth file but not for .onnx file\n\nThe second one has knots and he should return 3 positive classe (1) and 1 negative (0)\n\n### **Urgency**\n\nIt is quite urgent as i need it within this week.\n\n### **Platform**\n\nWindows\n\n### **OS Version**\n\nWindows 11\n\n### **ONNX Runtime Installation**\n\nReleased Package\n\n### **ONNX Runtime Version or Commit ID**\n\nonnxruntime 1.23.2\n\n### **ONNX Runtime API**\n\nPython\n\n### **Architecture**\n\nX64\n\n### **Execution Provider**\n\nDefault CPU\n\n### **Execution Provider Library Version**\n\nCuda 12.8 (windows) and 12.6 (ubuntu\n\n### **Model File**\n\nIf needed i can try to upload it.\n\n### **Is this a quantized model?**\n\nNo\n\nI also have ticker on the onnxruntime github:\n[\\[Performance\\] Outputs are completely different between .onnx model and .pth model · Issue #26504 · microsoft/onnxruntime](https://github.com/microsoft/onnxruntime/issues/26504#issuecomment-3493467832)\n\nNew additions:\n\nFrom report:\n```## Error messages\n\nNo errors\n```\nBesides this i also added the latest torch nightly and onnxscript\n\ntorch 2.10.0.dev20251105+cu126\ntorchvision 0.25.0.dev20251105+cu126\nonnxscript 0.5.6\n\n```\nBut the issue seems to continue.\n\nThere is however 1 small difference between the tensors sent to the onnx and the pth. The .pth version is rounded off a bit earlier. \nI dont know if this is a big issue or not.\n\nPTH:\ntensor([[[[-1.9124, -1.8953, -1.8953, ..., -1.6213, -1.6213, -1.6555],\n[[[[-1.9124069 -1.8952821 -1.8952821 ... -1.6212862 -1.6212862 -1.6555357]\n [-1.9124, -1.8953, -1.8953, ..., -1.6555, -1.6555, -1.6384],\n [-1.9124069 -1.8952821 -1.8952821 ... -1.6555357 -1.6555357 -1.6384109]\n [-1.9124, -1.8953, -1.8953, ..., -1.6555, -1.6555, -1.6384]\n...\n\nONNX:\n[[[[-1.9124069 -1.8952821 -1.8952821 ... -1.6212862 -1.6212862 -1.6555357]\n [-1.9124, -1.8953, -1.8953, ..., -1.6555, -1.6555, -1.6384],\n [-1.9124069 -1.8952821 -1.8952821 ... -1.6555357 -1.6555357 -1.6384109]\n [-1.9124, -1.8953, -1.8953, ..., -1.6555, -1.6555, -1.6384],\n [-1.9124069 -1.8952821 -1.8952821 ... -1.6555357 -1.6555357 -1.6384109] \n...\n```\n\n---\n\nNow i also tried to use the exact same preprocessing, so i changed my onnx model to just do the following:\n\n```\n def forward(self, tiles):\n logits = self.model(tiles)\n return logits, logits\n```\n\nThen i added it right before my .pth model in my test\n\n```\nwith torch.no_grad():\n for patches, label, path in test_loader:\n sess = create_session(onnx_path)\n in_name = sess.get_inputs()[0].name\n outputs = sess.run(None, {in_name: patches.cpu().numpy()})\n print(f\"ONNX outputs: {outputs}\")\n logits = model(patches) \n```\n\nAnd for the same input there are 2 different outputs\n\nONNX outputs: \\[array(\\[\\[-2.9795594\\],\n\\[-3.2486563\\],\n\\[-2.2178779\\],\n\\[-2.025703 \\]\\], dtype=float32)\n\nLogits per patch: \\[-3.072449 -2.8448505 -7.6250186 -6.501796 \\] (PTH)\n\nCould the difference be GPU for pth and CPU for onnx?\n\nUpdate:\n\nI exported another older checkpoint and it also gives different results than the earlier onnx version (Same code). This makes me think that it might be a version mismatch somewhere. I’ll look futher into it if its something else.\n\n(non patched version)\n\nEdit: It is almost as the models differ, but the exact same .pth file was used. Or that the weights/biases are incorrectly parsed/binded to the onnx model","reference_answer":"Export with inference mode on, `dynamo` set to False, `training=torch.onnx.TrainingMode.EVAL`, constant folding enabled, and `keep_initializers_as_inputs=False`.","needs_clarification":false,"thread_id":223825,"url":"https://discuss.pytorch.org/t/onnx-export-using-torch-gives-wrong-results/223825","created_at":"2025-11-06T09:56:38.915000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[3,4],"answer_authors":["Diamanka_Odore","timcov"],"answered_by_ptrblck":false} {"question":"Autograd and dead-code elimination\n\nHi,\nI have a question about dead-code elimination and autograd.\n\nI am looking at the functional API, which has torch.func.grad and torch.func.grad_and_value.\nClearly torch.func.grad_and_value needs to compute both the forward and backward pass.\nHowever, it seems like in some very simple cases torch.func.grad should be able to avoid computing the forward pass. For instance when computing the gradient $dE/dz$ of a quadratic term like $E=x^\\\\top W z$, where $W=A^\\\\top + A$ is a symmetric matrix, then I would like torch to be smart enough to compute $dE/dz = Wx$ without also computing E under the hood.\n\nMy question is if torch will avoid the redundant computation of E in such cases?\nDo I need to compile the code to get this kind of optimized behaviour?","reference_answer":"Hey!\n\ntorch.func by itself is indeed an eager only implementation. And thus will not do any DCE.\n\nYou will have to use torch.compile and similar compiler structure to get that behavior.","needs_clarification":false,"thread_id":223905,"url":"https://discuss.pytorch.org/t/autograd-and-dead-code-elimination/223905","created_at":"2025-11-07T09:58:28.293000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["albanD"],"answered_by_ptrblck":false} {"question":"In a multi-GPU DDP environment, if the loss on one rank is NaN while the others are normal, could this cause the all-reduce to hang?\n\nIn AMP mixed-precision training, if NaNs are detected, the model parameters’ gradients become `None`. In this case, will the all-reduce operation be skipped, causing other ranks to wait indefinitely and eventually crash the program?","reference_answer":"No, as answered in your [cross post](https://discuss.pytorch.org/t/how-to-continue-training-with-ddp-when-loss-is-nan-causing-by-amp/205920/5?u=ptrblck).","needs_clarification":false,"thread_id":223937,"url":"https://discuss.pytorch.org/t/in-a-multi-gpu-ddp-environment-if-the-loss-on-one-rank-is-nan-while-the-others-are-normal-could-this-cause-the-all-reduce-to-hang/223937","created_at":"2025-11-12T03:48:15.935000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Conv3D runs very slow in fp16 and bf16\n\nHello,\n\nI am experimenting with a pretrained model (Qwen3VL from Huggingface). I notice the embedding layer is exceptionally slow when processing image feature, while the later attention layers can run efficiently.\n\nThe model’s visual embedding layer uses Conv3D to perform linear embedding:\n\n```\nclass Qwen3VLVisionPatchEmbed(nn.Module):\n def __init__(self, config) -> None:\n super().__init__()\n self.patch_size = config.patch_size\n self.temporal_patch_size = config.temporal_patch_size\n self.in_channels = config.in_channels\n self.embed_dim = config.hidden_size\n\n kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size]\n self.proj = nn.Conv3d(self.in_channels, self.embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=True)\n\n def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:\n target_dtype = self.proj.weight.dtype\n hidden_states = hidden_states.view(\n -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size\n )\n hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim)\n return hidden_states\n```\n\nAfter some digging, I found that the nn.Conv3D can be significantly slower than nn.Linear under fp16 or bf16, while their performance is normal under fp32.\n\nTo verify, I ran a minimal benchmark:\n\n```\nimport torch\nimport torch.nn as nn\nimport time\n\nprint(\"torch version:\", torch.__version__)\nprint(\"CUDA available:\", torch.cuda.is_available())\nprint(\"cuDNN available:\", torch.backends.cudnn.is_available())\nprint(\"cuDNN version:\", torch.backends.cudnn.version())\n\ndevice = torch.device(\"cuda\")\nN = 10240\nC, T, H, W = 3, 2, 16, 16\nembed_dim = 1024\n\ndtype = torch.bfloat16\nx = torch.randn(N, C, T, H, W, device=device, dtype=dtype)\n\nconv = nn.Conv3d(C, embed_dim, kernel_size=(T, H, W), stride=(T, H, W), bias=True).to(device, dtype=dtype)\nlinear = nn.Linear(C*T*H*W, embed_dim, bias=True).to(device, dtype=dtype)\n\n# timing conv\ntorch.cuda.synchronize()\nt0 = time.time()\n_ = conv(x)\ntorch.cuda.synchronize()\nt1 = time.time()\n\n# timing linear\ntorch.cuda.synchronize()\n_ = linear(x.view(N, -1))\ntorch.cuda.synchronize()\nt2 = time.time()\n\nprint(\"Conv3d:\", t1 - t0, \"s\")\nprint(\"Linear:\", t2 - t1, \"s\")\n\n```\n\nWith `dtype = torch.bfloat16`, the output is:\n\n```\ntorch version: 2.9.0+cu128\nCUDA available: True\ncuDNN available: True\ncuDNN version: 91002\nConv3d: 42.12006068229675 s\nLinear: 0.0008780956268310547 s\n```\n\nWith `dtype = torch.float16`:\n\n```\nConv3d: 42.59985375404358 s\nLinear: 0.0016818046569824219 s\n```\n\nWith `dtype = torch.float32`:\n\n```\nConv3d: 0.06699419021606445 s\nLinear: 0.04182004928588867 s\n```\n\nLocal environment:\n\n* **GPU:** NVIDIA RTX 6000 Blackwell\n* **Driver:** 570.195.03\n* **CUDA:** 12.8\n* **Torch:** 2.9.0+cu128\n* **cuDNN:** 91002\n\nAm I missing anything here to run things appropriately? Any guidance would be greatly appreciated!","reference_answer":"Use a torch and cuDNN pair that works together. Torch 2.8.0 with cuDNN 9.10 works, and so does torch 2.9.1 with cuDNN 9.15, which can be installed with pip. Torch 2.9.0 didn't work with either cuDNN version.","needs_clarification":false,"thread_id":223940,"url":"https://discuss.pytorch.org/t/conv3d-runs-very-slow-in-fp16-and-bf16/223940","created_at":"2025-11-12T20:46:32.222000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["Marute1037","valerian.rey"],"answered_by_ptrblck":false} {"question":"PPO learning poorly on LunarLander-v3\n\nHi!\n\nI am using PPO to try to learn LunarLander-v3 in torchrl. I am having good results (avg reward > 280) using stable-baselines3 (sb3) with less than 1M steps. The thing is, I have tried a bunch of different things listed thereafter but the performance seems to be on average poor-ish (\\~150) in torchrl and never quite as high as sb3. Worse, it seems some updates made make the policy regress compared to what it was in the past (going back to episode length 1000 => lander is just hovering again instead of trying to land). There is in both cases exploration but I do not expect the exploration to degrade the current solution that much.\n\nSo, I started off the torchRL version off the python notebook related to double inverted pendulum found [on this page](https://docs.pytorch.org/rl/stable/tutorials/coding_ppo.html).\nHere is a couple of things I have changed compared to the example:\n\n1. Set all hyperparams the same as sb3\n2. Use the same models for both value and policy (MLP of 3 layers, 16 wide, same tanh activation) as sb3\n3. Set the policy as `ProbabilisticActor`\n `policy_module = ProbabilisticActor( module=policy_module, spec=single_env.action_spec, in_keys=[\"logits\"], distribution_class=OneHotCategorical, return_log_prob=True )`\n4. Removed the annealing scheduler\n5. Evaluate on parallel env\n\nI have attached several screenshots to compare both version results and full code for LunarLander-v3\n\nHere are a few things I have tried without any luck:\n\n1. Took the trained VecNormalize output of sb3 to replace loc and scale tensors after `single_env.transform[0].init_stats(num_iter=10000, reduce_dim=0, cat_dim=0)`. It learns absolutly nothing and gets stuck with reward 0.\n2. Changing the norm from `smooth_l1` to `l2` but the critic values are even higher than with smooth_l1 (which seem to be already quite large 16 at t0 then \\~1-2 on avg)\n3. Increase both `frames_per_batch` and `sub_batch_size` to have more stable grads / learning\n\nHere are some differences between torchrl and sb3:\n\n1. Original torchrl notebook has a replay buffer, sb3 does not\n2. sb3 has 8 training envs and 8 evals envs, torchrl has 1 training, 8 for eval. I was not confident yet modifying original code to add vec_env given the problem stated here.\n3. **\\[EDIT\\]** I believe the env is normalized just during the beginning where in sb3 it is constantly updating\n\nQuestions:\n-Could it be because I am using OneHotCaterogical and only one thruster is on ?\n-Do you have any idea of what could be wrong here ?\n\nFinally, note that I have a solid experience developing code on computers, and I am not very familiar with RL theory and training models. It may be something obvious.\n\nThanks in advance !\n\n[image]\n\n[details=\"Full code\" open]\n```python\n#!/usr/bin/env python3\n\nimport torch\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom os import environ\nfrom tensordict.nn import TensorDictModule\nfrom tensordict.nn.distributions import NormalParamExtractor\nfrom torch import multiprocessing, nn, tensor\nfrom torch.distributions.categorical import Categorical as TorchCategorical\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchrl.collectors import SyncDataCollector\nfrom torchrl.data.replay_buffers import ReplayBuffer\nfrom torchrl.data.replay_buffers.samplers import SamplerWithoutReplacement\nfrom torchrl.data.replay_buffers.storages import LazyTensorStorage\nfrom torchrl.envs import (Compose, DoubleToFloat, EnvCreator, ObservationNorm, ParallelEnv, StepCounter, TransformedEnv, step_mdp)\nfrom torchrl.envs.libs.gym import GymEnv\nfrom torchrl.envs.utils import check_env_specs, ExplorationType, set_exploration_type\nfrom torchrl.modules import OneHotCategorical, ProbabilisticActor, TanhNormal, ValueOperator\nfrom torchrl.objectives import ClipPPOLoss\nfrom torchrl.objectives.value import GAE\nfrom tqdm import tqdm\n\nif __name__ == \"__main__\":\n device = \"cpu\"\n\n num_cells = 16 # number of cells in each layer i.e. output dim.\n lr = 3e-4\n max_grad_norm = 0.5\n p_env_count = 8\n\n frames_per_batch = 2048\n # For a complete training, bring the number of frames up to 1M\n total_frames = 1_000_000\n\n sub_batch_size = 64 # cardinality of the sub-samples gathered from the current data in the inner loop\n num_epochs = 10 # optimization steps per batch of data collected\n clip_epsilon = (\n 0.2 # clip value for PPO loss: see the equation in the intro for more context.\n )\n gamma = 0.99\n lmbda = 0.95\n entropy_eps = 1e-3\n\n env_name = \"LunarLander-v3\"\n\n single_env = TransformedEnv(\n GymEnv(\"LunarLander-v3\", device=device, render_mode=\"rgb_array\"),\n Compose(\n # normalize observations\n ObservationNorm(in_keys=[\"observation\"]),\n DoubleToFloat(),\n StepCounter(),\n ),\n )\n\n parallel_env = TransformedEnv(\n ParallelEnv(p_env_count, EnvCreator(lambda: GymEnv(env_name, device=device))),\n Compose(\n # normalize observations\n ObservationNorm(in_keys=[\"observation\"]),\n DoubleToFloat(),\n StepCounter(),\n ),\n )\n\n single_env.transform[0].init_stats(num_iter=10000, reduce_dim=0, cat_dim=0)\n\n parallel_env.transform[0].loc = single_env.transform[0].loc.repeat(p_env_count, 1)\n parallel_env.transform[0].scale = single_env.transform[0].scale.repeat(p_env_count, 1)\n\n check_env_specs(single_env)\n check_env_specs(parallel_env)\n\n actor_net = nn.Sequential(\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(single_env.action_spec.space.n, device=device)\n )\n\n policy_module = TensorDictModule(actor_net, in_keys=[\"observation\"], out_keys=[\"logits\"])\n\n policy_module = ProbabilisticActor(\n module=policy_module,\n spec=single_env.action_spec,\n in_keys=[\"logits\"],\n distribution_class=OneHotCategorical,\n return_log_prob=True # Return log probability of sampled actions (required for PPO loss)\n )\n\n value_net = nn.Sequential(\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(num_cells, device=device),\n nn.Tanh(),\n nn.LazyLinear(1, device=device),\n )\n\n value_module = ValueOperator(\n module=value_net,\n in_keys=[\"observation\"],\n )\n\n policy_module(single_env.reset())\n value_module(single_env.reset())\n \n collector = SyncDataCollector(\n single_env,\n policy_module,\n frames_per_batch=frames_per_batch,\n total_frames=total_frames,\n split_trajs=False,\n device=device,\n )\n\n replay_buffer = ReplayBuffer(\n storage=LazyTensorStorage(max_size=frames_per_batch),\n sampler=SamplerWithoutReplacement(),\n )\n\n advantage_module = GAE(gamma=gamma, lmbda=lmbda, value_network=value_module, average_gae=True, device=device)\n\n loss_module = ClipPPOLoss(\n actor_network=policy_module,\n critic_network=value_module,\n clip_epsilon=clip_epsilon,\n entropy_bonus=bool(entropy_eps),\n entropy_coeff=entropy_eps,\n # these keys match by default but we set this for completeness\n critic_coeff=0.5,\n loss_critic_type=\"smooth_l1\"\n )\n\n optim = torch.optim.Adam(loss_module.parameters(), lr)\n\n timenow = str(datetime.now())[0:-7]\n timenow = '_' + timenow.replace(' ', '_').replace(':','')\n writepath = environ['HOME'] + '/ml_runs/trl_ppo_1M' + timenow\n writer = SummaryWriter(log_dir=writepath)\n\n total_steps = 0\n mean_rewards = []\n eval_reward_sums = []\n\n desc_bar = tqdm(total=0, position=0, bar_format='{desc}')\n pbar = tqdm(total=total_frames)\n eval_str = \"\"\n\n # We iterate over the collector until it reaches the total number of frames it was\n # designed to collect:\n for i, tensordict_data in enumerate(collector):\n # we now have a batch of data to work with. Let's learn something from it.\n for _ in range(num_epochs):\n # We'll need an \"advantage\" signal to make PPO work.\n # We re-compute it at each epoch as its value depends on the value\n # network which is updated in the inner loop.\n advantage_module(tensordict_data)\n data_view = tensordict_data.reshape(-1)\n replay_buffer.extend(data_view.cpu())\n for _ in range(frames_per_batch // sub_batch_size):\n subdata = replay_buffer.sample(sub_batch_size)\n loss_vals = loss_module(subdata.to(device))\n loss_value = (loss_vals[\"loss_objective\"] + loss_vals[\"loss_critic\"] + loss_vals[\"loss_entropy\"])\n\n # Optimization: backward, grad clipping and optimization step\n loss_value.backward()\n # this is not strictly mandatory but it's good practice to keep\n # your gradient norm bounded\n torch.nn.utils.clip_grad_norm_(loss_module.parameters(), max_grad_norm)\n optim.step()\n optim.zero_grad()\n\n total_steps += tensordict_data.numel()\n mean_rewards.append(tensordict_data[\"next\", \"reward\"].mean().item())\n \n ep_steps_max = tensordict_data[\"next\",\"step_count\"].max().item()\n current_lr = optim.param_groups[0][\"lr\"]\n\n writer.add_scalar('train/loss/objective', loss_vals[\"loss_objective\"], global_step=total_steps)\n writer.add_scalar('train/loss/critic', loss_vals[\"loss_critic\"], global_step=total_steps)\n writer.add_scalar('train/loss/entropy', loss_vals[\"loss_entropy\"], global_step=total_steps)\n writer.add_scalar('train/lr', current_lr, global_step=total_steps)\n \n writer.add_scalar('train/episode_steps_max', ep_steps_max, global_step=total_steps)\n writer.add_scalar('train/episode_steps_min', tensordict_data[\"step_count\"].min().item(), global_step=total_steps)\n # writer.add_scalar('episode_steps_avg', tensordict_data[\"step_count\"].mean().item(), global_step=total_steps)\n\n cum_reward_str = f\" avg reward: {mean_rewards[-1]:4.2f} (init: {mean_rewards[0]:4.2f})\"\n stepcount_str = f\"eps steps (max): {ep_steps_max}\"\n lr_str = f\"lr policy: {current_lr: 4.4f}\"\n\n if i % 10 == 0:\n # We evaluate the policy once every 10 batches of data.\n # Evaluation is rather simple: execute the policy without exploration\n # (take the expected value of the action distribution) for a given\n # number of steps (1000, which is our ``env`` horizon).\n # The ``rollout`` method of the ``env`` can take a policy as argument:\n # it will then execute this policy at each step.\n with set_exploration_type(ExplorationType.DETERMINISTIC), torch.no_grad():\n # execute a rollout with the trained policy\n eval_rollout = parallel_env.rollout(1000, policy_module)\n eval_sums = eval_rollout[\"next\", \"reward\"].sum(dim=1)\n eval_sums_avg = eval_sums.mean().item()\n eval_sums_std = eval_sums.std().item()\n eval_sums_min = eval_sums.min().item()\n eval_sums_max = eval_sums.max().item()\n\n writer.add_scalar(\"eval/reward_avg\", eval_sums_avg, global_step=total_steps)\n writer.add_scalar(\"eval/reward_std\", eval_sums_std, global_step=total_steps)\n writer.add_scalar(\"eval/reward_min\", eval_sums_min, global_step=total_steps)\n writer.add_scalar(\"eval/reward_max\", eval_sums_max, global_step=total_steps)\n # writer.add_scalar(\"eval/steps_max\", eval_steps_max, global_step=total_steps)\n eval_str = f\"eval avg: {eval_sums_avg: .1f} \"\n del eval_rollout\n\n pbar.update(tensordict_data.numel())\n desc_bar.set_description(\",\".join([eval_str, cum_reward_str, stepcount_str, lr_str]))\n\n del single_env\n\n```\n\n[/details]","reference_answer":"Observation statistics need to keep updating for PPO. ObservationNorm is fixed after the initial steps, unlike SB3's VecNormalize. Scale both observations and rewards with VecNorm:\n\n```\ntrain_env = TransformedEnv(\n GymEnv(env_name, device=device),\n Compose(\n VecNorm(in_keys=[\"observation\", \"reward\"], eps=1e-8, new_api=True),\n DoubleToFloat(),\n StepCounter(),\n ),\n)\n```","needs_clarification":false,"thread_id":223951,"url":"https://discuss.pytorch.org/t/ppo-learning-poorly-on-lunarlander-v3/223951","created_at":"2025-11-15T09:48:41.392000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["mario779petri","yoan"],"answered_by_ptrblck":false} {"question":"GPU VRAM not getting cleared\n\nI am trying to implement a federated learning experiment, where there is one server and 10 clients. For each client, I am using a copy of the ResNet18 model and a copy of the SGD optimizer. And another copy is in the server. I keep the client models and optimizers in a list like this\n\n```python\nfor client_idx in range(client_num):\n net_current = copy.deepcopy(net)\n optimizer = torch.optim.Adam(net_current.parameters(), lr=lr, betas=(0.9, 0.999))\n scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma = 0.95, last_epoch = -1)\n net_clients.append(net_current.to('cpu'))\n optimizer_clients.append(optimizer)\n scheduler_clients.append(scheduler)\n```\n\nFor each client, I run the local training,\n\n`for client_idx in source_site_idx:`\n` dataloader_current = dataloader_clients[client_idx]`\n` net_current.to(device=GPUdevice)`\n` net_current.train()`\n` optimizer_current = optimizer_clients[client_idx] #.to(GPUdevice)`\n` scheduler_current = scheduler_clients[client_idx]`\n\nAfter training is done, I assign `None` to both `net_current` and `optimizer_current`\n\nI want to clear the GPU VRAM being occupied by the current client model; however, I observe that the GPU VRAM that gets occupied by the client model does not get cleared if I assign None to both net_current and optimizer_current.\n\nI have also tried\n\n`net_clients[client_idx].cpu()`\n\nBut GPU VRAM does not get cleared.\n\nWhat can be done to clear the GPU VRAM by (maybe) offloading the model weights to CPU?","reference_answer":"Each optimizer and scheduler holds references to the model parameters, so the GPU memory stays in use while those references exist. Setting `net_current` and `optimizer_current` to None doesn't free anything, because the lists still hold references. Set `optimizer_clients` and `scheduler_clients` to None. To keep the client models for the next epoch, move `net_clients` to the CPU with `.cpu()`. This needs enough CPU memory for the models and costs some time to copy them back.","needs_clarification":false,"thread_id":223968,"url":"https://discuss.pytorch.org/t/gpu-vram-not-getting-cleared/223968","created_at":"2025-11-18T15:44:41.867000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[4,5,6],"answer_authors":["KFrank","Siladittya_Manna"],"answered_by_ptrblck":false} {"question":"Run PyTorch tests on local build, Mac, M1 Apple Silicon\n\nHello,\n\nI'm trying to run tests from the pytorch/test directory on Mac with M1 Apple Silicon.\n\nThe build was successful.\n\nPython 3.12.10, Apple CLang version 17.0.0 (clang-1700.4.4.1)\n\n`python -m pip install --no-build-isolation -v -e .`\n\nI use VS Code to browse all the tests in the corresponding directory.\n\nThe first fix was in conftest.py because VS Code could not find pytest_shard_custom package.\n\n```\n# from pytest_shard_custom import pytest_addoptions as shard_addoptions, PytestShardPlugin\n```\n\n```\nfrom .pytest_shard_custom import pytest_addoptions as shard_addoptions, PytestShardPlugin\n```\n\nDuring the directory scan, it now shows me the following error for all tests\n\n```\nImportError: dlopen(/Users/user1/Documents/GitHub/pytorch/torch/_C.cpython-312-darwin.so, 0x0002): symbol not found in flat namespace '_PyDict_GetItemRef'\n```\n\nIt would be great if you could help me.","reference_answer":"I’m not using VSCode myself so I can’t talk too much about the test discovery.\n\nBut we run test in a very particular way, you can check `python test/run_test.py –help` for details. And I am not surprised that VSCode doesn’t pick up on it.\n\n```\nImportError: dlopen(/Users/user1/Documents/GitHub/pytorch/torch/_C.cpython-312-darwin.so, 0x0002): symbol not found in flat namespace '_PyDict_GetItemRef'\n\n```\n\nThis error looks like a python version mismatch. Make sure that you build and run with the same python version.","needs_clarification":false,"thread_id":223977,"url":"https://discuss.pytorch.org/t/run-pytorch-tests-on-local-build-mac-m1-apple-silicon/223977","created_at":"2025-11-19T18:16:48.763000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["albanD"],"answered_by_ptrblck":false} {"question":"torchaudio undefined symbol\n\nlibtorchaudio.so: undefined symbol: \\_ZN3c1013MessageLogger6streamB5cxx11Ev","reference_answer":"This error comes from mixing libraries built from different PyTorch releases, for example a system-wide PyTorch install next to the one you use. Remove the system PyTorch install so only one version remains.","needs_clarification":false,"thread_id":224042,"url":"https://discuss.pytorch.org/t/torchaudio-undefined-symbol/224042","created_at":"2025-11-28T00:49:58.517000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,8],"answer_authors":["0xra0","ptrblck"],"answered_by_ptrblck":true} {"question":"Training and Validation Loss not improving\n\nHello ya’ll\n\nI’m running into a problem with my U-Net, I’m trying to train my model to capture people, but right now I’m reaching towards a dead end. I can’t find any way to improve training and validation, I’m sorta lost now.\n\nTo summarize my model, data, and anything else I can think off, my model is a normal U-Net that uses TanH and Group Normalization for each encoder and decoder block. My data comes from the COCO Dataset, which I add some padding, around 100-200 pixels of padding to either height or width depending on the image shape, to have it around 636 x 636, I then normalize the input values values to fit in between \\[-1,1\\] and then de-normalize it back to \\[0,1\\] for BCELoss() function. Additionally, I have about 1613 images to train or validate, and thinking about this now as I am typing this, could it be the lack of data I have? Not sure what the problem is but any insight or tips can help out!","reference_answer":"Hi Brandon!\n\nI would not denormalize. I would also suggest that you use `BCEWithLogitsLoss`, rather than\n`BCELoss`, as your loss criterion. (It's numerically more stable.)\n\nWhat are your target values? For `BCEWithLogitsLoss` (as well as `BCELoss`) you would\ntypically want them to be `0.0` or `1.0`.\n\nThis seems smallish, but it could be (or might not be) enough. In any event, you should be\nable to overfit in that you get a low loss value (and a good figure of merit) on your training\nset, even if your validation-set results start to get worse as you keep training.\n\nAm I right that by \"capture people\" you mean that you want to label pixels that are part of\na person in the original image as \"foreground\" (e.g., 1) and pixels that are not part of a\nperson as \"background\" (e.g, 0)?\n\nIf you have many more background pixels than foreground pixels (or vice versa), you should\nprobably make use of `BCEWithLogitsLoss`'s `pos_weight` constructor argument.\n\nThere are some nuances to U-Net, but try without the denormalization and try overfitting\nbefore getting into the weeds.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":224073,"url":"https://discuss.pytorch.org/t/training-and-validation-loss-not-improving/224073","created_at":"2025-12-02T01:01:48.114000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"[Profiler] Will the CPU version of PyTorch includes Kineto or not?\n\nHi, guys. As the title stated, I wonder if the CPU-only build of PyTorch would carry Kineto or not? I know that the `USE_KINETO` is an optional variable while building from source code, but don’t know that if Kineto is the default setting for PyTorch. Also, base on that question, if the answer is yes, is that mean the Kineto headers and `.so`s are included in the PyTorch wheel?\n\nThanks.","reference_answer":"Just listed related headers in wheels:\n\n```\n.direnv/python-3.12/lib/python3.12/site-packages/torch$ find -name '*kineto*'\n./include/kineto\n./include/kineto/libkineto.h\n./include/torch/csrc/autograd/profiler_kineto.h\n./include/torch/csrc/profiler/kineto_shim.h\n./include/torch/csrc/profiler/kineto_client_interface.h\n```\n\nAnd seems symbols are included in `libtorch_cpu.so`","needs_clarification":false,"thread_id":224096,"url":"https://discuss.pytorch.org/t/profiler-will-the-cpu-version-of-pytorch-includes-kineto-or-not/224096","created_at":"2025-12-04T08:22:49.218000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["take-cheeze"],"answered_by_ptrblck":false} {"question":"Should the bias in a Linear layer be considered when estimating FLOP?\n\nI am a bit confused on how the calculation of floating point operations within a neural network is done. This is somewhat a “well-established” topic, however I need some clarifications on the *proper/precise* way -- if we can say so -- for determining the FLOP^[Here we should also make the distinction between FLOP**s**, which denotes the plural of FLOP and FLOP**S**, which signifies the total operations per second] of a Linear layer with and without the **bias** term. I have seen [a similar post](https://discuss.pytorch.org/t/calculating-ops-in-a-linear-layer/77958) from quite some time, however it has no clear answer.\n\nLet’s first establish the fundamentals: \n- when passing some input `A` through a [`nn.Linear`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Linear.html) layer, we are basically performing GEMMs. If one assumes the notations from [NVIDIA guidelines](https://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html#fullyconnected-layer), the input matrix `A` can have a shape `(N, K)` (assuming here that `N` will play the role of the batch size and `K` is the feature dimension.\n- Furthermore, the linear layer will be described by its weight `W` of shape `(M, K)` where `M` defines the output feature dimension. \n- When the bias term is included in the linear layer, its shape will just match the output dimension `M`. \n\nIgnoring bias term for now, the product `AW^T` between the weight matrix `W` and the input matrix `A`will be considered as `M x N x K` [**fused-multiply adds** (or FMA for short)](https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#math-mem). Finally, one single FMA consists of one multiplication and one addition, which result in a total of **two FLOPs per single FMA**^[https://alessiodevoto.github.io/Efficiency-metrics-in-Machine-Learning/#macs-and-flops].\n\nThus, for a single linear layer with no bias, there are `2 x M x N x K` FLOPs. However, **if there is a bias term**, then *how should one correctly estimate the total FLOPs?* \nMy intuition tells me that we should simply consider **one extra addition operation**, since after `AW^T`, one needs to perform `AW^T + b`.\n\nI have been trying to test this using PyTorch built-in profiling with a toy model (I have denoted the \"Multiply-Add Accumulate\" with MAC throughout the logs).\n\n[details=\"Code\"]\n```python\n\nclass Model(nn.Module):\n def __init__(self, in_dim: int, out_dim: int, use_bias: bool):\n super(Model, self).__init__()\n self.linear = nn.Linear(in_dim, out_dim, bias=use_bias)\n\n def forward(self, x: torch.Tensor):\n x = self.linear(x)\n return x\n\ndef test_mac(use_bias: bool):\n print(f'Testing MAC for a Linear layer with bias={use_bias}')\n device = \"cpu\"\n\n N, K = 5, 10 # input shape: usually batch size and feature size\n M = 1 # output size\n A = torch.randn(N, K).to(device)\n model = Model(K, M, use_bias).to(device)\n\n print(f'A: (N , K) -> {A.shape}')\n print(f'W: (M, K) -> {model.linear.weight.shape}')\n if use_bias:\n print(f'b: (M,) -> {model.linear.bias.shape}')\n\n with profile(activities=[ProfilerActivity.CPU], record_shapes=True) as prof:\n with record_function(\"model_inference\"):\n model(A)\n\n print(prof.key_averages(group_by_input_shape=True).table(\n sort_by=\"cpu_time_total\", row_limit=100))\n```\n[/details]\n\nFirst, without bias, we can see the breakdown:\n```\nTesting MAC for a Linear layer with bias=False\nA: (N , K) -> torch.Size([5, 10])\nW: (M, K) -> torch.Size([1, 10])\n---------------------- ------------ ------------ ------------ ------------ ------------ ------------ -------------------------- \n Name Self CPU % Self CPU CPU total % CPU total CPU time avg # of Calls Input Shapes \n---------------------- ------------ ------------ ------------ ------------ ------------ ------------ -------------------------- \n model_inference 42.15% 72.438us 100.00% 171.841us 171.841us 1 [] \n aten::linear 6.36% 10.921us 57.85% 99.403us 99.403us 1 [[5, 10], [1, 10], []] \n aten::matmul 2.43% 4.168us 29.81% 51.222us 51.222us 1 [[5, 10], [10, 1]] \n aten::mm 26.53% 45.594us 27.38% 47.054us 47.054us 1 [[5, 10], [10, 1]] \n aten::t 13.07% 22.465us 21.68% 37.260us 37.260us 1 [[1, 10]] \n aten::transpose 5.36% 9.211us 8.61% 14.795us 14.795us 1 [[1, 10], [], []] \n aten::as_strided 3.25% 5.584us 3.25% 5.584us 5.584us 1 [[1, 10], [], [], []] \n aten::resolve_conj 0.75% 1.293us 0.75% 1.293us 1.293us 1 [[5, 1]] \n aten::resolve_conj 0.10% 0.167us 0.10% 0.167us 0.167us 1 [[10, 1]] \n---------------------- ------------ ------------ ------------ ------------ ------------ ------------ -------------------------- \n```\nwhich will ultimately perform the \"non broadcast-able\" version of matrix multiplication [`torch.mm`](https://docs.pytorch.org/docs/stable/generated/torch.mm.html). On the other hand, **when we include the bias**, the operation is now different:\n```\nTesting MAC for a Linear layer with bias=True\nA: (N , K) -> torch.Size([5, 10])\nW: (M, K) -> torch.Size([1, 10])\nb: (M,) -> torch.Size([1])\n---------------------- ------------ ------------ ------------ ------------ ------------ ------------ ----------------------------------- \n Name Self CPU % Self CPU CPU total % CPU total CPU time avg # of Calls Input Shapes \n---------------------- ------------ ------------ ------------ ------------ ------------ ------------ ----------------------------------- \n model_inference 35.30% 74.750us 100.00% 211.750us 211.750us 1 [] \n aten::linear 5.53% 11.708us 64.70% 137.000us 137.000us 1 [[5, 10], [1, 10], [1]] \n aten::addmm 31.39% 66.458us 40.00% 84.708us 84.708us 1 [[1], [5, 10], [10, 1], [], []] \n aten::t 9.54% 20.209us 19.17% 40.584us 40.584us 1 [[1, 10]] \n aten::transpose 7.04% 14.917us 9.62% 20.375us 20.375us 1 [[1, 10], [], []] \n aten::copy_ 6.93% 14.667us 6.93% 14.667us 14.667us 1 [[5, 1], [5, 1], []] \n aten::as_strided 2.58% 5.458us 2.58% 5.458us 5.458us 1 [[1, 10], [], [], []] \n aten::expand 0.75% 1.583us 1.12% 2.375us 2.375us 1 [[1], [], []] \n aten::resolve_conj 0.51% 1.083us 0.51% 1.083us 1.083us 1 [[5, 1]] \n aten::as_strided 0.37% 0.792us 0.37% 0.792us 0.792us 1 [[1], [], [], []] \n aten::resolve_conj 0.06% 0.125us 0.06% 0.125us 0.125us 1 [[10, 1]] \n---------------------- ------------ ------------ ------------ ------------ ------------ ------------ ----------------------------------- \n```\nIndeed, instead of `torch.mm`, the [`torch.addmm`](https://docs.pytorch.org/docs/stable/generated/torch.addmm.html#torch.addmm) operation is performed.\n\nIt is unclear for me if `addmm` has still the same `2 x M x N x K` number of FLOPs or not. Should it be ~~`2 x (M +1) x N x K`~~ -> `2 x (M x N x K + M x N)` ?\n\nThanks in advance!","reference_answer":"The bias is just + M x N. \n\nThere is only one operation, addition. And the bias is a vector of size M.","needs_clarification":false,"thread_id":224158,"url":"https://discuss.pytorch.org/t/should-the-bias-in-a-linear-layer-be-considered-when-estimating-flop/224158","created_at":"2025-12-10T15:30:48.648000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["J_Johnson"],"answered_by_ptrblck":false} {"question":"Intel A770 GPU + Debian13 -- XPU available: False\n\nhello, I’m struggling at correctly installing PyTorch and xpu. here is my config\n\n```\n$uname -ar\nLinux thor 6.12.57+deb13-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.12.57-1 (2025-11-05) x86_64 GNU/Linux\n```\n\n```\n$ python --version\nPython 3.14.0\n```\n\n```\n$ which python\n/home/fred/.pyenv/shims/python\n```\n\nthen I install PyTorch with\n\n```\n$pip install torch==2.9.1+xpu torchvision==0.23.1+xpu torchaudio==2.9.1+xpu intel-cmplr-lib-rt intel-cmplr-lib-ur intel-cmplr-lic-rt intel-sycl-rt pytorch-triton-xpu tcmlib umf intel-pti --index-url https://download.pytorch.org/whl/xpu\n```\n\nas (very well) explained [here](https://discuss.pytorch.org/t/solved-pytorch-2-7-1-xpu-intel-arc-graphics-complete-setup-guide-linux/220821/7)\n\nthen I checked\n\n```\n>>> import torch\n>>> print(f\"XPU available: {torch.xpu.is_available()}\")\n/media/SSD02/venv/lib/python3.14/site-packages/torch/xpu/__init__.py:61: UserWarning: XPU device count is zero! (Triggered internally at /pytorch/c10/xpu/XPUFunctions.cpp:115.)\n return torch._C._xpu_getDeviceCount()\nXPU available: False\n>>> print(f\"PyTorch version: {torch.__version__}\")\nPyTorch version: 2.9.1+xpu\n>>> print(f\"XPU compiled: {torch._C._xpu_getDeviceCount is not None}\")\nXPU compiled: True\n```\n\nWhat did I miss ? why it is not able to interact with xpu ?? thank you very much :slight_smile:\n\nEDIT : from a fresh and clean install of Debian 13 + Liquorix the problem is still the same… XPU available: False\n\n> $ uname -ar \n> Linux THOR 6.17.12-1-liquorix-amd64 #1 ZEN SMP PREEMPT_DYNAMIC liquorix 6.17-14.1\\~trixie (2025-12-12 x86_64 GNU/Linux\n\nand \n\n> $ pip install torch==2.9.1+xpu torchvision==0.24.1+xpu torchaudio==2.9.1+xpu intel-cmplr-lib-rt intel-cmplr-lib-ur intel-cmplr-lic-rt intel-sycl-rt pytorch-triton-xpu tcmlib umf intel-pti --index-url https://download.pytorch.org/whl/xpu\n\n\\-\\_-,","reference_answer":"Install the Intel Compute Runtime first. On a clean Debian 13 install its components are missing, and nothing warns you about it. Download all the `*.deb` files from the 25.44.36015.8 release at https://github.com/intel/compute-runtime/releases/tag/25.44.36015.8 and install them. Add your user to the `render` group. Then install the xpu build of PyTorch. Once `clinfo` lists the Arc GPU, `torch.xpu.is_available()` returns True.","needs_clarification":false,"thread_id":224215,"url":"https://discuss.pytorch.org/t/intel-a770-gpu-debian13-xpu-available-false/224215","created_at":"2025-12-17T20:52:12.808000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[5],"answer_authors":["FredZeFenec"],"answered_by_ptrblck":false} {"question":"An \"adaptable\" image dataset loader?\n\nHello to the PyTorch community!\n\n# Context\n\nI'm building a tool for training vision models, the main focus of the tool is to make everything \"just works\". An easy to use CLI binary you can use to inference and train models, without needing to tweak many different model/training parameters.\n\n# Problem\n\nAnd a problem I'm having is that I can't seem to find a good way to load datasets. The default loader is great but it doesn't \"adapt\" well to different model sizes and system specs, like the training device will go OOM depending on the model size and system specs.\n\n> Or maybe there's a formula to calculate the optimal parameters for the loader but I can't figure it out.\n\nAnother thing is that when loading the dataset, some extra processing of the tensors (resizing, masking) is required before they can be used in training. I think caching the tensors after they are processed will be a good idea, so I tried implementing my own dataset loader.\n\n# Attempt\n\nThe dataset loader I came up with have two caching method: memory, chunked with disk. If the device memory have enough space, it'll load all the processed tensor into the device memory. Otherwise it'll split them into chunks (the chunk size is also calculated with the available memory on the device) and save them onto the disk, and loading them chunk by chunk when training.\n\nBut for some reason the chunked with disk caching method will cause OOM when loading a chunk, even though the memory have enough space for the chunk (based on the size of the `.pth` chunk file). From my research `.pth` do some compression stuff when saving, but the chunk capacity is calculated using the `width`, `height`, `channels` and `dtype` of the tensors (along with the available memory on the device) so there shouldn't be a calculation error there.\n\n# Conclusion\n\nSo I guess my questions are:\n\n1. Can the default dataset loader achieve the level of adaptability that so model training can use as much resources as the system provides but not crashes itself.\n2. Is this even an reasonable approach? (I'm aware that letting the model/training parameter be automatically configured might not lead to the best model accuracy)","reference_answer":"Sounds like you just want something to dynamically set the batch size. \n\nIt's possible but just a bit challenging. \n\n1. You’ll want to make a key:query for all of the possible optimizers and the multiple of parameters in overhead each needs, along with possible variants. For example, RMSProp without momentum or centered is something like 1x overhead while RMSProp with momentum and centered is 3x overhead.\n2. You’ll need to determine the dtype. \n3. You’ll need to iterate over each conv2d layer and calculate the following as a baseline footprint: dtype × \\[(o × c × z × z + o) + (b × c × x × y) + (b × o × x_out × y_out) + (b × c × z × z × x_out × y_out)\\] where o is out_channels, z is kernel size on one dim, c is in_channels, x is local input size on the x dim, y is local input size on the y dim, b for batch size, x_out is layer output size on the x dim, and y_out is the layer output size on the y dim. Dtype is how many bits are needed per number. I.e. float32 is 4. That doesn't account for stride, padding, dilation, etc.\n4. Of course, you're looking to optimize for b(batch size), so you’ll need to perform some algebra to solve for it, and then find the max of b to where the memory footprint still fits in the max memory. \n\nBecause it's quite a convoluted calculation, most people just find the max batch size through trail and error, while also considering not to make it exceed 256, or you run into other problems with effective learning. See “On Large-Batch Training for Deep Learning: Generalization Gap and Sharp Minima\" by Nitish Shirish Keskar, Dheevatsa Mudigere, Jorge Nocedal, Mikhail Smelyanskiy, and Ping Tak Peter Tang (2016).","needs_clarification":false,"thread_id":224261,"url":"https://discuss.pytorch.org/t/an-adaptable-image-dataset-loader/224261","created_at":"2025-12-30T15:06:20.168000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["J_Johnson"],"answered_by_ptrblck":false} {"question":"Different numerical results between 4D batched matmul and equivalent 3D reshaped matmul\n\nHello,\n\nI noticed that two mathematically equivalent matrix multiplication operations produce different numerical results, with torch.allclose() failing even with relatively loose tolerances. I’d like to understand why this happens and whether this is expected behavior.\n\n```\nimport torch\n\n# Setup\nn_ens = 5\nbatch_size = 256\nens_k = 32\nd_in = 84\nd_out = 512\n\ntorch.manual_seed(42) \nx = torch.randn(n_ens, batch_size, ens_k, d_in)\nw = torch.randn(n_ens, 1, d_in, d_out)\n\n# Method 1: 4D batched matmul with broadcasting\n# Shape: (5, 256, 32, 84) @ (5, 1, 84, 512) -> (5, 256, 32, 512)\nresult_4d = x @ w\n\n# Method 2: Reshape to 3D, matmul, reshape back\nx_3d = x.reshape(n_ens, batch_size * ens_k, d_in) # (5, 8192, 84)\nw_3d = w.squeeze(1) # (5, 84, 512)\nresult_3d = (x_3d @ w_3d).reshape(n_ens, batch_size, ens_k, d_out)\n\n# Method 3: einsum\nresult_einsum = torch.einsum(\n 'nbki,nio->nbko', \n x, \n w.squeeze(1)\n)\nprint(f\"Shapes match: {result_4d.shape == result_3d.shape}\")\nprint(f\"4d vs 3d: torch.equal: {torch.equal(result_4d, result_3d)}\")\nprint(f\"4d vs 3d: torch.allclose (default): {torch.allclose(result_4d, result_3d)}\")\nprint(f\"4d vs 3d: torch.allclose (atol=1e-6): {torch.allclose(result_4d, result_3d, atol=1e-6)}\")\nprint(f\"einsum vs 3d: torch.allclose (default): {torch.allclose(result_einsum, result_3d)}\")\nprint(f\"einsum vs 3d: torch.allclose (atol=1e-6): {torch.allclose(result_einsum, result_3d, atol=1e-6)}\")\n```\n\nI got result_einsum = result_3d, however result_4d != result_3d.\n\nThank you in advance!","reference_answer":"Hi Duong!\n\nThis is due to expected numerical round-off error.\n\nYour various methods end up performing the operations that make up the `matmul()`s in\ndifferent, but mathematically equivalent orders. These different orders lead to slightly\ndifferent results due to floating-point round-off errors. Note that in the context of the larger\n`matmul()` computation, individual round-off errors can accumulate. So while `atol = 1e-6`\nis larger than typical single-precision round-off error, it's not larger than what one might\nexpect for the accumulated round-off error in the overall `matmul()` computation.\n\nTry looking at both the element-wise means and maxima of the differences of your various\nresults. You should see them shrink by maybe seven orders of magnitude if you repeat the\ncomputations in double precision.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":224317,"url":"https://discuss.pytorch.org/t/different-numerical-results-between-4d-batched-matmul-and-equivalent-3d-reshaped-matmul/224317","created_at":"2026-01-10T15:32:37.339000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Parallelizing matrix-matrix-matrix products\n\nI want to compute XW_kY for a list of W_k, k=1,…,K, where K is around 10 or so (but is a parameter). How might I parallelize this? My best guess is to change them all into block_diags, but I imagine there is a more efficient way to do this.","reference_answer":"I think you can use [torch.einsum](https://docs.pytorch.org/docs/stable/generated/torch.einsum.html) for that:\n```python\nimport torch\n\nk = 10\na=2\nb=3\nc=4\nd=5\n\nX = torch.randn(a, b)\nWs = [torch.randn(b, c) for _ in range(k)]\nW = torch.stack(Ws, dim=0) # shape: [k, b, c]\nY = torch.randn(c, d)\n\nresult = torch.einsum(\"ab,kbc,cd->kad\", X, W, Y) # shape: [k, a, d]\n```\n\nNote that since this is an einsum involving more than just 2 tensors, you could maybe have improved performances if you just install `opt-einsum` (nothing else to do, `torch.einsum` will detect that it's installed and use it to optimize the order of operations). `pip install opt-einsum` should be enough for that.","needs_clarification":false,"thread_id":224388,"url":"https://discuss.pytorch.org/t/parallelizing-matrix-matrix-matrix-products/224388","created_at":"2026-01-20T20:35:41.013000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["valerian.rey"],"answered_by_ptrblck":false} {"question":"How should use_amp be set when using torch.cuda.amp?\n\nWhen using:\n\n```python\nscaler = torch.cuda.amp.GradScaler(enabled=use_amp)\nwith torch.cuda.amp.autocast(enabled=use_amp):\n ...\n\n```\n\nhow should `use_amp` be determined?\nShould it explicitly reflect whether the GPU supports AMP, or is `torch.cuda.is_available()` sufficient?\n\nAlso, when using **DDP**, what is the recommended way to handle AMP in case different GPUs in the cluster have different AMP support?\nIs heterogeneous AMP across ranks supported, or should AMP be enabled/disabled globally?","reference_answer":"Unless you are using an older Pascal GPU (or even previous generations) all NVIDIA GPUs will support AMP via `float16`. Ampere and newer will also support AMP in `bfloat16`. \n\nI would globally enable or disable it in multi-GPU setups.","needs_clarification":false,"thread_id":224429,"url":"https://discuss.pytorch.org/t/how-should-use-amp-be-set-when-using-torch-cuda-amp/224429","created_at":"2026-01-29T08:04:31.954000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Can 'torch.profiler' support GB20X NVIDIA GPU architectures?\n\nFor more details, please see the open issue [#174195](https://github.com/pytorch/pytorch/issues/174195).\n\nI use torch.profiler like this:\n\n> prof = torch.profiler.profile(\n> activities=\\[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA\\],\n> schedule=torch.profiler.schedule(wait=3, warmup=3, active=3, repeat=1),\n> on_trace_ready=torch.profiler.tensorboard_trace_handler(f’./xxx’),\n> record_shapes=True,\n> with_stack=True,\n> acc_events=True,)\n\nBut I got an error:\n\n> WARNING:2026-02-03 20:37:18 334947:334947 init.cpp:115\\] function cbapi->getCuptiStatus() failed with error CUPTI_ERROR_INVALID_DEVICE (2)\n> WARNING:2026-02-03 20:37:18 334947:334947 init.cpp:116\\] CUPTI initialization failed - CUDA profiler activities will be missing\n> INFO:2026-02-03 20:37:18 334947:334947 init.cpp:118\\] If you see CUPTI_ERROR_INSUFFICIENT_PRIVILEGES, refer to https://developer.nvidia.com/nvidia-development-tools-solutions-err-nvgpuctrperm-cupti\n\nMy env:\n\n> PyTorch version: 2.10.0+cu128\n> Is debug build: False\n> CUDA used to build PyTorch: 12.8\n> ROCM used to build PyTorch: N/A\n>\n> OS: Ubuntu 24.04.3 LTS (x86_64)\n> GCC version: (Ubuntu 13.3.0-6ubuntu2\\~24.04) 13.3.0\n> Clang version: Could not collect\n> CMake version: version 3.28.3\n> Libc version: glibc-2.39\n>\n> Python version: 3.12.3 (main, Jan 8 2026, 11:30:50) \\[GCC 13.3.0\\] (64-bit runtime)\n> Python platform: Linux-6.14.0-37-generic-x86_64-with-glibc2.39\n> Is CUDA available: True\n> CUDA runtime version: 12.8.93\n> CUDA_MODULE_LOADING set to:\n> GPU models and configuration: GPU 0: NVIDIA GeForce RTX 5060 Laptop GPU\n> Nvidia driver version: 590.48.01\n> cuDNN version: Could not collect\n> Is XPU available: False\n> HIP runtime version: N/A\n> MIOpen runtime version: N/A\n> Is XNNPACK available: True\n> Caching allocator config: N/A","reference_answer":"Use CUDA 13, and new driver can solve this.","needs_clarification":false,"thread_id":224487,"url":"https://discuss.pytorch.org/t/can-torch-profiler-support-gb20x-nvidia-gpu-architectures/224487","created_at":"2026-02-05T15:39:41.957000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["arminzhu"],"answered_by_ptrblck":false} {"question":"RNN memory management: RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation\n\nThis is a very basic question, sorry. For memory management reasons I’d like to write simple RNN code like:\n\n```\n s = torch.empty_like(x) \n s[0] = x[0]\n for t in range(1, x.shape[0]):\n s[t] = decay * s[t-1] + x[t]\n```\n\nNow I understand why I can’t do that, s is one tensor and autograd needs to see a sequence to backprop from the end to the start. So I’ve always done what autograd needs (and is recommended at https://discuss.pytorch.org/t/runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation-torch-cuda-floattensor-32-768-which-is-output-0-of-tanhbackward-is-at-version-2-expected-version-0-instead-hint-enable-anomaly-detectio/137325 ):\n\n```\n s = [x[0]]\n for t in range(1, x.shape[0]):\n s.append(decay * s[t-1] + x[t])\n s = torch.stack(s)\n```\n\nI’m now considering learning the triton language in order to speed up the above code. However, that seems a bit pointless if I’m going to call read all the blocks and write them as one object at the end, the whole point of a triton kernel is would be to take in a single tensor and output a single tensor with minimal memory bandwidth.\n\nI can of course use torch.clone() to get the one tensor in, one tensor out functionality that I want, but this runs massively slower, and so doesn’t seem like the right direction:\n\n```\ns = torch.empty_like(x)\ns[0] = x[0]\nfor t in range(1, x.shape[0]):\n s[t] = decay * s[t-1].clone() + x[t]\n```\n\nAll I’m really after is some magic syntax that tells autograd that my output is one tensor but please treat it like a list of independent tensors that just happen to be adjacent in memory and we aren’t really going to have any graph clashes, honest.","reference_answer":"Keep the running value in a separate tensor and write it into the output at each step:\n\n```\ns = torch.empty_like(x)\nacc = x[0]\nfor t in range(x.shape[0]):\n s[t] = acc\n acc = decay * acc + x[t]\n```\n\nTry `torch.compile` on this loop first. In one test the loop took 2006 ms in eager mode and 331 ms compiled.","needs_clarification":false,"thread_id":224496,"url":"https://discuss.pytorch.org/t/rnn-memory-management-runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation/224496","created_at":"2026-02-06T11:52:03.726000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3],"answer_authors":["SchulzKilian","tonyr"],"answered_by_ptrblck":false} {"question":"Looking for matmul.h\n\nHi,\n\nThere is an include line\n\n#include \n\nin https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/Linear.cpp but when I navigate to ATen/ops, I don’t see such file. See this [path](https://github.com/pytorch/pytorch/tree/main/aten/src/ATen/ops) where there are two files only: from_blob.h and tensor.h.\n\nWhere can I find that header file?","reference_answer":"This file would be generated according to [this description](https://github.com/pytorch/pytorch/blob/46746185c803a05ff6dc310236896f888e62832e/aten/src/ATen/templates/Functions.h#L13-L57).","needs_clarification":false,"thread_id":224521,"url":"https://discuss.pytorch.org/t/looking-for-matmul-h/224521","created_at":"2026-02-10T12:57:55.261000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"CTCDecoder returns result.tokens longer than input emissions - why +2 extra tokens?\n\n## Problem Description\n\nI’m using `torchaudio.models.decoder.CTCDecoder` (CPU version with flashlight backend) and noticed that the decoder returns `result.tokens` that is consistently **2 elements longer** than the input `emissions` sequence length.\n\nThis causes issues when using `beam_result.timesteps` as indices into the original logits, because some timestep values exceed the valid range.\n\n## Code Example\n\n```python\nfrom torchaudio.models.decoder import CTCDecoder\n\n# Create decoder\ndecoder = CTCDecoder(\n lexicon=None,\n tokens=vocab_list,\n blank_token=\"\",\n beam_size=5,\n)\n\n# Input emissions with shape (batch=1, time=128, num_tokens=153)\nemissions = torch.randn(1, 128, 153, dtype=torch.float32)\n\n# Decode\nresults = decoder(emissions)\nbeam_result = results[0][0]\n\nprint(f\"emissions.size(1) = {emissions.size(1)}\") # 128\nprint(f\"len(result.tokens) = {len(beam_result.tokens)}\") # 130 (!!)\nprint(f\"beam_result.timesteps = {beam_result.timesteps}\") # Contains [128, 129]\n```\n\n## Observed Behavior\n\n**Input:**\n\n* `emissions.shape = (1, 128, 153)` — 128 time steps\n\n**Output:**\n\n* `len(result.tokens) = 130` — 130 tokens (2 extra!)\n* `beam_result.timesteps` contains values `[..., 128, 129]`\n\n## The Issue\n\nLooking at the source code in [`_get_timesteps`](https://github.com/pytorch/audio/blob/96200d42e795098ee5e3f0106bcf9c370cf126a1/src/torchaudio/models/decoder/_ctc_decoder.py#L259-L268):\n\n```python\ndef _get_timesteps(self, idxs: torch.IntTensor) -> torch.IntTensor:\n \"\"\"Returns frame numbers corresponding to non-blank tokens.\"\"\"\n timesteps = []\n for i, idx in enumerate(idxs):\n if idx == self.blank:\n continue\n if i == 0 or idx != idxs[i - 1]:\n timesteps.append(i) # ← Returns position in result.tokens array\n return torch.IntTensor(timesteps)\n```\n\nThe method returns **indices within `result.tokens`** (which has length 130), not frame numbers in the original emissions (which has length 128).\n\nWhen `beam_result.timesteps` contains values like `[128, 129]`, these are **out of bounds** for indexing into `emissions[:, 0:128, :]`.\n\n## Questions\n\n1. **Why does `result.tokens` have length 130 when emissions has only 128 frames?** Where do the 2 extra tokens come from?\n\n2. Is this expected behavior from the flashlight decoder backend?\n\n3. How should I correctly map `beam_result.timesteps` to actual frame indices in the original emissions tensor?\n\n## Additional Context\n\n* This happens consistently: `len(result.tokens) = emissions.size(1) + 2`\n* For larger inputs (e.g., 257 frames), I get 259 tokens\n* Related source code:\n * [`__call__` method](https://github.com/pytorch/audio/blob/96200d42e795098ee5e3f0106bcf9c370cf126a1/src/torchaudio/models/decoder/_ctc_decoder.py#L359-L407) where `decoder.decode()` is called\n * [`_to_hypo` method](https://github.com/pytorch/audio/blob/96200d42e795098ee5e3f0106bcf9c370cf126a1/src/torchaudio/models/decoder/_ctc_decoder.py#L332-L341) that processes results\n\n## Environment\n\n* `torchaudio`: 2.0.0+\n* `torch`: 2.0.0+\n* Platform: CPU (flashlight backend)","reference_answer":"The two extra tokens are the start and end tokens from the flashlight decoder, the `sil` token. The start token is at position 0, and the end token is at position 129.","needs_clarification":false,"thread_id":224550,"url":"https://discuss.pytorch.org/t/ctcdecoder-returns-result-tokens-longer-than-input-emissions-why-2-extra-tokens/224550","created_at":"2026-02-14T17:34:42.732000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,5,6],"answer_authors":["mantissa","ph3rro"],"answered_by_ptrblck":false} {"question":"Transforms are being applied to masks for some reason\n\nI am doing RandomHorizontalFlip and RandomVerticalFlip, though they are being applied to the image and mask separately.\n\n```python\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.utils.data import Dataset, DataLoader\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom PIL import Image\nfrom torchvision import tv_tensors\nfrom torchvision.transforms.v2 import Compose, RandomVerticalFlip, RandomHorizontalFlip,ToDtype\n\nmasks = np.load(‘path/to/masks’)\ntrain_images = Path(‘traindirectory’)\ntrain_imgs = [x for x in train_images.iterdir() if x.is_file()]\ntrain_imgs = sorted(train_imgs)\ntrain_imgs = [Image.open(x) for x in train_imgs]\n\nfor i in range(len(train_imgs)):\n image = train_imgs[i]\n image = image.transform(\n image.size,\n Image.AFFINE,\n (1, 0, -30, 0, 1, -30),\n fillcolor=(0, 0, 0)\n )\n train_imgs[i] = image\n\ntest_images = Path(‘testdirectory’)\ntest_imgs = [x for x in test_images.iterdir() if x.is_file()]\ntest_imgs = sorted(test_imgs)\ntest_imgs = [Image.open(x) for x in test_imgs]\n\nclass SegmentationDataset(Dataset):\n def init(self, subset, images, transforms, masks=None):\n super().init()\n self.images = images\n self.masks = masks\n self.subset = subset\n self.transforms = transforms\n\n def __len__(self):\n return len(self.images)\n\n def __getitem__(self, idx):\n if self.subset == 'test':\n image = self.images[idx]\n return image\n else:\n image = tv_tensors.Image(self.images[idx])\n mask = tv_tensors.Mask(torch.Tensor(self.masks[idx]))\n out = self.transforms({ 'mask':mask, 'image': image})\n return out\n\ntrain_er = SegmentationDataset(‘train’, train_imgs, Compose([RandomVerticalFlip(), RandomHorizontalFlip() , ToDtype(torch.float32, scale=True)]), masks =masks )\n\nimg = train_er[0][‘image’].permute(1, 2, 0).numpy()\nmsk = train_er[0][‘mask’]\nplt.imshow(img)\nplt.imshow(msk, alpha=0.5, cmap=‘plasma’)\n```\n\nthis is the output I get:\n\n[image]","reference_answer":"Could the problem be the you sample twice from the dataset, meaning that the randomness is different between the two calls to `train_er[0]`? I think you could try:\n```python\nsample = train_er[0]\nimage = sample[‘image’].permute(1, 2, 0).numpy()\nmsk = sample[‘mask’]\n```\nto have the same randomness for both image and msk.","needs_clarification":false,"thread_id":224568,"url":"https://discuss.pytorch.org/t/transforms-are-being-applied-to-masks-for-some-reason/224568","created_at":"2026-02-18T14:11:16.199000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["valerian.rey"],"answered_by_ptrblck":false} {"question":"[Solved] RTX 5090 (sm_120) Training Segfault - DDP Was the Cause\n\nHi everyone,\n\nI spent a few weeks debugging training crashes on my RTX 5090 and finally figured it out — sharing in case it helps anyone with the same GPU.\n\n## Setup\n\n```\nGPU: RTX 5090 Laptop (GB203, sm_120, 24GB VRAM)\nOS: Windows 11\nFramework: Style-Bert-VITS2 (VITS-based TTS model, DDP enabled by default)\n```\n\n## Symptom\n\nInference worked perfectly, but training would segfault (`0xC0000005` / ACCESS_VIOLATION) within seconds — no Python traceback, just a silent OS-level kill. I narrowed it down using checkpoint logging (`print(flush=True)` + file logging, since segfault kills stdout buffers):\n\n```\nCP7j: about to loss_slm.backward() ✅\nCP7k: backward DONE ❌ (never reached)\n```\n\nThe crash happened during `backward()` — specifically in gradient synchronization. Forward pass for all models (Generator, Discriminator, WavLM) completed fine every time.\n\nI tried everything I could think of: disabling GradScaler, pure fp32 mode, `CUDA_LAUNCH_BLOCKING=1`, disabling WavLM loss — nothing helped. Even with WavLM disabled, the regular Discriminator backward also segfaulted at the same stage.\n\n## What I Tried — Two Paths\n\n### Path 1: PyTorch stable (2.4.1+cu121)\n\nsm_120 native kernels don't exist in stable, so PyTorch falls back to PTX JIT compilation. This actually works for basic operations — you get a `UserWarning` but execution continues:\n\n```\nUserWarning: NVIDIA GeForce RTX 5090 Laptop GPU with CUDA capability sm_120\nis not compatible with the current PyTorch installation.\nThe current PyTorch install supports CUDA capabilities sm_50 sm_60 ... sm_90.\n```\n\nHowever, DDP's `broadcast_coalesced` immediately fails:\n\n```\nRuntimeError: CUDA error: no kernel image is available for execution on the device\n```\n\nAfter patching DDP out (conditional skip when `world_size == 1`), I hit a cascade of `no kernel image` errors on progressively basic operations:\n\n```\n1. torch.nn.functional.embedding (emb_g) → \"no kernel image\" ❌\n2. torch.nn.functional.conv1d (bert_proj) → \"no kernel image\" ❌\n```\n\nEach one could be individually patched with CPU fallback, but the cascade kept going — PTX JIT fallback doesn't cover enough ops for stable training. I gave up on this path.\n\n### Path 2: PyTorch nightly (2.12.0.dev+cu128)\n\nNightly has sm_120 native kernels, so forward pass works without any warnings or fallbacks. But training segfaults during backward — and here's where it gets interesting.\n\n**First attempt** — just setting `CUDA_VISIBLE_DEVICES=0` (no code changes):\n```\nset CUDA_VISIBLE_DEVICES=0\npython train_ms_jp_extra.py ...\n→ Same segfault. The training script still calls DDP(model) unconditionally.\n```\n\n**Second attempt** — patching the actual DDP wrapping out of the code:\n```\n→ Training runs stable ✅ (1000+ steps, no crash)\n```\n\nThe environment variable alone wasn't enough — the training script still wraps models with `DDP()` regardless of how many GPUs are visible. The fix required changing the source code to skip `DDP()` wrapping when `world_size == 1`.\n\n**Interesting finding**: On stable, the *absence* of native kernels triggers PTX JIT fallback, which at least gives you a warning and tries to continue. On nightly, native kernels *exist but the DDP/NCCL communication path is broken for sm_120* — and since native kernels exist, PyTorch uses them instead of falling back to PTX, leading to a harder crash (segfault with no Python traceback).\n\n## The Fix (2 patches to the training script)\n\n### Patch 1: Skip DDP wrapping on single GPU\n\n```python\n# Before (applied to ALL DDP-wrapped models):\nnet_g = DDP(net_g, device_ids=[rank])\nnet_d = DDP(net_d, device_ids=[rank])\nnet_dur_disc = DDP(net_dur_disc, device_ids=[rank])\nnet_wd = DDP(net_wd, device_ids=[rank])\n\n# After:\nif torch.distributed.get_world_size() > 1:\n net_g = DDP(net_g, device_ids=[rank])\n net_d = DDP(net_d, device_ids=[rank])\n net_dur_disc = DDP(net_dur_disc, device_ids=[rank])\n net_wd = DDP(net_wd, device_ids=[rank])\n```\n\n### Patch 2: Remove `.module` access\n\nWithout DDP wrapping, the model isn't wrapped in a `DistributedDataParallel` container, so `.module` doesn't exist. Every `.module` access needs to be changed to direct access:\n\n```python\n# Before:\nnet_g.module.use_noise_scaled_mas\nnet_g.module.mas_noise_scale_initial\nnet_g.module.noise_scale_delta\nnet_g.module.current_mas_noise_scale\ngenerator.module.infer(...)\n\n# After:\nnet_g.use_noise_scaled_mas\nnet_g.mas_noise_scale_initial\nnet_g.noise_scale_delta\nnet_g.current_mas_noise_scale\ngenerator.infer(...)\n```\n\n**Important**: You also need to set `CUDA_VISIBLE_DEVICES=0` when launching training, to ensure the distributed backend initializes with a single process.\n\nThat's it. Two patches + one environment variable.\n\n## Results\n\n```\nBatch size 8: 1.10–1.47 it/s\nVRAM: 18.5GB / 24GB\nStable over thousands of steps — verified across multiple epochs\nWavLM discriminator loss: works normally (was NOT the cause)\n```\n\nI initially suspected WavLM backward was the problem (it was the first backward to crash), but after removing DDP, WavLM backward runs fine. The segfault was always DDP's gradient synchronization, not any specific model component.\n\n## Why This Only Affects Certain Frameworks\n\nOther frameworks I tested on the same GPU worked fine from the start:\n\n| Framework | DDP | Result |\n|-----------|-----|--------|\n| GPT-SoVITS v2/v4/v2Pro+ | Not used | ✅ Training works |\n| Applio RVC | Not used | ✅ 200 epochs completed |\n| kohya_ss (SD training) | Accelerate auto-skips on single GPU | ✅ Training works |\n| Style-Bert-VITS2 | Enabled by default | ❌ Segfault |\n\nThe pattern is clear: frameworks that don't use DDP (or auto-skip it on single GPU) work fine on sm_120. DDP + sm_120 is the specific combination that crashes.\n\n## Environment\n\n```\nPyTorch: 2.12.0.dev (nightly) + cu128\nLaunch: set CUDA_VISIBLE_DEVICES=0\nPatches: DDP conditional skip + .module removal\n```\n\nHope this saves someone some debugging time. If anyone has more info on DDP behavior on Blackwell GPUs, I'd love to hear about it.","reference_answer":"If you wrap the model in DDP on a single GPU, skip the wrap when `world_size == 1`. Removing the unconditional `DDP()` call fixed the segfault in this case, since the DDP wrapper should be a no-op on one GPU.","needs_clarification":false,"thread_id":224584,"url":"https://discuss.pytorch.org/t/solved-rtx-5090-sm-120-training-segfault-ddp-was-the-cause/224584","created_at":"2026-02-23T12:44:58.959000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,4],"answer_authors":["k_k1","ptrblck"],"answered_by_ptrblck":true} {"question":"On Counting FLOPs/Energy for the Model\n\nHow to rigorously justify computational complexity for sparse/non-standard models? (Manual FLOPs vs. Hardware Energy)\n\nHi everyone,\n\nI'm currently working on a highly sparse, non-standard neural network architecture. Standard profilers’ (like `thop`, `fvcore`, `torch.profiler`) reports were all different (and mostly unhelpful), I guess because my model relies entirely on tensor indexing and element-wise operations (e.g., `+`, `*`, `tanh`, `exp`) rather than standard dense GEMMs or Convolutions.\n\nSince I cannot rely on off-the-shelf tools, I need to manually justify my model's computational cost for an upcoming paper submission. However, I am facing a dilemma on how to formalize this, and I am considering two approaches:\n\n**Approach A: Manual FLOPs Counting** I built a custom tracker to intercept every element-wise operation and accumulate FLOPs based on `tensor.numel()`.\n\n* **The issue with references:** In existing literature, there seems to be no clear consensus for non-standard models. Some papers simply report \"0 MACs\" and ignore element-wise ops (which feels like cheating since they are the actual bottleneck here), while others manually calculate Big-O complexity. Is there a \"gold standard\" reference or accepted methodology for reporting manual FLOPs in top-tier ML venues?\n\n* **Practical weight assignment dilemma:** When manually assigning FLOP costs to specific operations, things get highly subjective. For example, in my current draft, I practically assigned costs like:\n\n * `ADD` / `MUL` / `CMP` = 1 FLOP\n\n * `DIV` = 4 FLOPs\n\n * `TANH` / `EXP` = 8 FLOPs (assuming Look-Up Tables (LUT) or Piecewise Linear (PWL) hardware approximations).\n\n* **The transcendental function problem:** Is a cost of `8 FLOPs` for `tanh` widely accepted in the ML community? I worry that reviewers might attack this, arguing that a true FP32 `tanh` or `exp` requires Taylor series or CORDIC algorithms, costing dozens or hundreds of FLOPs. Should I count the exact mathematical operations of the Taylor series, or is the LUT/PWL assumption (e.g., 1\\~8 FLOPs) the norm for hardware-aware neural network papers?\n\n**Approach B: Hardware Energy Consumption Estimation (pJ)** Since treating an INT8 addition and an FP32 Tanh as roughly similar \"FLOPs\" is fundamentally misleading in terms of actual hardware cost, I am considering bypassing FLOPs entirely.\n\n* **The method:** I count the exact occurrences of each operation type and multiply them by their respective energy costs in pico-Joules (pJ).\n\n* **The references:** I plan to base this on established hardware specifications, such as the 45nm/7nm chip data from Horowitz (2014) or the EIE paper (Han et al., 2016). Is estimating total energy (pJ) using these classic references still considered a rigorous and highly preferred way to justify efficiency for non-standard architectures today?\n\n**My Questions for the Community:**\n\n1. For **Approach A**, what is the community consensus on practical FLOPs counting? Are my assumed costs (`DIV = 4`, `TANH = 8` via LUT) acceptable? Are there any good papers I can cite for this specific methodology and weight assignments?\n\n2. Between **Approach A (Total FLOPs)** and **Approach B (Total Energy in pJ)**, which metric provides a stronger, more bulletproof justification for a paper introducing a highly sparse, element-wise heavy architecture?\n\nAny insights, recommended references, or experiences with profiling such networks would be greatly appreciated!\n\nThanks in advance!","reference_answer":"1. The cost of higher-level operations like div and tanh highly depends on the hardware and the data type. For example, you can look at the instructions for Nvidia Hopper (SM 90) here : https://godbolt.org/z/h99TM4xss . DIV can be somewhat inexpensive (1 MUFU instruction, 6 floating-point instructions, 1 branching set), but there is a slow path for specific cases (usually denormals and the like) which would be much more expensive than tanh. I think that it would make total sense if you simply provide something like the link above as reference (or just embed the instructions in an appendix in your paper), to justify how many FLOPs those operations take.\n2. Getting a good estimate of energy consumption per high-level operation is significantly more complicated than just counting the type and number of operations. Hardware vendors won't be interested in publishing these numbers for competitive reasons, so there is no way you will get great estimates for modern hardware, unless you ask the hardware vendor to provide the numbers directly in private.","needs_clarification":false,"thread_id":224676,"url":"https://discuss.pytorch.org/t/on-counting-flops-energy-for-the-model/224676","created_at":"2026-03-10T07:13:11.627000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["mjoux"],"answered_by_ptrblck":false} {"question":"Transfer data GPU -> CPU and compute on GPU in parallel\n\nI am a beginner with PyTorch distributed, but never found this point explained anywhere.\n\nI am trying to implement gradient computation with activation checkpointing, where the model weights are kept on CPU, and only weights of the current layer (shard) are loaded to GPU. One iteration works like this (here, `l` counts down from the top):\n\n* Transfer weights for layer `l` from CPU to GPU\n* Run backward for layer `l`\n* Write gradients for layer `l` to CPU\n\nI’d like to do memory transfer and computation in parallel. Using two copies of shards, I’d like to run these in parallel:\n\n* Run backward for layer `l`\n* Write back gradients for layer `l+1` (GPU→CPU) and load weights for layer `l-1` (CPU→GPU)\n\nI read about `dist.isend` and `dist.ircv`, but this is async between two devices. What I want to do here, should run on a single device.\n\nI also read about adding `non_blocking=True` to all `copy_` and `to` statements used to transfer between GPU and CPU. I can do that, but I am sceptical as to whether this really works, without me being more explicit about what should be done in parallel when (just like I do with `isend` and `ircv`).\n\nIn general, async CPU←→ GPU transfer and GPU computation (on a single device) remains a big mistery to me. Thanks for pointing out some docs that explain this.","reference_answer":"It's not entirely clear to me what you mean by \"blocking on the device\". On the device, operations are typically stream-ordered, so if your device supports enough physical work queues, and you place operations in separate streams, and there is no contention between resources, nothing will be blocking on the device.\nFor your specific use case, you need at least 3 streams: one for the actual compute (Forward or backward), one for offloading activations of the previous layer and one for onloading activations for the next layer.\n\nThere are several utilities to help you do that: if you are using Nvidia transformer engine (or are able to switch to it), it supports everything you need through get_cpu_offload_context: https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/pytorch.html#transformer_engine.pytorch.get_cpu_offload_context\n\nThere seems to be a feature request for this for standard PyTorch FSDP: https://github.com/pytorch/pytorch/issues/174960\n\nAnd if you want to roll your own implementation, I used this for a GTC 2024 presentation: https://github.com/MatthiasKohl/llama-recipes/blob/60307ec06d7a4edf6d02f402d29c0eb093aac9fa/src/llama_recipes/interleaved_offload.py\n\nThese implementations might be much more generic and complicated than what you actually need, but they will always be based on some core principle: place computation in one stream, place copies in one direction in a second stream and place copies in the other direction in a third stream. Also note that this kind of offloading doesn't always make sense at all : it might make more sense to distribute across multiple devices or simply use a device with larger memory if it's possible.","needs_clarification":false,"thread_id":224695,"url":"https://discuss.pytorch.org/t/transfer-data-gpu-cpu-and-compute-on-gpu-in-parallel/224695","created_at":"2026-03-14T14:23:22.076000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[5],"answer_authors":["mjoux"],"answered_by_ptrblck":false} {"question":"PyTorch Profiler and jtop report significantly different GPU memory consumption (and OOM)\n\n## Problem\nI am trying to understand how the `torch.cuda.synchronize` works hands on, with the ultimate goal of profiling the CUDA processes on the Jetson Orin Nano (Jetpack 6.2.1).\n\nAs what I thought would be a `simple` example, I tried to add two tensors (`a` and `b`) together (to make `c`). With a size ranging from `(100, 100)` up to `(20000, 20000)`. Once with, and another time without `torch.cuda.synchronize()` enabled.\n\n**What works:**\n✅ Enabling CUDA\n✅ Printing wall time for `torch.cuda.synchronize()` enabled and disabled\n✅ Tensor size from `(100, 100)` up to `(10000, 10000)`\n\n**What doesn't work:**\n❗ Tensor size of `(20000, 20000)` -> Out of memory\n\n**How can I figure out what the problem is?**\n\n---\n\n## Debugging attempt\nThis is a minimal script, that replicates the problem that I have. \n\n```\nimport torch\nimport time\nimport sys\n\nfrom torch.profiler import profile, ProfilerActivity\nPROFILER_AVAILABLE = True\n\n# Ensure CUDA is available\nif not torch.cuda.is_available():\n print(\"CUDA is not available.\")\n exit()\n\nsizes = [\n (100, 100),\n (500, 500),\n (1000, 1000),\n (2000, 2000),\n (5000, 5000),\n (10000, 10000),\n (20000, 20000),# crashes\n \n]\n\nprint(f\"{'Size':>12} | {'No Sync (s)':>12} | {'Sync (s)':>12}\")\nprint(\"-\" * 42)\nfor shape in sizes:\n a = torch.randn(*shape, device='cuda')\n b = torch.randn(*shape, device='cuda')\n\n # Time without synchronization\n start_no_sync = time.time()\n c = a + b\n end_no_sync = time.time()\n no_sync_time = end_no_sync - start_no_sync\n\n # Time with synchronization\n start_sync = time.time()\n c = a + b\n torch.cuda.synchronize()\n end_sync = time.time()\n sync_time = end_sync - start_sync\n\n del a, b, c # Free memory\n\n print(f\"{str(shape):>12} | {no_sync_time:12.6f} | {sync_time:12.6f}\")\n```\n\nOutput\n\n```\njetson@jetson-desktop:~/Documents/github/EdgeFF/exploratory/cudasync/basicExplore$ sudo -E python 02movetensors.py \n Size | No Sync (s) | Sync (s)\n------------------------------------------\n (100, 100) | 0.078534 | 0.001095\n (500, 500) | 0.000775 | 0.000331\n(1000, 1000) | 0.000097 | 0.002389\n(2000, 2000) | 0.001786 | 0.005663\n(5000, 5000) | 0.042742 | 0.070821\n(10000, 10000) | 0.166306 | 0.244864\n\n```\n\nNotice that all the tensor sizes from `(100, 100)` up to `(10000, 10000)` are printed. I can confirm that we have an OOM incident occurring, by observing the `jtop` window. This is the last frame of `jtop` that is sent over SSH prior to the Jetson Orin Nano crashing. Note that I am using SSH, with the GUI disabled (`sudo init 3`) such that there is minimal overhead for competing GPU compute/memory.\n\n[grid]\n[image]\n[image]\n[image]\n[/grid]\n\nThe total memory rises to 7.1GB (out of shared 7.4GB CPU/GPU total), with 5.0GB of the GPU memory taken over by the python thread.\n\nNow, this is the interesting part. I tried to profile to better understand what is happening to the memory. Hence, I attempted to just profile the largest size, that would have a Python GPU memory footprint of under 5.0GB with the additional section below.\n\n```\ncustom_sizes = (16000, 16000)\n\n# Example: Use PyTorch profiler for the largest size without synchronization\nprint(\"\\nPyTorch Profiler output for the largest size (no synchronization):\")\nprint(\"\\nPyTorch Profiler output for the largest size:\")\na = torch.randn(custom_sizes, device='cuda')\nb = torch.randn(custom_sizes, device='cuda')\nwith profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],record_shapes=True, profile_memory=True) as prof:\n for _ in range(1):\n c = a + b\n #torch.cuda.synchronize()\n del c # Free memory immediately after each addition\nprint(prof.key_averages().table(sort_by=\"cuda_time_total\", row_limit=10))\n\ndel a, b # Free memory\n\n# Example: Use PyTorch profiler for the largest size with synchronization\nprint(\"\\nPyTorch Profiler output for the largest size (with synchronization):\")\nprint(\"\\nPyTorch Profiler output for the largest size:\")\nshape = sizes[-1]\na = torch.randn(custom_sizes, device='cuda')\nb = torch.randn(custom_sizes, device='cuda')\nwith profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True, profile_memory=True) as prof:\n for _ in range(1):\n c = a + b\n torch.cuda.synchronize()\n del c # Free memory immediately after each addition\nprint(prof.key_averages().table(sort_by=\"cuda_time_total\", row_limit=10))\n\ndel a, b # Free memory\n\nsys.exit(0)\n``` \n\nA size of `(16000, 16000)` leads to 4.9GB of GPU Ram being used by Python.\n\n[image]\n\n```\njetson@jetson-desktop:~/Documents/github/EdgeFF/exploratory/cudasync/basicExplore$ sudo -E python 02movetensors.py \n Size | No Sync (s) | Sync (s)\n------------------------------------------\n (100, 100) | 0.019701 | 0.000792\n (500, 500) | 0.000501 | 0.000534\n(1000, 1000) | 0.000095 | 0.002402\n(2000, 2000) | 0.001236 | 0.005430\n(5000, 5000) | 0.044867 | 0.073148\n(10000, 10000) | 0.164679 | 0.233903\n\nPyTorch Profiler output for the largest size (no synchronization):\n\nPyTorch Profiler output for the largest size:\n------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg CPU Mem Self CPU Mem CUDA Mem Self CUDA Mem # of Calls \n------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n aten::add 0.15% 550.612us 77.44% 276.848ms 276.848ms 80.485ms 100.00% 160.971ms 160.971ms 0 B 0 B 976.56 MB 976.56 MB 1 \n Unrecognized 0.55% 1.957ms 0.55% 1.957ms 1.957ms 80.485ms 100.00% 80.485ms 80.485ms 0 B 0 B 0 B 0 B 1 \nvoid at::native::vectorized_elementwise_kernel<4, at... 0.00% 0.000us 0.00% 0.000us 0.000us 80.485ms 100.00% 80.485ms 80.485ms 0 B 0 B 0 B 0 B 1 \n cudaStreamIsCapturing 0.01% 27.012us 0.01% 27.012us 27.012us 0.000us 0.00% 0.000us 0.000us 0 B 0 B 0 B 0 B 1 \n cudaMalloc 76.67% 274.096ms 76.67% 274.096ms 274.096ms 0.000us 0.00% 0.000us 0.000us 0 B 0 B 0 B 0 B 1 \n cudaLaunchKernel 0.06% 217.057us 0.06% 217.057us 217.057us 0.000us 0.00% 0.000us 0.000us 0 B 0 B 0 B 0 B 1 \n [memory] 0.00% 0.000us 0.00% 0.000us 0.000us 0.000us 0.00% 0.000us 0.000us 0 B 0 B -976.56 MB -976.56 MB 1 \n cudaDeviceSynchronize 22.56% 80.631ms 22.56% 80.631ms 80.631ms 0.000us 0.00% 0.000us 0.000us 0 B 0 B 0 B 0 B 1 \n------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \nSelf CPU time total: 357.479ms\nSelf CUDA time total: 80.485ms\n\nPyTorch Profiler output for the largest size (with synchronization):\n\nPyTorch Profiler output for the largest size:\n------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n Name Self CPU % Self CPU CPU total % CPU total CPU time avg Self CUDA Self CUDA % CUDA total CUDA time avg CPU Mem Self CPU Mem CUDA Mem Self CUDA Mem # of Calls \n------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \n aten::add 0.17% 231.493us 1.56% 2.115ms 2.115ms 48.063ms 100.00% 96.126ms 96.126ms 0 B 0 B 976.56 MB 976.56 MB 1 \n Unrecognized 1.31% 1.782ms 1.31% 1.782ms 1.782ms 48.063ms 100.00% 48.063ms 48.063ms 0 B 0 B 0 B 0 B 1 \nvoid at::native::vectorized_elementwise_kernel<4, at... 0.00% 0.000us 0.00% 0.000us 0.000us 48.063ms 100.00% 48.063ms 48.063ms 0 B 0 B 0 B 0 B 1 \n cudaLaunchKernel 0.07% 100.911us 0.07% 100.911us 100.911us 0.000us 0.00% 0.000us 0.000us 0 B 0 B 0 B 0 B 1 \n cudaDeviceSynchronize 98.44% 133.741ms 98.44% 133.741ms 66.870ms 0.000us 0.00% 0.000us 0.000us 0 B 0 B 0 B 0 B 2 \n [memory] 0.00% 0.000us 0.00% 0.000us 0.000us 0.000us 0.00% 0.000us 0.000us 0 B 0 B -976.56 MB -976.56 MB 1 \n------------------------------------------------------- ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ \nSelf CPU time total: 135.856ms\nSelf CUDA time total: 48.063ms\n```\n\nThis creates two additional questions:\n- The profiler puts the memory usage at `976.56 MB` which is clearly not `4.9GB` report in `jtop`. **What is the cause of this discrepancy?**\n- Even though `torch.cuda.synchronize` is not active, `cudaDeviceSynchronize` is part of the function call in the PyTorch profiler. I've read through the relavent section in the [documentation](https://docs.pytorch.org/tutorials/recipes/recipes/profiler_recipe.html#using-profiler-to-analyze-memory-consumption), and cannot figure out **what I am missing for accurate memory profiling**?\n\n---\n## System specifications:\n- Jetson Orin Nano with Ubuntu 22.04 (aarch64) and Jetpack 6.2.1\n- CUDA 12.6.68\n- PyTorch 2.8.0\n\nPlease let me know if I can provide additional information! Thanks in advance 😊","reference_answer":"Your peak memory usage should be around `20000 * 20000 * 4 * 4 / 1024**2 = 6103.51MB` since you are holding the previous output `c` still in memory before it gets replaced.\n\nAdd a `del c` after creating the first sum and reporting to lower the memory usage to `20000 * 20000 * 4 * 3 / 1024**2 = 4577.63MB`.","needs_clarification":false,"thread_id":224771,"url":"https://discuss.pytorch.org/t/pytorch-profiler-and-jtop-report-significantly-different-gpu-memory-consumption-and-oom/224771","created_at":"2026-04-05T19:48:04.113000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"5070 ti and 5080 support\n\nI found posts about issues with 5070 or 5080 in pytorch but they are all from 2025. Is it more supported now that we are in the big 2026?","reference_answer":"All Blackwell architectures are supported as of early 2025 in nightly binaries and came with the stable 2.7.0 release with CUDA12.8+. Issues that are still reported are caused by setup issues, such as installing old binaries released before the Blackwell launch.","needs_clarification":false,"thread_id":224825,"url":"https://discuss.pytorch.org/t/5070-ti-and-5080-support/224825","created_at":"2026-04-18T16:37:23.200000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Understanding torch.compile()\n\nHello,\n\nDoes Torch.compile() generate kernels at the Python level (quite abstract), at the C++ level (close to the metal), or using “assembly language” the current device uses (really close to the metal)?\n\nThanks!","reference_answer":"torch.compile generally stays at python level, and usually emits OpenAI triton code for kernels, which then ultimately lowers to assembly (e.g. CUDA PTX for cuda kernels).","needs_clarification":false,"thread_id":224829,"url":"https://discuss.pytorch.org/t/understanding-torch-compile/224829","created_at":"2026-04-20T01:01:23.916000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["mjoux"],"answered_by_ptrblck":false} {"question":"ValueError: Input contains NaN\n\nHello all,\n\nFirst all, full disclosure, I have *very* limited experience using PyTorch; I have largely reverse-engineered the code I’m using from examples I found on the internet.\n\nWith that said, I’ve used PyTorch to build a linear regression model to predict a single metric from a series of data points (1499 of them, to be precise), with the format:\n\n| Metric | Data points |\n|----|----|\n| 10.70685 | \\[0.0019238, 0.00176722, 0.001642…\\] |\n| 10.56528 | \\[0.000376129, 0.0010622, 0.000149819…\\] |\n| 10.93116 | \\[0.0025905, 0.00237781, 0.0022083…\\] |\n\nHowever, when I run the code, it comes back with the error `ValueError: Input contains NaN.` Using `torch.autograd.set_detect_anomaly(True)`yields the message `RuntimeError: Function ‘MseLossBackward0’ returned nan values in its 0th output.` Furthermore, the output of the regression model (`y_pred`in the code below) itself appears to be made up of nothing *but* nan values.\n\nI’ve cleaned the training data to ensure there aren’t any NaNs, and reduced the learning rate (which I’d seen suggested elsewhere), but to no avail. What’s the best way to solve this problem? Thanks!\n\nMy code:\n\n> ```python\n> import pandas as pd\n> import torch\n> from torch import nn\n> from torch.utils.data import TensorDataset, DataLoader\n> import torch.optim as optim\n> from sklearn.model_selection import train_test_split\n> from sklearn.metrics import r2_score\n> import numpy as np\n> \n> class Regression(nn.Module): \n> \n> def __init__(self):\n> super().__init__()\n> self.layers = nn.Sequential(\n> nn.Linear(1499, 64), \n> nn.ReLU(),\n> nn.Linear(64, 32),\n> nn.ReLU(),\n> nn.Linear(32, 1)\n> )\n> \n> \n> def forward(self, x):\n> '''\n> Forward pass\n> '''\n> return self.layers(x)\n> \n> def training_loop(n_epochs, train_loader):\n> for epoch in range(n_epochs):\n> \n> # Set current loss value\n> current_loss = 0.0\n> # Iterate over the DataLoader for training data\n> for i, data in enumerate(train_loader, 0):\n> # Get and prepare inputs\n> inputs, targets = data\n> inputs, targets = inputs.float(), targets.float()\n> targets = targets.reshape((targets.shape[0],1))\n> # Zero the gradients\n> optimizer.zero_grad()\n> # Perform forward pass\n> outputs = model(inputs)\n> \n> # Compute loss\n> loss = loss_function(outputs, targets)\n> \n> # Perform backward pass\n> loss.backward()\n> \n> # Perform optimization\n> optimizer.step()\n> return model\n> \n> data_file=\"data_file.csv\"\n> raw_data=pd.read_csv(raw_data)\n> \t\n> \t\n> input_size = raw_data.shape[1]\n> batch_size = 10\n> model=Regression()\n> n_epochs=100\n> # loss function and optimizer\n> loss_function =nn.MSELoss()\n> # mean square error\n> optimizer = torch.optim.Adam(model.parameters(), lr=1e-14)\n> # input data\n> data_metric=raw_data[metric]\n> \t\n> \t\n> raw_data_points=raw_data['Data Points'].to_list()\n> data_points=[]\n> \t\n> for l in range(len(raw_data_points)): # data sanitation and conversion from str to list of list of floats\n> data_values=raw_data_points[l].split(',')\n> for idx in range(len(raw_data_points)):\n> data_values[idx]=data_values[idx].replace('[','')\n> data_values[idx]=data_values[idx].replace(']','')\n> data_values[idx]=float(data_values[idx])\n> data_points.append(data_values)\n> \n> exo_spectra=np.array(exo_spectra)\n> \n> \t\n> \t\n> metrics=['metric']\n> \t\n> scores=[]\n> \t\n> \n> for metric in metrics:\n> #split and format data\n> data_target=metrics[metric]\n> X_train, X_test, y_train, y_test =train_test_split(data_points,data_target, test_size=0.2, random_state=23) \n> X_train_tensor = torch.from_numpy(X_train)\n> X_train_tensor = torch.tensor(X_train_tensor,dtype=torch.float32)\n> y_train_tensor = torch.from_numpy(y_train.values)\n> y_train_tensor = torch.tensor(y_train_tensor,dtype=torch.float32)\n> X_test_tensor = torch.from_numpy(X_test)\n> X_test_tensor = torch.tensor(X_test_tensor,dtype=torch.float32)\n> y_test_tensor= torch.from_numpy(y_test.values)\n> y_test_tensor = torch.tensor(y_test_tensor,dtype=torch.float32)\n> # load data\n> train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n> train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) \n> # train data and assess accuracy\n> model=training_loop(n_epochs,train_loader)\n> y_pred = model(X_test_tensor)\n> print(y_pred)\n> print(y_pred.detach().numpy())\n> model_score=r2_score(y_test_tensor.detach().numpy(),y_pred.detach().numpy())\n> scores.append(model_score)\n> \n> \t \n> r2_scores=[]\n> for score in scores:\n> r2_scores.append(score)\n> print(r2_scores)\n> ```","reference_answer":"Values around 1e20 are far outside the rest of the data. Huge inputs or targets can overflow to `inf` and then `nan` in the forward pass and in the MSE loss. Remove those outlier data points, and the NaN loss goes away. If you need to keep them, normalize the inputs and targets with the mean and standard deviation from the training set, and invert the transform on the predictions.","needs_clarification":false,"thread_id":224885,"url":"https://discuss.pytorch.org/t/valueerror-input-contains-nan/224885","created_at":"2026-05-01T16:20:36.566000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[2,3,4,5],"answer_authors":["tessarion","valerian.rey"],"answered_by_ptrblck":false} {"question":"How to use a cute dsl python kernel with pytorch\n\nhow can i integrate a cute dsl python kernel with pytorch?","reference_answer":"You can either use Inductor to generate cuteDSL kernels as described [here](https://pytorch.org/blog/gemms-torchinductor-cutedsl-backend/) or you can use custom kernels and pass PyTorch sensors to them as described [here](https://docs.nvidia.com/cutlass/latest/media/docs/pythonDSL/cute_dsl_general/framework_integration.html).","needs_clarification":false,"thread_id":224892,"url":"https://discuss.pytorch.org/t/how-to-use-a-cute-dsl-python-kernel-with-pytorch/224892","created_at":"2026-05-03T11:45:54.353000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Ubuntu 26.04 - what else do I need to install?\n\nSo Ubuntu 26.04 is out and it promises to come with all the Nvidia drivers, cuda and pytorch all out of one distribution. Great! For the last 7 or more years I've used lambda labs, I'd like to remove that dependency.\n\nSo I install ubuntu-26.04-live-server-amd64.iso and select non-free drivers. Once that is up and running I`apt install cuda-toolkit nvidia-cuda-toolkit python3-torch nvidia-utils-595-server`and great, `nvidia-smi` can see my GPUs. But pytorch can't see my GPUs:\n\n```\ntonyr@ml0:~$ python3\nPython 3.14.4 (main, Apr 8 2026, 04:02:31) [GCC 15.2.0] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import torch\n>>> torch.cuda.is_available()\nFalse\n```\n\nDoes anyone know what I am missing?","reference_answer":"And you were right - yet again - thanks a lot. I'm not the only person who is going to have this problem, so let me write it up and hopefully save others a lot of effort.\n\n**The problem** \n\nCanonical claim that Ubuntu 26.04 comes with CUDA support and is AI ready (\nhttps://canonical.com/blog/canonical-announces-it-will-support-and-distribute-nvidia-cuda-in-ubuntu , [Stop Struggling with CUDA: How Ubuntu 26.04 is Fixing AI Development Forever](https://www.youtube.com/watch?v=0CYm-KCw7yY)). This is very misleading for Pytorch users as the supplied python3-torch does not use CUDA and the simplest way to get things going does not use the Ubuntu CUDA support\n\n**The solution**\n\nI chose ubuntu-26.04-live-server-amd64.iso with third party drivers.\n\n`apt install nvidia-utils-595-server python3-venv python3-pip`\nnow you should be able to run `nvidia-smi` and see your GPUs.\n\n`pip3 install torch torchvision`\nand it works!","needs_clarification":false,"thread_id":224896,"url":"https://discuss.pytorch.org/t/ubuntu-26-04-what-else-do-i-need-to-install/224896","created_at":"2026-05-04T18:09:06.640000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[6],"answer_authors":["tonyr"],"answered_by_ptrblck":false} {"question":"Unable to install pytorch 2.10 using conda 26.3.2 on Windows 11\n\nHi\n\nHas anyone had issues installing pytorch using conda? We have an on-premises Anacoda repo (air gapped /w no Internet) and I am unable to install pytorch using 'conda install pytorch' in a clean environment.\n\nconda create -n pytorch\n\nconda activate pytorch\n\nconda clean --all\n\nconda install pytorch (or pytorch-cpu)\n\nI get this error\n\n\\>>>\n\nconda.CondaMultiError: Error with archive C:\\\\conda_pkgs\\\\pytorch-2.10.0-cpu_mkl_py314hf6a6a2c_103.conda. You probably n:\nfailed with error: \\[Errno 2\\] No such file or directory: 'C:\\\\conda_pkgs\\\\pytorch-2.10.0-cpu_mkl_py314hf6a6a2c_103\\\\info'\n\n\\>>>\n\n\\>>>\n\nDownloading and Extracting Packages:\n\nInvalidArchiveError(\"Error with archive C:\\\\conda_pkgs\\\\pytorch-2.10.0-cpu_mkl_py314hf6a6a2c_103.conda. You probably need to delete and re-download or re-create this file. Message was:\\\\n\\\\nfailed with error: \\[Errno 2\\] )\n\n\\>>>\n\nI can install all package dependencies except for pytorch itself. Other users have installed it so I am not sure if the .conda file itself might be corrupt in the repo. Installing other versions of pytorch < 2.10 results in the same error.\n\nReinstalling conda did not fix the problem.\n\nThe version in the Anaconda repo is pytorch(-cpu) v2.10.0 and was last updated May 6, 2026\n\nAny suggestions?\n\nTake care,\n\nShayne","reference_answer":"You could try to install the `conda-forge` builds but also keep in mind that these are community-maintained builds and I don't know how well tested these are. E.g. I cannot find the latest PyTorch 2.11 release there so am unsure if this release is still being planned for `conda-forge`.\n\nYou can install any pip wheels into conda environments in case this works as a lot of users are doing this for years without any issues (and without installing any conda libs at all).","needs_clarification":false,"thread_id":224920,"url":"https://discuss.pytorch.org/t/unable-to-install-pytorch-2-10-using-conda-26-3-2-on-windows-11/224920","created_at":"2026-05-08T17:20:02.804000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Given groups=1, weight of size [48, 32, 3, 3], expected input[1, 14, 128, 94] to have 32 channels, but got 14 channels instead\n\nHey guys, I' facing an issue regarding my dataloader itself.\n\nFor some reason, one of the last entries in the dataset is having a channel size of 14 channels instead of the 32 channels. Could it be due to some issue on my DataLoader?\n\nHere is the Dataset class:\n\n```python\nclass LogmelDataset(Dataset):\n def init(self, h5_file, feature_type, transform=None):\n self.h5_file = h5py.File(“bird_features.h5”, “r”)\n self.feature_imgs = self.h5_file[feature_type]\n self.transform = transform\n\n def __len__(self):\n return len(self.feature_imgs)\n\n def __getitem__(self, idx):\n if self.transform:\n img = self.transform(self.feature_imgs[idx])\n return img\n return self.feature_imgs[idx]\n```\n\nHere is the model I'm using:\n\n```python\nclass Autoencoder(nn.Module):\n def __init__(self):\n super(Autoencoder, self).__init__()\n\n self.encoder = nn.Sequential(\n nn.Conv2d(32, 48, 3, padding=(1, 2)),\n nn.ReLU(),\n nn.MaxPool2d(2, 2),\n nn.Conv2d(48, 16, 3, padding=1),\n nn.ReLU(),\n nn.MaxPool2d(2, 2)\n )\n\n self.decoder = nn.Sequential(\n nn.ConvTranspose2d(16, 48, 2, stride=2),\n nn.ReLU(),\n nn.ConvTranspose2d(48, 32, 2, stride=2),\n nn.ReLU(),\n nn.Conv2d(32, 32, 2, stride=1, padding=(1, 0)),\n nn.ReLU(),\n nn.Conv2d(32, 32, 2, stride=1, padding=(0, 0)),\n nn.Sigmoid()\n )\n\n def forward(self, X):\n encoded = self.encoder(X)\n decoded = self.decoder(encoded)\n return decoded\n```\n\nI'm trying to use an autoencoder to reconstruct bird-singing spectrograms. Currently using this dataset: https://www.kaggle.com/datasets/vinayshanbhag/bird-song-data-set\n\nAnd the data loader is being used as follow:\n\n```python\nlogmel_dataset = LogmelDataset(“bird_features.h5”,\n“logmel”)\n\nloader = torch.utils.data.DataLoader(\ndataset=logmel_dataset,\nbatch_size=32,\nshuffle=True\n)\n```\n\nFor some reason the training works perfectly but suddenly fails when processing the last batch. All the batches have the shape \\[32, 128, 94\\], but the last batch is having a shape of \\[14, 128, 94\\].","reference_answer":"Hi João!\n\nA `Conv2d` accepts an input tensor of either four or three dimensions. In the\nfour-dimensional case the first dimension is the batch dimension and the second\ndimension is the channels dimension.\n\nIn the three-dimensional case there is no batch dimension and the first dimension\nis the channels dimension.\n\nYour initial `Conv2d (32, 48, 3, padding = (1, 2))` expects 32 input channels. \nYour \"batches\" are single samples with no batch dimension (or an implicit batch\ndimension of one, if you prefer), so the leading dimension is the channels dimension.\nSo most of your \"batches\" are single samples with 32 channels, matching your `Conv2d`,\nbut your last \"batch\" has 14 channels, so you get the error.\n\nIt would appear that your dataset -- presumably `bird_features.h5` -- contains\nsamples with no channels dimension (or maybe a single explicit channel).\n\nYour `DataLoader` explicitly creates batches with `batch_size = 32` (with the last\nbatch having whatever is left over, in your case 14 samples).\n\nIf your data samples really have only a single channel, create your initial `Conv2d`\nwith a single input channel as `Conv2d (1, 48, 3, padding = (1, 2))` and make\nsure that your input tensors have an explicit channels dimension of size 1 (using\nsomething like `unsqueeze()`, as necessary), with, e.g., a shape of `[32, 1, 128, 94]`.\n\nBest.\n\nK. Frank","needs_clarification":false,"thread_id":225021,"url":"https://discuss.pytorch.org/t/given-groups-1-weight-of-size-48-32-3-3-expected-input-1-14-128-94-to-have-32-channels-but-got-14-channels-instead/225021","created_at":"2026-05-31T17:06:34.295000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KFrank"],"answered_by_ptrblck":false} {"question":"Splitting the Encoder and Decoder in an Autoencoder Architecture\n\nI am working on replicating a dimensionality reduction model that, at its core, comprises a simple autoencoder. My naive implementation was as follows:\n\n```\nclass encoder(nn.Module):\n def __init__(\n self,\n N,\n K\n ):\n super().__init__()\n self.U = nn.Linear(N,K)\n\n def forward(self,x):\n encoded_x = self.U(x)\n return encoded_x\n\nclass decoder(nn.Module):\n def __init__(\n self,\n N,\n K\n ):\n super().__init__()\n self.V = nn.Linear(K,N)\n\n def forward(self,x):\n decoded_x = self.V(x)\n return decoded_x\n\n```\n\nCreating a separate class for the encoder and decoder, and computing their inputs in the forward pass for the loss function:\n\n```\nencoded_X = encoder(X)\ndecoded_X = decoder(encoded_X)\n\nloss = my_loss_func(X, encoded_X, decoded_X,...)\n```\n\nHowever, I have noticed that most autoencoders put the encoder and decoder together in a single class:\n\n```\nclass SCA_autoencoder(nn.Module): \n\n def __init__(\n self,\n N,\n K\n ):\n super().__init__()\n self.U = nn.Linear(N,K)\n self.V = nn.Linear(K,N)\n\n def forward(self,x):\n encoded_x = self.U(x)\n decoded_x = self.V(encoded_x)\n return encoded_x, decoded_x\n``` \n\nWhen I test these two different implementations, the latter appears to converge while the former does not. Intuitively, this doesn't make sense to me. Beyond readability, is there a difference in the way in which the gradients flow between these two different implementations? I can provide more code snippets or context if people want; the architecture/model I am trying to replicate is from this repo: \n\nhttps://github.com/glaserlab/sca/\n\nAlbert","reference_answer":"There shouldn't be any principle difference. Having the encoder and decoder as own classes is very common as it yields cleaner coder, particularly once the encoder and decoder become more complex.\n\nYou could try to ensure that both version give you the same initial output for a batch. For this you create instances of both version and copy the weights and biases from one instance to the other; something like:\n\n```\nwith torch.no_grad():\n layer2.weight.copy_(layer1.weight)\n layer2.bias.copy_(layer1.bias)\n```\n\nAt least this gives you some sanity check by comparing both outputs and the loss. If those match, you can perform on backward pass to see if the gradients match.","needs_clarification":false,"thread_id":225053,"url":"https://discuss.pytorch.org/t/splitting-the-encoder-and-decoder-in-an-autoencoder-architecture/225053","created_at":"2026-06-07T23:09:01.167000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["vdw"],"answered_by_ptrblck":false} {"question":"Clarification regarding (truncated) backpropagation through time\n\nHi, I am unsure how the backpropagation works/the gradient is computed in a scenario with truncated backpropagation through time. Currently, I do something akin to \n\n```\noutputs = []\nfor t in range(max_steps):\n y_t, hidden = custom_rnn(x[t], hidden.detach())\n outputs.append(y_t)\n\ny = torch.stack(outputs)\nmy_loss = criterion(y,x)\nreturn y, my_loss\n```\n\nIn this code, when the derivative of hidden with respect to the rnn's parameters are computed ends at every time step, because due to the .detach() it acts as a constant in every time step. \n\nNow, what about this:\n```\noutputs = []\nfor t in range(max_steps):\n y_t, hidden = custom_rnn(x[t], hidden)\n if t % 10 == 0 and t > 0:\n hidden = hidden.detach()\n outputs.append(y_t)\n\ny = torch.stack(outputs)\nmy_loss = criterion(y,x)\nreturn y, my_loss\n```\n\nWhen the derivative of the loss is computed with respect to the rnn's parameters, are only the last <= 10 time steps relevant for the chain-rule derivative of hidden (with respect to the rnn's parameters)? Or is the derivative somehow restarted inbetween? \nIf it is the former (only the last <= 10 time steps are relevant), what about this:\n\n```\noutputs = []\nsegments = []\nsegments.append(torch.tensor(0, requires_grad=False))\nfor t in range(max_steps):\n y_t, hidden = custom_rnn(x[t], hidden)\n if t % 10 == 0 and t > 0:\n hidden = hidden.detach()\n segments.append(t)\n outputs.append(y_t)\n\ny = torch.stack(outputs)\ntotal_loss = 0.0\nfor t in segments:\n total_loss += criterion(y[t:t+10], x[t:t+10]) # ignore the last chunk possibly being shorter\nmy_loss = total_loss/len(segments)\nreturn y, my_loss\n```\n\nNow here I compute the loss independently for each segment between the detach operations. Is the gradient flowing properly for each chunk/segment? \n\nNow in practice I have the following scenario: \nMy whole model is roughly:\n\n```\nclass MyModel(nn.Module):\n # some defs \ndef forward(self, x):\n y = self.submodel_A(x)\n z, rnn_loss = my_rnn(y)\n return z, rnn_loss\n\n```\nand then I have an outer criterion:\n\n```\nmy_model = MyModel()\nfor (input, target) in dataloader:\n output, my_loss = my_model(input)\n loss = outer_criterion(output, target) + my_loss\n loss.backward()\n```\nHow does the loss.backward() interact with the segment losses I compute inside the rnn? Are the derivates correctly computed for each segment? Or just for the last one? Also, for the outer_critertion, does the derivative of hidden with respect to the rnn's parameters stop at the last hidden.detach()? Or does the gradient somehow propagate through the entire sequence the rnn processes?\n\nIt would be really helpful to get some clarification on this as I am still unsure what is going on under the hood. \nThank you :)","reference_answer":"`.detach()` creates a hard boundary in the autograd graph, and gradient cannot cross it. If `hidden` is detached at every step, no gradient flows through the recurrent connection, and each step only gets gradient from its own direct dependence on the RNN parameters. If `hidden` is detached every 10 steps, the gradient through the recurrence reaches at most 10 steps back, to the last detach point, and each output reaches back to the most recent boundary. If you compute the loss per segment and sum the segment losses, each segment's gradient flows at most to its own start, and the total gradient is the sum of the per-segment gradients. This is mathematically equivalent to computing each segment's loss, calling backward on it with `retain_graph`, and then detaching.","needs_clarification":false,"thread_id":225131,"url":"https://discuss.pytorch.org/t/clarification-regarding-truncated-backpropagation-through-time/225131","created_at":"2026-06-26T21:22:06.541000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[1,3],"answer_authors":["Aditya_Mehra","Cola_Lightyear"],"answered_by_ptrblck":false} {"question":"Is gpu_tensor.to('cpu', non_blocking=True) ever asynchronous?\n\nI ask because I've heard you need pinned target memory for asynchronous copies and that for some reason pytorch might not be allocating pinned target tensors for GPU to CPU transfers with non_blocking=True? Yet I find it counter intuitive that gpu_tensor.to('cpu', non_blocking=True) must always block... What is the truth?","reference_answer":"Yes, as described in [this section](https://docs.pytorch.org/tutorials/intermediate/pinmem_nonblock.html#other-copy-directions-gpu-cpu-cpu-mps) of the \"A guide on good usage of `non_blocking` and `pin_memory()` in PyTorch\" tutorial.","needs_clarification":false,"thread_id":225135,"url":"https://discuss.pytorch.org/t/is-gpu-tensor-to-cpu-non-blocking-true-ever-asynchronous/225135","created_at":"2026-06-30T21:04:10.951000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Weights dont sychronise in multi GPU training\n\nHi all,\n\nI have been trying to train a GNN in multiple gpus. I use the standard python libraries, PyG and DDP. I can see the data distributed in the GPUs, and each of them training a model. However the weights are not sychronized. Before the training all the weights are exactly the same, but after one epoch they are different. I feel that the problem comes from :\n\n\"\\[rank0\\]: RuntimeError: Expected to mark a variable ready only once. This error is caused by one of the following reasons: 1) Use of a module parameter outside the `forward` function. Please make sure model parameters are not shared across multiple concurrent forward-backward passes. or try to use \\_set_static_graph() as a workaround if this module graph does not change during training loop.2) Reused parameters in multiple reentrant backward passes. For example, if you use multiple `checkpoint` functions to wrap the same part of your model, it would result in the same set of parameters been used by different reentrant backward passes multiple times, and hence marking a variable ready multiple times. DDP does not support such use cases in default. You can try to use \\_set_static_graph() as a workaround if your module graph does not change over iterations.\"\n\nwhich i masked/bypassed (?) by setting set_static_graph(). Does anyone have any ideas what is the problem and what I should do?\n\nthank you, Panagiotis","reference_answer":"Gradient sync breaks for parameters that aren't used in the forward pass, so make sure every parameter is used in `forward`. Calling modules or methods that run the forward pass outside `forward` can also skip gradient sync. Move such code, for example a loss function that calls the model, out of the model class.","needs_clarification":false,"thread_id":225141,"url":"https://discuss.pytorch.org/t/weights-dont-sychronise-in-multi-gpu-training/225141","created_at":"2026-07-02T12:53:59.403000Z","tier":"gold","answer_origin":"composed","answer_post_numbers":[3,7,8],"answer_authors":["Albert_Flugel","pbellos","ptrblck"],"answered_by_ptrblck":true} {"question":"Tutorials/examples of captum with 1D data?\n\nHello all,\n\nI'm hoping to use captum for feature attribution on a basic 1-D linear regression model (see below), but all the examples I've seen use 2D models (usually for machine vision applications). Is there a good tutorial out there for using captum with simpler models?\n\nThanks!\n\n```python\nclass Regression(nn.Module):\n\n def __init__(self):\n super().__init__()\n self.layers = nn.Sequential(\n nn.Linear(7490, 64),\n nn.ReLU(),\n nn.Linear(64, 32),\n nn.ReLU(),\n nn.Linear(32, 1)\n )\n\n def forward(self, x):\n '''\n Forward pass\n '''\n return self.layers(x)\n\ndef training_loop(n_epochs, train_loader):\n# training loop\n\n for epoch in range(n_epochs):\n\n # Set current loss value\n current_loss = 0.0\n # Iterate over the DataLoader for training data\n for i, data in enumerate(train_loader, 0):\n # Get and prepare inputs\n inputs, targets = data\n inputs, targets = inputs.float(), targets.float()\n targets = targets.reshape((targets.shape[0],1))\n # Zero the gradients\n optimizer.zero_grad()\n # Perform forward pass\n outputs = model(inputs)\n\n # Compute loss\n loss = loss_function(outputs, targets)\n\n # Perform backward pass\n loss.backward()\n\n # Perform optimization\n optimizer.step()\n return model\n```","reference_answer":"Captum works with 1D models too. Most of the examples use images, but the attribution methods are model agnostic. For a simple feed forward network like yours, methods such as Integrated Gradients or Saliency should work without changing the model. The main difference is that your input tensor will have shape `[batch_size, 7490]` instead of image dimensions. The image examples still apply once you replace the input format.","needs_clarification":false,"thread_id":225162,"url":"https://discuss.pytorch.org/t/tutorials-examples-of-captum-with-1d-data/225162","created_at":"2026-07-09T21:43:05.934000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["KevinTurner"],"answered_by_ptrblck":false} {"question":"Conditional Assignment of Tensors\n\nSuppose that I have a two element-wise functions h(x) and g(x) where x is an at::Tensor.\nHow should I compute an element-wise conditional assignment; e.g.,\n`f(x) = h(x) if x > 0 else g(x)`","reference_answer":"Would `at::where` work for you? It's the aten equivalent of [torch.where](https://docs.pytorch.org/docs/2.13/generated/torch.where.html).\n\nSomething like that:\n```cpp\nat::Tensor f(const at::Tensor& x) {\n auto mask = x > 0;\n return at::where(mask, h(x), g(x));\n}\n```\n\nThe only issue is that h(x) and g(x) are computed for the entire x tensor, so they need to be defined for both positive and negative values. Also, if they're slow to compute there could be faster alternatives that don't require computing values that you won't use. But I think in most cases `where` is good enough.","needs_clarification":false,"thread_id":225208,"url":"https://discuss.pytorch.org/t/conditional-assignment-of-tensors/225208","created_at":"2026-07-21T23:18:30.187000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["valerian.rey"],"answered_by_ptrblck":false} {"question":"Using max pooling kernels without computing indices\n\nHi PyTorch forum,\n\nI'm trying to address a bottleneck in some code of mine where a big `F.max_pool1d` is being applied (very long input length and long kernel length of 121). I noticed that this was a bottleneck from running in VizTracer, where I also learned that internally it's calling into an ATen max_pool2d_with_indices. I'm running on a GPU (CUDA).\n\nI don't need gradients or anything, so I was wondering if it would be possible to avoid the indices. I noticed some merged PRs in PyTorch relating to implementing no-indices optimizations (like https://github.com/pytorch/pytorch/pull/43745), and I was curious if it's possible for end users to access those code paths from Python. I've tried inference_mode and set_grad_enabled(False), but I still see the with_indices function in the call stack.\n\nJust curious if that's possible -- thanks!","reference_answer":"AFAICT, there is currently no native implementation without indices (both adaptive: https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/cuda/AdaptiveMaxPooling2d.cu and regular : https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/cuda/DilatedMaxPool2d.cu ).\n\nSo you cannot call into this implementation without the indices tensor, regardless at what API level.","needs_clarification":false,"thread_id":225213,"url":"https://discuss.pytorch.org/t/using-max-pooling-kernels-without-computing-indices/225213","created_at":"2026-07-22T14:18:16.508000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["mjoux"],"answered_by_ptrblck":false} {"question":"Mps seems much slower than cpu on an M1 Mac\n\nDoes someone know an example where mps is faster than cpu on an m1 Mac ?\n\nI have found that running the tutorial example polynomial_autograd.py using device mp3 is much slower that cpu. Below is an example script (temp.sh) that demonstrates the problem. This script wirte the files polynomial_autograd.py, temp.sed, and temp.py in the working directory.\n\n```\n#! /usr/bin/env bash\nset -e\nif [ \"$1\" != cpu ] && [ \"$1\" != mps ]\nthen\n echo 'usage: ./temp.sh (cpu | mps)'\n exit 1\nfi\n#\n# polynomial_autograd.py\nfile='polynomial_autograd.py'\nremote_dir='https://raw.githubusercontent.com/pytorch/tutorials/refs/heads/main/beginner_source/examples_autograd'\nif [ -e $file ]\nthen\n rm $file\nfi\nwget \"$remote_dir/$file\"\n#\n# temp.sed\ncat << EOF > temp.sed\ns|import math|&\\\\\nimport time\\\\\nstart_time = time.time()|\ns|^device *=.*|device = '$1'|\nEOF\n#\n# temp.py\nsed -f temp.sed $file > temp.py\ncat << EOF >> temp.py\nend_time = time.time()\nelapsed_time = end_time - start_time\nprint(f'device = {device}, elapsed_time = {elapsed_time}')\nEOF\n#\n# run temp.py \npython temp.py\n#\necho 'temp.sh: OK'\n```\n\nHere is the timing result for cpu on my machine:\n\n```\n...\nResult: y = 0.9962908029556274 + 0.959979772567749 x + 0.5367483496665955 x^2 + 0.23622195422649384 x^3\ndevice = cpu, elapsed_time = 0.47927093505859375\ntemp.sh: OK\n```\n\nHere is the result for mps:\n\n```\nResult: y = 0.9962908625602722 + 0.994568943977356 x + 0.5367482900619507 x^2 + 0.18149884045124054 x^3\ndevice = mps, elapsed_time = 1.5502047538757324\ntemp.sh: OK\n\n```","reference_answer":"The problem with why its slower is that the task is too simple and thus the overhead overshadows the speed up. This is because polynomial_autograd.py is simple (basic arithmetic). Here checkout some more complex operations and look at the speed up\n\n```\nimport time\nimport torch\nimport sys\n\nDEVICE = sys.argv[1] if len(sys.argv) > 1 else \"cpu\"\nWARMUP = 3\nITERS = 10\n\ndef bench(name, fn, warmup=WARMUP, iters=ITERS):\n for _ in range(warmup):\n fn()\n if DEVICE == \"mps\":\n torch.mps.synchronize()\n times = []\n for _ in range(iters):\n t0 = time.perf_counter()\n fn()\n if DEVICE == \"mps\":\n torch.mps.synchronize()\n t1 = time.perf_counter()\n times.append(t1 - t0)\n mean = sum(times) / len(times)\n std = (sum((t - mean) ** 2 for t in times) / len(times)) ** 0.5\n print(f\" {name:40s} {mean*1000:8.2f} ms +/- {std*1000:.2f} ms\")\n return mean\n\nprint(f\"DeVICE: {DEVICE} | PyTorch {torch.__version__}\\n\", flush=True)\n\n# 1. Matrix multiply (large, compute-bound)\nN = 8192\na = torch.randn(N, N, device=DEVICE, dtype=torch.float32)\nb = torch.randn(N, N, device=DEVICE, dtype=torch.float32)\n\nbench(f\"matmul {N}x{N}\", lambda: torch.mm(a, b))\n\n# 2. Convolution (batched, spatial)\nB, C, H, W = 128, 64, 56, 56\nK = 128\nconv = torch.nn.Conv2d(C, K, 3, padding=1, device=DEVICE)\ninp = torch.randn(B, C, H, W, device=DEVICE)\n\nbench(f\"conv2d {B}x{C}x{H}x{W} -> {K}\", lambda: conv(inp))\n\n# 3. Batched MV with 512x1024x1024 random mats \nM_SIZE = 1024\nBATCH = 512\nmatrices = torch.randn(BATCH, M_SIZE, M_SIZE, device=DEVICE)\nvectors = torch.randn(BATCH, M_SIZE, 1, device=DEVICE)\n\nbench(f\"bmm {BATCH}x{M_SIZE}x{M_SIZE}\", lambda: torch.bmm(matrices, vectors))\n\n# 4. SoftMAX AND layer norm over large fake sequence\nSEQ, DIM = 4096, 2048\nx = torch.randn(SEQ, DIM, device=DEVICE)\n\nbench(f\"softmax {SEQ}x{DIM}\", lambda: torch.softmax(x, dim=-1))\nbench(f\"layernorm {SEQ}x{DIM}\", lambda: torch.nn.functional.layer_norm(x, (DIM,)))\n\n# 5. Small CNN training loop\nC_IN, C_OUT = 64, 64\nmodel = torch.nn.Sequential(\n torch.nn.Conv2d(C_IN, C_OUT, 3, padding=1, device=DEVICE),\n torch.nn.ReLU(),\n torch.nn.Conv2d(C_OUT, C_OUT, 3, padding=1, device=DEVICE),\n torch.nn.ReLU(),\n torch.nn.Conv2d(C_OUT, C_OUT, 3, padding=1, device=DEVICE),\n).to(DEVICE)\noptimizer = torch.optim.SGD(model.parameters(), lr=0.01)\ndata = torch.randn(64, C_IN, 32, 32, device=DEVICE)\ntarget = torch.randn(64, C_OUT, 32, 32, device=DEVICE)\n\ndef training_step():\n optimizer.zero_grad()\n out = model(data)\n loss = torch.nn.functional.mse_loss(out, target)\n loss.backward()\n optimizer.step()\n\nWARMUP_SMALL = 20\nITERS_SMALL = 50\nfor _ in range(WARMUP_SMALL):\n training_step()\nif DEVICE == \"mps\":\n torch.mps.synchronize()\ntimes = []\nfor _ in range(ITERS_SMALL):\n t0 = time.perf_counter()\n training_step()\n if DEVICE == \"mps\":\n torch.mps.synchronize()\n t1 = time.perf_counter()\n times.append(t1 - t0)\nmean = sum(times) / len(times)\nstd = (sum((t - mean) ** 2 for t in times) / len(times)) ** 0.5\nprint(f\" {'training step (3-layer CNN)':40s} {mean*1000:8.2f} ms +/{std*1000:.2f} ms\")\n\n \n```\n\nNote: we use `time.perf_counter` instead of `time.time` as it is more reliable (not affected by external system things)\n\n```\n| Benchmark | CPU | MPS | Speedup |\n|---|---|---|---|\n| matmul 8192×8192 | 1366 ms | 696 ms | 1.96× |\n| conv2d 128×64×56×56 | 179 ms | 16.6 ms | 10.8× |\n| bmm 512×1024×1024 | 48.2 ms | 26.3 ms | 1.83× |\n| softmax 4096×2048 | 5.4 ms | 1.2 ms | 4.6× |\n| layernorm 4096×2048 | 2.4 ms | 1.1 ms | 2.3× |\n| training step (3-layer CNN) | 216 ms | 23.9 ms | 9.0× |\n```\n\nsee how on the CNN it gets around 9x. This was done on a macbook m1 air. The warmup is there so the timings do not include one time Metal shader compilation... So therefore, most places (especially for real heavy work)\n\nnote: you'll probably see the speed up with changing `x = torch.linspace(-1, 1, 2000, dtype=dtype)` to `torch.linspace(-math.pi, math.pi, 2000)` in the example\n\nhttps://raw.githubusercontent.com/pytorch/tutorials/refs/heads/main/beginner_source/examples_autograd/polynomial_autograd.py","needs_clarification":false,"thread_id":225242,"url":"https://discuss.pytorch.org/t/mps-seems-much-slower-than-cpu-on-an-m1-mac/225242","created_at":"2026-08-01T23:53:09.591000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["Jonathan_Coletti"],"answered_by_ptrblck":false} {"question":"Editing data labels\n\nHello,\n\nI am trying to split Cifar10 to get two subsets (Animals and Vehicles). I was able to successfully separate them by the labels \n\n```python\npartitioner = IidPartitioner(num_partitions=1)\nfds = FederatedDataset(dataset=\"uoft-cs/cifar10\", partitioners={\"train\": partitioner},)\n\npartition1_train_test = fds.load_partition(0).train_test_split(test_size=0.2, seed=42)\n\npytorch_transforms = Compose([ToTensor(), Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ndef apply_transforms(batch):\n \"\"\"Apply transforms to the partition from FederatedDataset.\"\"\"\n batch[\"img\"] = [pytorch_transforms(img) for img in batch[\"img\"]]\n return batch\n\npartition_train_test = partition_train_test.with_transform(apply_transforms)\n\nlabels_list_partition1_train = [item['label'] for item in partition_train_test['train']]\n\nanimals = torch.tensor([2, 3, 4, 5, 6, 7])\nanimalsindicesTrain = (torch.tensor(labels_list_partition1_train)[..., None] == animals).any(-1).nonzero(as_tuple=True)[0]\n\nanimalsTrainSubset = torch.utils.data.Subset(partition1_train_test['train'], animalsindicesTrain)\n\nanimalsTrainDataloader = DataLoader(animalsTrainSubset, batch_size=128, shuffle=True, num_workers=2)\n```\n\nBut I still have 10 classes in that subset and I would like it to have 6 for animals and 4 for vehicles. Is in my interest to have different length heads as I am doing some tests with federated environments.\n\nIs there any straight forward way of reducing the number of classes of the subsets?\n\nThank you in advance.","reference_answer":"`Subset` is only a thin wrapper, which uses the specified indices and forwards it to the underlying `Dataset`. The same `Dataset.__getitem__` (with a subset of indices) will be used to load and transform the samples. \n\nYou could try to remap the target indices to new ranges (both starting at 0 to avoid issues with your criterion) e.g. via:\n\n```\nclass RemappedLabels(torch.utils.data.Dataset):\n def __init__(self, dataset, label_map):\n self.dataset = dataset\n self.label_map = label_map\n def __len__(self):\n return len(self.dataset)\n def __getitem__(self, idx):\n sample = dict(self.dataset[idx])\n sample[\"label\"] = self.label_map[int(sample[\"label\"])]\n return sample\n...\nanimal_map = {2: 0, 3: 1, 4: 2, 5: 3, 6: 4, 7: 5}\nvehicle_map = {0: 0, 1: 1, 8: 2, 9: 3}\nanimalsTrainSubset = torch.utils.data.Subset(partition1_train_test[\"train\"], animalsindicesTrain)\nanimalsTrainDataset = RemappedLabels(animalsTrainSubset, animal_map)\n```\n\nLet me know if this would work for your use case.","needs_clarification":false,"thread_id":225258,"url":"https://discuss.pytorch.org/t/editing-data-labels/225258","created_at":"2026-08-06T13:16:18.430000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["ptrblck"],"answered_by_ptrblck":true} {"question":"Torch.compile dependancy on system architecture / environment\n\n**TLDR:** Does the PyTorch-TensorRT compiler depend on the (a) underlying system architecture and/or (b) available system resources?\n\n---\n\n**More details:** I want to evaluate the performance of a compiled PyTorch model, for the TensorRT framework on the Jetson Orin Nano in Jetpack 6.2.\n\nA minimal working example is avaliable in the [README.md for pytorch/TensorRT](https://github.com/pytorch/TensorRT/blob/3141ff36ecfd4c0b6fcba10c21009b017e7f7f50/README.md?plain=1#L39-L53):\n\n```\nimport torch\nimport torch_tensorrt\n\nmodel = MyModel().eval().cuda() # define your model here\nx = torch.randn((1, 3, 224, 224)).cuda() # define what the inputs to the model will look like\n\noptimized_model = torch.compile(model, backend=\"tensorrt\")\noptimized_model(x) # compiled on first run\n\noptimized_model(x) # this will be fast!\n```\n\nI _think_ that the underlying TensorRT engine runs an optimisation to search the compilation space for the ~best compilation when we run `optimized_model(x)` for the first time. \n\n> ``optimization_level`` (0–5, default 3) controls how long TRT spends searching for\nfaster kernel implementations. Higher values produce faster engines at the cost of\nlonger compile time. \n\nSource: [TensorRT/docs/_sources/user_guide/performance_tuning.rst.txt](https://github.com/pytorch/TensorRT/blob/3141ff36ecfd4c0b6fcba10c21009b017e7f7f50/docs/_sources/user_guide/performance_tuning.rst.txt?plain=1#L161-L163)\n\nIn practise, this means for effective performative use of `torch.compile()` we should:\n- Be on the same device (or as close as possible) that we wish to deploy the compiled model\n- Ensure the working environment is the same (or as close as possible) to the deployed environment. As an example, the `jetson_clocks` and `nvpmodel` power state should be the same.\n \nIf the two above items are not respected, then the TensorRT compiler is NOT optimising for our target deployment scenario.\n\nIs my understanding correct? And where can I find more information about this? I have read the (very helpful ✨) [pytorch/TensorRT repo](https://github.com/pytorch/TensorRT) and the [NVIDIA TensorRT documentation](https://docs.nvidia.com/deeplearning/tensorrt/latest/index.html) but perhaps I have missed something?","reference_answer":"Yes this is correct. You should use the deployment device in the power mode you will deploy when you compile to build engines tuned for that scenario. More information on controlling the determinism of the engine construction can be found here: https://docs.nvidia.com/deeplearning/tensorrt/latest/performance/optimization.html#deterministic-tactic-selection","needs_clarification":false,"thread_id":225264,"url":"https://discuss.pytorch.org/t/torch-compile-dependancy-on-system-architecture-environment/225264","created_at":"2026-08-07T13:00:04.680000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[3],"answer_authors":["narendasan"],"answered_by_ptrblck":false} {"question":"Errors building torchaudio with Pytorch 2.13.0, CUDA 13.3.1, GCC 15.3.0\n\nWith Pytorch 2.13.0, CUDA 13.3.1, GCC 15.3.0; I'm getting many build errors.\n`pip install -e . --no-deps --no-build-isolation`:\n```\nDefaulting to user installation because normal site-packages is not writeable\nObtaining file:///tmp/audio\n Checking if build backend supports build_editable: started\n Checking if build backend supports build_editable: finished with status 'done'\n Preparing editable metadata (pyproject.toml): started\n Preparing editable metadata (pyproject.toml): finished with status 'done'\nBuilding wheels for collected packages: torchaudio\n Building editable for torchaudio (pyproject.toml): started\n Building editable for torchaudio (pyproject.toml): finished with status 'error'\n error: subprocess-exited-with-error\n \n × Building editable for torchaudio (pyproject.toml) did not run successfully.\n │ exit code: 1\n ╰─> [8973 lines of output]\n /home/geremia/.local/lib/python3.12/site-packages/setuptools/dist.py:765: SetuptoolsDeprecationWarning: License classifiers are deprecated.\n !!\n \n ********************************************************************************\n Please consider removing the following classifiers in favor of a SPDX license expression:\n \n License :: OSI Approved :: BSD License\n \n See https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license for details.\n ********************************************************************************\n \n !!\n self._finalize_license_expression()\n -- Git branch: main\n -- Git SHA: 4e3e282b0e23a0b9133abc8f719e2fa39be2a6e3\n -- Git tag: None\n -- Building version 2.11.0a0+4e3e282\n running editable_wheel\n creating /tmp/pip-ephem-wheel-cache-locw9zdq/wheels/79/c4/93/eeda50fa794d74362aa169fae3586975eb9bf1eb372a512457/tmpbod3ti1e/.tmp-a3_g3sr0/torchaudio.egg-info\n writing /tmp/pip-ephem-wheel-cache-locw9zdq/wheels/79/c4/93/eeda50fa794d74362aa169fae3586975eb9bf1eb372a512457/tmpbod3ti1e/.tmp-a3_g3sr0/torchaudio.egg-info/PKG-INFO\n writing dependency_links to /tmp/pip-ephem-wheel-cache-locw9zdq/wheels/79/c4/93/eeda50fa794d74362aa169fae3586975eb9bf1eb372a512457/tmpbod3ti1e/.tmp-a3_g3sr0/torchaudio.egg-info/dependency_links.txt\n writing top-level names to /tmp/pip-ephem-wheel-cache-locw9zdq/wheels/79/c4/93/eeda50fa794d74362aa169fae3586975eb9bf1eb372a512457/tmpbod3ti1e/.tmp-a3_g3sr0/torchaudio.egg-info/top_level.txt\n writing manifest file '/tmp/pip-ephem-wheel-cache-locw9zdq/wheels/79/c4/93/eeda50fa794d74362aa169fae3586975eb9bf1eb372a512457/tmpbod3ti1e/.tmp-a3_g3sr0/torchaudio.egg-info/SOURCES.txt'\n adding license file 'LICENSE'\n writing manifest file '/tmp/pip-ephem-wheel-cache-locw9zdq/wheels/79/c4/93/eeda50fa794d74362aa169fae3586975eb9bf1eb372a512457/tmpbod3ti1e/.tmp-a3_g3sr0/torchaudio.egg-info/SOURCES.txt'\n creating '/tmp/pip-ephem-wheel-cache-locw9zdq/wheels/79/c4/93/eeda50fa794d74362aa169fae3586975eb9bf1eb372a512457/tmpbod3ti1e/.tmp-a3_g3sr0/torchaudio-2.11.0a0+4e3e282.dist-info'\n creating /tmp/pip-ephem-wheel-cache-locw9zdq/wheels/79/c4/93/eeda50fa794d74362aa169fae3586975eb9bf1eb372a512457/tmpbod3ti1e/.tmp-a3_g3sr0/torchaudio-2.11.0a0+4e3e282.dist-info/WHEEL\n running build_py\n running build_ext\n W0830 20:31:43.116000 16450 site-packages/torch/utils/cpp_extension.py:657] There are no g++ version bounds defined for CUDA version 13.3\n building 'torchaudio.lib._torchaudio' extension\n [1/2] ccache c++ -MMD -MF '/tmp/tmpgvfi885p.build-temp/tmp/audio/src/libtorchaudio/_torchaudio.o'.d -fno-strict-overflow -Wsign-compare -DNDEBUG -g -O3 -Wall -fPIC '-I/tmp/audio/src' -I/usr/lib64/python3.12/site-packages/torch/include -I/usr/lib64/python3.12/site-packages/torch/include/torch/csrc/api/include -I/opt/cuda-13.3/include -I/usr/include/python3.12 -c -c '/tmp/audio/src/libtorchaudio/_torchaudio.cpp' -o '/tmp/tmpgvfi885p.build-temp/tmp/audio/src/libtorchaudio/_torchaudio.o' -DTORCH_TARGET_VERSION=0x020a000000000000 -fdiagnostics-color=always -DUSE_CUDA -DINCLUDE_ALIGN -DTORCH_API_INCLUDE_EXTENSION_H -DPy_LIMITED_API=0x030A0000 -DTORCH_EXTENSION_NAME=_torchaudio -std=c++20\n FAILED: [code=1] /tmp/tmpgvfi885p.build-temp/tmp/audio/src/libtorchaudio/_torchaudio.o\n ccache c++ -MMD -MF '/tmp/tmpgvfi885p.build-temp/tmp/audio/src/libtorchaudio/_torchaudio.o'.d -fno-strict-overflow -Wsign-compare -DNDEBUG -g -O3 -Wall -fPIC '-I/tmp/audio/src' -I/usr/lib64/python3.12/site-packages/torch/include -I/usr/lib64/python3.12/site-packages/torch/include/torch/csrc/api/include -I/opt/cuda-13.3/include -I/usr/include/python3.12 -c -c '/tmp/audio/src/libtorchaudio/_torchaudio.cpp' -o '/tmp/tmpgvfi885p.build-temp/tmp/audio/src/libtorchaudio/_torchaudio.o' -DTORCH_TARGET_VERSION=0x020a000000000000 -fdiagnostics-color=always -DUSE_CUDA -DINCLUDE_ALIGN -DTORCH_API_INCLUDE_EXTENSION_H -DPy_LIMITED_API=0x030A0000 -DTORCH_EXTENSION_NAME=_torchaudio -std=c++20\n In file included from :\n /usr/include/stdc-predef.h:68:2: error: #error \"This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined.\"\n 68 | #error \"This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined.\"\n | ^~~~~\n In file included from /usr/lib64/gcc/x86_64-slackware-linux/15.3.0/include/stdint.h:11,\n from /usr/include/torch/csrc/inductor/aoti_torch/c/macros.h:5,\n from /usr/include/torch/csrc/inductor/aoti_torch/c/shim.h:4,\n from /usr/include/torch/csrc/stable/c/shim.h:4,\n from /usr/include/torch/csrc/stable/device_inl.h:8,\n from /usr/include/torch/csrc/stable/device.h:3,\n from /tmp/audio/src/libtorchaudio/utils.h:3,\n from /tmp/audio/src/libtorchaudio/_torchaudio.cpp:1:\n /usr/include/stdint.h:318:2: error: #error \"This file should not be included when either ORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined.\"\n\n⋮\n```\n\n\\[⋮\\]\n\n```\n⋮\nnsor_inl.h:73:1: error: no matching function for call to ‘stdTorchCheckMsgImpl(const char [181], const char [31], const char [3], const char [44], const char [2], int, const char [3], const char [39], const char*)’\n 73 | DEFINE_CAST(uint32_t, UInt32)\n | ^~~~~~~~~~~\n /usr/include/torch/csrc/stable/tensor_inl.h:73:1: note: there are 2 candidates\n /usr/include/torch/headeronly/util/Exception.h:53:20: note: candidate 1: ‘const char* torch::headeronly::detail::stdTorchCheckMsgImpl(const char*)’\n 53 | inline const char* stdTorchCheckMsgImpl(const char* msg) {\n | ^~~~~~~~~~~~~~~~~~~~\n /usr/include/torch/headeronly/util/Exception.h:53:20: note: candidate expects 1 argument, 9 provided\n /usr/include/torch/headeronly/util/Exception.h:57:20: note: candidate 2: ‘const char* torch::headeronly::detail::stdTorchCheckMsgImpl(const char*, const char*)’\n 57 | inline const char* stdTorchCheckMsgImpl(const char* /*msg*/, const char* args) {\n | ^~~~~~~~~~~~~~~~~~~~\n /usr/include/torch/headeronly/util/Exception.h:57:20: note: candidate expects 2 arguments, 9 provided\n /usr/include/torch/csrc/stable/tensor_inl.h: At global scope:\n /usr/include/torch/csrc/stable/tensor_inl.h:73:1: error: template-id ‘const_data_ptr<>’ for ‘const uint32_t* torch::stable::Tensor::const_data_ptr() const’ does not match any template declaration\n 73 | DEFINE_CAST(uint32_t, UInt32)\n | ^~~~~~~~~~~\n /usr/include/torch/csrc/stable/tensor_struct.h:184:12: note: candidates are: ‘template > const T* torch::stable::Tensor::const_data_ptr() const’\n 184 | const T* const_data_ptr() const;\n | ^~~~~~~~~~~~~~\n /usr/include/torch/csrc/stable/tensor_struct.h:156:15: note: ‘const void* torch::stable::Tensor::const_data_ptr() const’\n 156 | const void* const_data_ptr() const {\n | ^~~~~~~~~~~~~~\n /usr/include/torch/csrc/stable/tensor_inl.h: In member function ‘T* torch::stable::Tensor::mutable_data_ptr() const [with T = long unsigned int]’:\n /usr/include/torch/csrc/stable/tensor_inl.h:74:1: error: ‘runtime_error’ is not a member of ‘std’\n 74 | DEFINE_CAST(uint64_t, UInt64)\n | ^~~~~~~~~~~\n /usr/include/torch/csrc/stable/tensor_inl.h:74:1: note: ‘std::runtime_error’ is defined in header ‘’; this is probably fixable by adding ‘#include ’\n /usr/include/torch/csrc/stable/tensor_inl.h:74:1: error: no matching function for call to ‘stdTorchCheckMsgImpl(const char [181], const char [36], const char [3], const char [44], const char [2], int, const char [3], const char [39], const char*)’\n 74 | DEFINE_CAST(uint64_t, UInt64)\n | ^~~~~~~~~~~\n /usr/include/torch/csrc/stable/tensor_inl.h:74:1: note: there are 2 candidates\n /usr/include/torch/headeronly/util/Exception.h:53:20: note: candidate 1: ‘const char* torch::headeronly::detail::stdTorchCheckMsgImpl(const char*)’\n 53 | inline const char* stdTorchCheckMsgImpl(const char* msg) {\n | ^~~~~~~~~~~~~~~~~~~~\n /usr/include/torch/headeronly/util/Exception.h:53:20: note: candidate expects 1 argument, 9 provided\n /usr/include/torch/headeronly/util/Exception.h:57:20: note: candidate 2: ‘const char* torch::headeronly::detail::stdTorchCheckMsgImpl(const char*, const char*)’\n 57 | inline const char* stdTorchCheckMsgImpl(const char* /*msg*/, const char* args) {\n | ^~~~~~~~~~~~~~~~~~~~\n /usr/include/torch/headeronly/util/Exception.h:57:20: note: candidate expects 2 arguments, 9 provided\n /usr/include/torch/csrc/stable/tensor_inl.h: At global scope:\n /usr/include/torch/csrc/stable/tensor_inl.h:74:1: error: template-id ‘const_data_ptr<>’ for ‘const uint64_t* torch::stable::Tensor::const_data_ptr() const’ does not match any template declaration\n 74 | DEFINE_CAST(uint64_t, UInt64)\n | ^~~~~~~~~~~\n /usr/include/torch/csrc/stable/tensor_struct.h:184:12: note: candidates are: ‘template > const T* torch::stable::Tensor::const_data_ptr() const’\n 184 | const T* const_data_ptr() const;\n | ^~~~~~~~~~~~~~\n /usr/include/torch/csrc/stable/tensor_struct.h:156:15: note: ‘const void* torch::stable::Tensor::const_data_ptr() const’\n 156 | const void* const_data_ptr() const {\n | ^~~~~~~~~~~~~~\n In file included from /tmp/audio/src/libtorchaudio/utils.h:6:\n /usr/include/torch/headeronly/core/TensorAccessor.h:187:20: error: ‘enable_if_t’ in namespace ‘std’ does not name a template type [-Wtemplate-body]\n 187 | class = std::enable_if_t>>\n | ^~~~~~~~~~~\n /usr/include/torch/headeronly/core/TensorAccessor.h:1:1: note: ‘std::enable_if_t’ is defined in header ‘’; this is probably fixable by adding ‘#include ’\n +++ |+#include \n 1 | #pragma once\n /usr/include/torch/headeronly/core/TensorAccessor.h:187:31: error: expected ‘>’ before ‘<’ token [-Wtemplate-body]\n 187 | class = std::enable_if_t>>\n | ^\n /usr/include/torch/headeronly/core/TensorAccessor.h: In constructor ‘torch::headeronly::detail::GenericPackedTensorAccessorBase::GenericPackedTensorAccessorBase(PtrType, const index_t*, const index_t*)’:\n /usr/include/torch/headeronly/core/TensorAccessor.h:180:10: error: ‘copy’ is not a member of ‘std’ [-Wtemplate-body]\n 180 | std::copy(sizes_, sizes_ + N, std::begin(this->sizes_));\n | ^~~~\n /usr/include/torch/headeronly/core/TensorAccessor.h:180:40: error: ‘begin’ is not a member of ‘std’ [-Wtemplate-body]\n 180 | std::copy(sizes_, sizes_ + N, std::begin(this->sizes_));\n | ^~~~~\n /usr/include/torch/headeronly/core/TensorAccessor.h:1:1: note: ‘std::begin’ is defined in header ‘’; this is probably fixable by adding ‘#include ’\n +++ |+#include \n 1 | #pragma once\n /usr/include/torch/headeronly/core/TensorAccessor.h:181:10: error: ‘copy’ is not a member of ‘std’ [-Wtemplate-body]\n 181 | std::copy(strides_, strides_ + N, std::begin(this->strides_));\n | ^~~~\n /usr/include/torch/headeronly/core/TensorAccessor.h:181:44: error: ‘begin’ is not a member of ‘std’ [-Wtemplate-body]\n 181 | std::copy(strides_, strides_ + N, std::begin(this->strides_));\n | ^~~~~\n /usr/include/torch/headeronly/core/TensorAccessor.h:181:44: note: ‘std::begin’ is defined in header ‘’; this is probably fixable by adding ‘#include ’\n /usr/include/torch/headeronly/core/TensorAccessor.h: At global scope:\n /usr/include/torch/headeronly/core/TensorAccessor.h:253:20: error: ‘enable_if_t’ in namespace ‘std’ does not name a template type [-Wtemplate-body]\n 253 | class = std::enable_if_t>>\n | ^~~~~~~~~~~\n /usr/include/torch/headeronly/core/TensorAccessor.h:253:15: note: ‘std::enable_if_t’ is defined in header ‘’; this is probably fixable by adding ‘#include ’\n 253 | class = std::enable_if_t>>\n | ^~~\n /usr/include/torch/headeronly/core/TensorAccessor.h:253:31: error: expected ‘>’ before ‘<’ token [-Wtemplate-body]\n 253 | class = std::enable_if_t>>\n | ^\n /usr/include/torch/headeronly/core/TensorAccessor.h: In member function ‘torch::headeronly::detail::GenericPackedTensorAccessor torch::headeronly::detail::GenericPackedTensorAccessor::transpose(index_t, index_t) const’:\n /usr/include/torch/headeronly/core/TensorAccessor.h:301:10: error: ‘swap’ is not a member of ‘std’ [-Wtemplate-body]\n 301 | std::swap(result.strides_[dim1], result.strides_[dim2]);\n | ^~~~\n /usr/include/torch/headeronly/core/TensorAccessor.h:302:10: error: ‘swap’ is not a member of ‘std’ [-Wtemplate-body]\n 302 | std::swap(result.sizes_[dim1], result.sizes_[dim2]);\n | ^~~~\n /usr/include/torch/headeronly/core/TensorAccessor.h: At global scope:\n /usr/include/torch/headeronly/core/TensorAccessor.h:342:20: error: ‘enable_if_t’ in namespace ‘std’ does not name a template type [-Wtemplate-body]\n 342 | class = std::enable_if_t>>\n | ^~~~~~~~~~~\n /usr/include/torch/headeronly/core/TensorAccessor.h:342:15: note: ‘std::enable_if_t’ is defined in header ‘’; this is probably fixable by adding ‘#include ’\n 342 | class = std::enable_if_t>>\n | ^~~\n /usr/include/torch/headeronly/core/TensorAccessor.h:342:31: error: expected ‘>’ before ‘<’ token [-Wtemplate-body]\n 342 | class = std::enable_if_t>>\n | ^\n /usr/include/torch/headeronly/core/TensorAccessor.h: In constructor ‘torch::headeronly::detail::HeaderOnlyIndexBoundsCheck::HeaderOnlyIndexBoundsCheck(index_t)’:\n /usr/include/torch/headeronly/core/TensorAccessor.h:387:5: error: ‘runtime_error’ is not a member of ‘std’ [-Wtemplate-body]\n 387 | STD_TORCH_CHECK(\n | ^~~~~~~~~~~~~~~\n /usr/include/torch/headeronly/core/TensorAccessor.h:1:1: note: ‘std::runtime_error’ is defined in header ‘’; this is probably fixable by adding ‘#include ’\n +++ |+#include \n 1 | #pragma once\n /tmp/audio/src/libtorchaudio/utils.h: In function ‘T torchaudio::util::max(const torch::stable::Tensor&)’:\n /tmp/audio/src/libtorchaudio/utils.h:16:12: error: ‘nullopt’ is not a member of ‘std’ [-Wtemplate-body]\n 16 | std::nullopt,\n | ^~~~~~~\n /tmp/audio/src/libtorchaudio/utils.h:7:1: note: ‘std::nullopt’ is defined in header ‘’; this is probably fixable by adding ‘#include ’\n 6 | #include \n +++ |+#include \n 7 |\n /tmp/audio/src/libtorchaudio/utils.h: At global scope:\n /tmp/audio/src/libtorchaudio/utils.h:23:6: error: ‘optional’ in namespace ‘std’ does not name a template type\n 23 | std::optional cuda_version();\n | ^~~~~~~~\n /tmp/audio/src/libtorchaudio/utils.h:23:1: note: ‘std::optional’ is defined in header ‘’; this is probably fixable by adding ‘#include ’\n 23 | std::optional cuda_version();\n | ^~~\n /tmp/audio/src/libtorchaudio/utils.cpp:17:6: error: ‘optional’ in namespace ‘std’ does not name a template type\n 17 | std::optional cuda_version() {\n | ^~~~~~~~\n /tmp/audio/src/libtorchaudio/utils.cpp:5:1: note: ‘std::optional’ is defined in header ‘’; this is probably fixable by adding ‘#include ’\n 4 | #include \n +++ |+#include \n 5 | #endif\n ninja: build stopped: subcommand failed.\n Traceback (most recent call last):\n File \"/usr/lib64/python3.12/site-packages/torch/utils/cpp_extension.py\", line 2893, in _run_ninja_build\n subprocess.run(\n File \"/usr/lib64/python3.12/subprocess.py\", line 571, in run\n raise CalledProcessError(retcode, process.args,\n subprocess.CalledProcessError: Command '['ninja', '-v']' returned non-zero exit status 1.\n \n The above exception was the direct cause of the following exception:\n \n Traceback (most recent call last):\n File \"/usr/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py\", line 389, in \n main()\n File \"/usr/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py\", line 373, in main\n json_out[\"return_val\"] = hook(**hook_input[\"kwargs\"])\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/usr/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py\", line 303, in build_editable\n return hook(wheel_directory, config_settings, metadata_directory)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/build_meta.py\", line 474, in build_editable\n return self._build_with_temp_dir(\n ^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/build_meta.py\", line 410, in _build_with_temp_dir\n self.run_setup()\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/build_meta.py\", line 520, in run_setup\n super().run_setup(setup_script=setup_script)\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/build_meta.py\", line 317, in run_setup\n exec(code, locals()) # noqa: S102 # exec is intentional here\n ^^^^^^^^^^^^^^^^^^^^\n File \"\", line 148, in \n File \"\", line 103, in _main\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/__init__.py\", line 117, in setup\n return distutils.core.setup(**attrs) # type: ignore[return-value]\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/_distutils/core.py\", line 168, in setup\n return run_commands(dist)\n ^^^^^^^^^^^^^^^^^^\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/_distutils/core.py\", line 184, in run_commands\n dist.run_commands()\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/_distutils/dist.py\", line 1028, in run_commands\n self.run_command(cmd)\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/dist.py\", line 1106, in run_command\n super().run_command(command)\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/_distutils/dist.py\", line 1047, in run_command\n cmd_obj.run()\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/command/editable_wheel.py\", line 142, in run\n self._create_wheel_file(bdist_wheel)\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/command/editable_wheel.py\", line 352, in _create_wheel_file\n files, mapping = self._run_build_commands(dist_name, unpacked, lib, tmp)\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/command/editable_wheel.py\", line 275, in _run_build_commands\n self._run_build_subcommands()\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/command/editable_wheel.py\", line 302, in _run_build_subcommands\n self.run_command(name)\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/_distutils/cmd.py\", line 342, in run_command\n self.distribution.run_command(command)\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/dist.py\", line 1106, in run_command\n super().run_command(command)\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/_distutils/dist.py\", line 1047, in run_command\n cmd_obj.run()\n File \"/usr/lib/python3.12/site-packages/scikit_build_core/setuptools/build_cmake.py\", line 870, in run\n super().run()\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/command/build_ext.py\", line 95, in run\n _build_ext.run(self)\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/_distutils/command/build_ext.py\", line 382, in run\n self.build_extensions()\n File \"/usr/lib64/python3.12/site-packages/torch/utils/cpp_extension.py\", line 1289, in build_extensions\n super().build_extensions()\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/_distutils/command/build_ext.py\", line 498, in build_extensions\n self._build_extensions_serial()\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/_distutils/command/build_ext.py\", line 524, in _build_extensions_serial\n self.build_extension(ext)\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/command/build_ext.py\", line 260, in build_extension\n _build_ext.build_extension(self, ext)\n File \"/usr/lib64/python3.12/site-packages/Cython/Distutils/build_ext.py\", line 140, in build_extension\n super().build_extension(ext)\n File \"/home/geremia/.local/lib/python3.12/site-packages/setuptools/_distutils/command/build_ext.py\", line 585, in build_extension\n objects = self.compiler.compile(\n ^^^^^^^^^^^^^^^^^^^^^^\n File \"/usr/lib64/python3.12/site-packages/torch/utils/cpp_extension.py\", line 1027, in unix_wrap_ninja_compile\n _write_ninja_file_and_compile_objects(\n File \"/usr/lib64/python3.12/site-packages/torch/utils/cpp_extension.py\", line 2475, in _write_ninja_file_and_compile_objects\n _run_ninja_build(\n File \"/usr/lib64/python3.12/site-packages/torch/utils/cpp_extension.py\", line 2910, in _run_ninja_build\n raise RuntimeError(message) from e\n RuntimeError: Error compiling objects for extension\n An error occurred when building editable wheel for torchaudio.\n See debugging tips in: https://setuptools.pypa.io/en/latest/userguide/development_mode.html#debugging-tips\n [end of output]\n \n note: This error originates from a subprocess, and is likely not a problem with pip.\n ERROR: Failed building editable for torchaudio\nFailed to build torchaudio\nerror: failed-wheel-build-for-install\n\n× Failed to build installable wheels for some pyproject.toml based projects\n╰─> torchaudio\n```\n\n[details=\"collect_env.py output\"]\n```\nCollecting environment information...\nPyTorch version: 2.13.0a0\nIs debug build: False\nCUDA used to build PyTorch: 13.3\nROCM used to build PyTorch: N/A\n\nOS: Slackware Linux (x86_64)\nGCC version: (GCC) 15.3.0\nClang version: 22.1.8\nCMake version: version 4.4.3\nLibc version: glibc-2.43\n\nPython version: 3.12.14 (main, Aug 13 2026, 15:48:25) [GCC 15.3.0] (64-bit runtime)\nPython platform: Linux-7.2.0-x86_64-AMD_Ryzen_Threadripper_2990WX_32-Core_Processor-with-glibc2.43\nIs CUDA available: True\nCUDA runtime version: 13.3.73\nCUDA_MODULE_LOADING set to: \nGPU models and configuration: GPU 0: Quadro RTX 4000\nNvidia driver version: Could not collect\ncuDNN version: Could not collect\nIs XPU available: False\nHIP runtime version: N/A\nMIOpen runtime version: N/A\nIs XNNPACK available: False\nCaching allocator config: N/A\n\nCPU:\nArchitecture: x86_64\nCPU op-mode(s): 32-bit, 64-bit\nAddress sizes: 43 bits physical, 48 bits virtual\nByte Order: Little Endian\nCPU(s): 64\nOn-line CPU(s) list: 0-63\nVendor ID: AuthenticAMD\nModel name: AMD Ryzen Threadripper 2990WX 32-Core Processor\nCPU family: 23\nModel: 8\nThread(s) per core: 2\nCore(s) per socket: 32\nSocket(s): 1\nStepping: 2\nMicrocode version: 0x800820d\nFrequency boost: disabled\nCPU(s) scaling MHz: 52%\nCPU max MHz: 4200.0000\nCPU min MHz: 2200.0000\nBogoMIPS: 5999.10\nFlags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid amd_dcm aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb hw_pstate ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt sha_ni xsaveopt xsavec xgetbv1 clzero xsaveerptr arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif overflow_recov succor smca sev sev_es\nVirtualization: AMD-V\nL1d cache: 1 MiB (32 instances)\nL1i cache: 2 MiB (32 instances)\nL2 cache: 16 MiB (32 instances)\nL3 cache: 64 MiB (8 instances)\nNUMA node(s): 4\nNUMA node0 CPU(s): 0-7,32-39\nNUMA node1 CPU(s): 16-23,48-55\nNUMA node2 CPU(s): 8-15,40-47\nNUMA node3 CPU(s): 24-31,56-63\nVulnerability Gather data sampling: Not affected\nVulnerability Ghostwrite: Not affected\nVulnerability Indirect target selection: Not affected\nVulnerability Itlb multihit: Not affected\nVulnerability L1tf: Not affected\nVulnerability Mds: Not affected\nVulnerability Meltdown: Not affected\nVulnerability Mmio stale data: Not affected\nVulnerability Old microcode: Not affected\nVulnerability Reg file data sampling: Not affected\nVulnerability Retbleed: Mitigation; untrained return thunk; SMT vulnerable\nVulnerability Spec rstack overflow: Mitigation; Safe RET\nVulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl\nVulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization\nVulnerability Spectre v2: Mitigation; Retpolines; IBPB conditional; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected\nVulnerability Srbds: Not affected\nVulnerability Tsa: Not affected\nVulnerability Tsx async abort: Not affected\nVulnerability Vmscape: Mitigation; IBPB before exit to userspace\n\nVersions of relevant libraries:\n[pip3] flake8==6.1.0\n[pip3] mypy_extensions==1.1.0\n[pip3] numpy==2.5.2\n[pip3] onnxruntime==1.28.0\n[pip3] onnxruntime-gpu==1.28.0.dev20260722004\n[pip3] torch==2.11.0a0+gitunknown\n[conda] Could not collect\n```\n\n[/details]","reference_answer":"Well, it ended up I didn't need to compile `libtorchaudio.so` for the apps I'm using that require `torchaudio`; I just needed the Python bindings, no C++ library.\n\nI built Python-only `torchaudio` successfully with:\n```patch\ndiff --git a/setup.py b/setup.py\nindex 8030c54..22468a5 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -134,7 +134,7 @@ def _main():\n ],\n packages=find_packages(where=\"src\"),\n package_dir={\"\": \"src\"},\n- ext_modules=setup_helpers.get_ext_modules(),\n+ ext_modules=[],\n cmdclass={\n \"build_ext\": setup_helpers.get_build_ext(),\n \"clean\": clean,\n```\n🎩-tip to Google Gemini:\n\n> If you only need TorchAudio for I/O (`torchaudio.load`), audio processing transforms (`MelSpectrogram`, `Resample`, `Spectrogram`, `MFCC`), or neural networks, **you do not need to compile `libtorchaudio.so`**. TorchAudio's Python API delegates all GPU tensor operations directly to PyTorch's C++/CUDA backend.","needs_clarification":false,"thread_id":225350,"url":"https://discuss.pytorch.org/t/errors-building-torchaudio-with-pytorch-2-13-0-cuda-13-3-1-gcc-15-3-0/225350","created_at":"2026-08-31T04:06:01.288000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[4],"answer_authors":["Geremia"],"answered_by_ptrblck":false} {"question":"Multi label classification accuracy calculation\n\nHello, I have a dataset with images and a tensor of multi labels in one hot encoding. During the training I am not able to calculate the accuracy, when I print the predictions for the batch what I am getting is a single number with the id of the label (Ex: 54) but I am expecting to get a one hot tensor with more than one class activated. I am doing something very wrong.\n\nThis is my training loop:\n\n```python\nfor _ in range(cfg.num_rounds):\n round_count = round_count+1\n epoch_count = 0\n for _ in range(cfg.num_epochs):\n epoch_count = epoch_count+1\n train_metric = evaluate.load('roc_auc', 'multilabel')\n running_loss = 0.\n for batch in trainloader:\n optimizer.zero_grad()\n outputs = model(batch[\"image_name\"].to(device))\n labels = batch[\"image_labels\"].to(device)\n loss = criterion(outputs, labels)\n\n loss.backward()\n optimizer.step()\n\n total += labels.size(0)\n correct += (torch.max(outputs.data, 1)[1] == labels).sum().item()\n\n # loss and metric over 1 epoch\nprint(\"loss: \", loss.item(), \"accuracy: \", correct / total)\n```\n\nAnd this is my NN:\n\n```python\nclass ResNet(nn.Module):\n \"\"\"Model (simple CNN adapted from 'PyTorch: A 60 Minute Blitz')\"\"\"\n\n def __init__(self) -> None:\n super(ResNet, self).__init__()\n self.body = resnet34()\n self.head = nn.Sequential(\n BasicBlock(512, 512),\n nn.AdaptiveAvgPool2d((1, 1)),\n nn.Flatten(),\n nn.Linear(512, 179),\n )\n self.body = nn.Sequential(*list(self.body.children())[:-2])\n body_layer4 = list(self.body.children())[-1]\n self.body = nn.Sequential(*list(self.body.children())[:-1])\n self.body.layer4 = nn.Sequential(*list(body_layer4.children())[:-1])\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\"Forward inputs through the model.\"\"\"\n x = self.body(x)\n return self.head(x)\n```\n\n\"image_name\" is the PIL image and the \"image_labels\" are the 179 classes in one hot.\n\nCould you help me?\n\nThank you!","reference_answer":"Hi,\nI think the problem is mostly in\n```python\ncorrect += (torch.max(outputs.data, 1)[1] == labels).sum().item()\n```\nyour last layer outputs 1 number per label (between -inf and +inf), which corresponds to the score that your model assigns to each label. Then, your `torch.max(outputs.data, 1)[1]` computes which label has the highest score for each element of the batch. This is already not what you want, since you want to keep multiple labels per output.\n\nThere are several ways of deciding which labels are considered positive by your model. You could for example decide that every output > 0 is positive:\n\n```python\npreds = (outputs > 0).long()\ncorrect += (preds == labels).all(dim=1).sum().item()\ntotal += labels.size(0)\n```\nThis means that a prediction is considered correct only if all of its 179 labels are predicted correctly. So the accuracy will be the number of samples for which all 179 labels are correctly predicted (I would thus assume you'll get an accuracy of 0 for a long time before your model starts to be good enough).\n\nMaybe the accuracy will become a bit more informative if it's computed at the label granularity:\n```\ncorrect += (preds == labels).sum().item()\ntotal += labels.numel()\n```\nThis will instead compute the number of correct labels divided by the total number of labels to predict.","needs_clarification":false,"thread_id":225513,"url":"https://discuss.pytorch.org/t/multi-label-classification-accuracy-calculation/225513","created_at":"2026-10-08T18:14:41.496000Z","tier":"gold","answer_origin":"verbatim","answer_post_numbers":[2],"answer_authors":["valerian.rey"],"answered_by_ptrblck":false}