tools/draft_vocab.py: the draft head's token subset, with whole scripts added (#137); setup replaces an older shipped subset at setup and at start, a hand-made one is kept

This commit is contained in:
Niko1221 committed 2026-09-29 22:26:45 +02:00
1 parent d92c2a3034
commit 717971d33b
2 files changed
+115 -2

No files matched your search

+21 -2
View File
@@ -1422,6 +1422,8 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_
if missing:
fail(f"{cfg_path.name} refers to missing files: {missing[0]}", "run it again with --setup to repair")
cfg_path.touch() # the most recently used model
if "--mtp" in cfg["args"][:-1]:
refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]))
cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path),
"--port", str(port or cfg.get("port", 8080))]
if cfg.get("backend") == "hip": # AMD: one card, numbered as HIP numbers them
@@ -1483,6 +1485,24 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_
return subprocess.call(cmd)
# the draft subsets setup copied before (sha256): replaced by the current one, a subset made by hand is kept
OLD_DRAFT_VOCABS = {"369151522226a5edaa5f12cfd1e2ae7db8f4fbdbd222f3dcf327dced9597fb25"} # to 0.1.26: 27 Han tokens
def refresh_draft_vocab(rt: Path) -> None:
"""The draft layer's token subset (data/draft_vocab.bin) in the MTP folder: copied when missing, and an older
shipped one is replaced, so an update reaches existing installs (0.1.27 added the CJK scripts, #137)."""
new, dst = ROOT / "data" / "draft_vocab.bin", rt / "draft_vocab.bin"
if not new.exists() or not rt.is_dir():
return
if dst.exists():
old = hashlib.sha256(dst.read_bytes()).hexdigest()
if old not in OLD_DRAFT_VOCABS or old == hashlib.sha256(new.read_bytes()).hexdigest():
return
ok("draft layer: the token subset now includes Chinese, Japanese and Korean")
shutil.copyfile(new, dst)
def ensure_engine_for(cards, cfg_path: Path, cfg: dict, yes: bool) -> dict:
"""The installed engine must have code for every card the model starts on: a card added later (--gpus with an
older or newer generation, #128) or a new GPU in the PC otherwise stops the start with 'no kernel image'. Such a
@@ -1930,8 +1950,7 @@ def main() -> int:
"--out", str(mtp / "mtp-q2_0.gguf")], env=env)
run([sys.executable, str(ROOT / "tools" / "mtp_rt.py"), "--gguf", str(mtp / "mtp-q2_0.gguf"), "--out", str(rt)],
env=env)
if not (rt / "draft_vocab.bin").exists():
shutil.copyfile(ROOT / "data" / "draft_vocab.bin", rt / "draft_vocab.bin")
refresh_draft_vocab(rt)
ok(f"MTP draft layer: {rt}")
# ---- 7. the start script
+94
View File
@@ -0,0 +1,94 @@
"""The draft head's token subset (rt/draft_vocab.bin): the vocabulary rows the MTP draft layer may propose.
The engine reads rt/draft_vocab.bin (int32 token ids) when the draft layer binds and computes the draft logits over
those rows only: a smaller head is faster and takes less VRAM, but a token outside the subset can never be drafted.
The shipped subset was built from English and code and had 27 of the vocabulary's 55,328 Han tokens, so an answer in
Chinese drafted almost nothing (#137). This adds whole scripts to a subset:
python tools/draft_vocab.py --gguf <model>-00001-of-0000N.gguf --base data/draft_vocab.bin --add cjk \
--out data/draft_vocab.bin
--add takes han, kana, hangul, cjk_punct, or cjk (all four). The base ids keep their order; the added ones follow in
id order. --stats prints what a subset holds.
"""
from __future__ import annotations
import argparse
import sys
from array import array
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import strata_tokenizer as ST # noqa: E402
SCRIPTS = {
"han": [(0x3400, 0x4DBF), (0x4E00, 0x9FFF), (0xF900, 0xFAFF), (0x20000, 0x2FA1F)],
"kana": [(0x3040, 0x30FF), (0x31F0, 0x31FF), (0xFF66, 0xFF9F)],
"hangul": [(0x1100, 0x11FF), (0x3130, 0x318F), (0xAC00, 0xD7AF)],
"cjk_punct": [(0x3000, 0x303F), (0xFF00, 0xFF65), (0xFFA0, 0xFFEF)],
}
GROUPS = {"cjk": ["han", "kana", "hangul", "cjk_punct"]}
def scripts_of(text: str) -> set[str]:
found = set()
for ch in text:
c = ord(ch)
for name, ranges in SCRIPTS.items():
if any(a <= c <= b for a, b in ranges):
found.add(name)
return found
def token_text(tok, i: int) -> str | None:
"""A token's text, or None when its bytes are not whole UTF-8 characters (a piece of one) or it is special."""
try:
return tok.token_bytes(i).decode("utf-8")
except (KeyError, UnicodeDecodeError, IndexError):
return None
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--gguf", required=True, help="the model's (first) GGUF file: its vocabulary")
ap.add_argument("--base", help="the subset to extend (int32 ids)")
ap.add_argument("--add", default="", help="comma list: han, kana, hangul, cjk_punct, cjk")
ap.add_argument("--out", help="where to write the new subset")
ap.add_argument("--stats", action="store_true", help="print what the base (and the new) subset holds")
a = ap.parse_args()
tok = ST.Tokenizer.from_gguf(a.gguf)
n = len(tok.tokens)
kinds = [scripts_of(t) if (t := token_text(tok, i)) is not None else set() for i in range(n)]
base = list(array("i", Path(a.base).read_bytes())) if a.base else []
if any(i < 0 or i >= n for i in base):
sys.exit(f"{a.base} has ids outside the vocabulary ({n})")
want = set()
for x in filter(None, (s.strip() for s in a.add.split(","))):
names = GROUPS.get(x, [x])
if any(nm not in SCRIPTS for nm in names):
sys.exit(f"--add {x}: expected one of {', '.join([*SCRIPTS, *GROUPS])}")
want.update(names)
have = set(base)
added = [i for i in range(n) if i not in have and kinds[i] & want]
ids = base + added
def stats(label, sel):
counts = {nm: sum(1 for i in sel if nm in kinds[i]) for nm in SCRIPTS}
full = {nm: sum(1 for k in kinds if nm in k) for nm in SCRIPTS}
print(f"{label}: {len(sel)} ids; " + ", ".join(f"{nm} {counts[nm]}/{full[nm]}" for nm in SCRIPTS))
if a.stats or not a.out:
if base:
stats("base", base)
if added:
stats("new", ids)
if a.out:
Path(a.out).write_bytes(array("i", ids).tobytes())
print(f"wrote {a.out}: {len(ids)} ids ({len(added)} added)")
return 0
if __name__ == "__main__":
sys.exit(main())