okami.mom/strata

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

Gopilayer split: score every four-way placement instead of guessing ite2b32892a

main
6.2 KiB126 linesraw
1"""tools/make_profile.py - the expert-cache profile (`data/expert-profile.bin`): every (layer, expert) pair, ranked.
2
3`--expert-cache auto` fills the VRAM slots it can afford with the profile's pairs in order, so the ranking decides
4which experts start resident (the adaptive tier then swaps in what a conversation routes most).  A profile that
5ranks fewer pairs than a card can hold caps the cache (issue #46: a 32 GB card stopped at 8,000 slots); this tool
6writes one that ranks all 24,576.
7
8The order: the base profile's ranking (default: the shipped data/expert-profile.bin), then the pairs your routing
9traces used, most frequent first, then every pair still missing, interleaved across the layers.  The base is only
10*appended to*, never reordered - and the shipped profile already ranks all 24,576 pairs, so with it a trace is a
11no-op.  `--reorder` ranks the traces first and lets the base fill the rest, which is how a workload's trace decides
12the top; `--no-base` drops the base entirely.
13
14WATCH THE BASE: `take()` skips a pair it has already ranked, and the shipped base ranks all 24,576, so a plain
15`--base` run cannot be moved by any trace - the output is the base again.  `--reorder` (traces first) or
16`--no-base` is what makes a trace decide the top.  Which ordering is in use is not cosmetic: the layer-split cost
17model reads this RANKING as if it were a frequency curve, and the coverage curve in src/program/generate.cpp
18carries the measured hit rates that say how far off that goes (94.9% claimed against 69.2% measured at 5,805 pairs
19held, on the IQ3_S 4-way rig).
20
21    python tools/make_profile.py [TRACE ...] [--base data/expert-profile.bin | --no-base] [--reorder] [--out PATH]
22                                 [--n-expert 256]      (a pruned model: GSQ-RCO Coder keeps 256 of 512)
23
24A routing trace comes from a one-shot engine run with `--dump-routing FILE` (a prompt typical of your use; the
25routed experts of every layer and position are written).  Point the model config's `--expert-profile` at the result.
26"""
27import argparse
28import struct
29from collections import defaultdict
30from pathlib import Path
31
32ROOT = Path(__file__).resolve().parent.parent
33N_LAYER, N_EXPERT = 48, 512
34MAGIC, VERSION = b"STRP", 1
35
36
37def read_profile(path, n_expert=N_EXPERT):
38    blob = Path(path).read_bytes()
39    if blob[:4] != MAGIC:
40        raise SystemExit(f"{path}: not a Strata profile")
41    ver, nl, ne, slots, n = struct.unpack_from("<5I", blob, 4)
42    if (nl, ne) != (N_LAYER, n_expert):
43        raise SystemExit(f"{path}: {nl}x{ne}, not {N_LAYER}x{n_expert}")
44    return [struct.unpack_from("<HH", blob, 24 + 4 * i) for i in range(n)]
45
46
47def read_trace(path, n_expert=N_EXPERT):
48    """(layer, k, k expert ids, k weights) records, as `--dump-routing` writes them."""
49    blob = Path(path).read_bytes()
50    off, freq = 0, defaultdict(int)
51    while off + 8 <= len(blob):
52        layer, k = struct.unpack_from("<ii", blob, off)
53        off += 8
54        for e in struct.unpack_from("<%di" % k, blob, off):
55            if 0 <= layer < N_LAYER and 0 <= e < n_expert:
56                freq[(layer, e)] += 1
57        off += 8 * k                                    # the ids and the weights
58    return freq
59
60
61def write_profile(path, ranked, n_expert=N_EXPERT):
62    table = [[-1] * n_expert for _ in range(N_LAYER)]
63    for slot, (layer, e) in enumerate(ranked):
64        table[layer][e] = slot
65    with open(path, "wb") as f:
66        f.write(MAGIC + struct.pack("<5I", VERSION, N_LAYER, n_expert, len(ranked), len(ranked)))
67        for layer, e in ranked:
68            f.write(struct.pack("<HH", layer, e))
69        for layer in range(N_LAYER):
70            f.write(struct.pack("<%di" % n_expert, *table[layer]))
71
72
73def rank_profile(base_pairs, trace_freq, n_expert=N_EXPERT, no_base=False, reorder=False):
74    """The ranked (layer, expert) list and the counts it was built from (`base`, `trace`, `fill`).
75
76    Default: the base's order, then the traces' pairs most frequent first, then the fill.  With `reorder` (or
77    `no_base`) the traces' pairs come first, so a base that already ranks every pair no longer hides them; the base
78    (unless `no_base`) and then the fill follow.  A base is never reordered against itself - it only ever fills."""
79    ranked, seen, counts = [], set(), defaultdict(int)
80
81    def take(pairs, key):
82        for p in pairs:
83            p = (int(p[0]), int(p[1]))
84            if p not in seen:
85                seen.add(p)
86                ranked.append(p)
87                counts[key] += 1
88
89    trace_pairs = [p for p, _ in sorted(trace_freq.items(), key=lambda kv: (-kv[1], kv[0]))]
90    if no_base or reorder:
91        take(trace_pairs, "trace")
92    if not no_base:
93        take(base_pairs, "base")
94    if not (no_base or reorder):
95        take(trace_pairs, "trace")
96    take(((layer, e) for e in range(n_expert) for layer in range(N_LAYER)), "fill")
97    return ranked, counts
98
99
100def main():
101    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
102    ap.add_argument("traces", nargs="*", help="routing traces from --dump-routing")
103    ap.add_argument("--base", default=str(ROOT / "data" / "expert-profile.bin"), help="ranking to keep first")
104    ap.add_argument("--no-base", action="store_true", help="rank by the traces only")
105    ap.add_argument("--reorder", action="store_true",
106                    help="rank the traces' pairs before the base's (the base, then the fill, follow); needed with a "
107                         "base that already ranks every pair, where --base alone cannot change the order")
108    ap.add_argument("--out", default=str(ROOT / "data" / "expert-profile.bin"))
109    ap.add_argument("--n-expert", type=int, default=N_EXPERT, help="experts per layer (default 512)")
110    a = ap.parse_args()
111
112    ne = a.n_expert
113    freq = defaultdict(int)
114    for t in a.traces:
115        for p, c in read_trace(t, ne).items():
116            freq[p] += c
117    base_pairs = [] if a.no_base else read_profile(a.base, ne)
118    ranked, counts = rank_profile(base_pairs, freq, ne, no_base=a.no_base, reorder=a.reorder)
119    write_profile(a.out, ranked, ne)
120    assert read_profile(a.out, ne) == ranked, "the profile did not survive the round trip"
121    print(f"wrote {a.out}: {len(ranked)} ranked pairs ({counts['base']} from the base, {counts['trace']} from the "
122          f"traces, {counts['fill']} filled in)")
123
124
125if __name__ == "__main__":
126    main()