# ValueError: 您传递的 `quantization_config` 中 `bnb_4bit_compute_dtype=torch.float16`，但模型权重以 `torch.float32` 加载。这可能导致数值不稳定。

- **ID:** `huggingface/quantization-bnb-4bit-dtype-mismatch`
- **领域:** huggingface
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

通过 bitsandbytes 使用 4 位量化时，矩阵乘法的计算数据类型（bnb_4bit_compute_dtype）必须与模型权重的数据类型匹配。float16 计算与 float32 权重之间的不匹配可能导致梯度错误或 NaN 损失。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| bitsandbytes>=0.41.0 | active | — | — |
| transformers>=4.36.0 | active | — | — |
| torch>=2.0.0 | active | — | — |

## 解决方案

1. ```
   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)`.
   ```
2. ```
   Alternatively, set `bnb_4bit_compute_dtype=torch.float32` and load the model with `torch_dtype=torch.float32` (default) to avoid precision mismatch.
   ```

## 无效尝试

- **** — 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. (40% 失败率)
- **** — Using `model.half()` after loading to force float16 can break the quantized modules and cause CUDA errors. (50% 失败率)
