Multiple choice

A multiple choice task is similar to question answering, except several candidate answers are provided along with a context and the model is trained to select the correct answer.

This guide will show you how to:

  1. Finetune BERT on the regular configuration of the SWAG dataset to select the best answer given multiple options and some context.

  2. Use your finetuned model for inference.

The task illustrated in this tutorial is supported by the following model architectures:

ALBERT, BERT, BigBird, CamemBERT, CANINE, ConvBERT, Data2VecText, DeBERTa-v2, DistilBERT, ELECTRA, ERNIE, ErnieM, FlauBERT, FNet, Funnel Transformer, I-BERT, Longformer, LUKE, MEGA, Megatron-BERT, MobileBERT, MPNet, MRA, Nezha, NystrΓΆmformer, QDQBert, RemBERT, RoBERTa, RoBERTa-PreLayerNorm, RoCBert, RoFormer, SqueezeBERT, XLM, XLM-RoBERTa, XLM-RoBERTa-XL, XLNet, X-MOD, YOSO

Before you begin, make sure you have all the necessary libraries installed:

Copied

pip install transformers datasets evaluate

We encourage you to login to your BOINC AI account so you can upload and share your model with the community. When prompted, enter your token to login:

Copied

>>> from boincai_hub import notebook_login

>>> notebook_login()

Load SWAG dataset

Start by loading the regular configuration of the SWAG dataset from the 🌍 Datasets library:

Copied

Then take a look at an example:

Copied

While it looks like there are a lot of fields here, it is actually pretty straightforward:

  • sent1 and sent2: these fields show how a sentence starts, and if you put the two together, you get the startphrase field.

  • ending: suggests a possible ending for how a sentence can end, but only one of them is correct.

  • label: identifies the correct sentence ending.

Preprocess

The next step is to load a BERT tokenizer to process the sentence starts and the four possible endings:

Copied

The preprocessing function you want to create needs to:

  1. Make four copies of the sent1 field and combine each of them with sent2 to recreate how a sentence starts.

  2. Combine sent2 with each of the four possible sentence endings.

  3. Flatten these two lists so you can tokenize them, and then unflatten them afterward so each example has a corresponding input_ids, attention_mask, and labels field.

Copied

To apply the preprocessing function over the entire dataset, use 🌍 Datasets map method. You can speed up the map function by setting batched=True to process multiple elements of the dataset at once:

Copied

🌍 Transformers doesn’t have a data collator for multiple choice, so you’ll need to adapt the DataCollatorWithPadding to create a batch of examples. It’s more efficient to dynamically pad the sentences to the longest length in a batch during collation, instead of padding the whole dataset to the maximum length.

DataCollatorForMultipleChoice flattens all the model inputs, applies padding, and then unflattens the results:

PytorchHide Pytorch contentCopied

TensorFlowHide TensorFlow contentCopied

Evaluate

Including a metric during training is often helpful for evaluating your model’s performance. You can quickly load a evaluation method with the 🌍 Evaluate library. For this task, load the accuracy metric (see the 🌍 Evaluate quick tour to learn more about how to load and compute a metric):

Copied

Then create a function that passes your predictions and labels to compute to calculate the accuracy:

Copied

Your compute_metrics function is ready to go now, and you’ll return to it when you setup your training.

Train

PytorchHide Pytorch content

If you aren’t familiar with finetuning a model with the Trainer, take a look at the basic tutorial here!

You’re ready to start training your model now! Load BERT with AutoModelForMultipleChoice:

Copied

At this point, only three steps remain:

  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.

  2. Pass the training arguments to Trainer along with the model, dataset, tokenizer, data collator, and compute_metrics function.

  3. Call train() to finetune your model.

Copied

Once training is completed, share your model to the Hub with the push_to_hub() method so everyone can use your model:

Copied

TensorFlowHide TensorFlow content

If you aren’t familiar with finetuning a model with Keras, take a look at the basic tutorial here!

To finetune a model in TensorFlow, start by setting up an optimizer function, learning rate schedule, and some training hyperparameters:Copied

Then you can load BERT with TFAutoModelForMultipleChoice:

Copied

Convert your datasets to the tf.data.Dataset format with prepare_tf_dataset():

Copied

Configure the model for training with compile. Note that Transformers models all have a default task-relevant loss function, so you don’t need to specify one unless you want to:

Copied

The last two things to setup before you start training is to compute the accuracy from the predictions, and provide a way to push your model to the Hub. Both are done by using Keras callbacks.

Pass your compute_metrics function to KerasMetricCallback:

Copied

Specify where to push your model and tokenizer in the PushToHubCallback:

Copied

Then bundle your callbacks together:

Copied

Finally, you’re ready to start training your model! Call fit with your training and validation datasets, the number of epochs, and your callbacks to finetune the model:

Copied

Once training is completed, your model is automatically uploaded to the Hub so everyone can use it!

For a more in-depth example of how to finetune a model for multiple choice, take a look at the corresponding PyTorch notebook or TensorFlow notebook.

Inference

Great, now that you’ve finetuned a model, you can use it for inference!

Come up with some text and two candidate answers:

Copied

PytorchHide Pytorch content

Tokenize each prompt and candidate answer pair and return PyTorch tensors. You should also create some labels:

Copied

Pass your inputs and labels to the model and return the logits:

Copied

Get the class with the highest probability:

Copied

TensorFlowHide TensorFlow content

Tokenize each prompt and candidate answer pair and return TensorFlow tensors:

Copied

Pass your inputs to the model and return the logits:

Copied

Get the class with the highest probability:

Copied

Last updated