Views
No views yet
1from transformers import MT5ForConditionalGeneration, MT5Tokenizer
2import torch
3
4model_path = 'adenhaus/mt5-small-stata'
5tokenizer = MT5Tokenizer.from_pretrained(model_path)
6model = MT5ForConditionalGeneration.from_pretrained(model_path)
7unused_token = "<extra_id_1>"
8
9class RegressionLogitsProcessor(torch.nn.Module):
10 def __init__(self, extra_token_id):
11 super().__init__()
12 self.extra_token_id = extra_token_id
13
14 def __call__(self, input_ids, scores):
15 extra_token_logit = scores[:, :, self.extra_token_id]
16 return extra_token_logit
17
18def preprocess_inference_input(input_text):
19 input_encoded = tokenizer(input_text, return_tensors='pt')
20 return input_encoded
21
22def sigmoid(x):
23 return 1 / (1 + torch.exp(-x))
24
25def do_regression(input_str):
26 input_data = preprocess_inference_input(input_str)
27
28 logits_processor = RegressionLogitsProcessor(tokenizer.get_vocab()[unused_token])
29
30 output_sequences = model.generate(
31 **input_data,
32 max_length=2, # Generate just the regression token
33 do_sample=False, # Important: Disable sampling for deterministic output
34 return_dict_in_generate=True, # Get the scores directly
35 output_scores=True
36 )
37
38 # Extract the logit
39 unused_token_id = tokenizer.get_vocab()[unused_token]
40 regression_logit = output_sequences.scores[0][0][unused_token_id]
41 regression_score = sigmoid(regression_logit).item()
42 return regression_score
43
44source_table = "Vaccination Coverage by Province | Percent of children age 12-23 months who received all basic vaccinations | (Angola, 31) (Cabinda, 38) (Zaire, 38) (Uige, 15) (Bengo, 24) (Cuanza Norte, 30) (Luanda, 50) (Malanje, 38) (Lunda Norte, 21) (Cuanza Sul, 19) (Lunda Sul, 21) (Benguela, 26) (Huambo, 26) (Bié, 10) (Moxico, 10) (Namibe, 30) (Huíla, 23) (Cunene, 40) (Cuando Cubango, 8"
45output = "Three in ten children age 12-23 months received all basic vaccinations—one dose each of BCG and measles and three doses each of DPT-containing vaccine and polio."
46
47print(do_regression(source_table + " [output] " + output))