okami.mom/strata

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

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

main
9.4 KiB176 linesraw
1#!/usr/bin/env python3
2"""Fixed-token, single-session native engine baseline. TTFT here excludes HTTP/SSE."""
3import argparse
4import hashlib
5import json
6import os
7from pathlib import Path
8import subprocess
9import sys
10import threading
11import time
12
13from single_gpu import ISOLATION, ROOT, validate_config
14from resource_sampler import ResourceSampler
15
16sys.path[:0] = [str(ROOT), str(ROOT / "tools")]
17from serve.frontend import ChatTemplate
18from serve.server import StrataEngine, child_env
19from conversation_cache_parity import load_tokenizer, state_hashes
20
21
22def save(path, data):
23    tmp = path.with_suffix(path.suffix + ".tmp")
24    tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
25    tmp.replace(path)
26
27
28def gpu_fdinfo(pid):
29    """Per-DRM-device counters; amd-smi may list one KFD process on every card."""
30    records = {}
31    for path in (Path("/proc") / str(pid) / "fdinfo").iterdir():
32        try:
33            text = path.read_text()
34            if "drm-" in text:
35                records[path.name] = text
36        except FileNotFoundError:
37            continue
38    return records
39
40
41def make_fixtures(cfg, lengths):
42    directory = Path(cfg["tokenizer"])
43    tok = load_tokenizer(directory)
44    tpl = ChatTemplate(directory / "chat_template.jinja")
45    marker = "STRATA_FIXTURE_DOCUMENT_MARKER"
46    template = tpl.render([{"role": "user", "content": "Read the following numbered records.\n" + marker
47                           + "\nSummarize the record format, then write Python code to parse and validate it. "
48                           "Explain duplicate IDs and invalid integers."}], enable_thinking=False)
49    before, after = template.split(marker)
50    prefix, suffix = (tok.encode(text, parse_special=True) for text in (before, after))
51    corpus = "\n".join(f"record {i:06d}: color={('red', 'green', 'blue')[i % 3]}, value={i * 17 % 997};"
52                       for i in range(max(lengths) // 8 + 100))
53    body = tok.encode(corpus)
54    fixtures = []
55    for length in lengths:
56        count = length - len(prefix) - len(suffix)
57        if count <= 0 or count > len(body):
58            raise ValueError("fixture length outside corpus bounds")
59        ids = prefix + body[:count] + suffix
60        fixtures.append({"name": f"records-{length}", "tokens": length, "ids": ids,
61                         "text": tok.decode(ids),
62                         "ids_sha256": hashlib.sha256(json.dumps(ids).encode()).hexdigest()})
63    return {"schema": 1, "description": "Exact native protocol token IDs; performance fixtures, not quality gates.",
64            "tokenizer": str(directory), "fixtures": fixtures}
65
66
67def main():
68    parser = argparse.ArgumentParser(description=__doc__)
69    parser.add_argument("--config", type=Path, required=True)
70    parser.add_argument("--fixtures", type=Path, required=True)
71    parser.add_argument("--make-fixtures", action="store_true")
72    parser.add_argument("--lengths", type=int, nargs="+", default=[4096, 32768, 131072])
73    parser.add_argument("--out", type=Path)
74    parser.add_argument("--max-new", type=int, default=256)
75    parser.add_argument("--repeats", type=int, default=1)
76    parser.add_argument("--shape-warmups", type=int, default=0,
77                        help="full generations per selected shape, recorded but excluded from measurement")
78    args = parser.parse_args()
79    if args.repeats < 1 or args.shape_warmups < 0 or args.max_new < 1:
80        parser.error("repeats/max-new must be positive; shape-warmups must be nonnegative")
81    cfg = json.loads(args.config.read_text())
82    validate_config(cfg)
83    if args.make_fixtures:
84        if args.fixtures.exists():
85            parser.error("fixture already exists; use it unchanged or choose a new path")
86        save(args.fixtures, make_fixtures(cfg, args.lengths))
87        return
88    if args.out is None:
89        parser.error("--out is required for measurement")
90    if any(os.environ.get(k) != v for k, v in ISOLATION.items()):
91        parser.error("launch measurements through single_gpu.py")
92    args.out.mkdir(parents=True, exist_ok=False)
93    fixtures = json.loads(args.fixtures.read_text())["fixtures"]
94    selected = [f for f in fixtures if f["tokens"] in args.lengths]
95    if {f["tokens"] for f in selected} != set(args.lengths):
96        parser.error("missing requested fixture length")
97    for fixture in selected:
98        if (len(fixture["ids"]) != fixture["tokens"] or fixture["ids_sha256"] !=
99                hashlib.sha256(json.dumps(fixture["ids"]).encode()).hexdigest()):
100            raise ValueError("fixture token count or hash changed")
101    env = child_env(cfg)
102    if any(env.get(k) != v for k, v in ISOLATION.items()):
103        raise ValueError("child environment changed GPU isolation")
104    manifest = {"config": cfg, "config_sha256": hashlib.sha256(args.config.read_bytes()).hexdigest(),
105                "fixtures_path": str(args.fixtures.resolve()),
106                "fixtures_sha256": hashlib.sha256(args.fixtures.read_bytes()).hexdigest(),
107                "binary_sha256": hashlib.sha256(Path(cfg["exe"]).read_bytes()).hexdigest(),
108                "sampling": {"temperature": 0, "top_k": 1, "top_p": 1, "min_p": 0, "seed": 42},
109                "max_new": args.max_new, "timing_scope": "native engine; excludes HTTP/SSE",
110                "warmup": {"short": 1, "per_shape": args.shape_warmups,
111                           "max_new": args.max_new, "exclude_phases": ["short_warmup", "shape_warmup"]},
112                "records": []}
113    save(args.out / "results.json", manifest)
114    start = time.perf_counter()
115    engine = StrataEngine(cfg["exe"], cfg["args"], cwd=cfg["cwd"],
116                          log=str(args.out / "engine.log"), env=env)
117    manifest.update(load_s=time.perf_counter() - start, engine_info=dict(engine.info), pid=engine.proc.pid)
118    save(args.out / "results.json", manifest)
119    resources = ResourceSampler(engine.proc.pid)
120    try:
121        proc = Path(f"/proc/{engine.proc.pid}")
122        (args.out / "process-status.txt").write_text((proc / "status").read_text())
123        save(args.out / "thread-affinity.json", {
124            path.name: {k: v.strip() for line in (path / "status").read_text().splitlines()
125                        if ":" in line for k, v in [line.split(":", 1)]
126                        if k in {"Name", "Cpus_allowed_list", "Mems_allowed_list"}}
127            for path in (proc / "task").iterdir()})
128        (args.out / "loaded-maps.txt").write_text((proc / "maps").read_text())
129        (args.out / "numastat.txt").write_text(subprocess.check_output(["numastat", "-p", str(engine.proc.pid)], text=True))
130        save(args.out / "gpu-fdinfo-ready.json", gpu_fdinfo(engine.proc.pid))
131        tok = load_tokenizer(Path(cfg["tokenizer"]))
132        tpl = ChatTemplate(Path(cfg["tokenizer"]) / "chat_template.jinja")
133        warm_ids = tok.encode(tpl.render([{"role": "user", "content": "请用一句话解释什么是质数。"}],
134                                         enable_thinking=False), parse_special=True)
135        manifest["warmup_ids"] = warm_ids
136        work = [{"name": "warmup", "ids": warm_ids, "tokens": len(warm_ids), "phase": "short_warmup"}]
137        work += [dict(f, repeat=n, phase="shape_warmup")
138                 for n in range(args.shape_warmups) for f in selected]
139        work += [dict(f, repeat=n, phase="measurement") for n in range(args.repeats) for f in selected]
140        for fixture in work:
141            begin, first, output = time.perf_counter(), None, []
142            for token in engine.generate(fixture["ids"], args.max_new, manifest["sampling"], threading.Event()):
143                if token is not None:
144                    if first is None:
145                        first = time.perf_counter()
146                    output.append(token)
147            record = {"name": fixture["name"], "repeat": fixture.get("repeat"),
148                      "phase": fixture["phase"],
149                      "start_monotonic_s": begin, "end_monotonic_s": time.perf_counter(),
150                      "input_tokens": len(fixture["ids"]), "input_ids_sha256":
151                      hashlib.sha256(json.dumps(fixture["ids"]).encode()).hexdigest(),
152                      "wall_s": time.perf_counter() - begin, "ttft_s": first - begin if first else None,
153                      "output_ids": output, "text": tok.decode(output), **engine.last}
154            manifest["records"].append(record)
155            if env.get("STRATA_STATE_HASH") is not None:
156                hashes = state_hashes((args.out / "engine.log").read_text())
157                if len(hashes) != len(manifest["records"]):
158                    save(args.out / "results.json", manifest)
159                    raise RuntimeError("requested state hash was not emitted; this engine requires --prompt-cache > 0")
160                record["state"] = hashes[-1]
161            save(args.out / "results.json", manifest)
162            save(args.out / f"gpu-fdinfo-{len(manifest['records'])}.json", gpu_fdinfo(engine.proc.pid))
163            print(json.dumps({k: v for k, v in record.items() if k not in ("text", "output_ids")}), flush=True)
164            if not output or record["finish"] not in ("stop", "length"):
165                raise RuntimeError("generation did not finish normally")
166            if record["prompt_tokens"] != len(fixture["ids"]):
167                raise RuntimeError("engine prompt length does not match fixed fixture")
168            if fixture["name"] != "warmup" and record.get("reused") != 0:
169                raise RuntimeError("fresh baseline reused prompt tokens")
170    finally:
171        save(args.out / "resources.json", resources.close())
172        engine.close()
173
174
175if __name__ == "__main__":
176    main()