HawkLabofficial commited on
Commit
da527f7
·
verified ·
1 Parent(s): 94aec8f

Upload tokenizer_module.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. tokenizer_module.py +54 -0
tokenizer_module.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """BPE tokenizer training and loading."""
2
+
3
+ import os
4
+ from tokenizers import Tokenizer, models, pre_tokenizers, trainers
5
+
6
+ import config
7
+
8
+
9
+ def train_tokenizer(text_path: str, vocab_size: int = None) -> Tokenizer:
10
+ """Train a BPE tokenizer from a text file using whitespace tokenization."""
11
+ if vocab_size is None:
12
+ vocab_size = config.VOCAB_SIZE
13
+
14
+ tokenizer = Tokenizer(models.BPE())
15
+ tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()
16
+
17
+ trainer = trainers.BpeTrainer(
18
+ vocab_size=vocab_size,
19
+ special_tokens=["[PAD]", "[BOS]", "[EOS]", "[UNK]", "[MASK]"],
20
+ min_frequency=2,
21
+ )
22
+
23
+ # Stream lines from file to save memory
24
+ def line_iterator():
25
+ with open(text_path, "r", encoding="utf-8") as f:
26
+ for line in f:
27
+ yield line
28
+
29
+ tokenizer.train_from_iterator(line_iterator(), trainer=trainer)
30
+
31
+ # NO post-processor — we add BOS/EOS manually in dataset/generate
32
+ tokenizer.enable_padding(length=config.MAX_SEQ_LEN, pad_id=tokenizer.token_to_id("[PAD]"))
33
+ tokenizer.enable_truncation(max_length=config.MAX_SEQ_LEN)
34
+
35
+ os.makedirs(config.DATA_DIR, exist_ok=True)
36
+ tokenizer.save(config.TOKENIZER_PATH)
37
+ print(f"Tokenizer saved: {config.TOKENIZER_PATH} | vocab={tokenizer.get_vocab_size()}")
38
+ return tokenizer
39
+
40
+
41
+ def load_tokenizer() -> Tokenizer:
42
+ if not os.path.exists(config.TOKENIZER_PATH):
43
+ raise FileNotFoundError(f"Tokenizer not found at {config.TOKENIZER_PATH}")
44
+ return Tokenizer.from_file(config.TOKENIZER_PATH)
45
+
46
+
47
+ if __name__ == "__main__":
48
+ tok = train_tokenizer(config.DATA_TEXT_PATH)
49
+ tok.no_padding()
50
+ tok.no_truncation()
51
+ enc = tok.encode("Привет! Как дела?")
52
+ print(f"Tokens: {enc.tokens}")
53
+ print(f"IDs: {enc.ids}")
54
+ print(f"Decoded: {tok.decode(enc.ids)}")