--- title: modeling.question_answering keywords: fastai sidebar: home_sidebar summary: "This module contains custom models, loss functions, custom splitters, etc... for question answering tasks" description: "This module contains custom models, loss functions, custom splitters, etc... for question answering tasks" nb_path: "nbs/02b_modeling-question-answering.ipynb" ---
{% raw %}
{% endraw %} {% raw %}
{% endraw %} {% raw %}
torch.cuda.set_device(1)
print(f'Using GPU #{torch.cuda.current_device()}: {torch.cuda.get_device_name()}')
Using GPU #1: GeForce GTX 1080 Ti
{% endraw %}

Question Answer

Given a document (context) and a question, the objective of these models is to predict the start and end token of the correct answer as it exists in the context.

Again, we'll use a subset of pre-processed SQUAD v2 for our purposes below.

{% raw %}
# squad_df = pd.read_csv('./data/task-question-answering/squad_cleaned.csv'); len(squad_df)

# sample
squad_df = pd.read_csv('./squad_sample.csv'); len(squad_df)
1000
{% endraw %} {% raw %}
squad_df.head(2)
id title context question answers ds_type answer_text is_impossible
0 56be85543aeaaa14008c9063 Beyoncé Beyoncé Giselle Knowles-Carter (/biːˈjɒnseɪ/ bee-YON-say) (born September 4, 1981) is an American singer, songwriter, record producer and actress. Born and raised in Houston, Texas, she performed in various singing and dancing competitions as a child, and rose to fame in the late 1990s as lead singer of R&B girl-group Destiny's Child. Managed by her father, Mathew Knowles, the group became one of the world's best-selling girl groups of all time. Their hiatus saw the release of Beyoncé's debut album, Dangerously in Love (2003), which established her as a solo artist worldwide, earned five G... When did Beyonce start becoming popular? {'text': ['in the late 1990s'], 'answer_start': [269]} train in the late 1990s False
1 56be85543aeaaa14008c9065 Beyoncé Beyoncé Giselle Knowles-Carter (/biːˈjɒnseɪ/ bee-YON-say) (born September 4, 1981) is an American singer, songwriter, record producer and actress. Born and raised in Houston, Texas, she performed in various singing and dancing competitions as a child, and rose to fame in the late 1990s as lead singer of R&B girl-group Destiny's Child. Managed by her father, Mathew Knowles, the group became one of the world's best-selling girl groups of all time. Their hiatus saw the release of Beyoncé's debut album, Dangerously in Love (2003), which established her as a solo artist worldwide, earned five G... What areas did Beyonce compete in when she was growing up? {'text': ['singing and dancing'], 'answer_start': [207]} train singing and dancing False
{% endraw %} {% raw %}
pretrained_model_name = 'bert-large-uncased-whole-word-masking-finetuned-squad'
hf_model_cls = BertForQuestionAnswering

hf_arch, hf_config, hf_tokenizer, hf_model = BLURR_MODEL_HELPER.get_hf_objects(pretrained_model_name,
                                                                               model_cls=hf_model_cls)

# # here's a pre-trained roberta model for squad you can try too
# pretrained_model_name = "ahotrod/roberta_large_squad2"
# hf_arch, hf_config, hf_tokenizer, hf_model = BLURR_MODEL_HELPER.get_hf_objects(pretrained_model_name,
#                                                                                task=HF_TASKS_AUTO.ForQuestionAnswering)

# # here's a pre-trained xlm model for squad you can try too
# pretrained_model_name = 'xlm-mlm-ende-1024'
# hf_arch, hf_config, hf_tokenizer, hf_model = BLURR_MODEL_HELPER.get_hf_objects(pretrained_model_name,
#                                                                                task=HF_TASKS_AUTO.ForQuestionAnswering)
{% endraw %} {% raw %}
squad_df = squad_df.apply(partial(pre_process_squad, hf_arch=hf_arch, hf_tokenizer=hf_tokenizer), axis=1)
{% endraw %} {% raw %}
max_seq_len= 128
{% endraw %} {% raw %}
squad_df = squad_df[(squad_df.tokenized_input_len < max_seq_len) & (squad_df.is_impossible == False)]
{% endraw %} {% raw %}
vocab = list(range(max_seq_len))
# vocab = dict(enumerate(range(max_seq_len)));
{% endraw %} {% raw %}
trunc_strat = 'only_second' if (hf_tokenizer.padding_side == 'right') else 'only_first'

blocks = (
    HF_TextBlock(hf_arch, hf_tokenizer, 
                 hf_batch_tfm=HF_QABatchTransform(hf_arch, hf_tokenizer), 
                 max_length=max_seq_len, truncation=trunc_strat, 
                 tok_kwargs={ 'return_special_tokens_mask': True }), 
    CategoryBlock(vocab=vocab),
    CategoryBlock(vocab=vocab)
)

def get_x(x):
    return (x.question, x.context) if (hf_tokenizer.padding_side == 'right') else (x.context, x.question)

dblock = DataBlock(blocks=blocks, 
                   get_x=get_x,
                   get_y=[ColReader('tok_answer_start'), ColReader('tok_answer_end')],
                   splitter=RandomSplitter(),
                   n_inp=1)
{% endraw %} {% raw %}
dls = dblock.dataloaders(squad_df, bs=4)
{% endraw %} {% raw %}
len(dls.vocab), dls.vocab[0], dls.vocab[1]
(2, (#128) [0,1,2,3,4,5,6,7,8,9...], (#128) [0,1,2,3,4,5,6,7,8,9...])
{% endraw %} {% raw %}
dls.show_batch(dataloaders=dls, max_n=2)
text start/end answer
0 beyonce has a clothing line known as what? in 2006, the animal rights organization people for the ethical treatment of animals ( peta ), criticized beyonce for wearing and using fur in her clothing line house of dereon. in 2011, she appeared on the cover of french fashion magazine l'officiel, in blackface and tribal makeup that drew criticism from the media. a statement released from a spokesperson for the magazine said that beyonce's look was " far from the glamorous sasha fierce " and that it was " a return to her african roots ". (41, 45) house of dereon
1 what two instruments did frederic's father play during this time? in october 1810, six months after fryderyk's birth, the family moved to warsaw, where his father acquired a post teaching french at the warsaw lyceum, then housed in the saxon palace. fryderyk lived with his family in the palace grounds. the father played the flute and violin ; the mother played the piano and gave lessons to boys in the boarding house that the chopins kept. chopin was of slight build, and even in early childhood was prone to illnesses. (73, 76) flute and violin
{% endraw %}

Training

Here we create a question/answer specific subclass of HF_BaseModelCallback in order to get all the start and end prediction. We also add here a new loss function that can handle multiple targets

{% raw %}
{% endraw %} {% raw %}

class HF_QstAndAnsModelCallback[source]

HF_QstAndAnsModelCallback(before_fit=None, before_epoch=None, before_train=None, before_batch=None, after_pred=None, after_loss=None, before_backward=None, after_backward=None, after_step=None, after_cancel_batch=None, after_batch=None, after_cancel_train=None, after_train=None, before_validate=None, after_cancel_validate=None, after_validate=None, after_cancel_epoch=None, after_epoch=None, after_cancel_fit=None, after_fit=None) :: HF_BaseModelCallback

We need to return everything from the model for question/answer tasks

{% endraw %}

And here we provide a custom loss function our question answer task, expanding on some techniques learned from here and here.

In fact, this new loss function can be used in many other multi-modal architectures, with any mix of loss functions. For example, this can be ammended to include the is_impossible task, as well as the start/end token tasks in the SQUAD v2 dataset.

{% raw %}
{% endraw %} {% raw %}

class MultiTargetLoss[source]

MultiTargetLoss(loss_classes=[<class 'fastai.layers.CrossEntropyLossFlat'>, <class 'fastai.layers.CrossEntropyLossFlat'>], loss_classes_kwargs=[{}, {}], weights=[1, 1], reduction='mean') :: Module

Provides the ability to apply different loss functions to multi-modal targets/predictions

{% endraw %} {% raw %}
model = HF_BaseModelWrapper(hf_model)

learn = Learner(dls, 
                model,
                opt_func=partial(Adam, decouple_wd=True),
                cbs=[HF_QstAndAnsModelCallback],
                splitter=hf_splitter)

learn.loss_func=MultiTargetLoss()
learn.create_opt()                # -> will create your layer groups based on your "splitter" function
learn.freeze()
{% endraw %}

Notice above how I had to define the loss function after creating the Learner object. I'm not sure why, but the MultiTargetLoss above prohibits the learner from being exported if I do.

{% raw %}
 
{% endraw %} {% raw %}
print(len(learn.opt.param_groups))
4
{% endraw %} {% raw %}
x, y_start, y_end = dls.one_batch()
preds = learn.model(x)
len(preds),preds[0].shape
(2, torch.Size([4, 117]))
{% endraw %} {% raw %}
learn.lr_find(suggestions=True)
SuggestedLRs(lr_min=0.003981071710586548, lr_steep=0.0010000000474974513)
{% endraw %} {% raw %}
learn.fit_one_cycle(3, lr_max=1e-3)
epoch train_loss valid_loss time
0 3.941690 1.963693 00:04
1 2.339156 1.317829 00:05
2 1.629417 1.221269 00:05
{% endraw %}

Showing results

Below we'll add in additional functionality to more intuitively show the results of our model.

{% raw %}
{% endraw %} {% raw %}
learn.show_results(learner=learn, skip_special_tokens=True, max_n=2)
text start/end answer pred start/end pred answer
0 where did chopin live with his family in warsaw? in october 1810, six months after fryderyk's birth, the family moved to warsaw, where his father acquired a post teaching french at the warsaw lyceum, then housed in the saxon palace. fryderyk lived with his family in the palace grounds. the father played the flute and violin ; the mother played the piano and gave lessons to boys in the boarding house that the chopins kept. chopin was of slight build, and even in early childhood was prone to illnesses. (51, 54) saxon palace . (62, 65) the palace grounds
1 how long did her hiatus last? beyonce announced a hiatus from her music career in january 2010, heeding her mother's advice, " to live life, to be inspired by things again ". during the break she and her father parted ways as business partners. beyonce's musical break lasted nine months and saw her visit multiple european cities, the great wall of china, the egyptian pyramids, australia, english music festivals and various museums and ballet performances. (61, 63) nine months (61, 63) nine months
{% endraw %} {% raw %}
inf_df = pd.DataFrame.from_dict([{
    'question': 'What did George Lucas make?',
    'context': 'George Lucas created Star Wars in 1977. He directed and produced it.'   
}], 
    orient='columns')

learn.blurr_predict(inf_df.iloc[0])
(('11', '13'),
 tensor([11]),
 tensor([[1.1308e-07, 2.2973e-08, 1.8233e-09, 3.2164e-09, 1.7925e-09, 1.7979e-09,
          2.2470e-10, 1.1308e-07, 1.4023e-04, 5.7377e-06, 8.6947e-04, 9.9893e-01,
          4.2286e-05, 9.6678e-08, 2.8473e-06, 1.3266e-07, 4.1118e-06, 4.3000e-06,
          9.2727e-09, 1.1698e-06, 2.9507e-07, 2.9422e-08, 1.1342e-07]]))
{% endraw %} {% raw %}
inp_ids = hf_tokenizer.encode('What did George Lucas make?',
                              'George Lucas created Star Wars in 1977. He directed and produced it.')

hf_tokenizer.convert_ids_to_tokens(inp_ids, skip_special_tokens=False)[11:13]
['star', 'wars']
{% endraw %}

Note that there is a bug currently in fastai v2 (or with how I'm assembling everything) that currently prevents us from seeing the decoded predictions and probabilities for the "end" token.

{% raw %}
inf_df = pd.DataFrame.from_dict([{
    'question': 'When was Star Wars made?',
    'context': 'George Lucas created Star Wars in 1977. He directed and produced it.'
}], 
    orient='columns')

test_dl = dls.test_dl(inf_df)
inp = test_dl.one_batch()[0]['input_ids']
probs, _, preds = learn.get_preds(dl=test_dl, with_input=False, with_decoded=True)
{% endraw %} {% raw %}
hf_tokenizer.convert_ids_to_tokens(inp.tolist()[0], 
                                   skip_special_tokens=False)[torch.argmax(probs[0]):torch.argmax(probs[1])]
['1977']
{% endraw %} {% raw %}
learn.unfreeze()
{% endraw %} {% raw %}
learn.fit_one_cycle(3, lr_max=slice(1e-7, 1e-4))
epoch train_loss valid_loss time
0 0.998621 1.170752 00:09
1 0.779585 1.133665 00:08
2 0.744533 1.123558 00:08
{% endraw %} {% raw %}
learn.recorder.plot_loss()
{% endraw %} {% raw %}
learn.show_results(learner=learn, max_n=2)
text start/end answer pred start/end pred answer
0 where did chopin live with his family in warsaw? in october 1810, six months after fryderyk's birth, the family moved to warsaw, where his father acquired a post teaching french at the warsaw lyceum, then housed in the saxon palace. fryderyk lived with his family in the palace grounds. the father played the flute and violin ; the mother played the piano and gave lessons to boys in the boarding house that the chopins kept. chopin was of slight build, and even in early childhood was prone to illnesses. (51, 54) saxon palace . (62, 65) the palace grounds
1 chopin's birth is recorded as when? fryderyk chopin was born in zelazowa wola, 46 kilometres ( 29 miles ) west of warsaw, in what was then the duchy of warsaw, a polish state established by napoleon. the parish baptismal record gives his birthday as 22 february 1810, and cites his given names in the latin form fridericus franciscus ( in polish, he was fryderyk franciszek ). however, the composer and his family used the birthdate 1 march, [ n 2 ] which is now generally accepted as the correct date. (60, 63) 22 february 1810 (60, 63) 22 february 1810
{% endraw %} {% raw %}
learn.blurr_predict(inf_df.iloc[0])
(('14', '15'),
 tensor([14]),
 tensor([[7.3327e-08, 2.5672e-08, 3.0294e-09, 2.2541e-09, 1.7953e-09, 7.0055e-09,
          8.6950e-10, 7.3329e-08, 8.8744e-07, 2.7221e-07, 2.7613e-06, 1.7843e-06,
          2.2260e-07, 6.5549e-04, 9.9934e-01, 2.6669e-07, 1.9501e-08, 1.5008e-08,
          1.4449e-09, 1.0403e-08, 2.6136e-08, 2.1571e-08, 7.2991e-08]]))
{% endraw %} {% raw %}
preds, pred_classes, probs = learn.blurr_predict(inf_df.iloc[0])
preds
('14', '15')
{% endraw %} {% raw %}
inp_ids = hf_tokenizer.encode('When was Star Wars made?',
                              'George Lucas created Star Wars in 1977. He directed and produced it.')

hf_tokenizer.convert_ids_to_tokens(inp_ids, skip_special_tokens=False)[int(preds[0]):int(preds[1])]
['1977']
{% endraw %}

Inference

Note that I had to replace the loss function because of the above-mentioned issue to exporting the model with the MultiTargetLoss loss function. After getting our inference learner, we put it back and we're good to go!

{% raw %}
learn.loss_func = nn.CrossEntropyLoss()
learn.export(fname='q_and_a_learn_export.pkl')
{% endraw %} {% raw %}
inf_learn = load_learner(fname='q_and_a_learn_export.pkl')
inf_learn.loss_func = MultiTargetLoss()

inf_df = pd.DataFrame.from_dict([
    {'question': 'Who created Star Wars?', 
     'context': 'George Lucas created Star Wars in 1977. He directed and produced it.'}],
    orient='columns')

inf_learn.blurr_predict(inf_df.iloc[0])
(('7', '9'),
 tensor([7]),
 tensor([[1.0196e-07, 7.8641e-09, 1.4333e-09, 3.4000e-09, 1.9695e-09, 7.5575e-10,
          1.0197e-07, 9.9980e-01, 1.9805e-04, 2.2385e-07, 1.0828e-07, 7.1924e-08,
          6.6511e-08, 2.9876e-06, 3.5409e-08, 3.6721e-07, 2.6438e-08, 1.5948e-09,
          1.4573e-08, 1.4323e-08, 1.2167e-08, 3.1713e-08]]))
{% endraw %} {% raw %}
inp_ids = hf_tokenizer.encode('Who created Star Wars?',
                              'George Lucas created Star Wars in 1977. He directed and produced it.')

hf_tokenizer.convert_ids_to_tokens(inp_ids, skip_special_tokens=False)[7:9]
['george', 'lucas']
{% endraw %}

Cleanup