okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-139-prs' into f-139-rel3ed9dafa1

main
6.6 KiB146 linesraw
1"""The draft head's token subset (rt/draft_vocab.bin): the vocabulary rows the MTP draft layer may propose.
2
3The engine reads rt/draft_vocab.bin (int32 token ids) when the draft layer binds and computes the draft logits over
4those rows only: a smaller head is faster and takes less VRAM, but a token outside the subset can never be drafted.
5The shipped subset was built from English and code and had 27 of the vocabulary's 55,328 Han tokens, so an answer in
6Chinese drafted almost nothing (#137).  This adds whole scripts to a subset:
7
8    python tools/draft_vocab.py --gguf <model>-00001-of-0000N.gguf --base data/draft_vocab.bin --add cjk \
9        --out data/draft_vocab.bin
10
11--add takes han, kana, hangul, cjk_punct, cjk (those four) or cyrillic.  The base ids keep their order; the added ones follow in
12id order.  --stats prints what a subset holds.
13
14A language written in a script the base already holds (French, Spanish, German... in Latin letters) needs specific
15words and word pieces, not a whole script.  --corpus adds the tokens of a text corpus in that language: the most
16frequent ones that together cover --coverage (default 0.99) of the corpus's token occurrences (#597):
17
18    python tools/draft_vocab.py --gguf <model>-00001-of-0000N.gguf --base data/draft_vocab_en.bin \
19        --corpus fr1.txt fr2.txt ... --coverage 0.99 --out data/draft_vocab_fr.bin
20
21It prints the share of the corpus's occurrences outside the base and outside the new subset.  --add and --corpus
22can be combined.
23"""
24from __future__ import annotations
25
26import argparse
27import sys
28from array import array
29from collections import Counter
30from pathlib import Path
31
32sys.path.insert(0, str(Path(__file__).resolve().parent))
33import strata_tokenizer as ST  # noqa: E402
34
35SCRIPTS = {
36    "han": [(0x3400, 0x4DBF), (0x4E00, 0x9FFF), (0xF900, 0xFAFF), (0x20000, 0x2FA1F)],
37    "kana": [(0x3040, 0x30FF), (0x31F0, 0x31FF), (0xFF66, 0xFF9F)],
38    "hangul": [(0x1100, 0x11FF), (0x3130, 0x318F), (0xAC00, 0xD7AF)],
39    "cjk_punct": [(0x3000, 0x303F), (0xFF00, 0xFF65), (0xFFA0, 0xFFEF)],
40    # Ukrainian, Russian, Bulgarian, Serbian...: the shipped subset held 142 of the vocabulary's 18,580 Cyrillic tokens
41    "cyrillic": [(0x0400, 0x04FF), (0x0500, 0x052F), (0x1C80, 0x1C8F), (0x2DE0, 0x2DFF), (0xA640, 0xA69F)],
42}
43GROUPS = {"cjk": ["han", "kana", "hangul", "cjk_punct"]}
44
45
46def scripts_of(text: str) -> set[str]:
47    found = set()
48    for ch in text:
49        c = ord(ch)
50        for name, ranges in SCRIPTS.items():
51            if any(a <= c <= b for a, b in ranges):
52                found.add(name)
53    return found
54
55
56def token_text(tok, i: int) -> str | None:
57    """A token's text, or None when its bytes are not whole UTF-8 characters (a piece of one) or it is special."""
58    try:
59        return tok.token_bytes(i).decode("utf-8")
60    except (KeyError, UnicodeDecodeError, IndexError):
61        return None
62
63
64def corpus_counts(tok, paths) -> Counter:
65    """Token occurrences over the corpus files (UTF-8 text, tokenized as plain text: no special tokens)."""
66    counts: Counter = Counter()
67    for path in paths:
68        counts.update(tok.encode(Path(path).read_text(encoding="utf-8")))
69    return counts
70
71
72def covering(counts: Counter, coverage: float) -> list[int]:
73    """The most frequent ids (ties: the lower id first) that together cover `coverage` of the occurrences."""
74    total = sum(counts.values())
75    picked, covered = [], 0
76    for i, c in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])):
77        if covered >= coverage * total:
78            break
79        picked.append(i)
80        covered += c
81    return picked
82
83
84def outside(counts: Counter, ids) -> float:
85    """The share of the occurrences whose token is not in `ids`."""
86    total = sum(counts.values())
87    have = set(ids)
88    return sum(c for i, c in counts.items() if i not in have) / total if total else 0.0
89
90
91def main() -> int:
92    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
93    ap.add_argument("--gguf", required=True, help="the model's (first) GGUF file: its vocabulary")
94    ap.add_argument("--base", help="the subset to extend (int32 ids)")
95    ap.add_argument("--add", default="", help="comma list: han, kana, hangul, cjk_punct, cjk, cyrillic")
96    ap.add_argument("--corpus", nargs="+", default=[], help="UTF-8 text files in the language to add (#597)")
97    ap.add_argument("--coverage", type=float, default=0.99,
98                    help="with --corpus: the share of its token occurrences the added tokens cover (default 0.99)")
99    ap.add_argument("--out", help="where to write the new subset")
100    ap.add_argument("--stats", action="store_true", help="print what the base (and the new) subset holds")
101    a = ap.parse_args()
102
103    tok = ST.Tokenizer.from_gguf(a.gguf)
104    n = len(tok.tokens)
105    kinds = [scripts_of(t) if (t := token_text(tok, i)) is not None else set() for i in range(n)]
106    base = list(array("i", Path(a.base).read_bytes())) if a.base else []
107    if any(i < 0 or i >= n for i in base):
108        sys.exit(f"{a.base} has ids outside the vocabulary ({n})")
109
110    want = set()
111    for x in filter(None, (s.strip() for s in a.add.split(","))):
112        names = GROUPS.get(x, [x])
113        if any(nm not in SCRIPTS for nm in names):
114            sys.exit(f"--add {x}: expected one of {', '.join([*SCRIPTS, *GROUPS])}")
115        want.update(names)
116    if not 0 < a.coverage <= 1:
117        sys.exit("--coverage: expected a share in (0, 1]")
118    counts = corpus_counts(tok, a.corpus) if a.corpus else Counter()
119    from_corpus = set(covering(counts, a.coverage)) if counts else set()
120    have = set(base)
121    added = [i for i in range(n) if i not in have and (kinds[i] & want or i in from_corpus)]
122    ids = base + added
123
124    def stats(label, sel):
125        counts = {nm: sum(1 for i in sel if nm in kinds[i]) for nm in SCRIPTS}
126        full = {nm: sum(1 for k in kinds if nm in k) for nm in SCRIPTS}
127        print(f"{label}: {len(sel)} ids; " + ", ".join(f"{nm} {counts[nm]}/{full[nm]}" for nm in SCRIPTS))
128
129    if a.stats or not a.out:
130        if base:
131            stats("base", base)
132        if added:
133            stats("new", ids)
134    if counts:
135        print(f"corpus: {sum(counts.values())} token occurrences, {len(counts)} distinct; "
136              f"{len(from_corpus)} tokens cover {a.coverage:g}, {len(from_corpus - have)} of them not in the base")
137        print(f"corpus occurrences outside the base: {outside(counts, base):.2%}, outside the new subset: "
138              f"{outside(counts, ids):.2%}")
139    if a.out:
140        Path(a.out).write_bytes(array("i", ids).tobytes())
141        print(f"wrote {a.out}: {len(ids)} ids ({len(added)} added)")
142    return 0
143
144
145if __name__ == "__main__":
146    sys.exit(main())