ValueError: 您传递的 `quantization_config` 中 `bnb_4bit_compute_dtype=torch.float16`,但模型权重以 `torch.float32` 加载。这可能导致数值不稳定。
ValueError: You passed `quantization_config` with `bnb_4bit_compute_dtype=torch.float16` but the model weights are loaded in `torch.float32`. This may cause numerical instability.
ID: huggingface/quantization-bnb-4bit-dtype-mismatch
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| bitsandbytes>=0.41.0 | active | — | — | — |
| transformers>=4.36.0 | active | — | — | — |
| torch>=2.0.0 | active | — | — | — |
根因分析
通过 bitsandbytes 使用 4 位量化时,矩阵乘法的计算数据类型(bnb_4bit_compute_dtype)必须与模型权重的数据类型匹配。float16 计算与 float32 权重之间的不匹配可能导致梯度错误或 NaN 损失。
English
When using 4-bit quantization via bitsandbytes, the compute dtype for matrix multiplications (bnb_4bit_compute_dtype) must match the dtype of the model weights. A mismatch between float16 compute and float32 weights can cause incorrect gradients or NaN losses.
官方文档
https://huggingface.co/docs/transformers/main_classes/quantization#4-bit-quantization解决方案
-
Set both `bnb_4bit_compute_dtype` and `torch_dtype` to the same value (e.g., `torch.float16`) when loading the model. Use `from_pretrained(..., torch_dtype=torch.float16, quantization_config=quant_config)`.
-
Alternatively, set `bnb_4bit_compute_dtype=torch.float32` and load the model with `torch_dtype=torch.float32` (default) to avoid precision mismatch.
无效尝试
常见但无效的做法:
-
40% 失败
Changing `bnb_4bit_compute_dtype` to `torch.float32` without also adjusting the model's `torch_dtype` may still leave the model in float16 if it was originally loaded that way.
-
50% 失败
Using `model.half()` after loading to force float16 can break the quantized modules and cause CUDA errors.