Upload 3 files
Browse files- custom_tokenizer.py +11 -0
- pipeline.py +76 -0
- requirements.txt +1 -0
custom_tokenizer.py
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PhobertTokenizer
|
2 |
+
from pyvi import ViTokenizer
|
3 |
+
|
4 |
+
|
5 |
+
class CustomPhobertTokenizer(PhobertTokenizer):
|
6 |
+
def rdr_segment(self, text):
|
7 |
+
return ViTokenizer.tokenize(text)
|
8 |
+
|
9 |
+
def _tokenize(self, text):
|
10 |
+
segmented_text = self.rdr_segment(text)
|
11 |
+
return super()._tokenize(segmented_text)
|
pipeline.py
ADDED
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Union
|
2 |
+
import torch
|
3 |
+
from transformers import AutoModel
|
4 |
+
from custom_tokenizer import CustomPhobertTokenizer
|
5 |
+
|
6 |
+
|
7 |
+
def mean_pooling(model_output, attention_mask):
|
8 |
+
token_embeddings = model_output[
|
9 |
+
0
|
10 |
+
] # First element of model_output contains all token embeddings
|
11 |
+
input_mask_expanded = (
|
12 |
+
attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
13 |
+
)
|
14 |
+
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
|
15 |
+
input_mask_expanded.sum(1), min=1e-9
|
16 |
+
)
|
17 |
+
|
18 |
+
|
19 |
+
class PreTrainedPipeline:
|
20 |
+
def __init__(self, path="."):
|
21 |
+
self.model = AutoModel.from_pretrained(path)
|
22 |
+
self.tokenizer = CustomPhobertTokenizer.from_pretrained(path)
|
23 |
+
|
24 |
+
def __call__(self, inputs: Dict[str, Union[str, List[str]]]) -> List[float]:
|
25 |
+
"""
|
26 |
+
Args:
|
27 |
+
inputs (Dict[str, Union[str, List[str]]]):
|
28 |
+
a dictionary containing a query sentence and a list of key sentences
|
29 |
+
"""
|
30 |
+
|
31 |
+
# Combine the query sentence and key sentences into one list
|
32 |
+
sentences = [inputs["source_sentence"]] + inputs["sentences"]
|
33 |
+
|
34 |
+
# Tokenize sentences
|
35 |
+
encoded_input = self.tokenizer(
|
36 |
+
sentences, padding=True, truncation=True, return_tensors="pt"
|
37 |
+
)
|
38 |
+
|
39 |
+
# Compute token embeddings
|
40 |
+
with torch.no_grad():
|
41 |
+
model_output = self.model(**encoded_input)
|
42 |
+
|
43 |
+
# Perform pooling to get sentence embeddings
|
44 |
+
sentence_embeddings = mean_pooling(
|
45 |
+
model_output, encoded_input["attention_mask"]
|
46 |
+
)
|
47 |
+
|
48 |
+
# Separate the query embedding from the key embeddings
|
49 |
+
query_embedding = sentence_embeddings[0]
|
50 |
+
key_embeddings = sentence_embeddings[1:]
|
51 |
+
|
52 |
+
# Compute cosine similarities (or any other comparison method you prefer)
|
53 |
+
cosine_similarities = torch.nn.functional.cosine_similarity(
|
54 |
+
query_embedding.unsqueeze(0), key_embeddings
|
55 |
+
)
|
56 |
+
|
57 |
+
# Convert the tensor of cosine similarities to a list of floats
|
58 |
+
scores = cosine_similarities.tolist()
|
59 |
+
|
60 |
+
return scores
|
61 |
+
|
62 |
+
|
63 |
+
if __name__ == "__main__":
|
64 |
+
inputs = {
|
65 |
+
"source_sentence": "Anh ấy đang là sinh viên năm cuối",
|
66 |
+
"sentences": [
|
67 |
+
"Anh ấy học tại Đại học Bách khoa Hà Nội, chuyên ngành Khoa học máy tính",
|
68 |
+
"Anh ấy đang làm việc tại nhà máy sản xuất linh kiện điện tử",
|
69 |
+
"Anh ấy chuẩn bị đi du học nước ngoài",
|
70 |
+
"Anh ấy sắp mở cửa hàng bán mỹ phẩm",
|
71 |
+
"Nhà anh ấy có rất nhiều cây cảnh",
|
72 |
+
],
|
73 |
+
}
|
74 |
+
|
75 |
+
pipeline = PreTrainedPipeline()
|
76 |
+
res = pipeline(inputs)
|
requirements.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
pyvi>=0.1.1
|