The bitsandbytes library provides quantization tools for LLMs through a lightweight Python wrapper, and it offers two main features: LLM.int8, an 8-bit method that dynamically preserves higher precision for critical computations, and QLoRA, a 4-bit technique that compresses models further while keeping them trainable. To load a model quantized, you pass a BitsAndBytesConfig to from_pretrained. Use 8-bit when you want the safest saving, and 4-bit when memory is the binding constraint.
What you need
- Python with transformers, accelerate and bitsandbytes installed
- An NVIDIA GPU that meets the minimum for the method you choose
- The model id and a note of how much GPU memory you have
Step 1: Choose 8-bit or 4-bit and set the config
For 8-bit, use BitsAndBytesConfig with load_in_8bit=True; for 4-bit, use load_in_4bit=True with bnb_4bit_quant_type set to nf4 for training or fp4, and set bnb_4bit_compute_dtype to bfloat16 to speed up computation.
Step 2: Load with device_map auto
Load the model with from_pretrained, device_map set to auto and the quantization config passed in, so the weights are distributed efficiently across the available GPUs.
Step 3: Check the memory footprint and test
Print the model memory footprint with get_memory_footprint and confirm it fits your GPU. Then run a short generation on a prompt you know, and check the answer is coherent before any longer run.
Worked example: synthetic bitsandbytes load check
The table below is a synthetic example. It shows the expected result of loading a model quantized; no model was loaded.
| Setting | Value | Result |
|---|---|---|
| Model | Llama-2-13b | 13B parameters |
| 8-bit load | About 13 GB | Fits 24 GB GPU |
| 4-bit NF4 load | About 7 GB | Fits with room |
| Test generation | Coherent short answer | Pass |
Expected result (UNTESTED). the 13B model loads in 8-bit at about 13 GB and in 4-bit at about 7 GB, and a short generation is coherent. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- LLM.int8 needs an NVIDIA Turing GPU or newer; NF4 and FP4 need Pascal or newer.
- Once a model is quantized to 8-bit, you cannot push the quantized weights to the Hub unless you use the latest Transformers and bitsandbytes.
- 8-bit and 4-bit training is only supported for training extra parameters, not for full fine-tuning.
- Check the memory footprint with get_memory_footprint; the config alone does not prove the model fits.
