"""Prompt-level expert selection, from a trace (trace_experts.py): if each layer only kept the M experts the prompt used most, how many of the experts the router picks while generating the answer would be among them? usage: python sim_prompt_experts.py TRACE.json""" import json, sys from collections import Counter, defaultdict def main(): t = json.load(open(sys.argv[1])) tr = t["trace"] E = t["E"] Ms = (8, 16, 24, 32, 48, 64, 96, 128) print(f"{'turn':12s} prompt answer " + " ".join(f"M={m:<3d}" for m in Ms) + " (share of the answer's expert picks covered)") tot = defaultdict(lambda: [0, 0]) for run in t["runs"]: seg = tr[run["start"]:run["end"]] pre = [x for x in seg if x[1] > 1] dec = [x for x in seg if x[1] == 1] if not pre or not dec: continue freq = defaultdict(Counter) # layer -> expert -> prompt blocks that used it for layer, S, n, experts in pre: freq[layer].update(experts) row = [] for m in Ms: keep = {l: {e for e, _ in c.most_common(m)} for l, c in freq.items()} hit = sum(1 for layer, S, n, experts in dec for e in experts if e in keep.get(layer, ())) allp = sum(len(experts) for _, _, _, experts in dec) tot[m][0] += hit tot[m][1] += allp row.append(hit / allp) print(f"{run['name']:12s} {run['prompt_tokens'] - run['cached']:5d} {run['completion']:6d} " + " ".join(f"{r * 100:5.1f}%" for r in row)) print(f"{'all':12s} " + " ".join(f"{tot[m][0] / tot[m][1] * 100:5.1f}%" for m in Ms)) per = 1.58 print("\nmemory of the kept experts (40 layers): " + " ".join(f"M={m}: {m * 40 * per / 1024:.1f} GB" for m in Ms)) if __name__ == "__main__": main()