Skip to content

[MLX] Use scaled FP16 GEMM for packed 8da4w prefill on GPUs without NAX - #26078

Open
mergennachin wants to merge 7 commits into
gh/mergennachin/59/headfrom
gh/mergennachin/60/head
Open

mergennachin wants to merge 7 commits into
gh/mergennachin/59/headfrom
gh/mergennachin/60/head

Conversation

@mergennachin

@mergennachin mergennachin commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Use scaled FP16 matrix multiplication for group-256 packed 8da4w prefill on GPUs with Metal tensor operations and without NAX. Reconstruct the BF16-rounded activation and weight operands, normalize them by powers of two, accumulate in FP32, and restore the gain at the output. Projections whose weights cannot be represented in normal FP16 use the packed BF16 fallback.

The native MLX primitive allocates a single FP16 panel of up to 4,096 output channels per invocation. It unpacks each panel, multiplies across the full input width, and writes the corresponding columns directly to the output. Both dispatches use the same MLX command encoder, which orders reads and writes to the scratch buffer. Projection size no longer determines eligibility. The 30B gate/up projection uses 52 MiB of unpacked weights, down from 507 MiB.

At 16–64 rows the panel multiply uses 16×16 output tiles. Larger prefills use 64×64 tiles. The exported program selects the implementation on the executing device. The parent PR provides the NAX integer path. Rows below 16 use the existing decode kernels.

Test plan

  • Built the native delegate and ran all 62 exported packed-linear cases on physical M2 Ultra. The added case compares 65 rows and 4,160 channels with the TorchAO tensor subclass, exercising a full panel and a 64-channel tail. The suite also covers the cancellation witness, dynamic shapes, nonfinite rows, and positive and negative normalization exponents. All 15 CPU tests passed.
  • Timed isolated exported projections using layer-zero gate/up and down weights from the public group-256 Muse-Glimmer-30B checkpoint. Each entry is median warm latency in milliseconds on M2 Ultra. The comparison uses this PR’s previous full-weight FP16 implementation. The output checksums matched in every row.
Input tokens Gate/up, previous Gate/up, panel Down, previous Down, panel
16 3.51 3.02 2.44 2.01
256 9.12 11.17 5.62 6.59
2,048 60.05 61.86 34.39 34.87

At 2,048 tokens, the measured MLX peak allocation above the post-warmup baseline fell from 715 to 260 MiB for gate/up and from 410 to 313 MiB for down. These totals include activations and outputs.

30B serving and WikiText-2

On M2 Ultra, re-exported the public TorchAO group-256 model for MLX with off-graph cache and a 2,048-token chunk, using its resident packed checkpoint tensors. The complete 13.83 GiB PTE answered “Paris” and stopped. With five warm requests and no prefix reuse, median prefill was 327.7 tok/s for 2,048 prompt tokens, versus 335.0 at the previous PR head. Median decode was 12.6 tok/s for 32 generated tokens after a 70-token prompt, versus 12.7.

We scored the same WikiText-2 next tokens with both PTEs and CPU TorchAO eager. The table gives mean NLL.

Context Positions Previous PR head Panel CPU TorchAO eager
Short 2,016 2.263955 2.263967 2.270728
Long 3,968 1.677482 1.677488 1.680408

The two PTEs selected the same top-1 token on all 3,968 long-context positions. The sampled peak worker footprint during prefill was 4.44 GiB at the previous head and 3.81 GiB with panels.

The panel PTE is 81,024 bytes smaller than the previous PR head’s canonical export.

M5 Max measurements are historical. The earlier revision served 1,140 prefill tok/s and 30.4 decode tok/s on its NAX path. The new panel kernel was measured on M2 Ultra.

Authored with AI assistance from OpenAI Codex.

[ghstack-poisoned]
@mergennachin

mergennachin commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor Author

@pytorch-bot

pytorch-bot Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/26078

Note: Links to docs will display an error until the docs builds have been completed.

⏳ No Failures, 24 Pending

As of commit 3288119 with merge base f2d27e5 (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Dec 4, 2026
mergennachin added a commit that referenced this pull request Dec 4, 2026
Reconstruct the BF16 activation and weight operands before the dot. A power of two per token and one per weight tensor make them exactly representable in FP16. Accumulate in FP32 and restore the scales before the BF16 output cast. A projection whose weights cannot fit a single exponent shift or whose expanded weights exceed 512 MiB keeps the packed BF16 path.

A load-time branch selects this implementation for eligible prefill. NAX devices keep the existing integer GEMM, and a runtime predating the optional branch field uses the existing implementation in the same PTE.

### Test plan

The MLX packed-linear suite passed all 53 cases on M5 Max, including forced BF16 execution, subnormal weight scales, a projection too wide for one exponent shift, dynamic row counts, and the TorchAO cancellation case. Lintrunner passed.

With the public Muse-Glimmer-30B BF16 release quantized at group size 256 and exported with an off-graph KV cache, a development build on M2 Ultra served a 2,048-token prompt at a median of 326 tok/s over five warm requests. Q4_K_M with its default FP16 export reached 306 tok/s in the same setup. The 5,984 teacher-forced prefill scores from that build matched the previous packed kernel individually. The final change adds an exponent-range check and a 512 MiB temporary-weight limit. Validation of the final revision on M2 Ultra is pending.

Authored with AI assistance from OpenAI Codex.


ghstack-source-id: 431094b
ghstack-comment-id: 7422715123
Pull-Request: #26078
@mergennachin

Copy link
Copy Markdown
Contributor Author

@claude review effort=max

@claude

claude Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Claude finished @mergennachin's task in 40m 31s —— View job


Review of #26078: Request changes, because the scaled FP16 prefill becomes the default for every ≥16-row call on non-NAX Macs without a measurement against the packed BF16 prefill it replaces, and no test can show that the new kernels actually ran.

Detailed review

PR Review: #26078

Summary

For prepacked packed_8da4w_linear, this adds a non-NAX prefill that expands the INT4 weights into a power-of-two-scaled FP16 matrix and runs an FP32-accumulating FP16 GEMM. The path is selected at load through a new IfNode.use_device_nax field. It takes over every eligible call of 16 or more rows on M1–M4, and on M5 with enable_nax=false. Problems found:

  • The performance evidence covers neither short prompts nor the path being replaced.
  • The tests can't tell which branch ran, and on NAX Macs most of them never reach the new kernels.
  • enable_nax takes on a second meaning, with no opt-out.
  • The new schema field is a NAX-specific side channel.

Code Quality

  • The exactness argument depends on operations this file otherwise avoids.
    • The new kernels use plain forms: NORMALIZE_ACTIVATIONS computes s / power (packed_int4_linear_shaders.py:412) and tests isfinite(s) (:408), and the GEMM unscales with exp2(-float(SHIFT)) (:448, :463).
    • The existing kernels use precise::divide (:209, :279) and bit-pattern inf tests (:218, :238), and the new unpack kernel uses ldexp (:419).
    • Either those guards are unnecessary, or the new kernels have the problem they guard against: an inexact quotient would silently change results, and a NaN row could come out as inf.
    • The file's own idioms fit here. as_type<float>((as_type<uint>(s) & 0x007fffffu) | 0x3f800000u) is exactly s / power, the existing 0x7f800000u test can replace isfinite, and ldexp(1.f, -SHIFT) can replace exp2. Fix this →
  • Low confidence: possible int overflow in the MPP path. It indexes activations through int extents, dextents<int, 2>(K, a_shape[0]) with lhs.slice(0, m0) (:435, :441). A call where m0 * K reaches 2^31 (about 150K rows at K = 14336) would overflow. The NAX GEMM (:295) has the same limit, but this path now runs on every non-NAX Mac. Building lhs from a + size_t(m0) * K with extents (K, BM) keeps int offsets within one block.

Testing

  • On a NAX Mac, most of the new path's edge cases never reach it.
    • These configs all use disable_nax=False (test_packed_int4_linear.py:287-302), so on M5 they take the NAX chain:
      • DynamicPrefillMatrixTest (dynamic and padded rows)
      • NonfinitePrefillTest (the NaN gain)
      • cls((2, 65), 192, 10) (3-D input)
      • cls(16) (the threshold)
    • Only cls(65, 192, 10, disable_nax=True) and ScaledWeightRangeTest run the scaled kernels there.
    • The M5 Max results in the description reproduce the parent's scores, so they ran the NAX chain too. M2 Ultra validation of the final revision is still pending.
    • Fix: add disable_nax=True variants of those configs. NonfinitePrefillTest and DynamicPrefillMatrixTest need to accept the flag. Fix this →
  • No test can show which chain ran.
    • With disable_nax=True or on a non-NAX Mac, compare_with_actual (:351-360) checks against the eager golden. The packed BF16 prefill in the existing chain matches that golden too.
    • expected_node_counts counts the serialized nodes of both chains, not the ones that executed.
    • So if bind_nax_capability stopped rewriting cond, every test would still pass while the scaled kernels never ran.
    • Fix: add a check that fails when the wrong branch runs. For example, a runtime test could load an IfNode with use_device_nax whose branches produce different values, then check the output with enable_nax on and off. Fix this →
  • ScaledWeightRangeTest can't fail on its small-activation row. x[5] *= 2**-20 also hits the 2**-24 token-scale clamp. That row's outputs lie between about 1e-11 and 1e-6, far below atol = 2e-5 (:268), so any result passes, including all zeros. Channel 2+ outputs on ordinary rows are mostly near 1e-5, so they're only loosely checked. Use a per-row tolerance, or compare row 5 after multiplying it back by 2**20. Fix this →
  • Untested cases:
    • A negative SHIFT, which happens whenever a reconstructed weight is 2^16 or more. It's also the only case that puts a negative template value into a kernel name.
    • The 512 MiB fallback (packed_int4_linear.py:252).
    • The boundaries of _normal_fp16_shift: lo == hi, all-zero weights, scale == 0 groups, and offsets where a code reconstructs exactly zero. The function is plain tensor math, so a CPU unit test would cover it. Fix this →

API Design

  • enable_nax now also picks between two non-NAX prefill implementations, and there's no way to choose the old one.
    • bind_nax_capability sets cond to enable_nax && has_nax (MLXBackend.cpp:80-84), so "no NAX" and "NAX disabled" both take the scaled chain.
    • On a new runtime, the packed BF16 prefill never runs for weights that pass the shift and size checks.
    • The scaled chain writes a transient FP16 copy of the projection (up to 512 MiB) on every call of 16 or more rows.
    • If that's slower or runs out of memory for some model, shape, or macOS version, the only way back is to re-export or use an older runtime.
    • backend_options.h:22-24 mentions none of this. Either document it there and in the module docstring (packed_int4_linear.py:22-23), or give the scaled path its own load option. Fix this →
  • IfNode.use_device_nax (schema.fbs:1036-1038) puts a device-capability flag on a generic control-flow node in a serialized format.
    • It's a second side channel for the same capability, next to the reserved ET_MLX_DEVICE_HAS_NAX template-argument name. The next capability would need another bool.
    • When the flag is set, the documentation of cond (:1033, "nonzero -> then_chain") no longer says what the runtime does.
    • The name reads as "use NAX" rather than "replace cond", and "per-model NAX setting" leaves out the device check.
    • Old runtimes ignore any unknown trailing field, so an enum would keep the same fallback and leave room for other capabilities. For example: cond_source: CondSource = Serialized, with a DeviceNax value.

Performance

  • The scaled path runs for every call of 16 or more rows.
    • nonempty() sends rows // 16 straight to _select_prefill (packed_int4_linear.py:429-436). Its only other checks are the exponent range and the 512 MiB limit, even though the comment at :250 says expanding the weights "pays off for long prompts".
    • For one 64-row block, the new path moves about 4.5 bytes per weight: it reads 0.5 B of codes, writes 2 B of FP16, and reads those 2 B back in the GEMM. The packed prefill it replaces moves about 0.5 B.
    • So short prompts and speculative verify blocks are likely slower on M1–M4, and on M5 with enable_nax=false. DFlash defaults to block_size = 16 (examples/models/muse-glimmer/model/dflash_model.py:67).
    • Low confidence, unmeasured: before macOS 26, PACKED_INT4_MPP is undefined and the GEMM falls back to a per-output SIMD dot, so the expansion gains no matrix throughput there.
    • The description's only non-NAX number is a single 2,048-token prompt. It comes from a development build that predates the final revision, and it's compared with Q4_K_M rather than the parent's packed prefill.
    • Fix: measure both paths on a non-NAX Mac across row counts. Gate the scaled branch on a row threshold taken from those measurements, falling back to prefill. Fix this →
  • Each distinct (N, K, SHIFT) compiles its own cooperative-tensor GEMM.
    • SHIFT is a template argument of the MPP GEMM (packed_int4_linear.py:245), and MLX puts template values in the kernel name.
    • The shift depends on each tensor's smallest nonzero weight, so same-shaped projections in different layers can each pay for a compile on first use.
    • Fix: fold 2^-SHIFT into gain in the normalize kernel, so the GEMM is keyed on (N, K) alone. The folded factor is still an exact power of two, and the normalize kernel is cheap to specialize. Fix this →
  • Static-shape exports stop freeing main-chain temporaries after their last use.
    • With literal rows, emit_if_else folds both outer branches, so before this PR a static prefill of 16 or more rows emitted no IfNode. _select_prefill now always emits one into the caller's chain (:263-270).
    • compute_temp_last_use skips any chain that contains an IF (MLXExecutor.h:245-246, :273-281). This happens at load, so NAX devices are affected too.
    • Dynamic-row exports already had IFs in the main chain, so they're unaffected.
    • Fix, either way: splice the selected chain into its parent once bind_nax_capability has bound cond, or have compute_temp_last_use treat an IF as a use of everything its branches touch. Fix this →

Specific Comments

  • packed_int4_linear.py:17 - "wide prefill" suggests the wide kernel, which handles 4–15 rows. This path starts at 16.
  • packed_int4_linear.py:185 - the docstring says the function finds a power of two, but it returns an exponent, or None when no shift fits.
  • packed_int4_linear.py:251 - "including for larger user-provided projections" doesn't say what it adds to the bound.
  • packed_int4_linear.py:259 - the chain named portable is the one old runtimes never take. schema.fbs:1037 calls the serialized cond, which selects existing, the "portable default". schema.fbs:1065 uses "portable" for the NAX-false kernel variant. Naming the chain scaled would avoid the clash.
  • packed_int4_linear.py:261-262 - "device-independent" isn't true on runtimes that bind ET_MLX_DEVICE_HAS_NAX, because there the existing chain's prefill kernels are rebound per device.
  • packed_int4_linear_shaders.py:394-395 - the values being normalized are the reconstructed INT8 activations bf16(code * s), not arbitrary BF16 activations. The "factor of 127" only holds for those.
  • packed_int4_linear_shaders.py:422 - the BF16 source weight isn't subnormal. It's below FP16's normal range.
  • packed_int4_linear_shaders.py:458 - float4 x shadows the kernel input x.
  • MLXBackend.cpp:73 - the deleted comment was the only note on what a runtime without this binding does with the serialized template value, and it's still accurate.

Recommendation

Request Changes

Two things block approval:

  • The default prefill on every non-NAX Mac changes without a measurement against the path it replaces, at either short or long row counts.
  • The tests would pass even if the scaled kernels never ran.

Settle the enable_nax contract and the IfNode field before PTEs start carrying the field.

[ghstack-poisoned]
mergennachin added a commit that referenced this pull request Dec 4, 2026
Reconstruct the BF16 activation and weight operands before the dot. A power of two per token and one per weight tensor make them exactly representable in FP16. Accumulate in FP32 and restore the scales before the BF16 output cast. A projection whose weights cannot fit a single exponent shift or whose expanded weights exceed 512 MiB keeps the packed BF16 path.

A load-time branch selects this implementation for eligible prefill. NAX devices keep the existing integer GEMM, and a runtime predating the optional branch field uses the existing implementation in the same PTE.

The Apple paravirtual GPU on hosted macOS runners rejects Metal cooperative tensors at pipeline creation. On this device, the delegate supplies a shader macro and the packed linear uses its SIMD fallback.

### Test plan

The MLX packed-linear suite passed all 53 cases on M5 Max, including forced BF16 execution, subnormal weight scales, a projection too wide for one exponent shift, dynamic row counts, and the TorchAO cancellation case. Lintrunner passed.

With the public Muse-Glimmer-30B BF16 release quantized at group size 256 and exported with an off-graph KV cache, a development build on M2 Ultra served a 2,048-token prompt at a median of 326 tok/s over five warm requests. Q4_K_M with its default FP16 export reached 306 tok/s in the same setup. The 5,984 teacher-forced prefill scores from that build matched the previous packed kernel individually. The final change adds an exponent-range check and a 512 MiB temporary-weight limit. Validation of the final revision on M2 Ultra is pending.

All 53 focused cases also passed with the paravirtual path forced on M5 Max, including the reference cancellation cases.

Authored with AI assistance from OpenAI Codex.

ghstack-source-id: edd471d
ghstack-comment-id: 7422715123
Pull-Request: #26078
[ghstack-poisoned]
mergennachin added a commit that referenced this pull request Dec 4, 2026
For group-256 packed 8da4w linear, make an FP32-accumulating FP16 matrix multiply the default for eligible prefill on GPUs without NAX. Reconstruct the BF16 activation and weight operands with exact power-of-two shifts before the multiply. Weights whose exponents do not fit FP16, and projections requiring more than 512 MiB of temporary weight storage, keep the existing BF16 dot.

Read the delegate's existing NAX template argument once at model load. An ordinary MLX graph branch selects the preparation and GEMM together, so NAX GPUs keep their integer kernel without allocating dense FP16 weights. Single-token decode uses the existing packed linear. The fallback Metal kernels use an explicit threadgroup FP32 accumulator tile.

### Test plan

- All 53 exported packed-linear cases passed on M5 Max, including with NAX disabled. Coverage includes TorchAO cancellation, BF16 exponent boundaries, dynamic shapes, and padded rows. Lintrunner passed.
- The public Muse-Glimmer-30B BF16 checkpoint, quantized with group size 256 and exported with off-graph KV cache, served at 1,093 tok/s on M5 Max (median of five warm requests, 2,048 prompt tokens). On the same device all 3,968 long-context WikiText-2 position scores matched the previous export exactly. The same PTE ran with the parent delegate.
- Physical M2 Ultra and hosted Metal results for this revision are pending.

Authored with AI assistance from OpenAI Codex.

ghstack-source-id: f1e0391
ghstack-comment-id: 7422715123
Pull-Request: #26078
[ghstack-poisoned]
mergennachin added a commit that referenced this pull request Dec 4, 2026
Use an FP16 matrix multiply with FP32 accumulation for group-256 packed 8da4w prefill when Metal tensor operations are available and the integer NAX kernel is disabled or unavailable. Both operands retain TorchAO’s BF16 rounding. Power-of-two normalization makes the operands exactly representable in normal FP16. A projection whose weight range cannot be represented, or whose unpacked weights would exceed 512 MiB, uses the packed BF16 kernel.

At 16 or more rows the Metal shader selects the matrix implementation at model load. Static prefill exports contain no control-flow node, so the executor can release temporaries at last use. The capability flag sizes the activation and weight scratch. The NAX and older Metal paths reserve only one unused weight row. The scaled GEMM can reuse the same compiled kernel for weights of the same shape with different exponent shifts. Single-token decode uses the existing packed linear.

### Test plan

- The exported-PTE suite passed 61/61 on M5 Max, again on M5 Max with NAX forced off, and on physical M2 Ultra. It covers TorchAO operand rounding, forced NAX opt-out at 16 rows, rank-three and dynamic inputs, nonfinite rows, and both signs of weight shift. A test that tags the running scaled shader fails if the exporter bypasses it (observed 256, expected 512). Zeroing the tiny-activation row also fails its reference comparison.
- All 15 CPU packed-linear tests passed, including the exact 512 MiB cutoff, zero-scale groups, and a range with exactly one valid exponent. Lintrunner and the hosted Metal 4 job passed on this revision. [CI run](https://github.com/pytorch/executorch/actions/runs/47430902642/job/145384007095)
- On physical M2 Ultra, each projection was exported with this change and its immediate parent and timed using identical inputs. The table shows median warm operator latency in milliseconds. Gate/up and down use layer-zero weights from the public group-256 TorchAO 30B checkpoint. The small projection has 64 outputs and 256 inputs.

| Input rows | Gate/up parent → PR | Down parent → PR | Small parent → PR |
| ---: | ---: | ---: | ---: |
| 16 | 8.01 → 3.41 | 4.18 → 2.14 | 0.303 → 0.255 |
| 64 | 8.16 → 3.48 | 4.31 → 2.20 | 0.296 → 0.269 |
| 256 | 27.73 → 8.93 | 16.41 → 5.52 | 0.326 → 0.285 |
| 2,048 | 214.20 → 59.48 | 111.50 → 34.16 | 0.354 → 0.328 |

### Public 30B serving and WikiText-2

On this revision the public Muse-Glimmer-30B group-256 TorchAO checkpoint exported for MLX with off-graph cache and a 2,048-token chunk. The M5 Max server answered “Paris” and stopped. Median warm prefill was **1,140 tok/s** for 2,048 prompt tokens; decode was **30.4 tok/s** for 32 generated tokens after a 70-token prompt. Each median covers five requests with no prefix reuse. The parent measured 1,120 and 30.4 tok/s respectively under the same protocol. Both revisions use the integer prefill path on this machine.

All **5,984** WikiText-2 next-token scores matched the previous M5 export exactly. Mean NLL was 2.272821 for 2,016 short-window positions and 1.683505 for 3,968 long-context positions. CPU TorchAO eager was 2.270728 and 1.680408 respectively. The canonical export size was 13.83 GiB. To share disk space between the model copies, validation relocated the serialized PTE segments and verified every segment against the exporter before running the native worker.

The M2 Ultra operator measurements above are from this revision. An earlier full-model M2 Ultra run measured 325.54 tok/s prefill and 12.65 tok/s decode, compared with 305.65 and 27.90 for Q4_K_M.

Authored with AI assistance from OpenAI Codex.

ghstack-source-id: e431616
ghstack-comment-id: 7422715123
Pull-Request: #26078
[ghstack-poisoned]
mergennachin added a commit that referenced this pull request Dec 4, 2026
Use an FP16 matrix multiply with FP32 accumulation for group-256 packed 8da4w prefill on GPUs that support Metal tensor operations and lack NAX. Both operands retain TorchAO’s BF16 rounding. Power-of-two normalization makes the operands exactly representable in normal FP16. A projection whose weight range cannot be represented, or whose unpacked weights would exceed 512 MiB, uses the packed BF16 kernel.

At 16 or more rows the Metal shader selects the matrix implementation at model load. Static prefill exports contain no control-flow node, so the executor can release temporaries at last use. The capability flag sizes the activation and weight scratch. The NAX and older Metal paths reserve only one unused weight row. The scaled GEMM can reuse the same compiled kernel for weights of the same shape with different exponent shifts. Single-token decode uses the existing packed linear.

### Test plan

- The exported-PTE suite passed 61/61 on M5 Max and physical M2 Ultra. The production PTE selects its kernel from the device capability. A test-only PTE fixes the same shader’s specialization to exercise the scaled path on M5. It covers TorchAO operand rounding, the forced fallback fixture at 16 rows, rank-three and dynamic inputs, nonfinite rows, and both signs of weight shift. A test that tags the running scaled shader fails if the exporter bypasses it (observed 256, expected 512). Zeroing the tiny-activation row also fails its reference comparison.
- All 15 CPU packed-linear tests passed, including the exact 512 MiB cutoff, zero-scale groups, and a range with exactly one valid exponent. Lintrunner passed. The hosted Metal 4 job passed on the earlier revision. [CI run](https://github.com/pytorch/executorch/actions/runs/47430902642/job/145384007095)
- On physical M2 Ultra, each projection was exported with this change and its immediate parent and timed using identical inputs. The table shows median warm operator latency in milliseconds. Gate/up and down use layer-zero weights from the public group-256 TorchAO 30B checkpoint. The small projection has 64 outputs and 256 inputs.

| Input rows | Gate/up parent → PR | Down parent → PR | Small parent → PR |
| ---: | ---: | ---: | ---: |
| 16 | 8.01 → 3.41 | 4.18 → 2.14 | 0.303 → 0.255 |
| 64 | 8.16 → 3.48 | 4.31 → 2.20 | 0.296 → 0.269 |
| 256 | 27.73 → 8.93 | 16.41 → 5.52 | 0.326 → 0.285 |
| 2,048 | 214.20 → 59.48 | 111.50 → 34.16 | 0.354 → 0.328 |

### Public 30B serving and WikiText-2

For the earlier serving measurements, the public Muse-Glimmer-30B group-256 TorchAO checkpoint was exported for MLX with off-graph cache and a 2,048-token chunk. The M5 Max server answered “Paris” and stopped. Median warm prefill was **1,140 tok/s** for 2,048 prompt tokens; decode was **30.4 tok/s** for 32 generated tokens after a 70-token prompt. Each median covers five requests with no prefix reuse. The parent measured 1,120 and 30.4 tok/s respectively under the same protocol. Both revisions use the integer prefill path on this machine.

On this revision the runtime replayed that PTE. All **5,984** WikiText-2 next-token scores matched the previous M5 export exactly. Mean NLL was 2.272821 for 2,016 short-window positions and 1.683505 for 3,968 long-context positions. CPU TorchAO eager was 2.270728 and 1.680408 respectively. The canonical export size was 13.83 GiB. To share disk space between the model copies, validation relocated the serialized PTE segments and verified every segment against the exporter before running the native worker.

The M2 Ultra operator measurements above used the same kernel on the earlier revision. An earlier full-model M2 Ultra run measured 325.54 tok/s prefill and 12.65 tok/s decode, compared with 305.65 and 27.90 for Q4_K_M.

Authored with AI assistance from OpenAI Codex.

ghstack-source-id: d36078a
ghstack-comment-id: 7422715123
Pull-Request: #26078
@mergennachin
mergennachin marked this pull request as draft December 4, 2026 22:54
@mergennachin
mergennachin marked this pull request as ready for review December 4, 2026 23:02
scale. The BF16 path rounds the reconstructed activations and weights before the
dot. On NAX GPUs, at least 16 rows and constant group-256 weights with N divisible
dot. On GPUs without NAX, Metal tensor operations enable scaled FP16 prefill
with up to 512 MiB of temporary weight storage.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why we have 512 MB contraint?

[ghstack-poisoned]
mergennachin added a commit that referenced this pull request Dec 5, 2026
Use scaled FP16 matrix multiplication for group-256 packed 8da4w prefill on GPUs with Metal tensor operations and without NAX. Reconstruct the BF16-rounded activation and weight operands, normalize them by powers of two, accumulate in FP32, and restore the gain at the output. Projections whose weights cannot be represented in normal FP16 use the packed BF16 fallback.

The native MLX primitive allocates a single FP16 panel of up to 4,096 output channels per invocation. It unpacks each panel, multiplies across the full input width, and writes the corresponding columns directly to the output. Both dispatches use the same MLX command encoder, which orders reads and writes to the scratch buffer. Projection size no longer determines eligibility. The 30B gate/up projection uses 52 MiB of unpacked weights, down from 507 MiB.

At 16–64 rows the panel multiply uses 16×16 output tiles. Larger prefills use 64×64 tiles. The exported program selects the implementation on the executing device. The parent PR provides the NAX integer path. Rows below 16 use the existing decode kernels.

### Test plan

- Built the native delegate and ran all 62 exported packed-linear cases on physical M2 Ultra. The added case compares 65 rows and 4,160 channels with the TorchAO tensor subclass, exercising a full panel and a 64-channel tail. The suite also covers the cancellation witness, dynamic shapes, nonfinite rows, and positive and negative normalization exponents. All 15 CPU tests passed.
- Timed isolated exported projections using layer-zero gate/up and down weights from the public group-256 Muse-Glimmer-30B checkpoint. Each entry is median warm latency in milliseconds on M2 Ultra. The comparison uses this PR’s previous full-weight FP16 implementation. The output checksums matched in every row.

| Input tokens | Gate/up, previous | Gate/up, panel | Down, previous | Down, panel |
| ---: | ---: | ---: | ---: | ---: |
| 16 | 3.51 | 3.02 | 2.44 | 2.01 |
| 256 | 9.12 | 11.17 | 5.62 | 6.59 |
| 2,048 | 60.05 | 61.86 | 34.39 | 34.87 |

At 2,048 tokens, the measured MLX peak allocation above the post-warmup baseline fell from 715 to 260 MiB for gate/up and from 410 to 313 MiB for down. These totals include activations and outputs.

### 30B serving and WikiText-2

On M2 Ultra, re-exported the public TorchAO group-256 model for MLX with off-graph cache and a 2,048-token chunk, using its resident packed checkpoint tensors. The complete 13.83 GiB PTE answered “Paris” and stopped. With five warm requests and no prefix reuse, median prefill was **327.7 tok/s** for 2,048 prompt tokens, versus **335.0** at the previous PR head. Median decode was **12.6 tok/s** for 32 generated tokens after a 70-token prompt, versus **12.7**.

We scored the same WikiText-2 next tokens with both PTEs and CPU TorchAO eager. The table gives mean NLL.

| Context | Positions | Previous PR head | Panel | CPU TorchAO eager |
| --- | ---: | ---: | ---: | ---: |
| Short | 2,016 | 2.263955 | 2.263967 | 2.270728 |
| Long | 3,968 | 1.677482 | 1.677488 | 1.680408 |

The two PTEs selected the same top-1 token on all 3,968 long-context positions. The sampled peak worker footprint during prefill was 4.44 GiB at the previous head and 3.81 GiB with panels.

The panel PTE is 81,024 bytes smaller than the previous PR head’s canonical export.

M5 Max measurements are historical. The earlier revision served 1,140 prefill tok/s and 30.4 decode tok/s on its NAX path. The new panel kernel was measured on M2 Ultra.

Authored with AI assistance from OpenAI Codex.

ghstack-source-id: a4f59d2
ghstack-comment-id: 7422715123
Pull-Request: #26078

This branch is being deployed

1 in progress deployment
cadence — 32881198 Deployed Dec 5, 2026 by mergennachin via hifi1s-op-test / hifi1s #42466
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants