Bitsandbytes is a Python library that provides k-bit optimizers and matrix multiplication routines, primarily designed for making large language models (LLMs) more accessible through quantization in PyTorch. It focuses on dramatically reducing memory consumption for both inference and training via 8-bit and 4-bit quantization, including techniques like LLM.int8() and QLoRA. The library is actively maintained, currently at version 0.49.2, and frequently updated.
Install & Compatibility
Where this runs
tested against v0.42.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
py 3.10
8/12 runs
8/12 runs
py 3.11
8/12 runs
8/12 runs
py 3.12
8/12 runs
8/12 runs
py 3.13
8/12 runs
8/12 runs
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
bnb.nn.Linear8bitLt
✓ import bitsandbytes as bnb
from bitsandbytes.nn import Linear8bitLt
bnb.optim.Adam8bit
✓ import bitsandbytes as bnb
from bitsandbytes.optim import Adam8bit
BitsAndBytesConfig
✓ from transformers import BitsAndBytesConfig
Commonly used when integrating with Hugging Face Transformers for quantization.
This quickstart demonstrates how to load a model using 8-bit quantization with `bitsandbytes` through the Hugging Face `transformers` library. It attempts to load a small, publicly available model if CUDA is detected, otherwise falls back to dummy classes to ensure the example is runnable for illustrating the `BitsAndBytesConfig` usage.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import os
# NOTE: Replace with a small, accessible model for actual testing if needed.
# For a quick runnable example without downloading a large model, this snippet
# focuses on the setup. For full inference, a suitable model would be larger.
# Using a small placeholder model for demonstration purposes.
# In a real scenario, 'meta-llama/Llama-2-7b-hf' (or similar) would be used.
# Configure 8-bit quantization
bnb_config = BitsAndBytesConfig(
load_in_8bit=True,
)
# Load a dummy model with 8-bit quantization (replace with a real model for actual use)
# This example is illustrative. For a real model, 'meta-llama/Llama-2-7b-hf'
# requires authentication/access. Using a placeholder for direct runnability checks.
# Set up a dummy class to simulate AutoModelForCausalLM for local testing if no GPU/model access
class DummyModel:
def __init__(self, config=None, **kwargs):
print(f"Dummy model initialized with config: {config}, kwargs: {kwargs}")
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
def generate(self, *args, **kwargs):
print(f"Dummy generate call with args: {args}, kwargs: {kwargs}")
return torch.tensor([[1, 2, 3]]) # Placeholder output
class DummyTokenizer:
def __init__(self, *args, **kwargs):
pass
def __call__(self, text, return_tensors):
print(f"Dummy tokenizer called with '{text}'")
return {'input_ids': torch.tensor([[0, 1, 2, 3]])}
def decode(self, *args, **kwargs):
return "dummy output"
# Use actual AutoModelForCausalLM and AutoTokenizer if `transformers` and a CUDA-enabled GPU are available
# Otherwise, the dummy classes above will be used to allow the code to run.
if torch.cuda.is_available():
try:
# Ensure you have access to a model like 'meta-llama/Llama-2-7b-hf' or similar
# and accept its terms of use on Hugging Face if using a restricted model.
# For a truly runnable quickstart *without* specific HF token or large download,
# consider a very small public model like 'hf-internal-testing/tiny-random-llama'
# but it might not fully demonstrate bnb benefits.
model_id = "hf-internal-testing/tiny-random-llama" # Publicly available tiny model
model = AutoModelForCausalLM.from_pretrained(
model_id,
device_map="auto",
quantization_config=bnb_config,
torch_dtype=torch.float16 # Often beneficial with bnb
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
print("Model loaded using transformers and bitsandbytes.")
inputs = tokenizer("Hello, my name is", return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=20)
print("Generated text (first 50 chars):", tokenizer.decode(outputs[0])[:50])
except Exception as e:
print(f"Could not load actual model: {e}. Using dummy classes instead.")
model = DummyModel(quantization_config=bnb_config, device_map="auto")
tokenizer = DummyTokenizer()
inputs = tokenizer("Hello, my name is", return_tensors="pt")
outputs = model.generate(**inputs, max_new_tokens=20)
print("Generated text (dummy):", tokenizer.decode(outputs[0]))
else:
print("CUDA not available. Using dummy classes for demonstration.")
model = DummyModel(quantization_config=bnb_config, device_map="auto")
tokenizer = DummyTokenizer()
inputs = tokenizer("Hello, my name is", return_tensors="pt")
outputs = model.generate(**inputs, max_new_tokens=20)
print("Generated text (dummy):", tokenizer.decode(outputs[0]))
print("Bitsandbytes integration quickstart completed.")
Debug
Known issues
breakingBitsandbytes v0.49.2 requires Python >=3.10 and PyTorch >=2.3.0. Support for older Python (e.g., 3.8, 3.9) and PyTorch (<2.3.0) versions has been dropped in recent releases.fixUpgrade Python to 3.10+ and PyTorch to 2.3.0+ to ensure compatibility.
affects: >=0.49.0
breakingPEFT users wishing to merge adapters with 8-bit weights will need to upgrade to `peft>=0.14.0` due to internal changes in `bitsandbytes` from version 0.43.fixEnsure your `peft` library version is 0.14.0 or newer when working with 8-bit models and adapters.
affects: >=0.43.0
gotchaGPU compatibility can be an issue. Older NVIDIA GPUs (Maxwell, Pascal generations or compute capability < 7.0) might not be fully supported or may require compiling `bitsandbytes` from source with specific flags, or using pre-compiled unofficial DLLs. Official support is for NVIDIA GPUs with CUDA 11.8 - 13.0, Intel XPUs, and Intel Gaudis.fixCheck your GPU's compute capability. If you encounter issues, ensure your CUDA toolkit is compatible, or consider compiling `bitsandbytes` from source. Refer to the official GitHub for detailed compilation instructions for unsupported hardware.
affects: All versions
gotchaThe error message "The installed version of bitsandbytes was compiled without GPU support" indicates that a CPU-only version was installed, or there's an issue with the CUDA setup/detection.fixVerify CUDA toolkit installation and environment variables. Ensure PyTorch is installed with CUDA support. Reinstall `bitsandbytes` using the appropriate `pip install` command (e.g., with `--extra-index-url` for your CUDA version) to force a GPU-enabled build.
affects: All versions
gotchaAfter upgrading from `bitsandbytes` v0.42 to v0.43, models using 4-bit quantization may generate slightly different outputs (approximately up to the 2nd decimal place) due to a fix in the underlying code.fixBe aware of this minor output discrepancy if reproducing exact results from models quantized with older versions.
affects: >=0.43.0 (when upgrading from <0.43.0)
breaking`bitsandbytes` requires `PyTorch` to be installed for its core functionalities. `PyTorch` is a peer dependency and is not automatically installed when you install `bitsandbytes`. Attempting to use `bitsandbytes` without `PyTorch` will result in a `ModuleNotFoundError`.fixInstall `PyTorch` separately using the appropriate command for your system (e.g., `pip install torch --index-url https://download.pytorch.org/whl/cpu` for CPU-only, or with the relevant CUDA version for GPU support).
affects: All versions
Errors
Common errors & fixes
CUDA SETUP: WARNING! libcudart.so not found in any environmental path. Searching in backup paths... OR The installed version of bitsandbytes was compiled without GPU support.
This error typically indicates that `bitsandbytes` cannot locate the necessary CUDA libraries (like `libcudart.so` or `cudart64_XX.dll`) or that the installed `bitsandbytes` wheel was not built for your specific CUDA version or operating system, especially common on Windows or when CUDA environment variables are not correctly set.
fixEnsure your NVIDIA CUDA Toolkit is correctly installed and its `bin` directory is in your system's `PATH` (and `LD_LIBRARY_PATH` on Linux). If on Windows, `bitsandbytes` traditionally requires custom pre-compiled wheels. A common fix involves uninstalling and then reinstalling PyTorch with CUDA support, and then installing `bitsandbytes` matching your PyTorch CUDA version. For persistent issues, run `python -m bitsandbytes` for detailed debug information.
ModuleNotFoundError: No module named 'bitsandbytes'
This error means the Python interpreter cannot find the `bitsandbytes` package, usually due to it not being installed, installed in a different Python environment, or an incomplete/corrupted installation.
fixInstall or reinstall the package using `pip install bitsandbytes`. If using a virtual environment or Conda, ensure you activate the correct environment before installation. Verify installation with `pip show bitsandbytes`.
ModuleNotFoundError: No module named 'triton.ops'
This error occurs when `bitsandbytes` features (especially 4-bit quantization) depend on the `triton` library, but `triton` is either not installed or an incompatible version is present.
fixInstall or upgrade `triton` using `pip install triton`. Sometimes, a specific version of `triton` might be required for compatibility with `bitsandbytes` and PyTorch, so you might need to try `pip install triton==<version>` (e.g., `triton==2.2.0` or `triton==3.1.0` depending on your setup and other libraries).
AttributeError: module 'bitsandbytes' has no attribute 'cuda'
This error happens when attempting to access CUDA-related attributes or functions directly via `bitsandbytes.cuda` or `bitsandbytes.utils.has_cuda_support`, which are not standard or have been deprecated/removed in newer versions.
fixTo check `bitsandbytes` installation and CUDA support, the recommended method is to run `python -m bitsandbytes` in your terminal. This command provides a detailed report on the library's setup and CUDA detection. Avoid using `bitsandbytes.cuda.is_available()` or `bitsandbytes.utils.has_cuda_support` as they are not officially supported APIs for this purpose.
ImportError: Using `bitsandbytes` 8-bit quantization requires the latest version of bitsandbytes: `pip install -U bitsandbytes`
This error indicates that the currently installed `bitsandbytes` version is too old to support the requested quantization features (e.g., 8-bit or 4-bit quantization), or there's a version mismatch with other libraries like `transformers`.
fixUpgrade `bitsandbytes` to the latest version using `pip install -U bitsandbytes`. It's also advisable to ensure your `transformers` library is up-to-date and compatible with the new `bitsandbytes` version.
Audit
Dependencies
torchrequiredBitsandbytes is a lightweight wrapper around CUDA custom functions for PyTorch.
transformersoptionalOften used in conjunction for loading and quantizing large language models.
accelerateoptionalCommonly used for distributed training and model loading with transformers.
peftoptionalRequired for QLoRA fine-tuning and merging adapters.