Views
No views yet
use_remote_code=True is no longer necessary.<cls> token must be manually added to the beginning of the question for this model to work properly.
It uses the <cls> token to be able to make "no answer" predictions.
The t5 tokenizer does not automatically add this special token which is why it is added manually.1import torch
2from transformers import(
3 AutoModelForQuestionAnswering,
4 AutoTokenizer,
5 pipeline
6)
7model_name = "sjrhuschlee/flan-t5-base-squad2"
8
9# a) Using pipelines
10nlp = pipeline(
11 'question-answering',
12 model=model_name,
13 tokenizer=model_name,
14 # trust_remote_code=True, # Do not use if version transformers>=4.31.0
15)
16qa_input = {
17'question': f'{nlp.tokenizer.cls_token}Where do I live?', # '<cls>Where do I live?'
18'context': 'My name is Sarah and I live in London'
19}
20res = nlp(qa_input)
21# {'score': 0.980, 'start': 30, 'end': 37, 'answer': ' London'}
22
23# b) Load model & tokenizer
24model = AutoModelForQuestionAnswering.from_pretrained(
25 model_name,
26 # trust_remote_code=True # Do not use if version transformers>=4.31.0
27)
28tokenizer = AutoTokenizer.from_pretrained(model_name)
29
30question = f'{tokenizer.cls_token}Where do I live?' # '<cls>Where do I live?'
31context = 'My name is Sarah and I live in London'
32encoding = tokenizer(question, context, return_tensors="pt")
33output = model(
34 encoding["input_ids"],
35 attention_mask=encoding["attention_mask"]
36)
37
38all_tokens = tokenizer.convert_ids_to_tokens(encoding["input_ids"][0].tolist())
39answer_tokens = all_tokens[torch.argmax(output["start_logits"]):torch.argmax(output["end_logits"]) + 1]
40answer = tokenizer.decode(tokenizer.convert_tokens_to_ids(answer_tokens))
41# 'London'1# Squad v2
2{
3 "eval_HasAns_exact": 79.97638326585695,
4 "eval_HasAns_f1": 86.1444296592862,
5 "eval_HasAns_total": 5928,
6 "eval_NoAns_exact": 84.42388561816652,
7 "eval_NoAns_f1": 84.42388561816652,
8 "eval_NoAns_total": 5945,
9 "eval_best_exact": 82.2033184536343,
10 "eval_best_exact_thresh": 0.0,
11 "eval_best_f1": 85.28292588395921,
12 "eval_best_f1_thresh": 0.0,
13 "eval_exact": 82.2033184536343,
14 "eval_f1": 85.28292588395928,
15 "eval_runtime": 522.0299,
16 "eval_samples": 12001,
17 "eval_samples_per_second": 22.989,
18 "eval_steps_per_second": 0.96,
19 "eval_total": 11873
20}
21
22# Squad
23{
24 "eval_exact_match": 86.3197729422895,
25 "eval_f1": 92.94686836210295,
26 "eval_runtime": 442.1088,
27 "eval_samples": 10657,
28 "eval_samples_per_second": 24.105,
29 "eval_steps_per_second": 1.007
30}