ExtraX1 commited on
Commit
8b3ec04
·
verified ·
1 Parent(s): bd5f181

Create train_tokenizer.py

Browse files
Files changed (1) hide show
  1. train_tokenizer.py +67 -0
train_tokenizer.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tokenizers import Tokenizer
2
+ from tokenizers.models import BPE
3
+ from tokenizers.trainers import BpeTrainer
4
+ from tokenizers.pre_tokenizers import ByteLevel
5
+ from tokenizers.decoders import ByteLevel as ByteLevelDecoder
6
+ from datasets import load_dataset
7
+ import os
8
+
9
+ def download_to_txt(dataset_name, config_name, split, text_field, out_file, limit):
10
+ print(f"⬇️ Скачиваем {out_file}...")
11
+ # Загружаем стримингом, но сразу пишем на диск
12
+ ds = load_dataset(dataset_name, config_name, split=split, streaming=True)
13
+
14
+ with open(out_file, "w", encoding="utf-8") as f:
15
+ for i, item in enumerate(ds):
16
+ if i >= limit: break
17
+ text = item.get(text_field, "")
18
+ if text.strip():
19
+ f.write(text + "\n")
20
+ print(f"✅ Готово: {out_file}")
21
+
22
+
23
+ download_to_txt("wikimedia/wikipedia", "20231101.en", "train", "text", "en.txt", 30000)
24
+
25
+ download_to_txt("wikimedia/wikipedia", "20231101.ru", "train", "text", "ru.txt", 20000)
26
+
27
+ download_to_txt("wikimedia/wikipedia", "20231101.zh", "train", "text", "zh.txt", 10000)
28
+
29
+ download_to_txt("codeparrot/codeparrot-clean", None, "train", "content", "code.txt", 5000)
30
+
31
+
32
+ special_tokens = [
33
+ "<unk>", "<s>", "</s>", "<pad>",
34
+ "<|im_start|>", "<|im_end|>",
35
+ "<|think|>", "<|/think|>"
36
+ ]
37
+ tokenizer = Tokenizer(BPE(unk_token="<unk>"))
38
+ tokenizer.pre_tokenizer = ByteLevel()
39
+ tokenizer.decoder = ByteLevelDecoder()
40
+ trainer = BpeTrainer(vocab_size=64000, special_tokens=special_tokens, min_frequency=2)
41
+
42
+
43
+ files = ["en.txt", "ru.txt", "zh.txt", "code.txt"]
44
+ tokenizer.train(files, trainer)
45
+
46
+
47
+ tokenizer.save("tokenizer.json")
48
+
49
+ # Удаляем временные файлы, чтобы не забивать диск Colab
50
+ for f in files:
51
+ if os.path.exists(f):
52
+ os.remove(f)
53
+ print("🧹 Временные файлы очищены.")
54
+
55
+
56
+ print("\n--- ТЕСТ ТОКЕНИЗАТОРА ---")
57
+ tok = Tokenizer.from_file("tokenizer.json")
58
+ test_texts = {
59
+ "Английский": "The quick brown fox jumps over the lazy dog.",
60
+ "Русский": "Привет, как дела? Это наш TinyCyclic.",
61
+ "Китайский": "这是一个测试,看看我们的分词器是否理解中文。",
62
+ "Код": "def hello_world(): print('Hello')",
63
+ "Спецтокены": "<|im_start|>assistant<|think|>Думаю...<|/think|>Ответ<|im_end|>"
64
+ }
65
+ for lang, text in test_texts.items():
66
+ encoded = tok.encode(text)
67
+ print(f"[{lang}] Токенов: {len(encoded.tokens)} -> {encoded.tokens}")