CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
huggingface

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: huggingface/notebooks
Path: blob/main/examples/question_answering_ort.ipynb
Views: 2535
Kernel: Python 3 (ipykernel)

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

# Check your GPU !nvidia-smi
Thu Apr 6 08:49:04 2023 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 510.108.03 Driver Version: 510.108.03 CUDA Version: 11.6 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |===============================+======================+======================| | 0 Tesla V100-SXM2... Off | 00000000:00:1D.0 Off | 0 | | N/A 38C P0 39W / 300W | 4MiB / 16384MiB | 0% Default | | | | N/A | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=============================================================================| +-----------------------------------------------------------------------------+

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.

!pip install optimum transformers datasets evaluate huggingface_hub
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
# This flag is the difference between SQUAD v1 or 2 (if you're using another dataset, it indicates if impossible # answers are allowed or not). squad_v2 = False model_checkpoint = "microsoft/deberta-base" batch_size = 16

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.

from datasets import load_dataset, load_metric datasets = load_dataset("squad_v2" if squad_v2 else "squad")
/usr/local/lib/python3.8/dist-packages/tqdm/auto.py:22: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm Downloading builder script: 100%|███████████████████████████████████████████████████████████| 5.27k/5.27k [00:00<00:00, 5.12MB/s] Downloading metadata: 100%|█████████████████████████████████████████████████████████████████| 2.36k/2.36k [00:00<00:00, 2.29MB/s] Downloading readme: 100%|███████████████████████████████████████████████████████████████████| 7.67k/7.67k [00:00<00:00, 5.37MB/s]
Downloading and preparing dataset squad/plain_text to /root/.cache/huggingface/datasets/squad/plain_text/1.0.0/d6ec3ceb99ca480ce37cdd35555d6cb2511d223b9150cce08a837ef62ffea453...
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]
Dataset squad downloaded and prepared to /root/.cache/huggingface/datasets/squad/plain_text/1.0.0/d6ec3ceb99ca480ce37cdd35555d6cb2511d223b9150cce08a837ef62ffea453. Subsequent calls will reuse this data.
100%|█████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:00<00:00, 278.17it/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.

datasets
DatasetDict({ train: Dataset({ features: ['id', 'title', 'context', 'question', 'answers'], num_rows: 87599 }) validation: Dataset({ features: ['id', 'title', 'context', 'question', 'answers'], num_rows: 10570 }) })

We can access an actual element to see what the data looks like:

datasets["train"][0]
{'id': '5733be284776f41900661182', 'title': 'University_of_Notre_Dame', 'context': 'Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.', 'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?', 'answers': {'text': ['Saint Bernadette Soubirous'], 'answer_start': [515]}}

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.

from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
Downloading (…)okenizer_config.json: 100%|████████████████████████████████████████████████████| 52.0/52.0 [00:00<00:00, 17.2kB/s] Downloading (…)lve/main/config.json: 100%|███████████████████████████████████████████████████████| 474/474 [00:00<00:00, 406kB/s] Downloading (…)olve/main/vocab.json: 100%|████████████████████████████████████████████████████| 899k/899k [00:00<00:00, 11.8MB/s] Downloading (…)olve/main/merges.txt: 100%|████████████████████████████████████████████████████| 456k/456k [00:00<00:00, 3.10MB/s]

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:

max_length = 384 # The maximum length of a feature (question and context) doc_stride = 128 # The authorized overlap between two part of the context when splitting it is needed.

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.

pad_on_right = tokenizer.padding_side == "right"

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.

def prepare_train_features(examples): # Some of the questions have lots of whitespace on the left, which is not useful and will make the # truncation of the context fail (the tokenized question will take a lots of space). So we remove that # left whitespace examples["question"] = [q.lstrip() for q in examples["question"]] # Tokenize our examples with truncation and padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. tokenized_examples = tokenizer( examples["question" if pad_on_right else "context"], examples["context" if pad_on_right else "question"], truncation="only_second" if pad_on_right else "only_first", max_length=max_length, stride=doc_stride, return_overflowing_tokens=True, return_offsets_mapping=True, padding="max_length", ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping") # The offset mappings will give us a map from token to character position in the original context. This will # help us compute the start_positions and end_positions. offset_mapping = tokenized_examples.pop("offset_mapping") # Let's label those examples! tokenized_examples["start_positions"] = [] tokenized_examples["end_positions"] = [] for i, offsets in enumerate(offset_mapping): # We will label impossible answers with the index of the CLS token. input_ids = tokenized_examples["input_ids"][i] cls_index = input_ids.index(tokenizer.cls_token_id) # Grab the sequence corresponding to that example (to know what is the context and what is the question). sequence_ids = tokenized_examples.sequence_ids(i) # One example can give several spans, this is the index of the example containing this span of text. sample_index = sample_mapping[i] answers = examples["answers"][sample_index] # If no answers are given, set the cls_index as answer. if len(answers["answer_start"]) == 0: tokenized_examples["start_positions"].append(cls_index) tokenized_examples["end_positions"].append(cls_index) else: # Start/end character index of the answer in the text. start_char = answers["answer_start"][0] end_char = start_char + len(answers["text"][0]) # Start token index of the current span in the text. token_start_index = 0 while sequence_ids[token_start_index] != (1 if pad_on_right else 0): token_start_index += 1 # End token index of the current span in the text. token_end_index = len(input_ids) - 1 while sequence_ids[token_end_index] != (1 if pad_on_right else 0): token_end_index -= 1 # Detect if the answer is out of the span (in which case this feature is labeled with the CLS index). if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char): tokenized_examples["start_positions"].append(cls_index) tokenized_examples["end_positions"].append(cls_index) else: # Otherwise move the token_start_index and token_end_index to the two ends of the answer. # Note: we could go after the last offset if the answer is the last word (edge case). while token_start_index < len(offsets) and offsets[token_start_index][0] <= start_char: token_start_index += 1 tokenized_examples["start_positions"].append(token_start_index - 1) while offsets[token_end_index][1] >= end_char: token_end_index -= 1 tokenized_examples["end_positions"].append(token_end_index + 1) return tokenized_examples

Now apply this function on all the sentences (or pairs of sentences) in our dataset:

tokenized_datasets = datasets.map(prepare_train_features, batched=True, remove_columns=datasets["train"].column_names)

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:

from transformers import AutoModelForQuestionAnswering from optimum.onnxruntime import ORTTrainer, ORTTrainingArguments from transformers import default_data_collator model = AutoModelForQuestionAnswering.from_pretrained(model_checkpoint) data_collator = default_data_collator
Some weights of the model checkpoint at microsoft/deberta-base were not used when initializing DebertaForQuestionAnswering: ['lm_predictions.lm_head.bias', 'lm_predictions.lm_head.dense.bias', 'lm_predictions.lm_head.LayerNorm.bias', 'lm_predictions.lm_head.LayerNorm.weight', 'deberta.embeddings.position_embeddings.weight', 'lm_predictions.lm_head.dense.weight'] - This IS expected if you are initializing DebertaForQuestionAnswering from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model). - This IS NOT expected if you are initializing DebertaForQuestionAnswering from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model). Some weights of DebertaForQuestionAnswering were not initialized from the model checkpoint at microsoft/deberta-base and are newly initialized: ['qa_outputs.weight', 'qa_outputs.bias'] You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.

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).

!wget https://raw.githubusercontent.com/huggingface/optimum/main/tests/onnxruntime/ds_configs/ds_config_zero_stage_1.json
huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) --2023-04-06 08:56:02-- https://raw.githubusercontent.com/huggingface/optimum/main/tests/onnxruntime/ds_configs/ds_config_zero_stage_1.json Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.108.133, 185.199.109.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 1224 (1.2K) [text/plain] Saving to: ‘ds_config_zero_stage_1.json.1’ ds_config_zero_stag 100%[===================>] 1.20K --.-KB/s in 0s 2023-04-06 08:56:02 (60.4 MB/s) - ‘ds_config_zero_stage_1.json.1’ saved [1224/1224]
model_name = model_checkpoint.split("/")[-1] args = ORTTrainingArguments( output_dir=f"{model_name}-finetuned-squad", evaluation_strategy = "epoch", learning_rate=2e-5, per_device_train_batch_size=batch_size, per_device_eval_batch_size=batch_size, num_train_epochs=3, weight_decay=0.01, optim="adamw_ort_fused", deepspeed="ds_config_zero_stage_1.json", )

Instantiate ORTTrainer, here we will use ORT fused optimizer to have better performance on latency:

trainer = ORTTrainer( model=model, args=args, train_dataset=tokenized_datasets["train"], eval_dataset=tokenized_datasets["validation"], data_collator=data_collator, tokenizer=tokenizer, feature="question-answering", )

Launch the training (it will leverage one single GPU for the training)

trainer.train() trainer.save_model()
Wrap ORTModule for ONNX Runtime training.
[2023-04-05 16:41:07,941] [WARNING] [config_utils.py:74:_process_deprecated_field] Config parameter cpu_offload is deprecated use offload_optimizer instead
/usr/local/lib/python3.8/dist-packages/torch/onnx/utils.py:1794: FutureWarning: The first argument to symbolic functions is deprecated in 1.13 and will be removed in the future. Please annotate treat the first argument (g) as GraphContext and use context information from the object instead. warnings.warn( /usr/local/lib/python3.8/dist-packages/onnxruntime/training/ortmodule/_utils.py:250: UserWarning: User Module's attribute name float collides with ORTModule's attribute name. User Module's method may not be called upon invocation through ORTModule. warnings.warn( /usr/local/lib/python3.8/dist-packages/onnxruntime/training/ortmodule/_utils.py:250: UserWarning: User Module's attribute name half collides with ORTModule's attribute name. User Module's method may not be called upon invocation through ORTModule. warnings.warn( /usr/local/lib/python3.8/dist-packages/onnxruntime/training/ortmodule/_utils.py:250: UserWarning: User Module's attribute name to collides with ORTModule's attribute name. User Module's method may not be called upon invocation through ORTModule. warnings.warn(
huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)
Using /root/.cache/torch_extensions/py38_cu116 as PyTorch extensions root... Creating extension directory /root/.cache/torch_extensions/py38_cu116/fused_adam... Detected CUDA files, patching ldflags Emitting ninja build file /root/.cache/torch_extensions/py38_cu116/fused_adam/build.ninja... Building extension module fused_adam... Allowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N)
huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) [1/3] /usr/local/cuda/bin/nvcc -DTORCH_EXTENSION_NAME=fused_adam -DTORCH_API_INCLUDE_EXTENSION_H -DPYBIND11_COMPILER_TYPE=\"_gcc\" -DPYBIND11_STDLIB=\"_libstdcpp\" -DPYBIND11_BUILD_ABI=\"_cxxabi1011\" -I/usr/local/lib/python3.8/dist-packages/deepspeed/ops/csrc/includes -I/usr/local/lib/python3.8/dist-packages/deepspeed/ops/csrc/adam -isystem /usr/local/lib/python3.8/dist-packages/torch/include -isystem /usr/local/lib/python3.8/dist-packages/torch/include/torch/csrc/api/include -isystem /usr/local/lib/python3.8/dist-packages/torch/include/TH -isystem /usr/local/lib/python3.8/dist-packages/torch/include/THC -isystem /usr/local/cuda/include -isystem /usr/include/python3.8 -D_GLIBCXX_USE_CXX11_ABI=0 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_BFLOAT16_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr -gencode=arch=compute_70,code=compute_70 -gencode=arch=compute_70,code=sm_70 --compiler-options '-fPIC' -O3 -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -lineinfo --use_fast_math -gencode=arch=compute_70,code=sm_70 -gencode=arch=compute_70,code=compute_70 -std=c++14 -c /usr/local/lib/python3.8/dist-packages/deepspeed/ops/csrc/adam/multi_tensor_adam.cu -o multi_tensor_adam.cuda.o [2/3] c++ -MMD -MF fused_adam_frontend.o.d -DTORCH_EXTENSION_NAME=fused_adam -DTORCH_API_INCLUDE_EXTENSION_H -DPYBIND11_COMPILER_TYPE=\"_gcc\" -DPYBIND11_STDLIB=\"_libstdcpp\" -DPYBIND11_BUILD_ABI=\"_cxxabi1011\" -I/usr/local/lib/python3.8/dist-packages/deepspeed/ops/csrc/includes -I/usr/local/lib/python3.8/dist-packages/deepspeed/ops/csrc/adam -isystem /usr/local/lib/python3.8/dist-packages/torch/include -isystem /usr/local/lib/python3.8/dist-packages/torch/include/torch/csrc/api/include -isystem /usr/local/lib/python3.8/dist-packages/torch/include/TH -isystem /usr/local/lib/python3.8/dist-packages/torch/include/THC -isystem /usr/local/cuda/include -isystem /usr/include/python3.8 -D_GLIBCXX_USE_CXX11_ABI=0 -fPIC -std=c++14 -O3 -std=c++14 -g -Wno-reorder -DVERSION_GE_1_1 -DVERSION_GE_1_3 -DVERSION_GE_1_5 -c /usr/local/lib/python3.8/dist-packages/deepspeed/ops/csrc/adam/fused_adam_frontend.cpp -o fused_adam_frontend.o [3/3] c++ fused_adam_frontend.o multi_tensor_adam.cuda.o -shared -L/usr/local/lib/python3.8/dist-packages/torch/lib -lc10 -lc10_cuda -ltorch_cpu -ltorch_cuda_cu -ltorch_cuda_cpp -ltorch -ltorch_python -L/usr/local/cuda/lib64 -lcudart -o fused_adam.so Time to load fused_adam op: 35.75363326072693 seconds huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)
Loading extension module fused_adam... Using /root/.cache/torch_extensions/py38_cu116 as PyTorch extensions root... Creating extension directory /root/.cache/torch_extensions/py38_cu116/utils... Emitting ninja build file /root/.cache/torch_extensions/py38_cu116/utils/build.ninja... Building extension module utils... Allowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N)
huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks... To disable this warning, you can either: - Avoid using `tokenizers` before the fork if possible - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false) [1/2] c++ -MMD -MF flatten_unflatten.o.d -DTORCH_EXTENSION_NAME=utils -DTORCH_API_INCLUDE_EXTENSION_H -DPYBIND11_COMPILER_TYPE=\"_gcc\" -DPYBIND11_STDLIB=\"_libstdcpp\" -DPYBIND11_BUILD_ABI=\"_cxxabi1011\" -isystem /usr/local/lib/python3.8/dist-packages/torch/include -isystem /usr/local/lib/python3.8/dist-packages/torch/include/torch/csrc/api/include -isystem /usr/local/lib/python3.8/dist-packages/torch/include/TH -isystem /usr/local/lib/python3.8/dist-packages/torch/include/THC -isystem /usr/include/python3.8 -D_GLIBCXX_USE_CXX11_ABI=0 -fPIC -std=c++14 -c /usr/local/lib/python3.8/dist-packages/deepspeed/ops/csrc/utils/flatten_unflatten.cpp -o flatten_unflatten.o [2/2] c++ flatten_unflatten.o -shared -L/usr/local/lib/python3.8/dist-packages/torch/lib -lc10 -ltorch_cpu -ltorch -ltorch_python -o utils.so Time to load utils op: 20.83265709877014 seconds
Loading extension module utils...
Rank: 0 partition count [1] and sizes[(138603266, False)]
Using /root/.cache/torch_extensions/py38_cu116 as PyTorch extensions root... No modifications detected for re-loaded extension module utils, skipping build step... Loading extension module utils... ***** Running training ***** Num examples = 88550 Num Epochs = 3 Instantaneous batch size per device = 16 Total train batch size (w. parallel, distributed & accumulation) = 16 Gradient Accumulation steps = 1 Total optimization steps = 16605 Number of trainable parameters = 138603266 /usr/local/lib/python3.8/dist-packages/onnxruntime/training/ortmodule/_training_manager.py:192: UserWarning: Fast path enabled - skipping checks. Rebuild graph: True, Execution agent: True, Device check: True warnings.warn(
Time to load utils op: 0.0007810592651367188 seconds
Warning: Checker does not support models with experimental ops: ATen /usr/local/lib/python3.8/dist-packages/onnxruntime/training/ortmodule/_logger.py:52: UserWarning: There were one or more warnings or errors raised while exporting the PyTorch model. Please enable INFO level logging to view all warnings and errors. warnings.warn( Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0
[INFO] Evaluating with PyTorch backend. If you want to use ONNX Runtime for the evaluation, set `trainer.evaluate(inference_with_ort=True)`. /usr/local/lib/python3.8/dist-packages/onnxruntime/training/ortmodule/_inference_manager.py:76: UserWarning: Fast path enabled - skipping checks.rebuild gradient graph: True,execution agent recreation: True,device check: True warnings.warn( Warning: Checker does not support models with experimental ops: ATen Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 Cannot determine if 512 - attention_mask_dim1 < 0 [INFO] Evaluating with PyTorch backend. If you want to use ONNX Runtime for the evaluation, set `trainer.evaluate(inference_with_ort=True)`. [INFO] Evaluating with PyTorch backend. If you want to use ONNX Runtime for the evaluation, set `trainer.evaluate(inference_with_ort=True)`. Training completed. Do not forget to share your model on huggingface.co/models =)

If you want to leverage multiple gpus for distributed data parallele training, you can use 🤗 Accelerate's notebook launcher to enable multi-gpu training:

from accelerate import notebook_launcher def train_trainer_ddp(): model = AutoModelForQuestionAnswering.from_pretrained(model_checkpoint) model_name = model_checkpoint.split("/")[-1] args = ORTTrainingArguments( output_dir=f"{model_name}-finetuned-squad", evaluation_strategy = "epoch", learning_rate=2e-5, per_device_train_batch_size=batch_size, per_device_eval_batch_size=batch_size, num_train_epochs=3, weight_decay=0.01, optim="adamw_ort_fused", deepspeed="ds_config_zero_stage_1.json", ) data_collator = default_data_collator trainer = ORTTrainer( model=model, args=args, train_dataset=tokenized_datasets["train"], eval_dataset=tokenized_datasets["validation"], data_collator=data_collator, tokenizer=tokenizer, feature="question-answering", ) trainer.train() trainer.save_model() notebook_launcher(train_trainer_ddp, args=(), num_processes=4)

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:

import torch for batch in trainer.get_eval_dataloader(): break batch = {k: v.to(trainer.args.device) for k, v in batch.items()} with torch.no_grad(): output = trainer.model(**batch) output.keys()

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:

n_best_size = 20
def prepare_validation_features(examples): # Some of the questions have lots of whitespace on the left, which is not useful and will make the # truncation of the context fail (the tokenized question will take a lots of space). So we remove that # left whitespace examples["question"] = [q.lstrip() for q in examples["question"]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. tokenized_examples = tokenizer( examples["question" if pad_on_right else "context"], examples["context" if pad_on_right else "question"], truncation="only_second" if pad_on_right else "only_first", max_length=max_length, stride=doc_stride, return_overflowing_tokens=True, return_offsets_mapping=True, padding="max_length", ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping") # We keep the example_id that gave us this feature and we will store the offset mappings. tokenized_examples["example_id"] = [] for i in range(len(tokenized_examples["input_ids"])): # Grab the sequence corresponding to that example (to know what is the context and what is the question). sequence_ids = tokenized_examples.sequence_ids(i) context_index = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. sample_index = sample_mapping[i] tokenized_examples["example_id"].append(examples["id"][sample_index]) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. tokenized_examples["offset_mapping"][i] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples["offset_mapping"][i]) ] return tokenized_examples
validation_features = datasets["validation"].map( prepare_validation_features, batched=True, remove_columns=datasets["validation"].column_names )

Now we can grab the predictions for all features by using the Trainer.predict method:

raw_predictions = trainer.predict(validation_features)

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:

validation_features.set_format(type=validation_features.format["type"], columns=list(validation_features.features.keys()))

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)

max_answer_length = 30
import collections examples = datasets["validation"] features = validation_features example_id_to_index = {k: i for i, k in enumerate(examples["id"])} features_per_example = collections.defaultdict(list) for i, feature in enumerate(features): features_per_example[example_id_to_index[feature["example_id"]]].append(i)
from tqdm.auto import tqdm import numpy as np def postprocess_qa_predictions(examples, features, raw_predictions, n_best_size = 20, max_answer_length = 30): all_start_logits, all_end_logits = raw_predictions # Build a map example to its corresponding features. example_id_to_index = {k: i for i, k in enumerate(examples["id"])} features_per_example = collections.defaultdict(list) for i, feature in enumerate(features): features_per_example[example_id_to_index[feature["example_id"]]].append(i) # The dictionaries we have to fill. predictions = collections.OrderedDict() # Logging. print(f"Post-processing {len(examples)} example predictions split into {len(features)} features.") # Let's loop over all the examples! for example_index, example in enumerate(tqdm(examples)): # Those are the indices of the features associated to the current example. feature_indices = features_per_example[example_index] min_null_score = None # Only used if squad_v2 is True. valid_answers = [] context = example["context"] # Looping through all the features associated to the current example. for feature_index in feature_indices: # We grab the predictions of the model for this feature. start_logits = all_start_logits[feature_index] end_logits = all_end_logits[feature_index] # This is what will allow us to map some the positions in our logits to span of texts in the original # context. offset_mapping = features[feature_index]["offset_mapping"] # Update minimum null prediction. cls_index = features[feature_index]["input_ids"].index(tokenizer.cls_token_id) feature_null_score = start_logits[cls_index] + end_logits[cls_index] if min_null_score is None or min_null_score < feature_null_score: min_null_score = feature_null_score # Go through all possibilities for the `n_best_size` greater start and end logits. start_indexes = np.argsort(start_logits)[-1 : -n_best_size - 1 : -1].tolist() end_indexes = np.argsort(end_logits)[-1 : -n_best_size - 1 : -1].tolist() for start_index in start_indexes: for end_index in end_indexes: # Don't consider out-of-scope answers, either because the indices are out of bounds or correspond # to part of the input_ids that are not in the context. if ( start_index >= len(offset_mapping) or end_index >= len(offset_mapping) or offset_mapping[start_index] is None or offset_mapping[end_index] is None ): continue # Don't consider answers with a length that is either < 0 or > max_answer_length. if end_index < start_index or end_index - start_index + 1 > max_answer_length: continue start_char = offset_mapping[start_index][0] end_char = offset_mapping[end_index][1] valid_answers.append( { "score": start_logits[start_index] + end_logits[end_index], "text": context[start_char: end_char] } ) if len(valid_answers) > 0: best_answer = sorted(valid_answers, key=lambda x: x["score"], reverse=True)[0] else: # In the very rare edge case we have not a single non-null prediction, we create a fake prediction to avoid # failure. best_answer = {"text": "", "score": 0.0} # Let's pick our final answer: the best one or the null answer (only for squad_v2) if not squad_v2: predictions[example["id"]] = best_answer["text"] else: answer = best_answer["text"] if best_answer["score"] > min_null_score else "" predictions[example["id"]] = answer return predictions
final_predictions = postprocess_qa_predictions(datasets["validation"], validation_features, raw_predictions.predictions)
Post-processing 10570 example predictions split into 10788 features.
100%|█████████████████████████████████████████████████████████████████████████████████████| 10570/10570 [00:35<00:00, 300.93it/s]

Then we can load the metric from the datasets library.

metric = load_metric("squad_v2" if squad_v2 else "squad")
/tmp/ipykernel_88/2905994612.py:1: FutureWarning: load_metric is deprecated and will be removed in the next major version of datasets. Use 'evaluate.load' instead, from the new library 🤗 Evaluate: https://huggingface.co/docs/evaluate metric = load_metric("squad_v2" if squad_v2 else "squad") Downloading builder script: 4.50kB [00:00, 2.50MB/s] Downloading extra modules: 3.31kB [00:00, 1.91MB/s]

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).

if squad_v2: formatted_predictions = [{"id": k, "prediction_text": v, "no_answer_probability": 0.0} for k, v in final_predictions.items()] else: formatted_predictions = [{"id": k, "prediction_text": v} for k, v in final_predictions.items()] references = [{"id": ex["id"], "answers": ex["answers"]} for ex in datasets["validation"]] metric.compute(predictions=formatted_predictions, references=references)
{'exact_match': 85.87511825922422, 'f1': 92.14116893007746}

Inference of fine-tuned DeBERTa model

In 🤗 Optimum, we also provides ORTModel API to ease the inference with ONNX Runtime backend.

from optimum.onnxruntime import ORTModelForQuestionAnswering from transformers import AutoTokenizer, pipeline model = ORTModelForQuestionAnswering.from_pretrained("deberta-base-finetuned-squad", export=True) tokenizer = AutoTokenizer.from_pretrained("deberta-base-finetuned-squad")
Framework not specified. Using pt to export to ONNX. Using framework PyTorch: 1.13.1+cu116
question, text = "What's the benefit of using Optimum library?", "Optimum is an open-sourced library. It can accelerate the training speed. We recommend you to test it." inputs = tokenizer(question, text, return_tensors="pt") inputs.pop("token_type_ids")
tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
outputs = model(**inputs) answer_start_index = outputs.start_logits.argmax() answer_end_index = outputs.end_logits.argmax() predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1] tokenizer.decode(predict_answer_tokens, skip_special_tokens=True)
' accelerate the training speed'