Skip to content

Commit de8f59f

Browse files
committed
experts offload: honour MAX_AHEAD from the environment, add an in-process sweep
`MAX_AHEAD` was a plain class attribute, so `TRANSFORMERS_EXPERTS_OFFLOAD_MAX_AHEAD` (already exported by the bench runners) silently did nothing and every run used 16. `max_ahead_sweep.py` sets the field on the live router and walks the range inside one process, which is what makes the sweep affordable: one checkpoint load instead of one per value. Measured at 16 GiB / events on / LOOKAHEAD=0: the knee is 4 and 4..32 is flat (35.65-36.03 ms/token); a cold 128-token verify at 32 with PIN_AHEAD=1 is exact but 17.48 sustained against 19.58, so 16 stays the default and is documented as a margin above the knee.
1 parent f92836e commit de8f59f

2 files changed

Lines changed: 191 additions & 1 deletion

File tree

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
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)

‎src/transformers/distributed/offload.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -545,7 +545,10 @@ class _MPSHostRouter:
545545
straight into free pool slots (`preadv` into the slots' unified memory: no copy, no device op), writes the slot
546546
table in place and signals. Pools and tables live in shared storage, written by the CPU while the device waits."""
547547

548-
MAX_AHEAD = 16
548+
# How many layers the host may queue ahead of the device. Overlap saturates fast: an in-process sweep puts the knee
549+
# at 4 and 4..32 is flat (35.65-36.03 ms/token), while a deeper queue loses cold throughput. 16 is a margin above
550+
# the knee, not a tuned optimum. See `benchmark_v2/experts_offload/max_ahead_sweep.py`.
551+
MAX_AHEAD = int(os.environ.get("TRANSFORMERS_EXPERTS_OFFLOAD_MAX_AHEAD", "16"))
549552
COMMIT_EVERY = int(os.environ.get("TRANSFORMERS_EXPERTS_OFFLOAD_COMMIT_EVERY", "2"))
550553

551554
def __init__(self, store, ext):

0 commit comments

Comments
 (0)