okami.mom/strata

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

Niko1221Merge f-142b-serve into f-1426e1085c1d

main
3.8 KiB72 linesraw
1#!/usr/bin/env python3
2"""make_prompts.py - builds this report's prompts from Strata's own repository text, so anyone can rebuild them.
3
4One ~1,000-token warm-up and three prompts each of 4,096, 32,768 and 128,000 tokens. The text is the tag's
5docs/*.md, src/**/*.cpp, src/**/*.cu, include/**/*.hpp, serve/**/*.py and tools/**/*.py in that order (the order
6tools/needle_bench.py uses, without third_party/), each file under a "=== path ===" line. Every prompt is a different,
7non-overlapping slice of that text and starts with its own run id, so no request can reuse another one's prefix beyond
8the chat template's first tokens. Token counts are of the rendered prompt, with the model pack's tokenizer and chat
9template; the server reports the real count of each request.
10
11    git -C Strata checkout v0.1.41
12    python make_prompts.py --tree Strata --tokenizer-dir <pack>/tokenizer --out prompts.json
13
14With the v0.1.41 tree and the IQ3_S pack's tokenizer this writes a file with sha256
15d1b10bd59376564bb826b290b50f684991988ec8765af99139e3bfbe044c8895."""
16import argparse
17import hashlib
18import json
19import sys
20from pathlib import Path
21
22ap = argparse.ArgumentParser()
23ap.add_argument("--tree", required=True, help="a Strata checkout at v0.1.41")
24ap.add_argument("--tokenizer-dir", required=True, help="the model pack's tokenizer/ folder")
25ap.add_argument("--out", default="prompts.json")
26a = ap.parse_args()
27TREE, TDIR = Path(a.tree).resolve(), Path(a.tokenizer_dir)
28sys.path.insert(0, str(TREE / "tools"))
29sys.path.insert(0, str(TREE))
30import strata_tokenizer as ST   # noqa: E402
31from serve.frontend import ChatTemplate   # noqa: E402
32
33vocab = json.loads((TDIR / "vocab.json").read_text(encoding="utf-8"))
34toks = [None] * len(vocab)
35for t, i in vocab.items():
36    toks[i] = t
37tok = ST.Tokenizer(toks, (TDIR / "merges.txt").read_text(encoding="utf-8").split("\n"),
38                   json.loads((TDIR / "token_type.json").read_text()))
39tpl = ChatTemplate(TDIR / "chat_template.jinja")
40
41SOURCES = [("docs", "*.md"), ("src", "*.cpp"), ("src", "*.cu"), ("include", "*.hpp"), ("serve", "*.py"), ("tools", "*.py")]
42parts = []
43for d, pat in SOURCES:
44    for f in sorted((TREE / d).rglob(pat)):
45        parts.append(f"\n\n=== {f.relative_to(TREE).as_posix()} ===\n{f.read_text(encoding='utf-8', errors='replace')}")
46text = "".join(parts)
47PLAN = [("warmup", 1000, 1)] + [(str(n), n, 3) for n in (4096, 32768, 128000)]
48need = sum(n * r for _, n, r in PLAN)
49ids = tok.encode(text[:int(need * 3.6)])
50TASK = "\n\nTask: in one short paragraph, say what the material above is about."
51n_prompt = lambda m: len(tok.encode(tpl.render(m), parse_special=True))
52out, cursor = [], 0
53for size, target, reps in PLAN:
54    for r in range(reps):
55        nonce = hashlib.sha1(f"cb-{size}-{r}".encode()).hexdigest()[:8]
56        head = f"[Run cb-{size}-r{r}-{nonce}] Below is source code and documentation from the Strata repository (tag v0.1.41).\n\n"
57        n = target - n_prompt([{"role": "user", "content": head + TASK}])
58        for _ in range(8):            # decode/re-encode can move the count by a token or two
59            body = tok.decode(ids[cursor:cursor + n])
60            msgs = [{"role": "user", "content": head + body + TASK}]
61            got = n_prompt(msgs)
62            if abs(got - target) <= 2:
63                break
64            n += target - got
65        if cursor + n > len(ids):
66            raise SystemExit("ran out of text")
67        cursor += n
68        out.append({"size": size, "rep": r, "target": target, "prompt_tokens": got, "messages": msgs,
69                    "first_file": body.split("\n=== ", 1)[-1].split(" ===", 1)[0] if "\n=== " in body else "(mid-file)"})
70        print(size, r, got, flush=True)
71Path(a.out).write_text(json.dumps(out, ensure_ascii=False))
72print(f"wrote {a.out}: {len(out)} prompts, sha256 {hashlib.sha256(Path(a.out).read_bytes()).hexdigest()}")