# RuntimeError：DataLoader工作进程（pid 12345）pin_memory()：CUDA错误：无效的设备上下文

- **ID:** `pytorch/dataloader-pin-memory-cuda`
- **领域:** pytorch
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

使用pin_memory=True的DataLoader会生成工作进程，这些进程尝试从fork的子进程中使用CUDA，导致设备上下文无效，因为CUDA在初始化后不支持fork。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| torch>=1.6.0 | active | — | — |
| CUDA>=11.0 | active | — | — |

## 解决方案

1. ```
   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
   ```
3. ```
   Move CUDA initialization after DataLoader creation or use single-process loading with num_workers=0
   ```

## 无效尝试

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