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/question_answering_ort.ipynb
Views: 2535
Fine-tunining DeBERTa model on a question answering task with ORTTrainer
In this notebook, we will see how to fine-tune the DeBERTa base model to a question answering task, which is the task of extracting the answer to a question from a given context. We will use the ORTTrainer
API in Optimum library to leverage ONNX Runtime backend to accelerate the training.
Start by setting up the environment
To use ONNX Runtime for training, you need a machine with at least one NVIDIA or AMD GPU.
ONNX Runtime training module need to be properly installed before launching the notebook! Please follow the instruction in Optimum's documentation to set up your environment, or use directly the dockerfiles in Optimum
If you're opening this Notebook on colab, you will probably need to install 🤗 Optimum, 🤗 Transformers, 🤗 Datasets and 🤗 evaluate. Uncomment the following cell and run it.
Collecting optimum
Downloading optimum-1.7.3-py3-none-any.whl (300 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 300.5/300.5 kB 9.4 MB/s eta 0:00:00
Requirement already satisfied: transformers in /usr/local/lib/python3.8/dist-packages (4.27.0.dev0)
Requirement already satisfied: datasets in /usr/local/lib/python3.8/dist-packages (2.10.0)
Requirement already satisfied: evaluate in /usr/local/lib/python3.8/dist-packages (0.4.0)
Requirement already satisfied: huggingface_hub in /usr/local/lib/python3.8/dist-packages (0.12.1)
Requirement already satisfied: torchvision in /usr/local/lib/python3.8/dist-packages (from optimum) (0.14.1+cu116)
Requirement already satisfied: sympy in /usr/local/lib/python3.8/dist-packages (from optimum) (1.11.1)
Requirement already satisfied: torch>=1.9 in /usr/local/lib/python3.8/dist-packages (from optimum) (1.13.1+cu116)
Requirement already satisfied: packaging in /usr/local/lib/python3.8/dist-packages (from optimum) (23.0)
Requirement already satisfied: coloredlogs in /usr/local/lib/python3.8/dist-packages (from optimum) (15.0.1)
Requirement already satisfied: numpy in /usr/local/lib/python3.8/dist-packages (from optimum) (1.24.2)
Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.8/dist-packages (from transformers) (4.64.1)
Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.8/dist-packages (from transformers) (6.0)
Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.8/dist-packages (from transformers) (2022.10.31)
Requirement already satisfied: filelock in /usr/local/lib/python3.8/dist-packages (from transformers) (3.9.0)
Requirement already satisfied: tokenizers!=0.11.3,<0.14,>=0.11.1 in /usr/local/lib/python3.8/dist-packages (from transformers) (0.13.2)
Requirement already satisfied: requests in /usr/local/lib/python3.8/dist-packages (from transformers) (2.28.2)
Requirement already satisfied: multiprocess in /usr/local/lib/python3.8/dist-packages (from datasets) (0.70.14)
Requirement already satisfied: responses<0.19 in /usr/local/lib/python3.8/dist-packages (from datasets) (0.18.0)
Requirement already satisfied: dill<0.3.7,>=0.3.0 in /usr/local/lib/python3.8/dist-packages (from datasets) (0.3.6)
Requirement already satisfied: pandas in /usr/local/lib/python3.8/dist-packages (from datasets) (1.5.3)
Requirement already satisfied: aiohttp in /usr/local/lib/python3.8/dist-packages (from datasets) (3.8.4)
Requirement already satisfied: pyarrow>=6.0.0 in /usr/local/lib/python3.8/dist-packages (from datasets) (11.0.0)
Requirement already satisfied: xxhash in /usr/local/lib/python3.8/dist-packages (from datasets) (3.2.0)
Requirement already satisfied: fsspec[http]>=2021.11.1 in /usr/local/lib/python3.8/dist-packages (from datasets) (2023.1.0)
Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.8/dist-packages (from huggingface_hub) (4.5.0)
Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.8/dist-packages (from aiohttp->datasets) (22.2.0)
Requirement already satisfied: yarl<2.0,>=1.0 in /usr/local/lib/python3.8/dist-packages (from aiohttp->datasets) (1.8.2)
Requirement already satisfied: charset-normalizer<4.0,>=2.0 in /usr/local/lib/python3.8/dist-packages (from aiohttp->datasets) (3.0.1)
Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.8/dist-packages (from aiohttp->datasets) (6.0.4)
Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.8/dist-packages (from aiohttp->datasets) (1.3.3)
Requirement already satisfied: aiosignal>=1.1.2 in /usr/local/lib/python3.8/dist-packages (from aiohttp->datasets) (1.3.1)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /usr/local/lib/python3.8/dist-packages (from aiohttp->datasets) (4.0.2)
Requirement already satisfied: idna<4,>=2.5 in /usr/lib/python3/dist-packages (from requests->transformers) (2.8)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.8/dist-packages (from requests->transformers) (1.26.14)
Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3/dist-packages (from requests->transformers) (2019.11.28)
Requirement already satisfied: protobuf<=3.20.2 in /usr/local/lib/python3.8/dist-packages (from transformers) (3.20.2)
Requirement already satisfied: sentencepiece!=0.1.92,>=0.1.91 in /usr/local/lib/python3.8/dist-packages (from transformers) (0.1.97)
Requirement already satisfied: humanfriendly>=9.1 in /usr/local/lib/python3.8/dist-packages (from coloredlogs->optimum) (10.0)
Requirement already satisfied: python-dateutil>=2.8.1 in /usr/local/lib/python3.8/dist-packages (from pandas->datasets) (2.8.2)
Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.8/dist-packages (from pandas->datasets) (2022.7.1)
Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.8/dist-packages (from sympy->optimum) (1.2.1)
Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /usr/local/lib/python3.8/dist-packages (from torchvision->optimum) (9.4.0)
Requirement already satisfied: six>=1.5 in /usr/lib/python3/dist-packages (from python-dateutil>=2.8.1->pandas->datasets) (1.14.0)
Installing collected packages: optimum
Successfully installed optimum-1.7.3
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Loading the dataset
We will use the 🤗 Datasets library 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_metric.
Downloading data files: 0%| | 0/2 [00:00<?, ?it/s]
Downloading data: 0%| | 0.00/8.12M [00:00<?, ?B/s]
Downloading data: 88%|████████████████████████████████████████████████████████████▋ | 7.14M/8.12M [00:00<00:00, 71.4MB/s]
Downloading data: 14.8MB [00:00, 74.6MB/s]
Downloading data: 22.4MB [00:00, 75.3MB/s]
Downloading data: 30.3MB [00:00, 74.6MB/s]
Downloading data files: 50%|███████████████████████████████████ | 1/2 [00:00<00:00, 1.83it/s]
Downloading data: 4.85MB [00:00, 70.1MB/s]
Downloading data files: 100%|██████████████████████████████████████████████████████████████████████| 2/2 [00:00<00:00, 2.52it/s]
Extracting data files: 100%|█████████████████████████████████████████████████████████████████████| 2/2 [00:00<00:00, 1732.47it/s]
We can see the training, validation and test sets all have a column for the context, the question and the answers to those questions.
We can access an actual element to see what the data looks like:
Preprocessing the training data
Before we can feed those texts to our model, we need to preprocess them. This is done by a 🤗 Transformers Tokenizer which will 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:
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.
Now one specific thing for the preprocessing in question answering is how to deal with very long documents. We usually truncate them in other tasks, when they are longer than the model maximum sentence length, but here, removing part of the the context might result in losing the answer we are looking for. To deal with this, we will allow one (long) example in our dataset to give several input features, each of length shorter than the maximum length of the model (or the one we set as a hyper-parameter). Also, just in case the answer lies at the point we split a long context, we allow some overlap between the features we generate controlled by the hyper-parameter doc_stride
:
Note that we never want to truncate the question, only the context, else the only_second
truncation picked. Now, our tokenizer can automatically return us a list of features capped by a certain maximum length, with the overlap we talked above, we just have to tell it with return_overflowing_tokens=True
and by passing the stride.
Now let's put everything together in one function we will apply to our training set. In the case of impossible answers (the answer is in another feature given by an example with a long context), we set the cls index for both the start and end position. We could also simply discard those examples from the training set if the flag allow_impossible_answers is False. Since the preprocessing is already complex enough as it is, we've kept is simple for this part.
Now apply this function on all the sentences (or pairs of sentences) in our dataset:
Fine-tuning DeBERTa model
Now that our data is ready for training, we can download the pretrained model and fine-tune it. Since our task is question answering, we use the AutoModelForQuestionAnswering
class. Like with the tokenizer, the from_pretrained method will download and cache the model for us:
Before setting up the training arguments, we will download a configuration of deepspeed stage 1. ONNX Runtime training supports ZeRO stage 1(optimizer state partitioning).
Instantiate ORTTrainer
, here we will use ORT fused optimizer to have better performance on latency:
Launch the training (it will leverage one single GPU for the training)
If you want to leverage multiple gpus for distributed data parallele training, you can use 🤗 Accelerate's notebook launcher to enable multi-gpu training:
Evaluation
Evaluating our model will require a bit more work, as we will need to map the predictions of our model back to parts of the context. The model itself predicts logits for the start and en position of our answer: if we take a batch from our validation datalaoder, here is the output our model gives us:
The output of the model is a dict-like object that contains the loss (since we provided labels), the start and end logits. We won't need the loss for our predictions, let's have a look a the logits:
We have one logit for each feature and each token. The most obvious thing to predict an answer for each feature is to take the index for the maximum of the start logits as a start position and the index of the maximum of the end logits as an end position. This will work great in a lot of cases, but what if this prediction gives us something impossible: the start position could be greater than the end position, or point to a span of text in the question instead of the answer. In that case, we might want to look at the second best prediction to see if it gives a possible answer and select that instead.
To classify our answers, we will use the score obtained by adding the start and end logits. We won't try to order all the possible answers and limit ourselves to with a hyper-parameter we call n_best_size. We'll pick the best indices in the start and end logits and gather all the answers this predicts. After checking if each one is valid, we will sort them by their score and keep the best one. Here is how we would do this on the first feature in the batch. And then we can sort the valid_answers
according to their score and only keep the best one. The only point left is how to check a given span is inside the context (and not the question) and how to get back the text inside. To do this, we need to add two things to our validation features:
the ID of the example that generated the feature (since each example can generate several features, as seen before);
the offset mapping that will give us a map from token indices to character positions in the context. That's why we will re-process the validation set with the following function, slightly different from
prepare_train_features
:
Now we can grab the predictions for all features by using the Trainer.predict
method:
The ORTTrainer
hides the columns that are not used by the model (here example_id
and offset_mapping
which we will need for our post-processing), so we set them back:
We can now refine the test we had before: since we set None
in the offset mappings when it corresponds to a part of the question, it's easy to check if an answer is fully inside the context. We also eliminate very long answers from our considerations (with an hyper-parameter we can tune)
Then we can load the metric from the datasets library.
Then we can call compute on it. We just need to format predictions and labels a bit as it expects a list of dictionaries and not one big dictionary. In the case of squad_v2, we also have to set a no_answer_probability
argument (which we set to 0.0 here as we have already set the answer to empty if we picked it).
Inference of fine-tuned DeBERTa model
In 🤗 Optimum, we also provides ORTModel
API to ease the inference with ONNX Runtime backend.