Stage Harbor release files 39001-39500
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_infer_gpu_one.md +297 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_torch_compile.md +71 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_cpu.md +52 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_cpu_many.md +274 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_gaudi.md +34 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_gpu_many.md +124 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_gpu_one.md +296 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_special.md +31 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perplexity.md +150 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/philosophy.md +79 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/pipeline_gradio.md +52 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/pipeline_tutorial.md +345 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/pipeline_webserver.md +162 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/pr_checks.md +200 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/processors.md +131 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/aqlm.md +56 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/auto_round.md +286 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/awq.md +251 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/bitnet.md +48 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/bitsandbytes.md +338 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/compressed_tensors.md +190 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/concept_guide.md +178 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/contribute.md +71 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/eetq.md +65 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/fbgemm_fp8.md +56 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/finegrained_fp8.md +62 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/fp_quant.md +66 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/gptq.md +171 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/higgs.md +80 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/hqq.md +101 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/optimum.md +19 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/overview.md +61 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/quanto.md +69 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/quark.md +83 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/selecting.md +157 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/spqr.md +40 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/torchao.md +675 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/vptq.md +72 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quicktour.md +361 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/reference/environment_variables.md +58 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/run_scripts.md +211 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/serialization.md +99 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/serving.md +371 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/asr.md +371 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/audio_classification.md +324 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/document_question_answering.md +492 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/idefics.md +423 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/image_captioning.md +277 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/image_classification.md +542 -0
- tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/image_feature_extraction.md +134 -0
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_infer_gpu_one.md
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 11 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 12 |
+
rendered properly in your Markdown viewer.
|
| 13 |
+
|
| 14 |
+
-->
|
| 15 |
+
|
| 16 |
+
# GPU
|
| 17 |
+
|
| 18 |
+
GPUs are the standard hardware for machine learning because they're optimized for memory bandwidth and parallelism. With the increasing sizes of modern models, it's more important than ever to make sure GPUs are capable of efficiently handling and delivering the best possible performance.
|
| 19 |
+
|
| 20 |
+
This guide will demonstrate a few ways to optimize inference on a GPU. The optimization methods shown below can be combined with each other to achieve even better performance, and they also work for distributed GPUs.
|
| 21 |
+
|
| 22 |
+
## bitsandbytes
|
| 23 |
+
|
| 24 |
+
[bitsandbytes](https://hf.co/docs/bitsandbytes/index) is a quantization library that supports 8-bit and 4-bit quantization. Quantization represents weights in a lower precision compared to the original full precision format. It reduces memory requirements and makes it easier to fit large model into memory.
|
| 25 |
+
|
| 26 |
+
Make sure bitsandbytes and Accelerate are installed first.
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
pip install bitsandbytes accelerate
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
<hfoptions id="bnb">
|
| 33 |
+
<hfoption id="8-bit">
|
| 34 |
+
|
| 35 |
+
For text generation with 8-bit quantization, you should use [`~GenerationMixin.generate`] instead of the high-level [`Pipeline`] API. The [`Pipeline`] returns slower performance because it isn't optimized for 8-bit models, and some sampling strategies (nucleus sampling) also aren't supported.
|
| 36 |
+
|
| 37 |
+
Set up a [`BitsAndBytesConfig`] and set `load_in_8bit=True` to load a model in 8-bit precision. The [`BitsAndBytesConfig`] is passed to the `quantization_config` parameter in [`~PreTrainedModel.from_pretrained`].
|
| 38 |
+
|
| 39 |
+
Allow Accelerate to automatically distribute the model across your available hardware by setting [device_map="auto"](https://hf.co/docs/accelerate/concept_guides/big_model_inference#designing-a-device-map).
|
| 40 |
+
|
| 41 |
+
Place all inputs on the same device as the model.
|
| 42 |
+
|
| 43 |
+
```py
|
| 44 |
+
from transformers import BitsAndBytesConfig, AutoTokenizer, AutoModelForCausalLM
|
| 45 |
+
|
| 46 |
+
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
|
| 47 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B")
|
| 48 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B", device_map="auto", quantization_config=quantization_config)
|
| 49 |
+
|
| 50 |
+
prompt = "Hello, my llama is cute"
|
| 51 |
+
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
|
| 52 |
+
generated_ids = model.generate(**inputs)
|
| 53 |
+
outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
For distributed setups, use the `max_memory` parameter to create a mapping of the amount of memory to allocate to each GPU. The example below distributes 16GB of memory to the first GPU and 16GB of memory to the second GPU.
|
| 57 |
+
|
| 58 |
+
```py
|
| 59 |
+
max_memory_mapping = {0: "16GB", 1: "16GB"}
|
| 60 |
+
model_8bit = AutoModelForCausalLM.from_pretrained(
|
| 61 |
+
"meta-llama/Llama-3.1-8B", device_map="auto", quantization_config=quantization_config, max_memory=max_memory_mapping
|
| 62 |
+
)
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
Learn in more detail the concepts underlying 8-bit quantization in the [Gentle Introduction to 8-bit Matrix Multiplication for transformers at scale using Hugging Face Transformers, Accelerate and bitsandbytes](https://hf.co/blog/hf-bitsandbytes-integration) blog post.
|
| 66 |
+
|
| 67 |
+
</hfoption>
|
| 68 |
+
<hfoption id="4-bit">
|
| 69 |
+
|
| 70 |
+
Set up a [`BitsAndBytesConfig`] and set `load_in_4bit=True` to load a model in 4-bit precision. The [`BitsAndBytesConfig`] is passed to the `quantization_config` parameter in [`~PreTrainedModel.from_pretrained`].
|
| 71 |
+
|
| 72 |
+
Allow Accelerate to automatically distribute the model across your available hardware by setting `device_map=“auto”`.
|
| 73 |
+
|
| 74 |
+
Place all inputs on the same device as the model.
|
| 75 |
+
|
| 76 |
+
```py
|
| 77 |
+
from transformers import BitsAndBytesConfig, AutoTokenizer, AutoModelForCausalLM
|
| 78 |
+
|
| 79 |
+
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 80 |
+
tokenizer = AutoTokenizer("meta-llama/Llama-3.1-8B")
|
| 81 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B", device_map="auto", quantization_config=quantization_config)
|
| 82 |
+
|
| 83 |
+
prompt = "Hello, my llama is cute"
|
| 84 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model_8bit.device)
|
| 85 |
+
generated_ids = model_8bit.generate(**inputs)
|
| 86 |
+
outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
For distributed setups, use the `max_memory` parameter to create a mapping of the amount of memory to allocate to each GPU. The example below distributes 16GB of memory to the first GPU and 16GB of memory to the second GPU.
|
| 90 |
+
|
| 91 |
+
```py
|
| 92 |
+
max_memory_mapping = {0: "16GB", 1: "16GB"}
|
| 93 |
+
model_4bit = AutoModelForCausalLM.from_pretrained(
|
| 94 |
+
"meta-llama/Llama-3.1-8B", device_map="auto", quantization_config=quantization_config, max_memory=max_memory_mapping
|
| 95 |
+
)
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
</hfoption>
|
| 99 |
+
</hfoptions>
|
| 100 |
+
|
| 101 |
+
## Optimum
|
| 102 |
+
|
| 103 |
+
[Optimum](https://hf.co/docs/optimum/en/index) is a Hugging Face library focused on optimizing model performance across various hardware. It supports [ONNX Runtime](https://onnxruntime.ai/docs/) (ORT), a model accelerator, for a wide range of hardware and frameworks including NVIDIA GPUs and AMD GPUs that use the [ROCm](https://www.amd.com/en/products/software/rocm.html) stack.
|
| 104 |
+
|
| 105 |
+
ORT uses optimization techniques that fuse common operations into a single node and constant folding to reduce the number of computations. ORT also places the most computationally intensive operations on the GPU and the rest on the CPU to intelligently distribute the workload between the two devices.
|
| 106 |
+
|
| 107 |
+
Optimum provides the [`~optimum.onnxruntime.ORTModel`] class for loading ONNX models. Set the `provider` parameter according to the table below.
|
| 108 |
+
|
| 109 |
+
| provider | hardware |
|
| 110 |
+
|---|---|
|
| 111 |
+
| [CUDAExecutionProvider](https://hf.co/docs/optimum/main/en/onnxruntime/usage_guides/gpu#cudaexecutionprovider) | CUDA-enabled GPUs |
|
| 112 |
+
| [ROCMExecutionProvider](https://hf.co/docs/optimum/onnxruntime/usage_guides/amdgpu) | AMD Instinct, Radeon Pro, Radeon GPUs |
|
| 113 |
+
| [TensorrtExecutionProvider](https://hf.co/docs/optimum/onnxruntime/usage_guides/gpu#tensorrtexecutionprovider) | TensorRT |
|
| 114 |
+
|
| 115 |
+
For example, load the [distilbert/distilbert-base-uncased-finetuned-sst-2-english](https://hf.co/optimum/roberta-base-squad2) checkpoint for sequence classification. This checkpoint contains a [model.onnx](https://hf.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english/blob/main/onnx/model.onnx) file. If a checkpoint doesn't have a `model.onnx` file, set `export=True` to convert a checkpoint on the fly to the ONNX format.
|
| 116 |
+
|
| 117 |
+
```py
|
| 118 |
+
from optimum.onnxruntime import ORTModelForSequenceClassification
|
| 119 |
+
|
| 120 |
+
ort_model = ORTModelForSequenceClassification.from_pretrained(
|
| 121 |
+
"distilbert/distilbert-base-uncased-finetuned-sst-2-english",
|
| 122 |
+
#export=True,
|
| 123 |
+
provider="CUDAExecutionProvider",
|
| 124 |
+
)
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
Now you can use the model for inference in a [`Pipeline`].
|
| 128 |
+
|
| 129 |
+
```py
|
| 130 |
+
from optimum.pipelines import pipeline
|
| 131 |
+
from transformers import AutoTokenizer
|
| 132 |
+
|
| 133 |
+
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased-finetuned-sst-2-english")
|
| 134 |
+
pipeline = pipeline(task="text-classification", model=ort_model, tokenizer=tokenizer, device="cuda:0")
|
| 135 |
+
result = pipeline("Both the music and visual were astounding, not to mention the actors performance.")
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
Learn more details about using ORT with Optimum in the [Accelerated inference on NVIDIA GPUs](https://hf.co/docs/optimum/onnxruntime/usage_guides/gpu#accelerated-inference-on-nvidia-gpus) and [Accelerated inference on AMD GPUs](https://hf.co/docs/optimum/onnxruntime/usage_guides/amdgpu#accelerated-inference-on-amd-gpus) guides.
|
| 139 |
+
|
| 140 |
+
### BetterTransformer
|
| 141 |
+
|
| 142 |
+
[BetterTransformer](https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/) is a *fastpath* execution of specialized Transformers functions directly on the hardware level such as a GPU. There are two main components of the fastpath execution.
|
| 143 |
+
|
| 144 |
+
- fusing multiple operations into a single kernel for faster and more efficient execution
|
| 145 |
+
- skipping unnecessary computation of padding tokens with nested tensors
|
| 146 |
+
|
| 147 |
+
> [!WARNING]
|
| 148 |
+
> Some BetterTransformer features are being upstreamed to Transformers with default support for native [torch.nn.functional.scaled_dot_product_attention](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) (SDPA). BetterTransformer has a wider coverage than the Transformers SDPA integration, but you can expect more and more architectures to natively support SDPA in Transformers.
|
| 149 |
+
|
| 150 |
+
BetterTransformer is available through Optimum with [`~PreTrainedModel.to_bettertransformer`].
|
| 151 |
+
|
| 152 |
+
```py
|
| 153 |
+
from transformers import AutoModelForCausalLM
|
| 154 |
+
|
| 155 |
+
model = AutoModelForCausalLM.from_pretrained("bigscience/bloom")
|
| 156 |
+
model = model.to_bettertransformer()
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
Call [`~PreTrainedModel.reverse_bettertransformer`] and save it first to return the model to the original Transformers model.
|
| 160 |
+
|
| 161 |
+
```py
|
| 162 |
+
model = model.reverse_bettertransformer()
|
| 163 |
+
model.save_pretrained("saved_model")
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
Refer to the benchmarks in [Out of the box acceleration and memory savings of 🤗 decoder models with PyTorch 2.0](https://pytorch.org/blog/out-of-the-box-acceleration/) for BetterTransformer and scaled dot product attention performance. The [BetterTransformer](https://medium.com/pytorch/bettertransformer-out-of-the-box-performance-for-huggingface-transformers-3fbe27d50ab2) blog post also discusses fastpath execution in greater detail if you're interested in learning more.
|
| 167 |
+
|
| 168 |
+
## Scaled dot product attention (SDPA)
|
| 169 |
+
|
| 170 |
+
PyTorch's [torch.nn.functional.scaled_dot_product_attention](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) (SDPA) is a native implementation of the scaled dot product attention mechanism. SDPA is a more efficient and optimized version of the attention mechanism used in transformer models.
|
| 171 |
+
|
| 172 |
+
There are three supported implementations available.
|
| 173 |
+
|
| 174 |
+
- [FlashAttention2](https://github.com/Dao-AILab/flash-attention) only supports models with the fp16 or bf16 torch type. Make sure to cast your model to the appropriate type first.
|
| 175 |
+
- [xFormers](https://github.com/facebookresearch/xformers) or Memory-Efficient Attention is able to support models with the fp32 torch type.
|
| 176 |
+
- C++ implementation of scaled dot product attention
|
| 177 |
+
|
| 178 |
+
SDPA is used by default for PyTorch v2.1.1. and greater when an implementation is available. You could explicitly enable SDPA by setting `attn_implementation="sdpa"` in [`~PreTrainedModel.from_pretrained`] though. Certain attention parameters, such as `head_mask` and `output_attentions=True`, are unsupported and returns a warning that Transformers will fall back to the (slower) eager implementation.
|
| 179 |
+
|
| 180 |
+
Refer to the [AttentionInterface](./attention_interface) guide to learn how to change the attention implementation after loading a model.
|
| 181 |
+
|
| 182 |
+
```py
|
| 183 |
+
from transformers import AutoModelForCausalLM
|
| 184 |
+
|
| 185 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B", device_map="auto", attn_implementation="sdpa")
|
| 186 |
+
|
| 187 |
+
# Change the model's attention dynamically after loading it
|
| 188 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B", device_map="auto")
|
| 189 |
+
model.set_attention_implementation("sdpa")
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
SDPA selects the most performant implementation available, but you can also explicitly select an implementation with [torch.nn.attention.sdpa_kernel](https://pytorch.org/docs/master/backends.html#torch.backends.cuda.sdp_kernel) as a context manager. The example below shows how to enable the FlashAttention2 implementation with `enable_flash=True`.
|
| 193 |
+
|
| 194 |
+
```py
|
| 195 |
+
import torch
|
| 196 |
+
from torch.nn.attention import SDPBackend, sdpa_kernel
|
| 197 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 198 |
+
|
| 199 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B")
|
| 200 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B", device_map="auto").to("cuda")
|
| 201 |
+
|
| 202 |
+
input_text = "Hello, my llama is cute"
|
| 203 |
+
inputs = tokenizer(input_text, return_tensors="pt").to("cuda")
|
| 204 |
+
|
| 205 |
+
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
|
| 206 |
+
outputs = model.generate(**inputs)
|
| 207 |
+
|
| 208 |
+
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
| 209 |
+
```
|
| 210 |
+
|
| 211 |
+
If you encounter the following `RuntimeError`, try installing the nightly version of PyTorch which has broader coverage for FlashAttention.
|
| 212 |
+
|
| 213 |
+
```bash
|
| 214 |
+
RuntimeError: No available kernel. Aborting execution.
|
| 215 |
+
|
| 216 |
+
pip3 install -U --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu118
|
| 217 |
+
```
|
| 218 |
+
|
| 219 |
+
## FlashAttention
|
| 220 |
+
|
| 221 |
+
[FlashAttention](https://github.com/Dao-AILab/flash-attention) is also available as a standalone package. It can significantly speed up inference by:
|
| 222 |
+
|
| 223 |
+
1. additionally parallelizing the attention computation over sequence length
|
| 224 |
+
2. partitioning the work between GPU threads to reduce communication and shared memory reads/writes between them
|
| 225 |
+
|
| 226 |
+
Install FlashAttention first for the hardware you're using.
|
| 227 |
+
|
| 228 |
+
<hfoptions id="install">
|
| 229 |
+
<hfoption id="NVIDIA">
|
| 230 |
+
|
| 231 |
+
```bash
|
| 232 |
+
pip install flash-attn --no-build-isolation
|
| 233 |
+
```
|
| 234 |
+
|
| 235 |
+
</hfoption>
|
| 236 |
+
<hfoption id="AMD">
|
| 237 |
+
|
| 238 |
+
FlashAttention2 support is currently limited to Instinct MI210, Instinct MI250 and Instinct MI300. We strongly suggest running this [Dockerfile](https://github.com/huggingface/optimum-amd/tree/main/docker/transformers-pytorch-amd-gpu-flash/Dockerfile) for FlashAttention2 on AMD GPUs.
|
| 239 |
+
|
| 240 |
+
</hfoption>
|
| 241 |
+
</hfoptions>
|
| 242 |
+
|
| 243 |
+
Enable FlashAttention2 by setting `attn_implementation="flash_attention_2"` in [`~PreTrainedModel.from_pretrained`] or by setting `model.set_attention_implementation("flash_attention_2")` to dynamically update the [attention interface](./attention_interface). FlashAttention2 is only supported for models with the fp16 or bf16 torch type. Make sure to cast your model to the appropriate data type first.
|
| 244 |
+
|
| 245 |
+
```py
|
| 246 |
+
from transformers import AutoModelForCausalLM
|
| 247 |
+
|
| 248 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B", device_map="auto", torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2")
|
| 249 |
+
```
|
| 250 |
+
|
| 251 |
+
### Benchmarks
|
| 252 |
+
|
| 253 |
+
FlashAttention2 speeds up inference considerably especially for inputs with long sequences. However, since FlashAttention2 doesn't support computing attention scores with padding tokens, you must manually pad and unpad the attention scores for batched inference if a sequence contains padding tokens. The downside is batched generation is slower with padding tokens.
|
| 254 |
+
|
| 255 |
+
<hfoptions id="padded">
|
| 256 |
+
<hfoption id="short sequence length">
|
| 257 |
+
|
| 258 |
+
With a relatively small sequence length, a single forward pass creates overhead leading to a small speed up. The graph below shows the expected speed up for a single forward pass with [meta-llama/Llama-7b-hf](https://hf.co/meta-llama/Llama-7b-hf) with padding.
|
| 259 |
+
|
| 260 |
+
<div class="flex justify-center">
|
| 261 |
+
<img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/llama-2-small-seqlen-padding.png"/>
|
| 262 |
+
</div>
|
| 263 |
+
|
| 264 |
+
</hfoption>
|
| 265 |
+
<hfoption id="long sequence length">
|
| 266 |
+
|
| 267 |
+
You can train on much longer sequence lengths without running into out-of-memory issues with FlashAttention2, and potentially reduce memory usage up to 20x. The speed up benefits are even better. The graph below shows the expected speed up for a single forward pass with [meta-llama/Llama-7b-hf](https://hf.co/meta-llama/Llama-7b-hf) with padding on a longer sequence length.
|
| 268 |
+
|
| 269 |
+
<div class="flex justify-center">
|
| 270 |
+
<img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/llama-2-large-seqlen-padding.png"/>
|
| 271 |
+
</div>
|
| 272 |
+
|
| 273 |
+
</hfoption>
|
| 274 |
+
</hfoptions>
|
| 275 |
+
|
| 276 |
+
To avoid this slowdown, use FlashAttention2 without padding tokens in the sequence during training. Pack the dataset or concatenate sequences until reaching the maximum sequence length.
|
| 277 |
+
|
| 278 |
+
<hfoptions id="not-padded">
|
| 279 |
+
<hfoption id="tiiuae/falcon-7b">
|
| 280 |
+
|
| 281 |
+
The graph below shows the expected speed up for a single forward pass with [tiiuae/falcon-7b](https://hf.co/tiiuae/falcon-7b) with a sequence length of 4096 and various batch sizes without padding tokens.
|
| 282 |
+
|
| 283 |
+
<div class="flex justify-center">
|
| 284 |
+
<img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/falcon-7b-inference-large-seqlen.png"/>
|
| 285 |
+
</div>
|
| 286 |
+
|
| 287 |
+
</hfoption>
|
| 288 |
+
<hfoption id="meta-llama/Llama-7b-hf">
|
| 289 |
+
|
| 290 |
+
The graph below shows the expected speed up for a single forward pass with [meta-llama/Llama-7b-hf](https://hf.co/meta-llama/Llama-7b-hf) with a sequence length of 4096 and various batch sizes without padding tokens.
|
| 291 |
+
|
| 292 |
+
<div class="flex justify-center">
|
| 293 |
+
<img src="https://huggingface.co/datasets/ybelkada/documentation-images/resolve/main/llama-7b-inference-large-seqlen.png"/>
|
| 294 |
+
</div>
|
| 295 |
+
|
| 296 |
+
</hfoption>
|
| 297 |
+
</hfoptions>
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_torch_compile.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 11 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 12 |
+
rendered properly in your Markdown viewer.
|
| 13 |
+
|
| 14 |
+
-->
|
| 15 |
+
|
| 16 |
+
# torch.compile
|
| 17 |
+
|
| 18 |
+
[torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) compiles PyTorch code into optimized kernels that significantly speed up inference. This feature relies on [TorchDynamo](https://pytorch.org/docs/stable/torch.compiler_dynamo_overview.html) to compile the code into graphs and [TorchInductor](https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747) to further compile the graphs into optimized kernels. It is a powerful optimization tool, and in many cases, only requires adding a single line of code.
|
| 19 |
+
|
| 20 |
+
Wrap a model with torch.compile to compile and return an optimized model.
|
| 21 |
+
|
| 22 |
+
```py
|
| 23 |
+
from transformers import AutoModelForCausalLM
|
| 24 |
+
|
| 25 |
+
model = AutoModelForCausalLM.from_pretrained("google/gemma-2b", device_map="auto")
|
| 26 |
+
compiled_model = torch.compile(model)
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
> [!TIP]
|
| 30 |
+
> The initial call to torch.compile is slow because the model needs to be compiled. Subsequent calls to the compiled model are much faster because it doesn't need to compile again.
|
| 31 |
+
|
| 32 |
+
There are several parameters to customize the compilation process. Two of the more important ones are listed below. For a full list of parameters, refer to the torch.compile [documentation](https://pytorch.org/docs/stable/generated/torch.compile.html).
|
| 33 |
+
|
| 34 |
+
## Modes
|
| 35 |
+
|
| 36 |
+
The `mode` parameter offers several performance options for compiling. Try different modes to see which one works best for your use case.
|
| 37 |
+
|
| 38 |
+
- `default` is a balanced option between speed and memory.
|
| 39 |
+
- `reduce-overhead` reduces the Python overhead at the expense of a little more memory, but it can be faster.
|
| 40 |
+
- `max-autotune` offers the fastest speed, but compilation takes longer.
|
| 41 |
+
|
| 42 |
+
```py
|
| 43 |
+
from transformers import AutoModelForCausalLM
|
| 44 |
+
|
| 45 |
+
model = AutoModelForCausalLM.from_pretrained("google/gemma-2b", device_map="auto")
|
| 46 |
+
compiled_model = torch.compile(model, mode="reduce-overhead")
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
## Fullgraph
|
| 50 |
+
|
| 51 |
+
Fullgraph attempts to compile the entire model into a single graph to maximize performance. torch.compile raises an error if it encounters a graph break, which means it can't compile the model into a single graph.
|
| 52 |
+
|
| 53 |
+
```py
|
| 54 |
+
from transformers import AutoModelForCausalLM
|
| 55 |
+
|
| 56 |
+
model = AutoModelForCausalLM.from_pretrained("google/gemma-2b", device_map="auto")
|
| 57 |
+
compiled_model = torch.compile(model, mode="reduce-overhead", fullgraph=True)
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
## Benchmarks
|
| 61 |
+
|
| 62 |
+
Refer to the table below for performance benchmarks comparing the mean inference time in milliseconds with torch.compile enabled and disabled across various GPUs and batch sizes on the same image for different vision tasks.
|
| 63 |
+
|
| 64 |
+
Select **Subset** in the table below to switch between different GPUs, as well as benchmarks on [PyTorch nightly](https://download.pytorch.org/whl/nightly/cu118) 2.1.0dev and torch.compile with `reduce-overhead` mode enabled.
|
| 65 |
+
|
| 66 |
+
<iframe
|
| 67 |
+
src="https://huggingface.co/datasets/stevhliu/compile-benchmarks/embed/viewer/t4/train"
|
| 68 |
+
frameborder="0"
|
| 69 |
+
width="100%"
|
| 70 |
+
height="560px"
|
| 71 |
+
></iframe>
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_cpu.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 11 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 12 |
+
rendered properly in your Markdown viewer.
|
| 13 |
+
|
| 14 |
+
-->
|
| 15 |
+
|
| 16 |
+
# CPU
|
| 17 |
+
|
| 18 |
+
A modern CPU is capable of efficiently training large models by leveraging the underlying optimizations built into the hardware and training on fp16 or bf16 data types.
|
| 19 |
+
|
| 20 |
+
This guide focuses on how to train large models on an Intel CPU using mixed precision. AMP is enabled for CPU backends training with PyTorch.
|
| 21 |
+
|
| 22 |
+
[`Trainer`] supports AMP training with CPU by adding the `--use_cpu`, and `--bf16` parameters. The example below demonstrates the [run_qa.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering) script.
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
python run_qa.py \
|
| 26 |
+
--model_name_or_path google-bert/bert-base-uncased \
|
| 27 |
+
--dataset_name squad \
|
| 28 |
+
--do_train \
|
| 29 |
+
--do_eval \
|
| 30 |
+
--per_device_train_batch_size 12 \
|
| 31 |
+
--learning_rate 3e-5 \
|
| 32 |
+
--num_train_epochs 2 \
|
| 33 |
+
--max_seq_length 384 \
|
| 34 |
+
--doc_stride 128 \
|
| 35 |
+
--output_dir /tmp/debug_squad/ \
|
| 36 |
+
--bf16 \
|
| 37 |
+
--use_cpu
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
These parameters can also be added to [`TrainingArguments`] as shown below.
|
| 41 |
+
|
| 42 |
+
```py
|
| 43 |
+
training_args = TrainingArguments(
|
| 44 |
+
output_dir="./outputs",
|
| 45 |
+
bf16=True,
|
| 46 |
+
use_cpu=True,
|
| 47 |
+
)
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## Resources
|
| 51 |
+
|
| 52 |
+
Learn more about training on Intel CPUs in the [Accelerating PyTorch Transformers with Intel Sapphire Rapids](https://huggingface.co/blog/intel-sapphire-rapids) blog post.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_cpu_many.md
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 11 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 12 |
+
rendered properly in your Markdown viewer.
|
| 13 |
+
|
| 14 |
+
-->
|
| 15 |
+
|
| 16 |
+
# Distributed CPUs
|
| 17 |
+
|
| 18 |
+
CPUs are commonly available and can be a cost-effective training option when GPUs are unavailable. When training large models or if a single CPU is too slow, distributed training with CPUs can help speed up training.
|
| 19 |
+
|
| 20 |
+
This guide demonstrates how to perform distributed training with multiple CPUs using a [DistributedDataParallel (DDP)](./perf_train_gpu_many#distributeddataparallel) strategy on bare metal with [`Trainer`] and a Kubernetes cluster. All examples shown in this guide depend on the [Intel oneAPI HPC Toolkit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/hpc-toolkit.html).
|
| 21 |
+
|
| 22 |
+
There are two toolkits you'll need from Intel oneAPI.
|
| 23 |
+
|
| 24 |
+
1. [oneCCL](https://www.intel.com/content/www/us/en/developer/tools/oneapi/oneccl.html) includes efficient implementations of collectives commonly used in deep learning such as all-gather, all-reduce, and reduce-scatter. To install from a prebuilt wheel, make sure you always use the latest release. Refer to the table [here](https://github.com/intel/torch-ccl#install-prebuilt-wheel) to check if a version of oneCCL is supported for a Python and PyTorch version.
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
# installs oneCCL for PyTorch 2.4.0
|
| 28 |
+
pip install oneccl_bind_pt==2.4.0 -f https://developer.intel.com/ipex-whl-stable-cpu
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
> [!TIP]
|
| 32 |
+
> Refer to the oneCCL [installation](https://github.com/intel/torch-ccl#installation) for more details.
|
| 33 |
+
|
| 34 |
+
1. [MPI](https://www.intel.com/content/www/us/en/developer/tools/oneapi/mpi-library.html) is a message-passing interface for communications between hardware and networks. The oneCCL toolkit is installed along with MPI, but you need to source the environment as shown below before using it.
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
oneccl_bindings_for_pytorch_path=$(python -c "from oneccl_bindings_for_pytorch import cwd; print(cwd)")
|
| 38 |
+
source $oneccl_bindings_for_pytorch_path/env/setvars.sh
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
Lastly, install the [Intex Extension for PyTorch (IPEX)](https://intel.github.io/intel-extension-for-pytorch/index.html) which enables additional performance optimizations for Intel hardware such as weight sharing and better thread runtime control.
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
pip install intel_extension_for_pytorch==<version_name> -f https://developer.intel.com/ipex-whl-stable-cpu
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
> [!TIP]
|
| 48 |
+
> Refer to the IPEX [installation](https://intel.github.io/intel-extension-for-pytorch/index.html#installation) for more details.
|
| 49 |
+
|
| 50 |
+
## Trainer
|
| 51 |
+
|
| 52 |
+
[`Trainer`] supports distributed training with CPUs with the oneCCL backend. Add the `--ddp_backend ccl` parameter in the command arguments to enable it.
|
| 53 |
+
|
| 54 |
+
<hfoptions id="distrib-cpu">
|
| 55 |
+
<hfoption id="single node">
|
| 56 |
+
|
| 57 |
+
The example below demonstrates the [run_qa.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering) script. It enables training with two processes on one Xeon CPU, with one process running per socket.
|
| 58 |
+
|
| 59 |
+
> [!TIP]
|
| 60 |
+
> Tune the variable `OMP_NUM_THREADS/CCL_WORKER_COUNT` for optimal performance.
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
export CCL_WORKER_COUNT=1
|
| 64 |
+
export MASTER_ADDR=127.0.0.1
|
| 65 |
+
mpirun -n 2 -genv OMP_NUM_THREADS=23 \
|
| 66 |
+
python3 run_qa.py \
|
| 67 |
+
--model_name_or_path google-bert/bert-large-uncased \
|
| 68 |
+
--dataset_name squad \
|
| 69 |
+
--do_train \
|
| 70 |
+
--do_eval \
|
| 71 |
+
--per_device_train_batch_size 12 \
|
| 72 |
+
--learning_rate 3e-5 \
|
| 73 |
+
--num_train_epochs 2 \
|
| 74 |
+
--max_seq_length 384 \
|
| 75 |
+
--doc_stride 128 \
|
| 76 |
+
--output_dir /tmp/debug_squad/ \
|
| 77 |
+
--no_cuda \
|
| 78 |
+
--ddp_backend ccl
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
</hfoption>
|
| 82 |
+
<hfoption id="multiple nodes">
|
| 83 |
+
|
| 84 |
+
Scale the training script to four processes on two Xeon CPUs (`node0` and `node1`) by setting `-n 4` and `ppn 2`. The `ppn` parameter specifies the number of processes per node, with one process running per socket.
|
| 85 |
+
|
| 86 |
+
Assume `node0` is the main process and create a configuration file containing the IP addresses of each node (for example, hostfile) and pass the configuration file path as an argument.
|
| 87 |
+
|
| 88 |
+
```bash
|
| 89 |
+
cat hostfile
|
| 90 |
+
xxx.xxx.xxx.xxx #node0 ip
|
| 91 |
+
xxx.xxx.xxx.xxx #node1 ip
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
Run the script below on `node0` to enable DDP on `node0` and `node1` and train with bf16 auto mixed precision.
|
| 95 |
+
|
| 96 |
+
> [!TIP]
|
| 97 |
+
> Tune the variable `OMP_NUM_THREADS/CCL_WORKER_COUNT` for optimal performance.
|
| 98 |
+
|
| 99 |
+
```bash
|
| 100 |
+
export CCL_WORKER_COUNT=1
|
| 101 |
+
export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip
|
| 102 |
+
mpirun -f hostfile -n 4 -ppn 2 \
|
| 103 |
+
-genv OMP_NUM_THREADS=23 \
|
| 104 |
+
python3 run_qa.py \
|
| 105 |
+
--model_name_or_path google-bert/bert-large-uncased \
|
| 106 |
+
--dataset_name squad \
|
| 107 |
+
--do_train \
|
| 108 |
+
--do_eval \
|
| 109 |
+
--per_device_train_batch_size 12 \
|
| 110 |
+
--learning_rate 3e-5 \
|
| 111 |
+
--num_train_epochs 2 \
|
| 112 |
+
--max_seq_length 384 \
|
| 113 |
+
--doc_stride 128 \
|
| 114 |
+
--output_dir /tmp/debug_squad/ \
|
| 115 |
+
--no_cuda \
|
| 116 |
+
--ddp_backend ccl \
|
| 117 |
+
--bf16
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
</hfoption>
|
| 121 |
+
</hfoptions>
|
| 122 |
+
|
| 123 |
+
## Kubernetes
|
| 124 |
+
|
| 125 |
+
Distributed training with CPUs can also be deployed to a Kubernetes cluster with [PyTorchJob](https://www.kubeflow.org/docs/components/training/user-guides/pytorch/). Before you get started, you should perform the following setup steps.
|
| 126 |
+
|
| 127 |
+
1. Ensure you have access to a Kubernetes cluster with [Kubeflow](https://www.kubeflow.org/docs/started/installing-kubeflow/) installed.
|
| 128 |
+
1. Install and configure [kubectl](https://kubernetes.io/docs/tasks/tools) to interact with the cluster.
|
| 129 |
+
1. Set up a [PersistentVolumeClaim (PVC)](https://kubernetes.io/docs/concepts/storage/persistent-volumes/) to store datasets and model files. There are multiple options to choose from, including a [StorageClass](https://kubernetes.io/docs/concepts/storage/storage-classes/) or a cloud storage bucket.
|
| 130 |
+
1. Set up a Docker container for the training script and all required dependencies such as PyTorch, Transformers, IPEX, oneCCL, and OpenSSH to facilitate communicattion between containers.
|
| 131 |
+
|
| 132 |
+
The example Dockerfile below uses a base image that supports distributed training with CPUs, and extracts Transformers to the `/workspace` directory to include the training scripts in the image. The image needs to be built and copied to the clusters nodes or pushed to a container registry prior to deployment.
|
| 133 |
+
|
| 134 |
+
```dockerfile
|
| 135 |
+
FROM intel/intel-optimized-pytorch:2.4.0-pip-multinode
|
| 136 |
+
|
| 137 |
+
RUN apt-get update -y && \
|
| 138 |
+
apt-get install -y --no-install-recommends --fix-missing \
|
| 139 |
+
google-perftools \
|
| 140 |
+
libomp-dev
|
| 141 |
+
|
| 142 |
+
WORKDIR /workspace
|
| 143 |
+
|
| 144 |
+
# Download and extract the transformers code
|
| 145 |
+
ARG HF_TRANSFORMERS_VER="4.46.0"
|
| 146 |
+
RUN pip install --no-cache-dir \
|
| 147 |
+
transformers==${HF_TRANSFORMERS_VER} && \
|
| 148 |
+
mkdir transformers && \
|
| 149 |
+
curl -sSL --retry 5 https://github.com/huggingface/transformers/archive/refs/tags/v${HF_TRANSFORMERS_VER}.tar.gz | tar -C transformers --strip-components=1 -xzf -
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
### PyTorchJob
|
| 153 |
+
|
| 154 |
+
[PyTorchJob](https://www.kubeflow.org/docs/components/training/user-guides/pytorch/) is an extension of the Kubernetes API for running PyTorch training jobs on Kubernetes. It includes a yaml file that defines the training jobs parameters such as the name of the PyTorchJob, number of workers, types of resources for each worker, and more.
|
| 155 |
+
|
| 156 |
+
The volume mount parameter is a path to where the PVC is mounted in the container for each worker pod. The PVC is typically used to hold the dataset, checkpoint files, and the model after it has finished training.
|
| 157 |
+
|
| 158 |
+
The example yaml file below sets up four workers on the [run_qa.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering) script. Adapt the yaml file based on your training script and number of nodes in your cluster.
|
| 159 |
+
|
| 160 |
+
The CPU resource limits and requests are defined in [CPU units](https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#meaning-of-cpu). One CPU unit is equivalent to one physical CPU core or virtual core. The CPU units defined in the yaml file should be less than the amount of available CPU and memory capacity of a single machine in order to leave some resources for kubelet and the system. For a `Guaranteed` [quality of service](https://kubernetes.io/docs/tasks/configure-pod-container/quality-service-pod), set the same CPU and memory amounts for both the resource limits and requests.
|
| 161 |
+
|
| 162 |
+
```yaml
|
| 163 |
+
apiVersion: "kubeflow.org/v1"
|
| 164 |
+
kind: PyTorchJob
|
| 165 |
+
metadata:
|
| 166 |
+
name: transformers-pytorchjob
|
| 167 |
+
spec:
|
| 168 |
+
elasticPolicy:
|
| 169 |
+
rdzvBackend: c10d
|
| 170 |
+
minReplicas: 1
|
| 171 |
+
maxReplicas: 4
|
| 172 |
+
maxRestarts: 10
|
| 173 |
+
pytorchReplicaSpecs:
|
| 174 |
+
Worker:
|
| 175 |
+
replicas: 4 # The number of worker pods
|
| 176 |
+
restartPolicy: OnFailure
|
| 177 |
+
template:
|
| 178 |
+
spec:
|
| 179 |
+
containers:
|
| 180 |
+
- name: pytorch
|
| 181 |
+
image: <image name>:<tag> # Specify the docker image to use for the worker pods
|
| 182 |
+
imagePullPolicy: IfNotPresent
|
| 183 |
+
command: ["/bin/bash", "-c"]
|
| 184 |
+
args:
|
| 185 |
+
- >-
|
| 186 |
+
cd /workspace/transformers;
|
| 187 |
+
pip install -r /workspace/transformers/examples/pytorch/question-answering/requirements.txt;
|
| 188 |
+
source /usr/local/lib/python3.10/dist-packages/oneccl_bindings_for_pytorch/env/setvars.sh;
|
| 189 |
+
torchrun /workspace/transformers/examples/pytorch/question-answering/run_qa.py \
|
| 190 |
+
--model_name_or_path distilbert/distilbert-base-uncased \
|
| 191 |
+
--dataset_name squad \
|
| 192 |
+
--do_train \
|
| 193 |
+
--do_eval \
|
| 194 |
+
--per_device_train_batch_size 12 \
|
| 195 |
+
--learning_rate 3e-5 \
|
| 196 |
+
--num_train_epochs 2 \
|
| 197 |
+
--max_seq_length 384 \
|
| 198 |
+
--doc_stride 128 \
|
| 199 |
+
--output_dir /tmp/pvc-mount/output_$(date +%Y%m%d_%H%M%S) \
|
| 200 |
+
--no_cuda \
|
| 201 |
+
--ddp_backend ccl \
|
| 202 |
+
--bf16;
|
| 203 |
+
env:
|
| 204 |
+
- name: LD_PRELOAD
|
| 205 |
+
value: "/usr/lib/x86_64-linux-gnu/libtcmalloc.so.4.5.9:/usr/local/lib/libiomp5.so"
|
| 206 |
+
- name: TRANSFORMERS_CACHE
|
| 207 |
+
value: "/tmp/pvc-mount/transformers_cache"
|
| 208 |
+
- name: HF_DATASETS_CACHE
|
| 209 |
+
value: "/tmp/pvc-mount/hf_datasets_cache"
|
| 210 |
+
- name: LOGLEVEL
|
| 211 |
+
value: "INFO"
|
| 212 |
+
- name: CCL_WORKER_COUNT
|
| 213 |
+
value: "1"
|
| 214 |
+
- name: OMP_NUM_THREADS # Can be tuned for optimal performance
|
| 215 |
+
value: "240"
|
| 216 |
+
resources:
|
| 217 |
+
limits:
|
| 218 |
+
cpu: 240 # Update the CPU and memory limit values based on your nodes
|
| 219 |
+
memory: 128Gi
|
| 220 |
+
requests:
|
| 221 |
+
cpu: 240 # Update the CPU and memory request values based on your nodes
|
| 222 |
+
memory: 128Gi
|
| 223 |
+
volumeMounts:
|
| 224 |
+
- name: pvc-volume
|
| 225 |
+
mountPath: /tmp/pvc-mount
|
| 226 |
+
- mountPath: /dev/shm
|
| 227 |
+
name: dshm
|
| 228 |
+
restartPolicy: Never
|
| 229 |
+
nodeSelector: # Optionally use nodeSelector to match a certain node label for the worker pods
|
| 230 |
+
node-type: gnr
|
| 231 |
+
volumes:
|
| 232 |
+
- name: pvc-volume
|
| 233 |
+
persistentVolumeClaim:
|
| 234 |
+
claimName: transformers-pvc
|
| 235 |
+
- name: dshm
|
| 236 |
+
emptyDir:
|
| 237 |
+
medium: Memory
|
| 238 |
+
```
|
| 239 |
+
|
| 240 |
+
### Deploy
|
| 241 |
+
|
| 242 |
+
After you've setup the PyTorchJob yaml file with the appropriate settings for your cluster and training job, deploy it to the cluster with the command below.
|
| 243 |
+
|
| 244 |
+
```bash
|
| 245 |
+
export NAMESPACE=<specify your namespace>
|
| 246 |
+
|
| 247 |
+
kubectl create -f pytorchjob.yaml -n ${NAMESPACE}
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
List the pods in the namespace with `kubectl get pods -n ${NAMESPACE}`. At first, the status may be "Pending" but it should change to "Running" once the containers are pulled and created.
|
| 251 |
+
|
| 252 |
+
```bash
|
| 253 |
+
kubectl get pods -n ${NAMESPACE}
|
| 254 |
+
|
| 255 |
+
NAME READY STATUS RESTARTS AGE
|
| 256 |
+
...
|
| 257 |
+
transformers-pytorchjob-worker-0 1/1 Running 0 7m37s
|
| 258 |
+
transformers-pytorchjob-worker-1 1/1 Running 0 7m37s
|
| 259 |
+
transformers-pytorchjob-worker-2 1/1 Running 0 7m37s
|
| 260 |
+
transformers-pytorchjob-worker-3 1/1 Running 0 7m37s
|
| 261 |
+
...
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
Inspect the logs for each worker with the following command. Add `-f` to stream the logs.
|
| 265 |
+
|
| 266 |
+
```bash
|
| 267 |
+
kubectl logs transformers-pytorchjob-worker-0 -n ${NAMESPACE} -f
|
| 268 |
+
```
|
| 269 |
+
|
| 270 |
+
Once training is complete, the trained model can be copied from the PVC or storage location. Delete the PyTorchJob resource from the cluster with the command below.
|
| 271 |
+
|
| 272 |
+
```bash
|
| 273 |
+
kubectl delete -f pytorchjob.yaml -n ${NAMESPACE}
|
| 274 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_gaudi.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 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 |
+
|
| 11 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 12 |
+
rendered properly in your Markdown viewer.
|
| 13 |
+
|
| 14 |
+
-->
|
| 15 |
+
|
| 16 |
+
# Intel Gaudi
|
| 17 |
+
|
| 18 |
+
The Intel Gaudi AI accelerator family includes [Intel Gaudi 1](https://habana.ai/products/gaudi/), [Intel Gaudi 2](https://habana.ai/products/gaudi2/), and [Intel Gaudi 3](https://habana.ai/products/gaudi3/). Each server is equipped with 8 devices, known as Habana Processing Units (HPUs), providing 128GB of memory on Gaudi 3, 96GB on Gaudi 2, and 32GB on the first-gen Gaudi. For more details on the underlying hardware architecture, check out the [Gaudi Architecture](https://docs.habana.ai/en/latest/Gaudi_Overview/Gaudi_Architecture.html) overview.
|
| 19 |
+
|
| 20 |
+
[`TrainingArguments`], [`Trainer`] and [`Pipeline`] detect and set the backend device to `hpu` if an Intel Gaudi device is available. No additional changes are required to enable training and inference on your device.
|
| 21 |
+
|
| 22 |
+
Some modeling code in Transformers is not optimized for HPU lazy mode. If you encounter any errors, set the environment variable below to use eager mode:
|
| 23 |
+
```
|
| 24 |
+
PT_HPU_LAZY_MODE=0
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
In some cases, you'll also need to enable int64 support to avoid casting issues with long integers:
|
| 28 |
+
```
|
| 29 |
+
PT_ENABLE_INT64_SUPPORT=1
|
| 30 |
+
```
|
| 31 |
+
Refer to the [Gaudi docs](https://docs.habana.ai/en/latest/index.html) for more details.
|
| 32 |
+
|
| 33 |
+
> [!TIP]
|
| 34 |
+
> For training and inference with Gaudi-optimized model implementations, we recommend using [Optimum for Intel Gaudi](https://huggingface.co/docs/optimum/main/en/habana/index).
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_gpu_many.md
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 11 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 12 |
+
rendered properly in your Markdown viewer.
|
| 13 |
+
|
| 14 |
+
-->
|
| 15 |
+
|
| 16 |
+
# Parallelism methods
|
| 17 |
+
|
| 18 |
+
Multi-GPU setups are effective for accelerating training and fitting large models in memory that otherwise wouldn't fit on a single GPU. It relies on parallelizing the workload across GPUs. There are several types of parallelism such as data parallelism, tensor parallelism, pipeline parallelism, and model parallelism. Each type of parallelism splits the workload differently, whether it's the data or the model.
|
| 19 |
+
|
| 20 |
+
This guide will discuss the various parallelism methods, combining them, and choosing an appropriate strategy for your setup. For more details about distributed training, refer to the [Accelerate](https://hf.co/docs/accelerate/index) documentation.
|
| 21 |
+
|
| 22 |
+
For a comprehensive guide on scaling large language models, check out the [Ultrascale Playbook](https://huggingface.co/spaces/nanotron/ultrascale-playbook), which provides detailed strategies and best practices for training at scale.
|
| 23 |
+
|
| 24 |
+
## Scalability strategy
|
| 25 |
+
|
| 26 |
+
Use the [Model Memory Calculator](https://huggingface.co/spaces/hf-accelerate/model-memory-usage) to calculate how much memory a model requires. Then refer to the table below to select a strategy based on your setup.
|
| 27 |
+
|
| 28 |
+
| setup | scenario | strategy |
|
| 29 |
+
|---|---|---|
|
| 30 |
+
| single node/multi-GPU | fits on single GPU | DistributedDataParallel or ZeRO |
|
| 31 |
+
| | doesn't fit on single GPU | PipelineParallel, ZeRO or TensorParallel |
|
| 32 |
+
| | largest model layer doesn't fit | TensorParallel or ZeRO |
|
| 33 |
+
| multi-node/multi-GPU | fast inter-node connectivity (NVLink or NVSwitch) | ZeRO or 3D parallelism (PipelineParallel, TensorParallel, DataParallel) |
|
| 34 |
+
| | slow inter-node connectivity | ZeRO or 3D parallelism (PipelineParallel, TensorParallel, DataParallel) |
|
| 35 |
+
|
| 36 |
+
## Data parallelism
|
| 37 |
+
|
| 38 |
+
Data parallelism evenly distributes data across multiple GPUs. Each GPU holds a copy of the model and concurrently processes their portion of the data. At the end, the results from each GPU are synchronized and combined.
|
| 39 |
+
|
| 40 |
+
Data parallelism significantly reduces training time by processing data in parallel, and it is scalable to the number of GPUs available. However, synchronizing results from each GPU can add overhead.
|
| 41 |
+
|
| 42 |
+
There are two types of data parallelism, DataParallel (DP) and DistributedDataParallel (DDP).
|
| 43 |
+
|
| 44 |
+
### DataParallel
|
| 45 |
+
|
| 46 |
+
[DataParallel](https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html) supports distributed training on a *single machine* with multiple GPUs.
|
| 47 |
+
|
| 48 |
+
1. The default GPU, `GPU 0`, reads a batch of data and sends a mini batch of it to the other GPUs.
|
| 49 |
+
2. An up-to-date model is replicated from `GPU 0` to the other GPUs.
|
| 50 |
+
3. A `forward` pass is performed on each GPU and their outputs are sent to `GPU 0` to compute the loss.
|
| 51 |
+
4. The loss is distributed from `GPU 0` to the other GPUs for the `backward` pass.
|
| 52 |
+
5. The gradients from each GPU are sent back to `GPU 0` and averaged.
|
| 53 |
+
|
| 54 |
+
### DistributedDataParallel
|
| 55 |
+
|
| 56 |
+
[DistributedDataParallel](https://pytorch.org/docs/main/notes/ddp.html) supports distributed training across *multiple machines* with multiple GPUs.
|
| 57 |
+
|
| 58 |
+
1. The main process replicates the model from the default GPU, `GPU 0`, to each GPU.
|
| 59 |
+
2. Each GPU directly processes a mini batch of data.
|
| 60 |
+
3. The local gradients are averaged across all GPUs during the `backward` pass.
|
| 61 |
+
|
| 62 |
+
DDP is recommended because it reduces communication overhead between GPUs, efficiently utilizes each GPU, and scales to more than one machine.
|
| 63 |
+
|
| 64 |
+
### ZeRO data parallelism
|
| 65 |
+
|
| 66 |
+
[Zero Redundancy Optimizer](https://www.deepspeed.ai/tutorials/zero/) is a more memory efficient type of data parallelism. It significantly improves memory efficiency by partitioning parameters, gradients, and optimizer states across data parallel processes to reduce memory usage. There are three ZeRO stages:
|
| 67 |
+
|
| 68 |
+
- Stage 1 partitions the optimizer states
|
| 69 |
+
- Stage 2 partitions the optimizer and gradient states
|
| 70 |
+
- Stage 3 partitions the optimizer, gradient, and parameters
|
| 71 |
+
|
| 72 |
+
<div class="flex justify-center">
|
| 73 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-zero.png"/>
|
| 74 |
+
</div>
|
| 75 |
+
|
| 76 |
+
## Model parallelism
|
| 77 |
+
|
| 78 |
+
Model parallelism distributes a model across multiple GPUs. There are several ways to split a model, but the typical method distributes the model layers across GPUs. On the `forward` pass, the first GPU processes a batch of data and passes it to the next group of layers on the next GPU. For the `backward` pass, the data is sent backward from the final layer to the first layer.
|
| 79 |
+
|
| 80 |
+
Model parallelism is a useful strategy for training models that are too large to fit into the memory of a single GPU. However, GPU utilization is unbalanced because only one GPU is active at a time. Passing results between GPUs also adds communication overhead and it can be a bottleneck.
|
| 81 |
+
|
| 82 |
+
## Pipeline parallelism
|
| 83 |
+
|
| 84 |
+
Pipeline parallelism is conceptually very similar to model parallelism, but it's more efficient because it reduces the amount of idle GPU time. Instead of waiting for each GPU to finish processing a batch of data, pipeline parallelism creates *micro-batches* of data. As soon as one micro-batch is finished, it is passed to the next GPU. This way, each GPU can concurrently process part of the data without waiting for the other GPU to completely finish processing a mini batch of data.
|
| 85 |
+
|
| 86 |
+
Pipeline parallelism shares the same advantages as model parallelism, but it optimizes GPU utilization and reduces idle time. But pipeline parallelism can be more complex because models may need to be rewritten as a sequence of [nn.Sequential](https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html) modules and it also isn't possible to completely reduce idle time because the last `forward` pass must also wait for the `backward` pass to finish.
|
| 87 |
+
|
| 88 |
+
## Tensor parallelism
|
| 89 |
+
|
| 90 |
+
Tensor parallelism distributes large tensor computations across multiple GPUs. The tensors are sliced horizontally or vertically and each slice is processed by a separate GPU. Each GPU performs its calculations on its tensor slice and the results are synchronized at the end to reconstruct the final result.
|
| 91 |
+
|
| 92 |
+
Tensor parallelism is effective for training large models that don't fit into the memory of a single GPU. It is also faster and more efficient because each GPU can process its tensor slice in parallel, and it can be combined with other parallelism methods. Like other parallelism methods though, tensor parallelism adds communication overhead between GPUs.
|
| 93 |
+
|
| 94 |
+
Refer to the [Tensor parallelism](./perf_infer_gpu_multi) guide to learn how to use it for inference.
|
| 95 |
+
|
| 96 |
+
## Hybrid parallelism
|
| 97 |
+
|
| 98 |
+
Parallelism methods can be combined to achieve even greater memory savings and more efficiently train models with billions of parameters.
|
| 99 |
+
|
| 100 |
+
### Data parallelism and pipeline parallelism
|
| 101 |
+
|
| 102 |
+
Data and pipeline parallelism distributes the data across GPUs and divides each mini batch of data into micro-batches to achieve pipeline parallelism.
|
| 103 |
+
|
| 104 |
+
Each data parallel rank treats the process as if there were only one GPU instead of two, but GPUs 0 and 1 can offload micro-batches of data to GPUs 2 and 3 and reduce idle time.
|
| 105 |
+
|
| 106 |
+
This approach optimizes parallel data processing by reducing idle GPU utilization.
|
| 107 |
+
|
| 108 |
+
<div class="flex justify-center">
|
| 109 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-zero-dp-pp.png"/>
|
| 110 |
+
</div>
|
| 111 |
+
|
| 112 |
+
### ZeRO data parallelism, pipeline parallelism, and model parallelism (3D parallelism)
|
| 113 |
+
|
| 114 |
+
Data, pipeline and model parallelism combine to form [3D parallelism](https://www.microsoft.com/en-us/research/blog/deepspeed-extreme-scale-model-training-for-everyone/) to optimize memory and compute efficiency.
|
| 115 |
+
|
| 116 |
+
Memory efficiency is achieved by splitting the model across GPUs and also dividing it into stages to create a pipeline. This allows GPUs to work in parallel on micro-batches of data, reducing the memory usage of the model, optimizer, and activations.
|
| 117 |
+
|
| 118 |
+
Compute efficiency is enabled by ZeRO data parallelism where each GPU only stores a slice of the model, optimizer, and activations. This allows higher communication bandwidth between data parallel nodes because communication can occur independently or in parallel with the other pipeline stages.
|
| 119 |
+
|
| 120 |
+
This approach is scalable to extremely large models with trillions of parameters.
|
| 121 |
+
|
| 122 |
+
<div class="flex justify-center">
|
| 123 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-deepspeed-3d.png"/>
|
| 124 |
+
</div>
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_gpu_one.md
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 11 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 12 |
+
rendered properly in your Markdown viewer.
|
| 13 |
+
|
| 14 |
+
-->
|
| 15 |
+
|
| 16 |
+
# GPU
|
| 17 |
+
|
| 18 |
+
GPUs are commonly used to train deep learning models due to their high memory bandwidth and parallel processing capabilities. Depending on your GPU and model size, it is possible to even train models with billions of parameters. The key is to find the right balance between GPU memory utilization (data throughput/training time) and training speed.
|
| 19 |
+
|
| 20 |
+
This guide will show you the features available in Transformers and PyTorch for efficiently training a model on GPUs. In many cases, you'll want to use a combination of these features to optimize training.
|
| 21 |
+
|
| 22 |
+
Refer to the table below to quickly help you identify the features relevant to your training scenario.
|
| 23 |
+
|
| 24 |
+
| Feature | Training speed | Memory usage |
|
| 25 |
+
|---|---|---|
|
| 26 |
+
| batch size | yes | yes |
|
| 27 |
+
| gradient accumulation | no | yes |
|
| 28 |
+
| gradient checkpointing | no | yes |
|
| 29 |
+
| mixed precision | yes | depends |
|
| 30 |
+
| optimizers | yes | yes |
|
| 31 |
+
| data preloading | yes | no |
|
| 32 |
+
| torch_empty_cache_steps | no | yes |
|
| 33 |
+
| torch.compile | yes | no |
|
| 34 |
+
| scaled dot production attention (SDPA) | yes | yes |
|
| 35 |
+
|
| 36 |
+
## Trainer
|
| 37 |
+
|
| 38 |
+
[Trainer](./trainer) supports many useful training features that can be configured through [`TrainingArguments`]. This section highlights some of the more important features for optimizing training.
|
| 39 |
+
|
| 40 |
+
### Batch size
|
| 41 |
+
|
| 42 |
+
Batch size is one of the most important hyperparameters for efficient GPU training because it affects memory usage and training speed. Larger batch sizes lead to faster training because it takes advantage of a GPUs parallel processing power. It is recommended to use batch sizes that are powers of 2, such as 8, 64, 128, 256, 512, etc. The batch size depends on your GPU and the models data type.
|
| 43 |
+
|
| 44 |
+
Configure [`~TrainingArguments.per_device_train_batch_size`] in [`TrainingArguments`].
|
| 45 |
+
|
| 46 |
+
```py
|
| 47 |
+
from transformers import TrainingArguments
|
| 48 |
+
|
| 49 |
+
args = TrainingArguments(
|
| 50 |
+
per_device_train_batch_size=256,
|
| 51 |
+
per_device_eval_batch_size=256,
|
| 52 |
+
)
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
Refer to the NVIDIA [Performance](https://docs.nvidia.com/deeplearning/performance/dl-performance-fully-connected/index.html#input-features) guide to learn more about how input features and output neuron counts and batch size affect performance. These are involved in the General Matrix Multiplications (GEMMs) performed by the GPU. Larger parameters are better for parallelization and efficiency.
|
| 56 |
+
|
| 57 |
+
The [Tensor Core Requirements](https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#requirements-tc) section is also useful for selecting a batch size that maximizes the speed of tensor multiplication based on the data type and GPU. For example, multiples of 8 are recommended for fp16, unless it's an A100 GPU, in which case use multiples of 64.
|
| 58 |
+
|
| 59 |
+
Finally, consider [Dimension Quantization Effects](https://docs.nvidia.com/deeplearning/performance/dl-performance-matrix-multiplication/index.html#dim-quantization) for smaller parameters. Tile quantization results when matrix dimensions aren't divisible by a GPUs thread block tile size, causing the GPU to underutilize its resources. Selecting the correct batch size multiplier, such that the matrix is divisible by the tile size, can significantly speed up training.
|
| 60 |
+
|
| 61 |
+
### Gradient accumulation
|
| 62 |
+
|
| 63 |
+
Gradient accumulation overcomes memory constraints - useful for fitting a very large model that otherwise wouldn't fit on a single GPU - by accumulating gradients over multiple mini-batches before updating the parameters. This reduces memory by storing fewer gradients and enables training with a larger *effective batch size* because usually, the parameters are updated from a single batch of data. Training can slow down though due to the additional forward and backward passes introduced by gradient accumulation.
|
| 64 |
+
|
| 65 |
+
Configure [`~TrainingArguments.per_device_train_batch_size`] in [`TrainingArguments`] to enable gradient accumulation.
|
| 66 |
+
|
| 67 |
+
```py
|
| 68 |
+
from transformers import TrainingArguments
|
| 69 |
+
|
| 70 |
+
# effective batch size of 64
|
| 71 |
+
args = TrainingArguments(
|
| 72 |
+
per_device_train_batch_size=4,
|
| 73 |
+
gradient_accumulation_steps=16,
|
| 74 |
+
)
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
Try to avoid too many gradient accumulation steps because it can really slow down training. Consider the example below, where the maximum batch size that'll fit on your GPU is 4. You should keep your batch size at 4 to better utilize the GPU.
|
| 78 |
+
|
| 79 |
+
| batch size | gradient accumulation steps | effective batch size | |
|
| 80 |
+
|---|---|---|---|
|
| 81 |
+
| 1 | 64 | 64 | 👎 |
|
| 82 |
+
| 4 | 16 | 64 | 👍 |
|
| 83 |
+
|
| 84 |
+
### Gradient checkpointing
|
| 85 |
+
|
| 86 |
+
Gradient checkpointing reduces memory usage by only storing some of the intermediate activations during the backward pass and recomputing the remaining activations. This avoids storing *all* of the intermediate activations from the forward pass, which can require a lot of memory overhead. However, it comes at the cost of slower training speed (~20%).
|
| 87 |
+
|
| 88 |
+
Configure [`~TrainingArguments.gradient_checkpointing`] in [`TrainingArguments`] to enable gradient checkpointing.
|
| 89 |
+
|
| 90 |
+
```py
|
| 91 |
+
from transformers import TrainingArguments
|
| 92 |
+
|
| 93 |
+
args = TrainingArguments(
|
| 94 |
+
per_device_train_batch_size=4,
|
| 95 |
+
gradient_accumulation_steps=16,
|
| 96 |
+
gradient_checkpointing=True,
|
| 97 |
+
)
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
### Mixed precision
|
| 101 |
+
|
| 102 |
+
Mixed precision accelerates training speed by performing some calculations in half-precision (fp16) and some in full-precision (fp32). The half-precision calculations boosts training speed because it's not as computationally expensive as performing the calculations in full-precision. Meanwhile, preserving some of the calculations in full-precision maintains accuracy.
|
| 103 |
+
|
| 104 |
+
There are several data types available for mixed precision training.
|
| 105 |
+
|
| 106 |
+
<hfoptions id="mixed-precision">
|
| 107 |
+
<hfoption id="fp16">
|
| 108 |
+
|
| 109 |
+
The main advantage of mixed precision training is saving the activations in fp16.
|
| 110 |
+
|
| 111 |
+
Configure [`~TrainingArguments.fp16`] in [`TrainingArguments`] to enable mixed precision training with the fp16 data type.
|
| 112 |
+
|
| 113 |
+
```py
|
| 114 |
+
from transformers import TrainingArguments
|
| 115 |
+
|
| 116 |
+
args = TrainingArguments(
|
| 117 |
+
per_device_train_batch_size=4,
|
| 118 |
+
gradient_accumulation_steps=16,
|
| 119 |
+
gradient_checkpointing=True,
|
| 120 |
+
fp16=True.
|
| 121 |
+
)
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
fp16 isn't memory-optimized because the gradients that are computed in fp16 are converted back to fp32 during the optimization step. You may end up using more GPU memory, especially for small batch sizes, because there are now two versions (fp16 and fp32) of the model on the GPU.
|
| 125 |
+
|
| 126 |
+
</hfoption>
|
| 127 |
+
<hfoption id="bf16">
|
| 128 |
+
|
| 129 |
+
[bf16](https://cloud.google.com/blog/products/ai-machine-learning/bfloat16-the-secret-to-high-performance-on-cloud-tpus) trades off some precision for a much larger dynamic range, which is helpful for avoiding overflow and underflow errors. You can use bf16 without adding any loss scaling methods like you would with fp16. bf16 is supported by NVIDIAs Ampere architecture or newer.
|
| 130 |
+
|
| 131 |
+
Configure [`~TrainingArguments.bf16`] in [`TrainingArguments`] to enable mixed precision training with the bf16 data type.
|
| 132 |
+
|
| 133 |
+
```py
|
| 134 |
+
from transformers import TrainingArguments
|
| 135 |
+
|
| 136 |
+
args = TrainingArguments(
|
| 137 |
+
per_device_train_batch_size=4,
|
| 138 |
+
gradient_accumulation_steps=16,
|
| 139 |
+
gradient_checkpointing=True,
|
| 140 |
+
bf16=True,
|
| 141 |
+
)
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
</hfoption>
|
| 145 |
+
<hfoption id="tf32">
|
| 146 |
+
|
| 147 |
+
[tf32](https://blogs.nvidia.com/blog/tensorfloat-32-precision-format/) is a mode on NVIDIA Ampere GPUs that convert the convolution and matrix multiplication inputs to tf32. All other storage and operations are kept in fp32. This allows tf32 to maintain the same range as fp32, the same precision as fp16 and more precision than bf16. Combining tf32 with fp16 or bf16 mixed precision training can improve throughput by 16x.
|
| 148 |
+
|
| 149 |
+
tf32 is enabled by default on NVIDIA Ampere GPUs, but you can also add the code below to your fp32 training or inference code to explicitly enable it.
|
| 150 |
+
|
| 151 |
+
```py
|
| 152 |
+
import torch
|
| 153 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 154 |
+
torch.backends.cudnn.allow_tf32 = True
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
Configure [tf32()](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.tf32) in [`TrainingArguments`] to enable mixed precision training with tf32 mode.
|
| 158 |
+
|
| 159 |
+
```py
|
| 160 |
+
from transformers import TrainingArguments
|
| 161 |
+
|
| 162 |
+
args = TrainingArguments(
|
| 163 |
+
per_device_train_batch_size=4,
|
| 164 |
+
gradient_accumulation_steps=16,
|
| 165 |
+
gradient_checkpointing=True,
|
| 166 |
+
bf16=True.
|
| 167 |
+
tf32=True,
|
| 168 |
+
)
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
</hfoption>
|
| 172 |
+
</hfoptions>
|
| 173 |
+
|
| 174 |
+
### Optimizers
|
| 175 |
+
|
| 176 |
+
Transformers implements the [AdamW (adamw_torch)](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) optimizer from PyTorch by default. But because it stores a weighted average of past gradients, it requires additional memory proportional to the number of model parameters to store the past gradients. This can be an issue when training very large models, and in such cases, you should consider choosing a different optimizer. For example, if you have [Apex](https://nvidia.github.io/apex/index.html) installed on either [NVIDIA](https://github.com/NVIDIA/apex) or [AMD](https://github.com/ROCm/apex), then using the `adamw_apex_fused` optimizer provides the fastest training for all AdamW optimizers.
|
| 177 |
+
|
| 178 |
+
Configure [`~TrainingArguments.optim`] in [`TrainingArguments`] to choose an optimizer.
|
| 179 |
+
|
| 180 |
+
```py
|
| 181 |
+
from transformers import TrainingArguments
|
| 182 |
+
|
| 183 |
+
args = TrainingArguments(
|
| 184 |
+
per_device_train_batch_size=4,
|
| 185 |
+
gradient_accumulation_steps=16,
|
| 186 |
+
gradient_checkpointing=True,
|
| 187 |
+
bf16=True,
|
| 188 |
+
optim="adamw_bnb_8bit"
|
| 189 |
+
)
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
There are many optimizers to choose from (refer to [OptimizerNames](https://github.com/huggingface/transformers/blob/34f4080ff59b1668d919a1ba9f8bc4a3a2a3f478/src/transformers/training_args.py#L145) for a full supported list) depending on your training scenario. For example, Adafactor can significantly reduce memory requirements by storing a weighted average of a row or column instead of each element in the matrix at the cost of slower convergence. Another example is using a [8-bit AdamW optimizer](https://huggingface.co/docs/bitsandbytes) from bitsandbytes to quantize optimizer states. The optimizer state is stored in a lower precision and dequantized before being used in the optimizer step.
|
| 193 |
+
|
| 194 |
+
Refer to the [optimizer](./optimizers) guide for to learn about more specialized optimizers.
|
| 195 |
+
|
| 196 |
+
### Data preloading
|
| 197 |
+
|
| 198 |
+
Data preloading loads and prepares batches of data in advance on the CPU to ensure the GPU is continuously working, reducing GPU idling and increasing utilization. There are two ways to preload data to ensure the GPU is always working.
|
| 199 |
+
|
| 200 |
+
1. Allocate pinned memory on the CPU to store the data and transfer it directly to the GPU.
|
| 201 |
+
2. Increase the number of CPU threads or workers to preload the data faster.
|
| 202 |
+
|
| 203 |
+
Configure [`~TrainingArguments.dataloader_pin_memory`] and [`~TrainingArguments.dataloader_num_workers`] in [`TrainingArguments`] to allocate pinned memory and increase the number of workers.
|
| 204 |
+
|
| 205 |
+
```py
|
| 206 |
+
from transformers import TrainingArguments
|
| 207 |
+
|
| 208 |
+
args = TrainingArguments(
|
| 209 |
+
per_device_train_batch_size=4,
|
| 210 |
+
gradient_accumulation_steps=16,
|
| 211 |
+
gradient_checkpointing=True,
|
| 212 |
+
bf16=True,
|
| 213 |
+
optim="adamw_bnb_8bit",
|
| 214 |
+
dataloader_pin_memory=True,
|
| 215 |
+
dataloader_num_workers=4,
|
| 216 |
+
)
|
| 217 |
+
```
|
| 218 |
+
|
| 219 |
+
## PyTorch
|
| 220 |
+
|
| 221 |
+
PyTorch provides several features for reducing memory requirements and increasing training speed. These features can often be enabled in Transformers by only adding a few lines of code.
|
| 222 |
+
|
| 223 |
+
### torch.empty_cache_steps
|
| 224 |
+
|
| 225 |
+
The [torch.cuda.empty_cache](https://pytorch.org/docs/stable/generated/torch.cuda.empty_cache.html#torch.cuda.empty_cache) function releases unused cached memory, which can help avoid out-of-memory (OOM) errors at the cost of ~10% slower training.
|
| 226 |
+
|
| 227 |
+
Use [torch_empty_cache_steps()](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.torch_empty_cache_steps) in [`TrainingArguments`] to enable it after a certain number of training steps.
|
| 228 |
+
|
| 229 |
+
```py
|
| 230 |
+
from transformers import TrainingArguments
|
| 231 |
+
|
| 232 |
+
args = TrainingArguments(
|
| 233 |
+
per_device_train_batch_size=4,
|
| 234 |
+
gradient_accumulation_steps=16,
|
| 235 |
+
gradient_checkpointing=True,
|
| 236 |
+
bf16=True,
|
| 237 |
+
optim="adamw_bnb_8bit",
|
| 238 |
+
dataloader_pin_memory=True,
|
| 239 |
+
dataloader_num_workers=4,
|
| 240 |
+
torch_empty_cache_steps=4,
|
| 241 |
+
)
|
| 242 |
+
```
|
| 243 |
+
|
| 244 |
+
### torch.compile
|
| 245 |
+
|
| 246 |
+
[torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) compiles PyTorch code into optimized kernels that significantly speed up training. This feature relies on TorchDynamo to capture PyTorch graphs with the Frame Evaluation API. The graph can be further compiled into optimized kernels for different backends.
|
| 247 |
+
|
| 248 |
+
Configure [`~TrainingArguments.torch_compile`] in [`TrainingArguments`] to enable it, and configure [torch_compile_backend()](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.torch_compile_backend) to select a backend to use.
|
| 249 |
+
|
| 250 |
+
```py
|
| 251 |
+
from transformers import TrainingArguments
|
| 252 |
+
|
| 253 |
+
args = TrainingArguments(
|
| 254 |
+
per_device_train_batch_size=4,
|
| 255 |
+
gradient_accumulation_steps=16,
|
| 256 |
+
gradient_checkpointing=True,
|
| 257 |
+
bf16=True,
|
| 258 |
+
optim="adamw_bnb_8bit",
|
| 259 |
+
dataloader_pin_memory=True,
|
| 260 |
+
dataloader_num_workers=4,
|
| 261 |
+
torch_empty_cache_steps=4,
|
| 262 |
+
torch_compile=True,
|
| 263 |
+
torch_compile_backend="inductor"
|
| 264 |
+
)
|
| 265 |
+
```
|
| 266 |
+
|
| 267 |
+
Refer to the table below to help you choose the right backend for your training scenario.
|
| 268 |
+
|
| 269 |
+
| backend | description | goal |
|
| 270 |
+
|---|---|---|
|
| 271 |
+
| eager | uses PyTorch to run extracted GraphModule | debugging |
|
| 272 |
+
| aot_eager | uses PyTorch eager mode for AOTAutograd's extracted forward and backward graphs | debugging |
|
| 273 |
+
| inductor | uses TorchInductor with AOTAutograd and CUDA Graphs by leveraging Triton kernels | training and inference |
|
| 274 |
+
| nvfuser | uses nvFuser with TorchScript | training and inference |
|
| 275 |
+
| aot_nvfuser | uses nvFuser with AOTAutograd | training and inference |
|
| 276 |
+
| aot_cudagraphs | uses CUDA Graphs with AOTAutograd | training and inference |
|
| 277 |
+
| ofi | uses TorchScripts [optimize_for_inference](https://pytorch.org/docs/stable/generated/torch.jit.optimize_for_inference.html#torch-jit-optimize-for-inference) | inference |
|
| 278 |
+
| fx2trt | uses [Torch-TensorRT](https://pytorch.org/TensorRT/tutorials/getting_started_with_fx_path.html) | inference |
|
| 279 |
+
| onnxrt | uses [ONNX-RT](https://onnxruntime.ai/) for CPU and GPU inference | inference |
|
| 280 |
+
| ipex | uses [IPEX](https://github.com/intel/intel-extension-for-pytorch) for CPU inference | inference |
|
| 281 |
+
|
| 282 |
+
### Scaled dot production attention
|
| 283 |
+
|
| 284 |
+
[torch.nn.functional.scaled_dot_product_attention](https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) (SDPA) is a native PyTorch implementation of the scaled dot product attention mechanism. SDPA is more efficient and optimized than the original attention mechanism in transformer models. It supports three types of scaled dot product attention.
|
| 285 |
+
|
| 286 |
+
- [FlashAttention2](https://github.com/Dao-AILab/flash-attention) is automatically enabled for models with the fp16 or bf16 torch type. Make sure to cast your model to the appropriate type first.
|
| 287 |
+
- [xFormers](https://github.com/facebookresearch/xformers) or Memory-Efficient Attention supports models with the fp32 torch type.
|
| 288 |
+
- C++ implementation of scaled dot product attention.
|
| 289 |
+
|
| 290 |
+
SDPA is enabled by default for PyTorch 2.1.1+, but it can be explicitly enabled by setting `attn_implementation="sdpa"` in [`~PreTrainedModel.from_pretrained`].
|
| 291 |
+
|
| 292 |
+
```py
|
| 293 |
+
from transformers import AutoModelForCausalLM
|
| 294 |
+
|
| 295 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B", device_map="auto", attn_implementation="sdpa")
|
| 296 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perf_train_special.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 11 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 12 |
+
rendered properly in your Markdown viewer.
|
| 13 |
+
|
| 14 |
+
-->
|
| 15 |
+
|
| 16 |
+
# Apple Silicon
|
| 17 |
+
|
| 18 |
+
Apple Silicon (M series) features a unified memory architecture, making it possible to efficiently train large models locally and improves performance by reducing latency associated with data retrieval. You can take advantage of Apple Silicon for training with PyTorch due to its integration with [Metal Performance Shaders (MPS)](https://pytorch.org/docs/stable/notes/mps.html).
|
| 19 |
+
|
| 20 |
+
The `mps` backend requires macOS 12.3 or later.
|
| 21 |
+
|
| 22 |
+
> [!WARNING]
|
| 23 |
+
> Some PyTorch operations are not implemented in MPS yet. To avoid an error, set the environment variable `PYTORCH_ENABLE_MPS_FALLBACK=1` to fallback on the CPU kernels. Please open an issue in the [PyTorch](https://github.com/pytorch/pytorch/issues) repository if you encounter any other issues.
|
| 24 |
+
|
| 25 |
+
[`TrainingArguments`] and [`Trainer`] detects and sets the backend device to `mps` if an Apple Silicon device is available. No additional changes are required to enable training on your device.
|
| 26 |
+
|
| 27 |
+
The `mps` backend doesn't support [distributed training](https://pytorch.org/docs/stable/distributed.html#backends).
|
| 28 |
+
|
| 29 |
+
## Resources
|
| 30 |
+
|
| 31 |
+
Learn more about the MPS backend in the [Introducing Accelerated PyTorch Training on Mac](https://pytorch.org/blog/introducing-accelerated-pytorch-training-on-mac/) blog post.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/perplexity.md
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2020 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 |
+
|
| 17 |
+
# Perplexity of fixed-length models
|
| 18 |
+
|
| 19 |
+
[[open-in-colab]]
|
| 20 |
+
|
| 21 |
+
Perplexity (PPL) is one of the most common metrics for evaluating language models. Before diving in, we should note
|
| 22 |
+
that the metric applies specifically to classical language models (sometimes called autoregressive or causal language
|
| 23 |
+
models) and is not well defined for masked language models like BERT (see [summary of the models](model_summary)).
|
| 24 |
+
|
| 25 |
+
Perplexity is defined as the exponentiated average negative log-likelihood of a sequence. If we have a tokenized
|
| 26 |
+
sequence \\(X = (x_0, x_1, \dots, x_t)\\), then the perplexity of \\(X\\) is,
|
| 27 |
+
|
| 28 |
+
$$\text{PPL}(X) = \exp \left\{ {-\frac{1}{t}\sum_i^t \log p_\theta (x_i|x_{<i}) } \right\}$$
|
| 29 |
+
|
| 30 |
+
where \\(\log p_\theta (x_i|x_{<i})\\) is the log-likelihood of the ith token conditioned on the preceding tokens \\(x_{<i}\\) according to our model. Intuitively, it can be thought of as an evaluation of the model's ability to predict uniformly among the set of specified tokens in a corpus. Importantly, this means that the tokenization procedure has a direct impact on a model's perplexity which should always be taken into consideration when comparing different models.
|
| 31 |
+
|
| 32 |
+
This is also equivalent to the exponentiation of the cross-entropy between the data and model predictions. For more
|
| 33 |
+
intuition about perplexity and its relationship to Bits Per Character (BPC) and data compression, check out this
|
| 34 |
+
[fantastic blog post on The Gradient](https://thegradient.pub/understanding-evaluation-metrics-for-language-models/).
|
| 35 |
+
|
| 36 |
+
## Calculating PPL with fixed-length models
|
| 37 |
+
|
| 38 |
+
If we weren't limited by a model's context size, we would evaluate the model's perplexity by autoregressively
|
| 39 |
+
factorizing a sequence and conditioning on the entire preceding subsequence at each step, as shown below.
|
| 40 |
+
|
| 41 |
+
<img width="600" alt="Full decomposition of a sequence with unlimited context length" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_full.gif"/>
|
| 42 |
+
|
| 43 |
+
When working with approximate models, however, we typically have a constraint on the number of tokens the model can
|
| 44 |
+
process. The largest version of [GPT-2](model_doc/gpt2), for example, has a fixed length of 1024 tokens, so we
|
| 45 |
+
cannot calculate \\(p_\theta(x_t|x_{<t})\\) directly when \\(t\\) is greater than 1024.
|
| 46 |
+
|
| 47 |
+
Instead, the sequence is typically broken into subsequences equal to the model's maximum input size. If a model's max
|
| 48 |
+
input size is \\(k\\), we then approximate the likelihood of a token \\(x_t\\) by conditioning only on the
|
| 49 |
+
\\(k-1\\) tokens that precede it rather than the entire context. When evaluating the model's perplexity of a
|
| 50 |
+
sequence, a tempting but suboptimal approach is to break the sequence into disjoint chunks and add up the decomposed
|
| 51 |
+
log-likelihoods of each segment independently.
|
| 52 |
+
|
| 53 |
+
<img width="600" alt="Suboptimal PPL not taking advantage of full available context" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_chunked.gif"/>
|
| 54 |
+
|
| 55 |
+
This is quick to compute since the perplexity of each segment can be computed in one forward pass, but serves as a poor
|
| 56 |
+
approximation of the fully-factorized perplexity and will typically yield a higher (worse) PPL because the model will
|
| 57 |
+
have less context at most of the prediction steps.
|
| 58 |
+
|
| 59 |
+
Instead, the PPL of fixed-length models should be evaluated with a sliding-window strategy. This involves repeatedly
|
| 60 |
+
sliding the context window so that the model has more context when making each prediction.
|
| 61 |
+
|
| 62 |
+
<img width="600" alt="Sliding window PPL taking advantage of all available context" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_sliding.gif"/>
|
| 63 |
+
|
| 64 |
+
This is a closer approximation to the true decomposition of the sequence probability and will typically yield a more
|
| 65 |
+
favorable score. The downside is that it requires a separate forward pass for each token in the corpus. A good
|
| 66 |
+
practical compromise is to employ a strided sliding window, moving the context by larger strides rather than sliding by
|
| 67 |
+
1 token a time. This allows computation to proceed much faster while still giving the model a large context to make
|
| 68 |
+
predictions at each step.
|
| 69 |
+
|
| 70 |
+
## Example: Calculating perplexity with GPT-2 in 🤗 Transformers
|
| 71 |
+
|
| 72 |
+
Let's demonstrate this process with GPT-2.
|
| 73 |
+
|
| 74 |
+
```python
|
| 75 |
+
from transformers import GPT2LMHeadModel, GPT2TokenizerFast, infer_device
|
| 76 |
+
|
| 77 |
+
device = infer_device()
|
| 78 |
+
model_id = "openai-community/gpt2-large"
|
| 79 |
+
model = GPT2LMHeadModel.from_pretrained(model_id).to(device)
|
| 80 |
+
tokenizer = GPT2TokenizerFast.from_pretrained(model_id)
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
We'll load in the WikiText-2 dataset and evaluate the perplexity using a few different sliding-window strategies. Since
|
| 84 |
+
this dataset is small and we're just doing one forward pass over the set, we can just load and encode the entire
|
| 85 |
+
dataset in memory.
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
from datasets import load_dataset
|
| 89 |
+
|
| 90 |
+
test = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
|
| 91 |
+
encodings = tokenizer("\n\n".join(test["text"]), return_tensors="pt")
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
With 🤗 Transformers, we can simply pass the `input_ids` as the `labels` to our model, and the average negative
|
| 95 |
+
log-likelihood for each token is returned as the loss. With our sliding window approach, however, there is overlap in
|
| 96 |
+
the tokens we pass to the model at each iteration. We don't want the log-likelihood for the tokens we're just treating
|
| 97 |
+
as context to be included in our loss, so we can set these targets to `-100` so that they are ignored. The following
|
| 98 |
+
is an example of how we could do this with a stride of `512`. This means that the model will have at least 512 tokens
|
| 99 |
+
for context when calculating the conditional likelihood of any one token (provided there are 512 preceding tokens
|
| 100 |
+
available to condition on).
|
| 101 |
+
|
| 102 |
+
```python
|
| 103 |
+
import torch
|
| 104 |
+
from tqdm import tqdm
|
| 105 |
+
|
| 106 |
+
max_length = model.config.n_positions
|
| 107 |
+
stride = 512
|
| 108 |
+
seq_len = encodings.input_ids.size(1)
|
| 109 |
+
|
| 110 |
+
nll_sum = 0.0
|
| 111 |
+
n_tokens = 0
|
| 112 |
+
prev_end_loc = 0
|
| 113 |
+
for begin_loc in tqdm(range(0, seq_len, stride)):
|
| 114 |
+
end_loc = min(begin_loc + max_length, seq_len)
|
| 115 |
+
trg_len = end_loc - prev_end_loc # may be different from stride on last loop
|
| 116 |
+
input_ids = encodings.input_ids[:, begin_loc:end_loc].to(device)
|
| 117 |
+
target_ids = input_ids.clone()
|
| 118 |
+
target_ids[:, :-trg_len] = -100
|
| 119 |
+
|
| 120 |
+
with torch.no_grad():
|
| 121 |
+
outputs = model(input_ids, labels=target_ids)
|
| 122 |
+
|
| 123 |
+
# loss is calculated using CrossEntropyLoss which averages over valid labels
|
| 124 |
+
# N.B. the model only calculates loss over trg_len - 1 labels, because it internally shifts the labels
|
| 125 |
+
# to the left by 1.
|
| 126 |
+
neg_log_likelihood = outputs.loss
|
| 127 |
+
|
| 128 |
+
# Accumulate the total negative log-likelihood and the total number of tokens
|
| 129 |
+
num_valid_tokens = (target_ids != -100).sum().item() # number of valid tokens in target_ids
|
| 130 |
+
batch_size = target_ids.size(0)
|
| 131 |
+
num_loss_tokens = num_valid_tokens - batch_size # subtract batch_size due to internal label shift
|
| 132 |
+
nll_sum += neg_log_likelihood * num_loss_tokens
|
| 133 |
+
n_tokens += num_loss_tokens
|
| 134 |
+
|
| 135 |
+
prev_end_loc = end_loc
|
| 136 |
+
if end_loc == seq_len:
|
| 137 |
+
break
|
| 138 |
+
|
| 139 |
+
avg_nll = nll_sum / n_tokens # average negative log-likelihood per token
|
| 140 |
+
ppl = torch.exp(avg_nll)
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
Running this with the stride length equal to the max input length is equivalent to the suboptimal, non-sliding-window
|
| 144 |
+
strategy we discussed above. The smaller the stride, the more context the model will have in making each prediction,
|
| 145 |
+
and the better the reported perplexity will typically be.
|
| 146 |
+
|
| 147 |
+
When we run the above with `stride = 1024`, i.e. no overlap, the resulting PPL is `19.44`, which is about the same
|
| 148 |
+
as the `19.93` reported in the GPT-2 paper. By using `stride = 512` and thereby employing our striding window
|
| 149 |
+
strategy, this jumps down to `16.44`. This is not only a more favorable score, but is calculated in a way that is
|
| 150 |
+
closer to the true autoregressive decomposition of a sequence likelihood.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/philosophy.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2020 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 |
+
|
| 17 |
+
# Philosophy
|
| 18 |
+
|
| 19 |
+
🤗 Transformers is an opinionated library built for:
|
| 20 |
+
|
| 21 |
+
- machine learning researchers and educators seeking to use, study or extend large-scale Transformers models.
|
| 22 |
+
- hands-on practitioners who want to fine-tune those models or serve them in production, or both.
|
| 23 |
+
- engineers who just want to download a pretrained model and use it to solve a given machine learning task.
|
| 24 |
+
|
| 25 |
+
The library was designed with two strong goals in mind:
|
| 26 |
+
|
| 27 |
+
1. Be as easy and fast to use as possible:
|
| 28 |
+
|
| 29 |
+
- We strongly limited the number of user-facing abstractions to learn, in fact, there are almost no abstractions,
|
| 30 |
+
just three standard classes required to use each model: [configuration](main_classes/configuration),
|
| 31 |
+
[models](main_classes/model), and a preprocessing class ([tokenizer](main_classes/tokenizer) for NLP, [image processor](main_classes/image_processor) for vision, [feature extractor](main_classes/feature_extractor) for audio, and [processor](main_classes/processors) for multimodal inputs).
|
| 32 |
+
- All of these classes can be initialized in a simple and unified way from pretrained instances by using a common
|
| 33 |
+
`from_pretrained()` method which downloads (if needed), caches and
|
| 34 |
+
loads the related class instance and associated data (configurations' hyperparameters, tokenizers' vocabulary,
|
| 35 |
+
and models' weights) from a pretrained checkpoint provided on [Hugging Face Hub](https://huggingface.co/models) or your own saved checkpoint.
|
| 36 |
+
- On top of those three base classes, the library provides two APIs: [`pipeline`] for quickly
|
| 37 |
+
using a model for inference on a given task and [`Trainer`] to quickly train or fine-tune a PyTorch model (all TensorFlow models are compatible with `Keras.fit`).
|
| 38 |
+
- As a consequence, this library is NOT a modular toolbox of building blocks for neural nets. If you want to
|
| 39 |
+
extend or build upon the library, just use regular Python, PyTorch, TensorFlow, Keras modules and inherit from the base
|
| 40 |
+
classes of the library to reuse functionalities like model loading and saving. If you'd like to learn more about our coding philosophy for models, check out our [Repeat Yourself](https://huggingface.co/blog/transformers-design-philosophy) blog post.
|
| 41 |
+
|
| 42 |
+
2. Provide state-of-the-art models with performances as close as possible to the original models:
|
| 43 |
+
|
| 44 |
+
- We provide at least one example for each architecture which reproduces a result provided by the official authors
|
| 45 |
+
of said architecture.
|
| 46 |
+
- The code is usually as close to the original code base as possible which means some PyTorch code may be not as
|
| 47 |
+
*pytorchic* as it could be as a result of being converted TensorFlow code and vice versa.
|
| 48 |
+
|
| 49 |
+
A few other goals:
|
| 50 |
+
|
| 51 |
+
- Expose the models' internals as consistently as possible:
|
| 52 |
+
|
| 53 |
+
- We give access, using a single API, to the full hidden-states and attention weights.
|
| 54 |
+
- The preprocessing classes and base model APIs are standardized to easily switch between models.
|
| 55 |
+
|
| 56 |
+
- Incorporate a subjective selection of promising tools for fine-tuning and investigating these models:
|
| 57 |
+
|
| 58 |
+
- A simple and consistent way to add new tokens to the vocabulary and embeddings for fine-tuning.
|
| 59 |
+
- Simple ways to mask and prune Transformer heads.
|
| 60 |
+
|
| 61 |
+
- Easily switch between PyTorch, TensorFlow 2.0 and Flax, allowing training with one framework and inference with another.
|
| 62 |
+
|
| 63 |
+
## Main concepts
|
| 64 |
+
|
| 65 |
+
The library is built around three types of classes for each model:
|
| 66 |
+
|
| 67 |
+
- **Model classes** can be PyTorch models ([torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)), Keras models ([tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)) or JAX/Flax models ([flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html)) that work with the pretrained weights provided in the library.
|
| 68 |
+
- **Configuration classes** store the hyperparameters required to build a model (such as the number of layers and hidden size). You don't always need to instantiate these yourself. In particular, if you are using a pretrained model without any modification, creating the model will automatically take care of instantiating the configuration (which is part of the model).
|
| 69 |
+
- **Preprocessing classes** convert the raw data into a format accepted by the model. A [tokenizer](main_classes/tokenizer) stores the vocabulary for each model and provide methods for encoding and decoding strings in a list of token embedding indices to be fed to a model. [Image processors](main_classes/image_processor) preprocess vision inputs, [feature extractors](main_classes/feature_extractor) preprocess audio inputs, and a [processor](main_classes/processors) handles multimodal inputs.
|
| 70 |
+
|
| 71 |
+
All these classes can be instantiated from pretrained instances, saved locally, and shared on the Hub with three methods:
|
| 72 |
+
|
| 73 |
+
- `from_pretrained()` lets you instantiate a model, configuration, and preprocessing class from a pretrained version either
|
| 74 |
+
provided by the library itself (the supported models can be found on the [Model Hub](https://huggingface.co/models)) or
|
| 75 |
+
stored locally (or on a server) by the user.
|
| 76 |
+
- `save_pretrained()` lets you save a model, configuration, and preprocessing class locally so that it can be reloaded using
|
| 77 |
+
`from_pretrained()`.
|
| 78 |
+
- `push_to_hub()` lets you share a model, configuration, and a preprocessing class to the Hub, so it is easily accessible to everyone.
|
| 79 |
+
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/pipeline_gradio.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Machine learning apps
|
| 18 |
+
|
| 19 |
+
[Gradio](https://www.gradio.app/), a fast and easy library for building and sharing machine learning apps, is integrated with [`Pipeline`] to quickly create a simple interface for inference.
|
| 20 |
+
|
| 21 |
+
Before you begin, make sure Gradio is installed.
|
| 22 |
+
|
| 23 |
+
```py
|
| 24 |
+
!pip install gradio
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
Create a pipeline for your task, and then pass it to Gradio's [Interface.from_pipeline](https://www.gradio.app/docs/gradio/interface#interface-from_pipeline) function to create the interface. Gradio automatically determines the appropriate input and output components for a [`Pipeline`].
|
| 28 |
+
|
| 29 |
+
Add [launch](https://www.gradio.app/main/docs/gradio/blocks#blocks-launch) to create a web server and start up the app.
|
| 30 |
+
|
| 31 |
+
```py
|
| 32 |
+
from transformers import pipeline
|
| 33 |
+
import gradio as gr
|
| 34 |
+
|
| 35 |
+
pipeline = pipeline("image-classification", model="google/vit-base-patch16-224")
|
| 36 |
+
gr.Interface.from_pipeline(pipeline).launch()
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
The web app runs on a local server by default. To share the app with other users, set `share=True` in [launch](https://www.gradio.app/main/docs/gradio/blocks#blocks-launch) to generate a temporary public link. For a more permanent solution, host the app on Hugging Face [Spaces](https://hf.co/spaces).
|
| 40 |
+
|
| 41 |
+
```py
|
| 42 |
+
gr.Interface.from_pipeline(pipeline).launch(share=True)
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
The Space below is created with the code above and hosted on Spaces.
|
| 46 |
+
|
| 47 |
+
<iframe
|
| 48 |
+
src="https://stevhliu-gradio-pipeline-demo.hf.space"
|
| 49 |
+
frameborder="0"
|
| 50 |
+
width="850"
|
| 51 |
+
height="850"
|
| 52 |
+
></iframe>
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/pipeline_tutorial.md
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Pipeline
|
| 18 |
+
|
| 19 |
+
The [`Pipeline`] is a simple but powerful inference API that is readily available for a variety of machine learning tasks with any model from the Hugging Face [Hub](https://hf.co/models).
|
| 20 |
+
|
| 21 |
+
Tailor the [`Pipeline`] to your task with task specific parameters such as adding timestamps to an automatic speech recognition (ASR) pipeline for transcribing meeting notes. [`Pipeline`] supports GPUs, Apple Silicon, and half-precision weights to accelerate inference and save memory.
|
| 22 |
+
|
| 23 |
+
<Youtube id=tiZFewofSLM/>
|
| 24 |
+
|
| 25 |
+
Transformers has two pipeline classes, a generic [`Pipeline`] and many individual task-specific pipelines like [`TextGenerationPipeline`] or [`VisualQuestionAnsweringPipeline`]. Load these individual pipelines by setting the task identifier in the `task` parameter in [`Pipeline`]. You can find the task identifier for each pipeline in their API documentation.
|
| 26 |
+
|
| 27 |
+
Each task is configured to use a default pretrained model and preprocessor, but this can be overridden with the `model` parameter if you want to use a different model.
|
| 28 |
+
|
| 29 |
+
For example, to use the [`TextGenerationPipeline`] with [Gemma 2](./model_doc/gemma2), set `task="text-generation"` and `model="google/gemma-2-2b"`.
|
| 30 |
+
|
| 31 |
+
```py
|
| 32 |
+
from transformers import pipeline
|
| 33 |
+
|
| 34 |
+
pipeline = pipeline(task="text-generation", model="google/gemma-2-2b")
|
| 35 |
+
pipeline("the secret to baking a really good cake is ")
|
| 36 |
+
[{'generated_text': 'the secret to baking a really good cake is 1. the right ingredients 2. the'}]
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
When you have more than one input, pass them as a list.
|
| 40 |
+
|
| 41 |
+
```py
|
| 42 |
+
from transformers import pipeline
|
| 43 |
+
|
| 44 |
+
pipeline = pipeline(task="text-generation", model="google/gemma-2-2b", device="cuda")
|
| 45 |
+
pipeline(["the secret to baking a really good cake is ", "a baguette is "])
|
| 46 |
+
[[{'generated_text': 'the secret to baking a really good cake is 1. the right ingredients 2. the'}],
|
| 47 |
+
[{'generated_text': 'a baguette is 100% bread.\n\na baguette is 100%'}]]
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
This guide will introduce you to the [`Pipeline`], demonstrate its features, and show how to configure its various parameters.
|
| 51 |
+
|
| 52 |
+
## Tasks
|
| 53 |
+
|
| 54 |
+
[`Pipeline`] is compatible with many machine learning tasks across different modalities. Pass an appropriate input to the pipeline and it will handle the rest.
|
| 55 |
+
|
| 56 |
+
Here are some examples of how to use [`Pipeline`] for different tasks and modalities.
|
| 57 |
+
|
| 58 |
+
<hfoptions id="tasks">
|
| 59 |
+
<hfoption id="summarization">
|
| 60 |
+
|
| 61 |
+
```py
|
| 62 |
+
from transformers import pipeline
|
| 63 |
+
|
| 64 |
+
pipeline = pipeline(task="summarization", model="google/pegasus-billsum")
|
| 65 |
+
pipeline("Section was formerly set out as section 44 of this title. As originally enacted, this section contained two further provisions that 'nothing in this act shall be construed as in any wise affecting the grant of lands made to the State of California by virtue of the act entitled 'An act authorizing a grant to the State of California of the Yosemite Valley, and of the land' embracing the Mariposa Big-Tree Grove, approved June thirtieth, eighteen hundred and sixty-four; or as affecting any bona-fide entry of land made within the limits above described under any law of the United States prior to the approval of this act.' The first quoted provision was omitted from the Code because the land, granted to the state of California pursuant to the Act cite, was receded to the United States. Resolution June 11, 1906, No. 27, accepted the recession.")
|
| 66 |
+
[{'summary_text': 'Instructs the Secretary of the Interior to convey to the State of California all right, title, and interest of the United States in and to specified lands which are located within the Yosemite and Mariposa National Forests, California.'}]
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
</hfoption>
|
| 70 |
+
<hfoption id="automatic speech recognition">
|
| 71 |
+
|
| 72 |
+
```py
|
| 73 |
+
from transformers import pipeline
|
| 74 |
+
|
| 75 |
+
pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
|
| 76 |
+
pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
|
| 77 |
+
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
</hfoption>
|
| 81 |
+
<hfoption id="image classification">
|
| 82 |
+
|
| 83 |
+
```py
|
| 84 |
+
from transformers import pipeline
|
| 85 |
+
|
| 86 |
+
pipeline = pipeline(task="image-classification", model="google/vit-base-patch16-224")
|
| 87 |
+
pipeline(images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")
|
| 88 |
+
[{'label': 'lynx, catamount', 'score': 0.43350091576576233},
|
| 89 |
+
{'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor',
|
| 90 |
+
'score': 0.034796204417943954},
|
| 91 |
+
{'label': 'snow leopard, ounce, Panthera uncia',
|
| 92 |
+
'score': 0.03240183740854263},
|
| 93 |
+
{'label': 'Egyptian cat', 'score': 0.02394474856555462},
|
| 94 |
+
{'label': 'tiger cat', 'score': 0.02288915030658245}]
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
</hfoption>
|
| 98 |
+
<hfoption id="visual question answering">
|
| 99 |
+
|
| 100 |
+
```py
|
| 101 |
+
from transformers import pipeline
|
| 102 |
+
|
| 103 |
+
pipeline = pipeline(task="visual-question-answering", model="Salesforce/blip-vqa-base")
|
| 104 |
+
pipeline(
|
| 105 |
+
image="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg",
|
| 106 |
+
question="What is in the image?",
|
| 107 |
+
)
|
| 108 |
+
[{'answer': 'statue of liberty'}]
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
</hfoption>
|
| 112 |
+
</hfoptions>
|
| 113 |
+
|
| 114 |
+
## Parameters
|
| 115 |
+
|
| 116 |
+
At a minimum, [`Pipeline`] only requires a task identifier, model, and the appropriate input. But there are many parameters available to configure the pipeline with, from task-specific parameters to optimizing performance.
|
| 117 |
+
|
| 118 |
+
This section introduces you to some of the more important parameters.
|
| 119 |
+
|
| 120 |
+
### Device
|
| 121 |
+
|
| 122 |
+
[`Pipeline`] is compatible with many hardware types, including GPUs, CPUs, Apple Silicon, and more. Configure the hardware type with the `device` parameter. By default, [`Pipeline`] runs on a CPU which is given by `device=-1`.
|
| 123 |
+
|
| 124 |
+
<hfoptions id="device">
|
| 125 |
+
<hfoption id="GPU">
|
| 126 |
+
|
| 127 |
+
To run [`Pipeline`] on a GPU, set `device` to the associated CUDA device id. For example, `device=0` runs on the first GPU.
|
| 128 |
+
|
| 129 |
+
```py
|
| 130 |
+
from transformers import pipeline
|
| 131 |
+
|
| 132 |
+
pipeline = pipeline(task="text-generation", model="google/gemma-2-2b", device=0)
|
| 133 |
+
pipeline("the secret to baking a really good cake is ")
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
You could also let [Accelerate](https://hf.co/docs/accelerate/index), a library for distributed training, automatically choose how to load and store the model weights on the appropriate device. This is especially useful if you have multiple devices. Accelerate loads and stores the model weights on the fastest device first, and then moves the weights to other devices (CPU, hard drive) as needed. Set `device_map="auto"` to let Accelerate choose the device.
|
| 137 |
+
|
| 138 |
+
> [!TIP]
|
| 139 |
+
> Make sure have [Accelerate](https://hf.co/docs/accelerate/basic_tutorials/install) is installed.
|
| 140 |
+
>
|
| 141 |
+
> ```py
|
| 142 |
+
> !pip install -U accelerate
|
| 143 |
+
> ```
|
| 144 |
+
|
| 145 |
+
```py
|
| 146 |
+
from transformers import pipeline
|
| 147 |
+
|
| 148 |
+
pipeline = pipeline(task="text-generation", model="google/gemma-2-2b", device_map="auto")
|
| 149 |
+
pipeline("the secret to baking a really good cake is ")
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
</hfoption>
|
| 153 |
+
<hfoption id="Apple silicon">
|
| 154 |
+
|
| 155 |
+
To run [`Pipeline`] on Apple silicon, set `device="mps"`.
|
| 156 |
+
|
| 157 |
+
```py
|
| 158 |
+
from transformers import pipeline
|
| 159 |
+
|
| 160 |
+
pipeline = pipeline(task="text-generation", model="google/gemma-2-2b", device="mps")
|
| 161 |
+
pipeline("the secret to baking a really good cake is ")
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
</hfoption>
|
| 165 |
+
</hfoptions>
|
| 166 |
+
|
| 167 |
+
### Batch inference
|
| 168 |
+
|
| 169 |
+
[`Pipeline`] can also process batches of inputs with the `batch_size` parameter. Batch inference may improve speed, especially on a GPU, but it isn't guaranteed. Other variables such as hardware, data, and the model itself can affect whether batch inference improves speed. For this reason, batch inference is disabled by default.
|
| 170 |
+
|
| 171 |
+
In the example below, when there are 4 inputs and `batch_size` is set to 2, [`Pipeline`] passes a batch of 2 inputs to the model at a time.
|
| 172 |
+
|
| 173 |
+
```py
|
| 174 |
+
from transformers import pipeline
|
| 175 |
+
|
| 176 |
+
pipeline = pipeline(task="text-generation", model="google/gemma-2-2b", device="cuda", batch_size=2)
|
| 177 |
+
pipeline(["the secret to baking a really good cake is", "a baguette is", "paris is the", "hotdogs are"])
|
| 178 |
+
[[{'generated_text': 'the secret to baking a really good cake is to use a good cake mix.\n\ni’'}],
|
| 179 |
+
[{'generated_text': 'a baguette is'}],
|
| 180 |
+
[{'generated_text': 'paris is the most beautiful city in the world.\n\ni’ve been to paris 3'}],
|
| 181 |
+
[{'generated_text': 'hotdogs are a staple of the american diet. they are a great source of protein and can'}]]
|
| 182 |
+
```
|
| 183 |
+
|
| 184 |
+
Another good use case for batch inference is for streaming data in [`Pipeline`].
|
| 185 |
+
|
| 186 |
+
```py
|
| 187 |
+
from transformers import pipeline
|
| 188 |
+
from transformers.pipelines.pt_utils import KeyDataset
|
| 189 |
+
import datasets
|
| 190 |
+
|
| 191 |
+
# KeyDataset is a utility that returns the item in the dict returned by the dataset
|
| 192 |
+
dataset = datasets.load_dataset("imdb", name="plain_text", split="unsupervised")
|
| 193 |
+
pipeline = pipeline(task="text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english", device="cuda")
|
| 194 |
+
for out in pipeline(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"):
|
| 195 |
+
print(out)
|
| 196 |
+
```
|
| 197 |
+
|
| 198 |
+
Keep the following general rules of thumb in mind for determining whether batch inference can help improve performance.
|
| 199 |
+
|
| 200 |
+
1. The only way to know for sure is to measure performance on your model, data, and hardware.
|
| 201 |
+
2. Don't batch inference if you're constrained by latency (a live inference product for example).
|
| 202 |
+
3. Don't batch inference if you're using a CPU.
|
| 203 |
+
4. Don't batch inference if you don't know the `sequence_length` of your data. Measure performance, iteratively add to `sequence_length`, and include out-of-memory (OOM) checks to recover from failures.
|
| 204 |
+
5. Do batch inference if your `sequence_length` is regular, and keep pushing it until you reach an OOM error. The larger the GPU, the more helpful batch inference is.
|
| 205 |
+
6. Do make sure you can handle OOM errors if you decide to do batch inference.
|
| 206 |
+
|
| 207 |
+
### Task-specific parameters
|
| 208 |
+
|
| 209 |
+
[`Pipeline`] accepts any parameters that are supported by each individual task pipeline. Make sure to check out each individual task pipeline to see what type of parameters are available. If you can't find a parameter that is useful for your use case, please feel free to open a GitHub [issue](https://github.com/huggingface/transformers/issues/new?assignees=&labels=feature&template=feature-request.yml) to request it!
|
| 210 |
+
|
| 211 |
+
The examples below demonstrate some of the task-specific parameters available.
|
| 212 |
+
|
| 213 |
+
<hfoptions id="task-specific-parameters">
|
| 214 |
+
<hfoption id="automatic speech recognition">
|
| 215 |
+
|
| 216 |
+
Pass the `return_timestamps="word"` parameter to [`Pipeline`] to return when each word was spoken.
|
| 217 |
+
|
| 218 |
+
```py
|
| 219 |
+
from transformers import pipeline
|
| 220 |
+
|
| 221 |
+
pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3")
|
| 222 |
+
pipeline(audio="https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac", return_timestamp="word")
|
| 223 |
+
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.',
|
| 224 |
+
'chunks': [{'text': ' I', 'timestamp': (0.0, 1.1)},
|
| 225 |
+
{'text': ' have', 'timestamp': (1.1, 1.44)},
|
| 226 |
+
{'text': ' a', 'timestamp': (1.44, 1.62)},
|
| 227 |
+
{'text': ' dream', 'timestamp': (1.62, 1.92)},
|
| 228 |
+
{'text': ' that', 'timestamp': (1.92, 3.7)},
|
| 229 |
+
{'text': ' one', 'timestamp': (3.7, 3.88)},
|
| 230 |
+
{'text': ' day', 'timestamp': (3.88, 4.24)},
|
| 231 |
+
{'text': ' this', 'timestamp': (4.24, 5.82)},
|
| 232 |
+
{'text': ' nation', 'timestamp': (5.82, 6.78)},
|
| 233 |
+
{'text': ' will', 'timestamp': (6.78, 7.36)},
|
| 234 |
+
{'text': ' rise', 'timestamp': (7.36, 7.88)},
|
| 235 |
+
{'text': ' up', 'timestamp': (7.88, 8.46)},
|
| 236 |
+
{'text': ' and', 'timestamp': (8.46, 9.2)},
|
| 237 |
+
{'text': ' live', 'timestamp': (9.2, 10.34)},
|
| 238 |
+
{'text': ' out', 'timestamp': (10.34, 10.58)},
|
| 239 |
+
{'text': ' the', 'timestamp': (10.58, 10.8)},
|
| 240 |
+
{'text': ' true', 'timestamp': (10.8, 11.04)},
|
| 241 |
+
{'text': ' meaning', 'timestamp': (11.04, 11.4)},
|
| 242 |
+
{'text': ' of', 'timestamp': (11.4, 11.64)},
|
| 243 |
+
{'text': ' its', 'timestamp': (11.64, 11.8)},
|
| 244 |
+
{'text': ' creed.', 'timestamp': (11.8, 12.3)}]}
|
| 245 |
+
```
|
| 246 |
+
|
| 247 |
+
</hfoption>
|
| 248 |
+
<hfoption id="text generation">
|
| 249 |
+
|
| 250 |
+
Pass `return_full_text=False` to [`Pipeline`] to only return the generated text instead of the full text (prompt and generated text).
|
| 251 |
+
|
| 252 |
+
[`~TextGenerationPipeline.__call__`] also supports additional keyword arguments from the [`~GenerationMixin.generate`] method. To return more than one generated sequence, set `num_return_sequences` to a value greater than 1.
|
| 253 |
+
|
| 254 |
+
```py
|
| 255 |
+
from transformers import pipeline
|
| 256 |
+
|
| 257 |
+
pipeline = pipeline(task="text-generation", model="openai-community/gpt2")
|
| 258 |
+
pipeline("the secret to baking a good cake is", num_return_sequences=4, return_full_text=False)
|
| 259 |
+
[{'generated_text': ' how easy it is for me to do it with my hands. You must not go nuts, or the cake is going to fall out.'},
|
| 260 |
+
{'generated_text': ' to prepare the cake before baking. The key is to find the right type of icing to use and that icing makes an amazing frosting cake.\n\nFor a good icing cake, we give you the basics'},
|
| 261 |
+
{'generated_text': " to remember to soak it in enough water and don't worry about it sticking to the wall. In the meantime, you could remove the top of the cake and let it dry out with a paper towel.\n"},
|
| 262 |
+
{'generated_text': ' the best time to turn off the oven and let it stand 30 minutes. After 30 minutes, stir and bake a cake in a pan until fully moist.\n\nRemove the cake from the heat for about 12'}]
|
| 263 |
+
```
|
| 264 |
+
|
| 265 |
+
</hfoption>
|
| 266 |
+
</hfoptions>
|
| 267 |
+
|
| 268 |
+
## Chunk batching
|
| 269 |
+
|
| 270 |
+
There are some instances where you need to process data in chunks.
|
| 271 |
+
|
| 272 |
+
- for some data types, a single input (for example, a really long audio file) may need to be chunked into multiple parts before it can be processed
|
| 273 |
+
- for some tasks, like zero-shot classification or question answering, a single input may need multiple forward passes which can cause issues with the `batch_size` parameter
|
| 274 |
+
|
| 275 |
+
The [ChunkPipeline](https://github.com/huggingface/transformers/blob/99e0ab6ed888136ea4877c6d8ab03690a1478363/src/transformers/pipelines/base.py#L1387) class is designed to handle these use cases. Both pipeline classes are used in the same way, but since [ChunkPipeline](https://github.com/huggingface/transformers/blob/99e0ab6ed888136ea4877c6d8ab03690a1478363/src/transformers/pipelines/base.py#L1387) can automatically handle batching, you don't need to worry about the number of forward passes your inputs trigger. Instead, you can optimize `batch_size` independently of the inputs.
|
| 276 |
+
|
| 277 |
+
The example below shows how it differs from [`Pipeline`].
|
| 278 |
+
|
| 279 |
+
```py
|
| 280 |
+
# ChunkPipeline
|
| 281 |
+
all_model_outputs = []
|
| 282 |
+
for preprocessed in pipeline.preprocess(inputs):
|
| 283 |
+
model_outputs = pipeline.model_forward(preprocessed)
|
| 284 |
+
all_model_outputs.append(model_outputs)
|
| 285 |
+
outputs =pipeline.postprocess(all_model_outputs)
|
| 286 |
+
|
| 287 |
+
# Pipeline
|
| 288 |
+
preprocessed = pipeline.preprocess(inputs)
|
| 289 |
+
model_outputs = pipeline.forward(preprocessed)
|
| 290 |
+
outputs = pipeline.postprocess(model_outputs)
|
| 291 |
+
```
|
| 292 |
+
|
| 293 |
+
## Large datasets
|
| 294 |
+
|
| 295 |
+
For inference with large datasets, you can iterate directly over the dataset itself. This avoids immediately allocating memory for the entire dataset, and you don't need to worry about creating batches yourself. Try [Batch inference](#batch-inference) with the `batch_size` parameter to see if it improves performance.
|
| 296 |
+
|
| 297 |
+
```py
|
| 298 |
+
from transformers.pipelines.pt_utils import KeyDataset
|
| 299 |
+
from transformers import pipeline
|
| 300 |
+
from datasets import load_dataset
|
| 301 |
+
|
| 302 |
+
dataset = datasets.load_dataset("imdb", name="plain_text", split="unsupervised")
|
| 303 |
+
pipeline = pipeline(task="text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english", device="cuda")
|
| 304 |
+
for out in pipeline(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"):
|
| 305 |
+
print(out)
|
| 306 |
+
```
|
| 307 |
+
|
| 308 |
+
Other ways to run inference on large datasets with [`Pipeline`] include using an iterator or generator.
|
| 309 |
+
|
| 310 |
+
```py
|
| 311 |
+
def data():
|
| 312 |
+
for i in range(1000):
|
| 313 |
+
yield f"My example {i}"
|
| 314 |
+
|
| 315 |
+
pipeline = pipeline(model="openai-community/gpt2", device=0)
|
| 316 |
+
generated_characters = 0
|
| 317 |
+
for out in pipeline(data()):
|
| 318 |
+
generated_characters += len(out[0]["generated_text"])
|
| 319 |
+
```
|
| 320 |
+
|
| 321 |
+
## Large models
|
| 322 |
+
|
| 323 |
+
[Accelerate](https://hf.co/docs/accelerate/index) enables a couple of optimizations for running large models with [`Pipeline`]. Make sure Accelerate is installed first.
|
| 324 |
+
|
| 325 |
+
```py
|
| 326 |
+
!pip install -U accelerate
|
| 327 |
+
```
|
| 328 |
+
|
| 329 |
+
The `device_map="auto"` setting is useful for automatically distributing the model across the fastest devices (GPUs) first before dispatching to other slower devices if available (CPU, hard drive).
|
| 330 |
+
|
| 331 |
+
[`Pipeline`] supports half-precision weights (torch.float16), which can be significantly faster and save memory. Performance loss is negligible for most models, especially for larger ones. If your hardware supports it, you can enable torch.bfloat16 instead for more range.
|
| 332 |
+
|
| 333 |
+
> [!TIP]
|
| 334 |
+
> Inputs are internally converted to torch.float16 and it only works for models with a PyTorch backend.
|
| 335 |
+
|
| 336 |
+
Lastly, [`Pipeline`] also accepts quantized models to reduce memory usage even further. Make sure you have the [bitsandbytes](https://hf.co/docs/bitsandbytes/installation) library installed first, and then add `load_in_8bit=True` to `model_kwargs` in the pipeline.
|
| 337 |
+
|
| 338 |
+
```py
|
| 339 |
+
import torch
|
| 340 |
+
from transformers import pipeline, BitsAndBytesConfig
|
| 341 |
+
|
| 342 |
+
pipeline = pipeline(model="google/gemma-7b", torch_dtype=torch.bfloat16, device_map="auto", model_kwargs={"quantization_config": BitsAndBytesConfig(load_in_8bit=True)})
|
| 343 |
+
pipeline("the secret to baking a good cake is ")
|
| 344 |
+
[{'generated_text': 'the secret to baking a good cake is 1. the right ingredients 2. the right'}]
|
| 345 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/pipeline_webserver.md
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Web server inference
|
| 18 |
+
|
| 19 |
+
A web server is a system that waits for requests and serves them as they come in. This means you can use [`Pipeline`] as an inference engine on a web server, since you can use an iterator (similar to how you would [iterate over a dataset](./pipeline_tutorial#large-datasets)) to handle each incoming request.
|
| 20 |
+
|
| 21 |
+
Designing a web server with [`Pipeline`] is unique though because they're fundamentally different. Web servers are multiplexed (multithreaded, async, etc.) to handle multiple requests concurrently. [`Pipeline`] and its underlying model on the other hand are not designed for parallelism because they take a lot of memory. It's best to give a [`Pipeline`] all the available resources when they're running or for a compute intensive job.
|
| 22 |
+
|
| 23 |
+
This guide shows how to work around this difference by using a web server to handle the lighter load of receiving and sending requests, and having a single thread to handle the heavier load of running [`Pipeline`].
|
| 24 |
+
|
| 25 |
+
## Create a server
|
| 26 |
+
|
| 27 |
+
[Starlette](https://www.starlette.io/) is a lightweight framework for building web servers. You can use any other framework you'd like, but you may have to make some changes to the code below.
|
| 28 |
+
|
| 29 |
+
Before you begin, make sure Starlette and [uvicorn](http://www.uvicorn.org/) are installed.
|
| 30 |
+
|
| 31 |
+
```py
|
| 32 |
+
!pip install starlette uvicorn
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Now you can create a simple web server in a `server.py` file. The key is to only load the model **once** to prevent unnecessary copies of it from consuming memory.
|
| 36 |
+
|
| 37 |
+
Create a pipeline to fill in the masked token, `[MASK]`.
|
| 38 |
+
|
| 39 |
+
```py
|
| 40 |
+
from starlette.applications import Starlette
|
| 41 |
+
from starlette.responses import JSONResponse
|
| 42 |
+
from starlette.routing import Route
|
| 43 |
+
from transformers import pipeline
|
| 44 |
+
import asyncio
|
| 45 |
+
|
| 46 |
+
async def homepage(request):
|
| 47 |
+
payload = await request.body()
|
| 48 |
+
string = payload.decode("utf-8")
|
| 49 |
+
response_q = asyncio.Queue()
|
| 50 |
+
await request.app.model_queue.put((string, response_q))
|
| 51 |
+
output = await response_q.get()
|
| 52 |
+
return JSONResponse(output)
|
| 53 |
+
|
| 54 |
+
async def server_loop(q):
|
| 55 |
+
pipe = pipeline(task="fill-mask",model="google-bert/bert-base-uncased")
|
| 56 |
+
while True:
|
| 57 |
+
(string, response_q) = await q.get()
|
| 58 |
+
out = pipe(string)
|
| 59 |
+
await response_q.put(out)
|
| 60 |
+
|
| 61 |
+
app = Starlette(
|
| 62 |
+
routes=[
|
| 63 |
+
Route("/", homepage, methods=["POST"]),
|
| 64 |
+
],
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
@app.on_event("startup")
|
| 68 |
+
async def startup_event():
|
| 69 |
+
q = asyncio.Queue()
|
| 70 |
+
app.model_queue = q
|
| 71 |
+
asyncio.create_task(server_loop(q))
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Start the server with the following command.
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
uvicorn server:app
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
Query the server with a POST request.
|
| 81 |
+
|
| 82 |
+
```bash
|
| 83 |
+
curl -X POST -d "Paris is the [MASK] of France." http://localhost:8000/
|
| 84 |
+
```
|
| 85 |
+
This should return the output below.
|
| 86 |
+
|
| 87 |
+
```bash
|
| 88 |
+
[{'score': 0.9969332218170166,
|
| 89 |
+
'token': 3007,
|
| 90 |
+
'token_str': 'capital',
|
| 91 |
+
'sequence': 'paris is the capital of france.'},
|
| 92 |
+
{'score': 0.0005914849461987615,
|
| 93 |
+
'token': 2540,
|
| 94 |
+
'token_str': 'heart',
|
| 95 |
+
'sequence': 'paris is the heart of france.'},
|
| 96 |
+
{'score': 0.00043787318281829357,
|
| 97 |
+
'token': 2415,
|
| 98 |
+
'token_str': 'center',
|
| 99 |
+
'sequence': 'paris is the center of france.'},
|
| 100 |
+
{'score': 0.0003378340043127537,
|
| 101 |
+
'token': 2803,
|
| 102 |
+
'token_str': 'centre',
|
| 103 |
+
'sequence': 'paris is the centre of france.'},
|
| 104 |
+
{'score': 0.00026995912776328623,
|
| 105 |
+
'token': 2103,
|
| 106 |
+
'token_str': 'city',
|
| 107 |
+
'sequence': 'paris is the city of france.'}]
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
## Queuing requests
|
| 111 |
+
|
| 112 |
+
The server's queuing mechanism can be used for some interesting applications such as dynamic batching. Dynamic batching accumulates several requests first before processing them with [`Pipeline`].
|
| 113 |
+
|
| 114 |
+
The example below is written in pseudocode for readability rather than performance, in particular, you'll notice that:
|
| 115 |
+
|
| 116 |
+
1. There is no batch size limit.
|
| 117 |
+
2. The timeout is reset on every queue fetch, so you could end up waiting much longer than the `timeout` value before processing a request. This would also delay the first inference request by that amount of time. The web server always waits 1ms even if the queue is empty, which is inefficient, because that time can be used to start inference. It could make sense though if batching is essential to your use case.
|
| 118 |
+
|
| 119 |
+
It would be better to have a single 1ms deadline, instead of resetting it on every fetch, as shown below.
|
| 120 |
+
|
| 121 |
+
```py
|
| 122 |
+
async def server_loop(q):
|
| 123 |
+
pipe = pipeline(task="fill-mask", model="google-bert/bert-base-uncased")
|
| 124 |
+
while True:
|
| 125 |
+
(string, rq) = await q.get()
|
| 126 |
+
strings = []
|
| 127 |
+
queues = []
|
| 128 |
+
strings.append(string)
|
| 129 |
+
queues.append(rq)
|
| 130 |
+
while True:
|
| 131 |
+
try:
|
| 132 |
+
(string, rq) = await asyncio.wait_for(q.get(), timeout=1)
|
| 133 |
+
except asyncio.exceptions.TimeoutError:
|
| 134 |
+
break
|
| 135 |
+
strings.append(string)
|
| 136 |
+
queues.append(rq)
|
| 137 |
+
outs = pipe(strings, batch_size=len(strings))
|
| 138 |
+
for rq, out in zip(queues, outs):
|
| 139 |
+
await rq.put(out)
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
## Error checking
|
| 143 |
+
|
| 144 |
+
There are many things that can go wrong in production. You could run out-of-memory, out of space, fail to load a model, have an incorrect model configuration, have an incorrect query, and so much more.
|
| 145 |
+
|
| 146 |
+
Adding `try...except` statements is helpful for returning these errors to the user for debugging. Keep in mind this could be a security risk if you shouldn't be revealing certain information.
|
| 147 |
+
|
| 148 |
+
## Circuit breaking
|
| 149 |
+
|
| 150 |
+
Try to return a 503 or 504 error when the server is overloaded instead of forcing a user to wait indefinitely.
|
| 151 |
+
|
| 152 |
+
It is relatively simple to implement these error types since it's only a single queue. Take a look at the queue size to determine when to start returning errors before your server fails under load.
|
| 153 |
+
|
| 154 |
+
## Block the main thread
|
| 155 |
+
|
| 156 |
+
PyTorch is not async aware, so computation will block the main thread from running.
|
| 157 |
+
|
| 158 |
+
For this reason, it's better to run PyTorch on its own separate thread or process. When inference of a single request is especially long (more than 1s), it's even more important because it means every query during inference must wait 1s before even receiving an error.
|
| 159 |
+
|
| 160 |
+
## Dynamic batching
|
| 161 |
+
|
| 162 |
+
Dynamic batching can be very effective when used in the correct setting, but it's not necessary when you're only passing 1 request at a time (see [batch inference](./pipeline_tutorial#batch-inference) for more details).
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/pr_checks.md
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!---
|
| 2 |
+
Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 3 |
+
|
| 4 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
you may not use this file except in compliance with the License.
|
| 6 |
+
You may obtain a copy of the License at
|
| 7 |
+
|
| 8 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
|
| 10 |
+
Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
See the License for the specific language governing permissions and
|
| 14 |
+
limitations under the License.
|
| 15 |
+
|
| 16 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 17 |
+
rendered properly in your Markdown viewer.
|
| 18 |
+
|
| 19 |
+
-->
|
| 20 |
+
|
| 21 |
+
# Checks on a Pull Request
|
| 22 |
+
|
| 23 |
+
When you open a pull request on 🤗 Transformers, a fair number of checks will be run to make sure the patch you are adding is not breaking anything existing. Those checks are of four types:
|
| 24 |
+
- regular tests
|
| 25 |
+
- documentation build
|
| 26 |
+
- code and documentation style
|
| 27 |
+
- general repository consistency
|
| 28 |
+
|
| 29 |
+
In this document, we will take a stab at explaining what those various checks are and the reason behind them, as well as how to debug them locally if one of them fails on your PR.
|
| 30 |
+
|
| 31 |
+
Note that, ideally, they require you to have a dev install:
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
pip install transformers[dev]
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
or for an editable install:
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
pip install -e .[dev]
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
inside the Transformers repo. Since the number of optional dependencies of Transformers has grown a lot, it's possible you don't manage to get all of them. If the dev install fails, make sure to install the Deep Learning framework you are working with (PyTorch, TensorFlow and/or Flax) then do
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
pip install transformers[quality]
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
or for an editable install:
|
| 50 |
+
|
| 51 |
+
```bash
|
| 52 |
+
pip install -e .[quality]
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
## Tests
|
| 57 |
+
|
| 58 |
+
All the jobs that begin with `ci/circleci: run_tests_` run parts of the Transformers testing suite. Each of those jobs focuses on a part of the library in a certain environment: for instance `ci/circleci: run_tests_pipelines_tf` runs the pipelines test in an environment where TensorFlow only is installed.
|
| 59 |
+
|
| 60 |
+
Note that to avoid running tests when there is no real change in the modules they are testing, only part of the test suite is run each time: a utility is run to determine the differences in the library between before and after the PR (what GitHub shows you in the "Files changes" tab) and picks the tests impacted by that diff. That utility can be run locally with:
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
python utils/tests_fetcher.py
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
from the root of the Transformers repo. It will:
|
| 67 |
+
|
| 68 |
+
1. Check for each file in the diff if the changes are in the code or only in comments or docstrings. Only the files with real code changes are kept.
|
| 69 |
+
2. Build an internal map that gives for each file of the source code of the library all the files it recursively impacts. Module A is said to impact module B if module B imports module A. For the recursive impact, we need a chain of modules going from module A to module B in which each module imports the previous one.
|
| 70 |
+
3. Apply this map on the files gathered in step 1, which gives us the list of model files impacted by the PR.
|
| 71 |
+
4. Map each of those files to their corresponding test file(s) and get the list of tests to run.
|
| 72 |
+
|
| 73 |
+
When executing the script locally, you should get the results of step 1, 3 and 4 printed and thus know which tests are run. The script will also create a file named `test_list.txt` which contains the list of tests to run, and you can run them locally with the following command:
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
python -m pytest -n 8 --dist=loadfile -rA -s $(cat test_list.txt)
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
Just in case anything slipped through the cracks, the full test suite is also run daily.
|
| 80 |
+
|
| 81 |
+
## Documentation build
|
| 82 |
+
|
| 83 |
+
The `build_pr_documentation` job builds and generates a preview of the documentation to make sure everything looks okay once your PR is merged. A bot will add a link to preview the documentation in your PR. Any changes you make to the PR are automatically updated in the preview. If the documentation fails to build, click on **Details** next to the failed job to see where things went wrong. Often, the error is as simple as a missing file in the `toctree`.
|
| 84 |
+
|
| 85 |
+
If you're interested in building or previewing the documentation locally, take a look at the [`README.md`](https://github.com/huggingface/transformers/tree/main/docs) in the docs folder.
|
| 86 |
+
|
| 87 |
+
## Code and documentation style
|
| 88 |
+
|
| 89 |
+
Code formatting is applied to all the source files, the examples and the tests using `black` and `ruff`. We also have a custom tool taking care of the formatting of docstrings and `rst` files (`utils/style_doc.py`), as well as the order of the lazy imports performed in the Transformers `__init__.py` files (`utils/custom_init_isort.py`). All of this can be launched by executing
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
make style
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
The CI checks those have been applied inside the `ci/circleci: check_code_quality` check. It also runs `ruff`, that will have a basic look at your code and will complain if it finds an undefined variable, or one that is not used. To run that check locally, use
|
| 96 |
+
|
| 97 |
+
```bash
|
| 98 |
+
make quality
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
This can take a lot of time, so to run the same thing on only the files you modified in the current branch, run
|
| 102 |
+
|
| 103 |
+
```bash
|
| 104 |
+
make fixup
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
This last command will also run all the additional checks for the repository consistency. Let's have a look at them.
|
| 108 |
+
|
| 109 |
+
## Repository consistency
|
| 110 |
+
|
| 111 |
+
This regroups all the tests to make sure your PR leaves the repository in a good state, and is performed by the `ci/circleci: check_repository_consistency` check. You can locally run that check by executing the following:
|
| 112 |
+
|
| 113 |
+
```bash
|
| 114 |
+
make repo-consistency
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
This checks that:
|
| 118 |
+
|
| 119 |
+
- All objects added to the init are documented (performed by `utils/check_repo.py`)
|
| 120 |
+
- All `__init__.py` files have the same content in their two sections (performed by `utils/check_inits.py`)
|
| 121 |
+
- All code identified as a copy from another module is consistent with the original (performed by `utils/check_copies.py`)
|
| 122 |
+
- All configuration classes have at least one valid checkpoint mentioned in their docstrings (performed by `utils/check_config_docstrings.py`)
|
| 123 |
+
- All configuration classes only contain attributes that are used in corresponding modeling files (performed by `utils/check_config_attributes.py`)
|
| 124 |
+
- The translations of the READMEs and the index of the doc have the same model list as the main README (performed by `utils/check_copies.py`)
|
| 125 |
+
- The auto-generated tables in the documentation are up to date (performed by `utils/check_table.py`)
|
| 126 |
+
- The library has all objects available even if not all optional dependencies are installed (performed by `utils/check_dummies.py`)
|
| 127 |
+
- All docstrings properly document the arguments in the signature of the object (performed by `utils/check_docstrings.py`)
|
| 128 |
+
|
| 129 |
+
Should this check fail, the first two items require manual fixing, the last four can be fixed automatically for you by running the command
|
| 130 |
+
|
| 131 |
+
```bash
|
| 132 |
+
make fix-copies
|
| 133 |
+
```
|
| 134 |
+
|
| 135 |
+
Additional checks concern PRs that add new models, mainly that:
|
| 136 |
+
|
| 137 |
+
- All models added are in an Auto-mapping (performed by `utils/check_repo.py`)
|
| 138 |
+
<!-- TODO Sylvain, add a check that makes sure the common tests are implemented.-->
|
| 139 |
+
- All models are properly tested (performed by `utils/check_repo.py`)
|
| 140 |
+
|
| 141 |
+
<!-- TODO Sylvain, add the following
|
| 142 |
+
- All models are added to the main README, inside the main doc
|
| 143 |
+
- All checkpoints used actually exist on the Hub
|
| 144 |
+
|
| 145 |
+
-->
|
| 146 |
+
|
| 147 |
+
### Check copies
|
| 148 |
+
|
| 149 |
+
Since the Transformers library is very opinionated with respect to model code, and each model should fully be implemented in a single file without relying on other models, we have added a mechanism that checks whether a copy of the code of a layer of a given model stays consistent with the original. This way, when there is a bug fix, we can see all other impacted models and choose to trickle down the modification or break the copy.
|
| 150 |
+
|
| 151 |
+
<Tip>
|
| 152 |
+
|
| 153 |
+
If a file is a full copy of another file, you should register it in the constant `FULL_COPIES` of `utils/check_copies.py`.
|
| 154 |
+
|
| 155 |
+
</Tip>
|
| 156 |
+
|
| 157 |
+
This mechanism relies on comments of the form `# Copied from xxx`. The `xxx` should contain the whole path to the class of function which is being copied below. For instance, `RobertaSelfOutput` is a direct copy of the `BertSelfOutput` class, so you can see [here](https://github.com/huggingface/transformers/blob/2bd7a27a671fd1d98059124024f580f8f5c0f3b5/src/transformers/models/roberta/modeling_roberta.py#L289) it has a comment:
|
| 158 |
+
|
| 159 |
+
```py
|
| 160 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
Note that instead of applying this to a whole class, you can apply it to the relevant methods that are copied from. For instance [here](https://github.com/huggingface/transformers/blob/2bd7a27a671fd1d98059124024f580f8f5c0f3b5/src/transformers/models/roberta/modeling_roberta.py#L598) you can see how `RobertaPreTrainedModel._init_weights` is copied from the same method in `BertPreTrainedModel` with the comment:
|
| 164 |
+
|
| 165 |
+
```py
|
| 166 |
+
# Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
Sometimes the copy is exactly the same except for names: for instance in `RobertaAttention`, we use `RobertaSelfAttention` instead of `BertSelfAttention` but other than that, the code is exactly the same. This is why `# Copied from` supports simple string replacements with the following syntax: `Copied from xxx with foo->bar`. This means the code is copied with all instances of `foo` being replaced by `bar`. You can see how it used [here](https://github.com/huggingface/transformers/blob/2bd7a27a671fd1d98059124024f580f8f5c0f3b5/src/transformers/models/roberta/modeling_roberta.py#L304C1-L304C86) in `RobertaAttention` with the comment:
|
| 170 |
+
|
| 171 |
+
```py
|
| 172 |
+
# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Roberta
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
Note that there shouldn't be any spaces around the arrow (unless that space is part of the pattern to replace of course).
|
| 176 |
+
|
| 177 |
+
You can add several patterns separated by a comma. For instance here `CamemberForMaskedLM` is a direct copy of `RobertaForMaskedLM` with two replacements: `Roberta` to `Camembert` and `ROBERTA` to `CAMEMBERT`. You can see [here](https://github.com/huggingface/transformers/blob/15082a9dc6950ecae63a0d3e5060b2fc7f15050a/src/transformers/models/camembert/modeling_camembert.py#L929) this is done with the comment:
|
| 178 |
+
|
| 179 |
+
```py
|
| 180 |
+
# Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM with Roberta->Camembert, ROBERTA->CAMEMBERT
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
If the order matters (because one of the replacements might conflict with a previous one), the replacements are executed from left to right.
|
| 184 |
+
|
| 185 |
+
<Tip>
|
| 186 |
+
|
| 187 |
+
If the replacements change the formatting (if you replace a short name by a very long name for instance), the copy is checked after applying the auto-formatter.
|
| 188 |
+
|
| 189 |
+
</Tip>
|
| 190 |
+
|
| 191 |
+
Another way when the patterns are just different casings of the same replacement (with an uppercased and a lowercased variants) is just to add the option `all-casing`. [Here](https://github.com/huggingface/transformers/blob/15082a9dc6950ecae63a0d3e5060b2fc7f15050a/src/transformers/models/mobilebert/modeling_mobilebert.py#L1237) is an example in `MobileBertForSequenceClassification` with the comment:
|
| 192 |
+
|
| 193 |
+
```py
|
| 194 |
+
# Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification with Bert->MobileBert all-casing
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
In this case, the code is copied from `BertForSequenceClassification` by replacing:
|
| 198 |
+
- `Bert` by `MobileBert` (for instance when using `MobileBertModel` in the init)
|
| 199 |
+
- `bert` by `mobilebert` (for instance when defining `self.mobilebert`)
|
| 200 |
+
- `BERT` by `MOBILEBERT` (in the constant `MOBILEBERT_INPUTS_DOCSTRING`)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/processors.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Processors
|
| 18 |
+
|
| 19 |
+
Multimodal models require a preprocessor capable of handling inputs that combine more than one modality. Depending on the input modality, a processor needs to convert text into an array of tensors, images into pixel values, and audio into an array with tensors with the correct sampling rate.
|
| 20 |
+
|
| 21 |
+
For example, [PaliGemma](./model_doc/paligemma) is a vision-language model that uses the [SigLIP](./model_doc/siglip) image processor and the [Llama](./model_doc/llama) tokenizer. A [`ProcessorMixin`] class wraps both of these preprocessor types, providing a single and unified processor class for a multimodal model.
|
| 22 |
+
|
| 23 |
+
Call [`~ProcessorMixin.from_pretrained`] to load a processor. Pass the input type to the processor to generate the expected model inputs, input ids and pixel values.
|
| 24 |
+
|
| 25 |
+
```py
|
| 26 |
+
from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
|
| 27 |
+
from PIL import Image
|
| 28 |
+
import requests
|
| 29 |
+
|
| 30 |
+
processor = AutoProcessor.from_pretrained("google/paligemma-3b-pt-224")
|
| 31 |
+
|
| 32 |
+
prompt = "answer en Where is the cat standing?"
|
| 33 |
+
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
|
| 34 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
| 35 |
+
|
| 36 |
+
inputs = processor(text=prompt, images=image, return_tensors="pt")
|
| 37 |
+
inputs
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
This guide describes the processor class and how to preprocess multimodal inputs.
|
| 41 |
+
|
| 42 |
+
## Processor classes
|
| 43 |
+
|
| 44 |
+
All processors inherit from the [`ProcessorMixin`] class which provides methods like [`~ProcessorMixin.from_pretrained`], [`~ProcessorMixin.save_pretrained`], and [`~ProcessorMixin.push_to_hub`] for loading, saving, and sharing processors to the Hub.
|
| 45 |
+
|
| 46 |
+
There are two ways to load a processor, with an [`AutoProcessor`] and with a model-specific processor class.
|
| 47 |
+
|
| 48 |
+
<hfoptions id="processor-class">
|
| 49 |
+
<hfoption id="AutoProcessor">
|
| 50 |
+
|
| 51 |
+
The [AutoClass](./model_doc/auto) API provides a simple interface to load processors without directly specifying the specific model class it belongs to.
|
| 52 |
+
|
| 53 |
+
Use [`~AutoProcessor.from_pretrained`] to load a processor.
|
| 54 |
+
|
| 55 |
+
```py
|
| 56 |
+
from transformers import AutoProcessor
|
| 57 |
+
|
| 58 |
+
processor = AutoProcessor.from_pretrained("google/paligemma-3b-pt-224")
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
</hfoption>
|
| 62 |
+
<hfoption id="model-specific processor">
|
| 63 |
+
|
| 64 |
+
Processors are also associated with a specific pretrained multimodal model class. You can load a processor directly from the model class with [`~ProcessorMixin.from_pretrained`].
|
| 65 |
+
|
| 66 |
+
```py
|
| 67 |
+
from transformers import WhisperProcessor
|
| 68 |
+
|
| 69 |
+
processor = WhisperProcessor.from_pretrained("openai/whisper-tiny")
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
You could also separately load the two preprocessor types, [`WhisperTokenizerFast`] and [`WhisperFeatureExtractor`].
|
| 73 |
+
|
| 74 |
+
```py
|
| 75 |
+
from transformers import WhisperTokenizerFast, WhisperFeatureExtractor, WhisperProcessor
|
| 76 |
+
|
| 77 |
+
tokenizer = WhisperTokenizerFast.from_pretrained("openai/whisper-tiny")
|
| 78 |
+
feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-tiny")
|
| 79 |
+
processor = WhisperProcessor(feature_extractor=feature_extractor, tokenizer=tokenizer)
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
</hfoption>
|
| 83 |
+
</hfoptions>
|
| 84 |
+
|
| 85 |
+
## Preprocess
|
| 86 |
+
|
| 87 |
+
Processors preprocess multimodal inputs into the expected Transformers format. There are a couple combinations of input modalities that a processor can handle such as text and audio or text and image.
|
| 88 |
+
|
| 89 |
+
Automatic speech recognition (ASR) tasks require a processor that can handle text and audio inputs. Load a dataset and take a look at the `audio` and `text` columns (you can remove the other columns which aren't needed).
|
| 90 |
+
|
| 91 |
+
```py
|
| 92 |
+
from datasets import load_dataset
|
| 93 |
+
|
| 94 |
+
dataset = load_dataset("lj_speech", split="train")
|
| 95 |
+
dataset = dataset.map(remove_columns=["file", "id", "normalized_text"])
|
| 96 |
+
dataset[0]["audio"]
|
| 97 |
+
{'array': array([-7.3242188e-04, -7.6293945e-04, -6.4086914e-04, ...,
|
| 98 |
+
7.3242188e-04, 2.1362305e-04, 6.1035156e-05], dtype=float32),
|
| 99 |
+
'path': '/root/.cache/huggingface/datasets/downloads/extracted/917ece08c95cf0c4115e45294e3cd0dee724a1165b7fc11798369308a465bd26/LJSpeech-1.1/wavs/LJ001-0001.wav',
|
| 100 |
+
'sampling_rate': 22050}
|
| 101 |
+
|
| 102 |
+
dataset[0]["text"]
|
| 103 |
+
'Printing, in the only sense with which we are at present concerned, differs from most if not from all the arts and crafts represented in the Exhibition'
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
Remember to resample the sampling rate to match the pretrained models required sampling rate.
|
| 107 |
+
|
| 108 |
+
```py
|
| 109 |
+
from datasets import Audio
|
| 110 |
+
|
| 111 |
+
dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
Load a processor and pass the audio `array` and `text` columns to it.
|
| 115 |
+
|
| 116 |
+
```py
|
| 117 |
+
from transformers import AutoProcessor
|
| 118 |
+
|
| 119 |
+
processor = AutoProcessor.from_pretrained("openai/whisper-tiny")
|
| 120 |
+
|
| 121 |
+
def prepare_dataset(example):
|
| 122 |
+
audio = example["audio"]
|
| 123 |
+
example.update(processor(audio=audio["array"], text=example["text"], sampling_rate=16000))
|
| 124 |
+
return example
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
Apply the `prepare_dataset` function to preprocess the dataset. The processor returns `input_features` for the `audio` column and `labels` for the text column.
|
| 128 |
+
|
| 129 |
+
```py
|
| 130 |
+
prepare_dataset(dataset[0])
|
| 131 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/aqlm.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# AQLM
|
| 18 |
+
|
| 19 |
+
Additive Quantization of Language Models ([AQLM](https://huggingface.co/papers/2401.06118)) quantizes multiple weights together and takes advantage of interdependencies between them. AQLM represents groups of 8-16 weights as a sum of multiple vector codes.
|
| 20 |
+
|
| 21 |
+
AQLM also supports fine-tuning with [LoRA](https://huggingface.co/docs/peft/package_reference/lora) with the [PEFT](https://huggingface.co/docs/peft) library, and is fully compatible with [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) for even faster inference and training.
|
| 22 |
+
|
| 23 |
+
Run the command below to install the AQLM library with kernel support for both GPU and CPU inference and training. AQLM only works with Python 3.10+.
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
pip install aqlm[gpu,cpu]
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
Load an AQLM-quantized model with [`~PreTrainedModel.from_pretrained`].
|
| 30 |
+
|
| 31 |
+
```python
|
| 32 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 33 |
+
|
| 34 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 35 |
+
"ISTA-DASLab/Mixtral-8x7b-AQLM-2Bit-1x16-hf",
|
| 36 |
+
torch_dtype="auto",
|
| 37 |
+
device_map="auto"
|
| 38 |
+
)
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
## Configurations
|
| 42 |
+
|
| 43 |
+
AQLM quantization setups vary mainly in the number of codebooks used, as well as codebook sizes in bits. The most popular setups and supported inference kernels are shown below.
|
| 44 |
+
|
| 45 |
+
| Kernel | Number of codebooks | Codebook size, bits | Notation | Accuracy | Speedup | Fast GPU inference | Fast CPU inference |
|
| 46 |
+
|---|---------------------|---------------------|----------|-------------|-------------|--------------------|--------------------|
|
| 47 |
+
| Triton | K | N | KxN | - | Up to ~0.7x | ✅ | ❌ |
|
| 48 |
+
| CUDA | 1 | 16 | 1x16 | Best | Up to ~1.3x | ✅ | ❌ |
|
| 49 |
+
| CUDA | 2 | 8 | 2x8 | OK | Up to ~3.0x | ✅ | ❌ |
|
| 50 |
+
| Numba | K | 8 | Kx8 | Good | Up to ~4.0x | ❌ | ✅ |
|
| 51 |
+
|
| 52 |
+
## Resources
|
| 53 |
+
|
| 54 |
+
Run the AQLM demo [notebook](https://colab.research.google.com/drive/1-xZmBRXT5Fm3Ghn4Mwa2KRypORXb855X?usp=sharing) for more examples of how to quantize a model, push a quantized model to the Hub, and more.
|
| 55 |
+
|
| 56 |
+
For more example demo notebooks, visit the AQLM [repository](https://github.com/Vahe1994/AQLM).
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/auto_round.md
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
|
| 2 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 3 |
+
the License. You may obtain a copy of the License at
|
| 4 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 5 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 6 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 7 |
+
specific language governing permissions and limitations under the License.
|
| 8 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 9 |
+
rendered properly in your Markdown viewer.
|
| 10 |
+
-->
|
| 11 |
+
|
| 12 |
+
# AutoRound
|
| 13 |
+
|
| 14 |
+
[AutoRound](https://github.com/intel/auto-round) is an advanced quantization algorithm that delivers strong accuracy, even at 2-bit precision.
|
| 15 |
+
It leverages sign gradient descent to fine-tune both rounding values and min-max clipping thresholds in just 200 steps. Designed for broad compatibility, it seamlessly supports a wide range of LLMs and is actively expanding to cover more VLMs as well.
|
| 16 |
+
It also supports quantization and inference across multiple hardware platforms, including CPU, XPU, and CUDA.
|
| 17 |
+
|
| 18 |
+
AutoRound also offers a variety of useful features, including mixed-bit tuning and inference, lm-head quantization, support for exporting to formats like GPTQ/AWQ/GGUF, and flexible tuning recipes.
|
| 19 |
+
For a comprehensive overview and the latest updates, check out the AutoRound [README](https://github.com/intel/auto-round).
|
| 20 |
+
|
| 21 |
+
AutoRound was originally developed as part of the [Intel Neural Compressor](https://github.com/intel/neural-compressor), serving as a general-purpose model compression library for deep learning.
|
| 22 |
+
It has since evolved into a standalone library focused specifically on low-precision optimization for large language models (LLMs).
|
| 23 |
+
AutoRound remains fully integrated with the Intel Neural Compressor, and you can explore the repository for more details.
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
## Installation
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
pip install auto-round
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
## Supported Quantization Configurations
|
| 33 |
+
|
| 34 |
+
AutoRound supports several quantization configurations:
|
| 35 |
+
|
| 36 |
+
- **Int8 Weight Only**
|
| 37 |
+
- **Int4 Weight Only**
|
| 38 |
+
- **Int3 Weight Only**
|
| 39 |
+
- **Int2 Weight Only**
|
| 40 |
+
- **Mixed bits Weight only**
|
| 41 |
+
|
| 42 |
+
## Hardware Compatibility
|
| 43 |
+
|
| 44 |
+
CPU, XPU, and CUDA for both quantization and inference.
|
| 45 |
+
|
| 46 |
+
## Quantization and Serialization (offline)
|
| 47 |
+
|
| 48 |
+
Currently, only offline mode is supported to generate quantized models.
|
| 49 |
+
|
| 50 |
+
<hfoptions id="quantization">
|
| 51 |
+
<hfoption id="quantization cmd">
|
| 52 |
+
|
| 53 |
+
### Command Line Usage
|
| 54 |
+
```bash
|
| 55 |
+
auto-round \
|
| 56 |
+
--model facebook/opt-125m \
|
| 57 |
+
--bits 4 \
|
| 58 |
+
--group_size 128 \
|
| 59 |
+
--output_dir ./tmp_autoround
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
AutoRound also offer another two recipes, `auto-round-best` and `auto-round-light`, designed for optimal accuracy and improved speed, respectively.
|
| 63 |
+
For 2 bits, we recommend using `auto-round-best` or `auto-round`.
|
| 64 |
+
</hfoption>
|
| 65 |
+
|
| 66 |
+
<hfoption id="quantization auto-round api">
|
| 67 |
+
|
| 68 |
+
### AutoRound API Usage
|
| 69 |
+
This setting offers a better trade-off between accuracy and tuning cost, and is recommended in all scenarios.
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 73 |
+
from auto_round import AutoRound
|
| 74 |
+
|
| 75 |
+
model_name = "facebook/opt-125m"
|
| 76 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto")
|
| 77 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 78 |
+
bits, group_size, sym = 4, 128, True
|
| 79 |
+
# mixed bits config
|
| 80 |
+
# layer_config = {"model.decoder.layers.6.self_attn.out_proj": {"bits": 2, "group_size": 32}}
|
| 81 |
+
autoround = AutoRound(
|
| 82 |
+
model,
|
| 83 |
+
tokenizer,
|
| 84 |
+
bits=bits,
|
| 85 |
+
group_size=group_size,
|
| 86 |
+
sym=sym,
|
| 87 |
+
# enable_torch_compile=True,
|
| 88 |
+
# layer_config=layer_config,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
output_dir = "./tmp_autoround"
|
| 92 |
+
# format= 'auto_round'(default), 'auto_gptq', 'auto_awq'
|
| 93 |
+
autoround.quantize_and_save(output_dir, format='auto_round')
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
</hfoption>
|
| 97 |
+
|
| 98 |
+
<hfoption id="quantization auto-round-best">
|
| 99 |
+
|
| 100 |
+
### AutoRoundBest recipe
|
| 101 |
+
This setting provides the best accuracy in most scenarios but is 4–5× slower than the standard AutoRound recipe. It is especially recommended for 2-bit quantization and is a good choice if sufficient resources are available.
|
| 102 |
+
```python
|
| 103 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 104 |
+
from auto_round import AutoRound
|
| 105 |
+
|
| 106 |
+
model_name = "facebook/opt-125m"
|
| 107 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto")
|
| 108 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 109 |
+
bits, group_size, sym = 4, 128, True
|
| 110 |
+
autoround = AutoRound(
|
| 111 |
+
model,
|
| 112 |
+
tokenizer,
|
| 113 |
+
bits=bits,
|
| 114 |
+
group_size=group_size,
|
| 115 |
+
sym=sym,
|
| 116 |
+
nsamples=512,
|
| 117 |
+
iters=1000,
|
| 118 |
+
low_gpu_mem_usage=True
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
output_dir = "./tmp_autoround"
|
| 122 |
+
autoround.quantize_and_save(output_dir, format='auto_round')
|
| 123 |
+
```
|
| 124 |
+
</hfoption>
|
| 125 |
+
|
| 126 |
+
<hfoption id="quantization auto-round-light">
|
| 127 |
+
|
| 128 |
+
### AutoRoundLight recipe
|
| 129 |
+
This setting offers the best speed (2 - 3X faster than AutoRound), but it may cause a significant accuracy drop for small models and 2-bit quantization. It is recommended for 4-bit settings and models larger than 3B.
|
| 130 |
+
|
| 131 |
+
```python
|
| 132 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 133 |
+
from auto_round import AutoRound
|
| 134 |
+
|
| 135 |
+
model_name = "facebook/opt-125m"
|
| 136 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto")
|
| 137 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 138 |
+
bits, group_size, sym = 4, 128, True
|
| 139 |
+
autoround = AutoRound(
|
| 140 |
+
model,
|
| 141 |
+
tokenizer,
|
| 142 |
+
bits=bits,
|
| 143 |
+
group_size=group_size,
|
| 144 |
+
sym=sym,
|
| 145 |
+
iters=50,
|
| 146 |
+
lr=5e-3,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
output_dir = "./tmp_autoround"
|
| 150 |
+
autoround.quantize_and_save(output_dir, format='auto_round')
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
</hfoption>
|
| 154 |
+
|
| 155 |
+
</hfoptions>
|
| 156 |
+
|
| 157 |
+
W4G128 Average Accuracy of 13 tasks (mmlu-pro, if_eval, gsm8k, etc) and Time Cost Results (Testing was conducted on the Nvidia A100 80G using the version of PyTorch 2.6.0 with enable_torch_compile):
|
| 158 |
+
|
| 159 |
+
| Model | Qwen2.5-0.5B-Instruct | Falcon3-3B | Qwen2.5-7B-Instruct | Meta-Llama-3.1-8B-Instruct | Falcon3-10B | Qwen2.5-72B-Instruct |
|
| 160 |
+
|---------|--------------------|---------------|------------------|----------------------------|---------------|-------------------|
|
| 161 |
+
| 16bits | 0.4192 | 0.5203 | 0.6470 | 0.6212 | 0.6151 | 0.7229 |
|
| 162 |
+
| Best | **0.4137**(7m) | **0.5142**(23m) | 0.6426(58m) | **0.6116**(65m) | **0.6092**(81m) | 0.7242(575m) |
|
| 163 |
+
| Default | 0.4129(2m) | 0.5133(6m) | 0.6441(13m) | 0.6106(13m) | 0.6080(18m) | **0.7252**(118m) |
|
| 164 |
+
| Light | 0.4052(2m) | 0.5108(3m) | **0.6453**(5m) | 0.6104(6m) | 0.6063(6m) | 0.7243(37m) |
|
| 165 |
+
|
| 166 |
+
## Inference
|
| 167 |
+
|
| 168 |
+
AutoRound automatically selects the best available backend based on the installed libraries and prompts the user to install additional libraries when a better backend is found.
|
| 169 |
+
<hfoptions id="inference">
|
| 170 |
+
<hfoption id="inference cpu">
|
| 171 |
+
|
| 172 |
+
### CPU
|
| 173 |
+
|
| 174 |
+
Supports 2, 4, and 8 bits. We recommend using intel-extension-for-pytorch (IPEX) for 4 bits inference.
|
| 175 |
+
|
| 176 |
+
```python
|
| 177 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 178 |
+
|
| 179 |
+
model_name = "OPEA/Qwen2.5-1.5B-Instruct-int4-sym-inc"
|
| 180 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="cpu", torch_dtype="auto")
|
| 181 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 182 |
+
text = "There is a girl who likes adventure,"
|
| 183 |
+
inputs = tokenizer(text, return_tensors="pt").to(model.device)
|
| 184 |
+
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50, do_sample=False)[0]))
|
| 185 |
+
```
|
| 186 |
+
|
| 187 |
+
</hfoption>
|
| 188 |
+
|
| 189 |
+
<hfoption id="inference xpu">
|
| 190 |
+
|
| 191 |
+
### XPU
|
| 192 |
+
|
| 193 |
+
Supports 4 bits only. We recommend using intel-extension-for-pytorch (IPEX) for inference.
|
| 194 |
+
|
| 195 |
+
```python
|
| 196 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 197 |
+
|
| 198 |
+
model_name = "OPEA/Qwen2.5-1.5B-Instruct-int4-sym-inc"
|
| 199 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="xpu", torch_dtype="auto")
|
| 200 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 201 |
+
text = "There is a girl who likes adventure,"
|
| 202 |
+
inputs = tokenizer(text, return_tensors="pt").to(model.device)
|
| 203 |
+
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50, do_sample=False)[0]))
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
</hfoption>
|
| 207 |
+
|
| 208 |
+
<hfoption id="inference cuda">
|
| 209 |
+
|
| 210 |
+
### CUDA
|
| 211 |
+
|
| 212 |
+
Supports 2, 3, 4, and 8 bits. We recommend using GPTQModel for 4 and 8 bits inference.
|
| 213 |
+
|
| 214 |
+
```python
|
| 215 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 216 |
+
|
| 217 |
+
model_name = "OPEA/Qwen2.5-1.5B-Instruct-int4-sym-inc"
|
| 218 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="cuda", torch_dtype="auto")
|
| 219 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 220 |
+
text = "There is a girl who likes adventure,"
|
| 221 |
+
inputs = tokenizer(text, return_tensors="pt").to(model.device)
|
| 222 |
+
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50, do_sample=False)[0]))
|
| 223 |
+
```
|
| 224 |
+
|
| 225 |
+
</hfoption>
|
| 226 |
+
|
| 227 |
+
<hfoption id="inference backend">
|
| 228 |
+
|
| 229 |
+
### Specify Inference Backend
|
| 230 |
+
|
| 231 |
+
AutoRound automatically selects the backend for each layer based on compatibility. In general, the priority order is Marlin > ExLLaMAV2 > Triton, but the final choice depends on factors such as group size, bit width, packing format, hardware device, and other implementation details. For more details, please refer to [backends](https://github.com/intel/auto-round?tab=readme-ov-file#specify-backend),
|
| 232 |
+
|
| 233 |
+
The backend may not always be the most suitable for certain devices.
|
| 234 |
+
You can specify your preferred backend such as "ipex" for CPU, "ipex/triton" for XPU, "marlin/exllamav2/triton" for CUDA, according to your needs or hardware compatibility. Please note that additional corresponding libraries may be required.
|
| 235 |
+
|
| 236 |
+
```python
|
| 237 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, AutoRoundConfig
|
| 238 |
+
|
| 239 |
+
model_name = "OPEA/Qwen2.5-1.5B-Instruct-int4-sym-inc"
|
| 240 |
+
quantization_config = AutoRoundConfig(backend="ipex")
|
| 241 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="cpu", quantization_config=quantization_config, torch_dtype="auto")
|
| 242 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 243 |
+
text = "There is a girl who likes adventure,"
|
| 244 |
+
inputs = tokenizer(text, return_tensors="pt").to(model.device)
|
| 245 |
+
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50, do_sample=False)[0]))
|
| 246 |
+
```
|
| 247 |
+
|
| 248 |
+
</hfoption>
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
<hfoption id="format convert">
|
| 252 |
+
|
| 253 |
+
### Convert GPTQ/AWQ to AutoRound
|
| 254 |
+
|
| 255 |
+
Most GPTQ/AWQ models can be converted to the AutoRound format for better compatibility and support with Intel devices. Please note that the quantization config will be changed if the model is serialized.
|
| 256 |
+
|
| 257 |
+
```python
|
| 258 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, AutoRoundConfig
|
| 259 |
+
|
| 260 |
+
model_name = "ybelkada/opt-125m-gptq-4bit"
|
| 261 |
+
quantization_config = AutoRoundConfig()
|
| 262 |
+
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="cpu", quantization_config=quantization_config, torch_dtype="auto")
|
| 263 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 264 |
+
text = "There is a girl who likes adventure,"
|
| 265 |
+
inputs = tokenizer(text, return_tensors="pt").to(model.device)
|
| 266 |
+
print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50, do_sample=False)[0]))
|
| 267 |
+
```
|
| 268 |
+
|
| 269 |
+
</hfoption>
|
| 270 |
+
|
| 271 |
+
</hfoptions>
|
| 272 |
+
|
| 273 |
+
## Issues
|
| 274 |
+
|
| 275 |
+
If you encounter any issues with the transformers integration, please open an issue on
|
| 276 |
+
the [transformers](https://github.com/huggingface/transformers/issues) repository.
|
| 277 |
+
If you encounter any issues with auto-round, please open an issue on
|
| 278 |
+
the [AutoRound](https://github.com/intel/auto-round/issues) repository.
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
## Acknowledgement
|
| 282 |
+
Special thanks to open-source low precision libraries such as AutoGPTQ, AutoAWQ, GPTQModel, Triton, Marlin, and ExLLaMAV2 for providing low-precision CUDA kernels, which are leveraged in AutoRound.
|
| 283 |
+
|
| 284 |
+
## Contribution
|
| 285 |
+
Contributions to [AutoRound](https://github.com/intel/auto-round/pulls) are welcome and greatly appreciated!
|
| 286 |
+
Whether it's fixing bugs, improving documentation, adding new features, or suggesting improvements, your help is always valued.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/awq.md
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# AWQ
|
| 18 |
+
|
| 19 |
+
[Activation-aware Weight Quantization (AWQ)](https://hf.co/papers/2306.00978) preserves a small fraction of the weights that are important for LLM performance to compress a model to 4-bits with minimal performance degradation.
|
| 20 |
+
|
| 21 |
+
There are several libraries for quantizing models with the AWQ algorithm, such as [llm-awq](https://github.com/mit-han-lab/llm-awq), [autoawq](https://github.com/casper-hansen/AutoAWQ) or [optimum-intel](https://huggingface.co/docs/optimum/main/en/intel/optimization_inc). Transformers supports loading models quantized with the llm-awq and autoawq libraries. This guide will show you how to load models quantized with autoawq, but the process is similar for llm-awq quantized models.
|
| 22 |
+
|
| 23 |
+
Run the command below to install autoawq
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
pip install autoawq
|
| 27 |
+
```
|
| 28 |
+
> [!WARNING]
|
| 29 |
+
> AutoAWQ downgrades Transformers to version 4.47.1. If you want to do inference with AutoAWQ, you may need to reinstall your Transformers' version after installing AutoAWQ.
|
| 30 |
+
|
| 31 |
+
Identify an AWQ-quantized model by checking the `quant_method` key in the models [config.json](https://huggingface.co/TheBloke/zephyr-7B-alpha-AWQ/blob/main/config.json) file.
|
| 32 |
+
|
| 33 |
+
```json
|
| 34 |
+
{
|
| 35 |
+
"_name_or_path": "/workspace/process/huggingfaceh4_zephyr-7b-alpha/source",
|
| 36 |
+
"architectures": [
|
| 37 |
+
"MistralForCausalLM"
|
| 38 |
+
],
|
| 39 |
+
...
|
| 40 |
+
...
|
| 41 |
+
...
|
| 42 |
+
"quantization_config": {
|
| 43 |
+
"quant_method": "awq",
|
| 44 |
+
"zero_point": true,
|
| 45 |
+
"group_size": 128,
|
| 46 |
+
"bits": 4,
|
| 47 |
+
"version": "gemm"
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
Load the AWQ-quantized model with [`~PreTrainedModel.from_pretrained`]. This automatically sets the other weights to fp16 by default for performance reasons. Use the `torch_dtype` parameter to load these other weights in a different format.
|
| 53 |
+
|
| 54 |
+
If the model is loaded on the CPU, use the `device_map` parameter to move it to a GPU.
|
| 55 |
+
|
| 56 |
+
```py
|
| 57 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 58 |
+
import torch
|
| 59 |
+
|
| 60 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 61 |
+
"TheBloke/zephyr-7B-alpha-AWQ",
|
| 62 |
+
torch_dtype=torch.float32,
|
| 63 |
+
device_map="cuda:0"
|
| 64 |
+
)
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
Use `attn_implementation` to enable [FlashAttention2](../perf_infer_gpu_one#flashattention-2) to further accelerate inference.
|
| 68 |
+
|
| 69 |
+
```py
|
| 70 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 71 |
+
|
| 72 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 73 |
+
"TheBloke/zephyr-7B-alpha-AWQ",
|
| 74 |
+
attn_implementation="flash_attention_2",
|
| 75 |
+
device_map="cuda:0"
|
| 76 |
+
)
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
## Fused modules
|
| 80 |
+
|
| 81 |
+
Fused modules offer improved accuracy and performance. They are supported out-of-the-box for AWQ modules for [Llama](https://huggingface.co/meta-llama) and [Mistral](https://huggingface.co/mistralai/Mistral-7B-v0.1) architectures, but you can also fuse AWQ modules for unsupported architectures.
|
| 82 |
+
|
| 83 |
+
> [!WARNING]
|
| 84 |
+
> Fused modules cannot be combined with other optimization techniques such as FlashAttention2.
|
| 85 |
+
|
| 86 |
+
<hfoptions id="fuse">
|
| 87 |
+
<hfoption id="supported architectures">
|
| 88 |
+
|
| 89 |
+
Create an [`AwqConfig`] and set the parameters `fuse_max_seq_len` and `do_fuse=True` to enable fused modules. The `fuse_max_seq_len` parameter is the total sequence length and it should include the context length and the expected generation length. Set it to a larger value to be safe.
|
| 90 |
+
|
| 91 |
+
The example below fuses the AWQ modules of the [TheBloke/Mistral-7B-OpenOrca-AWQ](https://huggingface.co/TheBloke/Mistral-7B-OpenOrca-AWQ) model.
|
| 92 |
+
|
| 93 |
+
```python
|
| 94 |
+
import torch
|
| 95 |
+
from transformers import AwqConfig, AutoModelForCausalLM
|
| 96 |
+
|
| 97 |
+
quantization_config = AwqConfig(
|
| 98 |
+
bits=4,
|
| 99 |
+
fuse_max_seq_len=512,
|
| 100 |
+
do_fuse=True,
|
| 101 |
+
)
|
| 102 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 103 |
+
"TheBloke/Mistral-7B-OpenOrca-AWQ",
|
| 104 |
+
quantization_config=quantization_config
|
| 105 |
+
).to(0)
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
The [TheBloke/Mistral-7B-OpenOrca-AWQ](https://huggingface.co/TheBloke/Mistral-7B-OpenOrca-AWQ) model was benchmarked with `batch_size=1` with and without fused modules.
|
| 109 |
+
|
| 110 |
+
<figcaption class="text-center text-gray-500 text-lg">Unfused module</figcaption>
|
| 111 |
+
|
| 112 |
+
| Batch Size | Prefill Length | Decode Length | Prefill tokens/s | Decode tokens/s | Memory (VRAM) |
|
| 113 |
+
|-------------:|-----------------:|----------------:|-------------------:|------------------:|:----------------|
|
| 114 |
+
| 1 | 32 | 32 | 60.0984 | 38.4537 | 4.50 GB (5.68%) |
|
| 115 |
+
| 1 | 64 | 64 | 1333.67 | 31.6604 | 4.50 GB (5.68%) |
|
| 116 |
+
| 1 | 128 | 128 | 2434.06 | 31.6272 | 4.50 GB (5.68%) |
|
| 117 |
+
| 1 | 256 | 256 | 3072.26 | 38.1731 | 4.50 GB (5.68%) |
|
| 118 |
+
| 1 | 512 | 512 | 3184.74 | 31.6819 | 4.59 GB (5.80%) |
|
| 119 |
+
| 1 | 1024 | 1024 | 3148.18 | 36.8031 | 4.81 GB (6.07%) |
|
| 120 |
+
| 1 | 2048 | 2048 | 2927.33 | 35.2676 | 5.73 GB (7.23%) |
|
| 121 |
+
|
| 122 |
+
<figcaption class="text-center text-gray-500 text-lg">Fused module</figcaption>
|
| 123 |
+
|
| 124 |
+
| Batch Size | Prefill Length | Decode Length | Prefill tokens/s | Decode tokens/s | Memory (VRAM) |
|
| 125 |
+
|-------------:|-----------------:|----------------:|-------------------:|------------------:|:----------------|
|
| 126 |
+
| 1 | 32 | 32 | 81.4899 | 80.2569 | 4.00 GB (5.05%) |
|
| 127 |
+
| 1 | 64 | 64 | 1756.1 | 106.26 | 4.00 GB (5.05%) |
|
| 128 |
+
| 1 | 128 | 128 | 2479.32 | 105.631 | 4.00 GB (5.06%) |
|
| 129 |
+
| 1 | 256 | 256 | 1813.6 | 85.7485 | 4.01 GB (5.06%) |
|
| 130 |
+
| 1 | 512 | 512 | 2848.9 | 97.701 | 4.11 GB (5.19%) |
|
| 131 |
+
| 1 | 1024 | 1024 | 3044.35 | 87.7323 | 4.41 GB (5.57%) |
|
| 132 |
+
| 1 | 2048 | 2048 | 2715.11 | 89.4709 | 5.57 GB (7.04%) |
|
| 133 |
+
|
| 134 |
+
The speed and throughput of fused and unfused modules were also tested with the [optimum-benchmark](https://github.com/huggingface/optimum-benchmark) library.
|
| 135 |
+
|
| 136 |
+
<div class="flex gap-4">
|
| 137 |
+
<div>
|
| 138 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/quantization/fused_forward_memory_plot.png" alt="generate throughput per batch size" />
|
| 139 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">forward peak memory/batch size</figcaption>
|
| 140 |
+
</div>
|
| 141 |
+
<div>
|
| 142 |
+
<img class="rounded-xl" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/quantization/fused_generate_throughput_plot.png" alt="forward latency per batch size" />
|
| 143 |
+
<figcaption class="mt-2 text-center text-sm text-gray-500">generate throughput/batch size</figcaption>
|
| 144 |
+
</div>
|
| 145 |
+
</div>
|
| 146 |
+
|
| 147 |
+
</hfoption>
|
| 148 |
+
<hfoption id="unsupported architectures">
|
| 149 |
+
|
| 150 |
+
For architectures that don't support fused modules, create an [`AwqConfig`] and define a custom fusing mapping in `modules_to_fuse` to determine which modules need to be fused.
|
| 151 |
+
|
| 152 |
+
The example below fuses the AWQ modules of the [TheBloke/Yi-34B-AWQ](https://huggingface.co/TheBloke/Yi-34B-AWQ) model.
|
| 153 |
+
|
| 154 |
+
```python
|
| 155 |
+
import torch
|
| 156 |
+
from transformers import AwqConfig, AutoModelForCausalLM
|
| 157 |
+
|
| 158 |
+
quantization_config = AwqConfig(
|
| 159 |
+
bits=4,
|
| 160 |
+
fuse_max_seq_len=512,
|
| 161 |
+
modules_to_fuse={
|
| 162 |
+
"attention": ["q_proj", "k_proj", "v_proj", "o_proj"],
|
| 163 |
+
"layernorm": ["ln1", "ln2", "norm"],
|
| 164 |
+
"mlp": ["gate_proj", "up_proj", "down_proj"],
|
| 165 |
+
"use_alibi": False,
|
| 166 |
+
"num_attention_heads": 56,
|
| 167 |
+
"num_key_value_heads": 8,
|
| 168 |
+
"hidden_size": 7168
|
| 169 |
+
}
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 173 |
+
"TheBloke/Yi-34B-AWQ",
|
| 174 |
+
quantization_config=quantization_config
|
| 175 |
+
).to(0)
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
The parameter `modules_to_fuse` should include the following keys.
|
| 179 |
+
|
| 180 |
+
- `"attention"`: The names of the attention layers to fuse in the following order: query, key, value and output projection layer. If you don't want to fuse these layers, pass an empty list.
|
| 181 |
+
- `"layernorm"`: The names of all the LayerNorm layers you want to replace with a custom fused LayerNorm. If you don't want to fuse these layers, pass an empty list.
|
| 182 |
+
- `"mlp"`: The names of the MLP layers you want to fuse into a single MLP layer in the order: (gate (dense, layer, post-attention) / up / down layers).
|
| 183 |
+
- `"use_alibi"`: If your model uses ALiBi positional embedding.
|
| 184 |
+
- `"num_attention_heads"`: The number of attention heads.
|
| 185 |
+
- `"num_key_value_heads"`: The number of key value heads that should be used to implement Grouped Query Attention (GQA).
|
| 186 |
+
|
| 187 |
+
| parameter value | attention |
|
| 188 |
+
|---|---|
|
| 189 |
+
| `num_key_value_heads=num_attention_heads` | Multi-Head Attention |
|
| 190 |
+
| `num_key_value_heads=1` | Multi-Query Attention |
|
| 191 |
+
| `num_key_value_heads=...` | Grouped Query Attention |
|
| 192 |
+
|
| 193 |
+
- `"hidden_size"`: The dimension of the hidden representations.
|
| 194 |
+
|
| 195 |
+
</hfoption>
|
| 196 |
+
</hfoptions>
|
| 197 |
+
|
| 198 |
+
## ExLlamaV2
|
| 199 |
+
|
| 200 |
+
[ExLlamaV2](https://github.com/turboderp/exllamav2) kernels support faster prefill and decoding. Run the command below to install the latest version of autoawq with ExLlamaV2 support.
|
| 201 |
+
|
| 202 |
+
```bash
|
| 203 |
+
pip install git+https://github.com/casper-hansen/AutoAWQ.git
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
Set `version="exllama"` in [`AwqConfig`] to enable ExLlamaV2 kernels.
|
| 207 |
+
|
| 208 |
+
> [!TIP]
|
| 209 |
+
> ExLlamaV2 is supported on AMD GPUs.
|
| 210 |
+
|
| 211 |
+
```py
|
| 212 |
+
import torch
|
| 213 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, AwqConfig
|
| 214 |
+
|
| 215 |
+
quantization_config = AwqConfig(version="exllama")
|
| 216 |
+
|
| 217 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 218 |
+
"TheBloke/Mistral-7B-Instruct-v0.1-AWQ",
|
| 219 |
+
quantization_config=quantization_config,
|
| 220 |
+
device_map="auto",
|
| 221 |
+
)
|
| 222 |
+
```
|
| 223 |
+
|
| 224 |
+
## CPU
|
| 225 |
+
|
| 226 |
+
[Intel Extension for PyTorch (IPEX)](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/) is designed to enable performance optimizations on Intel hardware. Run the command below to install the latest version of autoawq with IPEX support.
|
| 227 |
+
|
| 228 |
+
```bash
|
| 229 |
+
pip install intel-extension-for-pytorch # for IPEX-GPU refer to https://intel.github.io/intel-extension-for-pytorch/xpu/2.5.10+xpu/
|
| 230 |
+
pip install git+https://github.com/casper-hansen/AutoAWQ.git
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
Set `version="ipex"` in [`AwqConfig`] to enable ExLlamaV2 kernels.
|
| 234 |
+
|
| 235 |
+
```python
|
| 236 |
+
import torch
|
| 237 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, AwqConfig
|
| 238 |
+
|
| 239 |
+
device = "cpu" # set to "xpu" for Intel GPU
|
| 240 |
+
quantization_config = AwqConfig(version="ipex")
|
| 241 |
+
|
| 242 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 243 |
+
"TheBloke/TinyLlama-1.1B-Chat-v0.3-AWQ",
|
| 244 |
+
quantization_config=quantization_config,
|
| 245 |
+
device_map=device,
|
| 246 |
+
)
|
| 247 |
+
```
|
| 248 |
+
|
| 249 |
+
## Resources
|
| 250 |
+
|
| 251 |
+
Run the AWQ demo [notebook](https://colab.research.google.com/drive/1HzZH89yAXJaZgwJDhQj9LqSBux932BvY#scrollTo=Wwsg6nCwoThm) for more examples of how to quantize a model, push a quantized model to the Hub, and more.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/bitnet.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# BitNet
|
| 18 |
+
|
| 19 |
+
[BitNet](https://huggingface.co/papers/2402.17764) replaces traditional linear layers in Multi-Head Attention and feed-forward networks with specialized BitLinear layers. The BitLinear layers quantize the weights using ternary precision (with values of -1, 0, and 1) and quantize the activations to 8-bit precision.
|
| 20 |
+
|
| 21 |
+
<figure style="text-align: center;">
|
| 22 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/1.58llm_extreme_quantization/bitlinear.png" alt="Alt Text" />
|
| 23 |
+
<figcaption>The architecture of BitNet with BitLinear layers.</figcaption>
|
| 24 |
+
</figure>
|
| 25 |
+
|
| 26 |
+
BitNet models can't be quantized on the fly. They need to be quantized during pretraining or fine-tuning because it is a Quantization-Aware Training (QAT) technique. During training, the weights are quantized to ternary values with symmetric per tensor quantization.
|
| 27 |
+
|
| 28 |
+
1. Compute the average of the absolute values of the weight matrix and use as a scale.
|
| 29 |
+
2. Divide the weights by the scale, round the values, constrain them between -1 and 1, and rescale them to continue in full precision.
|
| 30 |
+
3. Activations are quantized to a specified bit-width (8-bit) using [absmax](https://huggingface.co/papers/2208.07339) quantization (symmetric per channel quantization). This involves scaling the activations into a range of [−128,127].
|
| 31 |
+
|
| 32 |
+
Refer to this [PR](https://github.com/huggingface/nanotron/pull/180) to pretrain or fine-tune a 1.58-bit model with [Nanotron](https://github.com/huggingface/nanotron). For fine-tuning, convert a model from the Hugging Face to Nanotron format. Find the conversion steps in this [PR](https://github.com/huggingface/nanotron/pull/174).
|
| 33 |
+
|
| 34 |
+
Load a BitNet quantized model with [`~PreTrainedModel.from_pretrained`].
|
| 35 |
+
|
| 36 |
+
```py
|
| 37 |
+
from transformers import AutoModelForCausalLM
|
| 38 |
+
path = "/path/to/model"
|
| 39 |
+
model = AutoModelForCausalLM.from_pretrained(path, device_map="auto")
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
## Kernels
|
| 43 |
+
|
| 44 |
+
`@torch.compile` is used to unpack the weights and perform the forward pass. It’s very straightforward to implement and delivers significant speed improvements. Additional optimized kernels will be integrated in future versions.
|
| 45 |
+
|
| 46 |
+
## Resources
|
| 47 |
+
|
| 48 |
+
Read [Fine-tuning LLMs to 1.58bit: extreme quantization made easy](https://huggingface.co/blog/1_58_llm_extreme_quantization) to learn more about how BitNet models are trained and fine-tuned.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/bitsandbytes.md
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Bitsandbytes
|
| 18 |
+
|
| 19 |
+
The [bitsandbytes](https://github.com/bitsandbytes-foundation/bitsandbytes) library provides quantization tools for LLMs through a lightweight Python wrapper around CUDA functions. It enables working with large models using limited computational resources by reducing their memory footprint.
|
| 20 |
+
|
| 21 |
+
At its core, bitsandbytes provides:
|
| 22 |
+
|
| 23 |
+
- **Quantized Linear Layers**: `Linear8bitLt` and `Linear4bit` layers that replace standard PyTorch linear layers with memory-efficient quantized alternatives
|
| 24 |
+
- **Optimized Optimizers**: 8-bit versions of common optimizers through its `optim` module, enabling training of large models with reduced memory requirements
|
| 25 |
+
- **Matrix Multiplication**: Optimized matrix multiplication operations that leverage the quantized format
|
| 26 |
+
|
| 27 |
+
bitsandbytes offers two main quantization features:
|
| 28 |
+
|
| 29 |
+
1. **LLM.int8()** - An 8-bit quantization method that makes inference more accessible without significant performance degradation. Unlike naive quantization, [LLM.int8()](https://hf.co/papers/2208.07339) dynamically preserves higher precision for critical computations, preventing information loss in sensitive parts of the model.
|
| 30 |
+
|
| 31 |
+
2. **QLoRA** - A 4-bit quantization technique that compresses models even further while maintaining trainability by inserting a small set of trainable low-rank adaptation (LoRA) weights.
|
| 32 |
+
|
| 33 |
+
> **Note:** For a user-friendly quantization experience, you can use the `bitsandbytes` [community space](https://huggingface.co/spaces/bnb-community/bnb-my-repo).
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
Run the command below to install bitsandbytes.
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
pip install --upgrade transformers accelerate bitsandbytes
|
| 40 |
+
```
|
| 41 |
+
To compile from source, follow the instructions in the [bitsandbytes installation guide](https://huggingface.co/docs/bitsandbytes/main/en/installation).
|
| 42 |
+
|
| 43 |
+
## Hardware Compatibility
|
| 44 |
+
bitsandbytes is currently only supported on CUDA GPUs for CUDA versions 11.0 - 12.8. However, there's an ongoing multi-backend effort under development, which is currently in alpha. If you're interested in providing feedback or testing, check out the [bitsandbytes repository](https://github.com/bitsandbytes-foundation/bitsandbytes) for more information.
|
| 45 |
+
|
| 46 |
+
### CUDA
|
| 47 |
+
|
| 48 |
+
| Feature | Minimum Hardware Requirement |
|
| 49 |
+
|---------|-------------------------------|
|
| 50 |
+
| 8-bit optimizers | NVIDIA Maxwell (GTX 900 series, TITAN X, M40) or newer GPUs * |
|
| 51 |
+
| LLM.int8() | NVIDIA Turing (RTX 20 series, T4) or newer GPUs |
|
| 52 |
+
| NF4/FP4 quantization | NVIDIA Maxwell (GTX 900 series, TITAN X, M40) or newer GPUs * |
|
| 53 |
+
|
| 54 |
+
### Multi-backend
|
| 55 |
+
|
| 56 |
+
| Backend | Supported Versions | Python versions | Architecture Support | Status |
|
| 57 |
+
|---------|-------------------|----------------|---------------------|---------|
|
| 58 |
+
| AMD ROCm | 6.1+ | 3.10+ | minimum CDNA - gfx90a, RDNA - gfx1100 | Alpha |
|
| 59 |
+
| Apple Silicon (MPS) | WIP | 3.10+ | M1/M2 chips | Planned |
|
| 60 |
+
| Intel CPU | v2.4.0+ (ipex) | 3.10+ | Intel CPU | Alpha |
|
| 61 |
+
| Intel GPU | v2.4.0+ (ipex) | 3.10+ | Intel GPU | Experimental |
|
| 62 |
+
| Ascend NPU | 2.1.0+ (torch_npu) | 3.10+ | Ascend NPU | Experimental |
|
| 63 |
+
|
| 64 |
+
> **Note:** Bitsandbytes is moving away from the multi-backend approach towards using [Pytorch Custom Operators](https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html), as the main mechanism for supporting new hardware, and dispatching to the correct backend.
|
| 65 |
+
|
| 66 |
+
## Quantization Examples
|
| 67 |
+
|
| 68 |
+
Quantize a model by passing a [`BitsAndBytesConfig`] to [`~PreTrainedModel.from_pretrained`]. This works for any model in any modality, as long as it supports [Accelerate](https://huggingface.co/docs/accelerate/index) and contains [torch.nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) layers.
|
| 69 |
+
|
| 70 |
+
<hfoptions id="bnb">
|
| 71 |
+
<hfoption id="8-bit">
|
| 72 |
+
<div class="bnb-container" style="border: 1px solid #ddd; border-radius: 8px; padding: 20px; margin: 20px 0">
|
| 73 |
+
Quantizing a model in 8-bit halves the memory-usage, and for large models, set `device_map="auto"` to efficiently distribute the weights across all available GPUs.
|
| 74 |
+
|
| 75 |
+
```py
|
| 76 |
+
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
|
| 77 |
+
|
| 78 |
+
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
|
| 79 |
+
|
| 80 |
+
model_8bit = AutoModelForCausalLM.from_pretrained(
|
| 81 |
+
"bigscience/bloom-1b7",
|
| 82 |
+
device_map="auto",
|
| 83 |
+
quantization_config=quantization_config
|
| 84 |
+
)
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
By default, all other modules such as [torch.nn.LayerNorm](https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html) are set to the default torch dtype. You can change the data type of these modules with the `torch_dtype` parameter. Setting `torch_dtype="auto"` loads the model in the data type defined in a model's `config.json` file.
|
| 88 |
+
|
| 89 |
+
```py
|
| 90 |
+
import torch
|
| 91 |
+
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
|
| 92 |
+
|
| 93 |
+
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
|
| 94 |
+
|
| 95 |
+
model_8bit = AutoModelForCausalLM.from_pretrained(
|
| 96 |
+
"facebook/opt-350m",
|
| 97 |
+
device_map="auto",
|
| 98 |
+
quantization_config=quantization_config,
|
| 99 |
+
torch_dtype="auto"
|
| 100 |
+
)
|
| 101 |
+
model_8bit.model.decoder.layers[-1].final_layer_norm.weight.dtype
|
| 102 |
+
```
|
| 103 |
+
|
| 104 |
+
Once a model is quantized to 8-bit, you can't push the quantized weights to the Hub unless you're using the latest version of Transformers and bitsandbytes. If you have the latest versions, then you can push the 8-bit model to the Hub with [`~PreTrainedModel.push_to_hub`]. The quantization config.json file is pushed first, followed by the quantized model weights.
|
| 105 |
+
|
| 106 |
+
```py
|
| 107 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 108 |
+
|
| 109 |
+
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
|
| 110 |
+
|
| 111 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 112 |
+
"bigscience/bloom-560m",
|
| 113 |
+
device_map="auto",
|
| 114 |
+
quantization_config=quantization_config
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
model.push_to_hub("bloom-560m-8bit")
|
| 118 |
+
```
|
| 119 |
+
</div>
|
| 120 |
+
</hfoption>
|
| 121 |
+
<hfoption id="4-bit">
|
| 122 |
+
<div class="bnb-container" style="border: 1px solid #ddd; border-radius: 8px; padding: 20px; margin: 20px 0">
|
| 123 |
+
Quantizing a model in 4-bit reduces your memory-usage by 4x, and for large models, set `device_map="auto"` to efficiently distribute the weights across all available GPUs.
|
| 124 |
+
|
| 125 |
+
```py
|
| 126 |
+
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
|
| 127 |
+
|
| 128 |
+
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 129 |
+
|
| 130 |
+
model_4bit = AutoModelForCausalLM.from_pretrained(
|
| 131 |
+
"bigscience/bloom-1b7",
|
| 132 |
+
device_map="auto",
|
| 133 |
+
quantization_config=quantization_config
|
| 134 |
+
)
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
By default, all other modules such as [torch.nn.LayerNorm](https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html) are converted to `torch.float16`. You can change the data type of these modules with the `torch_dtype` parameter.. Setting `torch_dtype="auto"` loads the model in the data type defined in a model's `config.json` file.
|
| 138 |
+
|
| 139 |
+
```py
|
| 140 |
+
import torch
|
| 141 |
+
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
|
| 142 |
+
|
| 143 |
+
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 144 |
+
|
| 145 |
+
model_4bit = AutoModelForCausalLM.from_pretrained(
|
| 146 |
+
"facebook/opt-350m",
|
| 147 |
+
device_map="auto",
|
| 148 |
+
quantization_config=quantization_config,
|
| 149 |
+
torch_dtype="auto"
|
| 150 |
+
)
|
| 151 |
+
model_4bit.model.decoder.layers[-1].final_layer_norm.weight.dtype
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
Make sure you have the latest bitsandbytes version so you can serialize 4-bit models and push them to the Hub with [`~PreTrainedModel.push_to_hub`]. Use [`~PreTrainedModel.save_pretrained`] to save the 4-bit model locally.
|
| 155 |
+
|
| 156 |
+
```py
|
| 157 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 158 |
+
|
| 159 |
+
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 160 |
+
|
| 161 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 162 |
+
"bigscience/bloom-560m",
|
| 163 |
+
device_map="auto",
|
| 164 |
+
quantization_config=quantization_config
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
model.push_to_hub("bloom-560m-4bit")
|
| 168 |
+
```
|
| 169 |
+
</div>
|
| 170 |
+
</hfoption>
|
| 171 |
+
</hfoptions>
|
| 172 |
+
|
| 173 |
+
> [!WARNING]
|
| 174 |
+
> 8 and 4-bit training is only supported for training *extra* parameters.
|
| 175 |
+
|
| 176 |
+
Check your memory footprint with `get_memory_footprint`.
|
| 177 |
+
|
| 178 |
+
```py
|
| 179 |
+
print(model.get_memory_footprint())
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
Load quantized models with [`~PreTrainedModel.from_pretrained`] without a `quantization_config`.
|
| 183 |
+
|
| 184 |
+
```py
|
| 185 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 186 |
+
|
| 187 |
+
model = AutoModelForCausalLM.from_pretrained("{your_username}/bloom-560m-8bit", device_map="auto")
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
## LLM.int8
|
| 191 |
+
|
| 192 |
+
This section explores some of the specific features of 8-bit quantization, such as offloading, outlier thresholds, skipping module conversion, and finetuning.
|
| 193 |
+
|
| 194 |
+
### Offloading
|
| 195 |
+
|
| 196 |
+
8-bit models can offload weights between the CPU and GPU to fit very large models into memory. The weights dispatched to the CPU are stored in **float32** and aren't converted to 8-bit. For example, enable offloading for [bigscience/bloom-1b7](https://huggingface.co/bigscience/bloom-1b7) through [`BitsAndBytesConfig`].
|
| 197 |
+
|
| 198 |
+
```py
|
| 199 |
+
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
|
| 200 |
+
|
| 201 |
+
quantization_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True)
|
| 202 |
+
```
|
| 203 |
+
|
| 204 |
+
Design a custom device map to fit everything on your GPU except for the `lm_head`, which is dispatched to the CPU.
|
| 205 |
+
|
| 206 |
+
```py
|
| 207 |
+
device_map = {
|
| 208 |
+
"transformer.word_embeddings": 0,
|
| 209 |
+
"transformer.word_embeddings_layernorm": 0,
|
| 210 |
+
"lm_head": "cpu",
|
| 211 |
+
"transformer.h": 0,
|
| 212 |
+
"transformer.ln_f": 0,
|
| 213 |
+
}
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
Now load your model with the custom `device_map` and `quantization_config`.
|
| 217 |
+
|
| 218 |
+
```py
|
| 219 |
+
model_8bit = AutoModelForCausalLM.from_pretrained(
|
| 220 |
+
"bigscience/bloom-1b7",
|
| 221 |
+
torch_dtype="auto",
|
| 222 |
+
device_map=device_map,
|
| 223 |
+
quantization_config=quantization_config,
|
| 224 |
+
)
|
| 225 |
+
```
|
| 226 |
+
|
| 227 |
+
### Outlier threshold
|
| 228 |
+
|
| 229 |
+
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).
|
| 230 |
+
|
| 231 |
+
To find the best threshold for your model, experiment with the `llm_int8_threshold` parameter in [`BitsAndBytesConfig`]. For example, setting the threshold to `0.0` significantly speeds up inference at the potential cost of some accuracy loss.
|
| 232 |
+
|
| 233 |
+
```py
|
| 234 |
+
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
|
| 235 |
+
|
| 236 |
+
model_id = "bigscience/bloom-1b7"
|
| 237 |
+
|
| 238 |
+
quantization_config = BitsAndBytesConfig(
|
| 239 |
+
llm_int8_threshold=0.0,
|
| 240 |
+
llm_int8_enable_fp32_cpu_offload=True
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
model_8bit = AutoModelForCausalLM.from_pretrained(
|
| 244 |
+
model_id,
|
| 245 |
+
torch_dtype="auto",
|
| 246 |
+
device_map=device_map,
|
| 247 |
+
quantization_config=quantization_config,
|
| 248 |
+
)
|
| 249 |
+
```
|
| 250 |
+
|
| 251 |
+
### Skip module conversion
|
| 252 |
+
|
| 253 |
+
For some models, like [Jukebox](model_doc/jukebox), you don't need to quantize every module to 8-bit because it can actually cause instability. With Jukebox, there are several `lm_head` modules that should be skipped using the `llm_int8_skip_modules` parameter in [`BitsAndBytesConfig`].
|
| 254 |
+
|
| 255 |
+
```py
|
| 256 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 257 |
+
|
| 258 |
+
model_id = "bigscience/bloom-1b7"
|
| 259 |
+
|
| 260 |
+
quantization_config = BitsAndBytesConfig(
|
| 261 |
+
llm_int8_skip_modules=["lm_head"],
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
model_8bit = AutoModelForCausalLM.from_pretrained(
|
| 265 |
+
model_id,
|
| 266 |
+
torch_dtype="auto",
|
| 267 |
+
device_map="auto",
|
| 268 |
+
quantization_config=quantization_config,
|
| 269 |
+
)
|
| 270 |
+
```
|
| 271 |
+
|
| 272 |
+
### Finetuning
|
| 273 |
+
|
| 274 |
+
The [PEFT](https://github.com/huggingface/peft) library supports fine-tuning large models like [flan-t5-large](https://huggingface.co/google/flan-t5-large) and [facebook/opt-6.7b](https://huggingface.co/facebook/opt-6.7b) with 8-bit quantization. You don't need to pass the `device_map` parameter for training because it automatically loads your model on a GPU. However, you can still customize the device map with the `device_map` parameter (`device_map="auto"` should only be used for inference).
|
| 275 |
+
|
| 276 |
+
## QLoRA
|
| 277 |
+
|
| 278 |
+
This section explores some of the specific features of 4-bit quantization, such as changing the compute data type, the Normal Float 4 (NF4) data type, and nested quantization.
|
| 279 |
+
|
| 280 |
+
### Compute data type
|
| 281 |
+
|
| 282 |
+
Change the data type from float32 (the default value) to bf16 in [`BitsAndBytesConfig`] to speedup computation.
|
| 283 |
+
|
| 284 |
+
```py
|
| 285 |
+
import torch
|
| 286 |
+
from transformers import BitsAndBytesConfig
|
| 287 |
+
|
| 288 |
+
quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
|
| 289 |
+
```
|
| 290 |
+
|
| 291 |
+
### Normal Float 4 (NF4)
|
| 292 |
+
|
| 293 |
+
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.
|
| 294 |
+
|
| 295 |
+
```py
|
| 296 |
+
from transformers import BitsAndBytesConfig
|
| 297 |
+
|
| 298 |
+
nf4_config = BitsAndBytesConfig(
|
| 299 |
+
load_in_4bit=True,
|
| 300 |
+
bnb_4bit_quant_type="nf4",
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
model_nf4 = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", quantization_config=nf4_config)
|
| 304 |
+
```
|
| 305 |
+
|
| 306 |
+
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.
|
| 307 |
+
|
| 308 |
+
### Nested quantization
|
| 309 |
+
|
| 310 |
+
Nested quantization 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. For example, with nested quantization, you can finetune a [Llama-13b](https://huggingface.co/meta-llama/Llama-2-13b) model on a 16GB NVIDIA T4 GPU with a sequence length of 1024, a batch size of 1, and enable gradient accumulation with 4 steps.
|
| 311 |
+
|
| 312 |
+
```py
|
| 313 |
+
from transformers import BitsAndBytesConfig
|
| 314 |
+
|
| 315 |
+
double_quant_config = BitsAndBytesConfig(
|
| 316 |
+
load_in_4bit=True,
|
| 317 |
+
bnb_4bit_use_double_quant=True,
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
model_double_quant = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-13b-chat-hf", torch_dtype="auto", quantization_config=double_quant_config)
|
| 321 |
+
```
|
| 322 |
+
|
| 323 |
+
## Dequantizing bitsandbytes models
|
| 324 |
+
|
| 325 |
+
Once quantized, you can [`~PreTrainedModel.dequantize`] a model to the original precision but this may result in some quality loss. Make sure you have enough GPU memory to fit the dequantized model.
|
| 326 |
+
|
| 327 |
+
```python
|
| 328 |
+
from transformers import AutoModelForCausalLM, BitsAndBytesConfig, AutoTokenizer
|
| 329 |
+
|
| 330 |
+
model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m", BitsAndBytesConfig(load_in_4bit=True))
|
| 331 |
+
model.dequantize()
|
| 332 |
+
```
|
| 333 |
+
|
| 334 |
+
## Resources
|
| 335 |
+
|
| 336 |
+
Learn more about the details of 8-bit quantization in [A Gentle Introduction to 8-bit Matrix Multiplication for transformers at scale using Hugging Face Transformers, Accelerate and bitsandbytes](https://huggingface.co/blog/hf-bitsandbytes-integration).
|
| 337 |
+
|
| 338 |
+
Try 4-bit quantization in this [notebook](https://colab.research.google.com/drive/1ge2F1QSK8Q7h0hn3YKuBCOAS0bK8E0wf) and learn more about it's details in [Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA](https://huggingface.co/blog/4bit-transformers-bitsandbytes).
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/compressed_tensors.md
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# compressed-tensors
|
| 18 |
+
|
| 19 |
+
[compressed-tensors](https://github.com/neuralmagic/compressed-tensors) extends [safetensors](https://github.com/huggingface/safetensors) files to compressed tensor data types to provide a unified checkpoint format for storing and loading various quantization and sparsity formats such dense, int-quantized (int8), float-quantized (fp8), and pack-quantized (int4 or int8 weight-quantized packed into int32).
|
| 20 |
+
|
| 21 |
+
compressed-tensors supports fine-tuning with [PEFT](https://huggingface.co/docs/peft) and includes the following features as well.
|
| 22 |
+
|
| 23 |
+
- fp8, int4, int8 weight and activation precisions.
|
| 24 |
+
- Quantization scales and zero-points strategies for [tensor, channel, group, block, token](https://github.com/neuralmagic/compressed-tensors/blob/83b2e7a969d70606421a76b9a3d112646077c8de/src/compressed_tensors/quantization/quant_args.py#L43-L52).
|
| 25 |
+
- Dynamic per-token activation quantization (or any static strategy).
|
| 26 |
+
- Weight sparsity (unstructured or semi-structured like 2:4) can be composed with quantization for extreme compression.
|
| 27 |
+
- Quantization of arbitrary modules, not just [nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) modules.
|
| 28 |
+
- Targeted support for specific modules by name or class.
|
| 29 |
+
|
| 30 |
+
Install compressed-tensors from [PyPI](https://pypi.org/project/compressed-tensors) to get the latest stable release (recommended) or install it from source to get the latest features.
|
| 31 |
+
|
| 32 |
+
<hfoptions id="install">
|
| 33 |
+
<hfoption id="PyPI">
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
pip install compressed-tensors
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
</hfoption>
|
| 40 |
+
<hfoption id="source code">
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
git clone https://github.com/neuralmagic/compressed-tensors
|
| 44 |
+
cd compressed-tensors
|
| 45 |
+
pip install -e .
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
</hfoption>
|
| 49 |
+
</hfoptions>
|
| 50 |
+
|
| 51 |
+
Search using the compressed-tensors [tag](https://huggingface.co/models?other=compressed-tensors) to find a compatible model on the Hugging Face Hub.
|
| 52 |
+
|
| 53 |
+
Only models that have already been quantized can be loaded at the moment, and once a model is loaded, it cannot be saved. To quantize a model into the compressed-tensors format, see [llm-compressor](https://github.com/vllm-project/llm-compressor). Alternatively, models can be created independently and serizlied with a compressed-tensors config.
|
| 54 |
+
|
| 55 |
+
```python
|
| 56 |
+
from transformers import AutoModelForCausalLM
|
| 57 |
+
|
| 58 |
+
ct_model = AutoModelForCausalLM.from_pretrained("nm-testing/Meta-Llama-3.1-8B-Instruct-FP8-hf", device_map="auto")
|
| 59 |
+
|
| 60 |
+
# measure memory usage
|
| 61 |
+
mem_params = sum([param.nelement()*param.element_size() for param in ct_model.parameters()])
|
| 62 |
+
print(f"{mem_params/2**30:.4f} GB")
|
| 63 |
+
# 8.4575 GB
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
## Model checkpoint
|
| 67 |
+
|
| 68 |
+
compressed-tensor models are defined through its configuration entry. The following example is taken from the [nm-testing/Meta-Llama-3.1-8B-Instruct-FP8-hf](https://huggingface.co/nm-testing/Meta-Llama-3.1-8B-Instruct-FP8-hf/blob/main/config.json) `config.json` file.
|
| 69 |
+
|
| 70 |
+
There are a lot of entries to allow for flexible expression both during and after compression, but the entries for loading and inference can be simplified to focus on just a few key entries.
|
| 71 |
+
|
| 72 |
+
```yaml
|
| 73 |
+
"quantization_config": {
|
| 74 |
+
"config_groups": {
|
| 75 |
+
"group_0": {
|
| 76 |
+
"input_activations": {
|
| 77 |
+
"num_bits": 8,
|
| 78 |
+
"strategy": "tensor",
|
| 79 |
+
"type": "float"
|
| 80 |
+
},
|
| 81 |
+
"targets": ["Linear"],
|
| 82 |
+
"weights": {
|
| 83 |
+
"num_bits": 8,
|
| 84 |
+
"strategy": "tensor",
|
| 85 |
+
"type": "float"
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
},
|
| 89 |
+
"format": "naive-quantized",
|
| 90 |
+
"ignore": ["lm_head"],
|
| 91 |
+
"quant_method": "compressed-tensors",
|
| 92 |
+
"quantization_status": "frozen"
|
| 93 |
+
},
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
The config file specifies the quantization of a config group (`group_0`), which includes weight and activation quantization to fp8 with a static per-tensor strategy. The `lm_head` module is unquantized as shown in the `ignore` key.
|
| 97 |
+
|
| 98 |
+
For a more detailed look at the model weights, use the [safetensors viewer](https://huggingface.co/nm-testing/Meta-Llama-3.1-8B-Instruct-FP8-hf?show_file_info=model.safetensors.index.json) on the model card to see the quantized weights, input scale, and weight scale for all [nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) modules.
|
| 99 |
+
|
| 100 |
+
| Tensors | Shape | Precision |
|
| 101 |
+
| ------- | ----- | --------- |
|
| 102 |
+
model.layers.0.input_layernorm.weight | [4 096] | BF16
|
| 103 |
+
model.layers.0.mlp.down_proj.input_scale | [1] | BF16
|
| 104 |
+
model.layers.0.mlp.down_proj.weight | [4 096, 14 336] | F8_E4M3
|
| 105 |
+
model.layers.0.mlp.down_proj.weight_scale | [1] | BF16
|
| 106 |
+
model.layers.0.mlp.gate_proj.input_scale | [1] | BF16
|
| 107 |
+
model.layers.0.mlp.gate_proj.weight | [14 336, 4 096] | F8_E4M3
|
| 108 |
+
model.layers.0.mlp.gate_proj.weight_scale | [1] | BF16
|
| 109 |
+
model.layers.0.mlp.up_proj.input_scale| [1] |BF16
|
| 110 |
+
model.layers.0.mlp.up_proj.weight | [14 336, 4 096] | F8_E4M3
|
| 111 |
+
model.layers.0.mlp.up_proj.weight_scale | [1] | BF16
|
| 112 |
+
model.layers.0.post_attention_layernorm.weight | [4 096] |BF16
|
| 113 |
+
model.layers.0.self_attn.k_proj.input_scale | [1] | BF16
|
| 114 |
+
model.layers.0.self_attn.k_proj.weight | [1 024, 4 096]| F8_E4M3
|
| 115 |
+
model.layers.0.self_attn.k_proj.weight_scale |[1] | BF16
|
| 116 |
+
model.layers.0.self_attn.o_proj.input_scale | [1] | BF16
|
| 117 |
+
model.layers.0.self_attn.o_proj.weight | [4 096, 4 096] | F8_E4M3
|
| 118 |
+
model.layers.0.self_attn.o_proj.weight_scale | [1] | BF16
|
| 119 |
+
model.layers.0.self_attn.q_proj.input_scale | [1] | BF16
|
| 120 |
+
model.layers.0.self_attn.q_proj.weight | [4 096, 4 096] | F8_E4M3
|
| 121 |
+
model.layers.0.self_attn.q_proj.weight_scale | [1] | BF16
|
| 122 |
+
model.layers.0.self_attn.v_proj.input_scale | [1] | BF16
|
| 123 |
+
model.layers.0.self_attn.v_proj.weight | [1 024, 4 096] | F8_E4M3
|
| 124 |
+
model.layers.0.self_attn.v_proj.weight_scale | [1] | BF16
|
| 125 |
+
|
| 126 |
+
When loading a compressed-tensors model with the [`~quantizers.HFQuantizer`] integration, all the [nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) modules specified in the quantization config are replaced by [CompressedLinear](https://github.com/neuralmagic/compressed-tensors/blob/975cb223b19fcac2b98a4271d17668462d4d6e1d/src/compressed_tensors/linear/compressed_linear.py#L30) modules that manage the compressed weights and forward pass for inference. The `lm_head` module is still kept as an unquantized nn.Linear module.
|
| 127 |
+
|
| 128 |
+
```python
|
| 129 |
+
from transformers import AutoModelForCausalLM
|
| 130 |
+
|
| 131 |
+
ct_model = AutoModelForCausalLM.from_pretrained("nm-testing/Meta-Llama-3.1-8B-Instruct-FP8-hf")
|
| 132 |
+
print(ct_model)
|
| 133 |
+
"""
|
| 134 |
+
LlamaForCausalLM(
|
| 135 |
+
(model): LlamaModel(
|
| 136 |
+
(embed_tokens): Embedding(128256, 4096)
|
| 137 |
+
(layers): ModuleList(
|
| 138 |
+
(0-31): 32 x LlamaDecoderLayer(
|
| 139 |
+
(self_attn): LlamaSdpaAttention(
|
| 140 |
+
(q_proj): CompressedLinear(
|
| 141 |
+
in_features=4096, out_features=4096, bias=False
|
| 142 |
+
(input_observer): MovingAverageMinMaxObserver()
|
| 143 |
+
(weight_observer): MovingAverageMinMaxObserver()
|
| 144 |
+
)
|
| 145 |
+
(k_proj): CompressedLinear(
|
| 146 |
+
in_features=4096, out_features=1024, bias=False
|
| 147 |
+
(input_observer): MovingAverageMinMaxObserver()
|
| 148 |
+
(weight_observer): MovingAverageMinMaxObserver()
|
| 149 |
+
)
|
| 150 |
+
(v_proj): CompressedLinear(
|
| 151 |
+
in_features=4096, out_features=1024, bias=False
|
| 152 |
+
(input_observer): MovingAverageMinMaxObserver()
|
| 153 |
+
(weight_observer): MovingAverageMinMaxObserver()
|
| 154 |
+
)
|
| 155 |
+
(o_proj): CompressedLinear(
|
| 156 |
+
in_features=4096, out_features=4096, bias=False
|
| 157 |
+
(input_observer): MovingAverageMinMaxObserver()
|
| 158 |
+
(weight_observer): MovingAverageMinMaxObserver()
|
| 159 |
+
)
|
| 160 |
+
(rotary_emb): LlamaRotaryEmbedding()
|
| 161 |
+
)
|
| 162 |
+
(mlp): LlamaMLP(
|
| 163 |
+
(gate_proj): CompressedLinear(
|
| 164 |
+
in_features=4096, out_features=14336, bias=False
|
| 165 |
+
(input_observer): MovingAverageMinMaxObserver()
|
| 166 |
+
(weight_observer): MovingAverageMinMaxObserver()
|
| 167 |
+
)
|
| 168 |
+
(up_proj): CompressedLinear(
|
| 169 |
+
in_features=4096, out_features=14336, bias=False
|
| 170 |
+
(input_observer): MovingAverageMinMaxObserver()
|
| 171 |
+
(weight_observer): MovingAverageMinMaxObserver()
|
| 172 |
+
)
|
| 173 |
+
(down_proj): CompressedLinear(
|
| 174 |
+
in_features=14336, out_features=4096, bias=False
|
| 175 |
+
(input_observer): MovingAverageMinMaxObserver()
|
| 176 |
+
(weight_observer): MovingAverageMinMaxObserver()
|
| 177 |
+
)
|
| 178 |
+
(act_fn): SiLU()
|
| 179 |
+
)
|
| 180 |
+
(input_layernorm): LlamaRMSNorm((4096,), eps=1e-05)
|
| 181 |
+
(post_attention_layernorm): LlamaRMSNorm((4096,), eps=1e-05)
|
| 182 |
+
)
|
| 183 |
+
)
|
| 184 |
+
(norm): LlamaRMSNorm((4096,), eps=1e-05)
|
| 185 |
+
(rotary_emb): LlamaRotaryEmbedding()
|
| 186 |
+
)
|
| 187 |
+
(lm_head): Linear(in_features=4096, out_features=128256, bias=False)
|
| 188 |
+
)
|
| 189 |
+
"""
|
| 190 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/concept_guide.md
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Quantization concepts
|
| 18 |
+
|
| 19 |
+
Quantization reduces the memory footprint and computational cost of large machine learning models like those found in the Transformers library. It achieves this by representing the model's weights and or activations with lower-precision data types (like 8-bit integers or int8) instead of the standard 32-bit floating-point (float32).
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
Reducing a model's precision offers several significant benefits:
|
| 23 |
+
|
| 24 |
+
- Smaller model size: Lower-precision data types require less storage space. An int8 model, for example, is roughly 4 times smaller than its float32 counterpart.
|
| 25 |
+
- Faster inference: Operations on lower-precision data types, especially integers, can be significantly faster on compatible hardware (CPUs and GPUs often have specialized instructions for int8 operations). This leads to lower latency.
|
| 26 |
+
- Reduced energy consumption: Faster computations and smaller memory transfers often translate to lower power usage.
|
| 27 |
+
|
| 28 |
+
The primary trade-off in quantization is *efficiency* vs. *accuracy*. Reducing precision saves resources but inevitably introduces small errors (quantization noise). The goal is to minimize this error using appropriate schemes (affine/symmetric), granularity (per-tensor/channel), and techniques (PTQ/QAT) so that the model's performance on its target task degrades as little as possible.
|
| 29 |
+
|
| 30 |
+
The sections below cover quantization schemes, granularity, and techniques.
|
| 31 |
+
|
| 32 |
+
## Quantization schemes
|
| 33 |
+
|
| 34 |
+
The core idea is to map the range of values found in the original float32 weights and activations to the much smaller range represented by int8 (typically \\([-128, 127]\\)).
|
| 35 |
+
|
| 36 |
+
This section covers how some quantization techniques work.
|
| 37 |
+
|
| 38 |
+
<div class="flex justify-center">
|
| 39 |
+
<img width="606" alt="quant_visual" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/quant_visual.png" />
|
| 40 |
+
</div>
|
| 41 |
+
|
| 42 |
+
### Affine quantization
|
| 43 |
+
|
| 44 |
+
The most common method is *affine quantization*. For a given float32 tensor (like a layer's weights), it finds the minimum \\(val_{min}\\) and maximum \\(val_{max}\\) values. This range \\([val_{min}, val_{max}]\\) is mapped to the int8 range \\([q_{min}, q_{max}]\\), which is typically \\([-128, 127]\\).
|
| 45 |
+
|
| 46 |
+
There are two main ways to perform this mapping, *symmetric* and *asymmetric*. The choice between symmetric and asymmetric quantization determines how the float32 range is mapped to the int8 range.
|
| 47 |
+
|
| 48 |
+
- Symmetric: This method assumes the original float32 range is symmetric around zero ( \\([ -a, a ]\\) ). This range is mapped symmetrically to the int8 range, for example, \\([-127, 127]\\). A key characteristic is that the float32 value \\(0.0\\) maps directly to the int8 value \\(0\\). This only requires one parameter, the **scale ( \\(S\\) )**, to define the mapping. It can simplify computations, but it might be less accurate if the original data distribution isn't naturally centered around zero.
|
| 49 |
+
- Asymmetric (Affine): This method does not assume the data is centered around zero. It maps the exact range \\([val_{min}, val_{max}]\\) from float32 to the full int8 range, like \\([-128, 127]\\). This requires two parameters, a **scale ( \\(S\\) )** and a **zero-point ( \\(Z\\) )**.
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
scale ( \\(S\\) ): A positive float32 number representing the ratio between the float32 and the int8 range.
|
| 53 |
+
|
| 54 |
+
$$
|
| 55 |
+
S = \frac{val_{max} - val_{min}}{q_{max} - q_{min}}
|
| 56 |
+
$$
|
| 57 |
+
|
| 58 |
+
zero-Point ( \\(Z\\) ): An int8 value that corresponds to the float32 value \\(0.0\\).
|
| 59 |
+
|
| 60 |
+
$$
|
| 61 |
+
Z = q_{min} - round\left(\frac{val_{min}}{S}\right)
|
| 62 |
+
$$
|
| 63 |
+
|
| 64 |
+
> [!TIP]
|
| 65 |
+
> In symmetric quantization, Z would typically be fixed at 0.
|
| 66 |
+
|
| 67 |
+
With these parameters, a float32 value, \\(x\\). can be quantized to int8 ( \\(q\\) ) with the formula below.
|
| 68 |
+
|
| 69 |
+
$$
|
| 70 |
+
q = round\left(\frac{x}{S} + Z\right)
|
| 71 |
+
$$
|
| 72 |
+
|
| 73 |
+
The int8 value, \\(q\\), can be dequantized back to approximate float32 with the formula below.
|
| 74 |
+
|
| 75 |
+
$$
|
| 76 |
+
x \approx S \cdot (q - Z)
|
| 77 |
+
$$
|
| 78 |
+
|
| 79 |
+
<div class="flex justify-center">
|
| 80 |
+
<img width="606" alt="dequant" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/dequant.png" />
|
| 81 |
+
</div>
|
| 82 |
+
|
| 83 |
+
During inference, computations like matrix multiplication are performed using the int8 values ( \\(q\\) ), and the result is dequantized back to float32 (often using a higher-precision accumulation type like int32 internally) before it is passed to the next layer.
|
| 84 |
+
|
| 85 |
+
### int4 and weight packing
|
| 86 |
+
|
| 87 |
+
<div class="flex justify-center">
|
| 88 |
+
<img width="606" alt="weight packing" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/weight_packing.png" />
|
| 89 |
+
</div>
|
| 90 |
+
|
| 91 |
+
int4 quantization further reduces the model size and memory usage (halving it compared to int8). The same affine or symmetric quantization principles apply, mapping the float32 range to the 16 possible values representable by int4 ( \\([-8, 7]\\) for signed int4).
|
| 92 |
+
|
| 93 |
+
A key aspect of int4 quantization is **weight packing**. Since most hardware can't natively handle 4-bit data types in memory, two int4 values are typically packed together into a single int8 byte for storage and transfer. For example, the first value might occupy the lower 4 bits and the second value the upper 4 bits of the byte (`packed_byte = (val1 & 0x0F) | (val2 << 4)`).
|
| 94 |
+
|
| 95 |
+
int4 is still beneficial even without native int4 compute because the primary benefit comes from reduced memory bandwidth. Loading packed int4 weights (stored as int8) from memory (RAM or VRAM) to the compute units is twice as fast as loading int8 weights. For large models, memory access is often a significant bottleneck. The speed up from faster data transfer can outweigh the computational overhead of unpacking and dequantizing on the fly, leading to overall faster inference, especially in memory-bound scenarios.
|
| 96 |
+
|
| 97 |
+
However, int4 quantization typically results in a larger accuracy drop compared to int8. Advanced quantization techniques like [GPTQ](./gptq) or [AWQ](./awq) are often necessary for good performance with int4.
|
| 98 |
+
|
| 99 |
+
### FP8 Quantization (A8W8)
|
| 100 |
+
|
| 101 |
+
<div class="flex justify-center">
|
| 102 |
+
<img width="606" alt="fp8" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/fp8.png" />
|
| 103 |
+
</div>
|
| 104 |
+
A newer datatype, 8-bit floating-point (FP8), offers another way to reduce precision while retaining more accuracy than int8 in certain scenarios. FP8 keeps the floating-point structure (sign, exponent, mantissa) but uses fewer bits.
|
| 105 |
+
|
| 106 |
+
There are two common FP8 variants.
|
| 107 |
+
|
| 108 |
+
- E4M3: 1 sign bit, 4 exponent bits, 3 mantissa bits. Offers higher precision (more mantissa bits) but a smaller dynamic range (fewer exponent bits).
|
| 109 |
+
- E5M2: 1 sign bit, 5 exponent bits, 2 mantissa bits. Offers a wider dynamic range but lower precision.
|
| 110 |
+
|
| 111 |
+
FP8 is used in the *A8W8* quantization scheme, which quantizes both activations (A) and weights (W) to 8-bit precision.
|
| 112 |
+
|
| 113 |
+
While int8 has broad support, efficient FP8 computation requires specific hardware capabilities found in newer GPUs like NVIDIA H100/H200/B100 and AMD Instinct MI300 series. Without native hardware acceleration, the benefits of FP8 might not be fully realized.
|
| 114 |
+
|
| 115 |
+
Transformers supports FP8 through specific backends like [FBGEMM](./fbgemm_fp8), [FineGrainedFP8](./finegrained_fp8), and [compressed-tensors](./compressed_tensors). These backends handle the underlying FP8 conversion and computation when the appropriate hardware and configurations are used.
|
| 116 |
+
|
| 117 |
+
## Granularity
|
| 118 |
+
|
| 119 |
+
Quantization parameters ( \\(S\\) and \\(Z\\)) can be calculated in one of two ways.
|
| 120 |
+
|
| 121 |
+
- Per-Tensor: One set of \\(S\\) and \\(Z\\) for the entire tensor. Simpler, but less accurate if data values vary greatly within the tensor.
|
| 122 |
+
- Per-Channel (or Per-Group/Block): Separate \\(S\\) and \\(Z\\) for each channel or group. More accurate and better performance at the cost of slightly more complexity and memory.
|
| 123 |
+
|
| 124 |
+
<div class="flex justify-center">
|
| 125 |
+
<img width="625" alt="Granularities" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Granularities.png" />
|
| 126 |
+
</div>
|
| 127 |
+
|
| 128 |
+
## Quantization techniques
|
| 129 |
+
|
| 130 |
+
There are two main types of quantization techniques.
|
| 131 |
+
|
| 132 |
+
- Post-Training Quantization (PTQ): Quantization is applied *after* the model is fully trained.
|
| 133 |
+
- Quantization-Aware Training (QAT): Quantization effects are simulated *during* training by inserting "fake quantization" ops that simulate the rounding errors of quantization. This lets the model adapt to quantization, and usually results in better accuracy, especially at lower bit-widths.
|
| 134 |
+
|
| 135 |
+
## Quantization in Transformers
|
| 136 |
+
|
| 137 |
+
Transformers integrates several quantization backends such as bitsandbytes, torchao, compressed-tensors, and more (refer to the quantization [overview](./overview) for more backends).
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
All backends are unified under the [`HfQuantizer`] API and associated [`QuantizationConfig`] classes. You can integrate your own custom quantization backends by implementing a custom [`HfQuantizer`] and [`QuantizationConfig`], as shown in the [Contribution](./contribute) guide.
|
| 141 |
+
|
| 142 |
+
The typical workflow for quantization in Transformers is to:
|
| 143 |
+
|
| 144 |
+
1. Choose a quantization method suitable for your hardware and use case (see the [Overview](./overview) or [Selecting a quantization method](./selecting) guide to help you).
|
| 145 |
+
2. Load a pre-quantized model from the Hugging Face Hub or load a float32/float16/bfloat16 model and apply a specific quantization method with [`QuantizationConfig`].
|
| 146 |
+
|
| 147 |
+
The example below demonstrates loading a 8B parameter model and quantizing it to 4-bits with bitsandbytes.
|
| 148 |
+
|
| 149 |
+
```python
|
| 150 |
+
import torch
|
| 151 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 152 |
+
|
| 153 |
+
model_id = "meta-llama/Llama-3.1-8B-Instruct"
|
| 154 |
+
|
| 155 |
+
quantization_config = BitsAndBytesConfig(
|
| 156 |
+
load_in_4bit=True,
|
| 157 |
+
bnb_4bit_compute_dtype=torch.bfloat16
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 161 |
+
model_id,
|
| 162 |
+
quantization_config=quantization_config,
|
| 163 |
+
torch_dtype=torch.bfloat16,
|
| 164 |
+
device_map="auto"
|
| 165 |
+
)
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
## Resources
|
| 170 |
+
|
| 171 |
+
To explore quantization and related performance optimization concepts more deeply, check out the following resources.
|
| 172 |
+
|
| 173 |
+
- [Quantization Fundamentals with Hugging Face](https://www.deeplearning.ai/short-courses/quantization-fundamentals-with-hugging-face/)
|
| 174 |
+
- [Quantization in Depth](https://www.deeplearning.ai/short-courses/quantization-in-depth)
|
| 175 |
+
- [Introduction to Quantization cooked in 🤗 with 💗🧑🍳](https://huggingface.co/blog/merve/quantization)
|
| 176 |
+
- [EfficientML.ai Lecture 5 - Quantization Part I](https://www.youtube.com/watch?v=RP23-dRVDWM)
|
| 177 |
+
- [Making Deep Learning Go Brrrr From First Principles](https://horace.io/brrr_intro.html)
|
| 178 |
+
- [Accelerating Generative AI with PyTorch Part 2: LLM Optimizations](https://pytorch.org/blog/accelerating-generative-ai-2/)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/contribute.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Contribute
|
| 18 |
+
|
| 19 |
+
Transformers supports many quantization methods such as QLoRA, GPTQ, LLM.int8, and AWQ. However, there are still many more quantization approaches that haven't been integrated yet. To make adding and using these quantization methods with Transformers easier, use the [`~quantizers.HfQuantizer`] class. [`~quantizers.HfQuantizer`] is designed to be an internal helper class for adding a quantization method instead of something applied to every PyTorch module.
|
| 20 |
+
|
| 21 |
+
This guide will show you how to integrate a new quantization method with [`~quantizers.HfQuantizer`].
|
| 22 |
+
|
| 23 |
+
## Requirements
|
| 24 |
+
|
| 25 |
+
Before integrating a new quantization method into Transformers, ensure the method meets the following requirements. Only quantization methods that can be run with PyTorch modules are supported.
|
| 26 |
+
|
| 27 |
+
- The quantization method is available through a Python package that is pip-installable (it is also fine if you can only install the package from source). Ideally, pre-compiled kernels are included in the pip package.
|
| 28 |
+
- The method can run on commonly-used hardware (CPU, GPU, etc.).
|
| 29 |
+
- The method is wrapped in a [nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html) ([`~bitsandbytes.nn.Linear8bitLt`], [`~bitsandbytes.nn.Linear4bit`]), and the quantized linear layer should have the following definition.
|
| 30 |
+
|
| 31 |
+
```py
|
| 32 |
+
class Linear4bit(nn.Module):
|
| 33 |
+
def __init__(self, ...):
|
| 34 |
+
...
|
| 35 |
+
|
| 36 |
+
def forward(self, x):
|
| 37 |
+
return my_4bit_kernel(x, self.weight, self.bias)
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
This way, Transformers models are easily quantized by replacing instances of [nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) with a target class.
|
| 41 |
+
|
| 42 |
+
- The quantization method should be serializable. You can save the quantized weights locally or push them to the Hub.
|
| 43 |
+
- Make sure the package containing the quantization kernels/primitive is stable (no frequent breaking changes).
|
| 44 |
+
|
| 45 |
+
Some quantization methods may require "pre-quantizing" the model through data calibration (AWQ). In this case, we prefer to only support inference in Transformers and let the third-party library maintained by the ML community deal handle the model quantization itself.
|
| 46 |
+
|
| 47 |
+
## Create new HFQuantizer class
|
| 48 |
+
|
| 49 |
+
1. Create a new quantization config class inside [src/transformers/utils/quantization_config.py](https://github.com/huggingface/transformers/blob/abbffc4525566a48a9733639797c812301218b83/src/transformers/utils/quantization_config.py). Add the new quantization config to the [_import_structure](https://github.com/huggingface/transformers/blob/abbffc4525566a48a9733639797c812301218b83/src/transformers/__init__.py#L1088) inside Transformers' [src/transformers/__init__.py](https://github.com/huggingface/transformers/blob/abbffc4525566a48a9733639797c812301218b83/src/transformers/__init__.py) file.
|
| 50 |
+
|
| 51 |
+
2. Create a new file inside [src/transformers/quantizers/](https://github.com/huggingface/transformers/tree/abbffc4525566a48a9733639797c812301218b83/src/transformers/quantizers) named `quantizer_your_method.py`, and make it inherit from [`~quantizers.HfQuantizer]. Make sure to add the new quantizer and quantization config in the quantization auto-mapping in [src/transformers/quantizers/auto.py](https://github.com/huggingface/transformers/blob/abbffc4525566a48a9733639797c812301218b83/src/transformers/quantizers/auto.py).
|
| 52 |
+
|
| 53 |
+
3. Define the following class attributes and property methods for your quantization method.
|
| 54 |
+
|
| 55 |
+
- `requires_calibration`: Whether the quantization method requires a data calibration process. If set to `True`, you can only support inference (with quantized weights) and not inference and quantization.
|
| 56 |
+
- `required_packages`: A list of strings of the required packages to use the quantized weights. You might need to define some new utility methods such as `is_auto_awq_available` in [transformers/src/utils/import_utils.py](https://github.com/huggingface/transformers/blob/abbffc4525566a48a9733639797c812301218b83/src/transformers/utils/import_utils.py).
|
| 57 |
+
- `requires_parameters_quantization`: Only required if your quantization method requires extra attention to the underlying [nn.Parameter](https://pytorch.org/docs/stable/generated/torch.nn.parameter.Parameter.html) object. For example, bitsandbytes uses [`~bitsandbytes.nn.Params4bit`] and [`~bitsandbytes.nn.Int8Params`], which requires some extra attention when quantizing the model. Most of the recent quantization method packs int2 and int4 weights inside [torch.uint8](https://pytorch.org/docs/stable/tensors.html) weights, so this flag should not be really required (set to `False` by default).
|
| 58 |
+
- `is_serializable`: A property method to determine whether the method is serializable or not.
|
| 59 |
+
- `is_trainable`: A property method to determine whether you can fine-tune models on top of the quantization method (with or without PEFT approaches).
|
| 60 |
+
|
| 61 |
+
4. Write the `validate_environment` and `update_torch_dtype` methods. These methods are called before creating the quantized model to ensure users use the right configuration. Refer to other quantizers for an example of it is implemented.
|
| 62 |
+
|
| 63 |
+
5. Write the `_process_model_before_weight_loading` method. In Transformers, the quantized models are initialized first on the `"meta"` device before loading the weights. This means the `_process_model_before_weight_loading` method takes care of manipulating the model skeleton to replace some modules ([nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html)) with the target modules (quantization modules).
|
| 64 |
+
|
| 65 |
+
You can define module replacement logic or any other utility method by creating a new file in [transformers/src/integrations/](https://github.com/huggingface/transformers/tree/abbffc4525566a48a9733639797c812301218b83/src/transformers/integrations) and exposing the relevant methods in that folder's `__init__.py` file. The best starting point would be to have a look at another quantization method such as [quantizer_awq.py](https://github.com/huggingface/transformers/blob/abbffc4525566a48a9733639797c812301218b83/src/transformers/quantizers/quantizer_awq.py).
|
| 66 |
+
|
| 67 |
+
6. Write the `_process_model_after_weight_loading` method. This method enables implementing additional features that require manipulating the model after loading the weights.
|
| 68 |
+
|
| 69 |
+
7. Document everything! Make sure your quantization method is documented by adding a new file under `docs/source/en/quantization`.
|
| 70 |
+
|
| 71 |
+
8. You should add tests by adding the package in our nightly Dockerfile inside `docker/transformers-quantization-latest-gpu` and then adding a new test file in `tests/quantization/xxx`. Feel free to check out existing quantization methods to see how it is implemented.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/eetq.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# EETQ
|
| 18 |
+
|
| 19 |
+
The [Easy & Efficient Quantization for Transformers (EETQ)](https://github.com/NetEase-FuXi/EETQ) library supports int8 weight-only per-channel quantization for NVIDIA GPUs. It uses high-performance GEMM and GEMV kernels from [FasterTransformer](https://github.com/NVIDIA/FasterTransformer) and [TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM). The attention layer is optimized with [FlashAttention2](https://github.com/Dao-AILab/flash-attention). No calibration dataset is required, and the model doesn't need to be pre-quantized. Accuracy degradation is negligible owing to the per-channel quantization.
|
| 20 |
+
|
| 21 |
+
EETQ further supports fine-tuning with [PEFT](https://huggingface.co/docs/peft).
|
| 22 |
+
|
| 23 |
+
Install EETQ from the [release page](https://github.com/NetEase-FuXi/EETQ/releases) or [source code](https://github.com/NetEase-FuXi/EETQ). CUDA 11.4+ is required for EETQ.
|
| 24 |
+
|
| 25 |
+
<hfoptions id="install">
|
| 26 |
+
<hfoption id="release page">
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
pip install --no-cache-dir https://github.com/NetEase-FuXi/EETQ/releases/download/v1.0.0/EETQ-1.0.0+cu121+torch2.1.2-cp310-cp310-linux_x86_64.whl
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
</hfoption>
|
| 33 |
+
<hfoption id="source code">
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
git clone https://github.com/NetEase-FuXi/EETQ.git
|
| 37 |
+
cd EETQ/
|
| 38 |
+
git submodule update --init --recursive
|
| 39 |
+
pip install .
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
</hfoption>
|
| 43 |
+
</hfoptions>
|
| 44 |
+
|
| 45 |
+
Quantize a model on-the-fly by defining the quantization data type in [`EetqConfig`].
|
| 46 |
+
|
| 47 |
+
```py
|
| 48 |
+
from transformers import AutoModelForCausalLM, EetqConfig
|
| 49 |
+
|
| 50 |
+
quantization_config = EetqConfig("int8")
|
| 51 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 52 |
+
"meta-llama/Llama-3.1-8B",
|
| 53 |
+
torch_dtype="auto",
|
| 54 |
+
device_map="auto",
|
| 55 |
+
quantization_config=quantization_config
|
| 56 |
+
)
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Save the quantized model with [`~PreTrainedModel.save_pretrained`] so it can be reused again with [`~PreTrainedModel.from_pretrained`].
|
| 60 |
+
|
| 61 |
+
```py
|
| 62 |
+
quant_path = "/path/to/save/quantized/model"
|
| 63 |
+
model.save_pretrained(quant_path)
|
| 64 |
+
model = AutoModelForCausalLM.from_pretrained(quant_path, device_map="auto")
|
| 65 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/fbgemm_fp8.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# FBGEMM
|
| 18 |
+
|
| 19 |
+
[FBGEMM (Facebook GEneral Matrix Multiplication)](https://github.com/pytorch/FBGEMM) is a low-precision matrix multiplication library for small batch sizes and support for accuracy-loss minimizing techniques such as row-wise quantization and outlier-aware quantization. With FBGEMM, quantize a models weights to 8-bits/channel and the activations to 8-bits/token (also known as fp8 or w8a8).
|
| 20 |
+
|
| 21 |
+
> [!TIP]
|
| 22 |
+
> You need a GPU with [compute capability 9+](https://developer.nvidia.com/cuda-gpus#collapseOne) like a H100.
|
| 23 |
+
|
| 24 |
+
Install the FBGEMM_GPU package with the command below to ensure you have the latest version.
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
pip install --upgrade accelerate fbgemm-gpu torch
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
If you're having installation issues, try installing the [nightly release](https://pytorch.org/FBGEMM/fbgemm_gpu-development/InstallationInstructions.html#fbgemm-gpu-install-libraries:~:text=found%20here.-,Install%20the%20FBGEMM_GPU%20Package,-Install%20through%20PyTorch).
|
| 31 |
+
|
| 32 |
+
Create a [`FbgemmFp8Config`] and pass it to [`~PreTrainedModel.from_pretrained`] to quantize a model to fp8.
|
| 33 |
+
|
| 34 |
+
```py
|
| 35 |
+
from transformers import FbgemmFp8Config, AutoModelForCausalLM
|
| 36 |
+
|
| 37 |
+
quantization_config = FbgemmFp8Config()
|
| 38 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 39 |
+
"meta-llama/Meta-Llama-3-8B",
|
| 40 |
+
torch_dtype="auto",
|
| 41 |
+
device_map="auto",
|
| 42 |
+
quantization_config=quantization_config
|
| 43 |
+
)
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
[`~PreTrainedModel.save_pretrained`] and [`~PreTrainedModel.from_pretrained`] enable saving and loading a quantized model.
|
| 47 |
+
|
| 48 |
+
```py
|
| 49 |
+
quant_path = "/path/to/save/quantized/model"
|
| 50 |
+
model.save_pretrained(quant_path)
|
| 51 |
+
model = AutoModelForCausalLM.from_pretrained(quant_path, device_map="auto")
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
## Resources
|
| 55 |
+
|
| 56 |
+
Read the [Open-sourcing FBGEMM for state-of-the-art server-side inference](https://engineering.fb.com/2018/11/07/ml-applications/fbgemm/) blog post for more details on FBGEMM.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/finegrained_fp8.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 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 |
+
|
| 17 |
+
# Fine-grained FP8
|
| 18 |
+
|
| 19 |
+
Fine-grained FP8 quantization quantizes the weights and activations to fp8.
|
| 20 |
+
|
| 21 |
+
- The weights are quantized to 8-bits for each 2D block (`weight_block_size=(128, 128)`).
|
| 22 |
+
- The activations are quantized to 8-bits for each group per token. The group value matches the weights in the input channel (128 by default).
|
| 23 |
+
|
| 24 |
+
FP8 quantization enables support for [DeepSeek-V3](https://hf.co/papers/2412.19437) and DeepSeek-R1.
|
| 25 |
+
|
| 26 |
+
<div class="flex justify-center">
|
| 27 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/b7b3b34bf826a6423ea82ffc57ecac80c46c3c76/transformers/quantization/quantization_deepseek.png">
|
| 28 |
+
</div>
|
| 29 |
+
|
| 30 |
+
> [!TIP]
|
| 31 |
+
> You need a GPU with Compute Capability>=9 (H100), and install a PyTorch version compatible with the CUDA version of your GPU.
|
| 32 |
+
|
| 33 |
+
Install Accelerate and upgrade to the latest version of PyTorch.
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
pip install --upgrade accelerate torch
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Create a [`FineGrainedFP8Config`] class and pass it to [`~PreTrainedModel.from_pretrained`] to quantize it. The weights are loaded in full precision (`torch.float32`) by default regardless of the actual data type the weights are stored in. Set `torch_dtype="auto"` to load the weights in the data type defined in a models `config.json` file to automatically load the most memory-optiomal data type.
|
| 40 |
+
|
| 41 |
+
```py
|
| 42 |
+
from transformers import FineGrainedFP8Config, AutoModelForCausalLM, AutoTokenizer
|
| 43 |
+
|
| 44 |
+
model_name = "meta-llama/Meta-Llama-3-8B"
|
| 45 |
+
quantization_config = FineGrainedFP8Config()
|
| 46 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto", quantization_config=quantization_config)
|
| 47 |
+
|
| 48 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 49 |
+
input_text = "What are we having for dinner?"
|
| 50 |
+
input_ids = tokenizer(input_text, return_tensors="pt").to(quantized_model.device.type)
|
| 51 |
+
|
| 52 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10)
|
| 53 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
Use [`~PreTrainedModel.save_pretrained`] to save the quantized model and reload it with [`~PreTrainedModel.from_pretrained`].
|
| 57 |
+
|
| 58 |
+
```py
|
| 59 |
+
quant_path = "/path/to/save/quantized/model"
|
| 60 |
+
model.save_pretrained(quant_path)
|
| 61 |
+
model = AutoModelForCausalLM.from_pretrained(quant_path, device_map="auto")
|
| 62 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/fp_quant.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 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 |
+
|
| 17 |
+
# FP-Quant
|
| 18 |
+
|
| 19 |
+
[FP-Quant](https://github.com/IST-DASLab/FP-Quant) is a family of quantization algorithms tailored for the Blackwell generation of Nvidia GPUs. The goal is to allow for efficient post-training quantization (PTQ) and quantization-aware training (QAT) of LLMs in the [MXFP4 and NVFP4 data-types](https://www.opencompute.org/documents/ocp-microscaling-formats-mx-v1-0-spec-final-pdf).
|
| 20 |
+
|
| 21 |
+
Currently, only PTQ with MXFP4 is supported. Models can either be quantized on the fly with `quantization_config=FPQuantConfig()`:
|
| 22 |
+
|
| 23 |
+
```python
|
| 24 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, FPQuantConfig
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 28 |
+
"qwen/Qwen3-8B",
|
| 29 |
+
quantization_config=FPQuantConfig(),
|
| 30 |
+
device_map="auto",
|
| 31 |
+
torch_dtype=torch.bfloat16,
|
| 32 |
+
)
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
or pre-processed with GPTQ for better quality (see [FP Format Quantization Harness](https://github.com/IST-DASLab/FP-Quant)).
|
| 36 |
+
|
| 37 |
+
A **Blackwell-generation GPU is required** to run the kernels. Runtime support for FP-Quant is implemented through the [QuTLASS](https://github.com/IST-DASLab/qutlass) library and a lightweight PyTorch interface lib [`fp_quant`](https://github.com/IST-DASLab/FP-Quant/tree/master/inference_lib). We recommend installing the former **from source** and the latter with `pip install fp_quant`.
|
| 38 |
+
|
| 39 |
+
Users **without a Blackwell-generation GPU** , can use the method with `quantization_config=FPQuantConfig(pseudoquant=True)` without having to install [QuTLASS](https://github.com/IST-DASLab/qutlass). This would provide no speedups but would fully emulate the effect of quantization.
|
| 40 |
+
|
| 41 |
+
> [!TIP]
|
| 42 |
+
> Find models pre-quantized with FP-Quant in the official ISTA-DASLab [collection](https://huggingface.co/collections/ISTA-DASLab/fp-quant-6877c186103a21d3a02568ee).
|
| 43 |
+
|
| 44 |
+
## torch.compile
|
| 45 |
+
|
| 46 |
+
FP-Quant is fully compatible with [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html).
|
| 47 |
+
|
| 48 |
+
```python
|
| 49 |
+
import torch
|
| 50 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, FPQuantConfig
|
| 51 |
+
|
| 52 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 53 |
+
"qwen/Qwen3-8B",
|
| 54 |
+
quantization_config=FPQuantConfig(),
|
| 55 |
+
device_map="auto",
|
| 56 |
+
torch_dtype=torch.bfloat16,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
model.forward = torch.compile(model.forward, mode="max-autotune", fullgraph=True)
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
## Speedups
|
| 63 |
+
|
| 64 |
+
FP-Quant currently performs best for very large batch size processing.
|
| 65 |
+
|
| 66 |
+
See [QuTLASS README](https://github.com/IST-DASLab/qutlass/blob/main/README.md) for speedups.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/gptq.md
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# GPTQ
|
| 18 |
+
|
| 19 |
+
The [GPTQModel](https://github.com/ModelCloud/GPTQModel) and [AutoGPTQ](https://github.com/PanQiWei/AutoGPTQ) implements the GPTQ algorithm, a post-training quantization technique where each row of the weight matrix is quantized independently to find a version of the weights that minimizes the error. These weights are quantized to int4, but they're restored to fp16 on the fly during inference. This can save memory usage by 4x because the int4 weights are dequantized in a fused kernel rather than a GPU's global memory. Inference is also faster because a lower bitwidth takes less time to communicate.
|
| 20 |
+
|
| 21 |
+
> [!WARNING]
|
| 22 |
+
> AutoGPTQ is likely to be deprecated in the future due to lack of continued support for new models and features. See the [GPTQModel](#gptqmodel) section for more details.
|
| 23 |
+
|
| 24 |
+
Install Accelerate, Transformers and Optimum first.
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
pip install --upgrade accelerate optimum transformers
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Then run the command below to install a GPTQ library.
|
| 31 |
+
|
| 32 |
+
<hfoptions id="install">
|
| 33 |
+
<hfoption id="GPTQmodel">
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
pip install gptqmodel --no-build-isolation
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
</hfoption>
|
| 40 |
+
<hfoption id="AutoGPTQ">
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
pip install auto-gptq --no-build-isolation
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
</hfoption>
|
| 47 |
+
</hfoptions>
|
| 48 |
+
|
| 49 |
+
Create a [`GPTQConfig`] class and set the number of bits to quantize to, a dataset to calbrate the weights for quantization, and a tokenizer to prepare the dataset.
|
| 50 |
+
|
| 51 |
+
```py
|
| 52 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, GPTQConfig
|
| 53 |
+
|
| 54 |
+
tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m")
|
| 55 |
+
gptq_config = GPTQConfig(bits=4, dataset="c4", tokenizer=tokenizer)
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
You can pass your own dataset as a list of strings, but it is highly recommended to use the same dataset from the GPTQ paper.
|
| 59 |
+
|
| 60 |
+
```py
|
| 61 |
+
dataset = ["auto-gptq is an easy-to-use model quantization library with user-friendly apis, based on GPTQ algorithm."]
|
| 62 |
+
gptq_config = GPTQConfig(bits=4, dataset=dataset, tokenizer=tokenizer)
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
Load a model to quantize and pass [`GPTQConfig`] to [`~AutoModelForCausalLM.from_pretrained`]. Set `device_map="auto"` to automatically offload the model to a CPU to help fit the model in memory, and allow the model modules to be moved between the CPU and GPU for quantization.
|
| 66 |
+
|
| 67 |
+
```py
|
| 68 |
+
quantized_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m", device_map="auto", quantization_config=gptq_config)
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
If you're running out of memory because a dataset is too large (disk offloading is not supported), try passing the `max_memory` parameter to allocate the amount of memory to use on your device (GPU and CPU).
|
| 72 |
+
|
| 73 |
+
```py
|
| 74 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 75 |
+
"facebook/opt-125m",
|
| 76 |
+
device_map="auto",
|
| 77 |
+
max_memory={0: "30GiB", 1: "46GiB", "cpu": "30GiB"},
|
| 78 |
+
quantization_config=gptq_config
|
| 79 |
+
)
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
> [!WARNING]
|
| 83 |
+
> Depending on your hardware, it can take some time to quantize a model from scratch. It can take ~5 minutes to quantize the [facebook/opt-350m](https://huggingface.co/facebook/opt-350m) model on a free-tier Google Colab GPU, but it'll take ~4 hours to quantize a 175B parameter model on a NVIDIA A100. Before you quantize a model, it is a good idea to check the Hub if a GPTQ-quantized version of the model already exists.
|
| 84 |
+
|
| 85 |
+
Once a model is quantized, you can use [`~PreTrainedModel.push_to_hub`] to push the model and tokenizer to the Hub where it can be easily shared and accessed. This saves the [`GPTQConfig`].
|
| 86 |
+
|
| 87 |
+
```py
|
| 88 |
+
quantized_model.push_to_hub("opt-125m-gptq")
|
| 89 |
+
tokenizer.push_to_hub("opt-125m-gptq")
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
[`~PreTrainedModel.save_pretrained`] saves a quantized model locally. If the model was quantized with the `device_map` parameter, make sure to move the entire model to a GPU or CPU before saving it. The example below saves the model on a CPU.
|
| 93 |
+
|
| 94 |
+
```py
|
| 95 |
+
quantized_model.save_pretrained("opt-125m-gptq")
|
| 96 |
+
tokenizer.save_pretrained("opt-125m-gptq")
|
| 97 |
+
|
| 98 |
+
# if quantized with device_map set
|
| 99 |
+
quantized_model.to("cpu")
|
| 100 |
+
quantized_model.save_pretrained("opt-125m-gptq")
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
Reload a quantized model with [`~PreTrainedModel.from_pretrained`], and set `device_map="auto"` to automatically distribute the model on all available GPUs to load the model faster without using more memory than needed.
|
| 104 |
+
|
| 105 |
+
```py
|
| 106 |
+
from transformers import AutoModelForCausalLM
|
| 107 |
+
|
| 108 |
+
model = AutoModelForCausalLM.from_pretrained("{your_username}/opt-125m-gptq", device_map="auto")
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
## Marlin
|
| 112 |
+
|
| 113 |
+
[Marlin](https://github.com/IST-DASLab/marlin) is a 4-bit only CUDA GPTQ kernel, highly optimized for the NVIDIA A100 GPU (Ampere) architecture. Loading, dequantization, and execution of post-dequantized weights are highly parallelized, offering a substantial inference improvement versus the original CUDA GPTQ kernel. Marlin is only available for quantized inference and does not support model quantization.
|
| 114 |
+
|
| 115 |
+
Marlin inference can be activated with the `backend` parameter in [`GPTQConfig`].
|
| 116 |
+
|
| 117 |
+
```py
|
| 118 |
+
|
| 119 |
+
from transformers import AutoModelForCausalLM, GPTQConfig
|
| 120 |
+
|
| 121 |
+
model = AutoModelForCausalLM.from_pretrained("{your_username}/opt-125m-gptq", device_map="auto", quantization_config=GPTQConfig(bits=4, backend="marlin"))
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
## ExLlama
|
| 125 |
+
|
| 126 |
+
> [!WARNING]
|
| 127 |
+
> Only 4-bit models are supported, and we recommend deactivating the ExLlama kernels if you're finetuning a quantized model with PEFT.
|
| 128 |
+
|
| 129 |
+
[ExLlama](https://github.com/turboderp/exllama) is a Python/C++/CUDA implementation of the [Llama](model_doc/llama) model that is designed for faster inference with 4-bit GPTQ weights (check out these [benchmarks](https://github.com/huggingface/optimum/tree/main/tests/benchmark#gptq-benchmark)). The ExLlama kernel is activated by default when you create a [`GPTQConfig`] object.
|
| 130 |
+
|
| 131 |
+
To boost inference speed even further, use the [ExLlamaV2](https://github.com/turboderp/exllamav2) kernels by configuring the `exllama_config` parameter in [`GPTQConfig`].
|
| 132 |
+
|
| 133 |
+
```py
|
| 134 |
+
import torch
|
| 135 |
+
from transformers import AutoModelForCausalLM, GPTQConfig
|
| 136 |
+
|
| 137 |
+
gptq_config = GPTQConfig(bits=4, exllama_config={"version":2})
|
| 138 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 139 |
+
"{your_username}/opt-125m-gptq",
|
| 140 |
+
device_map="auto",
|
| 141 |
+
quantization_config=gptq_config
|
| 142 |
+
)
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
The ExLlama kernels are only supported when the entire model is on the GPU. If you're doing inference on a CPU with AutoGPTQ 0.4.2+, disable the ExLlama kernel in [`GPTQConfig`]. This overwrites the attributes related to the ExLlama kernels in the quantization config of the `config.json` file.
|
| 146 |
+
|
| 147 |
+
```py
|
| 148 |
+
import torch
|
| 149 |
+
from transformers import AutoModelForCausalLM, GPTQConfig
|
| 150 |
+
|
| 151 |
+
gptq_config = GPTQConfig(bits=4, use_exllama=False)
|
| 152 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 153 |
+
"{your_username}/opt-125m-gptq",
|
| 154 |
+
device_map="cpu",
|
| 155 |
+
quantization_config=gptq_config
|
| 156 |
+
)
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
## GPTQModel
|
| 160 |
+
|
| 161 |
+
It is recommended to use GPTQModel, originally a maintained fork of AutoGPTQ, because it has since diverged from AutoGTPQ with some significant features. GPTQModel has faster quantization, lower memory usage, and more accurate default quantization.
|
| 162 |
+
|
| 163 |
+
GPTQModel provides asymmetric quantization which can potentially lower quantization errors compared to symmetric quantization. It is not backward compatible with AutoGPTQ, and not all kernels (Marlin) support asymmetric quantization.
|
| 164 |
+
|
| 165 |
+
GPTQModel also has broader support for the latest LLM models, multimodal models (Qwen2-VL and Ovis1.6-VL), platforms (Linux, macOS, Windows 11), and hardware (AMD ROCm, Apple Silicon, Intel/AMD CPUs, and Intel Datacenter Max/Arc GPUs, etc.).
|
| 166 |
+
|
| 167 |
+
The Marlin kernels are also updated for A100 GPUs and other kernels are updated to include auto-padding for legacy models and models with non-uniform in/out-features.
|
| 168 |
+
|
| 169 |
+
## Resources
|
| 170 |
+
|
| 171 |
+
Run the GPTQ quantization with PEFT [notebook](https://colab.research.google.com/drive/1_TIrmuKOFhuRRiTWN94iLKUFu6ZX4ceb?usp=sharing) for a hands-on experience, and read [Making LLMs lighter with AutoGPTQ and transformers](https://huggingface.co/blog/gptq-integration) to learn more about the AutoGPTQ integration.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/higgs.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# HIGGS
|
| 18 |
+
|
| 19 |
+
[HIGGS](https://huggingface.co/papers/2411.17525) is a zero-shot quantization algorithm that combines Hadamard preprocessing with MSE-Optimal quantization grids to achieve lower quantization error and state-of-the-art performance.
|
| 20 |
+
|
| 21 |
+
Runtime support for HIGGS is implemented through the [FLUTE](https://github.com/HanGuo97/flute) library. Only the 70B and 405B variants of Llama 3 and Llama 3.0, and the 8B and 27B variants of Gemma 2 are currently supported. HIGGS also doesn't support quantized training and backward passes in general at the moment.
|
| 22 |
+
|
| 23 |
+
Run the command below to install FLUTE.
|
| 24 |
+
|
| 25 |
+
<hfoptions id="install">
|
| 26 |
+
<hfoption id="CUDA 12.1">
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
pip install flute-kernel
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
</hfoption>
|
| 33 |
+
<hfoption id="CUDA 11.8">
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
pip install flute-kernel -i https://flute-ai.github.io/whl/cu12.4
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
</hfoption>
|
| 40 |
+
</hfoptions>
|
| 41 |
+
|
| 42 |
+
Create a [`HiggsConfig`] with the number of bits to quantize a model to.
|
| 43 |
+
|
| 44 |
+
```python
|
| 45 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, HiggsConfig
|
| 46 |
+
|
| 47 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 48 |
+
"google/gemma-2-9b-it",
|
| 49 |
+
quantization_config=HiggsConfig(bits=4),
|
| 50 |
+
device_map="auto",
|
| 51 |
+
)
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
> [!TIP]
|
| 55 |
+
> Find models pre-quantized with HIGGS in the official ISTA-DASLab [collection](https://huggingface.co/collections/ISTA-DASLab/higgs-675308e432fd56b7f6dab94e).
|
| 56 |
+
|
| 57 |
+
## torch.compile
|
| 58 |
+
|
| 59 |
+
HIGGS is fully compatible with [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html).
|
| 60 |
+
|
| 61 |
+
```python
|
| 62 |
+
import torch
|
| 63 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, HiggsConfig
|
| 64 |
+
|
| 65 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 66 |
+
"google/gemma-2-9b-it",
|
| 67 |
+
quantization_config=HiggsConfig(bits=4),
|
| 68 |
+
device_map="auto",
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
model = torch.compile(model)
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Refer to the table below for a benchmark of forward passes/sec for Llama-3.1-8B-Instruct on a RTX4090.
|
| 75 |
+
|
| 76 |
+
| Batch Size | BF16 (with `torch.compile`) | HIGGS 4bit (without `torch.compile`) | HIGGS 4bit (with `torch.compile`) |
|
| 77 |
+
|------------|-----------------------------|----------------------------------|-----------------------------------|
|
| 78 |
+
| 1 | 59 | 41 | 124 |
|
| 79 |
+
| 4 | 57 | 42 | 123 |
|
| 80 |
+
| 16 | 56 | 41 | 120 |
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/hqq.md
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# HQQ
|
| 18 |
+
|
| 19 |
+
[Half-Quadratic Quantization (HQQ)](https://github.com/mobiusml/hqq/) supports fast on-the-fly quantization for 8, 4, 3, 2, and even 1-bits. It doesn't require calibration data, and it is compatible with any model modality (LLMs, vision, etc.).
|
| 20 |
+
|
| 21 |
+
HQQ further supports fine-tuning with [PEFT](https://huggingface.co/docs/peft) and is fully compatible with [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) for even faster inference and training.
|
| 22 |
+
|
| 23 |
+
Install HQQ with the following command to get the latest version and to build its corresponding CUDA kernels if you are using a cuda device. It also support Intel XPU with pure pytorch implementation.
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
pip install hqq
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
You can choose to either replace all the linear layers in a model with the same quantization config or dedicate a specific quantization config for specific linear layers.
|
| 30 |
+
|
| 31 |
+
<hfoptions id="hqq">
|
| 32 |
+
<hfoption id="replace all layers">
|
| 33 |
+
|
| 34 |
+
Quantize a model by creating a [`HqqConfig`] and specifying the `nbits` and `group_size` to replace for all the linear layers ([torch.nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html)) of the model.
|
| 35 |
+
|
| 36 |
+
``` py
|
| 37 |
+
import torch
|
| 38 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, HqqConfig
|
| 39 |
+
|
| 40 |
+
quant_config = HqqConfig(nbits=8, group_size=64)
|
| 41 |
+
model = transformers.AutoModelForCausalLM.from_pretrained(
|
| 42 |
+
"meta-llama/Llama-3.1-8B",
|
| 43 |
+
torch_dtype=torch.float16,
|
| 44 |
+
device_map="auto",
|
| 45 |
+
quantization_config=quant_config
|
| 46 |
+
)
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
</hfoption>
|
| 50 |
+
<hfoption id="specific layers only">
|
| 51 |
+
|
| 52 |
+
Quantize a model by creating a dictionary specifying the `nbits` and `group_size` for the linear layers to quantize. Pass them to [`HqqConfig`] and set which layers to quantize with the config. This approach is especially useful for quantizing mixture-of-experts (MoEs) because they are less affected ly lower quantization settings.
|
| 53 |
+
|
| 54 |
+
``` py
|
| 55 |
+
q4_config = {'nbits':4, 'group_size':64}
|
| 56 |
+
q3_config = {'nbits':3, 'group_size':32}
|
| 57 |
+
quant_config = HqqConfig(dynamic_config={
|
| 58 |
+
'self_attn.q_proj':q4_config,
|
| 59 |
+
'self_attn.k_proj':q4_config,
|
| 60 |
+
'self_attn.v_proj':q4_config,
|
| 61 |
+
'self_attn.o_proj':q4_config,
|
| 62 |
+
|
| 63 |
+
'mlp.gate_proj':q3_config,
|
| 64 |
+
'mlp.up_proj' :q3_config,
|
| 65 |
+
'mlp.down_proj':q3_config,
|
| 66 |
+
})
|
| 67 |
+
|
| 68 |
+
model = transformers.AutoModelForCausalLM.from_pretrained(
|
| 69 |
+
"meta-llama/Llama-3.1-8B",
|
| 70 |
+
torch_dtype=torch.float16,
|
| 71 |
+
device_map="auto",
|
| 72 |
+
quantization_config=quant_config
|
| 73 |
+
)
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
</hfoption>
|
| 77 |
+
</hfoptions>
|
| 78 |
+
|
| 79 |
+
## Backends
|
| 80 |
+
|
| 81 |
+
HQQ supports various backends, including pure PyTorch and custom dequantization CUDA kernels. These backends are suitable for older GPUs and PEFT/QLoRA training.
|
| 82 |
+
|
| 83 |
+
```py
|
| 84 |
+
from hqq.core.quantize import *
|
| 85 |
+
|
| 86 |
+
HQQLinear.set_backend(HQQBackend.PYTORCH)
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
For faster inference, HQQ supports 4-bit fused kernels (torchao and Marlin) after a model is quantized. These can reach up to 200 tokens/sec on a single 4090. The example below demonstrates enabling the torchao_int4 backend.
|
| 90 |
+
|
| 91 |
+
```py
|
| 92 |
+
from hqq.utils.patching import prepare_for_inference
|
| 93 |
+
|
| 94 |
+
prepare_for_inference("model", backend="torchao_int4")
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
Refer to the [Backend](https://github.com/mobiusml/hqq/#backend) guide for more details.
|
| 98 |
+
|
| 99 |
+
## Resources
|
| 100 |
+
|
| 101 |
+
Read the [Half-Quadratic Quantization of Large Machine Learning Models](https://mobiusml.github.io/hqq_blog/) blog post for more details about HQQ.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/optimum.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Optimum
|
| 18 |
+
|
| 19 |
+
[Optimum](https://huggingface.co/docs/optimum/index) is an optimization library that supports quantization for Intel, Furiousa, ONNX Runtime, GPTQ, and lower-level PyTorch quantization functions. It is designed to enhance performance for specific hardware - Intel CPUs/HPUs, AMD GPUs, Furiousa NPUs, etc. - and model accelerators like ONNX Runtime.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/overview.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Overview
|
| 18 |
+
|
| 19 |
+
Quantization lowers the memory requirements of loading and using a model by storing the weights in a lower precision while trying to preserve as much accuracy as possible. Weights are typically stored in full-precision (fp32) floating point representations, but half-precision (fp16 or bf16) are increasingly popular data types given the large size of models today. Some quantization methods can reduce the precision even further to integer representations, like int8 or int4.
|
| 20 |
+
|
| 21 |
+
Transformers supports many quantization methods, each with their pros and cons, so you can pick the best one for your specific use case. Some methods require calibration for greater accuracy and extreme compression (1-2 bits), while other methods work out of the box with on-the-fly quantization.
|
| 22 |
+
|
| 23 |
+
Use the Space below to help you pick a quantization method depending on your hardware and number of bits to quantize to.
|
| 24 |
+
|
| 25 |
+
| Quantization Method | On the fly quantization | CPU | CUDA GPU | ROCm GPU | Metal (Apple Silicon) | Intel GPU | Torch compile() | Bits | PEFT Fine Tuning | Serializable with 🤗Transformers | 🤗Transformers Support | Link to library |
|
| 26 |
+
|-------------------------------------------|----------------------|-----------------|----------|-----------|------------------------------------|-----------------|-----------------|--------------|------------------|-----------------------------|-------------------------|---------------------------------------------|
|
| 27 |
+
| [AQLM](./aqlm) | 🔴 | 🟢 | 🟢 | 🔴 | 🔴 | 🔴 | 🟢 | 1/2 | 🟢 | 🟢 | 🟢 | https://github.com/Vahe1994/AQLM |
|
| 28 |
+
| [AutoRound](./auto_round) | 🔴 | 🟢 | 🟢 | 🔴 | 🔴 | 🟢 | 🔴 | 2/3/4/8 | 🔴 | 🟢 | 🟢 | https://github.com/intel/auto-round |
|
| 29 |
+
| [AWQ](./awq) | 🔴 | 🟢 | 🟢 | 🟢 | 🔴 | 🟢 | ? | 4 | 🟢 | 🟢 | 🟢 | https://github.com/casper-hansen/AutoAWQ |
|
| 30 |
+
| [bitsandbytes](./bitsandbytes) | 🟢 | 🟡 | 🟢 | 🟡 | 🔴 | 🟡 | 🟢 | 4/8 | 🟢 | 🟢 | 🟢 | https://github.com/bitsandbytes-foundation/bitsandbytes |
|
| 31 |
+
| [compressed-tensors](./compressed_tensors) | 🔴 | 🟢 | 🟢 | 🟢 | 🔴 | 🔴 | 🔴 | 1/8 | 🟢 | 🟢 | 🟢 | https://github.com/neuralmagic/compressed-tensors |
|
| 32 |
+
| [EETQ](./eetq) | 🟢 | 🔴 | 🟢 | 🔴 | 🔴 | 🔴 | ? | 8 | 🟢 | 🟢 | 🟢 | https://github.com/NetEase-FuXi/EETQ |
|
| 33 |
+
| [FP-Quant](./fp_quant) | 🟢 | 🔴 | 🟢 | 🔴 | 🔴 | 🔴 | 🟢 | 4 | 🔴 | 🟢 | 🟢 | https://github.com/IST-DASLab/FP-Quant |
|
| 34 |
+
| [GGUF / GGML (llama.cpp)](../gguf) | 🟢 | 🟢 | 🟢 | 🔴 | 🟢 | 🔴 | 🔴 | 1/8 | 🔴 | [See Notes](../gguf) | [See Notes](../gguf) | https://github.com/ggerganov/llama.cpp |
|
| 35 |
+
| [GPTQModel](./gptq) | 🔴 | 🟢 | 🟢 | 🟢 | 🟢 | 🟢 | 🔴 | 2/3/4/8 | 🟢 | 🟢 | 🟢 | https://github.com/ModelCloud/GPTQModel |
|
| 36 |
+
| [AutoGPTQ](./gptq) | 🔴 | 🔴 | 🟢 | 🟢 | 🔴 | 🔴 | 🔴 | 2/3/4/8 | 🟢 | 🟢 | 🟢 | https://github.com/AutoGPTQ/AutoGPTQ |
|
| 37 |
+
| [HIGGS](./higgs) | 🟢 | 🔴 | 🟢 | 🔴 | 🔴 | 🔴 | 🟢 | 2/4 | 🔴 | 🟢 | 🟢 | https://github.com/HanGuo97/flute |
|
| 38 |
+
| [HQQ](./hqq) | 🟢 | 🟢 | 🟢 | 🔴 | 🔴 | 🔴 | 🟢 | 1/8 | 🟢 | 🔴 | 🟢 | https://github.com/mobiusml/hqq/ |
|
| 39 |
+
| [optimum-quanto](./quanto) | 🟢 | 🟢 | 🟢 | 🔴 | 🟢 | 🔴 | 🟢 | 2/4/8 | 🔴 | 🔴 | 🟢 | https://github.com/huggingface/optimum-quanto |
|
| 40 |
+
| [FBGEMM_FP8](./fbgemm_fp8) | 🟢 | 🔴 | 🟢 | 🔴 | 🔴 | 🔴 | 🔴 | 8 | 🔴 | 🟢 | 🟢 | https://github.com/pytorch/FBGEMM |
|
| 41 |
+
| [torchao](./torchao) | 🟢 | 🟢 | 🟢 | 🔴 | 🟡 | 🔴 | | 4/8 | | 🟢🔴 | 🟢 | https://github.com/pytorch/ao |
|
| 42 |
+
| [VPTQ](./vptq) | 🔴 | 🔴 | 🟢 | 🟡 | 🔴 | 🔴 | 🟢 | 1/8 | 🔴 | 🟢 | 🟢 | https://github.com/microsoft/VPTQ |
|
| 43 |
+
| [FINEGRAINED_FP8](./finegrained_fp8) | 🟢 | 🔴 | 🟢 | 🔴 | 🔴 | 🔴 | 🔴 | 8 | 🔴 | 🟢 | 🟢 | |
|
| 44 |
+
| [SpQR](./spqr) | 🔴 | 🔴 | 🟢 | 🔴 | 🔴 | 🔴 | 🟢 | 3 | 🔴 | 🟢 | 🟢 | https://github.com/Vahe1994/SpQR/ |
|
| 45 |
+
| [Quark](./quark) | 🔴 | 🟢 | 🟢 | 🟢 | 🟢 | 🟢 | ? | 2/4/6/8/9/16 | 🔴 | 🔴 | 🟢 | https://quark.docs.amd.com/latest/ |
|
| 46 |
+
|
| 47 |
+
## Resources
|
| 48 |
+
|
| 49 |
+
If you are new to quantization, we recommend checking out these beginner-friendly quantization courses in collaboration with DeepLearning.AI.
|
| 50 |
+
|
| 51 |
+
* [Quantization Fundamentals with Hugging Face](https://www.deeplearning.ai/short-courses/quantization-fundamentals-with-hugging-face/)
|
| 52 |
+
* [Quantization in Depth](https://www.deeplearning.ai/short-courses/quantization-in-depth)
|
| 53 |
+
|
| 54 |
+
## User-Friendly Quantization Tools
|
| 55 |
+
|
| 56 |
+
If you are looking for a user-friendly quantization experience, you can use the following community spaces and notebooks:
|
| 57 |
+
|
| 58 |
+
* [Bitsandbytes Space](https://huggingface.co/spaces/bnb-community/bnb-my-repo)
|
| 59 |
+
* [GGUF Space](https://huggingface.co/spaces/ggml-org/gguf-my-repo)
|
| 60 |
+
* [MLX Space](https://huggingface.co/spaces/mlx-community/mlx-my-repo)
|
| 61 |
+
* [AuoQuant Notebook](https://colab.research.google.com/drive/1b6nqC7UZVt8bx4MksX7s656GXPM-eWw4?usp=sharing#scrollTo=ZC9Nsr9u5WhN)
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/quanto.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Optimum Quanto
|
| 18 |
+
|
| 19 |
+
[Quanto](https://github.com/huggingface/optimum-quanto) is a PyTorch quantization backend for [Optimum](https://huggingface.co/docs/optimum/index). It features linear quantization for weights (float8, int8, int4, int2) with accuracy very similar to full-precision models. Quanto is compatible with any model modality and device, making it simple to use regardless of hardware.
|
| 20 |
+
|
| 21 |
+
Quanto is also compatible with [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) for faster generation.
|
| 22 |
+
|
| 23 |
+
Install Quanto with the following command.
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
pip install optimum-quanto accelerate transformers
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
Quantize a model by creating a [`QuantoConfig`] and specifying the `weights` parameter to quantize to. This works for any model in any modality as long as it contains [torch.nn.Linear](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) layers.
|
| 30 |
+
|
| 31 |
+
> [!TIP]
|
| 32 |
+
> The Transformers integration only supports weight quantization. Use the Quanto library directly if you need activation quantization, calibration, or QAT.
|
| 33 |
+
|
| 34 |
+
```py
|
| 35 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, QuantoConfig
|
| 36 |
+
|
| 37 |
+
quant_config = QuantoConfig(weights="int8")
|
| 38 |
+
model = transformers.AutoModelForCausalLM.from_pretrained(
|
| 39 |
+
"meta-llama/Llama-3.1-8B",
|
| 40 |
+
torch_dtype="auto",
|
| 41 |
+
device_map="auto",
|
| 42 |
+
quantization_config=quant_config
|
| 43 |
+
)
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
## torch.compile
|
| 47 |
+
|
| 48 |
+
Wrap a Quanto model with [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) for faster generation.
|
| 49 |
+
|
| 50 |
+
```py
|
| 51 |
+
import torch
|
| 52 |
+
from transformers import AutoModelForSpeechSeq2Seq, QuantoConfig
|
| 53 |
+
|
| 54 |
+
quant_config = QuantoConfig(weights="int8")
|
| 55 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
| 56 |
+
"openai/whisper-large-v2",
|
| 57 |
+
torch_dtype="auto",
|
| 58 |
+
device_map="auto",
|
| 59 |
+
quantization_config=quant_config
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
model = torch.compile(model)
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
## Resources
|
| 66 |
+
|
| 67 |
+
Read the [Quanto: a PyTorch quantization backend for Optimum](https://huggingface.co/blog/quanto-introduction) blog post to learn more about the library design and benchmarks.
|
| 68 |
+
|
| 69 |
+
For more hands-on examples, take a look at the Quanto [notebook](https://colab.research.google.com/drive/16CXfVmtdQvciSh9BopZUDYcmXCDpvgrT?usp=sharing).
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/quark.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 Advanced Micro Devices, Inc. and 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 |
+
|
| 17 |
+
# Quark
|
| 18 |
+
|
| 19 |
+
[Quark](https://quark.docs.amd.com/latest/) is a deep learning quantization toolkit designed to be agnostic to specific data types, algorithms, and hardware. Different pre-processing strategies, algorithms and data-types can be combined in Quark.
|
| 20 |
+
|
| 21 |
+
The PyTorch support integrated through 🤗 Transformers primarily targets AMD CPUs and GPUs, and is primarily meant to be used for evaluation purposes. For example, it is possible to use [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) with 🤗 Transformers backend and evaluate a wide range of models quantized through Quark seamlessly.
|
| 22 |
+
|
| 23 |
+
Users interested in Quark can refer to its [documentation](https://quark.docs.amd.com/latest/) to get started quantizing models and using them in supported open-source libraries!
|
| 24 |
+
|
| 25 |
+
Although Quark has its own checkpoint / [configuration format](https://huggingface.co/amd/Llama-3.1-8B-Instruct-FP8-KV-Quark-test/blob/main/config.json#L26), the library also supports producing models with a serialization layout compliant with other quantization/runtime implementations ([AutoAWQ](https://huggingface.co/docs/transformers/quantization/awq), [native fp8 in 🤗 Transformers](https://huggingface.co/docs/transformers/quantization/finegrained_fp8)).
|
| 26 |
+
|
| 27 |
+
To be able to load Quark quantized models in Transformers, the library first needs to be installed:
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
pip install amd-quark
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
## Support matrix
|
| 34 |
+
|
| 35 |
+
Models quantized through Quark support a large range of features, that can be combined together. All quantized models independently of their configuration can seamlessly be reloaded through `PretrainedModel.from_pretrained`.
|
| 36 |
+
|
| 37 |
+
The table below shows a few features supported by Quark:
|
| 38 |
+
|
| 39 |
+
| **Feature** | **Supported subset in Quark** | |
|
| 40 |
+
|---------------------------------|-----------------------------------------------------------------------------------------------------------|---|
|
| 41 |
+
| Data types | int8, int4, int2, bfloat16, float16, fp8_e5m2, fp8_e4m3, fp6_e3m2, fp6_e2m3, fp4, OCP MX, MX6, MX9, bfp16 | |
|
| 42 |
+
| Pre-quantization transformation | SmoothQuant, QuaRot, SpinQuant, AWQ | |
|
| 43 |
+
| Quantization algorithm | GPTQ | |
|
| 44 |
+
| Supported operators | ``nn.Linear``, ``nn.Conv2d``, ``nn.ConvTranspose2d``, ``nn.Embedding``, ``nn.EmbeddingBag`` | |
|
| 45 |
+
| Granularity | per-tensor, per-channel, per-block, per-layer, per-layer type | |
|
| 46 |
+
| KV cache | fp8 | |
|
| 47 |
+
| Activation calibration | MinMax / Percentile / MSE | |
|
| 48 |
+
| Quantization strategy | weight-only, static, dynamic, with or without output quantization | |
|
| 49 |
+
|
| 50 |
+
## Models on Hugging Face Hub
|
| 51 |
+
|
| 52 |
+
Public models using Quark native serialization can be found at https://huggingface.co/models?other=quark.
|
| 53 |
+
|
| 54 |
+
Although Quark also supports [models using `quant_method="fp8"`](https://huggingface.co/models?other=fp8) and [models using `quant_method="awq"`](https://huggingface.co/models?other=awq), Transformers loads these models rather through [AutoAWQ](https://huggingface.co/docs/transformers/quantization/awq) or uses the [native fp8 support in 🤗 Transformers](https://huggingface.co/docs/transformers/quantization/finegrained_fp8).
|
| 55 |
+
|
| 56 |
+
## Using Quark models in Transformers
|
| 57 |
+
|
| 58 |
+
Here is an example of how one can load a Quark model in Transformers:
|
| 59 |
+
|
| 60 |
+
```python
|
| 61 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 62 |
+
|
| 63 |
+
model_id = "EmbeddedLLM/Llama-3.1-8B-Instruct-w_fp8_per_channel_sym"
|
| 64 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
|
| 65 |
+
|
| 66 |
+
print(model.model.layers[0].self_attn.q_proj)
|
| 67 |
+
# QParamsLinear(
|
| 68 |
+
# (weight_quantizer): ScaledRealQuantizer()
|
| 69 |
+
# (input_quantizer): ScaledRealQuantizer()
|
| 70 |
+
# (output_quantizer): ScaledRealQuantizer()
|
| 71 |
+
# )
|
| 72 |
+
|
| 73 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 74 |
+
inp = tokenizer("Where is a good place to cycle around Tokyo?", return_tensors="pt")
|
| 75 |
+
inp = inp.to(model.device)
|
| 76 |
+
|
| 77 |
+
res = model.generate(**inp, min_new_tokens=50, max_new_tokens=100)
|
| 78 |
+
|
| 79 |
+
print(tokenizer.batch_decode(res)[0])
|
| 80 |
+
# <|begin_of_text|>Where is a good place to cycle around Tokyo? There are several places in Tokyo that are suitable for cycling, depending on your skill level and interests. Here are a few suggestions:
|
| 81 |
+
# 1. Yoyogi Park: This park is a popular spot for cycling and has a wide, flat path that's perfect for beginners. You can also visit the Meiji Shrine, a famous Shinto shrine located in the park.
|
| 82 |
+
# 2. Imperial Palace East Garden: This beautiful garden has a large, flat path that's perfect for cycling. You can also visit the
|
| 83 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/selecting.md
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Selecting a quantization method
|
| 18 |
+
|
| 19 |
+
There are many quantization methods available in Transformers for inference and fine-tuning. This guide helps you choose the most common and production-ready quantization techniques depending on your use case, and presents the advantages and disadvantages of each technique.
|
| 20 |
+
|
| 21 |
+
For a comprehensive overview of all supported methods and their features, refer back to the table in the [Overview](./overview).
|
| 22 |
+
|
| 23 |
+
## Inference
|
| 24 |
+
|
| 25 |
+
Consider the quantization methods below for inference.
|
| 26 |
+
|
| 27 |
+
| quantization method | use case |
|
| 28 |
+
|---|---|
|
| 29 |
+
| bitsandbytes | ease of use and QLoRA fine-tuning on NVIDIA GPUs |
|
| 30 |
+
| compressed-tensors | loading specific quantized formats (FP8, Sparse) |
|
| 31 |
+
| GPTQModel or AWQ | good 4-bit accuracy with upfront calibration |
|
| 32 |
+
| HQQ | fast on the fly quantization without calibration |
|
| 33 |
+
| torchao | flexibility and fast inference with torch.compile |
|
| 34 |
+
|
| 35 |
+
### No Calibration Required (On-the-fly Quantization)
|
| 36 |
+
|
| 37 |
+
These methods are generally easier to use as they don't need a separate calibration dataset or step.
|
| 38 |
+
|
| 39 |
+
#### bitsandbytes
|
| 40 |
+
|
| 41 |
+
| Pros | Cons |
|
| 42 |
+
|--------------------------------------------------------------|---------------------------------------------------------|
|
| 43 |
+
| Very simple, no calibration dataset required for inference. | Primarily optimized for NVIDIA GPUs (CUDA). |
|
| 44 |
+
| Good community support and widely adopted. | Inference speedup isn't guaranteed. |
|
| 45 |
+
|
| 46 |
+
See the [bitsandbytes documentation](./bitsandbytes) for more details.
|
| 47 |
+
|
| 48 |
+
#### HQQ (Half-Quadratic Quantization)
|
| 49 |
+
|
| 50 |
+
| Pros | Cons |
|
| 51 |
+
|----------------------------------------------------------------------|----------------------------------------------------------------------------|
|
| 52 |
+
| Fast quantization process, no calibration data needed. | Accuracy can degrade significantly at bit depths <4-bit. |
|
| 53 |
+
| Multiple backends for fast inference. | Inference speed may not match others unless using `torch.compile` or backends. |
|
| 54 |
+
| Compatible with `torch.compile`. | |
|
| 55 |
+
| Supports wide range of bit depths (8, 4, 3, 2, 1-bit). | |
|
| 56 |
+
|
| 57 |
+
See the [HQQ documentation](./hqq) for more details.
|
| 58 |
+
|
| 59 |
+
#### torchao
|
| 60 |
+
|
| 61 |
+
| Pros | Cons |
|
| 62 |
+
|----------------------------------------------------------------------|----------------------------------------------------------------------|
|
| 63 |
+
| Strong integration with `torch.compile` for potential speedups. | Newer library, ecosystem still evolving. |
|
| 64 |
+
| Offers decent CPU quantization support. | Performance depends on `torch.compile` working well. |
|
| 65 |
+
| Flexibility in quantization schemes (int8, int4, fp8). | 4-bit quantization (int4wo) may not match GPTQ/AWQ in accuracy. |
|
| 66 |
+
|
| 67 |
+
See the [torchao documentation](./torchao) for more details.
|
| 68 |
+
|
| 69 |
+
### Calibration-based Quantization
|
| 70 |
+
|
| 71 |
+
These methods require an upfront calibration step using a dataset to potentially achieve higher accuracy.
|
| 72 |
+
|
| 73 |
+
#### GPTQ/GPTQModel
|
| 74 |
+
|
| 75 |
+
Calibration for 8B model takes ~20 minutes on one A100 gpu.
|
| 76 |
+
|
| 77 |
+
| Pros | Cons |
|
| 78 |
+
|----------------------------------------------------------------------|----------------------------------------------------------------------|
|
| 79 |
+
| Often achieves high accuracy. | Requires a calibration dataset and a separate calibration step. |
|
| 80 |
+
| Can lead to inference speedups. | Possible to overfit on calibration data. |
|
| 81 |
+
| Many pre-quantized GPTQ models on [Hugging Face Hub](https://huggingface.co/models?other=gptq). | |
|
| 82 |
+
|
| 83 |
+
See the [GPTQ documentation](./gptq) for more details.
|
| 84 |
+
|
| 85 |
+
#### AWQ (Activation-aware Weight Quantization)
|
| 86 |
+
|
| 87 |
+
Calibration for 8B model takes ~10 minutes on one A100 gpu.
|
| 88 |
+
|
| 89 |
+
| Pros | Cons |
|
| 90 |
+
|----------------------------------------------------------------------|-----------------------------------------------------|
|
| 91 |
+
| Often achieves high accuracy at 4-bit. (Sometimes surpasses GPTQ on specific tasks.) | Requires calibration if quantizing yourself. |
|
| 92 |
+
| Can lead to inference speedups. | |
|
| 93 |
+
| Shorter calibration time than GPTQ. | |
|
| 94 |
+
| Many pre-quantized AWQ models on [Hugging Face Hub](https://huggingface.co/models?other=awq). | |
|
| 95 |
+
|
| 96 |
+
See the [AWQ documentation](./awq) for more details.
|
| 97 |
+
|
| 98 |
+
### Loading Specific Formats
|
| 99 |
+
|
| 100 |
+
#### compressed-tensors
|
| 101 |
+
|
| 102 |
+
| Pros | Cons |
|
| 103 |
+
|--------------------------------------------------------------|-------------------------------------------------------------|
|
| 104 |
+
| Supports flexible formats including FP8 and sparsity. | Primarily for loading pre-quantized models. |
|
| 105 |
+
| | Doesn't perform quantization within Transformers directly. |
|
| 106 |
+
|
| 107 |
+
See the [compressed-tensors documentation](./compressed_tensors) for more details.
|
| 108 |
+
|
| 109 |
+
## Fine-tuning
|
| 110 |
+
|
| 111 |
+
Consider the quantization method below during fine-tuning to save memory.
|
| 112 |
+
|
| 113 |
+
### bitsandbytes[[training]]
|
| 114 |
+
|
| 115 |
+
* **Description:** The standard method for QLoRA fine-tuning via PEFT.
|
| 116 |
+
* **Pros:** Enables fine-tuning large models on consumer GPUs; widely supported and documented for PEFT.
|
| 117 |
+
* **Cons:** Primarily for NVIDIA GPUs.
|
| 118 |
+
|
| 119 |
+
Other methods offer PEFT compatibility, though bitsandbytes is the most established and straightforward path for QLoRA.
|
| 120 |
+
|
| 121 |
+
See the [bitsandbytes documentation](./bitsandbytes#qlora) and [PEFT Docs](https://huggingface.co/docs/peft/developer_guides/quantization#aqlm-quantization) for more details.
|
| 122 |
+
|
| 123 |
+
## Research
|
| 124 |
+
|
| 125 |
+
Methods like [AQLM](./aqlm), [SpQR](./spqr), [VPTQ](./vptq), [HIGGS](./higgs), etc., push the boundaries of compression (< 2-bit) or explore novel techniques.
|
| 126 |
+
|
| 127 |
+
* Consider these if:
|
| 128 |
+
* You need extreme compression (sub-4-bit).
|
| 129 |
+
* You are conducting research or require state-of-the-art results from their respective papers.
|
| 130 |
+
* You have significant compute resources available for potentially complex quantization procedures.
|
| 131 |
+
We recommend consulting each methods documentation and associated papers carefully before choosing one for use in production.
|
| 132 |
+
|
| 133 |
+
## Benchmark Comparison
|
| 134 |
+
|
| 135 |
+
To provide a quantitative comparison of different quantization methods, we benchmarked several popular techniques on the Llama 3.1 8B and 70B models. The following tables show results for accuracy (higher is better), inference throughput measured in tokens/second (higher is better), peak VRAM usage measured in GB (lower is better), and quantization time.
|
| 136 |
+
|
| 137 |
+
Performance metrics were measured on 2 NVIDIA A100 80GB GPU for Llama 3.1 70B (bfloat16), 1 NVIDIA H100 80GB GPU for FP8 methods, and 1 NVIDIA A100 80GB GPU for all other methods. Throughput was measured with a batch size of 1 and generating 64 tokens.
|
| 138 |
+
Results for `torch.compile` and Marlin kernels are included where applicable and supported.
|
| 139 |
+
|
| 140 |
+
<iframe
|
| 141 |
+
src="https://huggingface.co/datasets/derekl35/quantization-benchmarks/embed/viewer/default/train"
|
| 142 |
+
frameborder="0"
|
| 143 |
+
width="100%"
|
| 144 |
+
height="560px"
|
| 145 |
+
title="benchmarking results dataset"
|
| 146 |
+
></iframe>
|
| 147 |
+
|
| 148 |
+
The key takeaways are:
|
| 149 |
+
|
| 150 |
+
| Quantization & Methods | Memory Savings (vs bf16) | Accuracy | Other Notes |
|
| 151 |
+
|-------------------------------------------- |------------------------- |--------------------- |------------------------------------------------------------------- |
|
| 152 |
+
| **8-bit** (bnb-int8, HQQ, Quanto, torchao, fp8) | ~2x | Very close to baseline bf16 model | |
|
| 153 |
+
| **4-bit** (AWQ, GPTQ, HQQ, bnb-nf4) | ~4x | Relatively high accuracy | AWQ/GPTQ often lead in accuracy but need calibration. HQQ/bnb-nf4 are easy on-the-fly. |
|
| 154 |
+
| **Sub-4-bit** (VPTQ, AQLM, 2-bit GPTQ) | Extreme (>4x) | Noticeable drop, especially at 2-bit | Quantization times can be very long (AQLM, VPTQ). Performance varies. |
|
| 155 |
+
|
| 156 |
+
> [!TIP]
|
| 157 |
+
> Always benchmark the performance (accuracy and speed) of the quantized model on your specific task and hardware to ensure it meets your requirements. Refer to the individual documentation pages linked above for detailed usage instructions.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/spqr.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 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 |
+
|
| 17 |
+
# SpQR
|
| 18 |
+
|
| 19 |
+
The [SpQR](https://hf.co/papers/2306.03078) quantization algorithm involves a 16x16 tiled bi-level group 3-bit quantization structure with sparse outliers.
|
| 20 |
+
|
| 21 |
+
<div class="flex justify-center">
|
| 22 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/spqr-diagram.png">
|
| 23 |
+
</div>
|
| 24 |
+
|
| 25 |
+
> [!TIP]
|
| 26 |
+
> To quantize a model with SpQR, refer to the [Vahe1994/SpQR](https://github.com/Vahe1994/SpQR) repository.
|
| 27 |
+
|
| 28 |
+
Load a SpQR-quantized model with [`~PreTrainedModel.from_pretrained`].
|
| 29 |
+
|
| 30 |
+
```python
|
| 31 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 32 |
+
import torch
|
| 33 |
+
|
| 34 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 35 |
+
"elvircrn/Llama-2-7b-SPQR-3Bit-16x16-red_pajama-hf",
|
| 36 |
+
torch_dtype=torch.half,
|
| 37 |
+
device_map="auto"
|
| 38 |
+
)
|
| 39 |
+
tokenizer = AutoTokenizer.from_pretrained("elvircrn/Llama-2-7b-SPQR-3Bit-16x16-red_pajama-hf")
|
| 40 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/torchao.md
ADDED
|
@@ -0,0 +1,675 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 3 |
+
the License. You may obtain a copy of the License at
|
| 4 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 5 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 6 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 7 |
+
specific language governing permissions and limitations under the License.
|
| 8 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 9 |
+
rendered properly in your Markdown viewer.
|
| 10 |
+
-->
|
| 11 |
+
|
| 12 |
+
# torchao
|
| 13 |
+
|
| 14 |
+
[](https://colab.research.google.com/github/huggingface/notebooks/blob/main/transformers_doc/en/quantization/torchao.ipynb)
|
| 15 |
+
|
| 16 |
+
[torchao](https://github.com/pytorch/ao) is a PyTorch architecture optimization library with support for custom high performance data types, quantization, and sparsity. It is composable with native PyTorch features such as [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) for even faster inference and training.
|
| 17 |
+
|
| 18 |
+
See the table below for additional torchao features.
|
| 19 |
+
|
| 20 |
+
| Feature | Description |
|
| 21 |
+
|--------|-------------|
|
| 22 |
+
| **Quantization Aware Training (QAT)** | Train quantized models with minimal accuracy loss (see [QAT README](https://github.com/pytorch/ao/blob/main/torchao/quantization/qat/README.md)) |
|
| 23 |
+
| **Float8 Training** | High-throughput training with float8 formats (see [torchtitan](https://github.com/pytorch/torchtitan/blob/main/docs/float8.md) and [Accelerate](https://huggingface.co/docs/accelerate/usage_guides/low_precision_training#configuring-torchao) docs) |
|
| 24 |
+
| **Sparsity Support** | Semi-structured (2:4) sparsity for faster inference (see [Accelerating Neural Network Training with Semi-Structured (2:4) Sparsity](https://pytorch.org/blog/accelerating-neural-network-training/) blog post) |
|
| 25 |
+
| **Optimizer Quantization** | Reduce optimizer state memory with 4 and 8-bit variants of Adam |
|
| 26 |
+
| **KV Cache Quantization** | Enables long context inference with lower memory (see [KV Cache Quantization](https://github.com/pytorch/ao/blob/main/torchao/_models/llama/README.md)) |
|
| 27 |
+
| **Custom Kernels Support** | use your own `torch.compile` compatible ops |
|
| 28 |
+
| **FSDP2** | Composable with FSDP2 for training|
|
| 29 |
+
|
| 30 |
+
> [!TIP]
|
| 31 |
+
> Refer to the torchao [README.md](https://github.com/pytorch/ao#torchao-pytorch-architecture-optimization) for more details about the library.
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
torchao supports the [quantization techniques](https://github.com/pytorch/ao/blob/main/torchao/quantization/README.md) below.
|
| 35 |
+
|
| 36 |
+
- A16W8 Float8 Dynamic Quantization
|
| 37 |
+
- A16W8 Float8 WeightOnly Quantization
|
| 38 |
+
- A8W8 Int8 Dynamic Quantization
|
| 39 |
+
- A16W8 Int8 Weight Only Quantization
|
| 40 |
+
- A16W4 Int4 Weight Only Quantization
|
| 41 |
+
- A16W4 Int4 Weight Only Quantization + 2:4 Sparsity
|
| 42 |
+
- Autoquantization
|
| 43 |
+
|
| 44 |
+
torchao also supports module level configuration by specifying a dictionary from fully qualified name of module and its corresponding quantization config. This allows skip quantizing certain layers and using different quantization config for different modules.
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
Check the table below to see if your hardware is compatible.
|
| 48 |
+
|
| 49 |
+
| Component | Compatibility |
|
| 50 |
+
|----------|----------------|
|
| 51 |
+
| CUDA Versions | ✅ cu118, cu126, cu128 |
|
| 52 |
+
| XPU Versions | ✅ pytorch2.8 |
|
| 53 |
+
| CPU | ✅ change `device_map="cpu"` (see examples below) |
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
Install torchao from PyPi or the PyTorch index with the following commands.
|
| 58 |
+
|
| 59 |
+
<hfoptions id="install torchao">
|
| 60 |
+
<hfoption id="PyPi">
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
# Updating 🤗 Transformers to the latest version, as the example script below uses the new auto compilation
|
| 64 |
+
# Stable release from Pypi which will default to CUDA 12.6
|
| 65 |
+
pip install --upgrade torchao transformers
|
| 66 |
+
```
|
| 67 |
+
</hfoption>
|
| 68 |
+
<hfoption id="PyTorch Index">
|
| 69 |
+
Stable Release from the PyTorch index
|
| 70 |
+
|
| 71 |
+
```bash
|
| 72 |
+
pip install torchao --index-url https://download.pytorch.org/whl/cu126 # options are cpu/cu118/cu126/cu128
|
| 73 |
+
```
|
| 74 |
+
</hfoption>
|
| 75 |
+
</hfoptions>
|
| 76 |
+
|
| 77 |
+
If your torchao version is below 0.10.0, you need to upgrade it, please refer to the [deprecation notice](#deprecation-notice) for more details.
|
| 78 |
+
|
| 79 |
+
## Quantization examples
|
| 80 |
+
|
| 81 |
+
TorchAO provides a variety of quantization configurations. Each configuration can be further customized with parameters such as `group_size`, `scheme`, and `layout` to optimize for specific hardware and model architectures.
|
| 82 |
+
|
| 83 |
+
For a complete list of available configurations, see the [quantization API documentation](https://github.com/pytorch/ao/blob/main/torchao/quantization/quant_api.py).
|
| 84 |
+
|
| 85 |
+
You can manually choose the quantization types and settings or automatically select the quantization types.
|
| 86 |
+
|
| 87 |
+
Create a [`TorchAoConfig`] and specify the quantization type and `group_size` of the weights to quantize (for int8 weight only and int4 weight only). Set the `cache_implementation` to `"static"` to automatically [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) the forward method.
|
| 88 |
+
|
| 89 |
+
We'll show examples for recommended quantization methods based on hardwares, e.g. A100 GPU, H100 GPU, CPU.
|
| 90 |
+
|
| 91 |
+
### H100 GPU
|
| 92 |
+
<hfoptions id="examples-H100-GPU">
|
| 93 |
+
<hfoption id="float8-dynamic-and-weight-only">
|
| 94 |
+
|
| 95 |
+
```py
|
| 96 |
+
import torch
|
| 97 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 98 |
+
from torchao.quantization import Float8DynamicActivationFloat8WeightConfig, Float8WeightOnlyConfig
|
| 99 |
+
|
| 100 |
+
quant_config = Float8DynamicActivationFloat8WeightConfig()
|
| 101 |
+
# or float8 weight only quantization
|
| 102 |
+
# quant_config = Float8WeightOnlyConfig()
|
| 103 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 104 |
+
|
| 105 |
+
# Load and quantize the model
|
| 106 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 107 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
| 108 |
+
torch_dtype="auto",
|
| 109 |
+
device_map="auto",
|
| 110 |
+
quantization_config=quantization_config
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
| 114 |
+
input_text = "What are we having for dinner?"
|
| 115 |
+
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
|
| 116 |
+
|
| 117 |
+
# auto-compile the quantized model with `cache_implementation="static"` to get speed up
|
| 118 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
|
| 119 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 120 |
+
```
|
| 121 |
+
</hfoption>
|
| 122 |
+
<hfoption id="int4-weight-only">
|
| 123 |
+
|
| 124 |
+
```py
|
| 125 |
+
import torch
|
| 126 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 127 |
+
from torchao.quantization import GemliteUIntXWeightOnlyConfig
|
| 128 |
+
|
| 129 |
+
# We integrated with gemlite, which optimizes for batch size N on A100 and H100
|
| 130 |
+
quant_config = GemliteUIntXWeightOnlyConfig(group_size=128)
|
| 131 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 132 |
+
|
| 133 |
+
# Load and quantize the model
|
| 134 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 135 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
| 136 |
+
torch_dtype="auto",
|
| 137 |
+
device_map="auto",
|
| 138 |
+
quantization_config=quantization_config
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
| 142 |
+
input_text = "What are we having for dinner?"
|
| 143 |
+
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
|
| 144 |
+
|
| 145 |
+
# auto-compile the quantized model with `cache_implementation="static"` to get speed up
|
| 146 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
|
| 147 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 148 |
+
```
|
| 149 |
+
</hfoption>
|
| 150 |
+
</hfoptions>
|
| 151 |
+
|
| 152 |
+
</hfoption>
|
| 153 |
+
<hfoption id="int4-weight-only-24sparse">
|
| 154 |
+
|
| 155 |
+
```py
|
| 156 |
+
import torch
|
| 157 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 158 |
+
from torchao.quantization import Int4WeightOnlyConfig
|
| 159 |
+
from torchao.dtypes import MarlinSparseLayout
|
| 160 |
+
|
| 161 |
+
quant_config = Int4WeightOnlyConfig(layout=MarlinSparseLayout())
|
| 162 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 163 |
+
|
| 164 |
+
# Load and quantize the model with sparsity. A sparse checkpoint is needed to accelerate without accuracy loss
|
| 165 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 166 |
+
"RedHatAI/Sparse-Llama-3.1-8B-2of4",
|
| 167 |
+
torch_dtype=torch.float16,
|
| 168 |
+
device_map="cuda",
|
| 169 |
+
quantization_config=quantization_config
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
tokenizer = AutoTokenizer.from_pretrained("RedHatAI/Sparse-Llama-3.1-8B-2of4")
|
| 173 |
+
input_text = "What are we having for dinner?"
|
| 174 |
+
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
|
| 175 |
+
|
| 176 |
+
# auto-compile the quantized model with `cache_implementation="static"` to get speed up
|
| 177 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
|
| 178 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 179 |
+
```
|
| 180 |
+
</hfoption>
|
| 181 |
+
</hfoptions>
|
| 182 |
+
|
| 183 |
+
### A100 GPU
|
| 184 |
+
<hfoptions id="examples-A100-GPU">
|
| 185 |
+
<hfoption id="int8-dynamic-and-weight-only">
|
| 186 |
+
|
| 187 |
+
```py
|
| 188 |
+
import torch
|
| 189 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 190 |
+
from torchao.quantization import Int8DynamicActivationInt8WeightConfig, Int8WeightOnlyConfig
|
| 191 |
+
|
| 192 |
+
quant_config = Int8DynamicActivationInt8WeightConfig()
|
| 193 |
+
# or int8 weight only quantization
|
| 194 |
+
# quant_config = Int8WeightOnlyConfig()
|
| 195 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 196 |
+
|
| 197 |
+
# Load and quantize the model
|
| 198 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 199 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
| 200 |
+
torch_dtype="auto",
|
| 201 |
+
device_map="auto",
|
| 202 |
+
quantization_config=quantization_config
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
| 206 |
+
input_text = "What are we having for dinner?"
|
| 207 |
+
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
|
| 208 |
+
|
| 209 |
+
# auto-compile the quantized model with `cache_implementation="static"` to get speed up
|
| 210 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
|
| 211 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 212 |
+
```
|
| 213 |
+
</hfoption>
|
| 214 |
+
|
| 215 |
+
<hfoption id="int4-weight-only">
|
| 216 |
+
|
| 217 |
+
```py
|
| 218 |
+
import torch
|
| 219 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 220 |
+
from torchao.quantization import GemliteUIntXWeightOnlyConfig, Int4WeightOnlyConfig
|
| 221 |
+
|
| 222 |
+
# For batch size N, we recommend gemlite, which may require autotuning
|
| 223 |
+
# default is 4 bit, 8 bit is also supported by passing `bit_width=8`
|
| 224 |
+
quant_config = GemliteUIntXWeightOnlyConfig(group_size=128)
|
| 225 |
+
|
| 226 |
+
# For batch size 1, we also have custom tinygemm kernel that's only optimized for this
|
| 227 |
+
# We can set `use_hqq` to `True` for better accuracy
|
| 228 |
+
# quant_config = Int4WeightOnlyConfig(group_size=128, use_hqq=True)
|
| 229 |
+
|
| 230 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 231 |
+
|
| 232 |
+
# Load and quantize the model
|
| 233 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 234 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
| 235 |
+
torch_dtype="auto",
|
| 236 |
+
device_map="auto",
|
| 237 |
+
quantization_config=quantization_config
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
| 241 |
+
input_text = "What are we having for dinner?"
|
| 242 |
+
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
|
| 243 |
+
|
| 244 |
+
# auto-compile the quantized model with `cache_implementation="static"` to get speed up
|
| 245 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
|
| 246 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 247 |
+
```
|
| 248 |
+
</hfoption>
|
| 249 |
+
</hfoptions>
|
| 250 |
+
|
| 251 |
+
</hfoption>
|
| 252 |
+
<hfoption id="int4-weight-only-24sparse">
|
| 253 |
+
|
| 254 |
+
```py
|
| 255 |
+
import torch
|
| 256 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 257 |
+
from torchao.quantization import Int4WeightOnlyConfig
|
| 258 |
+
from torchao.dtypes import MarlinSparseLayout
|
| 259 |
+
|
| 260 |
+
quant_config = Int4WeightOnlyConfig(layout=MarlinSparseLayout())
|
| 261 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 262 |
+
|
| 263 |
+
# Load and quantize the model with sparsity. A sparse checkpoint is needed to accelerate without accuracy loss
|
| 264 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 265 |
+
"RedHatAI/Sparse-Llama-3.1-8B-2of4",
|
| 266 |
+
torch_dtype=torch.float16,
|
| 267 |
+
device_map="cuda",
|
| 268 |
+
quantization_config=quantization_config
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
tokenizer = AutoTokenizer.from_pretrained("RedHatAI/Sparse-Llama-3.1-8B-2of4")
|
| 272 |
+
input_text = "What are we having for dinner?"
|
| 273 |
+
input_ids = tokenizer(input_text, return_tensors="pt").to("cuda")
|
| 274 |
+
|
| 275 |
+
# auto-compile the quantized model with `cache_implementation="static"` to get speed up
|
| 276 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
|
| 277 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 278 |
+
```
|
| 279 |
+
</hfoption>
|
| 280 |
+
</hfoptions>
|
| 281 |
+
|
| 282 |
+
### Intel XPU
|
| 283 |
+
<hfoptions id="examples-Intel-XPU">
|
| 284 |
+
<hfoption id="int8-dynamic-and-weight-only">
|
| 285 |
+
|
| 286 |
+
```py
|
| 287 |
+
import torch
|
| 288 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 289 |
+
from torchao.quantization import Int8DynamicActivationInt8WeightConfig, Int8WeightOnlyConfig
|
| 290 |
+
|
| 291 |
+
quant_config = Int8DynamicActivationInt8WeightConfig()
|
| 292 |
+
# or int8 weight only quantization
|
| 293 |
+
# quant_config = Int8WeightOnlyConfig()
|
| 294 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 295 |
+
|
| 296 |
+
# Load and quantize the model
|
| 297 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 298 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
| 299 |
+
torch_dtype="auto",
|
| 300 |
+
device_map="auto",
|
| 301 |
+
quantization_config=quantization_config
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
| 305 |
+
input_text = "What are we having for dinner?"
|
| 306 |
+
input_ids = tokenizer(input_text, return_tensors="pt").to("xpu")
|
| 307 |
+
|
| 308 |
+
# auto-compile the quantized model with `cache_implementation="static"` to get speed up
|
| 309 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
|
| 310 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 311 |
+
```
|
| 312 |
+
</hfoption>
|
| 313 |
+
|
| 314 |
+
<hfoption id="int4-weight-only">
|
| 315 |
+
|
| 316 |
+
```py
|
| 317 |
+
import torch
|
| 318 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 319 |
+
from torchao.quantization import Int4WeightOnlyConfig
|
| 320 |
+
from torchao.dtypes import Int4XPULayout
|
| 321 |
+
from torchao.quantization.quant_primitives import ZeroPointDomain
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
quant_config = Int4WeightOnlyConfig(group_size=128, layout=Int4XPULayout(), zero_point_domain=ZeroPointDomain.INT)
|
| 325 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 326 |
+
|
| 327 |
+
# Load and quantize the model
|
| 328 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 329 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
| 330 |
+
torch_dtype="auto",
|
| 331 |
+
device_map="auto",
|
| 332 |
+
quantization_config=quantization_config
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
| 336 |
+
input_text = "What are we having for dinner?"
|
| 337 |
+
input_ids = tokenizer(input_text, return_tensors="pt").to("xpu")
|
| 338 |
+
|
| 339 |
+
# auto-compile the quantized model with `cache_implementation="static"` to get speed up
|
| 340 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
|
| 341 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 342 |
+
```
|
| 343 |
+
</hfoption>
|
| 344 |
+
</hfoptions>
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
### CPU
|
| 348 |
+
<hfoptions id="examples-CPU">
|
| 349 |
+
<hfoption id="int8-dynamic-and-weight-only">
|
| 350 |
+
|
| 351 |
+
```py
|
| 352 |
+
import torch
|
| 353 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 354 |
+
from torchao.quantization import Int8DynamicActivationInt8WeightConfig, Int8WeightOnlyConfig
|
| 355 |
+
|
| 356 |
+
quant_config = Int8DynamicActivationInt8WeightConfig()
|
| 357 |
+
# quant_config = Int8WeightOnlyConfig()
|
| 358 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 359 |
+
|
| 360 |
+
# Load and quantize the model
|
| 361 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 362 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
| 363 |
+
torch_dtype="auto",
|
| 364 |
+
device_map="cpu",
|
| 365 |
+
quantization_config=quantization_config
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
| 369 |
+
input_text = "What are we having for dinner?"
|
| 370 |
+
input_ids = tokenizer(input_text, return_tensors="pt")
|
| 371 |
+
|
| 372 |
+
# auto-compile the quantized model with `cache_implementation="static"` to get speed up
|
| 373 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
|
| 374 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 375 |
+
```
|
| 376 |
+
</hfoption>
|
| 377 |
+
<hfoption id="int4-weight-only">
|
| 378 |
+
|
| 379 |
+
> [!TIP]
|
| 380 |
+
> Run the quantized model on a CPU by changing `device_map` to `"cpu"` and `layout` to `Int4CPULayout()`.
|
| 381 |
+
|
| 382 |
+
```py
|
| 383 |
+
import torch
|
| 384 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 385 |
+
from torchao.quantization import Int4WeightOnlyConfig
|
| 386 |
+
from torchao.dtypes import Int4CPULayout
|
| 387 |
+
|
| 388 |
+
quant_config = Int4WeightOnlyConfig(group_size=128, layout=Int4CPULayout())
|
| 389 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 390 |
+
|
| 391 |
+
# Load and quantize the model
|
| 392 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 393 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
| 394 |
+
torch_dtype="auto",
|
| 395 |
+
device_map="cpu",
|
| 396 |
+
quantization_config=quantization_config
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
| 400 |
+
input_text = "What are we having for dinner?"
|
| 401 |
+
input_ids = tokenizer(input_text, return_tensors="pt")
|
| 402 |
+
|
| 403 |
+
# auto-compile the quantized model with `cache_implementation="static"` to get speed up
|
| 404 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
|
| 405 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 406 |
+
```
|
| 407 |
+
</hfoption>
|
| 408 |
+
</hfoptions>
|
| 409 |
+
|
| 410 |
+
### Per Module Quantization
|
| 411 |
+
#### 1. Skip quantization for certain layers
|
| 412 |
+
With `ModuleFqnToConfig` we can specify a default configuration for all layers while skipping quantization for certain layers.
|
| 413 |
+
```py
|
| 414 |
+
import torch
|
| 415 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
|
| 416 |
+
|
| 417 |
+
model_id = "meta-llama/Llama-3.1-8B-Instruct"
|
| 418 |
+
|
| 419 |
+
from torchao.quantization import Int4WeightOnlyConfig, ModuleFqnToConfig
|
| 420 |
+
config = Int4WeightOnlyConfig(group_size=128)
|
| 421 |
+
|
| 422 |
+
# set default to int4 (for linears), and skip quantizing `model.layers.0.self_attn.q_proj`
|
| 423 |
+
quant_config = ModuleFqnToConfig({"_default": config, "model.layers.0.self_attn.q_proj": None})
|
| 424 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 425 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16, quantization_config=quantization_config)
|
| 426 |
+
# lm_head is not quantized and model.layers.0.self_attn.q_proj is not quantized
|
| 427 |
+
print("quantized model:", quantized_model)
|
| 428 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 429 |
+
|
| 430 |
+
# Manual Testing
|
| 431 |
+
prompt = "Hey, are you conscious? Can you talk to me?"
|
| 432 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(quantized_model.device.type)
|
| 433 |
+
generated_ids = quantized_model.generate(**inputs, max_new_tokens=128)
|
| 434 |
+
output_text = tokenizer.batch_decode(
|
| 435 |
+
generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 436 |
+
)
|
| 437 |
+
print(output_text)
|
| 438 |
+
```
|
| 439 |
+
|
| 440 |
+
#### 2. Quantizing different layers with different quantization configs
|
| 441 |
+
```py
|
| 442 |
+
import torch
|
| 443 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
|
| 444 |
+
|
| 445 |
+
model_id = "facebook/opt-125m"
|
| 446 |
+
|
| 447 |
+
from torchao.quantization import Int4WeightOnlyConfig, ModuleFqnToConfig, Int8DynamicActivationInt4WeightConfig, IntxWeightOnlyConfig, PerAxis, MappingType
|
| 448 |
+
|
| 449 |
+
weight_dtype = torch.int8
|
| 450 |
+
granularity = PerAxis(0)
|
| 451 |
+
mapping_type = MappingType.ASYMMETRIC
|
| 452 |
+
embedding_config = IntxWeightOnlyConfig(
|
| 453 |
+
weight_dtype=weight_dtype,
|
| 454 |
+
granularity=granularity,
|
| 455 |
+
mapping_type=mapping_type,
|
| 456 |
+
)
|
| 457 |
+
linear_config = Int8DynamicActivationInt4WeightConfig(group_size=128)
|
| 458 |
+
quant_config = ModuleFqnToConfig({"_default": linear_config, "model.decoder.embed_tokens": embedding_config, "model.decoder.embed_positions": None})
|
| 459 |
+
# set `include_embedding` to True in order to include embedding in quantization
|
| 460 |
+
# when `include_embedding` is True, we'll remove input embedding from `modules_not_to_convert` as well
|
| 461 |
+
quantization_config = TorchAoConfig(quant_type=quant_config, include_embedding=True)
|
| 462 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cpu", torch_dtype=torch.bfloat16, quantization_config=quantization_config)
|
| 463 |
+
print("quantized model:", quantized_model)
|
| 464 |
+
# make sure embedding is quantized
|
| 465 |
+
print("embed_tokens weight:", quantized_model.model.decoder.embed_tokens.weight)
|
| 466 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 467 |
+
|
| 468 |
+
# Manual Testing
|
| 469 |
+
prompt = "Hey, are you conscious? Can you talk to me?"
|
| 470 |
+
inputs = tokenizer(prompt, return_tensors="pt").to("cpu")
|
| 471 |
+
generated_ids = quantized_model.generate(**inputs, max_new_tokens=128, cache_implementation="static")
|
| 472 |
+
output_text = tokenizer.batch_decode(
|
| 473 |
+
generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 474 |
+
)
|
| 475 |
+
print(output_text)
|
| 476 |
+
```
|
| 477 |
+
|
| 478 |
+
### Autoquant
|
| 479 |
+
|
| 480 |
+
If you want to automatically choose a quantization type for quantizable layers (`nn.Linear`) you can use the [autoquant](https://pytorch.org/ao/stable/generated/torchao.quantization.autoquant.html#torchao.quantization.autoquant) API.
|
| 481 |
+
|
| 482 |
+
The `autoquant` API automatically chooses a quantization type by micro-benchmarking on input type and shape and compiling a single linear layer.
|
| 483 |
+
|
| 484 |
+
Note: autoquant is for GPU only right now.
|
| 485 |
+
|
| 486 |
+
Create a [`TorchAoConfig`] and set to `"autoquant"`. Set the `cache_implementation` to `"static"` to automatically [torch.compile](https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) the forward method. Finally, call `finalize_autoquant` on the quantized model to finalize the quantization and log the input shapes.
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
```py
|
| 490 |
+
import torch
|
| 491 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 492 |
+
|
| 493 |
+
quantization_config = TorchAoConfig("autoquant", min_sqnr=None)
|
| 494 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 495 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
| 496 |
+
torch_dtype="auto",
|
| 497 |
+
device_map="auto",
|
| 498 |
+
quantization_config=quantization_config
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
| 502 |
+
input_text = "What are we having for dinner?"
|
| 503 |
+
input_ids = tokenizer(input_text, return_tensors="pt").to(quantized_model.device.type)
|
| 504 |
+
|
| 505 |
+
# auto-compile the quantized model with `cache_implementation="static"` to get speed up
|
| 506 |
+
output = quantized_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static")
|
| 507 |
+
# explicitly call `finalize_autoquant` (may be refactored and removed in the future)
|
| 508 |
+
quantized_model.finalize_autoquant()
|
| 509 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 510 |
+
```
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
## Serialization
|
| 514 |
+
|
| 515 |
+
torchao implements [torch.Tensor subclasses](https://pytorch.org/docs/stable/notes/extending.html#subclassing-torch-tensor) for maximum flexibility in supporting new quantized torch.Tensor formats. [Safetensors](https://huggingface.co/docs/safetensors/en/index) serialization and deserialization does not work with torchao.
|
| 516 |
+
|
| 517 |
+
To avoid arbitrary user code execution, torchao sets `weights_only=True` in [torch.load](https://pytorch.org/docs/stable/generated/torch.load.html) to ensure only tensors are loaded. Any known user functions can be whitelisted with [add_safe_globals](https://pytorch.org/docs/stable/notes/serialization.html#torch.serialization.add_safe_globals).
|
| 518 |
+
|
| 519 |
+
<hfoptions id="serialization-examples">
|
| 520 |
+
<hfoption id="save-locally">
|
| 521 |
+
|
| 522 |
+
```py
|
| 523 |
+
# don't serialize model with Safetensors
|
| 524 |
+
output_dir = "llama3-8b-int4wo-128"
|
| 525 |
+
quantized_model.save_pretrained("llama3-8b-int4wo-128", safe_serialization=False)
|
| 526 |
+
```
|
| 527 |
+
</hfoption>
|
| 528 |
+
<hfoption id="push-to-huggingface-hub">
|
| 529 |
+
|
| 530 |
+
```py
|
| 531 |
+
# don't serialize model with Safetensors
|
| 532 |
+
USER_ID = "your_huggingface_user_id"
|
| 533 |
+
REPO_ID = "llama3-8b-int4wo-128"
|
| 534 |
+
quantized_model.push_to_hub(f"{USER_ID}/llama3-8b-int4wo-128", safe_serialization=False)
|
| 535 |
+
tokenizer.push_to_hub(f"{USER_ID}/llama3-8b-int4wo-128")
|
| 536 |
+
```
|
| 537 |
+
</hfoption>
|
| 538 |
+
</hfoptions>
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
## Loading quantized models
|
| 542 |
+
|
| 543 |
+
Loading a quantized model depends on the quantization scheme. For quantization schemes, like int8 and float8, you can quantize the model on any device and also load it on any device. The example below demonstrates quantizing a model on the CPU and then loading it on CUDA or XPU.
|
| 544 |
+
```py
|
| 545 |
+
import torch
|
| 546 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 547 |
+
from torchao.quantization import Int8WeightOnlyConfig
|
| 548 |
+
|
| 549 |
+
quant_config = Int8WeightOnlyConfig(group_size=128)
|
| 550 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 551 |
+
|
| 552 |
+
# Load and quantize the model
|
| 553 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 554 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
| 555 |
+
torch_dtype="auto",
|
| 556 |
+
device_map="cpu",
|
| 557 |
+
quantization_config=quantization_config
|
| 558 |
+
)
|
| 559 |
+
# save the quantized model
|
| 560 |
+
output_dir = "llama-3.1-8b-torchao-int8"
|
| 561 |
+
quantized_model.save_pretrained(output_dir, safe_serialization=False)
|
| 562 |
+
|
| 563 |
+
# reload the quantized model
|
| 564 |
+
reloaded_model = AutoModelForCausalLM.from_pretrained(
|
| 565 |
+
output_dir,
|
| 566 |
+
device_map="auto",
|
| 567 |
+
torch_dtype=torch.bfloat16
|
| 568 |
+
)
|
| 569 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
| 570 |
+
input_text = "What are we having for dinner?"
|
| 571 |
+
input_ids = tokenizer(input_text, return_tensors="pt").to(reloaded_model.device.type)
|
| 572 |
+
|
| 573 |
+
output = reloaded_model.generate(**input_ids, max_new_tokens=10)
|
| 574 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 575 |
+
|
| 576 |
+
```
|
| 577 |
+
For int4, the model can only be loaded on the same device it was quantized on because the layout is specific to the device. The example below demonstrates quantizing and loading a model on the CPU.
|
| 578 |
+
|
| 579 |
+
```py
|
| 580 |
+
import torch
|
| 581 |
+
from transformers import TorchAoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 582 |
+
from torchao.quantization import Int4WeightOnlyConfig
|
| 583 |
+
from torchao.dtypes import Int4CPULayout
|
| 584 |
+
|
| 585 |
+
quant_config = Int4WeightOnlyConfig(group_size=128, layout=Int4CPULayout())
|
| 586 |
+
quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 587 |
+
|
| 588 |
+
# Load and quantize the model
|
| 589 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 590 |
+
"meta-llama/Llama-3.1-8B-Instruct",
|
| 591 |
+
torch_dtype="auto",
|
| 592 |
+
device_map="cpu",
|
| 593 |
+
quantization_config=quantization_config
|
| 594 |
+
)
|
| 595 |
+
# save the quantized model
|
| 596 |
+
output_dir = "llama-3.1-8b-torchao-int4-cpu"
|
| 597 |
+
quantized_model.save_pretrained(output_dir, safe_serialization=False)
|
| 598 |
+
|
| 599 |
+
# reload the quantized model
|
| 600 |
+
reloaded_model = AutoModelForCausalLM.from_pretrained(
|
| 601 |
+
output_dir,
|
| 602 |
+
device_map="cpu",
|
| 603 |
+
torch_dtype=torch.bfloat16
|
| 604 |
+
)
|
| 605 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.1-8B-Instruct")
|
| 606 |
+
input_text = "What are we having for dinner?"
|
| 607 |
+
input_ids = tokenizer(input_text, return_tensors="pt")
|
| 608 |
+
|
| 609 |
+
output = reloaded_model.generate(**input_ids, max_new_tokens=10)
|
| 610 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 611 |
+
|
| 612 |
+
```
|
| 613 |
+
|
| 614 |
+
## ⚠️ Deprecation Notice
|
| 615 |
+
|
| 616 |
+
> Starting with version 0.10.0, the string-based API for quantization configuration (e.g., `TorchAoConfig("int4_weight_only", group_size=128)`) is **deprecated** and will be removed in a future release.
|
| 617 |
+
>
|
| 618 |
+
> Please use the new `AOBaseConfig`-based approach instead:
|
| 619 |
+
>
|
| 620 |
+
> ```python
|
| 621 |
+
> # Old way (deprecated)
|
| 622 |
+
> quantization_config = TorchAoConfig("int4_weight_only", group_size=128)
|
| 623 |
+
>
|
| 624 |
+
> # New way (recommended)
|
| 625 |
+
> from torchao.quantization import Int4WeightOnlyConfig
|
| 626 |
+
> quant_config = Int4WeightOnlyConfig(group_size=128)
|
| 627 |
+
> quantization_config = TorchAoConfig(quant_type=quant_config)
|
| 628 |
+
> ```
|
| 629 |
+
>
|
| 630 |
+
> The new API offers greater flexibility, better type safety, and access to the full range of features available in torchao.
|
| 631 |
+
>
|
| 632 |
+
> [Migration Guide](#migration-guide)
|
| 633 |
+
>
|
| 634 |
+
> Here's how to migrate from common string identifiers to their `AOBaseConfig` equivalents:
|
| 635 |
+
>
|
| 636 |
+
> | Old String API | New `AOBaseConfig` API |
|
| 637 |
+
> |----------------|------------------------|
|
| 638 |
+
> | `"int4_weight_only"` | `Int4WeightOnlyConfig()` |
|
| 639 |
+
> | `"int8_weight_only"` | `Int8WeightOnlyConfig()` |
|
| 640 |
+
> | `"int8_dynamic_activation_int8_weight"` | `Int8DynamicActivationInt8WeightConfig()` |
|
| 641 |
+
>
|
| 642 |
+
> All configuration objects accept parameters for customization (e.g., `group_size`, `scheme`, `layout`).
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
## Resources
|
| 647 |
+
|
| 648 |
+
For a better sense of expected performance, view the [benchmarks](https://github.com/pytorch/ao/tree/main/torchao/quantization#benchmarks) for various models with CUDA and XPU backends. You can also run the code below to benchmark a model yourself.
|
| 649 |
+
|
| 650 |
+
```py
|
| 651 |
+
from torch._inductor.utils import do_bench_using_profiling
|
| 652 |
+
from typing import Callable
|
| 653 |
+
|
| 654 |
+
def benchmark_fn(func: Callable, *args, **kwargs) -> float:
|
| 655 |
+
"""Thin wrapper around do_bench_using_profiling"""
|
| 656 |
+
no_args = lambda: func(*args, **kwargs)
|
| 657 |
+
time = do_bench_using_profiling(no_args)
|
| 658 |
+
return time * 1e3
|
| 659 |
+
|
| 660 |
+
MAX_NEW_TOKENS = 1000
|
| 661 |
+
print("int4wo-128 model:", benchmark_fn(quantized_model.generate, **input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation="static"))
|
| 662 |
+
|
| 663 |
+
bf16_model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype=torch.bfloat16)
|
| 664 |
+
output = bf16_model.generate(**input_ids, max_new_tokens=10, cache_implementation="static") # auto-compile
|
| 665 |
+
print("bf16 model:", benchmark_fn(bf16_model.generate, **input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation="static"))
|
| 666 |
+
```
|
| 667 |
+
|
| 668 |
+
> [!TIP]
|
| 669 |
+
> For best performance, you can use recommended settings by calling `torchao.quantization.utils.recommended_inductor_config_setter()`
|
| 670 |
+
|
| 671 |
+
Refer to [Other Available Quantization Techniques](https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques) for more examples and documentation.
|
| 672 |
+
|
| 673 |
+
## Issues
|
| 674 |
+
|
| 675 |
+
If you encounter any issues with the Transformers integration, please open an issue on the [Transformers](https://github.com/huggingface/transformers/issues) repository. For issues directly related to torchao, please open an issue on the [torchao](https://github.com/pytorch/ao/issues) repository.
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quantization/vptq.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# VPTQ
|
| 18 |
+
|
| 19 |
+
[Vector Post-Training Quantization (VPTQ)](https://github.com/microsoft/VPTQ) is a Post-Training Quantization (PTQ) method that leverages vector quantization to quantize LLMs at an extremely low bit-width (<2-bit). VPTQ can compress a 70B, even a 405B model, to 1-2 bits without retraining and still maintain a high-degree of accuracy. It is a lightweight quantization algorithm that takes ~17 hours to quantize a 405B model. VPTQ features agile quantization inference with low decoding overhead and high throughput and Time To First Token (TTFT).
|
| 20 |
+
|
| 21 |
+
Run the command below to install VPTQ which provides efficient kernels for inference on NVIDIA and AMD GPUs.
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
pip install vptq
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
The [VPTQ-community](https://huggingface.co/VPTQ-community) provides a collection of VPTQ-quantized models. The model name contains information about its bitwidth (excluding cookbook, parameter, and padding overhead). Consider the [Meta-Llama-3.1-70B-Instruct-v8-k65536-256-woft] model as an example.
|
| 28 |
+
|
| 29 |
+
- The model name is Meta-Llama-3.1-70B-Instruct.
|
| 30 |
+
- The number of centroids is given by 65536 (2^16).
|
| 31 |
+
- The number of residual centroids is given by 256 (2^8).
|
| 32 |
+
|
| 33 |
+
The equivalent bit-width calculation is given by the following.
|
| 34 |
+
|
| 35 |
+
- index: log2(65536) = 16 / 8 = 2-bits
|
| 36 |
+
- residual index: log2(256) = 8 / 8 = 1-bit
|
| 37 |
+
- total bit-width: 2 + 1 = 3-bits
|
| 38 |
+
|
| 39 |
+
From here, estimate the model size by multiplying 70B * 3-bits / 8-bits/byte for a total of 26.25GB.
|
| 40 |
+
|
| 41 |
+
Load a VPTQ quantized model with [`~PreTrainedModel.from_pretrained`].
|
| 42 |
+
|
| 43 |
+
```py
|
| 44 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 45 |
+
|
| 46 |
+
quantized_model = AutoModelForCausalLM.from_pretrained(
|
| 47 |
+
"VPTQ-community/Meta-Llama-3.1-70B-Instruct-v16-k65536-65536-woft",
|
| 48 |
+
torch_dtype="auto",
|
| 49 |
+
device_map="auto"
|
| 50 |
+
)
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
To quantize your own model, refer to the [VPTQ Quantization Algorithm Tutorial](https://github.com/microsoft/VPTQ/blob/algorithm/algorithm.md) tutorial.
|
| 54 |
+
|
| 55 |
+
## Benchmarks
|
| 56 |
+
|
| 57 |
+
VPTQ achieves better accuracy and higher throughput with lower quantization overhead across models of different sizes. The following experimental results are for reference only; VPTQ can achieve better outcomes under reasonable parameters, especially in terms of model accuracy and inference speed.
|
| 58 |
+
|
| 59 |
+
| Model | bitwidth | W2↓ | C4↓ | AvgQA↑ | tok/s↑ | mem(GB) | cost/h↓ |
|
| 60 |
+
| ----------- | -------- | ---- | ---- | ------ | ------ | ------- | ------- |
|
| 61 |
+
| LLaMA-2 7B | 2.02 | 6.13 | 8.07 | 58.2 | 39.9 | 2.28 | 2 |
|
| 62 |
+
| | 2.26 | 5.95 | 7.87 | 59.4 | 35.7 | 2.48 | 3.1 |
|
| 63 |
+
| LLaMA-2 13B | 2.02 | 5.32 | 7.15 | 62.4 | 26.9 | 4.03 | 3.2 |
|
| 64 |
+
| | 2.18 | 5.28 | 7.04 | 63.1 | 18.5 | 4.31 | 3.6 |
|
| 65 |
+
| LLaMA-2 70B | 2.07 | 3.93 | 5.72 | 68.6 | 9.7 | 19.54 | 19 |
|
| 66 |
+
| | 2.11 | 3.92 | 5.71 | 68.7 | 9.7 | 20.01 | 19 |
|
| 67 |
+
|
| 68 |
+
## Resources
|
| 69 |
+
|
| 70 |
+
See an example demo of VPTQ on the VPTQ Online Demo [Space](https://huggingface.co/spaces/microsoft/VPTQ) or try running the VPTQ inference [notebook](https://colab.research.google.com/github/microsoft/VPTQ/blob/main/notebooks/vptq_example.ipynb).
|
| 71 |
+
|
| 72 |
+
For more information, read the VPTQ [paper](https://huggingface.co/papers/2409.17066).
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/quicktour.md
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Quickstart
|
| 18 |
+
|
| 19 |
+
[[open-in-colab]]
|
| 20 |
+
|
| 21 |
+
Transformers is designed to be fast and easy to use so that everyone can start learning or building with transformer models.
|
| 22 |
+
|
| 23 |
+
The number of user-facing abstractions is limited to only three classes for instantiating a model, and two APIs for inference or training. This quickstart introduces you to Transformers' key features and shows you how to:
|
| 24 |
+
|
| 25 |
+
- load a pretrained model
|
| 26 |
+
- run inference with [`Pipeline`]
|
| 27 |
+
- fine-tune a model with [`Trainer`]
|
| 28 |
+
|
| 29 |
+
## Set up
|
| 30 |
+
|
| 31 |
+
To start, we recommend creating a Hugging Face [account](https://hf.co/join). An account lets you host and access version controlled models, datasets, and [Spaces](https://hf.co/spaces) on the Hugging Face [Hub](https://hf.co/docs/hub/index), a collaborative platform for discovery and building.
|
| 32 |
+
|
| 33 |
+
Create a [User Access Token](https://hf.co/docs/hub/security-tokens#user-access-tokens) and log in to your account.
|
| 34 |
+
|
| 35 |
+
<hfoptions id="authenticate">
|
| 36 |
+
<hfoption id="notebook">
|
| 37 |
+
|
| 38 |
+
Paste your User Access Token into [`~huggingface_hub.notebook_login`] when prompted to log in.
|
| 39 |
+
|
| 40 |
+
```py
|
| 41 |
+
from huggingface_hub import notebook_login
|
| 42 |
+
|
| 43 |
+
notebook_login()
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
</hfoption>
|
| 47 |
+
<hfoption id="CLI">
|
| 48 |
+
|
| 49 |
+
Make sure the [huggingface_hub[cli]](https://huggingface.co/docs/huggingface_hub/guides/cli#getting-started) package is installed and run the command below. Paste your User Access Token when prompted to log in.
|
| 50 |
+
|
| 51 |
+
```bash
|
| 52 |
+
hf auth login
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
</hfoption>
|
| 56 |
+
</hfoptions>
|
| 57 |
+
|
| 58 |
+
Install a machine learning framework.
|
| 59 |
+
|
| 60 |
+
<hfoptions id="installation">
|
| 61 |
+
<hfoption id="PyTorch">
|
| 62 |
+
|
| 63 |
+
```bash
|
| 64 |
+
!pip install torch
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
</hfoption>
|
| 68 |
+
<hfoption id="TensorFlow">
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
!pip install tensorflow
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
</hfoption>
|
| 75 |
+
</hfoptions>
|
| 76 |
+
|
| 77 |
+
Then install an up-to-date version of Transformers and some additional libraries from the Hugging Face ecosystem for accessing datasets and vision models, evaluating training, and optimizing training for large models.
|
| 78 |
+
|
| 79 |
+
```bash
|
| 80 |
+
!pip install -U transformers datasets evaluate accelerate timm
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
## Pretrained models
|
| 84 |
+
|
| 85 |
+
Each pretrained model inherits from three base classes.
|
| 86 |
+
|
| 87 |
+
| **Class** | **Description** |
|
| 88 |
+
|---|---|
|
| 89 |
+
| [`PretrainedConfig`] | A file that specifies a models attributes such as the number of attention heads or vocabulary size. |
|
| 90 |
+
| [`PreTrainedModel`] | A model (or architecture) defined by the model attributes from the configuration file. A pretrained model only returns the raw hidden states. For a specific task, use the appropriate model head to convert the raw hidden states into a meaningful result (for example, [`LlamaModel`] versus [`LlamaForCausalLM`]). |
|
| 91 |
+
| Preprocessor | A class for converting raw inputs (text, images, audio, multimodal) into numerical inputs to the model. For example, [`PreTrainedTokenizer`] converts text into tensors and [`ImageProcessingMixin`] converts pixels into tensors. |
|
| 92 |
+
|
| 93 |
+
We recommend using the [AutoClass](./model_doc/auto) API to load models and preprocessors because it automatically infers the appropriate architecture for each task and machine learning framework based on the name or path to the pretrained weights and configuration file.
|
| 94 |
+
|
| 95 |
+
Use [`~PreTrainedModel.from_pretrained`] to load the weights and configuration file from the Hub into the model and preprocessor class.
|
| 96 |
+
|
| 97 |
+
<hfoptions id="base-classes">
|
| 98 |
+
<hfoption id="PyTorch">
|
| 99 |
+
|
| 100 |
+
When you load a model, configure the following parameters to ensure the model is optimally loaded.
|
| 101 |
+
|
| 102 |
+
- `device_map="auto"` automatically allocates the model weights to your fastest device first.
|
| 103 |
+
- `torch_dtype="auto"` directly initializes the model weights in the data type they're stored in, which can help avoid loading the weights twice (PyTorch loads weights in `torch.float32` by default).
|
| 104 |
+
|
| 105 |
+
```py
|
| 106 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 107 |
+
|
| 108 |
+
model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf", torch_dtype="auto", device_map="auto")
|
| 109 |
+
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
Tokenize the text and return PyTorch tensors with the tokenizer. Move the model to an accelerator if it's available to accelerate inference.
|
| 113 |
+
|
| 114 |
+
```py
|
| 115 |
+
model_inputs = tokenizer(["The secret to baking a good cake is "], return_tensors="pt").to(model.device)
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
The model is now ready for inference or training.
|
| 119 |
+
|
| 120 |
+
For inference, pass the tokenized inputs to [`~GenerationMixin.generate`] to generate text. Decode the token ids back into text with [`~PreTrainedTokenizerBase.batch_decode`].
|
| 121 |
+
|
| 122 |
+
```py
|
| 123 |
+
generated_ids = model.generate(**model_inputs, max_length=30)
|
| 124 |
+
tokenizer.batch_decode(generated_ids)[0]
|
| 125 |
+
'<s> The secret to baking a good cake is 100% in the preparation. There are so many recipes out there,'
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
</hfoption>
|
| 129 |
+
<hfoption id="TensorFlow">
|
| 130 |
+
|
| 131 |
+
```py
|
| 132 |
+
from transformers import TFAutoModelForCausalLM, AutoTokenizer
|
| 133 |
+
|
| 134 |
+
model = TFAutoModelForCausalLM.from_pretrained("openai-community/gpt2-xl")
|
| 135 |
+
tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2-xl")
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
Tokenize the text and return TensorFlow tensors with the tokenizer.
|
| 139 |
+
|
| 140 |
+
```py
|
| 141 |
+
model_inputs = tokenizer(["The secret to baking a good cake is "], return_tensors="tf")
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
The model is now ready for inference or training.
|
| 145 |
+
|
| 146 |
+
For inference, pass the tokenized inputs to [`~GenerationMixin.generate`] to generate text. Decode the token ids back into text with [`~PreTrainedTokenizerBase.batch_decode`].
|
| 147 |
+
|
| 148 |
+
```py
|
| 149 |
+
generated_ids = model.generate(**model_inputs, max_length=30)
|
| 150 |
+
tokenizer.batch_decode(generated_ids)[0]
|
| 151 |
+
'The secret to baking a good cake is \xa0to use the right ingredients. \xa0The secret to baking a good cake is to use the right'
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
</hfoption>
|
| 155 |
+
</hfoptions>
|
| 156 |
+
|
| 157 |
+
> [!TIP]
|
| 158 |
+
> Skip ahead to the [Trainer](#trainer-api) section to learn how to fine-tune a model.
|
| 159 |
+
|
| 160 |
+
## Pipeline
|
| 161 |
+
|
| 162 |
+
The [`Pipeline`] class is the most convenient way to inference with a pretrained model. It supports many tasks such as text generation, image segmentation, automatic speech recognition, document question answering, and more.
|
| 163 |
+
|
| 164 |
+
> [!TIP]
|
| 165 |
+
> Refer to the [Pipeline](./main_classes/pipelines) API reference for a complete list of available tasks.
|
| 166 |
+
|
| 167 |
+
Create a [`Pipeline`] object and select a task. By default, [`Pipeline`] downloads and caches a default pretrained model for a given task. Pass the model name to the `model` parameter to choose a specific model.
|
| 168 |
+
|
| 169 |
+
<hfoptions id="pipeline-tasks">
|
| 170 |
+
<hfoption id="text generation">
|
| 171 |
+
|
| 172 |
+
Use [`~infer_device`] to automatically detect an available accelerator for inference.
|
| 173 |
+
|
| 174 |
+
```py
|
| 175 |
+
from transformers import pipeline, infer_device
|
| 176 |
+
|
| 177 |
+
device = infer_device()
|
| 178 |
+
|
| 179 |
+
pipeline = pipeline("text-generation", model="meta-llama/Llama-2-7b-hf", device=device)
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
Prompt [`Pipeline`] with some initial text to generate more text.
|
| 183 |
+
|
| 184 |
+
```py
|
| 185 |
+
pipeline("The secret to baking a good cake is ", max_length=50)
|
| 186 |
+
[{'generated_text': 'The secret to baking a good cake is 100% in the batter. The secret to a great cake is the icing.\nThis is why we’ve created the best buttercream frosting reci'}]
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
</hfoption>
|
| 190 |
+
<hfoption id="image segmentation">
|
| 191 |
+
|
| 192 |
+
Use [`~infer_device`] to automatically detect an available accelerator for inference.
|
| 193 |
+
|
| 194 |
+
```py
|
| 195 |
+
from transformers import pipeline, infer_device
|
| 196 |
+
|
| 197 |
+
device = infer_device()
|
| 198 |
+
|
| 199 |
+
pipeline = pipeline("image-segmentation", model="facebook/detr-resnet-50-panoptic", device=device)
|
| 200 |
+
```
|
| 201 |
+
|
| 202 |
+
Pass an image - a URL or local path to the image - to [`Pipeline`].
|
| 203 |
+
|
| 204 |
+
<div class="flex justify-center">
|
| 205 |
+
<img src="https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png"/>
|
| 206 |
+
</div>
|
| 207 |
+
|
| 208 |
+
```py
|
| 209 |
+
segments = pipeline("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
|
| 210 |
+
segments[0]["label"]
|
| 211 |
+
'bird'
|
| 212 |
+
segments[1]["label"]
|
| 213 |
+
'bird'
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
</hfoption>
|
| 217 |
+
<hfoption id="automatic speech recognition">
|
| 218 |
+
|
| 219 |
+
Use [`~infer_device`] to automatically detect an available accelerator for inference.
|
| 220 |
+
|
| 221 |
+
```py
|
| 222 |
+
from transformers import pipeline, infer_device
|
| 223 |
+
|
| 224 |
+
device = infer_device()
|
| 225 |
+
|
| 226 |
+
pipeline = pipeline("automatic-speech-recognition", model="openai/whisper-large-v3", device=device)
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
Pass an audio file to [`Pipeline`].
|
| 230 |
+
|
| 231 |
+
```py
|
| 232 |
+
pipeline("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
|
| 233 |
+
{'text': ' He hoped there would be stew for dinner, turnips and carrots and bruised potatoes and fat mutton pieces to be ladled out in thick, peppered flour-fatten sauce.'}
|
| 234 |
+
```
|
| 235 |
+
|
| 236 |
+
</hfoption>
|
| 237 |
+
</hfoptions>
|
| 238 |
+
|
| 239 |
+
## Trainer
|
| 240 |
+
|
| 241 |
+
[`Trainer`] is a complete training and evaluation loop for PyTorch models. It abstracts away a lot of the boilerplate usually involved in manually writing a training loop, so you can start training faster and focus on training design choices. You only need a model, dataset, a preprocessor, and a data collator to build batches of data from the dataset.
|
| 242 |
+
|
| 243 |
+
Use the [`TrainingArguments`] class to customize the training process. It provides many options for training, evaluation, and more. Experiment with training hyperparameters and features like batch size, learning rate, mixed precision, torch.compile, and more to meet your training needs. You could also use the default training parameters to quickly produce a baseline.
|
| 244 |
+
|
| 245 |
+
Load a model, tokenizer, and dataset for training.
|
| 246 |
+
|
| 247 |
+
```py
|
| 248 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 249 |
+
from datasets import load_dataset
|
| 250 |
+
|
| 251 |
+
model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
|
| 252 |
+
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
|
| 253 |
+
dataset = load_dataset("rotten_tomatoes")
|
| 254 |
+
```
|
| 255 |
+
|
| 256 |
+
Create a function to tokenize the text and convert it into PyTorch tensors. Apply this function to the whole dataset with the [`~datasets.Dataset.map`] method.
|
| 257 |
+
|
| 258 |
+
```py
|
| 259 |
+
def tokenize_dataset(dataset):
|
| 260 |
+
return tokenizer(dataset["text"])
|
| 261 |
+
dataset = dataset.map(tokenize_dataset, batched=True)
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
Load a data collator to create batches of data and pass the tokenizer to it.
|
| 265 |
+
|
| 266 |
+
```py
|
| 267 |
+
from transformers import DataCollatorWithPadding
|
| 268 |
+
|
| 269 |
+
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
|
| 270 |
+
```
|
| 271 |
+
|
| 272 |
+
Next, set up [`TrainingArguments`] with the training features and hyperparameters.
|
| 273 |
+
|
| 274 |
+
```py
|
| 275 |
+
from transformers import TrainingArguments
|
| 276 |
+
|
| 277 |
+
training_args = TrainingArguments(
|
| 278 |
+
output_dir="distilbert-rotten-tomatoes",
|
| 279 |
+
learning_rate=2e-5,
|
| 280 |
+
per_device_train_batch_size=8,
|
| 281 |
+
per_device_eval_batch_size=8,
|
| 282 |
+
num_train_epochs=2,
|
| 283 |
+
push_to_hub=True,
|
| 284 |
+
)
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
Finally, pass all these separate components to [`Trainer`] and call [`~Trainer.train`] to start.
|
| 288 |
+
|
| 289 |
+
```py
|
| 290 |
+
from transformers import Trainer
|
| 291 |
+
|
| 292 |
+
trainer = Trainer(
|
| 293 |
+
model=model,
|
| 294 |
+
args=training_args,
|
| 295 |
+
train_dataset=dataset["train"],
|
| 296 |
+
eval_dataset=dataset["test"],
|
| 297 |
+
tokenizer=tokenizer,
|
| 298 |
+
data_collator=data_collator,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
trainer.train()
|
| 302 |
+
```
|
| 303 |
+
|
| 304 |
+
Share your model and tokenizer to the Hub with [`~Trainer.push_to_hub`].
|
| 305 |
+
|
| 306 |
+
```py
|
| 307 |
+
trainer.push_to_hub()
|
| 308 |
+
```
|
| 309 |
+
|
| 310 |
+
Congratulations, you just trained your first model with Transformers!
|
| 311 |
+
|
| 312 |
+
### TensorFlow
|
| 313 |
+
|
| 314 |
+
> [!WARNING]
|
| 315 |
+
> Not all pretrained models are available in TensorFlow. Refer to a models API doc to check whether a TensorFlow implementation is supported.
|
| 316 |
+
|
| 317 |
+
[`Trainer`] doesn't work with TensorFlow models, but you can still train a Transformers model implemented in TensorFlow with [Keras](https://keras.io/). Transformers TensorFlow models are a standard [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model), which is compatible with Keras' [compile](https://keras.io/api/models/model_training_apis/#compile-method) and [fit](https://keras.io/api/models/model_training_apis/#fit-method) methods.
|
| 318 |
+
|
| 319 |
+
Load a model, tokenizer, and dataset for training.
|
| 320 |
+
|
| 321 |
+
```py
|
| 322 |
+
from transformers import TFAutoModelForSequenceClassification, AutoTokenizer
|
| 323 |
+
|
| 324 |
+
model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased")
|
| 325 |
+
tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")
|
| 326 |
+
```
|
| 327 |
+
|
| 328 |
+
Create a function to tokenize the text and convert it into TensorFlow tensors. Apply this function to the whole dataset with the [`~datasets.Dataset.map`] method.
|
| 329 |
+
|
| 330 |
+
```py
|
| 331 |
+
def tokenize_dataset(dataset):
|
| 332 |
+
return tokenizer(dataset["text"])
|
| 333 |
+
dataset = dataset.map(tokenize_dataset)
|
| 334 |
+
```
|
| 335 |
+
|
| 336 |
+
Transformers provides the [`~TFPreTrainedModel.prepare_tf_dataset`] method to collate and batch a dataset.
|
| 337 |
+
|
| 338 |
+
```py
|
| 339 |
+
tf_dataset = model.prepare_tf_dataset(
|
| 340 |
+
dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer
|
| 341 |
+
)
|
| 342 |
+
```
|
| 343 |
+
|
| 344 |
+
Finally, call [compile](https://keras.io/api/models/model_training_apis/#compile-method) to configure the model for training and [fit](https://keras.io/api/models/model_training_apis/#fit-method) to start.
|
| 345 |
+
|
| 346 |
+
```py
|
| 347 |
+
from tensorflow.keras.optimizers import Adam
|
| 348 |
+
|
| 349 |
+
model.compile(optimizer="adam")
|
| 350 |
+
model.fit(tf_dataset)
|
| 351 |
+
```
|
| 352 |
+
|
| 353 |
+
## Next steps
|
| 354 |
+
|
| 355 |
+
Now that you have a better understanding of Transformers and what it offers, it's time to keep exploring and learning what interests you the most.
|
| 356 |
+
|
| 357 |
+
- **Base classes**: Learn more about the configuration, model and processor classes. This will help you understand how to create and customize models, preprocess different types of inputs (audio, images, multimodal), and how to share your model.
|
| 358 |
+
- **Inference**: Explore the [`Pipeline`] further, inference and chatting with LLMs, agents, and how to optimize inference with your machine learning framework and hardware.
|
| 359 |
+
- **Training**: Study the [`Trainer`] in more detail, as well as distributed training and optimizing training on specific hardware.
|
| 360 |
+
- **Quantization**: Reduce memory and storage requirements with quantization and speed up inference by representing weights with fewer bits.
|
| 361 |
+
- **Resources**: Looking for end-to-end recipes for how to train and inference with a model for a specific task? Check out the task recipes!
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/reference/environment_variables.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 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 |
+
|
| 17 |
+
# Environment Variables
|
| 18 |
+
|
| 19 |
+
## HF_ENABLE_PARALLEL_LOADING
|
| 20 |
+
|
| 21 |
+
By default this is disabled. Enables the loading of torch and safetensor based weights to be loaded in parallel. Can decrease the time to load large models significantly, often times producing speed ups around ~50%.
|
| 22 |
+
|
| 23 |
+
Can be set to a string equal to `"false"` or `"true"`. e.g. `os.environ["HF_ENABLE_PARALLEL_LOADING"] = "true"`.
|
| 24 |
+
|
| 25 |
+
e.g. `facebook/opt-30b` on an AWS EC2 g4dn.metal instance can be made to load in ~30s with this enabled vs ~55s without it.
|
| 26 |
+
|
| 27 |
+
Profile before committing to using this environment variable, this will not produce speed ups for smaller models.
|
| 28 |
+
|
| 29 |
+
```py
|
| 30 |
+
import os
|
| 31 |
+
|
| 32 |
+
os.environ["HF_ENABLE_PARALLEL_LOADING"] = "true"
|
| 33 |
+
|
| 34 |
+
from transformers import pipeline
|
| 35 |
+
|
| 36 |
+
model = pipeline(task="text-generation", model="facebook/opt-30b", device_map="auto")
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
## HF_PARALLEL_LOADING_WORKERS
|
| 40 |
+
|
| 41 |
+
Determines how many threads should be used when parallel loading is enabled. Default is `8`.
|
| 42 |
+
|
| 43 |
+
If the number of files that are being loaded is less than the number of threads specified, the number that is actually spawned will be equal to the number of files.
|
| 44 |
+
|
| 45 |
+
e.g. If you specify 8 workers, and there are only 2 files, only 2 workers will be spawned.
|
| 46 |
+
|
| 47 |
+
Tune as you see fit.
|
| 48 |
+
|
| 49 |
+
```py
|
| 50 |
+
import os
|
| 51 |
+
|
| 52 |
+
os.environ["HF_ENABLE_PARALLEL_LOADING"] = "true"
|
| 53 |
+
os.environ["HF_PARALLEL_LOADING_WORKERS"] = "4"
|
| 54 |
+
|
| 55 |
+
from transformers import pipeline
|
| 56 |
+
|
| 57 |
+
model = pipeline(task="text-generation", model="facebook/opt-30b", device_map="auto")
|
| 58 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/run_scripts.md
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 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 |
+
|
| 17 |
+
# Training scripts
|
| 18 |
+
|
| 19 |
+
Transformers provides many example training scripts for deep learning frameworks (PyTorch, TensorFlow, Flax) and tasks in [transformers/examples](https://github.com/huggingface/transformers/tree/main/examples). There are additional scripts in [transformers/research projects](https://github.com/huggingface/transformers-research-projects/) and [transformers/legacy](https://github.com/huggingface/transformers/tree/main/examples/legacy), but these aren't actively maintained and requires a specific version of Transformers.
|
| 20 |
+
|
| 21 |
+
Example scripts are only examples and you may need to adapt the script to your use-case. To help you with this, most scripts are very transparent in how data is preprocessed, allowing you to edit it as necessary.
|
| 22 |
+
|
| 23 |
+
For any feature you'd like to implement in an example script, please discuss it on the [forum](https://discuss.huggingface.co/) or in an [issue](https://github.com/huggingface/transformers/issues) before submitting a pull request. While we welcome contributions, it is unlikely a pull request that adds more functionality is added at the cost of readability.
|
| 24 |
+
|
| 25 |
+
This guide will show you how to run an example summarization training script in [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch/summarization) and [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/summarization).
|
| 26 |
+
|
| 27 |
+
## Setup
|
| 28 |
+
|
| 29 |
+
Install Transformers from source in a new virtual environment to run the latest version of the example script.
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
git clone https://github.com/huggingface/transformers
|
| 33 |
+
cd transformers
|
| 34 |
+
pip install .
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
Run the command below to checkout a script from a specific or older version of Transformers.
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
git checkout tags/v3.5.1
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
After you've setup the correct version, navigate to the example folder of your choice and install the example specific requirements.
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
pip install -r requirements.txt
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
## Run a script
|
| 50 |
+
|
| 51 |
+
Start with a smaller dataset by including the `max_train_samples`, `max_eval_samples`, and `max_predict_samples` parameters to truncate the dataset to a maximum number of samples. This helps ensure training works as expected before committing to the entire dataset which can take hours to complete.
|
| 52 |
+
|
| 53 |
+
> [!WARNING]
|
| 54 |
+
> Not all example scripts support the `max_predict_samples` parameter. Run the command below to check whether a script supports it or not.
|
| 55 |
+
> ```bash
|
| 56 |
+
> examples/pytorch/summarization/run_summarization.py -h
|
| 57 |
+
> ```
|
| 58 |
+
|
| 59 |
+
The example below fine-tunes [T5-small](https://huggingface.co/google-t5/t5-small) on the [CNN/DailyMail](https://huggingface.co/datasets/abisee/cnn_dailymail) dataset. T5 requires an additional `source_prefix` parameter to prompt it to summarize.
|
| 60 |
+
|
| 61 |
+
<hfoptions id="script">
|
| 62 |
+
<hfoption id="PyTorch">
|
| 63 |
+
|
| 64 |
+
The example script downloads and preprocesses a dataset, and then fine-tunes it with [`Trainer`] with a supported model architecture.
|
| 65 |
+
|
| 66 |
+
Resuming training from a checkpoint is very useful if training is interrupted because you don't have to start over again. There are two ways to resume training from a checkpoint.
|
| 67 |
+
|
| 68 |
+
* `--output dir previous_output_dir` resumes training from the latest checkpoint stored in `output_dir`. Remove the `--overwrite_output_dir` parameter if you're using this method.
|
| 69 |
+
* `--resume_from_checkpoint path_to_specific_checkpoint` resumes training from a specific checkpoint folder.
|
| 70 |
+
|
| 71 |
+
Share your model on the [Hub](https://huggingface.co/) with the `--push_to_hub` parameter. It creates a repository and uploads the model to the folder name specified in `--output_dir`. You could also use the `--push_to_hub_model_id` parameter to specify the repository name.
|
| 72 |
+
|
| 73 |
+
```bash
|
| 74 |
+
python examples/pytorch/summarization/run_summarization.py \
|
| 75 |
+
--model_name_or_path google-t5/t5-small \
|
| 76 |
+
# remove the `max_train_samples`, `max_eval_samples` and `max_predict_samples` if everything works
|
| 77 |
+
--max_train_samples 50 \
|
| 78 |
+
--max_eval_samples 50 \
|
| 79 |
+
--max_predict_samples 50 \
|
| 80 |
+
--do_train \
|
| 81 |
+
--do_eval \
|
| 82 |
+
--dataset_name cnn_dailymail \
|
| 83 |
+
--dataset_config "3.0.0" \
|
| 84 |
+
--source_prefix "summarize: " \
|
| 85 |
+
--output_dir /tmp/tst-summarization \
|
| 86 |
+
--per_device_train_batch_size=4 \
|
| 87 |
+
--per_device_eval_batch_size=4 \
|
| 88 |
+
--push_to_hub \
|
| 89 |
+
--push_to_hub_model_id finetuned-t5-cnn_dailymail \
|
| 90 |
+
# remove if using `output_dir previous_output_dir`
|
| 91 |
+
# --overwrite_output_dir \
|
| 92 |
+
--output_dir previous_output_dir \
|
| 93 |
+
# --resume_from_checkpoint path_to_specific_checkpoint \
|
| 94 |
+
--predict_with_generate \
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
For mixed precision and distributed training, include the following parameters and launch training with [torchrun](https://pytorch.org/docs/stable/elastic/run.html).
|
| 98 |
+
|
| 99 |
+
* Add the `fp16` or `bf16` parameters to enable mixed precision training. XPU devices only supports `bf16`.
|
| 100 |
+
* Add the `nproc_per_node` parameter to set number of GPUs to train with.
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
torchrun \
|
| 104 |
+
--nproc_per_node 8 pytorch/summarization/run_summarization.py \
|
| 105 |
+
--fp16 \
|
| 106 |
+
...
|
| 107 |
+
...
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
PyTorch supports TPUs, hardware designed to accelerate performance, through the [PyTorch/XLA](https://github.com/pytorch/xla/blob/master/README.md) package. Launch the `xla_spawn.py` script and use `num _cores` to set the number of TPU cores to train with.
|
| 111 |
+
|
| 112 |
+
```bash
|
| 113 |
+
python xla_spawn.py --num_cores 8 pytorch/summarization/run_summarization.py \
|
| 114 |
+
--model_name_or_path google-t5/t5-small \
|
| 115 |
+
...
|
| 116 |
+
...
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
</hfoption>
|
| 120 |
+
<hfoption id="TensorFlow">
|
| 121 |
+
|
| 122 |
+
```bash
|
| 123 |
+
python examples/tensorflow/summarization/run_summarization.py \
|
| 124 |
+
--model_name_or_path google-t5/t5-small \
|
| 125 |
+
# remove the `max_train_samples`, `max_eval_samples` and `max_predict_samples` if everything works
|
| 126 |
+
--max_train_samples 50 \
|
| 127 |
+
--max_eval_samples 50 \
|
| 128 |
+
--max_predict_samples 50 \
|
| 129 |
+
--dataset_name cnn_dailymail \
|
| 130 |
+
--dataset_config "3.0.0" \
|
| 131 |
+
--output_dir /tmp/tst-summarization \
|
| 132 |
+
--per_device_train_batch_size 8 \
|
| 133 |
+
--per_device_eval_batch_size 16 \
|
| 134 |
+
--num_train_epochs 3 \
|
| 135 |
+
--do_train \
|
| 136 |
+
--do_eval \
|
| 137 |
+
```
|
| 138 |
+
|
| 139 |
+
TensorFlow uses the [MirroredStrategy](https://www.tensorflow.org/guide/distributed_training#mirroredstrategy) for distributed training and doesn't require adding any additional parameters. The script uses multiple GPUs by default if they are available.
|
| 140 |
+
|
| 141 |
+
For TPU training, TensorFlow scripts use the [TPUStrategy](https://www.tensorflow.org/guide/distributed_training#tpustrategy). Pass the TPU resource name to the `--tpu` parameter.
|
| 142 |
+
|
| 143 |
+
```bash
|
| 144 |
+
python run_summarization.py \
|
| 145 |
+
--tpu name_of_tpu_resource \
|
| 146 |
+
...
|
| 147 |
+
...
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
</hfoption>
|
| 151 |
+
</hfoptions>
|
| 152 |
+
|
| 153 |
+
## Accelerate
|
| 154 |
+
|
| 155 |
+
[Accelerate](https://huggingface.co/docs/accelerate) is designed to simplify distributed training while offering complete visibility into the PyTorch training loop. If you're planning on training with a script with Accelerate, use the `_no_trainer.py` version of the script.
|
| 156 |
+
|
| 157 |
+
Install Accelerate from source to ensure you have the latest version.
|
| 158 |
+
|
| 159 |
+
```bash
|
| 160 |
+
pip install git+https://github.com/huggingface/accelerate
|
| 161 |
+
```
|
| 162 |
+
|
| 163 |
+
Run the [accelerate config](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-config) command to answer a few questions about your training setup. This creates and saves a config file about your system.
|
| 164 |
+
|
| 165 |
+
```bash
|
| 166 |
+
accelerate config
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
You can use [accelerate test](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-test) to ensure your system is properly configured.
|
| 170 |
+
|
| 171 |
+
```bash
|
| 172 |
+
accelerate test
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
Run [accelerate launch](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-launch) to start training.
|
| 176 |
+
|
| 177 |
+
```bash
|
| 178 |
+
accelerate launch run_summarization_no_trainer.py \
|
| 179 |
+
--model_name_or_path google-t5/t5-small \
|
| 180 |
+
--dataset_name cnn_dailymail \
|
| 181 |
+
--dataset_config "3.0.0" \
|
| 182 |
+
--source_prefix "summarize: " \
|
| 183 |
+
--output_dir ~/tmp/tst-summarization \
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
## Custom dataset
|
| 187 |
+
|
| 188 |
+
The summarization scripts supports custom datasets as long as they are a CSV or JSONL file. When using your own dataset, you need to specify the following additional parameters.
|
| 189 |
+
|
| 190 |
+
* `train_file` and `validation_file` specify the path to your training and validation files.
|
| 191 |
+
* `text_column` is the input text to summarize.
|
| 192 |
+
* `summary_column` is the target text to output.
|
| 193 |
+
|
| 194 |
+
An example command for summarizing a custom dataset is shown below.
|
| 195 |
+
|
| 196 |
+
```bash
|
| 197 |
+
python examples/pytorch/summarization/run_summarization.py \
|
| 198 |
+
--model_name_or_path google-t5/t5-small \
|
| 199 |
+
--do_train \
|
| 200 |
+
--do_eval \
|
| 201 |
+
--train_file path_to_csv_or_jsonlines_file \
|
| 202 |
+
--validation_file path_to_csv_or_jsonlines_file \
|
| 203 |
+
--text_column text_column_name \
|
| 204 |
+
--summary_column summary_column_name \
|
| 205 |
+
--source_prefix "summarize: " \
|
| 206 |
+
--output_dir /tmp/tst-summarization \
|
| 207 |
+
--overwrite_output_dir \
|
| 208 |
+
--per_device_train_batch_size=4 \
|
| 209 |
+
--per_device_eval_batch_size=4 \
|
| 210 |
+
--predict_with_generate \
|
| 211 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/serialization.md
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2020 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 |
+
|
| 17 |
+
# ONNX
|
| 18 |
+
|
| 19 |
+
[ONNX](http://onnx.ai) is an open standard that defines a common set of operators and a file format to represent deep learning models in different frameworks, including PyTorch and TensorFlow. When a model is exported to ONNX, the operators construct a computational graph (or *intermediate representation*) which represents the flow of data through the model. Standardized operators and data types makes it easy to switch between frameworks.
|
| 20 |
+
|
| 21 |
+
The [Optimum](https://huggingface.co/docs/optimum/index) library exports a model to ONNX with configuration objects which are supported for [many architectures](https://huggingface.co/docs/optimum/exporters/onnx/overview) and can be easily extended. If a model isn't supported, feel free to make a [contribution](https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/contribute) to Optimum.
|
| 22 |
+
|
| 23 |
+
The benefits of exporting to ONNX include the following.
|
| 24 |
+
|
| 25 |
+
- [Graph optimization](https://huggingface.co/docs/optimum/onnxruntime/usage_guides/optimization) and [quantization](https://huggingface.co/docs/optimum/onnxruntime/usage_guides/quantization) for improving inference.
|
| 26 |
+
- Use the [`~optimum.onnxruntime.ORTModel`] API to run a model with [ONNX Runtime](https://onnxruntime.ai/).
|
| 27 |
+
- Use [optimized inference pipelines](https://huggingface.co/docs/optimum/main/en/onnxruntime/usage_guides/pipelines) for ONNX models.
|
| 28 |
+
|
| 29 |
+
Export a Transformers model to ONNX with the Optimum CLI or the `optimum.onnxruntime` module.
|
| 30 |
+
|
| 31 |
+
## Optimum CLI
|
| 32 |
+
|
| 33 |
+
Run the command below to install Optimum and the [exporters](https://huggingface.co/docs/optimum/exporters/overview) module.
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
pip install optimum[exporters]
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
> [!TIP]
|
| 40 |
+
> Refer to the [Export a model to ONNX with optimum.exporters.onnx](https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model#exporting-a-model-to-onnx-using-the-cli) guide for all available arguments or with the command below.
|
| 41 |
+
> ```bash
|
| 42 |
+
> optimum-cli export onnx --help
|
| 43 |
+
> ```
|
| 44 |
+
|
| 45 |
+
Set the `--model` argument to export a PyTorch or TensorFlow model from the Hub.
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
optimum-cli export onnx --model distilbert/distilbert-base-uncased-distilled-squad distilbert_base_uncased_squad_onnx/
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
You should see logs indicating the progress and showing where the resulting `model.onnx` is saved.
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
Validating ONNX model distilbert_base_uncased_squad_onnx/model.onnx...
|
| 55 |
+
-[✓] ONNX model output names match reference model (start_logits, end_logits)
|
| 56 |
+
- Validating ONNX Model output "start_logits":
|
| 57 |
+
-[✓] (2, 16) matches (2, 16)
|
| 58 |
+
-[✓] all values close (atol: 0.0001)
|
| 59 |
+
- Validating ONNX Model output "end_logits":
|
| 60 |
+
-[✓] (2, 16) matches (2, 16)
|
| 61 |
+
-[✓] all values close (atol: 0.0001)
|
| 62 |
+
The ONNX export succeeded and the exported model was saved at: distilbert_base_uncased_squad_onnx
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
For local models, make sure the model weights and tokenizer files are saved in the same directory, for example `local_path`. Pass the directory to the `--model` argument and use `--task` to indicate the [task](https://huggingface.co/docs/optimum/exporters/task_manager) a model can perform. If `--task` isn't provided, the model architecture without a task-specific head is used.
|
| 66 |
+
|
| 67 |
+
```bash
|
| 68 |
+
optimum-cli export onnx --model local_path --task question-answering distilbert_base_uncased_squad_onnx/
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
The `model.onnx` file can be deployed with any [accelerator](https://onnx.ai/supported-tools.html#deployModel) that supports ONNX. The example below demonstrates loading and running a model with ONNX Runtime.
|
| 72 |
+
|
| 73 |
+
```python
|
| 74 |
+
>>> from transformers import AutoTokenizer
|
| 75 |
+
>>> from optimum.onnxruntime import ORTModelForQuestionAnswering
|
| 76 |
+
|
| 77 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert_base_uncased_squad_onnx")
|
| 78 |
+
>>> model = ORTModelForQuestionAnswering.from_pretrained("distilbert_base_uncased_squad_onnx")
|
| 79 |
+
>>> inputs = tokenizer("What am I using?", "Using DistilBERT with ONNX Runtime!", return_tensors="pt")
|
| 80 |
+
>>> outputs = model(**inputs)
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
## optimum.onnxruntime
|
| 84 |
+
|
| 85 |
+
The `optimum.onnxruntime` module supports programmatically exporting a Transformers model. Instantiate a [`~optimum.onnxruntime.ORTModel`] for a task and set `export=True`. Use [`~OptimizedModel.save_pretrained`] to save the ONNX model.
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
>>> from optimum.onnxruntime import ORTModelForSequenceClassification
|
| 89 |
+
>>> from transformers import AutoTokenizer
|
| 90 |
+
|
| 91 |
+
>>> model_checkpoint = "distilbert/distilbert-base-uncased-distilled-squad"
|
| 92 |
+
>>> save_directory = "onnx/"
|
| 93 |
+
|
| 94 |
+
>>> ort_model = ORTModelForSequenceClassification.from_pretrained(model_checkpoint, export=True)
|
| 95 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
|
| 96 |
+
|
| 97 |
+
>>> ort_model.save_pretrained(save_directory)
|
| 98 |
+
>>> tokenizer.save_pretrained(save_directory)
|
| 99 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/serving.md
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2025 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 |
+
|
| 17 |
+
# Serving
|
| 18 |
+
|
| 19 |
+
Transformer models can be efficiently deployed using libraries such as vLLM, Text Generation Inference (TGI), and others. These libraries are designed for production-grade user-facing services, and can scale to multiple servers and millions of concurrent users. Refer to [Transformers as Backend for Inference Servers](./transformers_as_backends) for usage examples.
|
| 20 |
+
|
| 21 |
+
> [!TIP]
|
| 22 |
+
> Responses API is now supported as an experimental API! Read more about it [here](#responses-api).
|
| 23 |
+
|
| 24 |
+
Apart from that you can also serve transformer models easily using the `transformers serve` CLI. This is ideal for experimentation purposes, or to run models locally for personal and private use.
|
| 25 |
+
|
| 26 |
+
In this document, we dive into the different supported endpoints and modalities; we also cover the setup of several user interfaces that can be used on top of `transformers serve` in the following guides:
|
| 27 |
+
- [Jan (text and MCP user interface)](./jan.md)
|
| 28 |
+
- [Cursor (IDE)](./cursor.md)
|
| 29 |
+
- [Open WebUI (text, image, speech user interface)](./open_webui.md)
|
| 30 |
+
- [Tiny-Agents (text and MCP CLI tool)](./tiny_agents.md)
|
| 31 |
+
|
| 32 |
+
## Serve CLI
|
| 33 |
+
|
| 34 |
+
> [!WARNING]
|
| 35 |
+
> This section is experimental and subject to change in future versions
|
| 36 |
+
|
| 37 |
+
You can serve models of diverse modalities supported by `transformers` with the `transformers serve` CLI. It spawns a local server that offers compatibility with the OpenAI SDK, which is the _de facto_ standard for LLM conversations and other related tasks. This way, you can use the server from many third party applications, or test it using the `transformers chat` CLI ([docs](conversations.md#chat-cli)).
|
| 38 |
+
|
| 39 |
+
The server supports the following REST APIs:
|
| 40 |
+
- `/v1/chat/completions`
|
| 41 |
+
- `/v1/responses`
|
| 42 |
+
- `/v1/audio/transcriptions`
|
| 43 |
+
- `/v1/models`
|
| 44 |
+
|
| 45 |
+
To launch a server, simply use the `transformers serve` CLI command:
|
| 46 |
+
|
| 47 |
+
```shell
|
| 48 |
+
transformers serve
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
The simplest way to interact with the server is through our `transformers chat` CLI
|
| 52 |
+
|
| 53 |
+
```shell
|
| 54 |
+
transformers chat localhost:8000 --model-name-or-path Qwen/Qwen3-4B
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
or by sending an HTTP request, like we'll see below.
|
| 58 |
+
|
| 59 |
+
## Chat Completions - text-based
|
| 60 |
+
|
| 61 |
+
See below for examples for text-based requests. Both LLMs and VLMs should handle
|
| 62 |
+
|
| 63 |
+
<hfoptions id="chat-completion-http">
|
| 64 |
+
<hfoption id="curl">
|
| 65 |
+
|
| 66 |
+
```shell
|
| 67 |
+
curl -X POST http://localhost:8000/v1/chat/completions -H "Content-Type: application/json" -d '{"messages": [{"role": "system", "content": "hello"}], "temperature": 0.9, "max_tokens": 1000, "stream": true, "model": "Qwen/Qwen2.5-0.5B-Instruct"}'
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
from which you'll receive multiple chunks in the Completions API format
|
| 71 |
+
|
| 72 |
+
```shell
|
| 73 |
+
data: {"object": "chat.completion.chunk", "id": "req_0", "created": 1751377863, "model": "Qwen/Qwen2.5-0.5B-Instruct", "system_fingerprint": "", "choices": [{"delta": {"role": "assistant", "content": "", "tool_call_id": null, "tool_calls": null}, "index": 0, "finish_reason": null, "logprobs": null}]}
|
| 74 |
+
|
| 75 |
+
data: {"object": "chat.completion.chunk", "id": "req_0", "created": 1751377863, "model": "Qwen/Qwen2.5-0.5B-Instruct", "system_fingerprint": "", "choices": [{"delta": {"role": "assistant", "content": "", "tool_call_id": null, "tool_calls": null}, "index": 0, "finish_reason": null, "logprobs": null}]}
|
| 76 |
+
|
| 77 |
+
(...)
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
</hfoption>
|
| 81 |
+
<hfoption id="python - huggingface_hub">
|
| 82 |
+
|
| 83 |
+
```python
|
| 84 |
+
import asyncio
|
| 85 |
+
from huggingface_hub import AsyncInferenceClient
|
| 86 |
+
|
| 87 |
+
messages = [{"role": "user", "content": "What is the Transformers library known for?"}]
|
| 88 |
+
client = AsyncInferenceClient("http://localhost:8000")
|
| 89 |
+
|
| 90 |
+
async def responses_api_test_async():
|
| 91 |
+
async for chunk in (await client.chat_completion(messages, model="Qwen/Qwen2.5-0.5B-Instruct", max_tokens=256, stream=True)):
|
| 92 |
+
token = chunk.choices[0].delta.content
|
| 93 |
+
if token:
|
| 94 |
+
print(token, end='')
|
| 95 |
+
|
| 96 |
+
asyncio.run(responses_api_test_async())
|
| 97 |
+
asyncio.run(client.close())
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
From which you should get an iterative string printed:
|
| 101 |
+
|
| 102 |
+
```shell
|
| 103 |
+
The Transformers library is primarily known for its ability to create and manipulate large-scale language models [...]
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
</hfoption>
|
| 107 |
+
<hfoption id="python - openai">
|
| 108 |
+
|
| 109 |
+
```python
|
| 110 |
+
from openai import OpenAI
|
| 111 |
+
|
| 112 |
+
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
|
| 113 |
+
|
| 114 |
+
completion = client.chat.completions.create(
|
| 115 |
+
model="Qwen/Qwen2.5-0.5B-Instruct",
|
| 116 |
+
messages=[
|
| 117 |
+
{
|
| 118 |
+
"role": "user",
|
| 119 |
+
"content": "What is the Transformers library known for?"
|
| 120 |
+
}
|
| 121 |
+
],
|
| 122 |
+
stream=True
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
for chunk in completion:
|
| 126 |
+
token = chunk.choices[0].delta.content
|
| 127 |
+
if token:
|
| 128 |
+
print(token, end='')
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
From which you should get an iterative string printed:
|
| 132 |
+
|
| 133 |
+
```shell
|
| 134 |
+
The Transformers library is primarily known for its ability to create and manipulate large-scale language models [...]
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
</hfoption>
|
| 138 |
+
</hfoptions>
|
| 139 |
+
|
| 140 |
+
## Chat Completions - VLMs
|
| 141 |
+
|
| 142 |
+
The Chat Completion API also supports images; see below for examples for text-and-image-based requests.
|
| 143 |
+
|
| 144 |
+
<hfoptions id="chat-completion-http-images">
|
| 145 |
+
<hfoption id="curl">
|
| 146 |
+
|
| 147 |
+
```shell
|
| 148 |
+
curl http://localhost:8000/v1/chat/completions \
|
| 149 |
+
-H "Content-Type: application/json" \
|
| 150 |
+
-d '{
|
| 151 |
+
"model": "Qwen/Qwen2.5-VL-7B-Instruct",
|
| 152 |
+
"stream": true,
|
| 153 |
+
"messages": [
|
| 154 |
+
{
|
| 155 |
+
"role": "user",
|
| 156 |
+
"content": [
|
| 157 |
+
{
|
| 158 |
+
"type": "text",
|
| 159 |
+
"text": "What is in this image?"
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"type": "image_url",
|
| 163 |
+
"image_url": {
|
| 164 |
+
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
|
| 165 |
+
}
|
| 166 |
+
}
|
| 167 |
+
]
|
| 168 |
+
}
|
| 169 |
+
],
|
| 170 |
+
"max_tokens": 300
|
| 171 |
+
}'
|
| 172 |
+
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
from which you'll receive multiple chunks in the Completions API format
|
| 176 |
+
|
| 177 |
+
```shell
|
| 178 |
+
data: {"id":"req_0","choices":[{"delta":{"role":"assistant"},"index":0}],"created":1753366665,"model":"Qwen/Qwen2.5-VL-7B-Instruct@main","object":"chat.completion.chunk","system_fingerprint":""}
|
| 179 |
+
|
| 180 |
+
data: {"id":"req_0","choices":[{"delta":{"content":"The "},"index":0}],"created":1753366701,"model":"Qwen/Qwen2.5-VL-7B-Instruct@main","object":"chat.completion.chunk","system_fingerprint":""}
|
| 181 |
+
|
| 182 |
+
data: {"id":"req_0","choices":[{"delta":{"content":"image "},"index":0}],"created":1753366701,"model":"Qwen/Qwen2.5-VL-7B-Instruct@main","object":"chat.completion.chunk","system_fingerprint":""}
|
| 183 |
+
```
|
| 184 |
+
|
| 185 |
+
</hfoption>
|
| 186 |
+
<hfoption id="python - huggingface_hub">
|
| 187 |
+
|
| 188 |
+
```python
|
| 189 |
+
import asyncio
|
| 190 |
+
from huggingface_hub import AsyncInferenceClient
|
| 191 |
+
|
| 192 |
+
messages = [
|
| 193 |
+
{
|
| 194 |
+
"role": "user",
|
| 195 |
+
"content": [
|
| 196 |
+
{"type": "text", "text": "What's in this image?"},
|
| 197 |
+
{
|
| 198 |
+
"type": "image_url",
|
| 199 |
+
"image_url": {
|
| 200 |
+
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg",
|
| 201 |
+
}
|
| 202 |
+
},
|
| 203 |
+
],
|
| 204 |
+
}
|
| 205 |
+
]
|
| 206 |
+
client = AsyncInferenceClient("http://localhost:8000")
|
| 207 |
+
|
| 208 |
+
async def responses_api_test_async():
|
| 209 |
+
async for chunk in (await client.chat_completion(messages, model="Qwen/Qwen2.5-VL-7B-Instruct", max_tokens=256, stream=True)):
|
| 210 |
+
token = chunk.choices[0].delta.content
|
| 211 |
+
if token:
|
| 212 |
+
print(token, end='')
|
| 213 |
+
|
| 214 |
+
asyncio.run(responses_api_test_async())
|
| 215 |
+
asyncio.run(client.close())
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
From which you should get an iterative string printed:
|
| 219 |
+
|
| 220 |
+
```xmp
|
| 221 |
+
The image depicts an astronaut in a space suit standing on what appears to be the surface of the moon, given the barren, rocky landscape and the dark sky in the background. The astronaut is holding a large egg that has cracked open, revealing a small creature inside. The scene is imaginative and playful, combining elements of space exploration with a whimsical twist involving the egg and the creature.
|
| 222 |
+
```
|
| 223 |
+
|
| 224 |
+
</hfoption>
|
| 225 |
+
<hfoption id="python - openai">
|
| 226 |
+
|
| 227 |
+
```python
|
| 228 |
+
from openai import OpenAI
|
| 229 |
+
|
| 230 |
+
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<random_string>")
|
| 231 |
+
|
| 232 |
+
completion = client.chat.completions.create(
|
| 233 |
+
model="Qwen/Qwen2.5-VL-7B-Instruct",
|
| 234 |
+
messages=[
|
| 235 |
+
{
|
| 236 |
+
"role": "user",
|
| 237 |
+
"content": [
|
| 238 |
+
{"type": "text", "text": "What's in this image?"},
|
| 239 |
+
{
|
| 240 |
+
"type": "image_url",
|
| 241 |
+
"image_url": {
|
| 242 |
+
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg",
|
| 243 |
+
}
|
| 244 |
+
},
|
| 245 |
+
],
|
| 246 |
+
}
|
| 247 |
+
],
|
| 248 |
+
stream=True
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
for chunk in completion:
|
| 252 |
+
token = chunk.choices[0].delta.content
|
| 253 |
+
if token:
|
| 254 |
+
print(token, end='')
|
| 255 |
+
```
|
| 256 |
+
|
| 257 |
+
From which you should get an iterative string printed:
|
| 258 |
+
|
| 259 |
+
```xmp
|
| 260 |
+
The image depicts an astronaut in a space suit standing on what appears to be the surface of the moon, given the barren, rocky landscape and the dark sky in the background. The astronaut is holding a large egg that has cracked open, revealing a small creature inside. The scene is imaginative and playful, combining elements of space exploration with a whimsical twist involving the egg and the creature.
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
</hfoption>
|
| 264 |
+
</hfoptions>
|
| 265 |
+
|
| 266 |
+
## Responses API
|
| 267 |
+
|
| 268 |
+
The Responses API is the newest addition to the supported APIs of `transformers serve`.
|
| 269 |
+
|
| 270 |
+
> [!TIP]
|
| 271 |
+
> This API is still experimental: expect bug patches and additition of new features in the coming weeks.
|
| 272 |
+
> If you run into any issues, please let us know and we'll work on fixing them ASAP.
|
| 273 |
+
|
| 274 |
+
Instead of the previous `/v1/chat/completions` path, the Responses API lies behind the `/v1/responses` path.
|
| 275 |
+
See below for examples interacting with our Responses endpoint with `curl`, as well as the Python OpenAI client.
|
| 276 |
+
|
| 277 |
+
So far, this endpoint only supports text and therefore only LLMs. VLMs to come!
|
| 278 |
+
|
| 279 |
+
<hfoptions id="responses">
|
| 280 |
+
<hfoption id="curl">
|
| 281 |
+
|
| 282 |
+
```shell
|
| 283 |
+
curl http://localhost:8000/v1/responses \
|
| 284 |
+
-H "Content-Type: application/json" \
|
| 285 |
+
-d '{
|
| 286 |
+
"model": "Qwen/Qwen2.5-0.5B-Instruct",
|
| 287 |
+
"stream": true,
|
| 288 |
+
"input": "Tell me a three sentence bedtime story about a unicorn."
|
| 289 |
+
}'
|
| 290 |
+
```
|
| 291 |
+
|
| 292 |
+
from which you'll receive multiple chunks in the Responses API format
|
| 293 |
+
|
| 294 |
+
```shell
|
| 295 |
+
data: {"response":{"id":"resp_req_0","created_at":1754059817.783648,"model":"Qwen/Qwen2.5-0.5B-Instruct@main","object":"response","output":[],"parallel_tool_calls":false,"tool_choice":"auto","tools":[],"status":"queued","text":{"format":{"type":"text"}}},"sequence_number":0,"type":"response.created"}
|
| 296 |
+
|
| 297 |
+
data: {"response":{"id":"resp_req_0","created_at":1754059817.783648,"model":"Qwen/Qwen2.5-0.5B-Instruct@main","object":"response","output":[],"parallel_tool_calls":false,"tool_choice":"auto","tools":[],"status":"in_progress","text":{"format":{"type":"text"}}},"sequence_number":1,"type":"response.in_progress"}
|
| 298 |
+
|
| 299 |
+
data: {"item":{"id":"msg_req_0","content":[],"role":"assistant","status":"in_progress","type":"message"},"output_index":0,"sequence_number":2,"type":"response.output_item.added"}
|
| 300 |
+
|
| 301 |
+
data: {"content_index":0,"item_id":"msg_req_0","output_index":0,"part":{"annotations":[],"text":"","type":"output_text"},"sequence_number":3,"type":"response.content_part.added"}
|
| 302 |
+
|
| 303 |
+
data: {"content_index":0,"delta":"","item_id":"msg_req_0","output_index":0,"sequence_number":4,"type":"response.output_text.delta"}
|
| 304 |
+
|
| 305 |
+
data: {"content_index":0,"delta":"Once ","item_id":"msg_req_0","output_index":0,"sequence_number":5,"type":"response.output_text.delta"}
|
| 306 |
+
|
| 307 |
+
data: {"content_index":0,"delta":"upon ","item_id":"msg_req_0","output_index":0,"sequence_number":6,"type":"response.output_text.delta"}
|
| 308 |
+
|
| 309 |
+
data: {"content_index":0,"delta":"a ","item_id":"msg_req_0","output_index":0,"sequence_number":7,"type":"response.output_text.delta"}
|
| 310 |
+
```
|
| 311 |
+
|
| 312 |
+
</hfoption>
|
| 313 |
+
<hfoption id="python - openai">
|
| 314 |
+
|
| 315 |
+
```python
|
| 316 |
+
from openai import OpenAI
|
| 317 |
+
|
| 318 |
+
client = OpenAI(base_url="http://localhost:8000/v1", api_key="<KEY>")
|
| 319 |
+
|
| 320 |
+
response = client.responses.create(
|
| 321 |
+
model="Qwen/Qwen2.5-0.5B-Instruct",
|
| 322 |
+
instructions="You are a helpful assistant.",
|
| 323 |
+
input="Hello!",
|
| 324 |
+
stream=True,
|
| 325 |
+
metadata={"foo": "bar"},
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
for event in response:
|
| 329 |
+
print(event)
|
| 330 |
+
```
|
| 331 |
+
|
| 332 |
+
From which you should get events printed out successively.
|
| 333 |
+
|
| 334 |
+
```shell
|
| 335 |
+
ResponseCreatedEvent(response=Response(id='resp_req_0', created_at=1754060400.3718212, error=None, incomplete_details=None, instructions='You are a helpful assistant.', metadata={'foo': 'bar'}, model='Qwen/Qwen2.5-0.5B-Instruct@main', object='response', output=[], parallel_tool_calls=False, temperature=None, tool_choice='auto', tools=[], top_p=None, background=None, max_output_tokens=None, max_tool_calls=None, previous_response_id=None, prompt=None, reasoning=None, service_tier=None, status='queued', text=ResponseTextConfig(format=ResponseFormatText(type='text')), top_logprobs=None, truncation=None, usage=None, user=None), sequence_number=0, type='response.created')
|
| 336 |
+
ResponseInProgressEvent(response=Response(id='resp_req_0', created_at=1754060400.3718212, error=None, incomplete_details=None, instructions='You are a helpful assistant.', metadata={'foo': 'bar'}, model='Qwen/Qwen2.5-0.5B-Instruct@main', object='response', output=[], parallel_tool_calls=False, temperature=None, tool_choice='auto', tools=[], top_p=None, background=None, max_output_tokens=None, max_tool_calls=None, previous_response_id=None, prompt=None, reasoning=None, service_tier=None, status='in_progress', text=ResponseTextConfig(format=ResponseFormatText(type='text')), top_logprobs=None, truncation=None, usage=None, user=None), sequence_number=1, type='response.in_progress')
|
| 337 |
+
ResponseOutputItemAddedEvent(item=ResponseOutputMessage(id='msg_req_0', content=[], role='assistant', status='in_progress', type='message'), output_index=0, sequence_number=2, type='response.output_item.added')
|
| 338 |
+
ResponseContentPartAddedEvent(content_index=0, item_id='msg_req_0', output_index=0, part=ResponseOutputText(annotations=[], text='', type='output_text', logprobs=None), sequence_number=3, type='response.content_part.added')
|
| 339 |
+
ResponseTextDeltaEvent(content_index=0, delta='', item_id='msg_req_0', output_index=0, sequence_number=4, type='response.output_text.delta')
|
| 340 |
+
ResponseTextDeltaEvent(content_index=0, delta='', item_id='msg_req_0', output_index=0, sequence_number=5, type='response.output_text.delta')
|
| 341 |
+
ResponseTextDeltaEvent(content_index=0, delta='Hello! ', item_id='msg_req_0', output_index=0, sequence_number=6, type='response.output_text.delta')
|
| 342 |
+
ResponseTextDeltaEvent(content_index=0, delta='How ', item_id='msg_req_0', output_index=0, sequence_number=7, type='response.output_text.delta')
|
| 343 |
+
ResponseTextDeltaEvent(content_index=0, delta='can ', item_id='msg_req_0', output_index=0, sequence_number=8, type='response.output_text.delta')
|
| 344 |
+
ResponseTextDeltaEvent(content_index=0, delta='I ', item_id='msg_req_0', output_index=0, sequence_number=9, type='response.output_text.delta')
|
| 345 |
+
ResponseTextDeltaEvent(content_index=0, delta='assist ', item_id='msg_req_0', output_index=0, sequence_number=10, type='response.output_text.delta')
|
| 346 |
+
ResponseTextDeltaEvent(content_index=0, delta='you ', item_id='msg_req_0', output_index=0, sequence_number=11, type='response.output_text.delta')
|
| 347 |
+
ResponseTextDeltaEvent(content_index=0, delta='', item_id='msg_req_0', output_index=0, sequence_number=12, type='response.output_text.delta')
|
| 348 |
+
ResponseTextDeltaEvent(content_index=0, delta='', item_id='msg_req_0', output_index=0, sequence_number=13, type='response.output_text.delta')
|
| 349 |
+
ResponseTextDeltaEvent(content_index=0, delta='today?', item_id='msg_req_0', output_index=0, sequence_number=14, type='response.output_text.delta')
|
| 350 |
+
ResponseTextDoneEvent(content_index=0, item_id='msg_req_0', output_index=0, sequence_number=15, text='Hello! How can I assist you today?', type='response.output_text.done')
|
| 351 |
+
ResponseContentPartDoneEvent(content_index=0, item_id='msg_req_0', output_index=0, part=ResponseOutputText(annotations=[], text='Hello! How can I assist you today?', type='output_text', logprobs=None), sequence_number=16, type='response.content_part.done')
|
| 352 |
+
ResponseOutputItemDoneEvent(item=ResponseOutputMessage(id='msg_req_0', content=[ResponseOutputText(annotations=[], text='Hello! How can I assist you today?', type='output_text', logprobs=None)], role='assistant', status='completed', type='message', annotations=[]), output_index=0, sequence_number=17, type='response.output_item.done')
|
| 353 |
+
ResponseCompletedEvent(response=Response(id='resp_req_0', created_at=1754060400.3718212, error=None, incomplete_details=None, instructions='You are a helpful assistant.', metadata={'foo': 'bar'}, model='Qwen/Qwen2.5-0.5B-Instruct@main', object='response', output=[ResponseOutputMessage(id='msg_req_0', content=[ResponseOutputText(annotations=[], text='Hello! How can I assist you today?', type='output_text', logprobs=None)], role='assistant', status='completed', type='message', annotations=[])], parallel_tool_calls=False, temperature=None, tool_choice='auto', tools=[], top_p=None, background=None, max_output_tokens=None, max_tool_calls=None, previous_response_id=None, prompt=None, reasoning=None, service_tier=None, status='completed', text=ResponseTextConfig(format=ResponseFormatText(type='text')), top_logprobs=None, truncation=None, usage=None, user=None), sequence_number=18, type='response.completed')
|
| 354 |
+
```
|
| 355 |
+
|
| 356 |
+
</hfoption>
|
| 357 |
+
</hfoptions>
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
## MCP integration
|
| 361 |
+
|
| 362 |
+
The `transformers serve` server is also an MCP client, so it can interact with MCP tools in agentic use cases. This, of course, requires the use of an LLM that is designed to use tools.
|
| 363 |
+
|
| 364 |
+
> [!TIP]
|
| 365 |
+
> At the moment, MCP tool usage in `transformers` is limited to the `qwen` family of models.
|
| 366 |
+
|
| 367 |
+
<!-- TODO: example with a minimal python example, and explain that it is possible to pass a full generation config in the request -->
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/asr.md
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 17 |
+
# Automatic speech recognition
|
| 18 |
+
|
| 19 |
+
[[open-in-colab]]
|
| 20 |
+
|
| 21 |
+
<Youtube id="TksaY_FDgnk"/>
|
| 22 |
+
|
| 23 |
+
Automatic speech recognition (ASR) converts a speech signal to text, mapping a sequence of audio inputs to text outputs. Virtual assistants like Siri and Alexa use ASR models to help users every day, and there are many other useful user-facing applications like live captioning and note-taking during meetings.
|
| 24 |
+
|
| 25 |
+
This guide will show you how to:
|
| 26 |
+
|
| 27 |
+
1. Fine-tune [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) on the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset to transcribe audio to text.
|
| 28 |
+
2. Use your fine-tuned model for inference.
|
| 29 |
+
|
| 30 |
+
<Tip>
|
| 31 |
+
|
| 32 |
+
To see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/automatic-speech-recognition)
|
| 33 |
+
|
| 34 |
+
</Tip>
|
| 35 |
+
|
| 36 |
+
Before you begin, make sure you have all the necessary libraries installed:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
pip install transformers datasets evaluate jiwer
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login:
|
| 43 |
+
|
| 44 |
+
```py
|
| 45 |
+
>>> from huggingface_hub import notebook_login
|
| 46 |
+
|
| 47 |
+
>>> notebook_login()
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## Load MInDS-14 dataset
|
| 51 |
+
|
| 52 |
+
Start by loading a smaller subset of the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset from the 🤗 Datasets library. This will give you a chance to experiment and make sure everything works before spending more time training on the full dataset.
|
| 53 |
+
|
| 54 |
+
```py
|
| 55 |
+
>>> from datasets import load_dataset, Audio
|
| 56 |
+
|
| 57 |
+
>>> minds = load_dataset("PolyAI/minds14", name="en-US", split="train[:100]")
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
Split the dataset's `train` split into a train and test set with the [`~Dataset.train_test_split`] method:
|
| 61 |
+
|
| 62 |
+
```py
|
| 63 |
+
>>> minds = minds.train_test_split(test_size=0.2)
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
Then take a look at the dataset:
|
| 67 |
+
|
| 68 |
+
```py
|
| 69 |
+
>>> minds
|
| 70 |
+
DatasetDict({
|
| 71 |
+
train: Dataset({
|
| 72 |
+
features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],
|
| 73 |
+
num_rows: 16
|
| 74 |
+
})
|
| 75 |
+
test: Dataset({
|
| 76 |
+
features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],
|
| 77 |
+
num_rows: 4
|
| 78 |
+
})
|
| 79 |
+
})
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
While the dataset contains a lot of useful information, like `lang_id` and `english_transcription`, this guide focuses on the `audio` and `transcription`. Remove the other columns with the [`~datasets.Dataset.remove_columns`] method:
|
| 83 |
+
|
| 84 |
+
```py
|
| 85 |
+
>>> minds = minds.remove_columns(["english_transcription", "intent_class", "lang_id"])
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
Review the example again:
|
| 89 |
+
|
| 90 |
+
```py
|
| 91 |
+
>>> minds["train"][0]
|
| 92 |
+
{'audio': {'array': array([-0.00024414, 0. , 0. , ..., 0.00024414,
|
| 93 |
+
0.00024414, 0.00024414], dtype=float32),
|
| 94 |
+
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',
|
| 95 |
+
'sampling_rate': 8000},
|
| 96 |
+
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',
|
| 97 |
+
'transcription': "hi I'm trying to use the banking app on my phone and currently my checking and savings account balance is not refreshing"}
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
There are two fields:
|
| 101 |
+
|
| 102 |
+
- `audio`: a 1-dimensional `array` of the speech signal that must be called to load and resample the audio file.
|
| 103 |
+
- `transcription`: the target text.
|
| 104 |
+
|
| 105 |
+
## Preprocess
|
| 106 |
+
|
| 107 |
+
The next step is to load a Wav2Vec2 processor to process the audio signal:
|
| 108 |
+
|
| 109 |
+
```py
|
| 110 |
+
>>> from transformers import AutoProcessor
|
| 111 |
+
|
| 112 |
+
>>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base")
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
The MInDS-14 dataset has a sampling rate of 8000Hz (you can find this information in its [dataset card](https://huggingface.co/datasets/PolyAI/minds14)), which means you'll need to resample the dataset to 16000Hz to use the pretrained Wav2Vec2 model:
|
| 116 |
+
|
| 117 |
+
```py
|
| 118 |
+
>>> minds = minds.cast_column("audio", Audio(sampling_rate=16_000))
|
| 119 |
+
>>> minds["train"][0]
|
| 120 |
+
{'audio': {'array': array([-2.38064706e-04, -1.58618059e-04, -5.43987835e-06, ...,
|
| 121 |
+
2.78103951e-04, 2.38446111e-04, 1.18740834e-04], dtype=float32),
|
| 122 |
+
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',
|
| 123 |
+
'sampling_rate': 16000},
|
| 124 |
+
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901cd4f.wav',
|
| 125 |
+
'transcription': "hi I'm trying to use the banking app on my phone and currently my checking and savings account balance is not refreshing"}
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
As you can see in the `transcription` above, the text contains a mix of uppercase and lowercase characters. The Wav2Vec2 tokenizer is only trained on uppercase characters so you'll need to make sure the text matches the tokenizer's vocabulary:
|
| 129 |
+
|
| 130 |
+
```py
|
| 131 |
+
>>> def uppercase(example):
|
| 132 |
+
... return {"transcription": example["transcription"].upper()}
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
>>> minds = minds.map(uppercase)
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
Now create a preprocessing function that:
|
| 139 |
+
|
| 140 |
+
1. Calls the `audio` column to load and resample the audio file.
|
| 141 |
+
2. Extracts the `input_values` from the audio file and tokenize the `transcription` column with the processor.
|
| 142 |
+
|
| 143 |
+
```py
|
| 144 |
+
>>> def prepare_dataset(batch):
|
| 145 |
+
... audio = batch["audio"]
|
| 146 |
+
... batch = processor(audio["array"], sampling_rate=audio["sampling_rate"], text=batch["transcription"])
|
| 147 |
+
... batch["input_length"] = len(batch["input_values"][0])
|
| 148 |
+
... return batch
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
To apply the preprocessing function over the entire dataset, use 🤗 Datasets [`~datasets.Dataset.map`] function. You can speed up `map` by increasing the number of processes with the `num_proc` parameter. Remove the columns you don't need with the [`~datasets.Dataset.remove_columns`] method:
|
| 152 |
+
|
| 153 |
+
```py
|
| 154 |
+
>>> encoded_minds = minds.map(prepare_dataset, remove_columns=minds.column_names["train"], num_proc=4)
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
🤗 Transformers doesn't have a data collator for ASR, so you'll need to adapt the [`DataCollatorWithPadding`] to create a batch of examples. It'll also dynamically pad your text and labels to the length of the longest element in its batch (instead of the entire dataset) so they are a uniform length. While it is possible to pad your text in the `tokenizer` function by setting `padding=True`, dynamic padding is more efficient.
|
| 158 |
+
|
| 159 |
+
Unlike other data collators, this specific data collator needs to apply a different padding method to `input_values` and `labels`:
|
| 160 |
+
|
| 161 |
+
```py
|
| 162 |
+
>>> import torch
|
| 163 |
+
|
| 164 |
+
>>> from dataclasses import dataclass, field
|
| 165 |
+
>>> from typing import Any, Dict, List, Optional, Union
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
>>> @dataclass
|
| 169 |
+
... class DataCollatorCTCWithPadding:
|
| 170 |
+
... processor: AutoProcessor
|
| 171 |
+
... padding: Union[bool, str] = "longest"
|
| 172 |
+
|
| 173 |
+
... def __call__(self, features: list[dict[str, Union[list[int], torch.Tensor]]]) -> dict[str, torch.Tensor]:
|
| 174 |
+
... # split inputs and labels since they have to be of different lengths and need
|
| 175 |
+
... # different padding methods
|
| 176 |
+
... input_features = [{"input_values": feature["input_values"][0]} for feature in features]
|
| 177 |
+
... label_features = [{"input_ids": feature["labels"]} for feature in features]
|
| 178 |
+
|
| 179 |
+
... batch = self.processor.pad(input_features, padding=self.padding, return_tensors="pt")
|
| 180 |
+
|
| 181 |
+
... labels_batch = self.processor.pad(labels=label_features, padding=self.padding, return_tensors="pt")
|
| 182 |
+
|
| 183 |
+
... # replace padding with -100 to ignore loss correctly
|
| 184 |
+
... labels = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1), -100)
|
| 185 |
+
|
| 186 |
+
... batch["labels"] = labels
|
| 187 |
+
|
| 188 |
+
... return batch
|
| 189 |
+
```
|
| 190 |
+
|
| 191 |
+
Now instantiate your `DataCollatorForCTCWithPadding`:
|
| 192 |
+
|
| 193 |
+
```py
|
| 194 |
+
>>> data_collator = DataCollatorCTCWithPadding(processor=processor, padding="longest")
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
## Evaluate
|
| 198 |
+
|
| 199 |
+
Including a metric during training is often helpful for evaluating your model's performance. You can quickly load an evaluation method with the 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [word error rate](https://huggingface.co/spaces/evaluate-metric/wer) (WER) metric (refer to the 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about loading and computing metrics):
|
| 200 |
+
|
| 201 |
+
```py
|
| 202 |
+
>>> import evaluate
|
| 203 |
+
|
| 204 |
+
>>> wer = evaluate.load("wer")
|
| 205 |
+
```
|
| 206 |
+
|
| 207 |
+
Then create a function that passes your predictions and labels to [`~evaluate.EvaluationModule.compute`] to calculate the WER:
|
| 208 |
+
|
| 209 |
+
```py
|
| 210 |
+
>>> import numpy as np
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
>>> def compute_metrics(pred):
|
| 214 |
+
... pred_logits = pred.predictions
|
| 215 |
+
... pred_ids = np.argmax(pred_logits, axis=-1)
|
| 216 |
+
|
| 217 |
+
... pred.label_ids[pred.label_ids == -100] = processor.tokenizer.pad_token_id
|
| 218 |
+
|
| 219 |
+
... pred_str = processor.batch_decode(pred_ids)
|
| 220 |
+
... label_str = processor.batch_decode(pred.label_ids, group_tokens=False)
|
| 221 |
+
|
| 222 |
+
... wer = wer.compute(predictions=pred_str, references=label_str)
|
| 223 |
+
|
| 224 |
+
... return {"wer": wer}
|
| 225 |
+
```
|
| 226 |
+
|
| 227 |
+
Your `compute_metrics` function is ready to go now, and you'll return to it when you setup your training.
|
| 228 |
+
|
| 229 |
+
## Train
|
| 230 |
+
|
| 231 |
+
<frameworkcontent>
|
| 232 |
+
<pt>
|
| 233 |
+
<Tip>
|
| 234 |
+
|
| 235 |
+
If you aren't familiar with finetuning a model with the [`Trainer`], take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!
|
| 236 |
+
|
| 237 |
+
</Tip>
|
| 238 |
+
|
| 239 |
+
You are now ready to start training your model! Load Wav2Vec2 with [`AutoModelForCTC`]. Specify the reduction to apply with the `ctc_loss_reduction` parameter. It is often better to use the average instead of the default summation:
|
| 240 |
+
|
| 241 |
+
```py
|
| 242 |
+
>>> from transformers import AutoModelForCTC, TrainingArguments, Trainer
|
| 243 |
+
|
| 244 |
+
>>> model = AutoModelForCTC.from_pretrained(
|
| 245 |
+
... "facebook/wav2vec2-base",
|
| 246 |
+
... ctc_loss_reduction="mean",
|
| 247 |
+
... pad_token_id=processor.tokenizer.pad_token_id,
|
| 248 |
+
... )
|
| 249 |
+
```
|
| 250 |
+
|
| 251 |
+
At this point, only three steps remain:
|
| 252 |
+
|
| 253 |
+
1. Define your training hyperparameters in [`TrainingArguments`]. The only required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [`Trainer`] will evaluate the WER and save the training checkpoint.
|
| 254 |
+
2. Pass the training arguments to [`Trainer`] along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.
|
| 255 |
+
3. Call [`~Trainer.train`] to fine-tune your model.
|
| 256 |
+
|
| 257 |
+
```py
|
| 258 |
+
>>> training_args = TrainingArguments(
|
| 259 |
+
... output_dir="my_awesome_asr_mind_model",
|
| 260 |
+
... per_device_train_batch_size=8,
|
| 261 |
+
... gradient_accumulation_steps=2,
|
| 262 |
+
... learning_rate=1e-5,
|
| 263 |
+
... warmup_steps=500,
|
| 264 |
+
... max_steps=2000,
|
| 265 |
+
... gradient_checkpointing=True,
|
| 266 |
+
... fp16=True,
|
| 267 |
+
... group_by_length=True,
|
| 268 |
+
... eval_strategy="steps",
|
| 269 |
+
... per_device_eval_batch_size=8,
|
| 270 |
+
... save_steps=1000,
|
| 271 |
+
... eval_steps=1000,
|
| 272 |
+
... logging_steps=25,
|
| 273 |
+
... load_best_model_at_end=True,
|
| 274 |
+
... metric_for_best_model="wer",
|
| 275 |
+
... greater_is_better=False,
|
| 276 |
+
... push_to_hub=True,
|
| 277 |
+
... )
|
| 278 |
+
|
| 279 |
+
>>> trainer = Trainer(
|
| 280 |
+
... model=model,
|
| 281 |
+
... args=training_args,
|
| 282 |
+
... train_dataset=encoded_minds["train"],
|
| 283 |
+
... eval_dataset=encoded_minds["test"],
|
| 284 |
+
... processing_class=processor,
|
| 285 |
+
... data_collator=data_collator,
|
| 286 |
+
... compute_metrics=compute_metrics,
|
| 287 |
+
... )
|
| 288 |
+
|
| 289 |
+
>>> trainer.train()
|
| 290 |
+
```
|
| 291 |
+
|
| 292 |
+
Once training is completed, share your model to the Hub with the [`~transformers.Trainer.push_to_hub`] method so it can be accessible to everyone:
|
| 293 |
+
|
| 294 |
+
```py
|
| 295 |
+
>>> trainer.push_to_hub()
|
| 296 |
+
```
|
| 297 |
+
</pt>
|
| 298 |
+
</frameworkcontent>
|
| 299 |
+
|
| 300 |
+
<Tip>
|
| 301 |
+
|
| 302 |
+
For a more in-depth example of how to fine-tune a model for automatic speech recognition, take a look at this blog [post](https://huggingface.co/blog/fine-tune-wav2vec2-english) for English ASR and this [post](https://huggingface.co/blog/fine-tune-xlsr-wav2vec2) for multilingual ASR.
|
| 303 |
+
|
| 304 |
+
</Tip>
|
| 305 |
+
|
| 306 |
+
## Inference
|
| 307 |
+
|
| 308 |
+
Great, now that you've fine-tuned a model, you can use it for inference!
|
| 309 |
+
|
| 310 |
+
Load an audio file you'd like to run inference on. Remember to resample the sampling rate of the audio file to match the sampling rate of the model if you need to!
|
| 311 |
+
|
| 312 |
+
```py
|
| 313 |
+
>>> from datasets import load_dataset, Audio
|
| 314 |
+
|
| 315 |
+
>>> dataset = load_dataset("PolyAI/minds14", "en-US", split="train")
|
| 316 |
+
>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
|
| 317 |
+
>>> sampling_rate = dataset.features["audio"].sampling_rate
|
| 318 |
+
>>> audio_file = dataset[0]["audio"]["path"]
|
| 319 |
+
```
|
| 320 |
+
|
| 321 |
+
The simplest way to try out your fine-tuned model for inference is to use it in a [`pipeline`]. Instantiate a `pipeline` for automatic speech recognition with your model, and pass your audio file to it:
|
| 322 |
+
|
| 323 |
+
```py
|
| 324 |
+
>>> from transformers import pipeline
|
| 325 |
+
|
| 326 |
+
>>> transcriber = pipeline("automatic-speech-recognition", model="stevhliu/my_awesome_asr_minds_model")
|
| 327 |
+
>>> transcriber(audio_file)
|
| 328 |
+
{'text': 'I WOUD LIKE O SET UP JOINT ACOUNT WTH Y PARTNER'}
|
| 329 |
+
```
|
| 330 |
+
|
| 331 |
+
<Tip>
|
| 332 |
+
|
| 333 |
+
The transcription is decent, but it could be better! Try finetuning your model on more examples to get even better results!
|
| 334 |
+
|
| 335 |
+
</Tip>
|
| 336 |
+
|
| 337 |
+
You can also manually replicate the results of the `pipeline` if you'd like:
|
| 338 |
+
|
| 339 |
+
<frameworkcontent>
|
| 340 |
+
<pt>
|
| 341 |
+
Load a processor to preprocess the audio file and transcription and return the `input` as PyTorch tensors:
|
| 342 |
+
|
| 343 |
+
```py
|
| 344 |
+
>>> from transformers import AutoProcessor
|
| 345 |
+
|
| 346 |
+
>>> processor = AutoProcessor.from_pretrained("stevhliu/my_awesome_asr_mind_model")
|
| 347 |
+
>>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
|
| 348 |
+
```
|
| 349 |
+
|
| 350 |
+
Pass your inputs to the model and return the logits:
|
| 351 |
+
|
| 352 |
+
```py
|
| 353 |
+
>>> from transformers import AutoModelForCTC
|
| 354 |
+
|
| 355 |
+
>>> model = AutoModelForCTC.from_pretrained("stevhliu/my_awesome_asr_mind_model")
|
| 356 |
+
>>> with torch.no_grad():
|
| 357 |
+
... logits = model(**inputs).logits
|
| 358 |
+
```
|
| 359 |
+
|
| 360 |
+
Get the predicted `input_ids` with the highest probability, and use the processor to decode the predicted `input_ids` back into text:
|
| 361 |
+
|
| 362 |
+
```py
|
| 363 |
+
>>> import torch
|
| 364 |
+
|
| 365 |
+
>>> predicted_ids = torch.argmax(logits, dim=-1)
|
| 366 |
+
>>> transcription = processor.batch_decode(predicted_ids)
|
| 367 |
+
>>> transcription
|
| 368 |
+
['I WOUL LIKE O SET UP JOINT ACOUNT WTH Y PARTNER']
|
| 369 |
+
```
|
| 370 |
+
</pt>
|
| 371 |
+
</frameworkcontent>
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/audio_classification.md
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 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 contains specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
# Audio classification
|
| 18 |
+
|
| 19 |
+
[[open-in-colab]]
|
| 20 |
+
|
| 21 |
+
<Youtube id="KWwzcmG98Ds"/>
|
| 22 |
+
|
| 23 |
+
Audio classification - just like with text - assigns a class label as output from the input data. The only difference is instead of text inputs, you have raw audio waveforms. Some practical applications of audio classification include identifying speaker intent, language classification, and even animal species by their sounds.
|
| 24 |
+
|
| 25 |
+
This guide will show you how to:
|
| 26 |
+
|
| 27 |
+
1. Fine-tune [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) on the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset to classify speaker intent.
|
| 28 |
+
2. Use your fine-tuned model for inference.
|
| 29 |
+
|
| 30 |
+
<Tip>
|
| 31 |
+
|
| 32 |
+
To see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/audio-classification)
|
| 33 |
+
|
| 34 |
+
</Tip>
|
| 35 |
+
|
| 36 |
+
Before you begin, make sure you have all the necessary libraries installed:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
pip install transformers datasets evaluate
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login:
|
| 43 |
+
|
| 44 |
+
```py
|
| 45 |
+
>>> from huggingface_hub import notebook_login
|
| 46 |
+
|
| 47 |
+
>>> notebook_login()
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
## Load MInDS-14 dataset
|
| 51 |
+
|
| 52 |
+
Start by loading the MInDS-14 dataset from the 🤗 Datasets library:
|
| 53 |
+
|
| 54 |
+
```py
|
| 55 |
+
>>> from datasets import load_dataset, Audio
|
| 56 |
+
|
| 57 |
+
>>> minds = load_dataset("PolyAI/minds14", name="en-US", split="train")
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
Split the dataset's `train` split into a smaller train and test set with the [`~datasets.Dataset.train_test_split`] method. This will give you a chance to experiment and make sure everything works before spending more time on the full dataset.
|
| 61 |
+
|
| 62 |
+
```py
|
| 63 |
+
>>> minds = minds.train_test_split(test_size=0.2)
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
Then take a look at the dataset:
|
| 67 |
+
|
| 68 |
+
```py
|
| 69 |
+
>>> minds
|
| 70 |
+
DatasetDict({
|
| 71 |
+
train: Dataset({
|
| 72 |
+
features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],
|
| 73 |
+
num_rows: 450
|
| 74 |
+
})
|
| 75 |
+
test: Dataset({
|
| 76 |
+
features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],
|
| 77 |
+
num_rows: 113
|
| 78 |
+
})
|
| 79 |
+
})
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
While the dataset contains a lot of useful information, like `lang_id` and `english_transcription`, you will focus on the `audio` and `intent_class` in this guide. Remove the other columns with the [`~datasets.Dataset.remove_columns`] method:
|
| 83 |
+
|
| 84 |
+
```py
|
| 85 |
+
>>> minds = minds.remove_columns(["path", "transcription", "english_transcription", "lang_id"])
|
| 86 |
+
```
|
| 87 |
+
|
| 88 |
+
Here's an example:
|
| 89 |
+
|
| 90 |
+
```py
|
| 91 |
+
>>> minds["train"][0]
|
| 92 |
+
{'audio': {'array': array([ 0. , 0. , 0. , ..., -0.00048828,
|
| 93 |
+
-0.00024414, -0.00024414], dtype=float32),
|
| 94 |
+
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602b9a5fbb1e6d0fbce91f52.wav',
|
| 95 |
+
'sampling_rate': 8000},
|
| 96 |
+
'intent_class': 2}
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
There are two fields:
|
| 100 |
+
|
| 101 |
+
- `audio`: a 1-dimensional `array` of the speech signal that must be called to load and resample the audio file.
|
| 102 |
+
- `intent_class`: represents the class id of the speaker's intent.
|
| 103 |
+
|
| 104 |
+
To make it easier for the model to get the label name from the label id, create a dictionary that maps the label name to an integer and vice versa:
|
| 105 |
+
|
| 106 |
+
```py
|
| 107 |
+
>>> labels = minds["train"].features["intent_class"].names
|
| 108 |
+
>>> label2id, id2label = dict(), dict()
|
| 109 |
+
>>> for i, label in enumerate(labels):
|
| 110 |
+
... label2id[label] = str(i)
|
| 111 |
+
... id2label[str(i)] = label
|
| 112 |
+
```
|
| 113 |
+
|
| 114 |
+
Now you can convert the label id to a label name:
|
| 115 |
+
|
| 116 |
+
```py
|
| 117 |
+
>>> id2label[str(2)]
|
| 118 |
+
'app_error'
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
## Preprocess
|
| 122 |
+
|
| 123 |
+
The next step is to load a Wav2Vec2 feature extractor to process the audio signal:
|
| 124 |
+
|
| 125 |
+
```py
|
| 126 |
+
>>> from transformers import AutoFeatureExtractor
|
| 127 |
+
|
| 128 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base")
|
| 129 |
+
```
|
| 130 |
+
|
| 131 |
+
The MInDS-14 dataset has a sampling rate of 8kHz (you can find this information in its [dataset card](https://huggingface.co/datasets/PolyAI/minds14)), which means you'll need to resample the dataset to 16kHz to use the pretrained Wav2Vec2 model:
|
| 132 |
+
|
| 133 |
+
```py
|
| 134 |
+
>>> minds = minds.cast_column("audio", Audio(sampling_rate=16_000))
|
| 135 |
+
>>> minds["train"][0]
|
| 136 |
+
{'audio': {'array': array([ 2.2098757e-05, 4.6582241e-05, -2.2803260e-05, ...,
|
| 137 |
+
-2.8419291e-04, -2.3305941e-04, -1.1425107e-04], dtype=float32),
|
| 138 |
+
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602b9a5fbb1e6d0fbce91f52.wav',
|
| 139 |
+
'sampling_rate': 16000},
|
| 140 |
+
'intent_class': 2}
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
Now create a preprocessing function that:
|
| 144 |
+
|
| 145 |
+
1. Calls the `audio` column to load, and if necessary, resample the audio file.
|
| 146 |
+
2. Checks if the sampling rate of the audio file matches the sampling rate of the audio data a model was pretrained with. You can find this information in the Wav2Vec2 [model card](https://huggingface.co/facebook/wav2vec2-base).
|
| 147 |
+
3. Set a maximum input length to batch longer inputs without truncating them.
|
| 148 |
+
|
| 149 |
+
```py
|
| 150 |
+
>>> def preprocess_function(examples):
|
| 151 |
+
... audio_arrays = [x["array"] for x in examples["audio"]]
|
| 152 |
+
... inputs = feature_extractor(
|
| 153 |
+
... audio_arrays, sampling_rate=feature_extractor.sampling_rate, max_length=16000, truncation=True
|
| 154 |
+
... )
|
| 155 |
+
... return inputs
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
To apply the preprocessing function over the entire dataset, use 🤗 Datasets [`~datasets.Dataset.map`] function. You can speed up `map` by setting `batched=True` to process multiple elements of the dataset at once. Remove unnecessary columns and rename `intent_class` to `label`, as required by the model:
|
| 159 |
+
|
| 160 |
+
```py
|
| 161 |
+
>>> encoded_minds = minds.map(preprocess_function, remove_columns="audio", batched=True)
|
| 162 |
+
>>> encoded_minds = encoded_minds.rename_column("intent_class", "label")
|
| 163 |
+
```
|
| 164 |
+
|
| 165 |
+
## Evaluate
|
| 166 |
+
|
| 167 |
+
Including a metric during training is often helpful for evaluating your model's performance. You can quickly load an evaluation method with the 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) metric (see the 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric):
|
| 168 |
+
|
| 169 |
+
```py
|
| 170 |
+
>>> import evaluate
|
| 171 |
+
|
| 172 |
+
>>> accuracy = evaluate.load("accuracy")
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
Then create a function that passes your predictions and labels to [`~evaluate.EvaluationModule.compute`] to calculate the accuracy:
|
| 176 |
+
|
| 177 |
+
```py
|
| 178 |
+
>>> import numpy as np
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
>>> def compute_metrics(eval_pred):
|
| 182 |
+
... predictions = np.argmax(eval_pred.predictions, axis=1)
|
| 183 |
+
... return accuracy.compute(predictions=predictions, references=eval_pred.label_ids)
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
Your `compute_metrics` function is ready to go now, and you'll return to it when you setup your training.
|
| 187 |
+
|
| 188 |
+
## Train
|
| 189 |
+
|
| 190 |
+
<frameworkcontent>
|
| 191 |
+
<pt>
|
| 192 |
+
<Tip>
|
| 193 |
+
|
| 194 |
+
If you aren't familiar with finetuning a model with the [`Trainer`], take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!
|
| 195 |
+
|
| 196 |
+
</Tip>
|
| 197 |
+
|
| 198 |
+
You're ready to start training your model now! Load Wav2Vec2 with [`AutoModelForAudioClassification`] along with the number of expected labels, and the label mappings:
|
| 199 |
+
|
| 200 |
+
```py
|
| 201 |
+
>>> from transformers import AutoModelForAudioClassification, TrainingArguments, Trainer
|
| 202 |
+
|
| 203 |
+
>>> num_labels = len(id2label)
|
| 204 |
+
>>> model = AutoModelForAudioClassification.from_pretrained(
|
| 205 |
+
... "facebook/wav2vec2-base", num_labels=num_labels, label2id=label2id, id2label=id2label
|
| 206 |
+
... )
|
| 207 |
+
```
|
| 208 |
+
|
| 209 |
+
At this point, only three steps remain:
|
| 210 |
+
|
| 211 |
+
1. Define your training hyperparameters in [`TrainingArguments`]. The only required parameter is `output_dir`, which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [`Trainer`] will evaluate the accuracy and save the training checkpoint.
|
| 212 |
+
2. Pass the training arguments to [`Trainer`] along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.
|
| 213 |
+
3. Call [`~Trainer.train`] to fine-tune your model.
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
```py
|
| 217 |
+
>>> training_args = TrainingArguments(
|
| 218 |
+
... output_dir="my_awesome_mind_model",
|
| 219 |
+
... eval_strategy="epoch",
|
| 220 |
+
... save_strategy="epoch",
|
| 221 |
+
... learning_rate=3e-5,
|
| 222 |
+
... per_device_train_batch_size=32,
|
| 223 |
+
... gradient_accumulation_steps=4,
|
| 224 |
+
... per_device_eval_batch_size=32,
|
| 225 |
+
... num_train_epochs=10,
|
| 226 |
+
... warmup_ratio=0.1,
|
| 227 |
+
... logging_steps=10,
|
| 228 |
+
... load_best_model_at_end=True,
|
| 229 |
+
... metric_for_best_model="accuracy",
|
| 230 |
+
... push_to_hub=True,
|
| 231 |
+
... )
|
| 232 |
+
|
| 233 |
+
>>> trainer = Trainer(
|
| 234 |
+
... model=model,
|
| 235 |
+
... args=training_args,
|
| 236 |
+
... train_dataset=encoded_minds["train"],
|
| 237 |
+
... eval_dataset=encoded_minds["test"],
|
| 238 |
+
... processing_class=feature_extractor,
|
| 239 |
+
... compute_metrics=compute_metrics,
|
| 240 |
+
... )
|
| 241 |
+
|
| 242 |
+
>>> trainer.train()
|
| 243 |
+
```
|
| 244 |
+
|
| 245 |
+
Once training is completed, share your model to the Hub with the [`~transformers.Trainer.push_to_hub`] method so everyone can use your model:
|
| 246 |
+
|
| 247 |
+
```py
|
| 248 |
+
>>> trainer.push_to_hub()
|
| 249 |
+
```
|
| 250 |
+
</pt>
|
| 251 |
+
</frameworkcontent>
|
| 252 |
+
|
| 253 |
+
<Tip>
|
| 254 |
+
|
| 255 |
+
For a more in-depth example of how to fine-tune a model for audio classification, take a look at the corresponding [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/audio_classification.ipynb).
|
| 256 |
+
|
| 257 |
+
</Tip>
|
| 258 |
+
|
| 259 |
+
## Inference
|
| 260 |
+
|
| 261 |
+
Great, now that you've fine-tuned a model, you can use it for inference!
|
| 262 |
+
|
| 263 |
+
Load an audio file for inference. Remember to resample the sampling rate of the audio file to match the model's sampling rate, if necessary.
|
| 264 |
+
|
| 265 |
+
```py
|
| 266 |
+
>>> from datasets import load_dataset, Audio
|
| 267 |
+
|
| 268 |
+
>>> dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")
|
| 269 |
+
>>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
|
| 270 |
+
>>> sampling_rate = dataset.features["audio"].sampling_rate
|
| 271 |
+
>>> audio_file = dataset[0]["audio"]["path"]
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
The simplest way to try out your fine-tuned model for inference is to use it in a [`pipeline`]. Instantiate a `pipeline` for audio classification with your model, and pass your audio file to it:
|
| 275 |
+
|
| 276 |
+
```py
|
| 277 |
+
>>> from transformers import pipeline
|
| 278 |
+
|
| 279 |
+
>>> classifier = pipeline("audio-classification", model="stevhliu/my_awesome_minds_model")
|
| 280 |
+
>>> classifier(audio_file)
|
| 281 |
+
[
|
| 282 |
+
{'score': 0.09766869246959686, 'label': 'cash_deposit'},
|
| 283 |
+
{'score': 0.07998877018690109, 'label': 'app_error'},
|
| 284 |
+
{'score': 0.0781070664525032, 'label': 'joint_account'},
|
| 285 |
+
{'score': 0.07667109370231628, 'label': 'pay_bill'},
|
| 286 |
+
{'score': 0.0755252093076706, 'label': 'balance'}
|
| 287 |
+
]
|
| 288 |
+
```
|
| 289 |
+
|
| 290 |
+
You can also manually replicate the results of the `pipeline` if you'd like:
|
| 291 |
+
|
| 292 |
+
<frameworkcontent>
|
| 293 |
+
<pt>
|
| 294 |
+
Load a feature extractor to preprocess the audio file and return the `input` as PyTorch tensors:
|
| 295 |
+
|
| 296 |
+
```py
|
| 297 |
+
>>> from transformers import AutoFeatureExtractor
|
| 298 |
+
|
| 299 |
+
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("stevhliu/my_awesome_minds_model")
|
| 300 |
+
>>> inputs = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
|
| 301 |
+
```
|
| 302 |
+
|
| 303 |
+
Pass your inputs to the model and return the logits:
|
| 304 |
+
|
| 305 |
+
```py
|
| 306 |
+
>>> from transformers import AutoModelForAudioClassification
|
| 307 |
+
|
| 308 |
+
>>> model = AutoModelForAudioClassification.from_pretrained("stevhliu/my_awesome_minds_model")
|
| 309 |
+
>>> with torch.no_grad():
|
| 310 |
+
... logits = model(**inputs).logits
|
| 311 |
+
```
|
| 312 |
+
|
| 313 |
+
Get the class with the highest probability, and use the model's `id2label` mapping to convert it to a label:
|
| 314 |
+
|
| 315 |
+
```py
|
| 316 |
+
>>> import torch
|
| 317 |
+
|
| 318 |
+
>>> predicted_class_ids = torch.argmax(logits).item()
|
| 319 |
+
>>> predicted_label = model.config.id2label[predicted_class_ids]
|
| 320 |
+
>>> predicted_label
|
| 321 |
+
'cash_deposit'
|
| 322 |
+
```
|
| 323 |
+
</pt>
|
| 324 |
+
</frameworkcontent>
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/document_question_answering.md
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 17 |
+
# Document Question Answering
|
| 18 |
+
|
| 19 |
+
[[open-in-colab]]
|
| 20 |
+
|
| 21 |
+
Document Question Answering, also referred to as Document Visual Question Answering, is a task that involves providing
|
| 22 |
+
answers to questions posed about document images. The input to models supporting this task is typically a combination of an image and
|
| 23 |
+
a question, and the output is an answer expressed in natural language. These models utilize multiple modalities, including
|
| 24 |
+
text, the positions of words (bounding boxes), and the image itself.
|
| 25 |
+
|
| 26 |
+
This guide illustrates how to:
|
| 27 |
+
|
| 28 |
+
- Fine-tune [LayoutLMv2](../model_doc/layoutlmv2) on the [DocVQA dataset](https://huggingface.co/datasets/nielsr/docvqa_1200_examples_donut).
|
| 29 |
+
- Use your fine-tuned model for inference.
|
| 30 |
+
|
| 31 |
+
<Tip>
|
| 32 |
+
|
| 33 |
+
To see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/image-to-text)
|
| 34 |
+
|
| 35 |
+
</Tip>
|
| 36 |
+
|
| 37 |
+
LayoutLMv2 solves the document question-answering task by adding a question-answering head on top of the final hidden
|
| 38 |
+
states of the tokens, to predict the positions of the start and end tokens of the
|
| 39 |
+
answer. In other words, the problem is treated as extractive question answering: given the context, extract which piece
|
| 40 |
+
of information answers the question. The context comes from the output of an OCR engine, here it is Google's Tesseract.
|
| 41 |
+
|
| 42 |
+
Before you begin, make sure you have all the necessary libraries installed. LayoutLMv2 depends on detectron2, torchvision and tesseract.
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
pip install -q transformers datasets
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
pip install 'git+https://github.com/facebookresearch/detectron2.git'
|
| 50 |
+
pip install torchvision
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
sudo apt install tesseract-ocr
|
| 55 |
+
pip install -q pytesseract
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
Once you have installed all of the dependencies, restart your runtime.
|
| 59 |
+
|
| 60 |
+
We encourage you to share your model with the community. Log in to your Hugging Face account to upload it to the 🤗 Hub.
|
| 61 |
+
When prompted, enter your token to log in:
|
| 62 |
+
|
| 63 |
+
```py
|
| 64 |
+
>>> from huggingface_hub import notebook_login
|
| 65 |
+
|
| 66 |
+
>>> notebook_login()
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
Let's define some global variables.
|
| 70 |
+
|
| 71 |
+
```py
|
| 72 |
+
>>> model_checkpoint = "microsoft/layoutlmv2-base-uncased"
|
| 73 |
+
>>> batch_size = 4
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
## Load the data
|
| 77 |
+
|
| 78 |
+
In this guide we use a small sample of preprocessed DocVQA that you can find on 🤗 Hub. If you'd like to use the full
|
| 79 |
+
DocVQA dataset, you can register and download it on [DocVQA homepage](https://rrc.cvc.uab.es/?ch=17). If you do so, to
|
| 80 |
+
proceed with this guide check out [how to load files into a 🤗 dataset](https://huggingface.co/docs/datasets/loading#local-and-remote-files).
|
| 81 |
+
|
| 82 |
+
```py
|
| 83 |
+
>>> from datasets import load_dataset
|
| 84 |
+
|
| 85 |
+
>>> dataset = load_dataset("nielsr/docvqa_1200_examples")
|
| 86 |
+
>>> dataset
|
| 87 |
+
DatasetDict({
|
| 88 |
+
train: Dataset({
|
| 89 |
+
features: ['id', 'image', 'query', 'answers', 'words', 'bounding_boxes', 'answer'],
|
| 90 |
+
num_rows: 1000
|
| 91 |
+
})
|
| 92 |
+
test: Dataset({
|
| 93 |
+
features: ['id', 'image', 'query', 'answers', 'words', 'bounding_boxes', 'answer'],
|
| 94 |
+
num_rows: 200
|
| 95 |
+
})
|
| 96 |
+
})
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
As you can see, the dataset is split into train and test sets already. Take a look at a random example to familiarize
|
| 100 |
+
yourself with the features.
|
| 101 |
+
|
| 102 |
+
```py
|
| 103 |
+
>>> dataset["train"].features
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
Here's what the individual fields represent:
|
| 107 |
+
* `id`: the example's id
|
| 108 |
+
* `image`: a PIL.Image.Image object containing the document image
|
| 109 |
+
* `query`: the question string - natural language asked question, in several languages
|
| 110 |
+
* `answers`: a list of correct answers provided by human annotators
|
| 111 |
+
* `words` and `bounding_boxes`: the results of OCR, which we will not use here
|
| 112 |
+
* `answer`: an answer matched by a different model which we will not use here
|
| 113 |
+
|
| 114 |
+
Let's leave only English questions, and drop the `answer` feature which appears to contain predictions by another model.
|
| 115 |
+
We'll also take the first of the answers from the set provided by the annotators. Alternatively, you can randomly sample it.
|
| 116 |
+
|
| 117 |
+
```py
|
| 118 |
+
>>> updated_dataset = dataset.map(lambda example: {"question": example["query"]["en"]}, remove_columns=["query"])
|
| 119 |
+
>>> updated_dataset = updated_dataset.map(
|
| 120 |
+
... lambda example: {"answer": example["answers"][0]}, remove_columns=["answer", "answers"]
|
| 121 |
+
... )
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
Note that the LayoutLMv2 checkpoint that we use in this guide has been trained with `max_position_embeddings = 512` (you can
|
| 125 |
+
find this information in the [checkpoint's `config.json` file](https://huggingface.co/microsoft/layoutlmv2-base-uncased/blob/main/config.json#L18)).
|
| 126 |
+
We can truncate the examples but to avoid the situation where the answer might be at the end of a large document and end up truncated,
|
| 127 |
+
here we'll remove the few examples where the embedding is likely to end up longer than 512.
|
| 128 |
+
If most of the documents in your dataset are long, you can implement a sliding window strategy - check out [this notebook](https://github.com/huggingface/notebooks/blob/main/examples/question_answering.ipynb) for details.
|
| 129 |
+
|
| 130 |
+
```py
|
| 131 |
+
>>> updated_dataset = updated_dataset.filter(lambda x: len(x["words"]) + len(x["question"].split()) < 512)
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
At this point let's also remove the OCR features from this dataset. These are a result of OCR for fine-tuning a different
|
| 135 |
+
model. They would still require some processing if we wanted to use them, as they do not match the input requirements
|
| 136 |
+
of the model we use in this guide. Instead, we can use the [`LayoutLMv2Processor`] on the original data for both OCR and
|
| 137 |
+
tokenization. This way we'll get the inputs that match model's expected input. If you want to process images manually,
|
| 138 |
+
check out the [`LayoutLMv2` model documentation](../model_doc/layoutlmv2) to learn what input format the model expects.
|
| 139 |
+
|
| 140 |
+
```py
|
| 141 |
+
>>> updated_dataset = updated_dataset.remove_columns("words")
|
| 142 |
+
>>> updated_dataset = updated_dataset.remove_columns("bounding_boxes")
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
Finally, the data exploration won't be complete if we don't peek at an image example.
|
| 146 |
+
|
| 147 |
+
```py
|
| 148 |
+
>>> updated_dataset["train"][11]["image"]
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
<div class="flex justify-center">
|
| 152 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/docvqa_example.jpg" alt="DocVQA Image Example"/>
|
| 153 |
+
</div>
|
| 154 |
+
|
| 155 |
+
## Preprocess the data
|
| 156 |
+
|
| 157 |
+
The Document Question Answering task is a multimodal task, and you need to make sure that the inputs from each modality
|
| 158 |
+
are preprocessed according to the model's expectations. Let's start by loading the [`LayoutLMv2Processor`], which internally combines an image processor that can handle image data and a tokenizer that can encode text data.
|
| 159 |
+
|
| 160 |
+
```py
|
| 161 |
+
>>> from transformers import AutoProcessor
|
| 162 |
+
|
| 163 |
+
>>> processor = AutoProcessor.from_pretrained(model_checkpoint)
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
### Preprocessing document images
|
| 167 |
+
|
| 168 |
+
First, let's prepare the document images for the model with the help of the `image_processor` from the processor.
|
| 169 |
+
By default, image processor resizes the images to 224x224, makes sure they have the correct order of color channels,
|
| 170 |
+
applies OCR with tesseract to get words and normalized bounding boxes. In this tutorial, all of these defaults are exactly what we need.
|
| 171 |
+
Write a function that applies the default image processing to a batch of images and returns the results of OCR.
|
| 172 |
+
|
| 173 |
+
```py
|
| 174 |
+
>>> image_processor = processor.image_processor
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
>>> def get_ocr_words_and_boxes(examples):
|
| 178 |
+
... images = [image.convert("RGB") for image in examples["image"]]
|
| 179 |
+
... encoded_inputs = image_processor(images)
|
| 180 |
+
|
| 181 |
+
... examples["image"] = encoded_inputs.pixel_values
|
| 182 |
+
... examples["words"] = encoded_inputs.words
|
| 183 |
+
... examples["boxes"] = encoded_inputs.boxes
|
| 184 |
+
|
| 185 |
+
... return examples
|
| 186 |
+
```
|
| 187 |
+
|
| 188 |
+
To apply this preprocessing to the entire dataset in a fast way, use [`~datasets.Dataset.map`].
|
| 189 |
+
|
| 190 |
+
```py
|
| 191 |
+
>>> dataset_with_ocr = updated_dataset.map(get_ocr_words_and_boxes, batched=True, batch_size=2)
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
### Preprocessing text data
|
| 195 |
+
|
| 196 |
+
Once we have applied OCR to the images, we need to encode the text part of the dataset to prepare it for the model.
|
| 197 |
+
This involves converting the words and boxes that we got in the previous step to token-level `input_ids`, `attention_mask`,
|
| 198 |
+
`token_type_ids` and `bbox`. For preprocessing text, we'll need the `tokenizer` from the processor.
|
| 199 |
+
|
| 200 |
+
```py
|
| 201 |
+
>>> tokenizer = processor.tokenizer
|
| 202 |
+
```
|
| 203 |
+
|
| 204 |
+
On top of the preprocessing mentioned above, we also need to add the labels for the model. For `xxxForQuestionAnswering` models
|
| 205 |
+
in 🤗 Transformers, the labels consist of the `start_positions` and `end_positions`, indicating which token is at the
|
| 206 |
+
start and which token is at the end of the answer.
|
| 207 |
+
|
| 208 |
+
Let's start with that. Define a helper function that can find a sublist (the answer split into words) in a larger list (the words list).
|
| 209 |
+
|
| 210 |
+
This function will take two lists as input, `words_list` and `answer_list`. It will then iterate over the `words_list` and check
|
| 211 |
+
if the current word in the `words_list` (words_list[i]) is equal to the first word of answer_list (answer_list[0]) and if
|
| 212 |
+
the sublist of `words_list` starting from the current word and of the same length as `answer_list` is equal `to answer_list`.
|
| 213 |
+
If this condition is true, it means that a match has been found, and the function will record the match, its starting index (idx),
|
| 214 |
+
and its ending index (idx + len(answer_list) - 1). If more than one match was found, the function will return only the first one.
|
| 215 |
+
If no match is found, the function returns (`None`, 0, and 0).
|
| 216 |
+
|
| 217 |
+
```py
|
| 218 |
+
>>> def subfinder(words_list, answer_list):
|
| 219 |
+
... matches = []
|
| 220 |
+
... start_indices = []
|
| 221 |
+
... end_indices = []
|
| 222 |
+
... for idx, i in enumerate(range(len(words_list))):
|
| 223 |
+
... if words_list[i] == answer_list[0] and words_list[i : i + len(answer_list)] == answer_list:
|
| 224 |
+
... matches.append(answer_list)
|
| 225 |
+
... start_indices.append(idx)
|
| 226 |
+
... end_indices.append(idx + len(answer_list) - 1)
|
| 227 |
+
... if matches:
|
| 228 |
+
... return matches[0], start_indices[0], end_indices[0]
|
| 229 |
+
... else:
|
| 230 |
+
... return None, 0, 0
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
To illustrate how this function finds the position of the answer, let's use it on an example:
|
| 234 |
+
|
| 235 |
+
```py
|
| 236 |
+
>>> example = dataset_with_ocr["train"][1]
|
| 237 |
+
>>> words = [word.lower() for word in example["words"]]
|
| 238 |
+
>>> match, word_idx_start, word_idx_end = subfinder(words, example["answer"].lower().split())
|
| 239 |
+
>>> print("Question: ", example["question"])
|
| 240 |
+
>>> print("Words:", words)
|
| 241 |
+
>>> print("Answer: ", example["answer"])
|
| 242 |
+
>>> print("start_index", word_idx_start)
|
| 243 |
+
>>> print("end_index", word_idx_end)
|
| 244 |
+
Question: Who is in cc in this letter?
|
| 245 |
+
Words: ['wie', 'baw', 'brown', '&', 'williamson', 'tobacco', 'corporation', 'research', '&', 'development', 'internal', 'correspondence', 'to:', 'r.', 'h.', 'honeycutt', 'ce:', 't.f.', 'riehl', 'from:', '.', 'c.j.', 'cook', 'date:', 'may', '8,', '1995', 'subject:', 'review', 'of', 'existing', 'brainstorming', 'ideas/483', 'the', 'major', 'function', 'of', 'the', 'product', 'innovation', 'graup', 'is', 'to', 'develop', 'marketable', 'nove!', 'products', 'that', 'would', 'be', 'profitable', 'to', 'manufacture', 'and', 'sell.', 'novel', 'is', 'defined', 'as:', 'of', 'a', 'new', 'kind,', 'or', 'different', 'from', 'anything', 'seen', 'or', 'known', 'before.', 'innovation', 'is', 'defined', 'as:', 'something', 'new', 'or', 'different', 'introduced;', 'act', 'of', 'innovating;', 'introduction', 'of', 'new', 'things', 'or', 'methods.', 'the', 'products', 'may', 'incorporate', 'the', 'latest', 'technologies,', 'materials', 'and', 'know-how', 'available', 'to', 'give', 'then', 'a', 'unique', 'taste', 'or', 'look.', 'the', 'first', 'task', 'of', 'the', 'product', 'innovation', 'group', 'was', 'to', 'assemble,', 'review', 'and', 'categorize', 'a', 'list', 'of', 'existing', 'brainstorming', 'ideas.', 'ideas', 'were', 'grouped', 'into', 'two', 'major', 'categories', 'labeled', 'appearance', 'and', 'taste/aroma.', 'these', 'categories', 'are', 'used', 'for', 'novel', 'products', 'that', 'may', 'differ', 'from', 'a', 'visual', 'and/or', 'taste/aroma', 'point', 'of', 'view', 'compared', 'to', 'canventional', 'cigarettes.', 'other', 'categories', 'include', 'a', 'combination', 'of', 'the', 'above,', 'filters,', 'packaging', 'and', 'brand', 'extensions.', 'appearance', 'this', 'category', 'is', 'used', 'for', 'novel', 'cigarette', 'constructions', 'that', 'yield', 'visually', 'different', 'products', 'with', 'minimal', 'changes', 'in', 'smoke', 'chemistry', 'two', 'cigarettes', 'in', 'cne.', 'emulti-plug', 'te', 'build', 'yaur', 'awn', 'cigarette.', 'eswitchable', 'menthol', 'or', 'non', 'menthol', 'cigarette.', '*cigarettes', 'with', 'interspaced', 'perforations', 'to', 'enable', 'smoker', 'to', 'separate', 'unburned', 'section', 'for', 'future', 'smoking.', '«short', 'cigarette,', 'tobacco', 'section', '30', 'mm.', '«extremely', 'fast', 'buming', 'cigarette.', '«novel', 'cigarette', 'constructions', 'that', 'permit', 'a', 'significant', 'reduction', 'iretobacco', 'weight', 'while', 'maintaining', 'smoking', 'mechanics', 'and', 'visual', 'characteristics.', 'higher', 'basis', 'weight', 'paper:', 'potential', 'reduction', 'in', 'tobacco', 'weight.', '«more', 'rigid', 'tobacco', 'column;', 'stiffing', 'agent', 'for', 'tobacco;', 'e.g.', 'starch', '*colored', 'tow', 'and', 'cigarette', 'papers;', 'seasonal', 'promotions,', 'e.g.', 'pastel', 'colored', 'cigarettes', 'for', 'easter', 'or', 'in', 'an', 'ebony', 'and', 'ivory', 'brand', 'containing', 'a', 'mixture', 'of', 'all', 'black', '(black', 'paper', 'and', 'tow)', 'and', 'ail', 'white', 'cigarettes.', '499150498']
|
| 246 |
+
Answer: T.F. Riehl
|
| 247 |
+
start_index 17
|
| 248 |
+
end_index 18
|
| 249 |
+
```
|
| 250 |
+
|
| 251 |
+
Once examples are encoded, however, they will look like this:
|
| 252 |
+
|
| 253 |
+
```py
|
| 254 |
+
>>> encoding = tokenizer(example["question"], example["words"], example["boxes"])
|
| 255 |
+
>>> tokenizer.decode(encoding["input_ids"])
|
| 256 |
+
[CLS] who is in cc in this letter? [SEP] wie baw brown & williamson tobacco corporation research & development ...
|
| 257 |
+
```
|
| 258 |
+
|
| 259 |
+
We'll need to find the position of the answer in the encoded input.
|
| 260 |
+
* `token_type_ids` tells us which tokens are part of the question, and which ones are part of the document's words.
|
| 261 |
+
* `tokenizer.cls_token_id` will help find the special token at the beginning of the input.
|
| 262 |
+
* `word_ids` will help match the answer found in the original `words` to the same answer in the full encoded input and determine
|
| 263 |
+
the start/end position of the answer in the encoded input.
|
| 264 |
+
|
| 265 |
+
With that in mind, let's create a function to encode a batch of examples in the dataset:
|
| 266 |
+
|
| 267 |
+
```py
|
| 268 |
+
>>> def encode_dataset(examples, max_length=512):
|
| 269 |
+
... questions = examples["question"]
|
| 270 |
+
... words = examples["words"]
|
| 271 |
+
... boxes = examples["boxes"]
|
| 272 |
+
... answers = examples["answer"]
|
| 273 |
+
|
| 274 |
+
... # encode the batch of examples and initialize the start_positions and end_positions
|
| 275 |
+
... encoding = tokenizer(questions, words, boxes, max_length=max_length, padding="max_length", truncation=True)
|
| 276 |
+
... start_positions = []
|
| 277 |
+
... end_positions = []
|
| 278 |
+
|
| 279 |
+
... # loop through the examples in the batch
|
| 280 |
+
... for i in range(len(questions)):
|
| 281 |
+
... cls_index = encoding["input_ids"][i].index(tokenizer.cls_token_id)
|
| 282 |
+
|
| 283 |
+
... # find the position of the answer in example's words
|
| 284 |
+
... words_example = [word.lower() for word in words[i]]
|
| 285 |
+
... answer = answers[i]
|
| 286 |
+
... match, word_idx_start, word_idx_end = subfinder(words_example, answer.lower().split())
|
| 287 |
+
|
| 288 |
+
... if match:
|
| 289 |
+
... # if match is found, use `token_type_ids` to find where words start in the encoding
|
| 290 |
+
... token_type_ids = encoding["token_type_ids"][i]
|
| 291 |
+
... token_start_index = 0
|
| 292 |
+
... while token_type_ids[token_start_index] != 1:
|
| 293 |
+
... token_start_index += 1
|
| 294 |
+
|
| 295 |
+
... token_end_index = len(encoding["input_ids"][i]) - 1
|
| 296 |
+
... while token_type_ids[token_end_index] != 1:
|
| 297 |
+
... token_end_index -= 1
|
| 298 |
+
|
| 299 |
+
... word_ids = encoding.word_ids(i)[token_start_index : token_end_index + 1]
|
| 300 |
+
... start_position = cls_index
|
| 301 |
+
... end_position = cls_index
|
| 302 |
+
|
| 303 |
+
... # loop over word_ids and increase `token_start_index` until it matches the answer position in words
|
| 304 |
+
... # once it matches, save the `token_start_index` as the `start_position` of the answer in the encoding
|
| 305 |
+
... for id in word_ids:
|
| 306 |
+
... if id == word_idx_start:
|
| 307 |
+
... start_position = token_start_index
|
| 308 |
+
... else:
|
| 309 |
+
... token_start_index += 1
|
| 310 |
+
|
| 311 |
+
... # similarly loop over `word_ids` starting from the end to find the `end_position` of the answer
|
| 312 |
+
... for id in word_ids[::-1]:
|
| 313 |
+
... if id == word_idx_end:
|
| 314 |
+
... end_position = token_end_index
|
| 315 |
+
... else:
|
| 316 |
+
... token_end_index -= 1
|
| 317 |
+
|
| 318 |
+
... start_positions.append(start_position)
|
| 319 |
+
... end_positions.append(end_position)
|
| 320 |
+
|
| 321 |
+
... else:
|
| 322 |
+
... start_positions.append(cls_index)
|
| 323 |
+
... end_positions.append(cls_index)
|
| 324 |
+
|
| 325 |
+
... encoding["image"] = examples["image"]
|
| 326 |
+
... encoding["start_positions"] = start_positions
|
| 327 |
+
... encoding["end_positions"] = end_positions
|
| 328 |
+
|
| 329 |
+
... return encoding
|
| 330 |
+
```
|
| 331 |
+
|
| 332 |
+
Now that we have this preprocessing function, we can encode the entire dataset:
|
| 333 |
+
|
| 334 |
+
```py
|
| 335 |
+
>>> encoded_train_dataset = dataset_with_ocr["train"].map(
|
| 336 |
+
... encode_dataset, batched=True, batch_size=2, remove_columns=dataset_with_ocr["train"].column_names
|
| 337 |
+
... )
|
| 338 |
+
>>> encoded_test_dataset = dataset_with_ocr["test"].map(
|
| 339 |
+
... encode_dataset, batched=True, batch_size=2, remove_columns=dataset_with_ocr["test"].column_names
|
| 340 |
+
... )
|
| 341 |
+
```
|
| 342 |
+
|
| 343 |
+
Let's check what the features of the encoded dataset look like:
|
| 344 |
+
|
| 345 |
+
```py
|
| 346 |
+
>>> encoded_train_dataset.features
|
| 347 |
+
{'image': Sequence(feature=Sequence(feature=Sequence(feature=Value(dtype='uint8', id=None), length=-1, id=None), length=-1, id=None), length=-1, id=None),
|
| 348 |
+
'input_ids': Sequence(feature=Value(dtype='int32', id=None), length=-1, id=None),
|
| 349 |
+
'token_type_ids': Sequence(feature=Value(dtype='int8', id=None), length=-1, id=None),
|
| 350 |
+
'attention_mask': Sequence(feature=Value(dtype='int8', id=None), length=-1, id=None),
|
| 351 |
+
'bbox': Sequence(feature=Sequence(feature=Value(dtype='int64', id=None), length=-1, id=None), length=-1, id=None),
|
| 352 |
+
'start_positions': Value(dtype='int64', id=None),
|
| 353 |
+
'end_positions': Value(dtype='int64', id=None)}
|
| 354 |
+
```
|
| 355 |
+
|
| 356 |
+
## Evaluation
|
| 357 |
+
|
| 358 |
+
Evaluation for document question answering requires a significant amount of postprocessing. To avoid taking up too much
|
| 359 |
+
of your time, this guide skips the evaluation step. The [`Trainer`] still calculates the evaluation loss during training so
|
| 360 |
+
you're not completely in the dark about your model's performance. Extractive question answering is typically evaluated using F1/exact match.
|
| 361 |
+
If you'd like to implement it yourself, check out the [Question Answering chapter](https://huggingface.co/course/chapter7/7?fw=pt#postprocessing)
|
| 362 |
+
of the Hugging Face course for inspiration.
|
| 363 |
+
|
| 364 |
+
## Train
|
| 365 |
+
|
| 366 |
+
Congratulations! You've successfully navigated the toughest part of this guide and now you are ready to train your own model.
|
| 367 |
+
Training involves the following steps:
|
| 368 |
+
* Load the model with [`AutoModelForDocumentQuestionAnswering`] using the same checkpoint as in the preprocessing.
|
| 369 |
+
* Define your training hyperparameters in [`TrainingArguments`].
|
| 370 |
+
* Define a function to batch examples together, here the [`DefaultDataCollator`] will do just fine
|
| 371 |
+
* Pass the training arguments to [`Trainer`] along with the model, dataset, and data collator.
|
| 372 |
+
* Call [`~Trainer.train`] to finetune your model.
|
| 373 |
+
|
| 374 |
+
```py
|
| 375 |
+
>>> from transformers import AutoModelForDocumentQuestionAnswering
|
| 376 |
+
|
| 377 |
+
>>> model = AutoModelForDocumentQuestionAnswering.from_pretrained(model_checkpoint)
|
| 378 |
+
```
|
| 379 |
+
|
| 380 |
+
In the [`TrainingArguments`] use `output_dir` to specify where to save your model, and configure hyperparameters as you see fit.
|
| 381 |
+
If you wish to share your model with the community, set `push_to_hub` to `True` (you must be signed in to Hugging Face to upload your model).
|
| 382 |
+
In this case the `output_dir` will also be the name of the repo where your model checkpoint will be pushed.
|
| 383 |
+
|
| 384 |
+
```py
|
| 385 |
+
>>> from transformers import TrainingArguments
|
| 386 |
+
|
| 387 |
+
>>> # REPLACE THIS WITH YOUR REPO ID
|
| 388 |
+
>>> repo_id = "MariaK/layoutlmv2-base-uncased_finetuned_docvqa"
|
| 389 |
+
|
| 390 |
+
>>> training_args = TrainingArguments(
|
| 391 |
+
... output_dir=repo_id,
|
| 392 |
+
... per_device_train_batch_size=4,
|
| 393 |
+
... num_train_epochs=20,
|
| 394 |
+
... save_steps=200,
|
| 395 |
+
... logging_steps=50,
|
| 396 |
+
... eval_strategy="steps",
|
| 397 |
+
... learning_rate=5e-5,
|
| 398 |
+
... save_total_limit=2,
|
| 399 |
+
... remove_unused_columns=False,
|
| 400 |
+
... push_to_hub=True,
|
| 401 |
+
... )
|
| 402 |
+
```
|
| 403 |
+
|
| 404 |
+
Define a simple data collator to batch examples together.
|
| 405 |
+
|
| 406 |
+
```py
|
| 407 |
+
>>> from transformers import DefaultDataCollator
|
| 408 |
+
|
| 409 |
+
>>> data_collator = DefaultDataCollator()
|
| 410 |
+
```
|
| 411 |
+
|
| 412 |
+
Finally, bring everything together, and call [`~Trainer.train`]:
|
| 413 |
+
|
| 414 |
+
```py
|
| 415 |
+
>>> from transformers import Trainer
|
| 416 |
+
|
| 417 |
+
>>> trainer = Trainer(
|
| 418 |
+
... model=model,
|
| 419 |
+
... args=training_args,
|
| 420 |
+
... data_collator=data_collator,
|
| 421 |
+
... train_dataset=encoded_train_dataset,
|
| 422 |
+
... eval_dataset=encoded_test_dataset,
|
| 423 |
+
... processing_class=processor,
|
| 424 |
+
... )
|
| 425 |
+
|
| 426 |
+
>>> trainer.train()
|
| 427 |
+
```
|
| 428 |
+
|
| 429 |
+
To add the final model to 🤗 Hub, create a model card and call `push_to_hub`:
|
| 430 |
+
|
| 431 |
+
```py
|
| 432 |
+
>>> trainer.create_model_card()
|
| 433 |
+
>>> trainer.push_to_hub()
|
| 434 |
+
```
|
| 435 |
+
|
| 436 |
+
## Inference
|
| 437 |
+
|
| 438 |
+
Now that you have finetuned a LayoutLMv2 model, and uploaded it to the 🤗 Hub, you can use it for inference. The simplest
|
| 439 |
+
way to try out your finetuned model for inference is to use it in a [`Pipeline`].
|
| 440 |
+
|
| 441 |
+
Let's take an example:
|
| 442 |
+
```py
|
| 443 |
+
>>> example = dataset["test"][2]
|
| 444 |
+
>>> question = example["query"]["en"]
|
| 445 |
+
>>> image = example["image"]
|
| 446 |
+
>>> print(question)
|
| 447 |
+
>>> print(example["answers"])
|
| 448 |
+
'Who is ‘presiding’ TRRF GENERAL SESSION (PART 1)?'
|
| 449 |
+
['TRRF Vice President', 'lee a. waller']
|
| 450 |
+
```
|
| 451 |
+
|
| 452 |
+
Next, instantiate a pipeline for
|
| 453 |
+
document question answering with your model, and pass the image + question combination to it.
|
| 454 |
+
|
| 455 |
+
```py
|
| 456 |
+
>>> from transformers import pipeline
|
| 457 |
+
|
| 458 |
+
>>> qa_pipeline = pipeline("document-question-answering", model="MariaK/layoutlmv2-base-uncased_finetuned_docvqa")
|
| 459 |
+
>>> qa_pipeline(image, question)
|
| 460 |
+
[{'score': 0.9949808120727539,
|
| 461 |
+
'answer': 'Lee A. Waller',
|
| 462 |
+
'start': 55,
|
| 463 |
+
'end': 57}]
|
| 464 |
+
```
|
| 465 |
+
|
| 466 |
+
You can also manually replicate the results of the pipeline if you'd like:
|
| 467 |
+
1. Take an image and a question, prepare them for the model using the processor from your model.
|
| 468 |
+
2. Forward the result or preprocessing through the model.
|
| 469 |
+
3. The model returns `start_logits` and `end_logits`, which indicate which token is at the start of the answer and
|
| 470 |
+
which token is at the end of the answer. Both have shape (batch_size, sequence_length).
|
| 471 |
+
4. Take an argmax on the last dimension of both the `start_logits` and `end_logits` to get the predicted `start_idx` and `end_idx`.
|
| 472 |
+
5. Decode the answer with the tokenizer.
|
| 473 |
+
|
| 474 |
+
```py
|
| 475 |
+
>>> import torch
|
| 476 |
+
>>> from transformers import AutoProcessor
|
| 477 |
+
>>> from transformers import AutoModelForDocumentQuestionAnswering
|
| 478 |
+
|
| 479 |
+
>>> processor = AutoProcessor.from_pretrained("MariaK/layoutlmv2-base-uncased_finetuned_docvqa")
|
| 480 |
+
>>> model = AutoModelForDocumentQuestionAnswering.from_pretrained("MariaK/layoutlmv2-base-uncased_finetuned_docvqa")
|
| 481 |
+
|
| 482 |
+
>>> with torch.no_grad():
|
| 483 |
+
... encoding = processor(image.convert("RGB"), question, return_tensors="pt")
|
| 484 |
+
... outputs = model(**encoding)
|
| 485 |
+
... start_logits = outputs.start_logits
|
| 486 |
+
... end_logits = outputs.end_logits
|
| 487 |
+
... predicted_start_idx = start_logits.argmax(-1).item()
|
| 488 |
+
... predicted_end_idx = end_logits.argmax(-1).item()
|
| 489 |
+
|
| 490 |
+
>>> processor.tokenizer.decode(encoding.input_ids.squeeze()[predicted_start_idx : predicted_end_idx + 1])
|
| 491 |
+
'lee a. waller'
|
| 492 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/idefics.md
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 17 |
+
# Image tasks with IDEFICS
|
| 18 |
+
|
| 19 |
+
[[open-in-colab]]
|
| 20 |
+
|
| 21 |
+
While individual tasks can be tackled by fine-tuning specialized models, an alternative approach
|
| 22 |
+
that has recently emerged and gained popularity is to use large models for a diverse set of tasks without fine-tuning.
|
| 23 |
+
For instance, large language models can handle such NLP tasks as summarization, translation, classification, and more.
|
| 24 |
+
This approach is no longer limited to a single modality, such as text, and in this guide, we will illustrate how you can
|
| 25 |
+
solve image-text tasks with a large multimodal model called IDEFICS.
|
| 26 |
+
|
| 27 |
+
[IDEFICS](../model_doc/idefics) is an open-access vision and language model based on [Flamingo](https://huggingface.co/papers/2204.14198),
|
| 28 |
+
a state-of-the-art visual language model initially developed by DeepMind. The model accepts arbitrary sequences of image
|
| 29 |
+
and text inputs and generates coherent text as output. It can answer questions about images, describe visual content,
|
| 30 |
+
create stories grounded in multiple images, and so on. IDEFICS comes in two variants - [80 billion parameters](https://huggingface.co/HuggingFaceM4/idefics-80b)
|
| 31 |
+
and [9 billion parameters](https://huggingface.co/HuggingFaceM4/idefics-9b), both of which are available on the 🤗 Hub. For each variant, you can also find fine-tuned instructed
|
| 32 |
+
versions of the model adapted for conversational use cases.
|
| 33 |
+
|
| 34 |
+
This model is exceptionally versatile and can be used for a wide range of image and multimodal tasks. However,
|
| 35 |
+
being a large model means it requires significant computational resources and infrastructure. It is up to you to decide whether
|
| 36 |
+
this approach suits your use case better than fine-tuning specialized models for each individual task.
|
| 37 |
+
|
| 38 |
+
In this guide, you'll learn how to:
|
| 39 |
+
- [Load IDEFICS](#loading-the-model) and [load the quantized version of the model](#quantized-model)
|
| 40 |
+
- Use IDEFICS for:
|
| 41 |
+
- [Image captioning](#image-captioning)
|
| 42 |
+
- [Prompted image captioning](#prompted-image-captioning)
|
| 43 |
+
- [Few-shot prompting](#few-shot-prompting)
|
| 44 |
+
- [Visual question answering](#visual-question-answering)
|
| 45 |
+
- [Image classification](#image-classification)
|
| 46 |
+
- [Image-guided text generation](#image-guided-text-generation)
|
| 47 |
+
- [Run inference in batch mode](#running-inference-in-batch-mode)
|
| 48 |
+
- [Run IDEFICS instruct for conversational use](#idefics-instruct-for-conversational-use)
|
| 49 |
+
|
| 50 |
+
Before you begin, make sure you have all the necessary libraries installed.
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
pip install -q bitsandbytes sentencepiece accelerate transformers
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
<Tip>
|
| 57 |
+
To run the following examples with a non-quantized version of the model checkpoint you will need at least 20GB of GPU memory.
|
| 58 |
+
</Tip>
|
| 59 |
+
|
| 60 |
+
## Loading the model
|
| 61 |
+
|
| 62 |
+
Let's start by loading the model's 9 billion parameters checkpoint:
|
| 63 |
+
|
| 64 |
+
```py
|
| 65 |
+
>>> checkpoint = "HuggingFaceM4/idefics-9b"
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
Just like for other Transformers models, you need to load a processor and the model itself from the checkpoint.
|
| 69 |
+
The IDEFICS processor wraps a [`LlamaTokenizer`] and IDEFICS image processor into a single processor to take care of
|
| 70 |
+
preparing text and image inputs for the model.
|
| 71 |
+
|
| 72 |
+
```py
|
| 73 |
+
>>> import torch
|
| 74 |
+
|
| 75 |
+
>>> from transformers import IdeficsForVisionText2Text, AutoProcessor
|
| 76 |
+
|
| 77 |
+
>>> processor = AutoProcessor.from_pretrained(checkpoint)
|
| 78 |
+
|
| 79 |
+
>>> model = IdeficsForVisionText2Text.from_pretrained(checkpoint, torch_dtype=torch.bfloat16, device_map="auto")
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
Setting `device_map` to `"auto"` will automatically determine how to load and store the model weights in the most optimized
|
| 83 |
+
manner given existing devices.
|
| 84 |
+
|
| 85 |
+
### Quantized model
|
| 86 |
+
|
| 87 |
+
If high-memory device availability is an issue, you can load the quantized version of the model. To load the model and the
|
| 88 |
+
processor in 4bit precision, pass a `BitsAndBytesConfig` to the `from_pretrained` method and the model will be compressed
|
| 89 |
+
on the fly while loading.
|
| 90 |
+
|
| 91 |
+
```py
|
| 92 |
+
>>> import torch
|
| 93 |
+
>>> from transformers import IdeficsForVisionText2Text, AutoProcessor, BitsAndBytesConfig
|
| 94 |
+
|
| 95 |
+
>>> quantization_config = BitsAndBytesConfig(
|
| 96 |
+
... load_in_4bit=True,
|
| 97 |
+
... bnb_4bit_compute_dtype=torch.float16,
|
| 98 |
+
... )
|
| 99 |
+
|
| 100 |
+
>>> processor = AutoProcessor.from_pretrained(checkpoint)
|
| 101 |
+
|
| 102 |
+
>>> model = IdeficsForVisionText2Text.from_pretrained(
|
| 103 |
+
... checkpoint,
|
| 104 |
+
... quantization_config=quantization_config,
|
| 105 |
+
... device_map="auto"
|
| 106 |
+
... )
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
Now that you have the model loaded in one of the suggested ways, let's move on to exploring tasks that you can use IDEFICS for.
|
| 110 |
+
|
| 111 |
+
## Image captioning
|
| 112 |
+
Image captioning is the task of predicting a caption for a given image. A common application is to aid visually impaired
|
| 113 |
+
people navigate through different situations, for instance, explore image content online.
|
| 114 |
+
|
| 115 |
+
To illustrate the task, get an image to be captioned, e.g.:
|
| 116 |
+
|
| 117 |
+
<div class="flex justify-center">
|
| 118 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-im-captioning.jpg" alt="Image of a puppy in a flower bed"/>
|
| 119 |
+
</div>
|
| 120 |
+
|
| 121 |
+
Photo by [Hendo Wang](https://unsplash.com/@hendoo).
|
| 122 |
+
|
| 123 |
+
IDEFICS accepts text and image prompts. However, to caption an image, you do not have to provide a text prompt to the
|
| 124 |
+
model, only the preprocessed input image. Without a text prompt, the model will start generating text from the
|
| 125 |
+
BOS (beginning-of-sequence) token thus creating a caption.
|
| 126 |
+
|
| 127 |
+
As image input to the model, you can use either an image object (`PIL.Image`) or a url from which the image can be retrieved.
|
| 128 |
+
|
| 129 |
+
```py
|
| 130 |
+
>>> prompt = [
|
| 131 |
+
... "https://images.unsplash.com/photo-1583160247711-2191776b4b91?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=3542&q=80",
|
| 132 |
+
... ]
|
| 133 |
+
|
| 134 |
+
>>> inputs = processor(prompt, return_tensors="pt").to(model.device)
|
| 135 |
+
>>> bad_words_ids = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
|
| 136 |
+
|
| 137 |
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=10, bad_words_ids=bad_words_ids)
|
| 138 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 139 |
+
>>> print(generated_text[0])
|
| 140 |
+
A puppy in a flower bed
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
<Tip>
|
| 144 |
+
|
| 145 |
+
It is a good idea to include the `bad_words_ids` in the call to `generate` to avoid errors arising when increasing
|
| 146 |
+
the `max_new_tokens`: the model will want to generate a new `<image>` or `<fake_token_around_image>` token when there
|
| 147 |
+
is no image being generated by the model.
|
| 148 |
+
You can set it on-the-fly as in this guide, or store in the `GenerationConfig` as described in the [Text generation strategies](../generation_strategies) guide.
|
| 149 |
+
</Tip>
|
| 150 |
+
|
| 151 |
+
## Prompted image captioning
|
| 152 |
+
|
| 153 |
+
You can extend image captioning by providing a text prompt, which the model will continue given the image. Let's take
|
| 154 |
+
another image to illustrate:
|
| 155 |
+
|
| 156 |
+
<div class="flex justify-center">
|
| 157 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-prompted-im-captioning.jpg" alt="Image of the Eiffel Tower at night"/>
|
| 158 |
+
</div>
|
| 159 |
+
|
| 160 |
+
Photo by [Denys Nevozhai](https://unsplash.com/@dnevozhai).
|
| 161 |
+
|
| 162 |
+
Textual and image prompts can be passed to the model's processor as a single list to create appropriate inputs.
|
| 163 |
+
|
| 164 |
+
```py
|
| 165 |
+
>>> prompt = [
|
| 166 |
+
... "https://images.unsplash.com/photo-1543349689-9a4d426bee8e?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=3501&q=80",
|
| 167 |
+
... "This is an image of ",
|
| 168 |
+
... ]
|
| 169 |
+
|
| 170 |
+
>>> inputs = processor(prompt, return_tensors="pt").to(model.device)
|
| 171 |
+
>>> bad_words_ids = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
|
| 172 |
+
|
| 173 |
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=10, bad_words_ids=bad_words_ids)
|
| 174 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 175 |
+
>>> print(generated_text[0])
|
| 176 |
+
This is an image of the Eiffel Tower in Paris, France.
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
## Few-shot prompting
|
| 180 |
+
|
| 181 |
+
While IDEFICS demonstrates great zero-shot results, your task may require a certain format of the caption, or come with
|
| 182 |
+
other restrictions or requirements that increase task's complexity. Few-shot prompting can be used to enable in-context learning.
|
| 183 |
+
By providing examples in the prompt, you can steer the model to generate results that mimic the format of given examples.
|
| 184 |
+
|
| 185 |
+
Let's use the previous image of the Eiffel Tower as an example for the model and build a prompt that demonstrates to the model
|
| 186 |
+
that in addition to learning what the object in an image is, we would also like to get some interesting information about it.
|
| 187 |
+
Then, let's see, if we can get the same response format for an image of the Statue of Liberty:
|
| 188 |
+
|
| 189 |
+
<div class="flex justify-center">
|
| 190 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg" alt="Image of the Statue of Liberty"/>
|
| 191 |
+
</div>
|
| 192 |
+
|
| 193 |
+
Photo by [Juan Mayobre](https://unsplash.com/@jmayobres).
|
| 194 |
+
|
| 195 |
+
```py
|
| 196 |
+
>>> prompt = ["User:",
|
| 197 |
+
... "https://images.unsplash.com/photo-1543349689-9a4d426bee8e?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=3501&q=80",
|
| 198 |
+
... "Describe this image.\nAssistant: An image of the Eiffel Tower at night. Fun fact: the Eiffel Tower is the same height as an 81-storey building.\n",
|
| 199 |
+
... "User:",
|
| 200 |
+
... "https://images.unsplash.com/photo-1524099163253-32b7f0256868?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=3387&q=80",
|
| 201 |
+
... "Describe this image.\nAssistant:"
|
| 202 |
+
... ]
|
| 203 |
+
|
| 204 |
+
>>> inputs = processor(prompt, return_tensors="pt").to(model.device)
|
| 205 |
+
>>> bad_words_ids = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
|
| 206 |
+
|
| 207 |
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=30, bad_words_ids=bad_words_ids)
|
| 208 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 209 |
+
>>> print(generated_text[0])
|
| 210 |
+
User: Describe this image.
|
| 211 |
+
Assistant: An image of the Eiffel Tower at night. Fun fact: the Eiffel Tower is the same height as an 81-storey building.
|
| 212 |
+
User: Describe this image.
|
| 213 |
+
Assistant: An image of the Statue of Liberty. Fun fact: the Statue of Liberty is 151 feet tall.
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
Notice that just from a single example (i.e., 1-shot) the model has learned how to perform the task. For more complex tasks,
|
| 217 |
+
feel free to experiment with a larger number of examples (e.g., 3-shot, 5-shot, etc.).
|
| 218 |
+
|
| 219 |
+
## Visual question answering
|
| 220 |
+
|
| 221 |
+
Visual Question Answering (VQA) is the task of answering open-ended questions based on an image. Similar to image
|
| 222 |
+
captioning it can be used in accessibility applications, but also in education (reasoning about visual materials), customer
|
| 223 |
+
service (questions about products based on images), and image retrieval.
|
| 224 |
+
|
| 225 |
+
Let's get a new image for this task:
|
| 226 |
+
|
| 227 |
+
<div class="flex justify-center">
|
| 228 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-vqa.jpg" alt="Image of a couple having a picnic"/>
|
| 229 |
+
</div>
|
| 230 |
+
|
| 231 |
+
Photo by [Jarritos Mexican Soda](https://unsplash.com/@jarritos).
|
| 232 |
+
|
| 233 |
+
You can steer the model from image captioning to visual question answering by prompting it with appropriate instructions:
|
| 234 |
+
|
| 235 |
+
```py
|
| 236 |
+
>>> prompt = [
|
| 237 |
+
... "Instruction: Provide an answer to the question. Use the image to answer.\n",
|
| 238 |
+
... "https://images.unsplash.com/photo-1623944889288-cd147dbb517c?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=3540&q=80",
|
| 239 |
+
... "Question: Where are these people and what's the weather like? Answer:"
|
| 240 |
+
... ]
|
| 241 |
+
|
| 242 |
+
>>> inputs = processor(prompt, return_tensors="pt").to(model.device)
|
| 243 |
+
>>> bad_words_ids = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
|
| 244 |
+
|
| 245 |
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=20, bad_words_ids=bad_words_ids)
|
| 246 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 247 |
+
>>> print(generated_text[0])
|
| 248 |
+
Instruction: Provide an answer to the question. Use the image to answer.
|
| 249 |
+
Question: Where are these people and what's the weather like? Answer: They're in a park in New York City, and it's a beautiful day.
|
| 250 |
+
```
|
| 251 |
+
|
| 252 |
+
## Image classification
|
| 253 |
+
|
| 254 |
+
IDEFICS is capable of classifying images into different categories without being explicitly trained on data containing
|
| 255 |
+
labeled examples from those specific categories. Given a list of categories and using its image and text understanding
|
| 256 |
+
capabilities, the model can infer which category the image likely belongs to.
|
| 257 |
+
|
| 258 |
+
Say, we have this image of a vegetable stand:
|
| 259 |
+
|
| 260 |
+
<div class="flex justify-center">
|
| 261 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-classification.jpg" alt="Image of a vegetable stand"/>
|
| 262 |
+
</div>
|
| 263 |
+
|
| 264 |
+
Photo by [Peter Wendt](https://unsplash.com/@peterwendt).
|
| 265 |
+
|
| 266 |
+
We can instruct the model to classify the image into one of the categories that we have:
|
| 267 |
+
|
| 268 |
+
```py
|
| 269 |
+
>>> categories = ['animals','vegetables', 'city landscape', 'cars', 'office']
|
| 270 |
+
>>> prompt = [f"Instruction: Classify the following image into a single category from the following list: {categories}.\n",
|
| 271 |
+
... "https://images.unsplash.com/photo-1471193945509-9ad0617afabf?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=3540&q=80",
|
| 272 |
+
... "Category: "
|
| 273 |
+
... ]
|
| 274 |
+
|
| 275 |
+
>>> inputs = processor(prompt, return_tensors="pt").to(model.device)
|
| 276 |
+
>>> bad_words_ids = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
|
| 277 |
+
|
| 278 |
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=6, bad_words_ids=bad_words_ids)
|
| 279 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 280 |
+
>>> print(generated_text[0])
|
| 281 |
+
Instruction: Classify the following image into a single category from the following list: ['animals', 'vegetables', 'city landscape', 'cars', 'office'].
|
| 282 |
+
Category: Vegetables
|
| 283 |
+
```
|
| 284 |
+
|
| 285 |
+
In the example above we instruct the model to classify the image into a single category, however, you can also prompt the model to do rank classification.
|
| 286 |
+
|
| 287 |
+
## Image-guided text generation
|
| 288 |
+
|
| 289 |
+
For more creative applications, you can use image-guided text generation to generate text based on an image. This can be
|
| 290 |
+
useful to create descriptions of products, ads, descriptions of a scene, etc.
|
| 291 |
+
|
| 292 |
+
Let's prompt IDEFICS to write a story based on a simple image of a red door:
|
| 293 |
+
|
| 294 |
+
<div class="flex justify-center">
|
| 295 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-story-generation.jpg" alt="Image of a red door with a pumpkin on the steps"/>
|
| 296 |
+
</div>
|
| 297 |
+
|
| 298 |
+
Photo by [Craig Tidball](https://unsplash.com/@devonshiremedia).
|
| 299 |
+
|
| 300 |
+
```py
|
| 301 |
+
>>> prompt = ["Instruction: Use the image to write a story. \n",
|
| 302 |
+
... "https://images.unsplash.com/photo-1517086822157-2b0358e7684a?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2203&q=80",
|
| 303 |
+
... "Story: \n"]
|
| 304 |
+
|
| 305 |
+
>>> inputs = processor(prompt, return_tensors="pt").to(model.device)
|
| 306 |
+
>>> bad_words_ids = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
|
| 307 |
+
|
| 308 |
+
>>> generated_ids = model.generate(**inputs, num_beams=2, max_new_tokens=200, bad_words_ids=bad_words_ids)
|
| 309 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 310 |
+
>>> print(generated_text[0])
|
| 311 |
+
Instruction: Use the image to write a story.
|
| 312 |
+
Story:
|
| 313 |
+
Once upon a time, there was a little girl who lived in a house with a red door. She loved her red door. It was the prettiest door in the whole world.
|
| 314 |
+
|
| 315 |
+
One day, the little girl was playing in her yard when she noticed a man standing on her doorstep. He was wearing a long black coat and a top hat.
|
| 316 |
+
|
| 317 |
+
The little girl ran inside and told her mother about the man.
|
| 318 |
+
|
| 319 |
+
Her mother said, “Don’t worry, honey. He’s just a friendly ghost.”
|
| 320 |
+
|
| 321 |
+
The little girl wasn’t sure if she believed her mother, but she went outside anyway.
|
| 322 |
+
|
| 323 |
+
When she got to the door, the man was gone.
|
| 324 |
+
|
| 325 |
+
The next day, the little girl was playing in her yard again when she noticed the man standing on her doorstep.
|
| 326 |
+
|
| 327 |
+
He was wearing a long black coat and a top hat.
|
| 328 |
+
|
| 329 |
+
The little girl ran
|
| 330 |
+
```
|
| 331 |
+
|
| 332 |
+
Looks like IDEFICS noticed the pumpkin on the doorstep and went with a spooky Halloween story about a ghost.
|
| 333 |
+
|
| 334 |
+
<Tip>
|
| 335 |
+
|
| 336 |
+
For longer outputs like this, you will greatly benefit from tweaking the text generation strategy. This can help
|
| 337 |
+
you significantly improve the quality of the generated output. Check out [Text generation strategies](../generation_strategies)
|
| 338 |
+
to learn more.
|
| 339 |
+
</Tip>
|
| 340 |
+
|
| 341 |
+
## Running inference in batch mode
|
| 342 |
+
|
| 343 |
+
All of the earlier sections illustrated IDEFICS for a single example. In a very similar fashion, you can run inference
|
| 344 |
+
for a batch of examples by passing a list of prompts:
|
| 345 |
+
|
| 346 |
+
```py
|
| 347 |
+
>>> prompts = [
|
| 348 |
+
... [ "https://images.unsplash.com/photo-1543349689-9a4d426bee8e?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=3501&q=80",
|
| 349 |
+
... "This is an image of ",
|
| 350 |
+
... ],
|
| 351 |
+
... [ "https://images.unsplash.com/photo-1623944889288-cd147dbb517c?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=3540&q=80",
|
| 352 |
+
... "This is an image of ",
|
| 353 |
+
... ],
|
| 354 |
+
... [ "https://images.unsplash.com/photo-1471193945509-9ad0617afabf?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=3540&q=80",
|
| 355 |
+
... "This is an image of ",
|
| 356 |
+
... ],
|
| 357 |
+
... ]
|
| 358 |
+
|
| 359 |
+
>>> inputs = processor(prompts, return_tensors="pt").to(model.device)
|
| 360 |
+
>>> bad_words_ids = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
|
| 361 |
+
|
| 362 |
+
>>> generated_ids = model.generate(**inputs, max_new_tokens=10, bad_words_ids=bad_words_ids)
|
| 363 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 364 |
+
>>> for i,t in enumerate(generated_text):
|
| 365 |
+
... print(f"{i}:\n{t}\n")
|
| 366 |
+
0:
|
| 367 |
+
This is an image of the Eiffel Tower in Paris, France.
|
| 368 |
+
|
| 369 |
+
1:
|
| 370 |
+
This is an image of a couple on a picnic blanket.
|
| 371 |
+
|
| 372 |
+
2:
|
| 373 |
+
This is an image of a vegetable stand.
|
| 374 |
+
```
|
| 375 |
+
|
| 376 |
+
## IDEFICS instruct for conversational use
|
| 377 |
+
|
| 378 |
+
For conversational use cases, you can find fine-tuned instructed versions of the model on the 🤗 Hub:
|
| 379 |
+
`HuggingFaceM4/idefics-80b-instruct` and `HuggingFaceM4/idefics-9b-instruct`.
|
| 380 |
+
|
| 381 |
+
These checkpoints are the result of fine-tuning the respective base models on a mixture of supervised and instruction
|
| 382 |
+
fine-tuning datasets, which boosts the downstream performance while making the models more usable in conversational settings.
|
| 383 |
+
|
| 384 |
+
The use and prompting for the conversational use is very similar to using the base models:
|
| 385 |
+
|
| 386 |
+
```py
|
| 387 |
+
>>> import torch
|
| 388 |
+
>>> from transformers import IdeficsForVisionText2Text, AutoProcessor
|
| 389 |
+
|
| 390 |
+
>>> checkpoint = "HuggingFaceM4/idefics-9b-instruct"
|
| 391 |
+
>>> model = IdeficsForVisionText2Text.from_pretrained(checkpoint, torch_dtype=torch.bfloat16, device_map="auto")
|
| 392 |
+
>>> processor = AutoProcessor.from_pretrained(checkpoint)
|
| 393 |
+
|
| 394 |
+
>>> prompts = [
|
| 395 |
+
... [
|
| 396 |
+
... "User: What is in this image?",
|
| 397 |
+
... "https://upload.wikimedia.org/wikipedia/commons/8/86/Id%C3%A9fix.JPG",
|
| 398 |
+
... "<end_of_utterance>",
|
| 399 |
+
|
| 400 |
+
... "\nAssistant: This picture depicts Idefix, the dog of Obelix in Asterix and Obelix. Idefix is running on the ground.<end_of_utterance>",
|
| 401 |
+
|
| 402 |
+
... "\nUser:",
|
| 403 |
+
... "https://static.wikia.nocookie.net/asterix/images/2/25/R22b.gif/revision/latest?cb=20110815073052",
|
| 404 |
+
... "And who is that?<end_of_utterance>",
|
| 405 |
+
|
| 406 |
+
... "\nAssistant:",
|
| 407 |
+
... ],
|
| 408 |
+
... ]
|
| 409 |
+
|
| 410 |
+
>>> # --batched mode
|
| 411 |
+
>>> inputs = processor(prompts, add_end_of_utterance_token=False, return_tensors="pt").to(model.device)
|
| 412 |
+
>>> # --single sample mode
|
| 413 |
+
>>> # inputs = processor(prompts[0], return_tensors="pt").to(model.device)
|
| 414 |
+
|
| 415 |
+
>>> # Generation args
|
| 416 |
+
>>> exit_condition = processor.tokenizer("<end_of_utterance>", add_special_tokens=False).input_ids
|
| 417 |
+
>>> bad_words_ids = processor.tokenizer(["<image>", "<fake_token_around_image>"], add_special_tokens=False).input_ids
|
| 418 |
+
|
| 419 |
+
>>> generated_ids = model.generate(**inputs, eos_token_id=exit_condition, bad_words_ids=bad_words_ids, max_length=100)
|
| 420 |
+
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
| 421 |
+
>>> for i, t in enumerate(generated_text):
|
| 422 |
+
... print(f"{i}:\n{t}\n")
|
| 423 |
+
```
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/image_captioning.md
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 17 |
+
|
| 18 |
+
# Image captioning
|
| 19 |
+
|
| 20 |
+
[[open-in-colab]]
|
| 21 |
+
|
| 22 |
+
Image captioning is the task of predicting a caption for a given image. Common real world applications of it include
|
| 23 |
+
aiding visually impaired people that can help them navigate through different situations. Therefore, image captioning
|
| 24 |
+
helps to improve content accessibility for people by describing images to them.
|
| 25 |
+
|
| 26 |
+
This guide will show you how to:
|
| 27 |
+
|
| 28 |
+
* Fine-tune an image captioning model.
|
| 29 |
+
* Use the fine-tuned model for inference.
|
| 30 |
+
|
| 31 |
+
Before you begin, make sure you have all the necessary libraries installed:
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
pip install transformers datasets evaluate -q
|
| 35 |
+
pip install jiwer -q
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
We encourage you to log in to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to log in:
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
from huggingface_hub import notebook_login
|
| 43 |
+
|
| 44 |
+
notebook_login()
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
## Load the Pokémon BLIP captions dataset
|
| 48 |
+
|
| 49 |
+
Use the 🤗 Dataset library to load a dataset that consists of {image-caption} pairs. To create your own image captioning dataset
|
| 50 |
+
in PyTorch, you can follow [this notebook](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/GIT/Fine_tune_GIT_on_an_image_captioning_dataset.ipynb).
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
from datasets import load_dataset
|
| 55 |
+
|
| 56 |
+
ds = load_dataset("lambdalabs/pokemon-blip-captions")
|
| 57 |
+
ds
|
| 58 |
+
```
|
| 59 |
+
```bash
|
| 60 |
+
DatasetDict({
|
| 61 |
+
train: Dataset({
|
| 62 |
+
features: ['image', 'text'],
|
| 63 |
+
num_rows: 833
|
| 64 |
+
})
|
| 65 |
+
})
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
The dataset has two features, `image` and `text`.
|
| 69 |
+
|
| 70 |
+
<Tip>
|
| 71 |
+
|
| 72 |
+
Many image captioning datasets contain multiple captions per image. In those cases, a common strategy is to randomly sample a caption amongst the available ones during training.
|
| 73 |
+
|
| 74 |
+
</Tip>
|
| 75 |
+
|
| 76 |
+
Split the dataset’s train split into a train and test set with the [`~datasets.Dataset.train_test_split`] method:
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
```python
|
| 80 |
+
ds = ds["train"].train_test_split(test_size=0.1)
|
| 81 |
+
train_ds = ds["train"]
|
| 82 |
+
test_ds = ds["test"]
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
Let's visualize a couple of samples from the training set.
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
```python
|
| 89 |
+
from textwrap import wrap
|
| 90 |
+
import matplotlib.pyplot as plt
|
| 91 |
+
import numpy as np
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def plot_images(images, captions):
|
| 95 |
+
plt.figure(figsize=(20, 20))
|
| 96 |
+
for i in range(len(images)):
|
| 97 |
+
ax = plt.subplot(1, len(images), i + 1)
|
| 98 |
+
caption = captions[i]
|
| 99 |
+
caption = "\n".join(wrap(caption, 12))
|
| 100 |
+
plt.title(caption)
|
| 101 |
+
plt.imshow(images[i])
|
| 102 |
+
plt.axis("off")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
sample_images_to_visualize = [np.array(train_ds[i]["image"]) for i in range(5)]
|
| 106 |
+
sample_captions = [train_ds[i]["text"] for i in range(5)]
|
| 107 |
+
plot_images(sample_images_to_visualize, sample_captions)
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
<div class="flex justify-center">
|
| 111 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/sample_training_images_image_cap.png" alt="Sample training images"/>
|
| 112 |
+
</div>
|
| 113 |
+
|
| 114 |
+
## Preprocess the dataset
|
| 115 |
+
|
| 116 |
+
Since the dataset has two modalities (image and text), the pre-processing pipeline will preprocess images and the captions.
|
| 117 |
+
|
| 118 |
+
To do so, load the processor class associated with the model you are about to fine-tune.
|
| 119 |
+
|
| 120 |
+
```python
|
| 121 |
+
from transformers import AutoProcessor
|
| 122 |
+
|
| 123 |
+
checkpoint = "microsoft/git-base"
|
| 124 |
+
processor = AutoProcessor.from_pretrained(checkpoint)
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
The processor will internally pre-process the image (which includes resizing, and pixel scaling) and tokenize the caption.
|
| 128 |
+
|
| 129 |
+
```python
|
| 130 |
+
def transforms(example_batch):
|
| 131 |
+
images = [x for x in example_batch["image"]]
|
| 132 |
+
captions = [x for x in example_batch["text"]]
|
| 133 |
+
inputs = processor(images=images, text=captions, padding="max_length")
|
| 134 |
+
inputs.update({"labels": inputs["input_ids"]})
|
| 135 |
+
return inputs
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
train_ds.set_transform(transforms)
|
| 139 |
+
test_ds.set_transform(transforms)
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
With the dataset ready, you can now set up the model for fine-tuning.
|
| 143 |
+
|
| 144 |
+
## Load a base model
|
| 145 |
+
|
| 146 |
+
Load the ["microsoft/git-base"](https://huggingface.co/microsoft/git-base) into a [`AutoModelForCausalLM`](https://huggingface.co/docs/transformers/model_doc/auto#transformers.AutoModelForCausalLM) object.
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
```python
|
| 150 |
+
from transformers import AutoModelForCausalLM
|
| 151 |
+
|
| 152 |
+
model = AutoModelForCausalLM.from_pretrained(checkpoint)
|
| 153 |
+
```
|
| 154 |
+
|
| 155 |
+
## Evaluate
|
| 156 |
+
|
| 157 |
+
Image captioning models are typically evaluated with the [Rouge Score](https://huggingface.co/spaces/evaluate-metric/rouge) or [Word Error Rate](https://huggingface.co/spaces/evaluate-metric/wer). For this guide, you will use the Word Error Rate (WER).
|
| 158 |
+
|
| 159 |
+
We use the 🤗 Evaluate library to do so. For potential limitations and other gotchas of the WER, refer to [this guide](https://huggingface.co/spaces/evaluate-metric/wer).
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
```python
|
| 163 |
+
from evaluate import load
|
| 164 |
+
import torch
|
| 165 |
+
|
| 166 |
+
wer = load("wer")
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def compute_metrics(eval_pred):
|
| 170 |
+
logits, labels = eval_pred
|
| 171 |
+
predicted = logits.argmax(-1)
|
| 172 |
+
decoded_labels = processor.batch_decode(labels, skip_special_tokens=True)
|
| 173 |
+
decoded_predictions = processor.batch_decode(predicted, skip_special_tokens=True)
|
| 174 |
+
wer_score = wer.compute(predictions=decoded_predictions, references=decoded_labels)
|
| 175 |
+
return {"wer_score": wer_score}
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
## Train!
|
| 179 |
+
|
| 180 |
+
Now, you are ready to start fine-tuning the model. You will use the 🤗 [`Trainer`] for this.
|
| 181 |
+
|
| 182 |
+
First, define the training arguments using [`TrainingArguments`].
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
```python
|
| 186 |
+
from transformers import TrainingArguments, Trainer
|
| 187 |
+
|
| 188 |
+
model_name = checkpoint.split("/")[1]
|
| 189 |
+
|
| 190 |
+
training_args = TrainingArguments(
|
| 191 |
+
output_dir=f"{model_name}-pokemon",
|
| 192 |
+
learning_rate=5e-5,
|
| 193 |
+
num_train_epochs=50,
|
| 194 |
+
fp16=True,
|
| 195 |
+
per_device_train_batch_size=32,
|
| 196 |
+
per_device_eval_batch_size=32,
|
| 197 |
+
gradient_accumulation_steps=2,
|
| 198 |
+
save_total_limit=3,
|
| 199 |
+
eval_strategy="steps",
|
| 200 |
+
eval_steps=50,
|
| 201 |
+
save_strategy="steps",
|
| 202 |
+
save_steps=50,
|
| 203 |
+
logging_steps=50,
|
| 204 |
+
remove_unused_columns=False,
|
| 205 |
+
push_to_hub=True,
|
| 206 |
+
label_names=["labels"],
|
| 207 |
+
load_best_model_at_end=True,
|
| 208 |
+
)
|
| 209 |
+
```
|
| 210 |
+
|
| 211 |
+
Then pass them along with the datasets and the model to 🤗 Trainer.
|
| 212 |
+
|
| 213 |
+
```python
|
| 214 |
+
trainer = Trainer(
|
| 215 |
+
model=model,
|
| 216 |
+
args=training_args,
|
| 217 |
+
train_dataset=train_ds,
|
| 218 |
+
eval_dataset=test_ds,
|
| 219 |
+
compute_metrics=compute_metrics,
|
| 220 |
+
)
|
| 221 |
+
```
|
| 222 |
+
|
| 223 |
+
To start training, simply call [`~Trainer.train`] on the [`Trainer`] object.
|
| 224 |
+
|
| 225 |
+
```python
|
| 226 |
+
trainer.train()
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
You should see the training loss drop smoothly as training progresses.
|
| 230 |
+
|
| 231 |
+
Once training is completed, share your model to the Hub with the [`~Trainer.push_to_hub`] method so everyone can use your model:
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
```python
|
| 235 |
+
trainer.push_to_hub()
|
| 236 |
+
```
|
| 237 |
+
|
| 238 |
+
## Inference
|
| 239 |
+
|
| 240 |
+
Take a sample image from `test_ds` to test the model.
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
```python
|
| 244 |
+
from PIL import Image
|
| 245 |
+
import requests
|
| 246 |
+
|
| 247 |
+
url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"
|
| 248 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
| 249 |
+
image
|
| 250 |
+
```
|
| 251 |
+
|
| 252 |
+
<div class="flex justify-center">
|
| 253 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/test_image_image_cap.png" alt="Test image"/>
|
| 254 |
+
</div>
|
| 255 |
+
|
| 256 |
+
Prepare image for the model.
|
| 257 |
+
|
| 258 |
+
```python
|
| 259 |
+
from transformers import infer_device
|
| 260 |
+
|
| 261 |
+
device = infer_device()
|
| 262 |
+
inputs = processor(images=image, return_tensors="pt").to(device)
|
| 263 |
+
pixel_values = inputs.pixel_values
|
| 264 |
+
```
|
| 265 |
+
|
| 266 |
+
Call [`generate`] and decode the predictions.
|
| 267 |
+
|
| 268 |
+
```python
|
| 269 |
+
generated_ids = model.generate(pixel_values=pixel_values, max_length=50)
|
| 270 |
+
generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 271 |
+
print(generated_caption)
|
| 272 |
+
```
|
| 273 |
+
```bash
|
| 274 |
+
a drawing of a pink and blue pokemon
|
| 275 |
+
```
|
| 276 |
+
|
| 277 |
+
Looks like the fine-tuned model generated a pretty good caption!
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/image_classification.md
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2022 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 |
+
|
| 17 |
+
# Image classification
|
| 18 |
+
|
| 19 |
+
[[open-in-colab]]
|
| 20 |
+
|
| 21 |
+
<Youtube id="tjAIM7BOYhw"/>
|
| 22 |
+
|
| 23 |
+
Image classification assigns a label or class to an image. Unlike text or audio classification, the inputs are the
|
| 24 |
+
pixel values that comprise an image. There are many applications for image classification, such as detecting damage
|
| 25 |
+
after a natural disaster, monitoring crop health, or helping screen medical images for signs of disease.
|
| 26 |
+
|
| 27 |
+
This guide illustrates how to:
|
| 28 |
+
|
| 29 |
+
1. Fine-tune [ViT](../model_doc/vit) on the [Food-101](https://huggingface.co/datasets/food101) dataset to classify a food item in an image.
|
| 30 |
+
2. Use your fine-tuned model for inference.
|
| 31 |
+
|
| 32 |
+
<Tip>
|
| 33 |
+
|
| 34 |
+
To see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/image-classification)
|
| 35 |
+
|
| 36 |
+
</Tip>
|
| 37 |
+
|
| 38 |
+
Before you begin, make sure you have all the necessary libraries installed:
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
pip install transformers datasets evaluate accelerate pillow torchvision scikit-learn
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
We encourage you to log in to your Hugging Face account to upload and share your model with the community. When prompted, enter your token to log in:
|
| 45 |
+
|
| 46 |
+
```py
|
| 47 |
+
>>> from huggingface_hub import notebook_login
|
| 48 |
+
|
| 49 |
+
>>> notebook_login()
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
## Load Food-101 dataset
|
| 53 |
+
|
| 54 |
+
Start by loading a smaller subset of the Food-101 dataset from the 🤗 Datasets library. This will give you a chance to
|
| 55 |
+
experiment and make sure everything works before spending more time training on the full dataset.
|
| 56 |
+
|
| 57 |
+
```py
|
| 58 |
+
>>> from datasets import load_dataset
|
| 59 |
+
|
| 60 |
+
>>> food = load_dataset("food101", split="train[:5000]")
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
Split the dataset's `train` split into a train and test set with the [`~datasets.Dataset.train_test_split`] method:
|
| 64 |
+
|
| 65 |
+
```py
|
| 66 |
+
>>> food = food.train_test_split(test_size=0.2)
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
Then take a look at an example:
|
| 70 |
+
|
| 71 |
+
```py
|
| 72 |
+
>>> food["train"][0]
|
| 73 |
+
{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=512x512 at 0x7F52AFC8AC50>,
|
| 74 |
+
'label': 79}
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
Each example in the dataset has two fields:
|
| 78 |
+
|
| 79 |
+
- `image`: a PIL image of the food item
|
| 80 |
+
- `label`: the label class of the food item
|
| 81 |
+
|
| 82 |
+
To make it easier for the model to get the label name from the label id, create a dictionary that maps the label name
|
| 83 |
+
to an integer and vice versa:
|
| 84 |
+
|
| 85 |
+
```py
|
| 86 |
+
>>> labels = food["train"].features["label"].names
|
| 87 |
+
>>> label2id, id2label = dict(), dict()
|
| 88 |
+
>>> for i, label in enumerate(labels):
|
| 89 |
+
... label2id[label] = str(i)
|
| 90 |
+
... id2label[str(i)] = label
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
Now you can convert the label id to a label name:
|
| 94 |
+
|
| 95 |
+
```py
|
| 96 |
+
>>> id2label[str(79)]
|
| 97 |
+
'prime_rib'
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
## Preprocess
|
| 101 |
+
|
| 102 |
+
The next step is to load a ViT image processor to process the image into a tensor:
|
| 103 |
+
|
| 104 |
+
```py
|
| 105 |
+
>>> from transformers import AutoImageProcessor
|
| 106 |
+
|
| 107 |
+
>>> checkpoint = "google/vit-base-patch16-224-in21k"
|
| 108 |
+
>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
<frameworkcontent>
|
| 112 |
+
<pt>
|
| 113 |
+
Apply some image transformations to the images to make the model more robust against overfitting. Here you'll use torchvision's [`transforms`](https://pytorch.org/vision/stable/transforms.html) module, but you can also use any image library you like.
|
| 114 |
+
|
| 115 |
+
Crop a random part of the image, resize it, and normalize it with the image mean and standard deviation:
|
| 116 |
+
|
| 117 |
+
```py
|
| 118 |
+
>>> from torchvision.transforms import RandomResizedCrop, Compose, Normalize, ToTensor
|
| 119 |
+
|
| 120 |
+
>>> normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)
|
| 121 |
+
>>> size = (
|
| 122 |
+
... image_processor.size["shortest_edge"]
|
| 123 |
+
... if "shortest_edge" in image_processor.size
|
| 124 |
+
... else (image_processor.size["height"], image_processor.size["width"])
|
| 125 |
+
... )
|
| 126 |
+
>>> _transforms = Compose([RandomResizedCrop(size), ToTensor(), normalize])
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
Then create a preprocessing function to apply the transforms and return the `pixel_values` - the inputs to the model - of the image:
|
| 130 |
+
|
| 131 |
+
```py
|
| 132 |
+
>>> def transforms(examples):
|
| 133 |
+
... examples["pixel_values"] = [_transforms(img.convert("RGB")) for img in examples["image"]]
|
| 134 |
+
... del examples["image"]
|
| 135 |
+
... return examples
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
To apply the preprocessing function over the entire dataset, use 🤗 Datasets [`~datasets.Dataset.with_transform`] method. The transforms are applied on the fly when you load an element of the dataset:
|
| 139 |
+
|
| 140 |
+
```py
|
| 141 |
+
>>> food = food.with_transform(transforms)
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
Now create a batch of examples using [`DefaultDataCollator`]. Unlike other data collators in 🤗 Transformers, the `DefaultDataCollator` does not apply additional preprocessing such as padding.
|
| 145 |
+
|
| 146 |
+
```py
|
| 147 |
+
>>> from transformers import DefaultDataCollator
|
| 148 |
+
|
| 149 |
+
>>> data_collator = DefaultDataCollator()
|
| 150 |
+
```
|
| 151 |
+
</pt>
|
| 152 |
+
</frameworkcontent>
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
<frameworkcontent>
|
| 156 |
+
<tf>
|
| 157 |
+
|
| 158 |
+
To avoid overfitting and to make the model more robust, add some data augmentation to the training part of the dataset.
|
| 159 |
+
Here we use Keras preprocessing layers to define the transformations for the training data (includes data augmentation),
|
| 160 |
+
and transformations for the validation data (only center cropping, resizing and normalizing). You can use `tf.image`or
|
| 161 |
+
any other library you prefer.
|
| 162 |
+
|
| 163 |
+
```py
|
| 164 |
+
>>> from tensorflow import keras
|
| 165 |
+
>>> from tensorflow.keras import layers
|
| 166 |
+
|
| 167 |
+
>>> size = (image_processor.size["height"], image_processor.size["width"])
|
| 168 |
+
|
| 169 |
+
>>> train_data_augmentation = keras.Sequential(
|
| 170 |
+
... [
|
| 171 |
+
... layers.RandomCrop(size[0], size[1]),
|
| 172 |
+
... layers.Rescaling(scale=1.0 / 127.5, offset=-1),
|
| 173 |
+
... layers.RandomFlip("horizontal"),
|
| 174 |
+
... layers.RandomRotation(factor=0.02),
|
| 175 |
+
... layers.RandomZoom(height_factor=0.2, width_factor=0.2),
|
| 176 |
+
... ],
|
| 177 |
+
... name="train_data_augmentation",
|
| 178 |
+
... )
|
| 179 |
+
|
| 180 |
+
>>> val_data_augmentation = keras.Sequential(
|
| 181 |
+
... [
|
| 182 |
+
... layers.CenterCrop(size[0], size[1]),
|
| 183 |
+
... layers.Rescaling(scale=1.0 / 127.5, offset=-1),
|
| 184 |
+
... ],
|
| 185 |
+
... name="val_data_augmentation",
|
| 186 |
+
... )
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
Next, create functions to apply appropriate transformations to a batch of images, instead of one image at a time.
|
| 190 |
+
|
| 191 |
+
```py
|
| 192 |
+
>>> import numpy as np
|
| 193 |
+
>>> import tensorflow as tf
|
| 194 |
+
>>> from PIL import Image
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
>>> def convert_to_tf_tensor(image: Image):
|
| 198 |
+
... np_image = np.array(image)
|
| 199 |
+
... tf_image = tf.convert_to_tensor(np_image)
|
| 200 |
+
... # `expand_dims()` is used to add a batch dimension since
|
| 201 |
+
... # the TF augmentation layers operates on batched inputs.
|
| 202 |
+
... return tf.expand_dims(tf_image, 0)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
>>> def preprocess_train(example_batch):
|
| 206 |
+
... """Apply train_transforms across a batch."""
|
| 207 |
+
... images = [
|
| 208 |
+
... train_data_augmentation(convert_to_tf_tensor(image.convert("RGB"))) for image in example_batch["image"]
|
| 209 |
+
... ]
|
| 210 |
+
... example_batch["pixel_values"] = [tf.transpose(tf.squeeze(image)) for image in images]
|
| 211 |
+
... return example_batch
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
... def preprocess_val(example_batch):
|
| 215 |
+
... """Apply val_transforms across a batch."""
|
| 216 |
+
... images = [
|
| 217 |
+
... val_data_augmentation(convert_to_tf_tensor(image.convert("RGB"))) for image in example_batch["image"]
|
| 218 |
+
... ]
|
| 219 |
+
... example_batch["pixel_values"] = [tf.transpose(tf.squeeze(image)) for image in images]
|
| 220 |
+
... return example_batch
|
| 221 |
+
```
|
| 222 |
+
|
| 223 |
+
Use 🤗 Datasets [`~datasets.Dataset.set_transform`] to apply the transformations on the fly:
|
| 224 |
+
|
| 225 |
+
```py
|
| 226 |
+
food["train"].set_transform(preprocess_train)
|
| 227 |
+
food["test"].set_transform(preprocess_val)
|
| 228 |
+
```
|
| 229 |
+
|
| 230 |
+
As a final preprocessing step, create a batch of examples using `DefaultDataCollator`. Unlike other data collators in 🤗 Transformers, the
|
| 231 |
+
`DefaultDataCollator` does not apply additional preprocessing, such as padding.
|
| 232 |
+
|
| 233 |
+
```py
|
| 234 |
+
>>> from transformers import DefaultDataCollator
|
| 235 |
+
|
| 236 |
+
>>> data_collator = DefaultDataCollator(return_tensors="tf")
|
| 237 |
+
```
|
| 238 |
+
</tf>
|
| 239 |
+
</frameworkcontent>
|
| 240 |
+
|
| 241 |
+
## Evaluate
|
| 242 |
+
|
| 243 |
+
Including a metric during training is often helpful for evaluating your model's performance. You can quickly load an
|
| 244 |
+
evaluation method with the 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load
|
| 245 |
+
the [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) metric (see the 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric):
|
| 246 |
+
|
| 247 |
+
```py
|
| 248 |
+
>>> import evaluate
|
| 249 |
+
|
| 250 |
+
>>> accuracy = evaluate.load("accuracy")
|
| 251 |
+
```
|
| 252 |
+
|
| 253 |
+
Then create a function that passes your predictions and labels to [`~evaluate.EvaluationModule.compute`] to calculate the accuracy:
|
| 254 |
+
|
| 255 |
+
```py
|
| 256 |
+
>>> import numpy as np
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
>>> def compute_metrics(eval_pred):
|
| 260 |
+
... predictions, labels = eval_pred
|
| 261 |
+
... predictions = np.argmax(predictions, axis=1)
|
| 262 |
+
... return accuracy.compute(predictions=predictions, references=labels)
|
| 263 |
+
```
|
| 264 |
+
|
| 265 |
+
Your `compute_metrics` function is ready to go now, and you'll return to it when you set up your training.
|
| 266 |
+
|
| 267 |
+
## Train
|
| 268 |
+
|
| 269 |
+
<frameworkcontent>
|
| 270 |
+
<pt>
|
| 271 |
+
<Tip>
|
| 272 |
+
|
| 273 |
+
If you aren't familiar with finetuning a model with the [`Trainer`], take a look at the basic tutorial [here](../training#train-with-pytorch-trainer)!
|
| 274 |
+
|
| 275 |
+
</Tip>
|
| 276 |
+
|
| 277 |
+
You're ready to start training your model now! Load ViT with [`AutoModelForImageClassification`]. Specify the number of labels along with the number of expected labels, and the label mappings:
|
| 278 |
+
|
| 279 |
+
```py
|
| 280 |
+
>>> from transformers import AutoModelForImageClassification, TrainingArguments, Trainer
|
| 281 |
+
|
| 282 |
+
>>> model = AutoModelForImageClassification.from_pretrained(
|
| 283 |
+
... checkpoint,
|
| 284 |
+
... num_labels=len(labels),
|
| 285 |
+
... id2label=id2label,
|
| 286 |
+
... label2id=label2id,
|
| 287 |
+
... )
|
| 288 |
+
```
|
| 289 |
+
|
| 290 |
+
At this point, only three steps remain:
|
| 291 |
+
|
| 292 |
+
1. Define your training hyperparameters in [`TrainingArguments`]. It is important you don't remove unused columns because that'll drop the `image` column. Without the `image` column, you can't create `pixel_values`. Set `remove_unused_columns=False` to prevent this behavior! The only other required parameter is `output_dir` which specifies where to save your model. You'll push this model to the Hub by setting `push_to_hub=True` (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [`Trainer`] will evaluate the accuracy and save the training checkpoint.
|
| 293 |
+
2. Pass the training arguments to [`Trainer`] along with the model, dataset, tokenizer, data collator, and `compute_metrics` function.
|
| 294 |
+
3. Call [`~Trainer.train`] to finetune your model.
|
| 295 |
+
|
| 296 |
+
```py
|
| 297 |
+
>>> training_args = TrainingArguments(
|
| 298 |
+
... output_dir="my_awesome_food_model",
|
| 299 |
+
... remove_unused_columns=False,
|
| 300 |
+
... eval_strategy="epoch",
|
| 301 |
+
... save_strategy="epoch",
|
| 302 |
+
... learning_rate=5e-5,
|
| 303 |
+
... per_device_train_batch_size=16,
|
| 304 |
+
... gradient_accumulation_steps=4,
|
| 305 |
+
... per_device_eval_batch_size=16,
|
| 306 |
+
... num_train_epochs=3,
|
| 307 |
+
... warmup_ratio=0.1,
|
| 308 |
+
... logging_steps=10,
|
| 309 |
+
... load_best_model_at_end=True,
|
| 310 |
+
... metric_for_best_model="accuracy",
|
| 311 |
+
... push_to_hub=True,
|
| 312 |
+
... )
|
| 313 |
+
|
| 314 |
+
>>> trainer = Trainer(
|
| 315 |
+
... model=model,
|
| 316 |
+
... args=training_args,
|
| 317 |
+
... data_collator=data_collator,
|
| 318 |
+
... train_dataset=food["train"],
|
| 319 |
+
... eval_dataset=food["test"],
|
| 320 |
+
... processing_class=image_processor,
|
| 321 |
+
... compute_metrics=compute_metrics,
|
| 322 |
+
... )
|
| 323 |
+
|
| 324 |
+
>>> trainer.train()
|
| 325 |
+
```
|
| 326 |
+
|
| 327 |
+
Once training is completed, share your model to the Hub with the [`~transformers.Trainer.push_to_hub`] method so everyone can use your model:
|
| 328 |
+
|
| 329 |
+
```py
|
| 330 |
+
>>> trainer.push_to_hub()
|
| 331 |
+
```
|
| 332 |
+
</pt>
|
| 333 |
+
</frameworkcontent>
|
| 334 |
+
|
| 335 |
+
<frameworkcontent>
|
| 336 |
+
<tf>
|
| 337 |
+
|
| 338 |
+
<Tip>
|
| 339 |
+
|
| 340 |
+
If you are unfamiliar with fine-tuning a model with Keras, check out the [basic tutorial](./training#train-a-tensorflow-model-with-keras) first!
|
| 341 |
+
|
| 342 |
+
</Tip>
|
| 343 |
+
|
| 344 |
+
To fine-tune a model in TensorFlow, follow these steps:
|
| 345 |
+
1. Define the training hyperparameters, and set up an optimizer and a learning rate schedule.
|
| 346 |
+
2. Instantiate a pre-trained model.
|
| 347 |
+
3. Convert a 🤗 Dataset to a `tf.data.Dataset`.
|
| 348 |
+
4. Compile your model.
|
| 349 |
+
5. Add callbacks and use the `fit()` method to run the training.
|
| 350 |
+
6. Upload your model to 🤗 Hub to share with the community.
|
| 351 |
+
|
| 352 |
+
Start by defining the hyperparameters, optimizer and learning rate schedule:
|
| 353 |
+
|
| 354 |
+
```py
|
| 355 |
+
>>> from transformers import create_optimizer
|
| 356 |
+
|
| 357 |
+
>>> batch_size = 16
|
| 358 |
+
>>> num_epochs = 5
|
| 359 |
+
>>> num_train_steps = len(food["train"]) * num_epochs
|
| 360 |
+
>>> learning_rate = 3e-5
|
| 361 |
+
>>> weight_decay_rate = 0.01
|
| 362 |
+
|
| 363 |
+
>>> optimizer, lr_schedule = create_optimizer(
|
| 364 |
+
... init_lr=learning_rate,
|
| 365 |
+
... num_train_steps=num_train_steps,
|
| 366 |
+
... weight_decay_rate=weight_decay_rate,
|
| 367 |
+
... num_warmup_steps=0,
|
| 368 |
+
... )
|
| 369 |
+
```
|
| 370 |
+
|
| 371 |
+
Then, load ViT with [`TFAutoModelForImageClassification`] along with the label mappings:
|
| 372 |
+
|
| 373 |
+
```py
|
| 374 |
+
>>> from transformers import TFAutoModelForImageClassification
|
| 375 |
+
|
| 376 |
+
>>> model = TFAutoModelForImageClassification.from_pretrained(
|
| 377 |
+
... checkpoint,
|
| 378 |
+
... id2label=id2label,
|
| 379 |
+
... label2id=label2id,
|
| 380 |
+
... )
|
| 381 |
+
```
|
| 382 |
+
|
| 383 |
+
Convert your datasets to the `tf.data.Dataset` format using the [`~datasets.Dataset.to_tf_dataset`] and your `data_collator`:
|
| 384 |
+
|
| 385 |
+
```py
|
| 386 |
+
>>> # converting our train dataset to tf.data.Dataset
|
| 387 |
+
>>> tf_train_dataset = food["train"].to_tf_dataset(
|
| 388 |
+
... columns="pixel_values", label_cols="label", shuffle=True, batch_size=batch_size, collate_fn=data_collator
|
| 389 |
+
... )
|
| 390 |
+
|
| 391 |
+
>>> # converting our test dataset to tf.data.Dataset
|
| 392 |
+
>>> tf_eval_dataset = food["test"].to_tf_dataset(
|
| 393 |
+
... columns="pixel_values", label_cols="label", shuffle=True, batch_size=batch_size, collate_fn=data_collator
|
| 394 |
+
... )
|
| 395 |
+
```
|
| 396 |
+
|
| 397 |
+
Configure the model for training with `compile()`:
|
| 398 |
+
|
| 399 |
+
```py
|
| 400 |
+
>>> from tensorflow.keras.losses import SparseCategoricalCrossentropy
|
| 401 |
+
|
| 402 |
+
>>> loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
|
| 403 |
+
>>> model.compile(optimizer=optimizer, loss=loss)
|
| 404 |
+
```
|
| 405 |
+
|
| 406 |
+
To compute the accuracy from the predictions and push your model to the 🤗 Hub, use [Keras callbacks](../main_classes/keras_callbacks).
|
| 407 |
+
Pass your `compute_metrics` function to [KerasMetricCallback](../main_classes/keras_callbacks#transformers.KerasMetricCallback),
|
| 408 |
+
and use the [PushToHubCallback](../main_classes/keras_callbacks#transformers.PushToHubCallback) to upload the model:
|
| 409 |
+
|
| 410 |
+
```py
|
| 411 |
+
>>> from transformers.keras_callbacks import KerasMetricCallback, PushToHubCallback
|
| 412 |
+
|
| 413 |
+
>>> metric_callback = KerasMetricCallback(metric_fn=compute_metrics, eval_dataset=tf_eval_dataset)
|
| 414 |
+
>>> push_to_hub_callback = PushToHubCallback(
|
| 415 |
+
... output_dir="food_classifier",
|
| 416 |
+
... tokenizer=image_processor,
|
| 417 |
+
... save_strategy="no",
|
| 418 |
+
... )
|
| 419 |
+
>>> callbacks = [metric_callback, push_to_hub_callback]
|
| 420 |
+
```
|
| 421 |
+
|
| 422 |
+
Finally, you are ready to train your model! Call `fit()` with your training and validation datasets, the number of epochs,
|
| 423 |
+
and your callbacks to fine-tune the model:
|
| 424 |
+
|
| 425 |
+
```py
|
| 426 |
+
>>> model.fit(tf_train_dataset, validation_data=tf_eval_dataset, epochs=num_epochs, callbacks=callbacks)
|
| 427 |
+
Epoch 1/5
|
| 428 |
+
250/250 [==============================] - 313s 1s/step - loss: 2.5623 - val_loss: 1.4161 - accuracy: 0.9290
|
| 429 |
+
Epoch 2/5
|
| 430 |
+
250/250 [==============================] - 265s 1s/step - loss: 0.9181 - val_loss: 0.6808 - accuracy: 0.9690
|
| 431 |
+
Epoch 3/5
|
| 432 |
+
250/250 [==============================] - 252s 1s/step - loss: 0.3910 - val_loss: 0.4303 - accuracy: 0.9820
|
| 433 |
+
Epoch 4/5
|
| 434 |
+
250/250 [==============================] - 251s 1s/step - loss: 0.2028 - val_loss: 0.3191 - accuracy: 0.9900
|
| 435 |
+
Epoch 5/5
|
| 436 |
+
250/250 [==============================] - 238s 949ms/step - loss: 0.1232 - val_loss: 0.3259 - accuracy: 0.9890
|
| 437 |
+
```
|
| 438 |
+
|
| 439 |
+
Congratulations! You have fine-tuned your model and shared it on the 🤗 Hub. You can now use it for inference!
|
| 440 |
+
</tf>
|
| 441 |
+
</frameworkcontent>
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
<Tip>
|
| 445 |
+
|
| 446 |
+
For a more in-depth example of how to finetune a model for image classification, take a look at the corresponding [PyTorch notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/image_classification.ipynb).
|
| 447 |
+
|
| 448 |
+
</Tip>
|
| 449 |
+
|
| 450 |
+
## Inference
|
| 451 |
+
|
| 452 |
+
Great, now that you've fine-tuned a model, you can use it for inference!
|
| 453 |
+
|
| 454 |
+
Load an image you'd like to run inference on:
|
| 455 |
+
|
| 456 |
+
```py
|
| 457 |
+
>>> ds = load_dataset("food101", split="validation[:10]")
|
| 458 |
+
>>> image = ds["image"][0]
|
| 459 |
+
```
|
| 460 |
+
|
| 461 |
+
<div class="flex justify-center">
|
| 462 |
+
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png" alt="image of beignets"/>
|
| 463 |
+
</div>
|
| 464 |
+
|
| 465 |
+
The simplest way to try out your finetuned model for inference is to use it in a [`pipeline`]. Instantiate a `pipeline` for image classification with your model, and pass your image to it:
|
| 466 |
+
|
| 467 |
+
```py
|
| 468 |
+
>>> from transformers import pipeline
|
| 469 |
+
|
| 470 |
+
>>> classifier = pipeline("image-classification", model="my_awesome_food_model")
|
| 471 |
+
>>> classifier(image)
|
| 472 |
+
[{'score': 0.31856709718704224, 'label': 'beignets'},
|
| 473 |
+
{'score': 0.015232225880026817, 'label': 'bruschetta'},
|
| 474 |
+
{'score': 0.01519392803311348, 'label': 'chicken_wings'},
|
| 475 |
+
{'score': 0.013022331520915031, 'label': 'pork_chop'},
|
| 476 |
+
{'score': 0.012728818692266941, 'label': 'prime_rib'}]
|
| 477 |
+
```
|
| 478 |
+
|
| 479 |
+
You can also manually replicate the results of the `pipeline` if you'd like:
|
| 480 |
+
|
| 481 |
+
<frameworkcontent>
|
| 482 |
+
<pt>
|
| 483 |
+
Load an image processor to preprocess the image and return the `input` as PyTorch tensors:
|
| 484 |
+
|
| 485 |
+
```py
|
| 486 |
+
>>> from transformers import AutoImageProcessor
|
| 487 |
+
>>> import torch
|
| 488 |
+
|
| 489 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("my_awesome_food_model")
|
| 490 |
+
>>> inputs = image_processor(image, return_tensors="pt")
|
| 491 |
+
```
|
| 492 |
+
|
| 493 |
+
Pass your inputs to the model and return the logits:
|
| 494 |
+
|
| 495 |
+
```py
|
| 496 |
+
>>> from transformers import AutoModelForImageClassification
|
| 497 |
+
|
| 498 |
+
>>> model = AutoModelForImageClassification.from_pretrained("my_awesome_food_model")
|
| 499 |
+
>>> with torch.no_grad():
|
| 500 |
+
... logits = model(**inputs).logits
|
| 501 |
+
```
|
| 502 |
+
|
| 503 |
+
Get the predicted label with the highest probability, and use the model's `id2label` mapping to convert it to a label:
|
| 504 |
+
|
| 505 |
+
```py
|
| 506 |
+
>>> predicted_label = logits.argmax(-1).item()
|
| 507 |
+
>>> model.config.id2label[predicted_label]
|
| 508 |
+
'beignets'
|
| 509 |
+
```
|
| 510 |
+
</pt>
|
| 511 |
+
</frameworkcontent>
|
| 512 |
+
|
| 513 |
+
<frameworkcontent>
|
| 514 |
+
<tf>
|
| 515 |
+
Load an image processor to preprocess the image and return the `input` as TensorFlow tensors:
|
| 516 |
+
|
| 517 |
+
```py
|
| 518 |
+
>>> from transformers import AutoImageProcessor
|
| 519 |
+
|
| 520 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("MariaK/food_classifier")
|
| 521 |
+
>>> inputs = image_processor(image, return_tensors="tf")
|
| 522 |
+
```
|
| 523 |
+
|
| 524 |
+
Pass your inputs to the model and return the logits:
|
| 525 |
+
|
| 526 |
+
```py
|
| 527 |
+
>>> from transformers import TFAutoModelForImageClassification
|
| 528 |
+
|
| 529 |
+
>>> model = TFAutoModelForImageClassification.from_pretrained("MariaK/food_classifier")
|
| 530 |
+
>>> logits = model(**inputs).logits
|
| 531 |
+
```
|
| 532 |
+
|
| 533 |
+
Get the predicted label with the highest probability, and use the model's `id2label` mapping to convert it to a label:
|
| 534 |
+
|
| 535 |
+
```py
|
| 536 |
+
>>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0])
|
| 537 |
+
>>> model.config.id2label[predicted_class_id]
|
| 538 |
+
'beignets'
|
| 539 |
+
```
|
| 540 |
+
|
| 541 |
+
</tf>
|
| 542 |
+
</frameworkcontent>
|
tasks/tasksmith-5cbfd9f64dbc/tests/source/docs/source/en/tasks/image_feature_extraction.md
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2024 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 |
+
|
| 17 |
+
# Image Feature Extraction
|
| 18 |
+
|
| 19 |
+
[[open-in-colab]]
|
| 20 |
+
|
| 21 |
+
Image feature extraction is the task of extracting semantically meaningful features given an image. This has many use cases, including image similarity and image retrieval. Moreover, most computer vision models can be used for image feature extraction, where one can remove the task-specific head (image classification, object detection etc) and get the features. These features are very useful on a higher level: edge detection, corner detection and so on. They may also contain information about the real world (e.g. what a cat looks like) depending on how deep the model is. Therefore, these outputs can be used to train new classifiers on a specific dataset.
|
| 22 |
+
|
| 23 |
+
In this guide, you will:
|
| 24 |
+
|
| 25 |
+
- Learn to build a simple image similarity system on top of the `image-feature-extraction` pipeline.
|
| 26 |
+
- Accomplish the same task with bare model inference.
|
| 27 |
+
|
| 28 |
+
## Image Similarity using `image-feature-extraction` Pipeline
|
| 29 |
+
|
| 30 |
+
We have two images of cats sitting on top of fish nets, one of them is generated.
|
| 31 |
+
|
| 32 |
+
```python
|
| 33 |
+
from PIL import Image
|
| 34 |
+
import requests
|
| 35 |
+
|
| 36 |
+
img_urls = ["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png", "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.jpeg"]
|
| 37 |
+
image_real = Image.open(requests.get(img_urls[0], stream=True).raw).convert("RGB")
|
| 38 |
+
image_gen = Image.open(requests.get(img_urls[1], stream=True).raw).convert("RGB")
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
Let's see the pipeline in action. First, initialize the pipeline. If you don't pass any model to it, the pipeline will be automatically initialized with [google/vit-base-patch16-224](google/vit-base-patch16-224). If you'd like to calculate similarity, set `pool` to True.
|
| 42 |
+
|
| 43 |
+
```python
|
| 44 |
+
import torch
|
| 45 |
+
from transformers import pipeline, infer_device
|
| 46 |
+
# automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.)
|
| 47 |
+
DEVICE = infer_device()
|
| 48 |
+
pipe = pipeline(task="image-feature-extraction", model_name="google/vit-base-patch16-384", device=DEVICE, pool=True)
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
To infer with `pipe` pass both images to it.
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
outputs = pipe([image_real, image_gen])
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
The output contains pooled embeddings of those two images.
|
| 58 |
+
|
| 59 |
+
```python
|
| 60 |
+
# get the length of a single output
|
| 61 |
+
print(len(outputs[0][0]))
|
| 62 |
+
# show outputs
|
| 63 |
+
print(outputs)
|
| 64 |
+
|
| 65 |
+
# 768
|
| 66 |
+
# [[[-0.03909236937761307, 0.43381670117378235, -0.06913255900144577,
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
To get the similarity score, we need to pass them to a similarity function.
|
| 70 |
+
|
| 71 |
+
```python
|
| 72 |
+
from torch.nn.functional import cosine_similarity
|
| 73 |
+
|
| 74 |
+
similarity_score = cosine_similarity(torch.Tensor(outputs[0]),
|
| 75 |
+
torch.Tensor(outputs[1]), dim=1)
|
| 76 |
+
|
| 77 |
+
print(similarity_score)
|
| 78 |
+
|
| 79 |
+
# tensor([0.6043])
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
If you want to get the last hidden states before pooling, avoid passing any value for the `pool` parameter, as it is set to `False` by default. These hidden states are useful for training new classifiers or models based on the features from the model.
|
| 83 |
+
|
| 84 |
+
```python
|
| 85 |
+
pipe = pipeline(task="image-feature-extraction", model_name="google/vit-base-patch16-224", device=DEVICE)
|
| 86 |
+
outputs = pipe(image_real)
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
Since the outputs are unpooled, we get the last hidden states where the first dimension is the batch size, and the last two are the embedding shape.
|
| 90 |
+
|
| 91 |
+
```python
|
| 92 |
+
import numpy as np
|
| 93 |
+
print(np.array(outputs).shape)
|
| 94 |
+
# (1, 197, 768)
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
## Getting Features and Similarities using `AutoModel`
|
| 98 |
+
|
| 99 |
+
We can also use `AutoModel` class of transformers to get the features. `AutoModel` loads any transformers model with no task-specific head, and we can use this to get the features.
|
| 100 |
+
|
| 101 |
+
```python
|
| 102 |
+
from transformers import AutoImageProcessor, AutoModel
|
| 103 |
+
|
| 104 |
+
processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
|
| 105 |
+
model = AutoModel.from_pretrained("google/vit-base-patch16-224").to(DEVICE)
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
Let's write a simple function for inference. We will pass the inputs to the `processor` first and pass its outputs to the `model`.
|
| 109 |
+
|
| 110 |
+
```python
|
| 111 |
+
def infer(image):
|
| 112 |
+
inputs = processor(image, return_tensors="pt").to(DEVICE)
|
| 113 |
+
outputs = model(**inputs)
|
| 114 |
+
return outputs.pooler_output
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
We can pass the images directly to this function and get the embeddings.
|
| 118 |
+
|
| 119 |
+
```python
|
| 120 |
+
embed_real = infer(image_real)
|
| 121 |
+
embed_gen = infer(image_gen)
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
We can get the similarity again over the embeddings.
|
| 125 |
+
|
| 126 |
+
```python
|
| 127 |
+
from torch.nn.functional import cosine_similarity
|
| 128 |
+
|
| 129 |
+
similarity_score = cosine_similarity(embed_real, embed_gen, dim=1)
|
| 130 |
+
print(similarity_score)
|
| 131 |
+
|
| 132 |
+
# tensor([0.6061], device='cuda:0', grad_fn=<SumBackward1>)
|
| 133 |
+
```
|
| 134 |
+
|