# torch.cuda.OutOfMemoryError：CUDA 内存不足。尝试分配 2.00 GiB。GPU 0 总容量为 79.15 GiB，其中 2.00 GiB 空闲。包括非阻塞分配，当前已分配：77.15 GiB。

- **ID:** `llm/vllm-cuda-oom-batch`
- **领域:** llm
- **类别:** resource_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

vLLM 的动态批处理按请求分配 KV 缓存块，在高并发或长序列下，累积分配超过 GPU 内存，即使模型权重本身可以容纳。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| vLLM 0.4.0 | active | — | — |
| PyTorch 2.2.0 | active | — | — |
| CUDA 12.1 | active | — | — |
| A100 80GB | active | — | — |
| H100 80GB | active | — | — |

## 解决方案

1. ```
   在 vLLM 配置中减少 `max_num_seqs`（例如从 256 减到 64）以限制并发请求。代码示例：`LLM(model='meta-llama/Llama-2-7b-hf', max_num_seqs=64)`。
   ```
2. ```
   减小 `max_model_len` 以限制序列长度，例如 `LLM(model='...', max_model_len=4096)`。这会减少每个序列的 KV 缓存大小。
   ```
3. ```
   在 vLLM 中启用 `enable_prefix_caching=True` 以重用常见前缀的 KV 缓存块，从而减少重复提示的内存使用。
   ```

## 无效尝试

- **** — The OOM is from KV cache allocation, not model weights. Even a 7B model can OOM with very long sequences or high concurrency. (50% 失败率)
- **** — vLLM manages its own memory pool and does not release KV cache blocks to PyTorch's cache; empty_cache has no effect on vLLM allocations. (90% 失败率)
- **** — vLLM uses tensor parallelism across GPUs, but KV cache is still per-GPU; adding GPUs without adjusting max_num_seqs or max_model_len may still OOM on each GPU. (70% 失败率)
