Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/main/examples/text_classification_quantization_ort.ipynb
Views: 2535
Quantizing a model with ONNX Runtime for text classification tasks
This notebook shows how to apply different post-training quantization approaches such as static and dynamic quantization using ONNX Runtime, for any tasks of the GLUE benchmark. This is made possible thanks to 🤗 Optimum, an extension of 🤗 Transformers, providing a set of performance optimization tools enabling maximum efficiency to train and run models on targeted hardwares.
If you're opening this Notebook on colab, you will probably need to install 🤗 Transformers, 🤗 Datasets and 🤗 Optimum. Uncomment the following cell and run it.
Make sure your version of 🤗 Optimum is at least 1.1.0 since the functionality was introduced in that version:
The GLUE Benchmark is a group of nine classification tasks on sentences or pairs of sentences which are:
CoLA (Corpus of Linguistic Acceptability) Determine if a sentence is grammatically correct or not.
MNLI (Multi-Genre Natural Language Inference) Determine if a sentence entails, contradicts or is unrelated to a given hypothesis. This dataset has two versions, one with the validation and test set coming from the same distribution, another called mismatched where the validation and test use out-of-domain data.
MRPC (Microsoft Research Paraphrase Corpus) Determine if two sentences are paraphrases from one another or not.
QNLI (Question-answering Natural Language Inference) Determine if the answer to a question is in the second sentence or not. This dataset is built from the SQuAD dataset.
QQP (Quora Question Pairs2) Determine if two questions are semantically equivalent or not.
RTE (Recognizing Textual Entailment) Determine if a sentence entails a given hypothesis or not.
SST-2 (Stanford Sentiment Treebank) Determine if the sentence has a positive or negative sentiment.
STS-B (Semantic Textual Similarity Benchmark) Determine the similarity of two sentences with a score from 1 to 5.
WNLI (Winograd Natural Language Inference) Determine if a sentence with an anonymous pronoun and a sentence with this pronoun replaced are entailed or not. This dataset is built from the Winograd Schema Challenge dataset.
We will see how to apply post-training static quantization on a DistilBERT model fine-tuned on the SST-2 task:
We also quickly upload some telemetry - this tells us which examples and software versions are getting used so we know where to prioritize our maintenance efforts. We don't collect (or care about) any personally identifiable information, but if you'd prefer not to be counted, feel free to skip this step or delete this cell entirely.
Loading the dataset
We will use the 🤗 Datasets library to download the dataset and get the metric we need to use for evaluation. This can be easily done with the functions load_dataset
and load_metric
.
load_dataset
will cache the dataset to avoid downloading it again the next time you run this cell.
Note that load_metric
has loaded the proper metric associated to your task, which is:
for CoLA: Matthews Correlation Coefficient
for MNLI (matched or mismatched): Accuracy
for MRPC: Accuracy and F1 score
for QNLI: Accuracy
for QQP: Accuracy and F1 score
for RTE: Accuracy
for SST-2: Accuracy
for STS-B: Pearson Correlation Coefficient and Spearman's_Rank_Correlation_Coefficient
for WNLI: Accuracy
so the metric object only computes the one(s) needed for your task.
Preprocessing the data
To preprocess our dataset, we will need the names of the columns containing the sentence(s). The following dictionary keeps track of the correspondence task to column names:
We can then write the function that will preprocess our samples. We just feed them to the tokenizer
with the argument truncation=True
. This will ensure that an input longer than what the model selected can handle will be truncated to the maximum length accepted by the model.
Applying quantization on the model
We can set our quantization_approach
to either dynamic
or static
in order to apply respectively dynamic and static quantization.
Post-training static quantization : introduces an additional calibration step where data is fed through the network in order to compute the activations quantization parameters.
Post-training dynamic quantization : dynamically computes activations quantization parameters based on the data observed at runtime.
First, let's create the output directory where the resulting quantized model will be saved.
We will use the 🤗 Optimum library to instantiate an ORTQuantizer
, which will take care of the quantization process. To instantiate an ORTQuantizer
, we need to provide a path to a converted ONNX checkpoint or instance of a ORTModelForXXX
.
We also need to create an QuantizationConfig
instance, which is the configuration handling the ONNX Runtime quantization related parameters.
We set
per_channel
toFalse
in order to apply per-tensor quantization on the weights. As opposed to per-channel quantization, which introduces one set of quantization parameters per channel, per-tensor quantization means that there will be one set of quantization parameters per tensor.We set the number of samples
num_calibration_samples
to use for the calibration step resulting from static quantization to40
.operators_to_quantize
is used to specify the types of operators to quantize, here we want to quantize all the network's fully connected and embedding layers.
When applying static quantization, we need to perform a calibration step where the activations quantization ranges are computed. This additionnal step should only be performed in the case of static quantization and not for dynamic quantization. Because the quantization of certain nodes often results in degradation in accuracy, we create an instance of QuantizationPreprocessor
to determine the nodes to exclude when applying static quantization.
Finally, we export the quantized model.
Evaluation
To evaluate our resulting quantized model we need to define how to compute the metrics from the predictions. We need to define a function for this, which will just use the metric
we loaded earlier, the only preprocessing we have to do is to take the argmax of our predicted logits (our just squeeze the last axis in the case of STS-B).
The metric chosen to evaluate the quantized model's performance will be Matthews correlation coefficient (MCC) for CoLA, Pearson correlation coefficient (PCC) for STS-B and accuracy for any other tasks.
Then to apply the preprocessing on all the sentences (or pairs of sentences) of our validation dataset, we just use the map
method of our dataset
object that was earlier created. This will apply the preprocess_function
function on all the elements of our validation dataset.
Finally, to estimate the drop in performance resulting from quantization, we are going to perform an evaluation step for both models (before and after quantization). In order to perform the latter, we will need to instantiate an ORTModel
and thus need:
The path of the model to evaluate.
The dataset to use for the evaluation step.
The model's ONNX configuration
onnx_config
associated to the model. This instance ofOnnxConfig
describes how to export the model through the ONNX format.The function that will be used to compute the evaluation metrics
compute_metrics
that was defined previously.
Now let's compute the full-precision and the quantized model respective size in megabyte (MB) :
The reduction in the model size resulting from quantization is: