# 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`
- **Domain:** huggingface
- **Category:** config_error
- **Verification:** ai_generated
- **Fix Rate:** 88%

## 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.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| bitsandbytes>=0.41.0 | active | — | — |
| transformers>=4.36.0 | active | — | — |
| torch>=2.0.0 | active | — | — |

## Workarounds

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

## Dead Ends

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