Debian Codegraph @

docs/source/usage_guides/quantization.md

raw
1 <!--Copyright 2023 The HuggingFace Team. All rights reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4 the License. You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9 an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10 specific language governing permissions and limitations under the License.
11
12 ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13 rendered properly in your Markdown viewer.
14 -->
15
16 # Model quantization
17
18 ## `bitsandbytes` Integration
19
20 Accelerate brings `bitsandbytes` quantization to your model. You can now load any pytorch model in 8-bit or 4-bit with a few lines of code.
21
22 If you want to use Transformers models with `bitsandbytes`, you should follow this [documentation](https://huggingface.co/docs/transformers/main_classes/quantization).
23
24 To learn more about how the `bitsandbytes` quantization works, check out the blog posts on [8-bit quantization](https://huggingface.co/blog/hf-bitsandbytes-integration) and [4-bit quantization](https://huggingface.co/blog/4bit-transformers-bitsandbytes).
25
26 ### Pre-Requisites
27 You will need to install the following requirements:
28
29 - Install `bitsandbytes` library
30 ```bash
31 pip install bitsandbytes
32 ```
33 For non-cuda devices, you can refer to the bitsandbytes installation guide [here](https://huggingface.co/docs/bitsandbytes/main/en/installation#multi-backend).
34
35 - Install latest `accelerate` from source
36 ```bash
37 pip install git+https://github.com/huggingface/accelerate.git
38 ```
39 - Install `minGPT` and `huggingface_hub` to run examples
40 ```bash
41 git clone https://github.com/karpathy/minGPT.git
42 pip install minGPT/
43 pip install huggingface_hub
44 ```
45
46 ### How it works
47
48 First, we need to initialize our model. To save memory, we can initialize an empty model using the context manager [`init_empty_weights`].
49
50 Let's take the GPT2 model from minGPT library.
51 ```py
52 from accelerate import init_empty_weights
53 from mingpt.model import GPT
54
55 model_config = GPT.get_default_config()
56 model_config.model_type = 'gpt2-xl'
57 model_config.vocab_size = 50257
58 model_config.block_size = 1024
59
60 with init_empty_weights():
61 empty_model = GPT(model_config)
62 ```
63
64 Then, we need to get the path to the weights of your model. The path can be the state_dict file (e.g. "pytorch_model.bin") or a folder containing the sharded checkpoints.
65
66 ```py
67 from huggingface_hub import snapshot_download
68 weights_location = snapshot_download(repo_id="marcsun13/gpt2-xl-linear-sharded")
69 ```
70
71 Finally, you need to set your quantization configuration with [`~utils.BnbQuantizationConfig`].
72
73 Here's an example for 8-bit quantization:
74 ```py
75 from accelerate.utils import BnbQuantizationConfig
76 bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True, llm_int8_threshold = 6)
77 ```
78
79 Here's an example for 4-bit quantization:
80 ```py
81 from accelerate.utils import BnbQuantizationConfig
82 bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4")
83 ```
84
85 To quantize your empty model with the selected configuration, you need to use [`~utils.load_and_quantize_model`].
86
87 ```py
88 from accelerate.utils import load_and_quantize_model
89 quantized_model = load_and_quantize_model(empty_model, weights_location=weights_location, bnb_quantization_config=bnb_quantization_config)
90 ```
91
92 ### Saving and loading 8-bit model
93
94 You can save your 8-bit model with accelerate using [`~Accelerator.save_model`].
95
96 ```py
97 from accelerate import Accelerator
98 accelerate = Accelerator()
99 new_weights_location = "path/to/save_directory"
100 accelerate.save_model(quantized_model, new_weights_location)
101
102 quantized_model_from_saved = load_and_quantize_model(empty_model, weights_location=new_weights_location, bnb_quantization_config=bnb_quantization_config, device_map = "auto")
103 ```
104
105 Note that 4-bit model serialization is currently not supported.
106
107 ### Offload modules to cpu and disk
108
109 You can offload some modules to cpu/disk if you don't have enough space on the GPU to store the entire model on your GPUs.
110 This uses big model inference under the hood. Check this [documentation](https://huggingface.co/docs/accelerate/usage_guides/big_modeling) for more details.
111
112 For 8-bit quantization, the selected modules will be converted to 8-bit precision.
113
114 For 4-bit quantization, the selected modules will be kept in `torch_dtype` that the user passed in `BnbQuantizationConfig`. We will add support to convert these offloaded modules in 4-bit when 4-bit serialization will be possible.
115
116 You just need to pass a custom `device_map` in order to offload modules on cpu/disk. The offload modules will be dispatched on the GPU when needed. Here's an example :
117
118 ```py
119 device_map = {
120 "transformer.wte": 0,
121 "transformer.wpe": 0,
122 "transformer.drop": 0,
123 "transformer.h": "cpu",
124 "transformer.ln_f": "disk",
125 "lm_head": "disk",
126 }
127 ```
128 ### Fine-tune a quantized model
129
130 It is not possible to perform pure 8bit or 4bit training on these models. However, you can train these models by leveraging parameter efficient fine tuning methods (PEFT) and train for example adapters on top of them. Please have a look at [peft](https://github.com/huggingface/peft) library for more details.
131
132 Currently, you can't add adapters on top of any quantized model. However, with the official support of adapters with Transformers models, you can fine-tune quantized models. If you want to fine-tune a Transformers model , follow this [documentation](https://huggingface.co/docs/transformers/main_classes/quantization) instead. Check out this [demo](https://colab.research.google.com/drive/1VoYNfYDKcKRQRor98Zbf2-9VQTtGJ24k?usp=sharing) on how to fine-tune a 4-bit Transformers model.
133
134 Note that you don’t need to pass `device_map` when loading the model for training. It will automatically load your model on your GPU. Please note that `device_map=auto` should be used for inference only.
135
136 ### Example demo - running GPT2 1.5b on a Google Colab
137
138 Check out the Google Colab [demo](https://colab.research.google.com/drive/1T1pOgewAWVpR9gKpaEWw4orOrzPFb3yM?usp=sharing) for running quantized models on a GPT2 model. The GPT2-1.5B model checkpoint is in FP32 which uses 6GB of memory. After quantization, it uses 1.6GB with 8-bit modules and 1.2GB with 4-bit modules.