Skip to content

perf(glm5_next): route verify rows like one-token decode - #4324

Merged
jundot merged 1 commit into
jundot:mainfrom
junmo-kim:perf/glm53-verify-router-main
Oct 7, 2026
Merged

jundot merged 1 commit into
jundot:mainfrom
junmo-kim:perf/glm53-verify-router-main

Conversation

@junmo-kim

@junmo-kim junmo-kim commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

GLM-5.3 MTP verification blocks (batch size 1, 2–8 rows, n_group == 1, fused path on M5 GPUs with neural accelerators, "NAX") currently route experts with moe_router_rows, which replays MLX's TF32 block GEMM. This PR routes each verification row with the existing one-token moe_router instead, so every row gets the same fp32 routing arithmetic as the decode step it verifies.

The block replay is the slow part of verification routing. An earlier per-layer microbenchmark (layer 10, MLX 0.32.2, a different GLM-5.3 checkpoint) measured about 99/108/108 µs per MoE layer at 2/3/4 rows for the block replay versus 11/23/23 µs row by row. End to end on an M5 Ultra this raises decode throughput by +15.1% on a 28.9K-token prompt and +20.2% on short prompts.

Trade-off: one-row fp32 routing is not bit-identical to the TF32 block GEMM, so outputs can change. On real activations the router logits differed by at most 4.8e-6 and no top-8 expert set changed in 210 rows. There is no new environment switch; unsupported configurations keep the existing fallback, and one-token decode is unchanged.

After this change moe_router_rows is no longer called by production, and the one-time eager warm-up in _check_verify_router that existed for its first-use check is redundant. I left both in place to keep the diff minimal and am happy to remove them here or in a follow-up.

Validation

Setup: Mac Studio M5 Ultra (80-core GPU, 256 GB), macOS 27.0, Python 3.12, official MLX/MLX-metal 0.32.3 with the GLM native extensions rebuilt; unmodified GLM-5.3-Flash 4-bit MTP checkpoint; upstream defaults in both arms (context-copy on, stock TF32, adaptive MTP with four draft tokens), temperature 0. Measurements used this patch applied to 7f3a87f0. This branch (9ebe097f) is the same patch (identical patch-id) rebased onto 79f4488e; the four commits in between do not touch the changed files or GLM/MTP code, and the GPU measurements were not rerun after the rebase.

Throughput

Three alternating main/PR pairs per workload. Each arm ran in a freshly started server with a one-token warm-up excluded. Values are the median of the three suite medians; decode throughput is completion tokens divided by the time after the first streamed token.

Workload main This PR Change
Three 28,850–28,858-token prompts, 512 output tokens each 82.12 tok/s 94.54 tok/s +15.1%
Six prompts of 42–640 tokens, 768 output tokens each 77.41 tok/s 93.05 tok/s +20.2%

Every pair improved (long +24.8/+13.7/+15.1%, short +17.2/+20.2/+20.9%). Per-request TTFT medians: 12.60→12.62 s (long), 0.167→0.163 s (short). Long prompts carried a per-round nonce so rounds did not share a prefix; short prompts were cold in round 1 and reused all but 2 prompt tokens from each arm's own cache in rounds 2–3. The first short-prompt attempt was interrupted by unrelated GPU load, so all three short pairs were rerun with fresh caches. Memory was not separately instrumented. Greedy text differed in 27/27 pairs, so this benchmark makes no output-identity claim.

Routing numerics

  • Same-input Metal comparison: 40/40 cases (real layers 3 and 44 at 1/2/4/8 rows, plus tied and near-tied synthetic cases) gave identical expert IDs and fp32 scores between verification-row routing and the one-token decode selection path.
  • Against the block path on real activations (layers 3/12/24/36/44, 2/4/8-row windows): 0 top-8 changes in 210 overlapping rows, max |Δlogit| 4.8e-6, max normalized-weight difference 4.0e-7.

These compare identical inputs across dispatches; they do not make whole GLM forwards row-exact.

Quality (NLL, measured earlier on MLX 0.32.2)

Same 4-bit checkpoint, 240 fresh 512-token held-out windows, 122,640 scored targets per arm, window-paired bootstrap (20,000 resamples). STEP1 is non-speculative one-token scoring; STEP4 is teacher-forced scoring through 4-token verification blocks.

Contrast Relative NLL 95% CI
STEP4 block (main) − STEP1 −0.23% −0.39% to −0.07%
STEP4 one-row (this PR) − STEP1 −0.06% −0.21% to +0.08%
STEP4 one-row − STEP4 block +0.16% +0.04% to +0.29%

Against the existing block path, a predeclared +0.15% non-inferiority margin was not met. Against non-speculative decoding, no difference was detected for this PR, while the block path did differ. This is not a proof of equivalence, and NLL was not remeasured on MLX 0.32.3.

Tests

New tests/test_glm53_verify_router.py (10 cases): row-wise equality with one-token routing at 2/3/4/8 rows, expert selection, ineligible blocks (batch size 2, 9 rows, grouped routing), disabled fusion and declined-kernel fallback.

On the same machine and environment (7f3a87f0 → this patch):

  • Related (tests/test_glm*.py, tests/test_mlx_vlm_glm5_next_compat.py, tests/test_mlx_lm_mtp_patch.py): 850 → 860 passed, 7 skipped each.
  • Default suite (python -m pytest): 17,313 → 17,323 passed, 298 skipped each. Both runs have the same 12 pre-existing failures (test_dspark_attention_matches_stock_m1_fallback, a native-vs-stock attention comparison on this machine) and no new failures.

Reproduction

Start one server per arm (main and this branch) with the same model and settings, then run each suite against it, alternating arm order per round (main/PR, PR/main, main/PR):

python replay_benchmark.py --inputs inputs.json --url http://127.0.0.1:<port> --model <model-id> --workload long --round 0
python replay_benchmark.py --inputs inputs.json --url http://127.0.0.1:<port> --model <model-id> --workload short --round 0

inputs.json holds three long prompts per round ({"long": {"0": {...}, "1": {...}, "2": {...}}}) and six short prompts ({"short": {...}}). I can share the exact input file on request.

replay_benchmark.py
"""Portable replay of frozen inputs against an independently started OpenAI-compatible arm."""
import argparse,hashlib,json,os,statistics,time,urllib.request
from pathlib import Path

def request(url,model,prompt,limit):
 body={'model':model,'stream':True,'stream_options':{'include_usage':True},'temperature':0,'max_tokens':limit,'messages':[{'role':'user','content':prompt}]}
 headers={'Content-Type':'application/json'}
 token=os.environ.get('OMLX_API_KEY')
 if token:headers['Authorization']='Bearer '+token
 start=time.perf_counter();first=None;usage=None;text=[]
 req=urllib.request.Request(url.rstrip('/')+'/v1/chat/completions',data=json.dumps(body).encode(),headers=headers,method='POST')
 with urllib.request.urlopen(req,timeout=900) as response:
  for raw in response:
   line=raw.decode().strip()
   if not line.startswith('data:') or line=='data: [DONE]':continue
   event=json.loads(line[5:]);assert not event.get('error'),event.get('error')
   usage=event.get('usage') or usage
   for choice in event.get('choices') or []:
    d=choice.get('delta') or {};piece=(d.get('content') or '')+(d.get('reasoning_content') or d.get('reasoning') or '')
    if piece:first=first or time.perf_counter();text.append(piece)
 end=time.perf_counter();assert first and usage and usage['completion_tokens']>1
 ct=usage['completion_tokens']
 return {'ct':ct,'gen_s':end-first,'ttft':first-start,'client_tg':ct/(end-first),'usage':usage,'text':''.join(text)}

def main():
 p=argparse.ArgumentParser();p.add_argument('--inputs',type=Path,required=True);p.add_argument('--url',required=True);p.add_argument('--model',required=True);p.add_argument('--workload',choices=['long','short'],required=True);p.add_argument('--round',type=int,choices=range(3),required=True);p.add_argument('--dry-run',action='store_true');a=p.parse_args()
 inputs=json.loads(a.inputs.read_text());prompts=inputs['short'] if a.workload=='short' else inputs['long'][str(a.round)]
 if a.dry_run:
  print(json.dumps({'exit_code':0,'requests':len(prompts),'input_sha256':hashlib.sha256(a.inputs.read_bytes()).hexdigest(),'model_loads':0,'gpu_executions':0,'network_requests':0}));return
 # Exclude one non-streaming, one-token warmup before this suite.
 warm={'model':a.model,'temperature':0,'max_tokens':1,'messages':[{'role':'user','content':'Hi'}]}
 headers={'Content-Type':'application/json'}
 if os.environ.get('OMLX_API_KEY'):headers['Authorization']='Bearer '+os.environ['OMLX_API_KEY']
 req=urllib.request.Request(a.url.rstrip('/')+'/v1/chat/completions',data=json.dumps(warm).encode(),headers=headers,method='POST')
 with urllib.request.urlopen(req,timeout=180) as response:json.load(response)
 values=[]
 for name,prompt in prompts.items():
  value=request(a.url,a.model,prompt,512 if a.workload=='long' else 768);values.append(value['client_tg']);print(json.dumps({'task':name,'value':value}),flush=True)
 print(json.dumps({'suite_median_client_tg':statistics.median(values)}))
if __name__=='__main__':main()

Checklist

  • I read CONTRIBUTING.md.
  • I understand every change in this PR and can explain it in review.
  • For UI or UX changes, I attached before and after screenshots. (Not applicable: no UI or UX changes.)

@N1k1tung

N1k1tung commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

looks to be faster for dflash as well (against mlx 0.32.3)
affine 4-bit https://omlx.ai/benchmarks/performance/i9zl3yj0
oQ4e: https://omlx.ai/benchmarks/performance/goj6q9vt

Though I think it's more of an issue with the batch verify

@junmo-kim

Copy link
Copy Markdown
Contributor Author

Thanks for checking this with DFlash. That fits the mechanism: DFlash verification goes through the same multi-row verify block, so it was hitting the same moe_router_rows path.

Agreed that the underlying cost is in the batched verify router (the TF32 block-GEMM replay). This PR sidesteps it by reusing the one-row router for each verify row, which also keeps verify routing consistent with decode. A faster batched router kernel would be a separate change.

@jundot jundot left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested this on an M5 Max with a smaller 20-layer GLM-5.3-Flash MTP model. Decode went from 30.1 to 31.4 tok/s, and the verify step was faster in every single run. It's a smaller model on a smaller chip than your M5 Ultra setup, but the improvement showed up consistently.

The change itself is small and easy to follow, and your NLL comparison made it easy to accept that the outputs change a bit. Thanks for the careful measurements and the clear write-up. After merging I'll do a small cleanup on main to remove the old verify router path that's no longer used and to trim the related comments and tests. LGTM, merging.

@jundot
jundot merged commit d67333a into jundot:main Oct 7, 2026
1 check passed
jundot added a commit that referenced this pull request Oct 7, 2026
Drop the GLM moe_router_rows kernel and its warm-up now that verify rows use the one-row router, and fold the new GLM router and routed A8 tests into the existing modules.
@junmo-kim
junmo-kim deleted the perf/glm53-verify-router-main branch October 7, 2026 04:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants