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_inc.ipynb
Views: 2535
Quantizing a model during fine-tuning with Intel Neural Compressor (INC) for text classification tasks
This notebook shows how to apply quantization aware training, using the Intel Neural Compressor (INC) library, for any tasks of the GLUE benchmark. This is made possible thanks to 🤗 Optimum Intel, an extension of 🤗 Transformers, providing a set of performance optimization tools enabling maximum efficiency to accelerate end-to-end pipelines on a variety of Intel processors.
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.6.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:
Loading the dataset
We will use the 🤗 Datasets and 🤗 Evaluate libraries to download the data and get the metric we need to use for evaluation. This can be easily done with the functions load_dataset
and load
.
Apart from mnli-mm
being a special code, we can directly pass our task name to those functions. load_dataset
will cache the dataset to avoid downloading it again the next time you run this cell.
Note that load
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.
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.
Preprocessing the data
Before we can feed those texts to our model, we need to preprocess them. This is done by a 🤗 Transformers Tokenizer
which will (as the name indicates) tokenize the inputs (including converting the tokens to their corresponding IDs in the pretrained vocabulary) and put it in a format the model expects, as well as generate the other inputs that model requires.
To do all of this, we instantiate our tokenizer with the AutoTokenizer.from_pretrained
method, which will ensure that:
we get a tokenizer that corresponds to the model architecture we want to use
we download the vocabulary used when pretraining this specific checkpoint
That vocabulary will be cached, so it's not downloaded again the next time we run the cell.
To preprocess our dataset, we will thus need the names of the columns containing the sentence(s). The following dictionary keeps track of the correspondence task to column names:
We can double check it does work on our current dataset:
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.
To apply this function on all the sentences (or pairs of sentences) in our dataset, we just use the map
method of our dataset
object we created earlier. This will apply the function on all the elements of all the splits in dataset
, so our training, validation and testing data will be preprocessed in one single command.
Even better, the results are automatically cached by the 🤗 Datasets library to avoid spending time on this step the next time you run your notebook. The 🤗 Datasets library is normally smart enough to detect when the function you pass to map has changed (and thus requires to not use the cache data). For instance, it will properly detect if you change the task in the first cell and rerun the notebook. 🤗 Datasets warns you when it uses cached files, you can pass load_from_cache_file=False
in the call to map
to not use the cached files and force the preprocessing to be applied again.
Note that we passed batched=True
to encode the texts by batches together. This is to leverage the full benefit of the fast tokenizer we loaded earlier, which will use multi-threading to treat the texts in a batch concurrently.
Applying quantization on the model
Quantization aware training simulates the effects of quantization during training in order to alleviate its effects on the model's performance.
Now that our data is ready, we can download the pretrained model and fine-tune it. Since all our tasks are about sentence classification, we use the AutoModelForSequenceClassification
class. Like with the tokenizer, the from_pretrained
method will download and cache the model for us. The only thing we have to specify is the number of labels for our problem (which is always 2, except for STS-B which is a regression problem and MNLI where we have 3 labels):
The INCTrainer
class provides an API to train your model while combining different compression techniques such as knowledge distillation, pruning and quantization. The INCTrainer
is very similar to the 🤗 Transformers Trainer
, which can be replaced with minimal changes in your code. In addition to the usual
To instantiate an INCTrainer
, we will need to define three more things. First, we need to create the quantization configuration describing the quantization proccess we wish to apply. Quantization will be applied on the embeddings, on the linear layers as well as on their corresponding input activations.
TrainingArguments
is a class that contains all the attributes to customize the training. It requires one folder name, which will be used to save the checkpoints of the model, and all other arguments are optional:
The last thing to define for our INCTrainer
is 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):
Then we just need to pass all of this along with our datasets to the INCTrainer
:
We can now finetune our model by just calling the train
method:
We can run evaluation by just calling the evaluate
method:
To save the resulting quantized model, you can use the save_model
method. By setting save_onnx_model
to True
, the model will be additionnaly exported to the ONNX format.
Loading the quantized model
You must instantiate you model using our INCModelForXxx
[https://huggingface.co/docs/optimum/main/intel/reference_inc#optimum.intel.neural_compressor.INCModel] or ORTModelForXxx
[https://huggingface.co/docs/optimum/onnxruntime/package_reference/modeling_ort] classes to load respectively your quantized PyTorch or ONNX model hosted locally or on the 🤗 hub :