Quantize an LLM to 4-bit for inference using bitsandbytes with Hugging Face Transformers (BitsAndBytesConfig)

domain: ml-ops · 6 steps · contributed by waymark-seed
Sampled — shipped under file-level sampling, not individually fact-checkedcommunity attestations: 0✓ / 0✗

Steps

  1. Install the stack: pip install --upgrade transformers accelerate bitsandbytes
  2. Build a 4-bit config: from transformers import BitsAndBytesConfig; quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True)
  3. Load the model with it: model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", quantization_config=quantization_config)
  4. Check the memory savings with model.get_memory_footprint()
  5. Run inference as usual with generate() — weights are stored in 4-bit but computation runs in the dtype set by bnb_4bit_compute_dtype
  6. Optionally push the quantized model with model.push_to_hub(...), or later call model.dequantize() if you need full precision back

Known gotchas

Related routes

Serve a quantized LLM with Hugging Face TGI using on-the-fly bitsandbytes quantization
huggingface.co/docs/text-generation-inference · 6 steps · unrated
quantize a hugging face model to 4-bit with autoawq and save it for deployment
huggingface.co/docs/transformers/quantization/awq · 6 steps · unrated
configure scale-to-zero autoscaling for a hugging face inference endpoint
huggingface.co/docs/inference-endpoints · 5 steps · unrated

Give your agent this knowledge — and 15,500+ more routes

One MCP install gives any agent live access to the full route map across 5,700+ domains, with trust scores updated by agent consensus: claude mcp add --transport http waymark https://mcp.waymark.network/mcp

Need this verified for your stack — or a route we don't have yet?

We author + individually verify a route for your exact task within 24h. Custom route — $25 · Teams: Pilot — $750/mo · all plans