File size: 3,753 Bytes
fc1b627
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"""
Tokenizer GromGPT — BPE thật (Byte-Pair Encoding), giống cách các LLM hiện đại
(GPT, LLaMA, Mistral...) tokenize dữ liệu, thay vì tách theo từ/ký tự đơn giản.

Dùng thư viện `tokenizers` của HuggingFace (Rust backend, cực nhanh) để:
  - train một BPE tokenizer từ corpus của chính GromGPT
  - lưu lại thành 1 file JSON duy nhất (tokenizer.json), tự chứa toàn bộ vocab + merges
  - encode/decode văn bản thành id token, có hỗ trợ special tokens cho hội thoại
    (Người dùng:, G/AI:, <suy_nghi>, </suy_nghi>, <tra_loi>, </tra_loi>, <unk>, <pad>)

BPE thật khác word-level ở chỗ: nó học các đơn vị sub-word phổ biến nhất từ dữ liệu
(ví dụ "ngh", "ia", "tr", "a"...) thay vì chỉ tách theo khoảng trắng/ký tự đơn,
nên vocab nhỏ hơn nhiều mà vẫn biểu diễn được từ hiếm/từ mới ghép từ subword đã biết.
"""

from tokenizers import Tokenizer as HFTokenizer
from tokenizers import decoders, normalizers, pre_tokenizers
from tokenizers.models import BPE
from tokenizers.trainers import BpeTrainer

SPECIAL_TOKENS = [
    "<pad>",
    "<unk>",
    "Người dùng:",
    "G/AI:",
    "<suy_nghi>",
    "</suy_nghi>",
    "<tra_loi>",
    "</tra_loi>",
]

DEFAULT_VOCAB_SIZE = 8000


class Tokenizer:
    """Wrapper mỏng quanh HuggingFace `tokenizers.Tokenizer` (BPE),
    giữ API tương thích với phần còn lại của GromGPT: build(), encode(), decode(), len()."""

    def __init__(self, hf_tokenizer=None):
        self._tok = hf_tokenizer
        self.unk_id = 0
        if self._tok is not None:
            unk = self._tok.token_to_id("<unk>")
            self.unk_id = unk if unk is not None else 0

    # ---------- training ----------

    def _new_tokenizer(self, vocab_size: int, min_frequency: int):
        tok = HFTokenizer(BPE(unk_token="<unk>"))
        tok.normalizer = normalizers.NFKC()
        tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
        tok.decoder = decoders.ByteLevel()
        trainer = BpeTrainer(
            vocab_size=vocab_size,
            min_frequency=min_frequency,
            special_tokens=SPECIAL_TOKENS,
            show_progress=True,
            initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
        )
        return tok, trainer

    def build(self, text: str, vocab_size: int = DEFAULT_VOCAB_SIZE, min_frequency: int = 2):
        """Train BPE từ một chuỗi corpus."""
        tok, trainer = self._new_tokenizer(vocab_size, min_frequency)
        tok.train_from_iterator([text], trainer=trainer)
        self._tok = tok
        self.unk_id = tok.token_to_id("<unk>")
        return self

    def build_from_iterator(self, iterator, vocab_size: int = DEFAULT_VOCAB_SIZE, min_frequency: int = 2):
        """Train BPE streaming, không cần nạp toàn bộ corpus vào RAM."""
        tok, trainer = self._new_tokenizer(vocab_size, min_frequency)
        tok.train_from_iterator(iterator, trainer=trainer)
        self._tok = tok
        self.unk_id = tok.token_to_id("<unk>")
        return self

    # ---------- persistence ----------

    def save(self, path):
        self._tok.save(str(path))

    @classmethod
    def load(cls, path):
        tok = HFTokenizer.from_file(str(path))
        return cls(tok)

    # ---------- encode/decode ----------

    def encode(self, text: str):
        return self._tok.encode(text).ids

    def decode(self, ids):
        ids = [int(i) for i in ids]
        return self._tok.decode(ids, skip_special_tokens=False)

    def token_to_id(self, token: str):
        return self._tok.token_to_id(token)

    def __len__(self):
        return self._tok.get_vocab_size()