
CUDA out of memory
快速结论:此报错在 transformers v5 中使用 BitsAndBytes 4-bit 量化加载大模型时触发。原因是新版 core_model_loading.py 在量化前错误地将全精度张量直接分配到 GPU,导致显存溢出。优先排查 transformers 版本是否为 v5 以及是否启用了 4-bit 量化。
问题场景
用户在 transformers 5.0.0.dev0(安装自 main 分支)中使用 AutoModelForCausalLM 配合 BitsAndBytesConfig 加载 4-bit 量化模型时,遇到 OOM。相同配置在 transformers 4.48 上可正常加载(约 9GB 显存),但在 v5 中显存飙升至 15GB+ 后崩溃。影响模型包括 Qwen3.5-27B、Qwen3-32B 及 junotrade/phi4v1(~14B 参数)。
报错原文
Loading weights: 53%|████| 194/363 [00:02<00:01, 96.85it/s]
torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 176.00 MiB.
GPU 0 has a total capacity of 15.47 GiB of which 127.88 MiB is free.
原因分析
根本原因是 transformers v5 中的 core_model_loading.py 存在逻辑缺陷。在 convert_and_load_state_dict_in_model 函数中:
- 第 1043 行正确设置了
mapping.quantization_operation(当参数需要量化时) - 但第 1079-1080 行直接调用
spawn_materialize将张量完整加载到 GPU,忽略量化操作 - 第 1098 行执行量化时,张量已因全精度上 GPU 而 OOM
量化操作本应在 CPU 上处理完再移动到 GPU,但新版加载系统跳过了这一设备放置逻辑。
环境排查
- transformers 版本:5.0.0.dev0(来自 main 分支)或受影响的其他 v5 版本
- bitsandbytes 版本:0.49.0
- torch 版本:2.9.1+cu128
- Python 版本:3.12
- GPU 型号及显存:NVIDIA GeForce RTX 5080 (16GB),但问题在 48GB 显存上也会出现
- 操作系统:Ubuntu 24.04
解决步骤
- 临时方案 A——官方指定修复(可优先尝试):在
core_model_loading.py文件第 1079-1080 行附近,检查mapping.quantization_operation是否为None。若非None,则强制将param_device设置为"cpu",使张量先在 CPU 上完成量化再移到 GPU。修改示例如下:if future_or_tensor is None: param_device = get_device(device_map, renamed_key, valid_torch_device=True) if mapping.quantization_operation is not None: param_device = "cpu" future_or_tensor = spawn_materialize(thread_pool, tensor, param_device, _dtype) - 临时方案 B(不推荐):先设置
device_map="cpu"加载模型,加载完成后调用model.cuda()。但此方案加载速度极慢,不适合大模型。 - 等待主线修复:Issue 已于 2026-03-18 由维护者重新开启并关闭(标记为 resolved),请升级 transformers 到后续修复版本。
验证方法
应用补丁或升级后,运行同样的 4-bit 量化加载脚本,确认:
- 模型成功加载(应显示 280 个 Linear4bit 层)
- 加载后显存占用约为 8.88 GB(符合 4-bit 预期)
- 模型在 GPU 上正常执行推理



![RuntimeError: shape '[32, 64, 576]' is invalid for input of size 1343488](https://www.chat-gpts.plus/wp-content/uploads/2026/07/48896-f8250d36-768x403.jpg)