"""Count how often each routed expert is chosen on coding traffic. python train/expert_usage.py --model --data --out usage.json [--convs 60] Runs the model forward (no training) over kept coding conversations and records, at every layer, which 8 of the 128 experts the router picks for each token. The looped layers are visited three times per token; their visits are added together, because the three passes share one set of experts. """ import argparse import json import time from unsloth import FastModel # noqa: E402 import torch def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--data", required=True) ap.add_argument("--out", required=True) ap.add_argument("--convs", type=int, default=60) ap.add_argument("--max-len", type=int, default=24000) a = ap.parse_args() model, tok = FastModel.from_pretrained(model_name=a.model, max_seq_length=a.max_len, load_in_4bit=False, full_finetuning=False) model.eval() gates = [(n, m) for n, m in model.named_modules() if type(m).__name__.endswith("TopKRouter")] # one per layer: `mlp.gate` if not gates: raise SystemExit("no router found: " + str([n for n, _ in model.named_modules() if "mlp" in n][:10])) topk = int(getattr(getattr(model.config, "text_config", model.config), "num_experts_per_tok", 8)) counts = {n: torch.zeros(128, dtype=torch.long) for n, _ in gates} calls = {n: 0 for n, _ in gates} def hook(name): def f(_m, _inp, out): # the router returns its logits, its scores and the chosen expert indices: take the integer tensor idx = next(o for o in out if torch.is_tensor(o) and not o.is_floating_point()).detach().reshape(-1).cpu() counts[name] += torch.bincount(idx, minlength=128) calls[name] += 1 return f hs = [m.register_forward_hook(hook(n)) for n, m in gates] tool = json.load(open(a.data + "/tool.json")) rows = [json.loads(line) for line in open(a.data + "/sft.jsonl", encoding="utf-8")] tokens, used, t0 = 0, 0, time.time() with torch.no_grad(): for r in rows: enc = tok.apply_chat_template(r["messages"], tools=[tool], tokenize=True, add_generation_prompt=False, return_dict=True) ids = enc["input_ids"] if ids and isinstance(ids[0], (list, tuple)): ids = ids[0] if len(ids) > a.max_len: continue model(input_ids=torch.tensor([ids], device=model.device)) tokens += len(ids) used += 1 if used >= a.convs: break for h in hs: h.remove() layers = {} for n, c in counts.items(): share = (c.float() / c.sum().clamp(min=1)).tolist() order = sorted(range(128), key=lambda i: -c[i].item()) layers[n] = {"router_calls": calls[n], "counts": c.tolist(), "order_most_used_first": order, "share_of_top_96": round(sum(share[i] for i in order[:96]), 5), "share_of_top_64": round(sum(share[i] for i in order[:64]), 5), "never_used": int((c == 0).sum())} json.dump({"model": a.model, "conversations": used, "tokens": tokens, "topk": topk, "seconds": round(time.time() - t0, 1), "layers": layers}, open(a.out, "w")) s96 = sorted(v["share_of_top_96"] for v in layers.values()) s64 = sorted(v["share_of_top_64"] for v in layers.values()) print("USAGE", json.dumps({"routers": len(layers), "conversations": used, "tokens": tokens, "seconds": round(time.time() - t0, 1), "calls_per_router": sorted(set(calls.values())), "share kept by the 96 most used, per layer (min/median/max)": [s96[0], s96[len(s96) // 2], s96[-1]], "share kept by the 64 most used": [s64[0], s64[len(s64) // 2], s64[-1]], "router names": [n for n, _ in gates][:3]})) if __name__ == "__main__": main()