Skip to content

glm metal: fuse 8-bit/64 shared expert with 4-bit/64 routed MoE - #4249

Open
gilby wants to merge 6 commits into
ashhart:mainfrom
gilby:glm-metal-moe-sh8
Open

gilby wants to merge 6 commits into
ashhart:mainfrom
gilby:glm-metal-moe-sh8

Conversation

@gilby

@gilby gilby commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Extends the fused Metal 4/64 MoE gather/down kernels (glm_moe_gateup_0_sh8, glm_moe_down_0_sh8, _one, and _pick) with uint4 8-bit/64-group shared-expert loads so mixed 4/64 routed + 8/64 shared layers stay on the single fused MoE launch (both + combine_0) instead of falling back to unfused wide.moe launches.

  • Adds sh8Source in zig/src/families/glm/moe_sh8.zig (re-exported in kernels.zig) with error.Sh8TemplateMismatch diagnostic and host test, explicit m3_slot indexing in kernels.zig, [[max_total_threads_per_threadgroup(512)]] on the gateup kernels, and 6 sh8 pipelines loaded alongside moe_gateup_0* / moe_down_0*.
  • Adds shared8 / canBoth and fused sh8 dispatch in zig/src/families/glm/moe.zig.
  • Registers glm sh8 contract launches, planted controls, M1/M2 offline records (zig/src/core/contract/glm_sh8_records.zig), and bit-exact parity test zig/src/families/glm/sh8_moe_test.zig.

Checks & Performance Receipt (7513e6671a945df370543ba6648c938e15874adf, code ba662f203051)

  • Merged origin/main (9cd11ef068adf656f9a84dd7014ae3b64d230887).
  • zig test zig/src/families/glm/moe_sh8.zig (All 1 tests passed.), zig fmt --check build.zig zig, python3 tools/zig/env_names.py (841 variables read, 0 problems), python3 tools/pr_check.py --base origin/main --pr 4249 (0 error(s)).
  • Kernel contract --only "glm sh8":
    • Apple M3 Ultra (applegpu_g15, tensor units false): SUMMARY 2 kernels: 2 pass gates 1-4, 0 fail, 0 known findings; 2 controls: 2 red as planted, 0 missed; 0 limit problems; gates 1229 ms, limits 470 ms.
    • Apple M5 Pro (applegpu_g17, tensor units true): SUMMARY 2 kernels: 2 pass gates 1-4, 0 fail, 0 known findings; 2 controls: 2 red as planted, 0 missed; 0 limit problems; gates 1233 ms, limits 16 ms.
  • Committed receipt: docs/receipts/glm-metal-moe-sh8/perf-receipt.json (verified PASS perf-receipt 534f236f726c0c76 against merge-base 9cd11ef068ad and branch HEAD):
    • Apple M3 Ultra (Jundot/GLM-5.3-Flash-oQ4e-mtp, --draft --check-draft, --pairs 2): +3.02% (58.119 -> 59.876 tok/s, base-vs-base noise 0.80%, head beats base in every ABBA pair), 4/4 prompts token_equal: true (exactness_sha256: 142d8d9479751bcc3b33ae7cc0224231758c22566a94af6d0d118ab16ab7d359), draft_check.equal: true.
  • Apple M3 Ultra tf-glm-run post-8K profiles (8,205-token prompt, GLM_CAP=10240, GLM_PROFILE):
    • Jundot/GLM-5.3-Flash-oQ4e-mtp (GLM_DEPTHS=0,3): all 32 tokens equal, depth 0 == depth 3 (hash 205fd10a8f874895); depth-0 decode 38.8–38.9 -> 40.7–40.9 tok/s (+5.1%); 1-row step 25.487–25.597 ms -> 24.251–24.264 ms (-4.8% to -5.2%), shared class cut 2.259 -> 1.064 ms.
    • zai-org/GLM-5.3-Flash-MLX-4bit control (GLM_DEPTHS=0): all 16 tokens equal (hash 8e6cfa0e46473e90); 1-row step 18.700 -> 18.723 ms (+0.12%, zero post-8K regression).

@AIFlowML

AIFlowML commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Independent device run at 59ffca4b on M5 Max with Zig 0.17.0. I ran zig build tf-kernel-contract -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j3 --summary all, then ./zig-out/bin/tf-kernel-contract --only 'glm sh8' (exit 0).

SUMMARY 2 kernels: 2 pass gates 1-4, 0 fail, 0 known findings; 2 controls: 2 red as planted, 0 missed; 0 limit problems; gates 1454 ms, limits 18 ms

The exact head merges cleanly with 46c6ee22. The #4248 and #4254 public heads conflict with this one in GLM and the contract lists. The combined-head check should retain all six glm sh8 registered launch limits along with the two gated kernels in the SUMMARY. I verified the device contract here. Served-model timing and equality are covered by the separate checkpoint receipts.

After the DFlash2 merge, this head conflicts with 3025ce9d2 in registry_joins.zig and metal_main.zig. Keeping both the DFlash2 and sh8 entries in each file gave a passing M5 trial. The same glm sh8 command passed both kernels and caught both controls, with all six launch records passing. The separate --only "glm dflash2 accept" run also passed both kernels, caught its control and found zero limit problems. These runs cover the device contracts.

Igor Lessio - AIFLOW LABS

@ashhart

ashhart commented Nov 21, 2026

Copy link
Copy Markdown
Owner

Thanks @gilby. Fusing the 8-bit/64 shared expert into the 4-bit/64 routed MoE reads correct: uniform 4-bit/64 layers keep their pipelines, the mixed layers match wide + moe_2 bit for bit in your tests, and your 12 token_sha256 matches agree.

The GLM DFlash2 work that landed on main conflicts with this branch in two places. We're rebasing it ourselves, keeping your commit as it is, and then running it on our M5 Ultra and M3 Ultra Macs. We'll post the results here.

  • Synthena

@ashhart
ashhart force-pushed the glm-metal-moe-sh8 branch 3 times, most recently from e003903 to 9d2bcbc Compare November 22, 2026 00:08
@AIFlowML

Copy link
Copy Markdown
Contributor

I checked current heads 9d2bcbc83 and #4248 63c5dbde5 against main 2ce240cf0. They trial-merge cleanly on their own. Taking #4248 first and then this PR conflicts in five registration, limits, and kernel files.

In a scratch resolution I kept both families’ registrations and tests, assigned KVB8 jobs to slots 27–29 and SH8 jobs to 30–35, and left the optional M3 job last at 36. On M5 Max with Zig 0.17.0, zig build test-glm-gathers test-glm-metal-dflash-host tf-kernel-contract -Dcpu=apple_m1 -Doptimize=ReleaseSafe -j4 --summary all passed 51/51 steps and 21/21 tests. Both focused device runs exited 0.

  • tf-kernel-contract --only 'glm kvb8' passed two kernels and caught all four planted controls, with zero limit problems.
  • tf-kernel-contract --only 'glm sh8' passed two kernels and caught both planted controls, with zero limit problems.

The combined metal_main.zig is 602 lines and still needs to fit the repository’s 600-line limit before using this resolution. Full-checkpoint serving and M1/M2/M3 device runs were outside this check.

Igor Lessio - AIFLOW LABS

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Thanks @gilby. The shared 8 path retains the wide reference's four-term dot grouping and final combine placement, and the direct fixture compares BF16 output bits exactly. Uniform 4/64 keeps its pipeline selection.

The new contract collector needs partial-construction cleanup: a later pipeline or append failure can lose the Suite and completed probes. Please unwind completed resources and roll back exported entries, with focused failure coverage. We can handle the main overlap; final combined-tree numerical checks remain open.

  • Synthena

@ashhart

ashhart commented Nov 25, 2026

Copy link
Copy Markdown
Owner

@gilby, about the probe-registration cleanup our review asked for: the same two-append pattern was on main in 85 places, and #5058 (now merged) fixes it there with one helper, contract.register. It reserves room in both lists before publishing, so a failed append can no longer free a probe the suite still holds:

errdefer p.deinit(); // with errdefer s.a.destroy(p) after create, as the suite's teardown frees it
try ct.register(s.a, &s.probes, &s.kernels, p, p.kernel());

Using it for this PR's new suites closes that item. zig/src/core/contract/register_test.zig shows the failure cases it covers.

  • Synthena

gilby and others added 2 commits November 28, 2026 12:20
Extend the fused Metal MoE gather/down kernels (moe_gateup_0_sh8, moe_down_0_sh8, _one, and _pick) via uint4 8-bit/64 shared-expert loads so mixed 4/64 routed + 8/64 shared layers stay on the single fused path instead of falling back to unfused wide launches. Includes M1/M2 512-thread reservation, contract gates/controls/records, and bit-exact parity unit test.

Refs ashhart#3152
@gilby

gilby commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Updated glm-metal-moe-sh8 at 436ef0832b (preserving existing branch commits and merging origin/main):

  • Transactional contract collector (zig/tests/contract/metal_glm_sh8.zig): Added Probe.init (errdefer unwinding partial pipeline builds), migrated Suite.create to contract.register with errdefer ks.items.len = base_len; and errdefer s.destroy();, and added a FailingAllocator test (glm sh8 suite:) covering OOM rollback across Suite.create.
  • Runtime source origins (zig/src/families/glm/kernels.zig): Updated the assemble origin table indices for the SH8 jobs (generated.len + 27..33) to match origin/main's rawFrom checks.

Verification (436ef0832b):

  • zig fmt --check build.zig zig, python3 tools/pr_check.py --pr 4249 (0 errors), python3 tools/zig/env_names.py (0 problems)
  • zig build -Dfixed-cpu test-originals-host (5/5 steps succeeded, cached), zig build test-metal-runtime-source-modes-host (8/8 pass), zig build test-kernel-contract (380/380 pass)
  • ./zig-out/bin/tf-kernel-contract --only "glm sh8" on Apple M5 Ultra: SUMMARY 2 kernels: 2 pass gates 1-4, 0 fail, 0 known findings; 2 controls: 2 red as planted, 0 missed; 0 limit problems
  • sh8_moe_test (70/70 filtered tests pass) & glm sh8 suite: FailingAllocator test (1/1 pass)

@ashhart

ashhart commented Dec 2, 2026

Copy link
Copy Markdown
Owner

Thanks for the transactional contract collector, which closes the review's probe-registration ask.

Decision: ready for our review and device run. The zero-regression set on the oq071 checkpoint is ours on our M3 Ultra; your M5 Ultra cells stand as posted. Conflicts with #1835/#2239/#2273/#2634 are ours at pickup, and this lands with #4248.

The fused sh8 path stands: mixed 8-bit/64 shared with 4-bit/64 routed experts stays on the single fused launch instead of falling back to unfused wide.moe, with the six launches' limits checked against M1/M2 and both controls red.

  • Synthena

@ashhart

ashhart commented Dec 2, 2026

Copy link
Copy Markdown
Owner

@gilby, same finding here as on #4248, from our M3 Ultra run (GLM-5.3-Flash MLX 4-bit, main against this head, base, new, new, base). Tokens are equal on every prompt row, but decode right after an 8K prompt is 16% slower (40.0 against 33.6 tok/s, steady in both runs of each side), and 2K cells are level.

Since #4248 shows the same shape, it may be one cause across the series: something in the decode path that grows with cache length on pre-M5 chips. A per-kernel timing of one decode step after an 8K prompt would show it. We'll hold both until we know.

  • Synthena

@ashhart ashhart added kind:perf Classified by Synthena as performance improvement synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 3, 2026
@ashhart

ashhart commented Dec 3, 2026

Copy link
Copy Markdown
Owner

Synthena Initial Review — Performance receipt required (kind:perf)

Fuses 8-bit/64-group shared-expert loads into the existing 4-bit/64 routed MoE Metal kernels so mixed-precision GLM layers stay on the single fused MoE launch instead of falling back to unfused wide.moe launches, adding six new sh8 pipelines, contract records, and bit-exact parity tests.

  • Performance claim detected without a verified tf-receipt-v1 receipt.

Performance PRs require a verifiable benchmark receipt before running project CI hardware. See CONTRIBUTING.md (Performance PRs: verifiable benchmark receipt) and attach the output of:

python3 tools/perf_receipt.py run --base-bin /path/to/base-tf --head-bin /path/to/head-tf --model /path/to/model.tfold --out receipt.json

Findings:

  • [WARNING] zig/src/families/glm/kernels.zig: sh8Source silently assumes the template parameter string appears exactly twice in the base source; if the upstream kernel template changes, this fails at kernel-assembly time with a generic KernelCompile error rather than a clear message. Suggested fix: Include the kernel key or a short reason in the error (e.g. return error.Sh8TemplateMismatch) so assembly failures are diagnosable, or assert with a compile-time-checked source hash.
  • Synthena

@gilby

gilby commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Updated onto origin/main (9cd11ef068ad -> code commit ba662f203051, receipt commit 7513e6671a94), resolved Synthena's warning, and added a verified M3 Ultra performance receipt on Jundot/GLM-5.3-Flash-oQ4e-mtp plus post-8K tf-glm-run profiles:

1. Review Fix & Contract Verification

  • Extracted sh8Source into zig/src/families/glm/moe_sh8.zig with explicit error.Sh8TemplateMismatch when template parameters do not appear twice + host test (All 1 tests passed.), fixed edit() to verify std.mem.count(u8, text, from) == 1 so prefix/suffix edits ([[max_total_threads_per_threadgroup(512)]] and _sh8 renames) compile cleanly, and placed m3_fast in trailing m3_slot.
  • tools/pr_check.py --base origin/main --pr 4249: 0 error(s).
  • tf-kernel-contract --only "glm sh8":
    • Apple M3 Ultra (applegpu_g15): SUMMARY 2 kernels: 2 pass gates 1-4, 0 fail, 0 known findings; 2 controls: 2 red as planted, 0 missed; 0 limit problems; gates 1229 ms, limits 470 ms.
    • Apple M5 Pro (applegpu_g17): SUMMARY 2 kernels: 2 pass gates 1-4, 0 fail, 0 known findings; 2 controls: 2 red as planted, 0 missed; 0 limit problems; gates 1233 ms, limits 16 ms.

2. Apple M3 Ultra Post-8K Kernel Profiles (tf-glm-run, 8,205-token prompt, GLM_CAP=10240)

  • Jundot/GLM-5.3-Flash-oQ4e-mtp (8/64 shared + 4/64 routed, GLM_DEPTHS=0,3, 9cd11ef068ad vs ba662f203051):
    • all 32 tokens equal, depth 0 == depth 3 (hash 205fd10a8f874895).
    • Depth-0 decode: 38.8–38.9 -> 40.7–40.9 tok/s (+5.1%).
    • 1-row step time (GLM_PROFILE=0): 25.597 ms (parts) / 25.487 ms (classes) -> 24.251 ms (parts) / 24.264 ms (classes) (-4.8% to -5.2%), with shared class cost dropping from 2.259 ms (8.9%) to 1.064 ms (4.4%).
  • zai-org/GLM-5.3-Flash-MLX-4bit (4/64 uniform control, GLM_DEPTHS=0, 9cd11ef068ad vs ba662f203051):
    • all 16 tokens equal (hash 8e6cfa0e46473e90), 1-row step 18.700 -> 18.723 ms (+0.12% classes) / 18.722 -> 18.729 ms (+0.04% parts), confirming zero post-8K regression on 4-bit checkpoints.

3. Committed Receipt (docs/receipts/glm-metal-moe-sh8/perf-receipt.json)

  • Apple M3 Ultra (Jundot/GLM-5.3-Flash-oQ4e-mtp, --draft --check-draft, --pairs 2):
    • PASS perf-receipt 534f236f726c0c76 (receipt_sha256: 534f236f726c0c7602b1e3ef9c952c977258dff3d73264e755995b12f559cfb3)
    • +3.02% (58.119 -> 59.876 tok/s, base-vs-base noise 0.80%; head beat base in all 4 mirrored ABBA half-pairs)
    • 4/4 prompts token_equal: true (exactness_sha256: 142d8d9479751bcc3b33ae7cc0224231758c22566a94af6d0d118ab16ab7d359), draft_check.equal: true, control.diverged: true.
  • CI note: Verify performance receipt (23s) and No GPU/zig (22m31s) both passed on 7513e6671a94; ci/perf-golden-hash failed only with no golden token_sha256 reference configured for checkpoint 'Jundot/GLM-5.3-Flash-oQ4e-mtp' because secrets.TF_GOLDEN_TOKEN_HASHES does not yet list this mixed 8/64+4/64 checkpoint.

@ashhart ashhart added synthena:needs-changes Reviewed by Synthena; changes requested and removed synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 4, 2026
@ashhart

ashhart commented Dec 5, 2026

Copy link
Copy Markdown
Owner

A correction to our automated review: Your committed receipt passes verify; the golden-hash status checks our own reference hashes, so that part is ours and nothing more is needed from you for it.

  • Synthena

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind:perf Classified by Synthena as performance improvement synthena:needs-changes Reviewed by Synthena; changes requested

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants