Same script works everywhere except on 4090. How to debug CUDA error?

I’ve encountered a very weird problem:
loss.backward() for my model works on every machine I have access to, namely V100 and 2080ti, but it just fails on the 4090, suggesting that:

In [2]: print(loss)
tensor(0.3055, device='cuda:1', grad_fn=<MeanBackward0>)

In [3]: loss.backward()
RuntimeError                              Traceback (most recent call last)
Cell In[3], line 1
----> 1 loss.backward()

File ~/bin/anaconda3/envs/torch2.0/lib/python3.10/site-packages/torch/, in Tensor.backward(self, gradient, retain_graph, create_graph, inputs)
    477 if has_torch_function_unary(self):
    478     return handle_torch_function(
    479         Tensor.backward,
    480         (self,),
    485         inputs=inputs,
    486     )
--> 487 torch.autograd.backward(
    488     self, gradient, retain_graph, create_graph, inputs=inputs
    489 )

File ~/bin/anaconda3/envs/torch2.0/lib/python3.10/site-packages/torch/autograd/, in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)
    195     retain_graph = create_graph
    197 # The reason we repeat same the comment below is that
    198 # some Python versions print out the first line of a multi-line function
    199 # calls in the traceback and some print out the last line
--> 200 Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
    201     tensors, grad_tensors_, retain_graph, create_graph, inputs,
    202     allow_unreachable=True, accumulate_grad=True)

RuntimeError: CUDA error: invalid argument
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

All their drivers and cuda are install with the same file, and the torch version is all 2.0 (1.x is also ok on v100 and 2080ti).

Another weird thing is that on my 4090 it seems only this type of model can’t backward loss. My model is a Conformer based u-net. For other models, including a Transformer based u-net, the loss seems can backward normally, but I’ve not done extensive test on many architectures.

I guess that this issue is most likely caused by the GPU or CUDA, but I can’t find any useful information. Does anyone have any clue? Thanks!

Could you post a minimal and executable code snippet reproducing the error as well as the output of python -m torch.utils.collect_env, please?

I find out that need_weights in forward of torch.nn.MultiheadAttention controls my issue.
If it is set to False, then backward() fails. Otherwise backward() succeeds. Also, when using CPU, this issue won’t happen no matter what value need_weights is set to.

Code snippet:

import os
import torch

device = torch.device('cuda:1')

sepLayer = torch.nn.MultiheadAttention(768, 2).to(device)

sepIn = torch.rand([4, 62, 768]).to(device)
sepTarget = torch.rand([4, 62, 768]).to(device)

sepOut, _ = sepLayer(sepIn, sepIn, sepIn, need_weights=False)

assert sepOut.shape == sepTarget.shape
loss = (sepTarget - sepOut).pow(2).mean()


(torch2.0) ➜  ~ python -m torch.utils.collect_env
Collecting environment information...
PyTorch version: 2.0.0
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04.1) 11.3.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.10.9 (main, Mar  1 2023, 18:23:06) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-72-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
GPU models and configuration:
GPU 0: NVIDIA GeForce RTX 4090
GPU 1: NVIDIA GeForce RTX 4090
GPU 2: NVIDIA GeForce RTX 4090
GPU 3: NVIDIA GeForce RTX 4090

Nvidia driver version: 530.30.02
cuDNN version: Could not collect
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Address sizes:                   46 bits physical, 57 bits virtual
Byte Order:                      Little Endian
CPU(s):                          128
On-line CPU(s) list:             0-127
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) Platinum 8377C CPU @ 3.00GHz
CPU family:                      6
Model:                           106
Thread(s) per core:              2
Core(s) per socket:              32
Socket(s):                       2
Stepping:                        6
CPU max MHz:                     3500.0000
CPU min MHz:                     800.0000
BogoMIPS:                        6000.00
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       3 MiB (64 instances)
L1i cache:                       2 MiB (64 instances)
L2 cache:                        80 MiB (64 instances)
L3 cache:                        108 MiB (2 instances)
NUMA node(s):                    2
NUMA node0 CPU(s):               0-31,64-95
NUMA node1 CPU(s):               32-63,96-127
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:          Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] mypy-extensions==0.4.3
[pip3] numpy==1.23.5
[pip3] numpydoc==1.5.0
[pip3] pytorch-lightning==2.0.2
[pip3] pytorch-metric-learning==2.1.1
[pip3] pytorch-wpe==0.0.1
[pip3] torch==2.0.0
[pip3] torch-audiomentations==0.11.0
[pip3] torch-complex==0.4.3
[pip3] torch-pitch-shift==1.2.4
[pip3] torchaudio==2.0.0
[pip3] torchmetrics==0.11.4
[pip3] torchvision==0.15.0
[conda] blas                      1.0                         mkl
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] mkl                       2021.4.0           h06a4308_640
[conda] mkl-service               2.4.0           py310h7f8727e_0
[conda] mkl_fft                   1.3.1           py310hd6ae3a3_0
[conda] mkl_random                1.2.2           py310h00e6091_0
[conda] numpy                     1.23.5          py310hd5efca6_0
[conda] numpy-base                1.23.5          py310h8e6c178_0
[conda] numpydoc                  1.5.0           py310h06a4308_0
[conda] pytorch                   2.0.0           py3.10_cuda11.8_cudnn8.7.0_0    pytorch
[conda] pytorch-cuda              11.8                 h7e8668a_3    pytorch
[conda] pytorch-lightning         2.0.2                    pypi_0    pypi
[conda] pytorch-metric-learning   2.1.1                    pypi_0    pypi
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] pytorch-wpe               0.0.1                    pypi_0    pypi
[conda] torch-audiomentations     0.11.0                   pypi_0    pypi
[conda] torch-complex             0.4.3                    pypi_0    pypi
[conda] torch-pitch-shift         1.2.4                    pypi_0    pypi
[conda] torchaudio                2.0.0               py310_cu118    pytorch
[conda] torchmetrics              0.11.4                   pypi_0    pypi
[conda] torchtriton               2.0.0                     py310    pytorch
[conda] torchvision               0.15.0              py310_cu118    pytorch

Could you update to the latest nightly release and check if you would still run into the same error as I believe the BetterTransformer code path should already be fixed for sm_89.