CUDA error: device-side assert triggered

cudaErrorAsserterror 710sticky

In PyTorch the same failure appears as RuntimeError: CUDA error: device-side assert triggered.

This error is sticky

After it happens, every later CUDA call in the same process fails with the same error, even ones that are correct. Find the first failing call, fix it, and restart the program (or the notebook kernel). Resetting the error is not possible.

Common causes

A class label is out of range

cross_entropy and nll_loss need every target in [0, num_classes). Labels that start at 1, a -1 used for padding (use ignore_index), or a final layer with too few outputs all trigger Assertion t >= 0 && t < n_classes failed.

A token or embedding id is too large

nn.Embedding(num_embeddings, dim) accepts ids up to num_embeddings - 1. A tokenizer with a bigger vocabulary than the model, or new special tokens added without resizing the embeddings, triggers Assertion srcIndex < srcSelectDimSize failed.

binary_cross_entropy got values outside [0, 1]

F.binary_cross_entropy expects probabilities. Passing raw logits fails with Assertion input_val >= zero && input_val <= one failed. Use binary_cross_entropy_with_logits instead.

Your own kernel asserts

In CUDA C++, assert() from <cassert> works in device code. When it fails, the kernel stops and the next synchronizing call returns cudaErrorAssert.

Reproduce it

Press Run to execute this on a real NVIDIA GPU in the playground.

Repro: a label outside the number of classes
main.py
1234567
import torch
import torch.nn.functional as F

logits = torch.randn(4, 3, device="cuda")          # 3 classes: 0, 1, 2
target = torch.tensor([0, 2, 1, 3], device="cuda")  # 3 is out of range
loss = F.cross_entropy(logits, target)
print(loss.item())
Output on an NVIDIA T4
../aten/src/ATen/native/cuda/Loss.cu:250: nll_loss_forward_reduce_cuda_kernel_2d: block: [0,0,0], thread: [3,0,0] Assertion `t >= 0 && t < n_classes` failed.
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print(loss.item())
RuntimeError: CUDA error: device-side assert triggered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

Fix

Fixed: validate labels before the loss
main.py
1234567891011121314
import torch
import torch.nn.functional as F

logits = torch.randn(4, 3, device="cuda")
target = torch.tensor([0, 2, 1, 3], device="cuda")

num_classes = logits.shape[1]
bad = (target < 0) | (target >= num_classes)
if bad.any():
    print(f"labels must be in [0, {num_classes}), found {target[bad].tolist()}")
    target = target.clamp(0, num_classes - 1)   # or fix the data / the model's output size

loss = F.cross_entropy(logits, target)
print("loss is finite:", torch.isfinite(loss).item())
Output on an NVIDIA T4
labels must be in [0, 3), found [3]
loss is finite: True

In PyTorch

Without the variable, the traceback points at loss.item(), the first line that waited for the GPU. With CUDA_LAUNCH_BLOCKING=1 every kernel runs synchronously, so it points at the cross_entropy call that actually failed. It slows everything down, so only use it while debugging. Moving the same tensors to the CPU gives a plain Python error instead: IndexError: Target 3 is out of bounds.

Get the real line with CUDA_LAUNCH_BLOCKING
main.py
12345678910
import os
os.environ["CUDA_LAUNCH_BLOCKING"] = "1"   # must be set before CUDA starts

import torch
import torch.nn.functional as F

logits = torch.randn(4, 3, device="cuda")
target = torch.tensor([0, 2, 1, 3], device="cuda")
loss = F.cross_entropy(logits, target)
print("never reached")
Output on an NVIDIA T4 (stack frames shortened)
../aten/src/ATen/native/cuda/Loss.cu:250: nll_loss_forward_reduce_cuda_kernel_2d: block: [0,0,0], thread: [3,0,0] Assertion `t >= 0 && t < n_classes` failed.
Traceback (most recent call last):
  File "main.py", line 9, in <module>
    loss = F.cross_entropy(logits, target)
  ...
RuntimeError: CUDA error: device-side assert triggered

Debugging checklist

  1. Scroll up: the line above the traceback, Assertion ... failed, names the kernel and the condition that broke.
  2. Rerun with CUDA_LAUNCH_BLOCKING=1 so the traceback points at the operation that failed, not a later one.
  3. Run the same batch on the CPU. PyTorch's CPU kernels raise a readable IndexError with the bad value.
  4. Print target.min(), target.max() and the model's output size (or the embedding's num_embeddings) right before the failing call.
  5. Restart the Python process or notebook kernel. Every CUDA call fails after a device-side assert.

FAQ

What does "Compile with TORCH_USE_CUDA_DSA" mean?

It refers to building PyTorch from source with device-side assertion tracking, which adds more detail to the message. You do not need it: the Assertion line above the traceback and CUDA_LAUNCH_BLOCKING=1 are enough to find the problem.

Why do I have to restart Jupyter after this error?

NVIDIA documents cudaErrorAssert as unrecoverable: the device cannot be used again and all existing allocations are invalid until the process is relaunched. Restarting the notebook kernel does that.

Does assert() work in my own CUDA kernels?

Yes. Include <cassert> and call assert() in device code. A failed assert prints the file, line, block and thread, and the next cudaDeviceSynchronize() returns cudaErrorAssert. Compiling with -DNDEBUG removes the checks.