--- 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'

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

blocks = (
    HF_TextBlock(hf_batch_tfm=hf_batch_tfm), 
    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 when did beyonce have her first child? on january 7, 2012, beyonce gave birth to her first child, a daughter, blue ivy carter, at lenox hill hospital in new york. five months later, she performed for four nights at revel atlantic city's ovation hall to celebrate the resort's opening, her first performances since giving birth to blue ivy. (11, 15) january 7 , 2012
1 in what city did frederic achieve celebrity status? in paris, chopin encountered artists and other distinguished figures, and found many opportunities to exercise his talents and achieve celebrity. during his years in paris he was to become acquainted with, among many others, hector berlioz, franz liszt, ferdinand hiller, heinrich heine, eugene delacroix, and alfred de vigny. chopin was also acquainted with the poet adam mickiewicz, principal of the polish literary society, some of whose verses he set as songs. (12, 13) paris
{% 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, 116]))
{% endraw %} {% raw %}
learn.lr_find(suggestions=True)
SuggestedLRs(lr_min=0.003981071710586548, lr_steep=7.585775847473997e-07)
{% endraw %} {% raw %}
learn.fit_one_cycle(3, lr_max=1e-3)
epoch train_loss valid_loss time
0 4.402006 2.119611 00:05
1 2.355530 1.628156 00:05
2 1.576271 1.559822 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 beyonce released the song " formation " on which online music service? on february 6, 2016, one day before her performance at the super bowl, beyonce released a new single exclusively on music streaming service tidal called " formation ". (41, 42) tidal (41, 42) tidal
1 where did beyonce perform in 2011? in 2011, documents obtained by wikileaks revealed that beyonce was one of many entertainers who performed for the family of libyan ruler muammar gaddafi. rolling stone reported that the music industry was urging them to return the money they earned for the concerts ; a spokesperson for beyonce later confirmed to the huffington post that she donated the money to the clinton bush haiti fund. later that year she became the first solo female artist to headline the main pyramid stage at the 2011 glastonbury festival in over twenty years, and was named the highest - paid performer in the world per minute. (102, 107) glastonbury festival (102, 111) glastonbury festival in over twenty years
{% 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.8803e-07, 7.6365e-08, 5.2116e-09, 1.0237e-08, 7.7016e-09, 5.8971e-09,
          6.6167e-10, 1.8803e-07, 5.8261e-04, 3.8029e-05, 1.2377e-03, 9.9782e-01,
          2.8809e-04, 5.7679e-07, 1.3494e-05, 7.7548e-07, 7.5614e-06, 5.9867e-06,
          2.8694e-08, 2.8148e-06, 1.0733e-06, 1.5398e-07, 1.1601e-06]]))
{% 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.913628 1.529447 00:09
1 0.819364 1.476102 00:09
2 0.755131 1.467101 00:09
{% 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 beyonce released the song " formation " on which online music service? on february 6, 2016, one day before her performance at the super bowl, beyonce released a new single exclusively on music streaming service tidal called " formation ". (41, 42) tidal (41, 42) tidal
1 what was the name of the streaming service? on february 6, 2016, one day before her performance at the super bowl, beyonce released a new single exclusively on music streaming service tidal called " formation ". (37, 38) tidal (37, 38) tidal
{% endraw %} {% raw %}
learn.blurr_predict(inf_df.iloc[0])
(('14', '15'),
 tensor([14]),
 tensor([[8.6330e-08, 5.4166e-08, 8.1394e-09, 5.7046e-09, 4.8600e-09, 1.6930e-08,
          2.4619e-09, 8.6331e-08, 2.8848e-06, 8.7822e-07, 8.0265e-06, 5.3678e-06,
          1.1227e-06, 7.0352e-04, 9.9928e-01, 1.1809e-06, 1.5530e-07, 5.6486e-08,
          4.0244e-09, 4.3187e-08, 9.9077e-08, 7.6848e-08, 3.1637e-07]]))
{% 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.4677e-07, 2.3531e-08, 3.7708e-09, 9.2142e-09, 6.9512e-09, 1.8539e-09,
          1.4678e-07, 9.9821e-01, 1.7701e-03, 1.2117e-06, 6.7467e-07, 5.6864e-07,
          3.5706e-07, 1.8533e-05, 2.3238e-07, 1.5476e-06, 1.0116e-07, 5.7917e-09,
          7.5709e-08, 7.4858e-08, 6.8549e-08, 2.2211e-07]]))
{% 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