Skip to content

glm metal: add TFQ3 (2D-AffineCoset/half4) runtime and kernels - #4953

Merged
ashhart merged 8 commits into
mainfrom
feat/glm-tfq3
Nov 25, 2026
Merged

ashhart merged 8 commits into
mainfrom
feat/glm-tfq3

Conversation

@ashhart

@ashhart ashhart commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Summary

Adds native Metal runtime support for TFQ3 (2D-AffineCoset/half4 Hadamard-rotated trellis quantization) in the GLM-5.3-Flash family, enabling zero-copy mmap loading and native decode/prefill execution of .tffpw MoE layers (layer_XX.tffpw), unified non-MoE projections (nonmoe.tffpw), and codebook tables (pw_v3_tables.bin).

  • Zero overhead on non-TFQ3 checkpoints: TFQ3 Metal pipelines and scratch buffers are initialized lazily (kernels.enableTfq3) only when a checkpoint contains TFQ3 files; existing FP8 and MLX 4/6/8-bit checkpoints compile no TFQ3 kernels and allocate no TFQ3 scratch memory.
  • Modular Metal kernels (zig/kernels/metal/glm_tfq3/):
    • common.metal: 2D-AffineCoset/half4 3b/4b/5b decoders, FWHT-128 transforms, fused KDA FWHT(X) + 320-row 8-bit/64 gates, and bit-exact single-row route selection (metal::precise::exp / metal::precise::divide).
    • moe_mv.metal & moe_decode.metal: B=1 and deduplicated speculative-window MoE decode kernels with zero-5b specialization on L07–44 and fused TFQ3 shared experts.
    • dense_decode.metal: Fused inv-FWHT (TG=256), zero-SRAM TG=64 no-split, and 2D SPLIT_K=8 dense decode kernels.
    • prefill.metal: Tile-scanned MoE and dense prefill kernels using nax.h (tfp::mma_16x32) with both M5 NAX and pre-M5 TF_SIMD_FRAGS (simdgroup_matrix) staging support.
  • 8-bit/64 KDA split-parts & window kernels: Adds glm_kda_parts_q8 and glm_kda_window_q8 instantiations for TFQ3 checkpoints whose small f_b/g_b gates stay in 8-bit/64.
  • Contiguous TFQ3 run merging: Merges contiguous nonmoe.tffpw tensors (KDA q/k/v, Shared gate/up, MLA q_b + indexer.wq_b) in weights.zig via tfq3.planRuns.

Verification

Local & CI Gates

  • zig fmt --check build.zig zig — passed
  • python3 tools/pr_check.py — 0 errors, 0 new lean findings (every touched source file ≤ 600 lines)
  • zig build test-glm-tfq3 — 5/5 passed (host ABI/admission/tally, contiguous run merging, synthetic dry-run loader & bad-magic refusal, M5 vs pre-M5 TF_SIMD_FRAGS source expansion, and live Metal GPU dual-mode compile + decode-vs-prefill parity)
  • zig build -Dfixed-cpu test-kernel-contract — passed (1271 registered launches, 0 missing)
  • zig build test-glm-metal-dflash-host & zig build check-glm-gather-gpu-host — passed

Apple M5 Ultra 45-Layer Verification (GLM-5.3-Flash-TFQ3)

  • zig build test-glm-tfq3 on M5 Ultra: 5/5 passed
  • Non-TFQ3 regression check (GLM_DRY=1 on GLM-5.3-Flash-MLX-4bit): 180.58 GB in buffers; 4-bit/64 x408 (unchanged)
  • Full 45-layer ReleaseFast verification (tf-glm-run + tensorfold-native serve):
Metric Raw FP8 (320 GB) MLX 4-bit (181 GB) TFQ3 (140 GB)
Disk / Buffer Size 319.76 GB 180.58 GB 139.55 GB (138.23 GB buffers)
e8_ppl NLL / PPL (146 tok) 2.8367 / 17.06 2.8858 / 17.92 2.7884 / 16.26
4-Prompt Weighted NLL / PPL (235 tok) 3.1846 / 24.16 3.2316 / 25.32 3.1184 / 22.61
p2048 Prefill — 1,400 tok/s 1,567 tok/s
Decode B=1 / B=4 (tf-glm-run) — 13.25 ms / 29.56 ms 14.44 ms / 30.68 ms
MTP depth 3 == depth 0 Bit-exact Bit-exact Bit-exact (hash e9769c136852cdbf)

ashhart added a commit that referenced this pull request Nov 24, 2026
ashhart added a commit that referenced this pull request Nov 24, 2026
ashhart added a commit that referenced this pull request Nov 25, 2026
…or a pointer, and each mapping has one owner

E332's F1 and F2, as #4953 had them fixed:
- tfq3_check.zig (std only, beside tfq3_files in the memory module) checks a shard with checked casts, sums
  and products: magic and version, the layer it must hold (layer_NN.tffpw; the MTP shard has none to
  match), 512 experts and 1,536 tensors at 640 x 2560, three in-file sections apart from each other and the
  header, and every expert's 3/4/5-bit width with its gate, up and down words and scales inside their
  sections. Records are decoded by copy, so no host pointer depends on an alignment. Refusals are named
  (Tfq3Truncated, Tfq3Overflow, Tfq3Overlap, Tfq3Geometry, Tfq3Bits, Tfq3Layer, Tfq3Table).
- tfq3_files.scan reads each present shard's header and records and checks them, and needs the table
  beside them: presence now means a checked shard, so a 16-byte sidecar no longer relaxes index admission
  or reaches construction. Admission, both budgets and the --ssd-experts refusal take its refusal.
- The loaders check the whole mapping with the same checks, reserve their lists, make their views under
  local cleanup and then hand the mapping and views over in one step that cannot fail; bytes are counted
  after. A failure unmaps once and leaves no entry for run_cleanup. Page-unaligned sections keep their copy.
- Host tests: a valid control, E332's witnesses (the 65,540-byte shard, layer 1 in layer_00, the wrapping
  offsets and counts) and each boundary, and the scan over real files. The format and its arithmetic are
  unchanged.
…ep main's paths

- Every TFQ3 file (tables, nonmoe.tffpw, layer_NN.tffpw) is checked by tfq3_check.zig before any pointer is
  formed or byte read, on the dry and live paths: checked casts, sums and products for every header, record,
  section and tensor span; 16 KiB GPU sections whose rounded views stay in the mapping; no section overlapping
  another or the header; 4/5-bit dense and 3/4/5-bit routed widths; whole 128 blocks and each tensor's and
  expert's words and scales inside its section; a layer file's index, experts and widths against the
  checkpoint; the shared table whole and finite. Refusals are named (Tfq3Truncated, Tfq3Overflow,
  Tfq3Misaligned, Tfq3Overlap, Tfq3Geometry, Tfq3Bits, Tfq3Layer, Tfq3Table). A mapping and its views pass to
  the weights in one step after room is reserved, so a failure unmaps once and leaves nothing behind.
- A checkpoint without TFQ3 files keeps main's path: the KDA step picks main's pipeline unless the layer's
  stacked input holds TFQ3 runs with 8-bit/64 gates; the q8 parts and window pipelines are built only by
  enableTfq3 (their instantiations moved to glm_tfq3/kda_q8.metal; glm_kda_parts.metal and
  glm_kda_window.metal are main's again); load_plan's stack bytes are main's formula unless a member is in
  nonmoe.tffpw.
- The shared expert folds into the routed launches on one decision (tfq3_check.sharedFusion: both shared
  projections single TFQ3 runs at the routed specialization's width, the kernels' shapes, every stage on and
  the combine fused), made in moe.zig and obeyed by the dispatcher; otherwise it runs separately.
- Dense GLU fuses [gate; up] only when up's words, scales and table follow gate's; otherwise each run goes
  through its own addresses.
- Decode at 1 and 4 rows, prefill and a repeat are compared by exact output bytes at 4 and 5 bits, with and
  without split-K, in the device's mode and (on an M5) the simdgroup mode too.
- test-glm-tfq3-host runs the file checks' refusal fixtures and the fusion, GLU and KDA rules on any host.
…w, and names a differing pair

On an M5 the test panicked "integer overflow" before its first mode: the mode loop's bound was
`1 + @intFromBool(device.tensorUnits())`, a u1 sum, so 1 + 1 overflowed (the trace's objc.zig:56 was LLVM's
merged panic site; the safe build's one integerOverflow block takes the branch right after tensorUnits()).
Pre-M5 GPUs never took it. No object is released twice. The modes are now a slice, and each run that
differs from the 16-row prefill is printed by name, mode, width and shape with its first differing output
before the test fails.
…by the plan and the loader

The planner left a named nonmoe.tffpw record out of the load's bytes by its name alone, while `stack` used
it only whole and at the model's rows and columns, falling back otherwise to ordinary tensors the plan had
not priced: a valid 128x128 lm_head record beside real 4/64 head tensors overran the buffer at take()
(E329b's R1). Now tfq3.record makes the one decision for both, asked with the same slice and shape: no record
is the ordinary tensor, a fitting record is mapped, and a present record the model cannot read whole at its
shape is refused by name (Tfq3RecordShape, Tfq3RecordSlice) before the first allocation. The head, the MTP
draft head, the non-MoE matrices and the stacks plan through it (weights.zig, load_plan.zig) and matchPart
uses it. TFQ3 files with --tp are refused by name in initLoader (Tfq3TensorParallel): a record is a whole
tensor and a rank would read only its share, so no rank's slice is ever planned one way and built another.

A full dry load of a header-only checkpoint with real-shaped 4/64 embedding and head tensors covers the
wrong-shape record (refused), no record and a fitting one (ordinary and mapped heads) and a TP2 head
(refused); recordFits' cases run on any host. The format is unchanged.
…t equals its prefill and 1-row decode equals 4-row decode
@ashhart
ashhart merged commit ed70f71 into main Nov 25, 2026
1 check failed
ashhart added a commit that referenced this pull request Nov 25, 2026
@ashhart
ashhart deleted the feat/glm-tfq3 branch November 25, 2026 03:24
ashhart added a commit that referenced this pull request Nov 25, 2026
…or a pointer, and each mapping has one owner

E332's F1 and F2, as #4953 had them fixed:
- tfq3_check.zig (std only, beside tfq3_files in the memory module) checks a shard with checked casts, sums
  and products: magic and version, the layer it must hold (layer_NN.tffpw; the MTP shard has none to
  match), 512 experts and 1,536 tensors at 640 x 2560, three in-file sections apart from each other and the
  header, and every expert's 3/4/5-bit width with its gate, up and down words and scales inside their
  sections. Records are decoded by copy, so no host pointer depends on an alignment. Refusals are named
  (Tfq3Truncated, Tfq3Overflow, Tfq3Overlap, Tfq3Geometry, Tfq3Bits, Tfq3Layer, Tfq3Table).
- tfq3_files.scan reads each present shard's header and records and checks them, and needs the table
  beside them: presence now means a checked shard, so a 16-byte sidecar no longer relaxes index admission
  or reaches construction. Admission, both budgets and the --ssd-experts refusal take its refusal.
- The loaders check the whole mapping with the same checks, reserve their lists, make their views under
  local cleanup and then hand the mapping and views over in one step that cannot fail; bytes are counted
  after. A failure unmaps once and leaves no entry for run_cleanup. Page-unaligned sections keep their copy.
- Host tests: a valid control, E332's witnesses (the 65,540-byte shard, layer 1 in layer_00, the wrapping
  offsets and counts) and each boundary, and the scan over real files. The format and its arithmetic are
  unchanged.
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.

1 participant