# RuntimeError: DataLoader worker (pid 12345) pin_memory(): CUDA error: invalid device context

- **ID:** `pytorch/dataloader-pin-memory-cuda`
- **Domain:** pytorch
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 88%

## Root Cause

DataLoader with pin_memory=True spawns workers that attempt to use CUDA from forked processes, causing invalid device context due to CUDA not supporting fork after initialization.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| torch>=1.6.0 | active | — | — |
| CUDA>=11.0 | active | — | — |

## Workarounds

1. **Set multiprocessing start method to 'spawn': torch.multiprocessing.set_start_method('spawn', force=True) before creating DataLoader** (95% success)
   ```
   Set multiprocessing start method to 'spawn': torch.multiprocessing.set_start_method('spawn', force=True) before creating DataLoader
   ```
2. **Use pin_memory=False in DataLoader and manually move tensors to GPU after loading** (85% success)
   ```
   Use pin_memory=False in DataLoader and manually move tensors to GPU after loading
   ```
3. **Move CUDA initialization after DataLoader creation or use single-process loading with num_workers=0** (90% success)
   ```
   Move CUDA initialization after DataLoader creation or use single-process loading with num_workers=0
   ```

## Dead Ends

- **** — Workers need CUDA context for pin_memory; hiding devices breaks the purpose. (80% fail)
- **** — More workers increase chance of CUDA context issues. (90% fail)
