aurora-code / aurora_train /tokenizer_ext.py
AdminHugging's picture
Aurora2-400M: код дообучения, конфиги, бенчмарки
44dc92f verified
Raw History Blame
9.73 kB
"""Расширение словаря под русский язык.
Проблема: в исходном словаре (16 384 токена) НЕТ ни одного кириллического
токена. Русский текст кодируется побайтово: ~0.8 символа на токен,
8–10 токенов на слово — и медленно, и бьёт по качеству.
Решение: добавить в словарь кириллические буквы и частые русские слова
(формы с ведущим пробелом и без). Дальше модель дообучается, и новые
эмбеддинги учатся вместе с остальными весами.
Модуль намеренно не тянет torch/transformers — только `tokenizers`,
чтобы его можно было проверять отдельно от обучения.
"""
from __future__ import annotations
import json
import os
import re
import shutil
from collections import Counter
from typing import Iterable, Iterator
from .config import paths
RU_LOWER = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
WORD_RE = re.compile(r"[А-Яа-яЁё]+")
# ------------------------------------------------------------------- сэмпл ---
def _iter_texts(cfg: dict, token: str | None, max_chars: int) -> Iterator[str]:
"""Поток текста для обучения токенизатора."""
corpus_file = cfg["tokenizer"].get("corpus_file")
got = 0
if corpus_file:
with open(corpus_file, encoding="utf-8", errors="ignore") as fh:
for line in fh:
if not line.strip():
continue
yield line
got += len(line)
if got >= max_chars:
return
return
from . import data as data_mod
name = cfg["tokenizer"].get("corpus") or "ru_wiki"
stream = data_mod.load_stream(name, token)
spec = data_mod.SOURCES.get(name, {})
for ex in stream:
text = data_mod.format_doc(name, ex, spec)
if not text:
continue
yield text
got += len(text)
if got >= max_chars:
return
# --------------------------------------------------------------- измерение ---
def chars_per_token(backend, texts: Iterable[str]) -> tuple[float, int, int]:
chars = 0
tokens = 0
for text in texts:
chars += len(text)
tokens += len(backend.encode(text).ids)
return chars / max(tokens, 1), chars, tokens
# -------------------------------------------------------------- расширение ---
def extend_tokenizer(base_dir: str, out_dir: str, texts: list[str], n_new: int,
min_word_freq: int = 40, min_word_len: int = 3,
word_share: float = 0.6, held_frac: float = 0.1) -> dict:
"""Добавить кириллицу в словарь.
Состав нового блока: буквы -> частые слова (форма с пробелом) -> частые
подстроки 3..7 символов. Замеры на 650 КБ русского текста дали
0.81 -> 1.92 симв./токен (2.4x меньше токенов); на корпусе в 20M символов
покрытие слов выше, ожидаемо 2.3-2.6.
"""
from tokenizers import Tokenizer
backend = Tokenizer.from_file(os.path.join(base_dir, "tokenizer.json"))
old_vocab = backend.get_vocab_size(with_added_tokens=True)
split = max(1, int(len(texts) * (1.0 - held_frac)))
train_texts, held = texts[:split], texts[split:] or texts[:split]
before, chars, toks_before = chars_per_token(backend, held)
print(f"[tok] ДО: {before:.2f} симв./токен ({toks_before} токенов на {chars} симв.)")
freq: Counter[str] = Counter()
for text in train_texts:
freq.update(WORD_RE.findall(text.lower()))
vocab = set(backend.get_vocab().keys())
new_tokens: list[str] = []
chosen: set[str] = set()
def push(form: str) -> None:
if len(new_tokens) >= n_new or not form.strip():
return
if form in vocab or form in chosen:
return
chosen.add(form)
new_tokens.append(form)
# 1) буквы: сейчас каждая кириллическая буква — это ~2 байтовых токена
for ch in RU_LOWER:
push(ch)
push(ch.upper())
# 2) слова: выгода = частота * (текущая стоимость в токенах - 1)
cands = [(w, c) for w, c in freq.most_common(300_000)
if c >= min_word_freq and len(w) >= min_word_len]
scored: list[tuple[float, str, int]] = []
for word, count in cands:
cost = len(backend.encode(" " + word).ids)
gain = (cost - 1) * count
if gain > 0:
scored.append((gain, word, count))
scored.sort(reverse=True)
print(f"[tok] слов-кандидатов: {len(scored)} (уникальных слов {len(freq)})")
word_budget = int(n_new * word_share)
words_added = 0
for _gain, word, _count in scored:
if len(new_tokens) >= word_budget:
break
push(" " + word) # форма после пробела — самый частый случай
words_added += 1
# 3) подстроки: закрывают падежи/склонения, которых нет в списке слов
sub: Counter[str] = Counter()
for word, count in cands[:60_000]:
for k in range(3, 8):
for i in range(len(word) - k + 1):
sub[word[i:i + k]] += count
subs_added = 0
for piece, _count in sub.most_common(80_000):
if len(new_tokens) >= n_new:
break
before_len = len(new_tokens)
push(piece)
subs_added += len(new_tokens) - before_len
print(f"[tok] добавлено: слов {words_added}, подстрок {subs_added}, "
f"всего {len(new_tokens)}")
os.makedirs(out_dir, exist_ok=True)
for name in os.listdir(base_dir):
src = os.path.join(base_dir, name)
if os.path.isdir(src) or name in ("tokenizer.json", "config.json"):
continue
shutil.copy2(src, os.path.join(out_dir, name))
backend.add_tokens(new_tokens)
backend.save(os.path.join(out_dir, "tokenizer.json"))
config_path = os.path.join(base_dir, "config.json")
new_vocab = backend.get_vocab_size(with_added_tokens=True)
if os.path.exists(config_path):
with open(config_path, encoding="utf-8") as fh:
config = json.load(fh)
config["vocab_size"] = new_vocab
with open(os.path.join(out_dir, "config.json"), "w", encoding="utf-8") as fh:
json.dump(config, fh, ensure_ascii=False, indent=2)
reloaded = Tokenizer.from_file(os.path.join(out_dir, "tokenizer.json"))
after, chars, toks_after = chars_per_token(reloaded, held)
saved = 1.0 - toks_after / max(toks_before, 1)
print(f"[tok] ПОСЛЕ: {after:.2f} симв./токен ({toks_after} токенов на {chars} симв.)")
print(f"[tok] словарь {old_vocab} → {new_vocab}; токенов на русском меньше "
f"на {100*saved:.0f}% (быстрее в {after/before:.2f}x)")
meta = {
"base_vocab": old_vocab,
"new_vocab": new_vocab,
"added_tokens": len(new_tokens),
"words_added": words_added,
"substrings_added": subs_added,
"chars_per_token_before": round(before, 3),
"chars_per_token_after": round(after, 3),
"token_reduction": round(saved, 3),
"held_chars": chars,
}
with open(os.path.join(out_dir, "extend_meta.json"), "w", encoding="utf-8") as fh:
json.dump(meta, fh, ensure_ascii=False, indent=2)
return meta
def build(cfg: dict, token: str | None = None) -> dict:
"""Собрать сэмпл русского текста и расширить словарь."""
from .model import prepare_work_dir
p = paths(cfg)
work = prepare_work_dir(cfg, token)
tcfg = cfg["tokenizer"]
max_chars = int(tcfg["sample_chars"])
print(f"[tok] сэмпл до {max_chars/1e6:.0f}M символов "
f"({tcfg.get('corpus_file') or tcfg.get('corpus')})")
texts: list[str] = []
got = 0
for text in _iter_texts(cfg, token, max_chars):
texts.append(text)
got += len(text)
if got >= max_chars:
break
if not texts:
raise SystemExit("[tok] не удалось собрать текст для обучения токенизатора")
print(f"[tok] сэмпл: {len(texts)} документов, {got/1e6:.1f}M символов")
return extend_tokenizer(
work, p["model_ext"], texts,
n_new=int(tcfg["new_tokens"]),
min_word_freq=int(tcfg["min_word_freq"]),
min_word_len=int(tcfg["min_word_len"]),
word_share=float(tcfg.get("word_share", 0.6)),
)
def report(tok_dir: str, samples: dict[str, str]) -> None:
from tokenizers import Tokenizer
backend = Tokenizer.from_file(os.path.join(tok_dir, "tokenizer.json"))
print(f"словарь: {backend.get_vocab_size(with_added_tokens=True)}")
for name, text in samples.items():
ids = backend.encode(text).ids
words = max(len(text.split()), 1)
print(f" {name:6s} {len(ids):4d} ток. {len(ids)/words:5.2f} ток./слово "
f"{len(text)/max(len(ids),1):4.2f} симв./ток.")