AI and LLM integration · Troubleshooting walkthrough
PyTorch training stops with a device-side assert on the GPU
Short answer
CUDA error: device-side assert triggered means a GPU kernel found a value outside its allowed range. In PyTorch 2.x common culprits are a class label outside 0 to C-1 for CrossEntropyLoss, a token id at or above the embedding size, or BCELoss inputs outside 0 to 1. Rerun with CUDA_LAUNCH_BLOCKING=1, then print that tensor's min and max.
A device-side assert means a GPU kernel checked its input, found a value outside the allowed range, and stopped. The traceback Python shows is usually misleading: GPU work runs asynchronously, so the error is reported at some later call, and the message itself says the stack trace might be incorrect.
The walk is: make the traceback honest, see which operation failed, print the range of that operation's input, and fix the value at its source. In practice the operation is almost always one of three: a classification loss, an embedding lookup or a binary cross-entropy.
The text you see
torch.AcceleratorError: CUDA error: device-side assert triggeredRuntimeError: CUDA error: device-side assert triggeredCompile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.Search for `cudaErrorAssert' in https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__TYPES.html for more information.CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
Stage 1
Make the traceback point at the real line
Force synchronous kernel launches. The traceback then ends at the operation that tripped the check rather than a later unrelated line. The PyTorch CUDA notes explain the asynchronous execution that causes the confusion.
Run again with blocking launches
CUDA_LAUNCH_BLOCKING=1 python train.py| Traceback ends in | Likely cause | What to print |
|---|---|---|
| The loss call (CrossEntropyLoss, NLLLoss) | A label outside 0 to C-1 | labels min and max, class count |
| An embedding forward pass | An id at or past the table size | input_ids max, vocab_size, len(tokenizer) |
| BCELoss | Outputs or targets outside 0 to 1 | outputs and targets min and max |
After this assert the process cannot be reused. Restart the script or the notebook kernel before testing a fix.
Stage 2
A label outside the class range
CrossEntropyLoss expects each target to be a class index in the range 0 to C-1, and the CUDA kernel behind it asserts that range. Only the ignore_index value, -100 by default, may fall outside. Labels stored as 1 to C, a class that exists only in the validation set, and padding marked -1 all break it.
Map labels to dense zero-based ids once, size the output layer to the count, and use ignore_index for positions that should not count.
Print the range, then build a dense label map
# just before loss = criterion(logits, labels)
print("labels", labels.min().item(), labels.max().item(), "classes", logits.shape[1])
classes = sorted(set(train_labels))
label_to_id = {c: i for i, c in enumerate(classes)}
labels = torch.tensor([label_to_id[c] for c in batch_labels], device="cuda")
model.classifier = torch.nn.Linear(hidden_size, len(classes))
criterion = torch.nn.CrossEntropyLoss(ignore_index=-100)Stage 3
Ids past the end of the embedding table
nn.Embedding holds num_embeddings rows, so valid indices run from 0 to num_embeddings - 1. An id beyond that trips the lookup kernel. With Hugging Face models the common path is adding tokens to the tokenizer without resizing the model, which leaves the new ids with no row to point at.
Compare the sizes, then resize after adding tokens
print(int(batch["input_ids"].max()), model.config.vocab_size, len(tokenizer))
tokenizer.add_tokens(["<ticket_id>", "<order_ref>"])
model.resize_token_embeddings(len(tokenizer))For a plain nn.Embedding, create it with num_embeddings set to the largest id plus one.
Stage 4
BCELoss fed raw scores
BCELoss takes probabilities and targets between 0 and 1, and its CUDA kernel asserts on both. A last layer that is a plain Linear produces unbounded scores, which trip the check on the first batch with a large value. Switch to BCEWithLogitsLoss, which applies the sigmoid inside the loss and is more stable numerically, and remove any sigmoid you added before it.
Inspect the range, then use the logits version
print(outputs.min().item(), outputs.max().item(), targets.min().item(), targets.max().item())
criterion = torch.nn.BCEWithLogitsLoss()
loss = criterion(outputs, targets.float())Stage 5
Catching it earlier next time
If every range check passes, report the operation named in the blocking traceback to the library, with a minimal script that reproduces it.
- Assert label and id ranges on the CPU in the data loader, where a bad value raises a readable Python error instead of a GPU assert.
- Call
resize_token_embeddingsin the same function that adds tokens. - Save the label-to-id map with the model and load it for inference, so a new class cannot arrive with an out-of-range id.
If you only keep one thing
- Run with CUDA_LAUNCH_BLOCKING=1 so the traceback names the real operation.
- The assert is nearly always a value outside a documented range: labels, ids, probabilities.
- Restart the process after the assert before testing again.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.