Views
No views yet
1from transformers import MLukeTokenizer, LukeModel
2import torch
3
4
5class SentenceLukeJapanese:
6 def __init__(self, model_name_or_path, device=None):
7 self.tokenizer = MLukeTokenizer.from_pretrained(model_name_or_path)
8 self.model = LukeModel.from_pretrained(model_name_or_path)
9 self.model.eval()
10
11 if device is None:
12 device = "cuda" if torch.cuda.is_available() else "cpu"
13 self.device = torch.device(device)
14 self.model.to(device)
15
16 def _mean_pooling(self, model_output, attention_mask):
17 token_embeddings = model_output[0] #First element of model_output contains all token embeddings
18 input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
19 return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
20
21 @torch.no_grad()
22 def encode(self, sentences, batch_size=8):
23 all_embeddings = []
24 iterator = range(0, len(sentences), batch_size)
25 for batch_idx in iterator:
26 batch = sentences[batch_idx:batch_idx + batch_size]
27
28 encoded_input = self.tokenizer.batch_encode_plus(batch, padding="longest",
29 truncation=True, return_tensors="pt").to(self.device)
30 model_output = self.model(**encoded_input)
31 sentence_embeddings = self._mean_pooling(model_output, encoded_input["attention_mask"]).to('cpu')
32
33 all_embeddings.extend(sentence_embeddings)
34
35 return torch.stack(all_embeddings)
36
37
38MODEL_NAME = "sonoisa/sentence-luke-japanese-base-lite"
39model = SentenceLukeJapanese(MODEL_NAME)
40
41sentences = ["暴走したAI", "暴走した人工知能"]
42sentence_embeddings = model.encode(sentences, batch_size=8)
43
44print("Sentence embeddings:", sentence_embeddings)