PyTorch torch.OutOfMemoryError: CUDA out of memory

Batch size, sequence length, or retained autograd tensors exceeded GPU VRAM.

Runs locally in browser Free · No login Independently Verified 2026-11-25 v4.1.0
Identifier: PyTorch torch.OutOfMemoryError Platform: Python
Common Root Causes:
  • Batch size, sequence length, or retained autograd tensors exceeded GPU VRAM.

Interactive Diagnostic Checklist

Verified Solutions:
  1. Wrap inference in `torch.inference_mode()`, enable mixed precision (`bf16`), and reduce batch size with grad accumulation.
Safe Diagnostic Command:
nvidia-smi && check torch.cuda.memory_summary()
Warning: Verify configuration changes in staging or with dry-run flags (e.g. nginx -t) before reloading production services.

Technical Explanation

Batch size, sequence length, or retained autograd tensors exceeded GPU VRAM. Recommended diagnostic: `nvidia-smi && check torch.cuda.memory_summary()`. Remediation: Wrap inference in `torch.inference_mode()`, enable mixed precision (`bf16`), and reduce batch size with grad accumulation.

Worked Examples

  • Run `nvidia-smi && check torch.cuda.memory_summary()` to verify root cause before applying the remediation.

Limitations & Assumptions

  • Always verify configuration changes in staging or with dry-run flags (e.g. `nginx -t`) before reloading production services.

Source References & Verification

Resource ID: err-py-pytorch-cuda-oom · Independently verified: 2026-11-25

Related Resources