|
| 1 | +"""Sweep `_MPSHostRouter.MAX_AHEAD` in one process: how far the host may run ahead of the device. |
| 2 | +
|
| 3 | +Reloading the 30B checkpoint per value costs ~8 minutes, so this loads once, warms the compiled step up, then walks |
| 4 | +`MA_VALUES` ascending. Results print (and flush) per value, so a deadlock at the top of the range still leaves the |
| 5 | +lower values on disk. `MAX_AHEAD` is set on the live router, which is the same field `route()` spins on. |
| 6 | +
|
| 7 | +The point of the sweep: `route()` blocks the main thread once the host is `MAX_AHEAD` layers ahead, and `wait()` |
| 8 | +commits a command buffer every `COMMIT_EVERY`. Metal stops accepting buffers at ~64 in flight, so too deep a queue |
| 9 | +deadlocks the flush; too shallow one under-overlaps the miss reads with the GPU. We want the knee, not a guess. |
| 10 | +
|
| 11 | +Run through the bounded runner so the same loader patches apply: |
| 12 | + MA_VALUES=1,2,4,8,12,16,24,32 MA_TOKENS=16 \ |
| 13 | + python .bench/mem_bounded_run.py max_ahead_sweep.py ~/qwen38-metal/final-ckpt 4g32c 16 |
| 14 | +""" |
| 15 | + |
| 16 | +import os |
| 17 | +import sys |
| 18 | +import time |
| 19 | + |
| 20 | +import torch |
| 21 | +from dense_quant import quantize_dense |
| 22 | + |
| 23 | +from transformers import AutoModelForCausalLM, AutoTokenizer, CompileConfig |
| 24 | + |
| 25 | +repo = sys.argv[1] if len(sys.argv) > 1 else "ArthurZ/Qwen3-30B-A3B-metal-experts-4bit" |
| 26 | +spec = sys.argv[2] if len(sys.argv) > 2 else "4g32c" |
| 27 | +cache_gib = float(sys.argv[3]) if len(sys.argv) > 3 else 0 |
| 28 | +N = int(os.environ.get("MA_TOKENS", "16")) |
| 29 | +values = [int(v) for v in os.environ.get("MA_VALUES", "1,2,4,8,12,16,24,32,48").split(",") if v.strip()] |
| 30 | + |
| 31 | +tok = AutoTokenizer.from_pretrained(repo) |
| 32 | +if cache_gib: |
| 33 | + import glob |
| 34 | + |
| 35 | + from huggingface_hub import snapshot_download |
| 36 | + from safetensors import safe_open |
| 37 | + |
| 38 | + path = repo if os.path.isdir(repo) else snapshot_download(repo) |
| 39 | + resident = 0 |
| 40 | + for file in glob.glob(f"{path}/*.safetensors"): |
| 41 | + with safe_open(file, "pt") as f: |
| 42 | + for key in f.keys(): |
| 43 | + if ".experts." not in key and ".ngram_embedding." not in key: |
| 44 | + meta = f.get_tensor_meta(key) if hasattr(f, "get_tensor_meta") else None |
| 45 | + shape = meta.shape if meta else f.get_slice(key).get_shape() |
| 46 | + resident += torch.Size(shape).numel() * 2 |
| 47 | + model = AutoModelForCausalLM.from_pretrained( |
| 48 | + repo, |
| 49 | + dtype=torch.bfloat16, |
| 50 | + device_map={"": "mps", "experts": "disk", "ngram_embedding": "disk"}, |
| 51 | + max_memory={"mps": int(resident + cache_gib * 2**30)}, |
| 52 | + ) |
| 53 | +else: |
| 54 | + model = AutoModelForCausalLM.from_pretrained(repo, dtype=torch.bfloat16, device_map="mps") |
| 55 | +quantize_dense(model, spec) |
| 56 | +compile_config = CompileConfig() |
| 57 | +compile_config._compile_all_devices = True |
| 58 | +compiled = {"cache_implementation": "static", "compile_config": compile_config} |
| 59 | + |
| 60 | +prompt = "Write a short story about a lighthouse keeper who finds a message in a bottle." |
| 61 | + |
| 62 | + |
| 63 | +def ids(p): |
| 64 | + return tok.apply_chat_template( |
| 65 | + [{"role": "user", "content": p}], add_generation_prompt=True, return_tensors="pt", return_dict=True, |
| 66 | + enable_thinking=False, |
| 67 | + ).input_ids.to("mps") # fmt: skip |
| 68 | + |
| 69 | + |
| 70 | +stores = [] |
| 71 | +seen = set() |
| 72 | +for name, module in model.named_modules(): |
| 73 | + store = getattr(module, "offload_store", None) |
| 74 | + if store is not None and id(store) not in seen: |
| 75 | + seen.add(id(store)) |
| 76 | + stores.append((name, store)) |
| 77 | +if not stores: |
| 78 | + raise SystemExit("no offload store found: is this a streamed checkpoint?") |
| 79 | + |
| 80 | + |
| 81 | +def routers(): |
| 82 | + out = [] |
| 83 | + for _, store in stores: |
| 84 | + r = getattr(store, "mps_router", None) |
| 85 | + if r is not None: |
| 86 | + out.append(r) |
| 87 | + return out |
| 88 | + |
| 89 | + |
| 90 | +class Stamps: |
| 91 | + """Per-token timestamps (and the token ids) from the generate streamer, so prefill is excluded.""" |
| 92 | + |
| 93 | + def __init__(self): |
| 94 | + self.t = [] |
| 95 | + self.tokens = [] |
| 96 | + |
| 97 | + def put(self, token): |
| 98 | + self.t.append(time.perf_counter()) |
| 99 | + try: |
| 100 | + self.tokens.append(int(token)) |
| 101 | + except (TypeError, ValueError): |
| 102 | + pass |
| 103 | + |
| 104 | + def end(self): |
| 105 | + pass |
| 106 | + |
| 107 | + |
| 108 | +def generate(n): |
| 109 | + stamps = Stamps() |
| 110 | + with torch.inference_mode(): |
| 111 | + model.generate(ids(prompt), max_new_tokens=n, min_new_tokens=n, do_sample=False, streamer=stamps, **compiled) |
| 112 | + steps = [b - a for a, b in zip(stamps.t[2:], stamps.t[3:])] |
| 113 | + return steps, stamps.tokens |
| 114 | + |
| 115 | + |
| 116 | +def snapshot(): |
| 117 | + out = {} |
| 118 | + for _, store in stores: |
| 119 | + for k, v in store.stats().items(): |
| 120 | + out[k] = out.get(k, 0) + v |
| 121 | + for r in routers(): |
| 122 | + for k in ("spin_seconds", "work_seconds", "ahead_reads", "jobs_done"): |
| 123 | + out[k] = out.get(k, 0) + getattr(r, k) |
| 124 | + # Steady-state lag: how many routings the host was ahead of the device when the window closed. |
| 125 | + out["lag"] = max(out.get("lag", 0), r.counter - r.ext.signaled(r.event)) |
| 126 | + return out |
| 127 | + |
| 128 | + |
| 129 | +def reset(): |
| 130 | + for _, store in stores: |
| 131 | + store.reset_stats() |
| 132 | + for r in routers(): |
| 133 | + r.spin_seconds = r.work_seconds = 0.0 |
| 134 | + r.ahead_reads = r.jobs_done = 0 |
| 135 | + |
| 136 | + |
| 137 | +generate(32) # compile warmup |
| 138 | +torch.mps.synchronize() |
| 139 | +print(f"routers: {len(routers())} commit_every: {[r.COMMIT_EVERY for r in routers()]}", flush=True) |
| 140 | + |
| 141 | +baseline_tokens = None |
| 142 | +rows = [] |
| 143 | +for ma in values: |
| 144 | + for r in routers(): |
| 145 | + r.MAX_AHEAD = ma |
| 146 | + reset() |
| 147 | + print(f"\n=== MAX_AHEAD={ma} ===", flush=True) |
| 148 | + try: |
| 149 | + steps, tokens = generate(N) |
| 150 | + except Exception as error: # noqa: BLE001 - a deadlock surfaces here as a Metal timeout |
| 151 | + print(f" FAILED: {type(error).__name__}: {str(error)[:300]}", flush=True) |
| 152 | + rows.append((ma, None)) |
| 153 | + break |
| 154 | + if not steps: |
| 155 | + print(" no steps measured", flush=True) |
| 156 | + rows.append((ma, None)) |
| 157 | + continue |
| 158 | + wall = sum(steps) |
| 159 | + per_tok = wall / len(steps) |
| 160 | + snap = snapshot() |
| 161 | + n = len(steps) |
| 162 | + host = snap["spin_seconds"] + snap["work_seconds"] |
| 163 | + same = "n/a" if baseline_tokens is None else ("same" if tokens == baseline_tokens else "DIFFERENT") |
| 164 | + if baseline_tokens is None: |
| 165 | + baseline_tokens = tokens |
| 166 | + hits, misses = snap.get("hits", 0), snap.get("misses", 0) |
| 167 | + print( |
| 168 | + f" wall {per_tok * 1000:7.2f} ms/token {1 / per_tok:6.2f} tok/s " |
| 169 | + f"spin {snap['spin_seconds'] / n * 1000:6.2f} work {snap['work_seconds'] / n * 1000:6.2f} " |
| 170 | + f"lag {snap.get('lag', 0):3d} " |
| 171 | + f"hit {hits / max(hits + misses, 1) * 100:5.2f}% ahead_reads {snap.get('ahead_reads', 0):6d} " |
| 172 | + f"tokens {same}", |
| 173 | + flush=True, |
| 174 | + ) |
| 175 | + rows.append((ma, per_tok)) |
| 176 | + |
| 177 | +print("\n=== summary ===", flush=True) |
| 178 | +best = None |
| 179 | +for ma, per_tok in rows: |
| 180 | + if per_tok is None: |
| 181 | + print(f"MAX_AHEAD={ma:3d} failed", flush=True) |
| 182 | + continue |
| 183 | + print(f"MAX_AHEAD={ma:3d} {per_tok * 1000:7.2f} ms/token {1 / per_tok:6.2f} tok/s", flush=True) |
| 184 | + if best is None or per_tok < best[1]: |
| 185 | + best = (ma, per_tok) |
| 186 | +if best: |
| 187 | + print(f"\nbest: MAX_AHEAD={best[0]} {1 / best[1]:.2f} tok/s", flush=True) |
0 commit comments