This module contains custom models, loss functions, custom splitters, etc... for question answering tasks
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

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.

# 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
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
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)
squad_df = squad_df.apply(partial(pre_process_squad, hf_arch=hf_arch, hf_tokenizer=hf_tokenizer), axis=1)
max_seq_len= 128
squad_df = squad_df[(squad_df.tokenized_input_len < max_seq_len) & (squad_df.is_impossible == False)]
vocab = list(range(max_seq_len))
# vocab = dict(enumerate(range(max_seq_len)));
trunc_strat = 'only_second' if (hf_tokenizer.padding_side == 'right') else 'only_first'

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

blocks = (
    HF_TextBlock(before_batch_tfms=before_batch_tfm, input_return_type=HF_QuestionAnswerInput), 
    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)
dls = dblock.dataloaders(squad_df, bs=4)
len(dls.vocab), dls.vocab[0], dls.vocab[1]
(2,
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127],
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127])
dls.show_batch(dataloaders=dls, max_n=2)
text start/end answer
0 the duchy of warsaw was created by whom? 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. (49, 50) napoleon
1 what people did chopin meet while in paris? 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. (50, 78) hector berlioz , franz liszt , ferdinand hiller , heinrich heine , eugene delacroix , and alfred de vigny

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

class HF_QstAndAnsModelCallback[source]

HF_QstAndAnsModelCallback(after_create=None, 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

The prediction is a combination start/end logits

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.

class MultiTargetLoss[source]

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

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

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

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.

 
print(len(learn.opt.param_groups))
3
x, y_start, y_end = dls.one_batch()
preds = learn.model(x)
len(preds),preds[0].shape
(2, torch.Size([4, 121]))
learn.lr_find(suggestions=True)
SuggestedLRs(lr_min=0.003981071710586548, lr_steep=1.4454397387453355e-05)
learn.fit_one_cycle(3, lr_max=1e-3)
epoch train_loss valid_loss time
0 4.159886 1.792180 00:04
1 2.421132 1.173712 00:04
2 1.639415 1.105648 00:04

Showing results

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

learn.show_results(learner=learn, skip_special_tokens=True, max_n=2, trunc_at=500)
text start/end answer pred start/end pred answer
0 which social media company proclaimed beyonce fans are know as the bey hive? the bey hive is the name given to beyonce's fan base. fans were previously titled " the beyontourage ", ( a portmanteau of beyonce and entourage ). the name bey hive derives from the word beehive, purposely misspelled to resemble her first name, and was penned by fans after petitions on the online social networking service twitter and online news reports during competitions. (89, 90) twitter (89, 90) twitter
1 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 (41, 45) house of dereon (41, 45) house of dereon
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.7072e-07, 7.2564e-08, 5.2190e-09, 1.3088e-08, 7.8630e-09, 5.1895e-09,
          6.2369e-10, 1.7072e-07, 5.3902e-04, 2.8211e-05, 7.6042e-04, 9.9848e-01,
          1.6506e-04, 3.7685e-07, 1.0313e-05, 4.2551e-07, 4.6501e-06, 5.7999e-06,
          2.8140e-08, 2.7340e-06, 8.5120e-07, 1.1564e-07, 1.7016e-07]]))
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']

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.

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)
hf_tokenizer.convert_ids_to_tokens(inp.tolist()[0], 
                                   skip_special_tokens=False)[torch.argmax(probs[0]):torch.argmax(probs[1])]
['1977']
learn.unfreeze()
learn.fit_one_cycle(3, lr_max=slice(1e-7, 1e-4))
epoch train_loss valid_loss time
0 0.913757 1.033584 00:08
1 0.696784 0.990948 00:08
2 0.545841 0.998784 00:08
learn.recorder.plot_loss()
learn.show_results(learner=learn, max_n=2, trunc_at=100)
text start/end answer pred start/end pred answer
0 which social media company proclaimed beyonce fans are know as the bey hive? the bey hive is the nam (89, 90) twitter (89, 90) twitter
1 what did frederic create from verses of the poet adam mickiewicz? in paris, chopin encountered artis (110, 111) songs (110, 111) songs
learn.blurr_predict(inf_df.iloc[0])
(('14', '15'),
 tensor([14]),
 tensor([[9.7567e-08, 5.0001e-08, 8.6410e-09, 6.8171e-09, 6.3203e-09, 1.8096e-08,
          2.3108e-09, 9.7571e-08, 1.1719e-06, 5.3952e-07, 4.0020e-06, 4.0875e-06,
          6.5256e-07, 8.9042e-04, 9.9910e-01, 6.8082e-07, 6.8042e-08, 4.4974e-08,
          4.9029e-09, 3.7126e-08, 7.5763e-08, 5.7843e-08, 9.7379e-08]]))
preds, pred_classes, probs = learn.blurr_predict(inf_df.iloc[0])
preds
('14', '15')
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']

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!

learn.loss_func = nn.CrossEntropyLoss()
learn.export(fname='q_and_a_learn_export.pkl')
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.4050e-07, 1.8764e-08, 3.3632e-09, 8.3280e-09, 5.5236e-09, 1.5853e-09,
          1.4051e-07, 9.9882e-01, 1.1653e-03, 5.5529e-07, 3.1169e-07, 2.2807e-07,
          1.2281e-07, 8.8658e-06, 7.7648e-08, 7.1103e-07, 6.1086e-08, 4.1027e-09,
          4.2296e-08, 3.5451e-08, 3.0352e-08, 1.2254e-07]]))
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']

Cleanup