Skip to content

Commit feb12dd

Browse files
authored
Merge branch 'main' into del-convert-tokenizer-flag
2 parents 92d42f4 + 8880d2e commit feb12dd

12 files changed

+1040
-118
lines changed

docs/source/inference.mdx

+6-5
Original file line numberDiff line numberDiff line change
@@ -99,21 +99,22 @@ tokenizer.save_pretrained(save_directory)
9999

100100
### Weight-only quantization
101101

102-
You can also apply 8-bit or 4-bit weight quantization when exporting your model with the CLI by setting the `weight-format` argument to respectively `int8` or `int4`:
102+
You can also apply fp16, 8-bit or 4-bit weight compression on the Linear, Convolutional and Embedding layers when exporting your model with the CLI by setting `--weight-format` to respectively `fp16`, `int8` or `int4`:
103103

104104
```bash
105105
optimum-cli export openvino --model gpt2 --weight-format int8 ov_model
106106
```
107107

108-
This will result in the exported model linear and embedding layers to be quantized to INT8 or INT4, the activations will be kept in floating point precision. This type of optimization allows reducing the footprint and latency of LLMs.
108+
This type of optimization allows to reduce the memory footprint and inference latency.
109109

110-
By default the quantization scheme will be [assymmetric](https://github.com/openvinotoolkit/nncf/blob/develop/docs/compression_algorithms/Quantization.md#asymmetric-quantization), to make it [symmetric](https://github.com/openvinotoolkit/nncf/blob/develop/docs/compression_algorithms/Quantization.md#symmetric-quantization) you can add `--sym`.
110+
111+
By default the quantization scheme will be [asymmetric](https://github.com/openvinotoolkit/nncf/blob/develop/docs/compression_algorithms/Quantization.md#asymmetric-quantization), to make it [symmetric](https://github.com/openvinotoolkit/nncf/blob/develop/docs/compression_algorithms/Quantization.md#symmetric-quantization) you can add `--sym`.
111112

112113
For INT4 quantization you can also specify the following arguments :
113114
* The `--group-size` parameter will define the group size to use for quantization, `-1` it will results in per-column quantization.
114115
* The `--ratio` parameter controls the ratio between 4-bit and 8-bit quantization. If set to 0.9, it means that 90% of the layers will be quantized to `int4` while 10% will be quantized to `int8`.
115116

116-
Smaller `group_size` and `ratio` of usually improve accuracy at the sacrifice of the model size and inference latency.
117+
Smaller `group_size` and `ratio` values usually improve accuracy at the sacrifice of the model size and inference latency.
117118

118119
You can also apply 8-bit quantization on your model's weight when loading your model by setting the `load_in_8bit=True` argument when calling the `from_pretrained()` method.
119120

@@ -125,7 +126,7 @@ model = OVModelForCausalLM.from_pretrained(model_id, load_in_8bit=True)
125126

126127
<Tip warning={true}>
127128

128-
`load_in_8bit` is enabled by default for the models larger than 1 billion parameters.
129+
`load_in_8bit` is enabled by default for the models larger than 1 billion parameters. You can disable it with `load_in_8bit=False`.
129130

130131
</Tip>
131132

docs/source/optimization_ov.mdx

+86-55
Original file line numberDiff line numberDiff line change
@@ -19,27 +19,95 @@ limitations under the License.
1919
🤗 Optimum Intel provides an `openvino` package that enables you to apply a variety of model compression methods such as quantization, pruning, on many models hosted on the 🤗 hub using the [NNCF](https://docs.openvino.ai/2022.1/docs_nncf_introduction.html) framework.
2020

2121

22-
## Post-training optimization
22+
## Post-training
2323

24-
Post-training static quantization introduces an additional calibration step where data is fed through the network in order to compute the activations quantization parameters.
25-
Here is how to apply static quantization on a fine-tuned DistilBERT:
24+
Quantization is a technique to reduce the computational and memory costs of running inference by representing the weights and / or the activations with lower precision data types like 8-bit or 4-bit.
25+
26+
### Weight-only quantization
27+
28+
Quantization can be applied on the model's Linear, Convolutional and Embedding layers, enabling the loading of large models on memory-limited devices. For example, when applying 8-bit quantization, the resulting model will be x4 smaller than its fp32 counterpart. For 4-bit quantization, the reduction in memory could theoretically reach x8, but is closer to x6 in practice.
29+
30+
31+
#### 8-bit
32+
33+
For the 8-bit weight quantization you can set `load_in_8bit=True` to load your model's weights in 8-bit:
2634

2735
```python
28-
from functools import partial
29-
from transformers import AutoTokenizer
30-
from optimum.intel import OVConfig, OVQuantizer, OVModelForSequenceClassification,
36+
from optimum.intel import OVModelForCausalLM
37+
38+
model_id = "helenai/gpt2-ov"
39+
model = OVModelForCausalLM.from_pretrained(model_id, load_in_8bit=True)
40+
41+
# Saves the int8 model that will be x4 smaller than its fp32 counterpart
42+
model.save_pretrained(saving_directory)
43+
```
44+
45+
<Tip warning={true}>
46+
47+
`load_in_8bit` is enabled by default for the models larger than 1 billion parameters. You can disable it with `load_in_8bit=False`.
48+
49+
</Tip>
50+
51+
You can also provide a `quantization_config` instead to specify additional optimization parameters.
52+
53+
#### 4-bit
54+
55+
For the 4-bit weight quantization, you need a `quantization_config` to define the optimization parameters, for example:
56+
57+
```python
58+
from optimum.intel import OVModelForCausalLM, OVWeightQuantizationConfig
59+
60+
quantization_config = OVWeightQuantizationConfig(bits=4)
61+
model = OVModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config)
62+
```
63+
64+
You can tune quantization parameters to achieve a better performance accuracy trade-off as follows:
65+
66+
```python
67+
quantization_config = OVWeightQuantizationConfig(bits=4, sym=False, ratio=0.8, dataset="ptb")
68+
```
69+
70+
By default the quantization scheme will be [asymmetric](https://github.com/openvinotoolkit/nncf/blob/develop/docs/compression_algorithms/Quantization.md#asymmetric-quantization), to make it [symmetric](https://github.com/openvinotoolkit/nncf/blob/develop/docs/compression_algorithms/Quantization.md#symmetric-quantization) you can add `sym=True`.
71+
72+
For 4-bit quantization you can also specify the following arguments in the quantization configuration :
73+
* The `group_size` parameter will define the group size to use for quantization, `-1` it will results in per-column quantization.
74+
* The `ratio` parameter controls the ratio between 4-bit and 8-bit quantization. If set to 0.9, it means that 90% of the layers will be quantized to `int4` while 10% will be quantized to `int8`.
75+
76+
Smaller `group_size` and `ratio` values usually improve accuracy at the sacrifice of the model size and inference latency.
77+
78+
### Static quantization
79+
80+
When applying post-training static quantization, both the weights and the activations are quantized.
81+
To apply quantization on the activations, an additional calibration step is needed which consists in feeding a `calibration_dataset` to the network in order to estimate the quantization activations parameters.
82+
83+
Here is how to apply static quantization on a fine-tuned DistilBERT given your own `calibration_dataset`:
84+
85+
```python
86+
from transformers import AutoTokenizer
87+
from optimum.intel import OVQuantizer, OVModelForSequenceClassification,
3188

3289
model_id = "distilbert-base-uncased-finetuned-sst-2-english"
3390
model = OVModelForSequenceClassification.from_pretrained(model_id, export=True)
3491
tokenizer = AutoTokenizer.from_pretrained(model_id)
3592
# The directory where the quantized model will be saved
3693
save_dir = "ptq_model"
3794

95+
quantizer = OVQuantizer.from_pretrained(model)
96+
97+
# Apply static quantization and export the resulting quantized model to OpenVINO IR format
98+
quantizer.quantize(calibration_dataset=calibration_dataset, save_directory=save_dir)
99+
# Save the tokenizer
100+
tokenizer.save_pretrained(save_dir)
101+
```
102+
103+
The calibration dataset can also be created easily using your `OVQuantizer`:
104+
105+
```python
106+
from functools import partial
107+
38108
def preprocess_function(examples, tokenizer):
39109
return tokenizer(examples["sentence"], padding="max_length", max_length=128, truncation=True)
40110

41-
# Instantiate our OVQuantizer using the desired configuration
42-
quantizer = OVQuantizer.from_pretrained(model)
43111
# Create the calibration dataset used to perform static quantization
44112
calibration_dataset = quantizer.get_calibration_dataset(
45113
"glue",
@@ -48,33 +116,23 @@ calibration_dataset = quantizer.get_calibration_dataset(
48116
num_samples=300,
49117
dataset_split="train",
50118
)
51-
# Apply static quantization and export the resulting quantized model to OpenVINO IR format
52-
quantizer.quantize(
53-
calibration_dataset=calibration_dataset,
54-
save_directory=save_dir,
55-
)
56-
# Save the tokenizer
57-
tokenizer.save_pretrained(save_dir)
58119
```
59120

60-
The `quantize()` method applies post-training static quantization and export the resulting quantized model to the OpenVINO Intermediate Representation (IR). The resulting graph is represented with two files: an XML file describing the network topology and a binary file describing the weights. The resulting model can be run on any target Intel device.
61121

62-
## Weight-only quantization
122+
The `quantize()` method applies post-training static quantization and export the resulting quantized model to the OpenVINO Intermediate Representation (IR). The resulting graph is represented with two files: an XML file describing the network topology and a binary file describing the weights. The resulting model can be run on any target Intel device.
63123

64-
You can optimize the performance of text-generation LLMs by quantizing weights to various precisions that provide different performance-accuracy trade-offs.
65124

66-
```python
67-
from optimum.intel import OVModelForCausalLM
125+
### Hybrid quantization
68126

69-
model = OVModelForCausalLM.from_pretrained(model_id, load_in_8bit=True)
70-
```
127+
Traditional optimization methods like post-training 8-bit quantization do not work well for Stable Diffusion (SD) models and can lead to poor generation results. On the other hand, weight compression does not improve performance significantly when applied to Stable Diffusion models, as the size of activations is comparable to weights.
128+
The U-Net component takes up most of the overall execution time of the pipeline. Thus, optimizing just this one component can bring substantial benefits in terms of inference speed while keeping acceptable accuracy without fine-tuning. Quantizing the rest of the diffusion pipeline does not significantly improve inference performance but could potentially lead to substantial accuracy degradation.
129+
Therefore, the proposal is to apply quantization in *hybrid mode* for the U-Net model and weight-only quantization for the rest of the pipeline components :
130+
* U-Net : quantization applied on both the weights and activations
131+
* The text encoder, VAE encoder / decoder : quantization applied on the weights
71132

72-
## Hybrid quantization
133+
The hybrid mode involves the quantization of weights in MatMul and Embedding layers, and activations of other layers, facilitating accuracy preservation post-optimization while reducing the model size.
73134

74-
Traditional optimization methods like post-training 8-bit quantization do not work well for Stable Diffusion models and can lead to poor generation results. On the other hand, weight compression does not improve performance significantly when applied to Stable Diffusion models, as the size of activations is comparable to weights.
75-
The UNet model takes up most of the overall execution time of the pipeline. Thus, optimizing just one model brings substantial benefits in terms of inference speed while keeping acceptable accuracy without fine-tuning. Quantizing the rest of the diffusion pipeline does not significantly improve inference performance but could potentially lead to substantial degradation of accuracy.
76-
Therefore, the proposal is to apply quantization in *hybrid mode* for the UNet model and weight-only quantization for the rest of the pipeline components. The hybrid mode involves the quantization of weights in MatMul and Embedding layers, and activations of other layers, facilitating accuracy preservation post-optimization while reducing the model size.
77-
The `quantization_config` is utilized to define optimization parameters for optimizing the Stable Diffusion pipeline. To enable hybrid quantization, specify the quantization dataset in the `quantization_config`. Otherwise, weight-only quantization to a specified data type (8 tr 4 bits) is applied to UNet model.
135+
The `quantization_config` is utilized to define optimization parameters for optimizing the SD pipeline. To enable hybrid quantization, specify the quantization dataset in the `quantization_config`. If the dataset is not defined, weight-only quantization will be applied on all components.
78136

79137
```python
80138
from optimum.intel import OVStableDiffusionPipeline, OVWeightQuantizationConfig
@@ -86,38 +144,11 @@ model = OVStableDiffusionPipeline.from_pretrained(
86144
)
87145
```
88146

89-
<Tip warning={true}>
90-
91-
`load_in_8bit` is enabled by default for the models larger than 1 billion parameters.
92-
93-
</Tip>
94-
95-
For the 4-bit weight quantization you can use the `quantization_config` to specify the optimization parameters, for example:
96-
97-
```python
98-
from optimum.intel import OVModelForCausalLM, OVWeightQuantizationConfig
99-
100-
model = OVModelForCausalLM.from_pretrained(
101-
model_id,
102-
quantization_config=OVWeightQuantizationConfig(bits=4),
103-
)
104-
```
105-
106-
You can tune quantization parameters to achieve a better performance accuracy trade-off as follows:
107-
108-
```python
109-
from optimum.intel import OVModelForCausalLM, OVWeightQuantizationConfig
110-
111-
model = OVModelForCausalLM.from_pretrained(
112-
model_id,
113-
quantization_config=OVWeightQuantizationConfig(bits=4, sym=False, ratio=0.8, dataset="ptb"),
114-
)
115-
```
116147

117148
For more details, please refer to the corresponding NNCF [documentation](https://github.com/openvinotoolkit/nncf/blob/develop/docs/compression_algorithms/CompressWeights.md).
118149

119150

120-
## Training-time optimization
151+
## Training-time
121152

122153
Apart from optimizing a model after training like post-training quantization above, `optimum.openvino` also provides optimization methods during training, namely Quantization-Aware Training (QAT) and Joint Pruning, Quantization and Distillation (JPQD).
123154

optimum/exporters/openvino/__init__.py

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import optimum.exporters.openvino.model_configs
16+
1517
from .__main__ import main_export
1618
from .convert import export, export_from_model, export_models, export_pytorch_via_onnx
1719
from .stateful import ensure_stateful_is_available, patch_stateful

optimum/exporters/openvino/__main__.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def main_export(
5757
local_files_only: bool = False,
5858
use_auth_token: Optional[Union[bool, str]] = None,
5959
model_kwargs: Optional[Dict[str, Any]] = None,
60-
custom_onnx_configs: Optional[Dict[str, "OnnxConfig"]] = None,
60+
custom_export_configs: Optional[Dict[str, "OnnxConfig"]] = None,
6161
fn_get_submodels: Optional[Callable] = None,
6262
compression_option: Optional[str] = None,
6363
compression_ratio: Optional[float] = None,
@@ -111,11 +111,11 @@ def main_export(
111111
when running `transformers-cli login` (stored in `~/.huggingface`).
112112
model_kwargs (`Optional[Dict[str, Any]]`, defaults to `None`):
113113
Experimental usage: keyword arguments to pass to the model during
114-
the export. This argument should be used along the `custom_onnx_configs` argument
114+
the export. This argument should be used along the `custom_export_configs` argument
115115
in case, for example, the model inputs/outputs are changed (for example, if
116116
`model_kwargs={"output_attentions": True}` is passed).
117-
custom_onnx_configs (`Optional[Dict[str, OnnxConfig]]`, defaults to `None`):
118-
Experimental usage: override the default ONNX config used for the given model. This argument may be useful for advanced users that desire a finer-grained control on the export. An example is available [here](https://huggingface.co/docs/optimum/main/en/exporters/onnx/usage_guides/export_a_model).
117+
custom_export_configs (`Optional[Dict[str, OnnxConfig]]`, defaults to `None`):
118+
Experimental usage: override the default export config used for the given model. This argument may be useful for advanced users that desire a finer-grained control on the export. An example is available [here](https://huggingface.co/docs/optimum/main/en/exporters/onnx/usage_guides/export_a_model).
119119
fn_get_submodels (`Optional[Callable]`, defaults to `None`):
120120
Experimental usage: Override the default submodels that are used at the export. This is
121121
especially useful when exporting a custom architecture that needs to split the ONNX (e.g. encoder-decoder). If unspecified with custom models, optimum will try to use the default submodels used for the given task, with no guarantee of success.
@@ -133,7 +133,7 @@ def main_export(
133133
```python
134134
>>> from optimum.exporters.openvino import main_export
135135
136-
>>> main_export("gpt2", output="gpt2_onnx/")
136+
>>> main_export("gpt2", output="gpt2_ov/")
137137
```
138138
"""
139139

@@ -199,14 +199,14 @@ def main_export(
199199
if model_type not in TasksManager._SUPPORTED_MODEL_TYPE:
200200
custom_architecture = True
201201
elif task not in TasksManager.get_supported_tasks_for_model_type(
202-
model_type, exporter="onnx", library_name=library_name
202+
model_type, exporter="openvino", library_name=library_name
203203
):
204204
if original_task == "auto":
205205
autodetected_message = " (auto-detected)"
206206
else:
207207
autodetected_message = ""
208208
model_tasks = TasksManager.get_supported_tasks_for_model_type(
209-
model_type, exporter="onnx", library_name=library_name
209+
model_type, exporter="openvino", library_name=library_name
210210
)
211211
raise ValueError(
212212
f"Asked to export a {model_type} model for the task {task}{autodetected_message}, but the Optimum OpenVINO exporter only supports the tasks {', '.join(model_tasks.keys())} for {model_type}. Please use a supported task. Please open an issue at https://github.com/huggingface/optimum/issues if you would like the task {task} to be supported in the ONNX export for {model_type}."
@@ -281,7 +281,7 @@ class StoreAttr(object):
281281
not custom_architecture
282282
and library_name != "diffusers"
283283
and task + "-with-past"
284-
in TasksManager.get_supported_tasks_for_model_type(model_type, exporter="onnx", library_name=library_name)
284+
in TasksManager.get_supported_tasks_for_model_type(model_type, exporter="openvino", library_name=library_name)
285285
):
286286
# Make -with-past the default if --task was not explicitely specified
287287
if original_task == "auto":
@@ -312,7 +312,7 @@ class StoreAttr(object):
312312
ov_config=ov_config,
313313
stateful=stateful,
314314
model_kwargs=model_kwargs,
315-
custom_onnx_configs=custom_onnx_configs,
315+
custom_export_configs=custom_export_configs,
316316
fn_get_submodels=fn_get_submodels,
317317
preprocessors=preprocessors,
318318
device=device,

0 commit comments

Comments
 (0)