huggingface config_error ai_generated true

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

Also available as: JSON · Markdown · 中文
88%Fix Rate
86%Confidence
1Evidence
2023-12-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
bitsandbytes>=0.41.0 active
transformers>=4.36.0 active
torch>=2.0.0 active

Root Cause

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.

generic

中文

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

Official Documentation

https://huggingface.co/docs/transformers/main_classes/quantization#4-bit-quantization

Workarounds

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

中文步骤

  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.

Dead Ends

Common approaches that don't work:

  1. 40% fail

    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.

  2. 50% fail

    Using `model.half()` after loading to force float16 can break the quantized modules and cause CUDA errors.