File size: 6,996 Bytes
ee15e43
 
c2220f4
 
ee15e43
 
 
 
 
 
 
 
 
 
c2220f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee15e43
 
 
 
 
 
 
 
 
 
 
c2220f4
ee15e43
c2220f4
ee15e43
 
 
 
 
 
 
 
 
 
 
 
 
c2220f4
ee15e43
 
 
 
 
c2220f4
ee15e43
 
 
 
 
c2220f4
ee15e43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
"""Обучение токенизатора PPAI с нуля: BPE 24576 на русском + английском + Python.

Словарь обучается с нуля под конкретный набор языков — так чище,
нет мусорных токенов от других моделей, и баланс ru/en/code выбираем сами.

Запускается как CPU-ядро Kaggle: GPU-квоту не тратит.
"""
from __future__ import annotations

import json
import os
import sys

SPECIALS = ["<|pad|>", "<|bos|>", "<|eos|>"]
# --- минимальный реестр источников (без внешних зависимостей) ---
SOURCES = {
    "ru_wiki": dict(hf="wikimedia/wikipedia", config="20231101.ru", split="train", cols=["text"]),
    "ru_web": dict(hf="HuggingFaceFW/fineweb-2", config="rus_Cyrl", split="train", cols=["text"]),
    "ru_c4": dict(hf="allenai/c4", config="ru", split="train", cols=["text"]),
    "en_web": dict(hf="HuggingFaceFW/fineweb-edu", config="sample-10BT", split="train", cols=["text"]),
    "code_python": dict(hf="codeparrot/codeparrot-clean", split="train", cols=["content"]),
}


def load_stream(name: str, token: str | None = None):
    from datasets import load_dataset

    spec = SOURCES[name]
    kw = dict(split=spec.get("split", "train"), streaming=True)
    if token:
        kw["token"] = token
    if spec.get("config"):
        kw["name"] = spec["config"]
    return load_dataset(spec["hf"], **kw)


def format_doc(name: str, ex: dict, spec: dict) -> str | None:
    for col in spec.get("cols", []):
        v = ex.get(col)
        if isinstance(v, str) and v.strip():
            return v
    return None

OUT_DIR = os.environ.get("PPAI_TOK_OUT", "/kaggle/working/ppai_tok")
REPO = os.environ.get("PPAI_TOK_REPO", "AdminHugging/PP-Hydrogen")

# доли источников для сэмпла (ру / англ / python)
SAMPLE = {"ru_wiki": 0.25, "ru_web": 0.25, "en_web": 0.25, "code_python": 0.25}
TOTAL_CHARS = 40_000_000
VOCAB = int(os.environ.get("PPAI_VOCAB", "24576"))


def find_pkg() -> str:
    for root, _dirs, files in os.walk("/kaggle/input"):
        if "train_tokenizer.py" in files:
            return root
    raise SystemExit("нет каталога ppai в /kaggle/input")


def find_token() -> str:
    for root, _dirs, files in os.walk("/kaggle/input"):
        if "hf_token.txt" in files:
            return open(os.path.join(root, "hf_token.txt"), encoding="utf-8").read().strip()
    return None


def collect_texts(pkg: str, token: str | None):

    per_source = {k: int(TOTAL_CHARS * v) for k, v in SAMPLE.items()}
    for name, budget in per_source.items():
        spec = SOURCES.get(name)
        if spec is None:
            print(f"[tok] нет источника {name}, пропуск")
            continue
        got = 0
        try:
            stream = load_stream(name, token)
        except Exception as exc:  # noqa: BLE001
            print(f"[tok] {name}: недоступен — {str(exc).splitlines()[0][:100]}")
            continue
        print(f"[tok] {name}: цель {budget/1e6:.1f}M символов", flush=True)
        for ex in stream:
            text = format_doc(name, ex, spec)
            if not text or len(text) < 200:
                continue
            yield text
            got += len(text)
            if got >= budget:
                break
        print(f"[tok] {name}: собрано {got/1e6:.1f}M символов", flush=True)


def main() -> None:
    import subprocess
    subprocess.run('pip install -q -U "tokenizers>=0.19" datasets transformers', shell=True)

    from tokenizers import Tokenizer, decoders, models, pre_tokenizers, processors, trainers

    pkg = find_pkg()
    token = find_token()
    os.makedirs(OUT_DIR, exist_ok=True)

    texts = list(collect_texts(pkg, token))
    total = sum(len(t) for t in texts)
    print(f"[tok] всего {len(texts)} документов, {total/1e6:.1f}M символов", flush=True)
    split = int(len(texts) * 0.9)
    train_texts, held = texts[:split], texts[split:]

    backend = Tokenizer(models.BPE())
    backend.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
    backend.decoder = decoders.ByteLevel()
    trainer = trainers.BpeTrainer(
        vocab_size=VOCAB,
        special_tokens=SPECIALS,
        initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
        show_progress=True,
    )
    print("[tok] учу BPE ...", flush=True)
    backend.train_from_iterator(train_texts, trainer=trainer)

    bos, eos, pad = SPECIALS[1], SPECIALS[2], SPECIALS[0]
    backend.post_processor = processors.TemplateProcessing(
        single=f"{bos} $A {eos}", special_tokens=[(bos, backend.token_to_id(bos)), (eos, backend.token_to_id(eos))]
    )

    def cpt(name, sample_texts):
        c = sum(len(t) for t in sample_texts)
        n = sum(len(backend.encode(t).ids) for t in sample_texts)
        return c / max(n, 1)

    samples = {
        "ru": [t for t in held if any("\u0400" <= ch <= "\u04FF" for ch in t[:200])][:200],
        "en": [t for t in held if all(ord(ch) < 128 for ch in t[:200])][:200],
        "py": [t for t in held if "def " in t[:400] or "import " in t[:400]][:200],
    }
    meta = {"vocab_size": backend.get_vocab_size(), "special_tokens": SPECIALS,
            "sample_chars": total, "chars_per_token": {}}
    for k, v in samples.items():
        if v:
            meta["chars_per_token"][k] = round(cpt(k, v), 2)
            print(f"[tok] {k}: {meta['chars_per_token'][k]} симв./токен", flush=True)

    backend.save(os.path.join(OUT_DIR, "tokenizer.json"))
    tok_cfg = {
        "tokenizer_class": "PreTrainedTokenizerFast",
        "bos_token": bos, "eos_token": eos, "pad_token": pad,
        "model_max_length": 1024, "clean_up_tokenization_spaces": False,
    }
    with open(os.path.join(OUT_DIR, "tokenizer_config.json"), "w", encoding="utf-8") as fh:
        json.dump(tok_cfg, fh, ensure_ascii=False, indent=2)
    with open(os.path.join(OUT_DIR, "special_tokens_map.json"), "w", encoding="utf-8") as fh:
        json.dump({"bos_token": bos, "eos_token": eos, "pad_token": pad}, fh, ensure_ascii=False, indent=2)
    with open(os.path.join(OUT_DIR, "meta.json"), "w", encoding="utf-8") as fh:
        json.dump(meta, fh, ensure_ascii=False, indent=2)
    print("[tok] сохранено в", OUT_DIR)

    if token:
        from huggingface_hub import HfApi
        api = HfApi(token=token)
        api.create_repo(REPO, repo_type="model", private=True, exist_ok=True)
        for name in ("tokenizer.json", "tokenizer_config.json", "special_tokens_map.json", "meta.json"):
            api.upload_file(path_or_fileobj=os.path.join(OUT_DIR, name),
                            path_in_repo=f"tokenizer/{name}", repo_id=REPO)
        print(f"[tok] залито в {REPO}/tokenizer/")
    print(json.dumps(meta, ensure_ascii=False))


if __name__ == "__main__":
    main()