Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
make_profile: --reorder so a trace can rank ahead of a complete base
Yannick Loth90d3251790f6
diff --git a/tools/make_profile.py b/tools/make_profile.pyindex 0f0238489..9916cf107 100644--- a/tools/make_profile.py+++ b/tools/make_profile.py@@ -6,9 +6,12 @@ ranks fewer pairs than a card can hold caps the cache (issue #46: a 32 GB card swrites one that ranks all 24,576.The order: the base profile's ranking (default: the shipped data/expert-profile.bin), then the pairs your routing-traces used, most frequent first, then every pair still missing, interleaved across the layers.+traces used, most frequent first, then every pair still missing, interleaved across the layers. The base is only+*appended to*, never reordered - and the shipped profile already ranks all 24,576 pairs, so with it a trace is a+no-op. `--reorder` ranks the traces first and lets the base fill the rest, which is how a workload's trace decides+the top; `--no-base` drops the base entirely.- python tools/make_profile.py [TRACE ...] [--base data/expert-profile.bin | --no-base] [--out PATH]+ python tools/make_profile.py [TRACE ...] [--base data/expert-profile.bin | --no-base] [--reorder] [--out PATH][--n-expert 256] (a pruned model: GSQ-RCO Coder keeps 256 of 512)A routing trace comes from a one-shot engine run with `--dump-routing FILE` (a prompt typical of your use; the@@ -60,39 +63,56 @@ def write_profile(path, ranked, n_expert=N_EXPERT):f.write(struct.pack("<%di" % n_expert, *table[layer]))+def rank_profile(base_pairs, trace_freq, n_expert=N_EXPERT, no_base=False, reorder=False):+ """The ranked (layer, expert) list and the counts it was built from (`base`, `trace`, `fill`).++ Default: the base's order, then the traces' pairs most frequent first, then the fill. With `reorder` (or+ `no_base`) the traces' pairs come first, so a base that already ranks every pair no longer hides them; the base+ (unless `no_base`) and then the fill follow. A base is never reordered against itself - it only ever fills."""+ ranked, seen, counts = [], set(), defaultdict(int)++ def take(pairs, key):+ for p in pairs:+ p = (int(p[0]), int(p[1]))+ if p not in seen:+ seen.add(p)+ ranked.append(p)+ counts[key] += 1++ trace_pairs = [p for p, _ in sorted(trace_freq.items(), key=lambda kv: (-kv[1], kv[0]))]+ if no_base or reorder:+ take(trace_pairs, "trace")+ if not no_base:+ take(base_pairs, "base")+ if not (no_base or reorder):+ take(trace_pairs, "trace")+ take(((layer, e) for e in range(n_expert) for layer in range(N_LAYER)), "fill")+ return ranked, counts++def main():ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])ap.add_argument("traces", nargs="*", help="routing traces from --dump-routing")ap.add_argument("--base", default=str(ROOT / "data" / "expert-profile.bin"), help="ranking to keep first")ap.add_argument("--no-base", action="store_true", help="rank by the traces only")+ ap.add_argument("--reorder", action="store_true",+ help="rank the traces' pairs before the base's (the base, then the fill, follow); needed with a "+ "base that already ranks every pair, where --base alone cannot change the order")ap.add_argument("--out", default=str(ROOT / "data" / "expert-profile.bin"))ap.add_argument("--n-expert", type=int, default=N_EXPERT, help="experts per layer (default 512)")a = ap.parse_args()- ranked, seen = [], set()-- def take(pairs):- for p in pairs:- p = (int(p[0]), int(p[1]))- if p not in seen:- seen.add(p)- ranked.append(p)-ne = a.n_expert- if not a.no_base:- take(read_profile(a.base, ne))- n_base = len(ranked)freq = defaultdict(int)for t in a.traces:for p, c in read_trace(t, ne).items():freq[p] += c- take(p for p, _ in sorted(freq.items(), key=lambda kv: (-kv[1], kv[0])))- n_trace = len(ranked) - n_base- take((layer, e) for e in range(ne) for layer in range(N_LAYER)) # the rest, across the layers+ base_pairs = [] if a.no_base else read_profile(a.base, ne)+ ranked, counts = rank_profile(base_pairs, freq, ne, no_base=a.no_base, reorder=a.reorder)write_profile(a.out, ranked, ne)assert read_profile(a.out, ne) == ranked, "the profile did not survive the round trip"- print(f"wrote {a.out}: {len(ranked)} ranked pairs ({n_base} from the base, {n_trace} from the traces, "- f"{len(ranked) - n_base - n_trace} filled in)")+ print(f"wrote {a.out}: {len(ranked)} ranked pairs ({counts['base']} from the base, {counts['trace']} from the "+ f"traces, {counts['fill']} filled in)")if __name__ == "__main__":diff --git a/tools/test_make_profile.py b/tools/test_make_profile.pynew file mode 100644index 000000000..f9c36202c--- /dev/null+++ b/tools/test_make_profile.py@@ -0,0 +1,104 @@+"""Tests for tools/make_profile.py, without a model: synthetic profiles and routing traces.++ python -m unittest tools.test_make_profile+"""+from __future__ import annotations++import struct+import sys+import tempfile+import unittest+from collections import defaultdict+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "tools"))+import make_profile as MP # noqa: E402++NE = 4 # a tiny "experts per layer"; the layer count is fixed at MP.N_LAYER+++def write_trace(path, records):+ """One record per (layer, [expert ids]); the reader skips k weights after the k ids."""+ with open(path, "wb") as f:+ for layer, experts in records:+ f.write(struct.pack("<ii", layer, len(experts)))+ f.write(struct.pack("<%di" % len(experts), *experts))+ f.write(struct.pack("<%df" % len(experts), *([1.0] * len(experts))))+++def full_base():+ """Every pair, in an order that differs from rank_profile's fill (e-major then layer)."""+ return [(layer, e) for layer in range(MP.N_LAYER) for e in range(NE)]+++class RankProfile(unittest.TestCase):+ def test_a_complete_base_hides_the_trace(self):+ # the shipped profile's situation: it already ranks every pair, so the trace cannot move anything+ base = full_base()+ freq = defaultdict(int, {(5, 1): 10, (6, 2): 7})+ ranked, counts = MP.rank_profile(base, freq, NE)+ self.assertEqual(ranked, base)+ self.assertEqual(counts["trace"], 0)+ self.assertEqual(counts["base"], MP.N_LAYER * NE)++ def test_reorder_puts_the_traces_first(self):+ base = full_base()+ freq = defaultdict(int, {(5, 1): 10, (6, 2): 7})+ ranked, counts = MP.rank_profile(base, freq, NE, reorder=True)+ self.assertEqual(ranked[:2], [(5, 1), (6, 2)])+ self.assertEqual(set(ranked), set(base)) # still every pair, once+ self.assertEqual(len(ranked), len(base))+ self.assertEqual(counts["trace"], 2)+ self.assertEqual(counts["base"], MP.N_LAYER * NE - 2) # the base fills the rest, minus the two++ def test_frequency_and_tie_break_order_the_trace(self):+ freq = defaultdict(int, {(1, 0): 1, (2, 0): 3, (3, 0): 3})+ ranked, _ = MP.rank_profile([], freq, NE, no_base=True) # (2,0)/(3,0) tie -> the smaller pair first+ self.assertEqual(ranked[:3], [(2, 0), (3, 0), (1, 0)])++ def test_default_appends_only(self):+ base = [(0, 0), (0, 1)]+ freq = defaultdict(int, {(0, 0): 5, (1, 3): 9})+ ranked, _ = MP.rank_profile(base, freq, NE)+ self.assertEqual(ranked[:3], [(0, 0), (0, 1), (1, 3)]) # base first; (0,0) already there, not moved++ def test_no_base_uses_the_traces_then_the_fill(self):+ base = [(0, 0), (0, 1)]+ freq = defaultdict(int, {(1, 3): 9, (0, 0): 5})+ ranked, counts = MP.rank_profile(base, freq, NE, no_base=True)+ self.assertEqual(ranked[:2], [(1, 3), (0, 0)])+ self.assertEqual(counts["base"], 0)+ self.assertEqual(len(ranked), MP.N_LAYER * NE)++ def test_reorder_without_traces_is_the_default(self):+ base = full_base()+ self.assertEqual(MP.rank_profile(base, defaultdict(int), NE, reorder=True)[0], base)+++class Main(unittest.TestCase):+ def run_main(self, argv):+ old, sys.argv = sys.argv, ["make_profile.py"] + argv+ try:+ MP.main()+ finally:+ sys.argv = old++ def test_end_to_end_reorder_over_a_complete_base(self):+ with tempfile.TemporaryDirectory() as d:+ base = Path(d) / "base.bin"+ out = Path(d) / "out.bin"+ trace = Path(d) / "t.bin"+ MP.write_profile(str(base), full_base(), NE)+ write_trace(str(trace), [(5, [1]), (6, [2]), (6, [2]), (6, [2])])+ self.run_main([str(trace), "--base", str(base), "--reorder", "--n-expert", str(NE), "--out", str(out)])+ ranked = MP.read_profile(str(out), NE)+ self.assertEqual(ranked[:2], [(6, 2), (5, 1)]) # most frequent first+ self.assertEqual(set(ranked), set(full_base()))+ # and without --reorder it is the base's order, untouched+ self.run_main([str(trace), "--base", str(base), "--n-expert", str(NE), "--out", str(out)])+ self.assertEqual(MP.read_profile(str(out), NE), full_base())+++if __name__ == "__main__":+ unittest.main()