Top Related Projects
Accessible large language models via k-bit quantization for PyTorch.
A PyTorch Extension: Tools for easy mixed precision and distributed training in Pytorch
Tensors and Dynamic neural networks in Python with strong GPU acceleration
🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
DeepSpeed is a deep learning optimization library that makes distributed training and inference easy, efficient, and effective.
PyTorch extensions for high performance and large scale training.
Quick Overview
Bitsandbytes is a lightweight wrapper around CUDA custom functions, primarily focused on 8-bit optimizers and quantization primitives. It aims to make 8-bit optimizers more accessible and easier to use in machine learning projects, particularly for large language models and other memory-intensive applications.
Pros
- Enables 8-bit optimization, reducing memory usage and potentially improving training speed
- Seamless integration with PyTorch, making it easy to incorporate into existing projects
- Supports both CPU and GPU operations
- Actively maintained and regularly updated
Cons
- Limited documentation, which may make it challenging for newcomers to understand and use all features
- Primarily focused on CUDA operations, limiting its usefulness for non-NVIDIA hardware
- Some users report occasional stability issues or unexpected behavior
- Relatively new project, so it may lack some advanced features or optimizations
Code Examples
- Creating an 8-bit Adam optimizer:
import torch
import bitsandbytes as bnb
model = torch.nn.Linear(10, 10)
optimizer = bnb.optim.Adam8bit(model.parameters(), lr=1e-3)
- Using 8-bit quantization for a linear layer:
from bitsandbytes.nn import Linear8bitLt
layer = Linear8bitLt(1024, 1024, bias=True)
output = layer(input_tensor)
- Initializing a model with 8-bit parameters:
from transformers import AutoModelForCausalLM
import bitsandbytes as bnb
model = AutoModelForCausalLM.from_pretrained("gpt2", load_in_8bit=True)
Getting Started
To get started with bitsandbytes, follow these steps:
- Install the library:
pip install bitsandbytes
- Import the library in your Python script:
import bitsandbytes as bnb
- Use 8-bit optimizers or quantized layers in your model:
model = YourModel()
optimizer = bnb.optim.Adam8bit(model.parameters(), lr=1e-3)
# Train your model as usual
for epoch in range(num_epochs):
for batch in dataloader:
optimizer.zero_grad()
loss = criterion(model(batch), targets)
loss.backward()
optimizer.step()
Remember to check the compatibility of bitsandbytes with your CUDA version and PyTorch installation for optimal performance.
Competitor Comparisons
Accessible large language models via k-bit quantization for PyTorch.
Pros of bitsandbytes
- More active development and frequent updates
- Better documentation and user guides
- Wider range of supported hardware and platforms
Cons of bitsandbytes
- Larger codebase, potentially more complex to maintain
- May have more dependencies, increasing potential compatibility issues
- Slightly higher memory footprint due to additional features
Code Comparison
bitsandbytes:
from bitsandbytes import nn
model = nn.Linear8bitLt(1024, 1024, bias=True)
bitsandbytes>:
from bitsandbytes.nn import Linear8bitLt
model = Linear8bitLt(1024, 1024, bias=True)
The code usage is very similar, with bitsandbytes offering a slightly more streamlined import structure. Both libraries provide 8-bit quantization for linear layers, but bitsandbytes may offer more advanced features and optimizations due to its more active development.
Overall, bitsandbytes appears to be the more robust and feature-rich option, while bitsandbytes> might be simpler and more lightweight for basic quantization needs. The choice between them would depend on specific project requirements and hardware constraints.
A PyTorch Extension: Tools for easy mixed precision and distributed training in Pytorch
Pros of Apex
- More comprehensive optimization toolkit with a wider range of features
- Better integration with NVIDIA GPUs and CUDA
- Extensive documentation and community support
Cons of Apex
- Limited to NVIDIA hardware, less flexible for other platforms
- More complex setup and usage compared to bitsandbytes
- Requires CUDA toolkit installation
Code Comparison
Apex (Mixed Precision Training):
model, optimizer = amp.initialize(model, optimizer, opt_level="O1")
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
bitsandbytes (8-bit Quantization):
import bitsandbytes as bnb
optimizer = bnb.optim.Adam8bit(model.parameters(), lr=1e-3)
Apex offers a more comprehensive approach to mixed precision training, while bitsandbytes focuses on efficient 8-bit quantization for optimizers. Apex provides finer control over precision levels, but bitsandbytes offers a simpler API for quantization. Both libraries aim to improve training efficiency and reduce memory usage, with Apex being more tightly integrated with NVIDIA hardware and bitsandbytes offering a more platform-agnostic solution.
Tensors and Dynamic neural networks in Python with strong GPU acceleration
Pros of PyTorch
- Comprehensive deep learning framework with a wide range of tools and functionalities
- Large and active community, extensive documentation, and ecosystem support
- Seamless integration with Python and native CUDA support for GPU acceleration
Cons of PyTorch
- Larger memory footprint and potentially slower for certain operations
- Steeper learning curve for beginners due to its extensive feature set
- Less focused on quantization and memory optimization compared to bitsandbytes
Code Comparison
PyTorch:
import torch
x = torch.randn(3, 3)
y = torch.matmul(x, x.t())
z = torch.relu(y)
bitsandbytes:
import bitsandbytes as bnb
x = bnb.rand(3, 3)
y = bnb.matmul(x, x.t())
z = bnb.nn.functional.relu(y)
The code snippets demonstrate basic tensor operations. While PyTorch offers a more comprehensive set of operations, bitsandbytes focuses on memory-efficient alternatives, particularly for large-scale models and quantization tasks.
🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
Pros of Transformers
- Comprehensive library with support for a wide range of transformer models
- Extensive documentation and community support
- Seamless integration with popular deep learning frameworks
Cons of Transformers
- Larger codebase and potentially steeper learning curve
- May include unnecessary features for specific use cases
- Higher memory requirements for some models
Code Comparison
Transformers:
from transformers import AutoModel, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModel.from_pretrained("bert-base-uncased")
inputs = tokenizer("Hello world!", return_tensors="pt")
outputs = model(**inputs)
Bitsandbytes:
import torch
import bitsandbytes as bnb
model = bnb.nn.Linear8bitLt(1024, 1024, bias=True)
input_tensor = torch.randn(1, 1024)
output = model(input_tensor)
Transformers offers a higher-level API for working with pre-trained models, while Bitsandbytes focuses on efficient, low-precision operations. Transformers is more suitable for general NLP tasks, whereas Bitsandbytes is ideal for optimizing memory usage and performance in specific scenarios.
DeepSpeed is a deep learning optimization library that makes distributed training and inference easy, efficient, and effective.
Pros of DeepSpeed
- More comprehensive optimization toolkit for distributed deep learning
- Supports a wider range of model parallelism techniques
- Offers advanced features like ZeRO-Offload and 3D parallelism
Cons of DeepSpeed
- Steeper learning curve due to more complex configuration options
- May be overkill for smaller-scale projects or single-GPU setups
- Requires more setup and integration effort compared to bitsandbytes
Code Comparison
DeepSpeed initialization:
import deepspeed
model_engine, optimizer, _, _ = deepspeed.initialize(args=args,
model=model,
model_parameters=params)
bitsandbytes quantization:
import bitsandbytes as bnb
model = bnb.nn.Linear8bitLt(input_size, output_size, bias=True)
DeepSpeed focuses on distributed training and offers a more comprehensive suite of optimization techniques, while bitsandbytes specializes in efficient quantization and memory-saving methods. DeepSpeed is better suited for large-scale distributed training, while bitsandbytes is more straightforward to integrate for quantization and memory optimization in smaller projects.
PyTorch extensions for high performance and large scale training.
Pros of FairScale
- More comprehensive suite of distributed training tools
- Better integration with PyTorch ecosystem
- More active development and community support
Cons of FairScale
- Steeper learning curve for beginners
- Potentially more complex setup for simple use cases
- May have higher computational overhead for small-scale projects
Code Comparison
FairScale example (Sharded DataParallel):
from fairscale.nn.data_parallel import ShardedDataParallel
model = ShardedDataParallel(model, optimizer)
output = model(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()
bitsandbytes example (8-bit Adam optimizer):
import bitsandbytes as bnb
optimizer = bnb.optim.Adam8bit(model.parameters(), lr=1e-3)
output = model(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()
FairScale offers more advanced distributed training features, while bitsandbytes focuses on memory-efficient optimizers and quantization techniques. FairScale is better suited for large-scale distributed training, while bitsandbytes excels in scenarios where memory optimization is crucial.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
bitsandbytes
bitsandbytes enables accessible large language models via k-bit quantization for PyTorch. We provide three main features for dramatically reducing memory consumption for inference and training:
- 8-bit optimizers uses block-wise quantization to maintain 32-bit performance at a small fraction of the memory cost.
- LLM.int8() or 8-bit quantization enables large language model inference with only half the required memory and without any performance degradation. This method is based on vector-wise quantization to quantize most features to 8-bits and separately treating outliers with 16-bit matrix multiplication.
- QLoRA or 4-bit quantization enables large language model training with several memory-saving techniques that don't compromise performance. This method quantizes a model to 4-bits and inserts a small set of trainable low-rank adaptation (LoRA) weights to allow training.
The library includes quantization primitives for 8-bit & 4-bit operations, through bitsandbytes.nn.Linear8bitLt and bitsandbytes.nn.Linear4bit and 8-bit optimizers through bitsandbytes.optim module.
System Requirements
bitsandbytes has the following minimum requirements for all platforms:
- Python 3.10+
- PyTorch 2.4+
- Note: While we aim to provide wide backwards compatibility, we recommend using the latest version of PyTorch for the best experience.
Accelerator support:
Note: this table reflects the status of the current development branch. For the latest stable release, see the document in the 0.49.2 tag.
Legend:
ð§ = In Development, ã°ï¸ = Partially Supported, â = Supported, ð¢ = Slow Implementation Supported, â = Not Supported
| Platform | Accelerator | Hardware Requirements | LLM.int8() | QLoRA 4-bit | 8-bit Optimizers |
|---|---|---|---|---|---|
| ð§ Linux, glibc >= 2.24 | |||||
| x86-64 | â»ï¸ CPU | Minimum: AVX2 Optimized: AVX512F, AVX512BF16 |
â | â | â |
ð© NVIDIA GPU cuda |
SM60+ minimum SM75+ recommended |
â | â | â | |
ð¥ AMD GPU cuda |
CDNA: gfx90a, gfx942, gfx950 RDNA: gfx1100, gfx1101, gfx1102, gfx1103, gfx1150, gfx1151, gfx1152, gfx1153, gfx1200, gfx1201 |
â | â | â | |
ð¦ Intel GPU xpu |
Data Center GPU Max Series Arc A-Series (Alchemist) Arc B-Series (Battlemage) |
â | â | â | |
ðª Intel Gaudi hpu |
Gaudi2, Gaudi3 | â | ã°ï¸ | â | |
| aarch64 | â»ï¸ CPU | â | â | â | |
ð© NVIDIA GPU cuda |
SM75+ | â | â | â | |
| ðª Windows 11 / Windows Server 2022+ | |||||
| x86-64 | â»ï¸ CPU | AVX2 | â | â | â |
ð© NVIDIA GPU cuda |
SM60+ minimum SM75+ recommended |
â | â | â | |
ð¥ AMD GPU cuda |
RDNA: gfx1100, gfx1101, gfx1102, gfx1150, gfx1151, gfx1200, gfx1201 |
â | â | â | |
ð¦ Intel GPU xpu |
Arc A-Series (Alchemist) Arc B-Series (Battlemage) |
â | â | â | |
| arm64 | â»ï¸ CPU | â | â | â | |
| ð macOS 14+ | |||||
| arm64 | â»ï¸ CPU | Apple M1+ | â | â | â |
⬠Metal mps |
Apple M1+ | ð¢ | ð¢ | ð§ | |
:book: Documentation
- Official Documentation
- ð¤ Transformers
- ð¤ Diffusers
- ð¤ PEFT
:heart: Sponsors
The continued maintenance and development of bitsandbytes is made possible thanks to the generous support of our sponsors. Their contributions help ensure that we can keep improving the project and delivering valuable updates to the community.
License
bitsandbytes is MIT licensed.
How to cite us
If you found this library useful, please consider citing our work:
QLoRA
@article{dettmers2023qlora,
title={Qlora: Efficient finetuning of quantized llms},
author={Dettmers, Tim and Pagnoni, Artidoro and Holtzman, Ari and Zettlemoyer, Luke},
journal={arXiv preprint arXiv:2305.14314},
year={2023}
}
LLM.int8()
@article{dettmers2022llmint8,
title={LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale},
author={Dettmers, Tim and Lewis, Mike and Belkada, Younes and Zettlemoyer, Luke},
journal={arXiv preprint arXiv:2208.07339},
year={2022}
}
8-bit Optimizers
@article{dettmers2022optimizers,
title={8-bit Optimizers via Block-wise Quantization},
author={Dettmers, Tim and Lewis, Mike and Shleifer, Sam and Zettlemoyer, Luke},
journal={9th International Conference on Learning Representations, ICLR},
year={2022}
}
Top Related Projects
Accessible large language models via k-bit quantization for PyTorch.
A PyTorch Extension: Tools for easy mixed precision and distributed training in Pytorch
Tensors and Dynamic neural networks in Python with strong GPU acceleration
🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
DeepSpeed is a deep learning optimization library that makes distributed training and inference easy, efficient, and effective.
PyTorch extensions for high performance and large scale training.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot