-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Quantization] Add quantization support for bitsandbytes
#9213
Merged
Merged
Changes from all commits
Commits
Show all changes
119 commits
Select commit
Hold shift + click to select a range
e634ff2
quantization config.
sayakpaul 02a6dff
fix-copies
sayakpaul c385a2b
Merge branch 'main' into quantization-config
sayakpaul 0355875
Merge branch 'main' into quantization-config
sayakpaul e41b494
Merge branch 'main' into quantization-config
sayakpaul dfb33eb
Merge branch 'main' into quantization-config
sayakpaul e492655
Merge branch 'main' into quantization-config
sayakpaul 6e86cc0
fix
sayakpaul 58a3d15
modules_to_not_convert
sayakpaul 1d477f9
Merge branch 'main' into quantization-config
sayakpaul bd7f46d
Merge branch 'main' into quantization-config
sayakpaul d5d7bb6
Merge branch 'main' into quantization-config
sayakpaul 44c8a75
Merge branch 'main' into quantization-config
sayakpaul 6a0fcdc
add bitsandbytes utilities.
sayakpaul e4590fa
make progress.
sayakpaul 77a1438
Merge branch 'main' into quantization-config
sayakpaul 335ab6b
fixes
sayakpaul d44ef85
quality
sayakpaul 210fa1e
up
sayakpaul f4feee1
up
sayakpaul e8c1722
Merge branch 'main' into quantization-config
sayakpaul 7f86a71
Merge branch 'main' into quantization-config
sayakpaul ba671b6
minor
sayakpaul c1a9f13
up
sayakpaul 4489c54
Merge branch 'main' into quantization-config
sayakpaul f2ca5e2
up
sayakpaul d6b8954
fix
sayakpaul 45029e2
provide credits where due.
sayakpaul 4eb468a
make configurations work.
sayakpaul 939965d
fixes
sayakpaul 8557166
Merge branch 'main' into quantization-config
sayakpaul d098d07
fix
sayakpaul c4a0074
update_missing_keys
sayakpaul ee45612
fix
sayakpaul b24c0a7
fix
sayakpaul 473505c
make it work.
sayakpaul c795c82
fix
sayakpaul c1d5b96
Merge branch 'main' into quantization-config
sayakpaul af7caca
provide credits to transformers.
sayakpaul 80967f5
empty commit
sayakpaul 3bdf25a
handle to() better.
sayakpaul 27415cc
tests
sayakpaul 51cac09
change to bnb from bitsandbytes
sayakpaul 15f3032
fix tests
sayakpaul 77c9fdb
better safeguard.
sayakpaul ddc9f29
change merging status
sayakpaul 44c4109
courtesy to transformers.
sayakpaul 27666a8
move upper.
sayakpaul 3464d83
better
sayakpaul b106124
Merge branch 'main' into quantization-config
sayakpaul 330fa0a
Merge branch 'main' into quantization-config
sayakpaul abc8607
make the unused kwargs warning friendlier.
sayakpaul 31725aa
harmonize changes with https://github.com/huggingface/transformers/pu…
sayakpaul e5938a6
style
sayakpaul 444588f
trainin tests
sayakpaul d3360ce
Merge branch 'main' into quantization-config
sayakpaul d8b35f4
Merge branch 'main' into quantization-config
sayakpaul 859f2d7
Merge branch 'main' into quantization-config
sayakpaul 3b2d6e1
feedback part i.
sayakpaul 5799954
Add Flux inpainting and Flux Img2Img (#9135)
Gothos 8e4bd08
Revert "Add Flux inpainting and Flux Img2Img (#9135)"
sayakpaul 835d4ad
tests
sayakpaul 27075fe
don
sayakpaul 5c00c1c
Merge branch 'main' into quantization-config
sayakpaul 5d633a0
Merge branch 'main' into quantization-config
sayakpaul c381fe0
Apply suggestions from code review
sayakpaul 3c92878
Merge branch 'main' into quantization-config
sayakpaul acdeb25
contribution guide.
sayakpaul aa295b7
Merge branch 'main' into quantization-config
sayakpaul 7f7c9ce
Merge branch 'main' into quantization-config
sayakpaul 55f96d8
Merge branch 'main' into quantization-config
sayakpaul b28cc65
changes
sayakpaul 8328e86
Merge branch 'main' into quantization-config
sayakpaul 9758942
empty
sayakpaul b1a9878
fix tests
sayakpaul 971305b
harmonize with https://github.com/huggingface/transformers/pull/33546.
sayakpaul f41adf1
numpy_cosine_distance
sayakpaul 0bcb88b
Merge branch 'main' into quantization-config
sayakpaul 55b3696
Merge branch 'main' into quantization-config
sayakpaul 4cb3a6d
Merge branch 'main' into quantization-config
sayakpaul 8a03eae
Merge branch 'main' into quantization-config
sayakpaul 53f0a92
Merge branch 'main' into quantization-config
sayakpaul 6aab47c
Merge branch 'main' into quantization-config
sayakpaul 9b9a610
resolved conflicts,
sayakpaul 510d57a
Merge branch 'main' into quantization-config
sayakpaul 555a5ae
config_dict modification.
sayakpaul da10365
remove if config comment.
sayakpaul 71316a6
note for load_state_dict changes.
sayakpaul 12f5c59
float8 check.
sayakpaul 5e722cd
quantizer.
sayakpaul c78dd0c
raise an error for non-True low_cpu_mem_usage values when using quant.
sayakpaul af3ecea
low_cpu_mem_usage shenanigans when using fp32 modules.
sayakpaul a473d28
don't re-assign _pre_quantization_type.
sayakpaul 870d74f
make comments clear.
sayakpaul 3e6cfeb
remove comments.
sayakpaul 673993c
handle mixed types better when moving to cpu.
sayakpaul 0d5f2f7
add tests to check if we're throwing warning rightly.
sayakpaul 3cb20fe
better check.
sayakpaul 10940a9
fix 8bit test_quality.
sayakpaul c0a88ae
Merge branch 'main' into quantization-config
sayakpaul dcc5bc5
Merge branch 'main' into quantization-config
sayakpaul 5e0b4eb
Merge branch 'main' into quantization-config
sayakpaul 569dd96
Merge branch 'main' into quantization-config
sayakpaul 8bdc846
Merge branch 'main' into quantization-config
sayakpaul ff8ddef
handle dtype more robustly.
sayakpaul de6394a
better message when keep_in_fp32_modules.
sayakpaul 81bb48a
handle dtype casting.
sayakpaul c5e62ae
Merge branch 'main' into quantization-config
sayakpaul d023b40
Merge branch 'main' into quantization-config
sayakpaul a3d2655
Merge branch 'main' into quantization-config
sayakpaul 700b0f3
Merge branch 'main' into quantization-config
sayakpaul 0ae70fe
fix dtype checks in pipeline.
sayakpaul ecdf1d0
fix warning message.
sayakpaul aea3398
Update src/diffusers/models/modeling_utils.py
sayakpaul 3a91974
Merge branch 'main' into quantization-config
sayakpaul 5d8e844
Merge branch 'main' into quantization-config
sayakpaul 501a6ba
mitigate the confusing cpu warning
sayakpaul 1a931cb
Merge branch 'main' into quantization-config
sayakpaul 2fa8fb9
Merge branch 'main' into quantization-config
sayakpaul File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
<!--Copyright 2024 The HuggingFace Team. All rights reserved. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with | ||
the License. You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
|
||
--> | ||
|
||
# Quantization | ||
|
||
Quantization techniques reduce memory and computational costs by representing weights and activations with lower-precision data types like 8-bit integers (int8). This enables loading larger models you normally wouldn't be able to fit into memory, and speeding up inference. Diffusers supports 8-bit and 4-bit quantization with [bitsandbytes](https://huggingface.co/docs/bitsandbytes/en/index). | ||
|
||
Quantization techniques that aren't supported in Transformers can be added with the [`DiffusersQuantizer`] class. | ||
|
||
<Tip> | ||
|
||
Learn how to quantize models in the [Quantization](../quantization/overview) guide. | ||
|
||
</Tip> | ||
|
||
|
||
## BitsAndBytesConfig | ||
|
||
[[autodoc]] BitsAndBytesConfig | ||
|
||
## DiffusersQuantizer | ||
|
||
[[autodoc]] quantizers.base.DiffusersQuantizer |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,267 @@ | ||
<!--Copyright 2024 The HuggingFace Team. All rights reserved. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with | ||
the License. You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
|
||
--> | ||
|
||
# bitsandbytes | ||
|
||
[bitsandbytes](https://huggingface.co/docs/bitsandbytes/index) is the easiest option for quantizing a model to 8 and 4-bit. 8-bit quantization multiplies outliers in fp16 with non-outliers in int8, converts the non-outlier values back to fp16, and then adds them together to return the weights in fp16. This reduces the degradative effect outlier values have on a model's performance. | ||
|
||
4-bit quantization compresses a model even further, and it is commonly used with [QLoRA](https://hf.co/papers/2305.14314) to finetune quantized LLMs. | ||
|
||
|
||
To use bitsandbytes, make sure you have the following libraries installed: | ||
|
||
```bash | ||
pip install diffusers transformers accelerate bitsandbytes -U | ||
``` | ||
|
||
Now you can quantize a model by passing a [`BitsAndBytesConfig`] to [`~ModelMixin.from_pretrained`]. This works for any model in any modality, as long as it supports loading with [Accelerate](https://hf.co/docs/accelerate/index) and contains `torch.nn.Linear` layers. | ||
|
||
<hfoptions id="bnb"> | ||
<hfoption id="8-bit"> | ||
|
||
Quantizing a model in 8-bit halves the memory-usage: | ||
|
||
```py | ||
from diffusers import FluxTransformer2DModel, BitsAndBytesConfig | ||
|
||
quantization_config = BitsAndBytesConfig(load_in_8bit=True) | ||
|
||
model_8bit = FluxTransformer2DModel.from_pretrained( | ||
"black-forest-labs/FLUX.1-dev", | ||
subfolder="transformer", | ||
quantization_config=quantization_config | ||
) | ||
``` | ||
|
||
By default, all the other modules such as `torch.nn.LayerNorm` are converted to `torch.float16`. You can change the data type of these modules with the `torch_dtype` parameter if you want: | ||
|
||
```py | ||
from diffusers import FluxTransformer2DModel, BitsAndBytesConfig | ||
|
||
quantization_config = BitsAndBytesConfig(load_in_8bit=True) | ||
|
||
model_8bit = FluxTransformer2DModel.from_pretrained( | ||
"black-forest-labs/FLUX.1-dev", | ||
subfolder="transformer", | ||
quantization_config=quantization_config, | ||
torch_dtype=torch.float32 | ||
) | ||
model_8bit.transformer_blocks.layers[-1].norm2.weight.dtype | ||
``` | ||
|
||
Once a model is quantized, you can push the model to the Hub with the [`~ModelMixin.push_to_hub`] method. The quantization `config.json` file is pushed first, followed by the quantized model weights. | ||
|
||
```py | ||
from diffusers import FluxTransformer2DModel, BitsAndBytesConfig | ||
|
||
quantization_config = BitsAndBytesConfig(load_in_8bit=True) | ||
|
||
model_8bit = FluxTransformer2DModel.from_pretrained( | ||
"black-forest-labs/FLUX.1-dev", | ||
subfolder="transformer", | ||
quantization_config=quantization_config | ||
) | ||
``` | ||
|
||
</hfoption> | ||
<hfoption id="4-bit"> | ||
|
||
Quantizing a model in 4-bit reduces your memory-usage by 4x: | ||
|
||
```py | ||
from diffusers import FluxTransformer2DModel, BitsAndBytesConfig | ||
|
||
quantization_config = BitsAndBytesConfig(load_in_4bit=True) | ||
|
||
model_4bit = FluxTransformer2DModel.from_pretrained( | ||
"black-forest-labs/FLUX.1-dev", | ||
subfolder="transformer", | ||
quantization_config=quantization_config | ||
) | ||
``` | ||
|
||
By default, all the other modules such as `torch.nn.LayerNorm` are converted to `torch.float16`. You can change the data type of these modules with the `torch_dtype` parameter if you want: | ||
|
||
```py | ||
from diffusers import FluxTransformer2DModel, BitsAndBytesConfig | ||
|
||
quantization_config = BitsAndBytesConfig(load_in_4bit=True) | ||
|
||
model_4bit = FluxTransformer2DModel.from_pretrained( | ||
"black-forest-labs/FLUX.1-dev", | ||
subfolder="transformer", | ||
quantization_config=quantization_config, | ||
torch_dtype=torch.float32 | ||
) | ||
model_4bit.transformer_blocks.layers[-1].norm2.weight.dtype | ||
``` | ||
|
||
Call [`~ModelMixin.push_to_hub`] after loading it in 4-bit precision. You can also save the serialized 4-bit models locally with [`~ModelMixin.save_pretrained`]. | ||
|
||
</hfoption> | ||
</hfoptions> | ||
|
||
<Tip warning={true}> | ||
|
||
Training with 8-bit and 4-bit weights are only supported for training *extra* parameters. | ||
|
||
</Tip> | ||
|
||
Check your memory footprint with the `get_memory_footprint` method: | ||
|
||
```py | ||
print(model.get_memory_footprint()) | ||
``` | ||
|
||
Quantized models can be loaded from the [`~ModelMixin.from_pretrained`] method without needing to specify the `quantization_config` parameters: | ||
|
||
```py | ||
from diffusers import FluxTransformer2DModel, BitsAndBytesConfig | ||
|
||
quantization_config = BitsAndBytesConfig(load_in_4bit=True) | ||
|
||
model_4bit = FluxTransformer2DModel.from_pretrained( | ||
"sayakpaul/flux.1-dev-nf4-pkg", subfolder="transformer" | ||
) | ||
``` | ||
|
||
## 8-bit (LLM.int8() algorithm) | ||
|
||
<Tip> | ||
|
||
Learn more about the details of 8-bit quantization in this [blog post](https://huggingface.co/blog/hf-bitsandbytes-integration)! | ||
|
||
</Tip> | ||
|
||
This section explores some of the specific features of 8-bit models, such as outlier thresholds and skipping module conversion. | ||
|
||
### Outlier threshold | ||
|
||
An "outlier" is a hidden state value greater than a certain threshold, and these values are computed in fp16. While the values are usually normally distributed ([-3.5, 3.5]), this distribution can be very different for large models ([-60, 6] or [6, 60]). 8-bit quantization works well for values ~5, but beyond that, there is a significant performance penalty. A good default threshold value is 6, but a lower threshold may be needed for more unstable models (small models or finetuning). | ||
|
||
To find the best threshold for your model, we recommend experimenting with the `llm_int8_threshold` parameter in [`BitsAndBytesConfig`]: | ||
|
||
```py | ||
from diffusers import FluxTransformer2DModel, BitsAndBytesConfig | ||
|
||
quantization_config = BitsAndBytesConfig( | ||
load_in_8bit=True, llm_int8_threshold=10, | ||
) | ||
|
||
model_8bit = FluxTransformer2DModel.from_pretrained( | ||
"black-forest-labs/FLUX.1-dev", | ||
subfolder="transformer", | ||
quantization_config=quantization_config, | ||
) | ||
``` | ||
|
||
### Skip module conversion | ||
|
||
For some models, you don't need to quantize every module to 8-bit which can actually cause instability. For example, for diffusion models like [Stable Diffusion 3](../api/pipelines/stable_diffusion/stable_diffusion_3), the `proj_out` module can be skipped using the `llm_int8_skip_modules` parameter in [`BitsAndBytesConfig`]: | ||
|
||
```py | ||
from diffusers import SD3Transformer2DModel, BitsAndBytesConfig | ||
|
||
quantization_config = BitsAndBytesConfig( | ||
load_in_8bit=True, llm_int8_skip_modules=["proj_out"], | ||
) | ||
|
||
model_8bit = SD3Transformer2DModel.from_pretrained( | ||
"stabilityai/stable-diffusion-3-medium-diffusers", | ||
subfolder="transformer", | ||
quantization_config=quantization_config, | ||
) | ||
``` | ||
|
||
|
||
## 4-bit (QLoRA algorithm) | ||
|
||
<Tip> | ||
|
||
Learn more about its details in this [blog post](https://huggingface.co/blog/4bit-transformers-bitsandbytes). | ||
|
||
</Tip> | ||
|
||
This section explores some of the specific features of 4-bit models, such as changing the compute data type, using the Normal Float 4 (NF4) data type, and using nested quantization. | ||
|
||
|
||
### Compute data type | ||
|
||
To speedup computation, you can change the data type from float32 (the default value) to bf16 using the `bnb_4bit_compute_dtype` parameter in [`BitsAndBytesConfig`]: | ||
|
||
```py | ||
import torch | ||
from diffusers import BitsAndBytesConfig | ||
|
||
quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16) | ||
``` | ||
|
||
### Normal Float 4 (NF4) | ||
|
||
NF4 is a 4-bit data type from the [QLoRA](https://hf.co/papers/2305.14314) paper, adapted for weights initialized from a normal distribution. You should use NF4 for training 4-bit base models. This can be configured with the `bnb_4bit_quant_type` parameter in the [`BitsAndBytesConfig`]: | ||
|
||
```py | ||
from diffusers import BitsAndBytesConfig | ||
|
||
nf4_config = BitsAndBytesConfig( | ||
load_in_4bit=True, | ||
bnb_4bit_quant_type="nf4", | ||
) | ||
|
||
model_nf4 = SD3Transformer2DModel.from_pretrained( | ||
"stabilityai/stable-diffusion-3-medium-diffusers", | ||
subfolder="transformer", | ||
quantization_config=nf4_config, | ||
) | ||
``` | ||
|
||
For inference, the `bnb_4bit_quant_type` does not have a huge impact on performance. However, to remain consistent with the model weights, you should use the `bnb_4bit_compute_dtype` and `torch_dtype` values. | ||
|
||
### Nested quantization | ||
|
||
Nested quantization is a technique that can save additional memory at no additional performance cost. This feature performs a second quantization of the already quantized weights to save an additional 0.4 bits/parameter. | ||
|
||
```py | ||
from diffusers import BitsAndBytesConfig | ||
|
||
double_quant_config = BitsAndBytesConfig( | ||
load_in_4bit=True, | ||
bnb_4bit_use_double_quant=True, | ||
) | ||
|
||
double_quant_model = SD3Transformer2DModel.from_pretrained( | ||
"stabilityai/stable-diffusion-3-medium-diffusers", | ||
subfolder="transformer", | ||
quantization_config=double_quant_config, | ||
) | ||
``` | ||
|
||
## Dequantizing `bitsandbytes` models | ||
|
||
Once quantized, you can dequantize the model to the original precision but this might result in a small quality loss of the model. Make sure you have enough GPU RAM to fit the dequantized model. | ||
|
||
```python | ||
from diffusers import BitsAndBytesConfig | ||
|
||
double_quant_config = BitsAndBytesConfig( | ||
load_in_4bit=True, | ||
bnb_4bit_use_double_quant=True, | ||
) | ||
|
||
double_quant_model = SD3Transformer2DModel.from_pretrained( | ||
"stabilityai/stable-diffusion-3-medium-diffusers", | ||
subfolder="transformer", | ||
quantization_config=double_quant_config, | ||
) | ||
model.dequantize() | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
<!--Copyright 2024 The HuggingFace Team. All rights reserved. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with | ||
the License. You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations under the License. | ||
|
||
--> | ||
|
||
# Quantization | ||
|
||
Quantization techniques focus on representing data with less information while also trying to not lose too much accuracy. This often means converting a data type to represent the same information with fewer bits. For example, if your model weights are stored as 32-bit floating points and they're quantized to 16-bit floating points, this halves the model size which makes it easier to store and reduces memory-usage. Lower precision can also speedup inference because it takes less time to perform calculations with fewer bits. | ||
|
||
<Tip> | ||
|
||
Interested in adding a new quantization method to Transformers? Refer to the [Contribute new quantization method guide](https://huggingface.co/docs/transformers/main/en/quantization/contribute) to learn more about adding a new quantization method. | ||
|
||
</Tip> | ||
|
||
<Tip> | ||
|
||
If you are new to the quantization field, we recommend you to check out these beginner-friendly courses about quantization in collaboration with DeepLearning.AI: | ||
|
||
* [Quantization Fundamentals with Hugging Face](https://www.deeplearning.ai/short-courses/quantization-fundamentals-with-hugging-face/) | ||
* [Quantization in Depth](https://www.deeplearning.ai/short-courses/quantization-in-depth/) | ||
|
||
</Tip> | ||
|
||
## When to use what? | ||
|
||
This section will be expanded once Diffusers has multiple quantization backends. Currently, we only support `bitsandbytes`. [This resource](https://huggingface.co/docs/transformers/main/en/quantization/overview#when-to-use-what) provides a good overview of the pros and cons of different quantization techniques. | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes I think it will be nice to also have a table directly in this doc in the future