Get the prediction for single question
(model, tokenizer, context_builder, question: dict, verbose: bool = False)
| 21 | return all_dataset_pred |
| 22 | |
| 23 | def get_pred(model, tokenizer, context_builder, question: dict, verbose: bool = False): |
| 24 | ''' |
| 25 | Get the prediction for single question |
| 26 | ''' |
| 27 | options = question['options'] |
| 28 | query = question['query'] |
| 29 | |
| 30 | option_dict = {} |
| 31 | for option in options: |
| 32 | encoded = tokenizer.encode(option) |
| 33 | |
| 34 | if len(encoded) == 1: |
| 35 | option_dict[option] = encoded |
| 36 | else: |
| 37 | option_dict[option] = tokenizer._convert_token_to_id(option) |
| 38 | |
| 39 | # build context |
| 40 | raw_text, context_tokens = context_builder.make_context(model, tokenizer, query) |
| 41 | input_ids = torch.tensor([context_tokens]).to(model.device) |
| 42 | |
| 43 | if verbose: |
| 44 | logger.info('sample raw_text={}\ncontext_tokens={}\nlen of context_tokens={}'.format(raw_text, context_tokens, len(context_tokens))) |
| 45 | |
| 46 | # if len(context_tokens) > 900: |
| 47 | # return 'A' |
| 48 | |
| 49 | # feed to the model |
| 50 | output = model(input_ids) |
| 51 | logits = output.logits |
| 52 | |
| 53 | # get pred option |
| 54 | score_dict = {} |
| 55 | for option in option_dict: |
| 56 | score = logits[0][-1][option_dict[option]] |
| 57 | score_dict[option] = float(score) |
| 58 | # logger.debug('score_dict={}'.format(score_dict)) |
| 59 | |
| 60 | max_score = float('-inf') |
| 61 | best_option = None |
| 62 | for option, score in score_dict.items(): |
| 63 | if score > max_score: |
| 64 | max_score = score |
| 65 | best_option = option |
| 66 | if verbose: |
| 67 | logger.debug('score_dict={}, max_score={}, best_option={}, answer={}'.format(score_dict, max_score, best_option, question['answer'])) |
| 68 | return best_option |
| 69 |
no test coverage detected