Views
No views yet
1import torch
2from transformers import MT5ForConditionalGeneration, MT5Tokenizer
3from huggingface_hub import hf_hub_download
4
5class ModelNSP(torch.nn.Module):
6 def __init__(self, pretrained_model, tokenizer, nsp_dim=300):
7 super(ModelNSP, self).__init__()
8 self.zero_token, self.one_token = (self.find_label_encoding(x, tokenizer).item() for x in ["0", "1"])
9 self.core_model = MT5ForConditionalGeneration.from_pretrained(pretrained_model)
10 self.nsp_head = torch.nn.Sequential(torch.nn.Linear(self.core_model.config.hidden_size, nsp_dim),
11 torch.nn.Linear(nsp_dim, nsp_dim), torch.nn.Linear(nsp_dim, 2))
12
13 def forward(self, input_ids, attention_mask=None):
14 outputs = self.core_model.generate(input_ids=input_ids, attention_mask=attention_mask, max_length=3,
15 output_scores=True, return_dict_in_generate=True)
16 logits = [torch.Tensor([score[self.zero_token], score[self.one_token]]) for score in outputs.scores[1]]
17 return torch.stack(logits).softmax(dim=-1)
18
19 @staticmethod
20 def find_label_encoding(input_str, tokenizer):
21 encoded_str = tokenizer.encode(input_str, add_special_tokens=False, return_tensors="pt")
22 return (torch.index_select(encoded_str, 1, torch.tensor([1])) if encoded_str.size(dim=1) == 2 else encoded_str)
23
24tokenizer = MT5Tokenizer.from_pretrained("tolga-ozturk/mT5-base-nsp")
25model = torch.nn.DataParallel(ModelNSP("google/mt5-base", tokenizer).eval())
26model.load_state_dict(torch.load(hf_hub_download(repo_id="tolga-ozturk/mT5-base-nsp", filename="model_weights.bin")))1batch_texts = [("In Italy, pizza is presented unsliced.", "The sky is blue."),
2 ("In Italy, pizza is presented unsliced.", "However, it is served sliced in Turkey.")]
3encoded_dict = tokenizer.batch_encode_plus(batch_text_or_text_pairs=batch_texts, truncation="longest_first", padding=True, return_tensors="pt", return_attention_mask=True, max_length=256)
4print(torch.argmax(model(encoded_dict.input_ids, attention_mask=encoded_dict.attention_mask), dim=-1))
1@misc{title={How Different Is Stereotypical Bias Across Languages?},
2 author={Ibrahim Tolga Öztürk and Rostislav Nedelchev and Christian Heumann and Esteban Garces Arias and Marius Roger and Bernd Bischl and Matthias Aßenmacher},
3 year={2023},
4 eprint={2307.07331},
5 archivePrefix={arXiv},
6 primaryClass={cs.CL}
7}