Repository navigation
[MLX] Use scaled FP16 GEMM for packed 8da4w prefill on GPUs without NAX - #26078
mergennachin wants to merge 7 commits into
Conversation
[ghstack-poisoned]
🔗 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 PendingAs of commit 3288119 with merge base f2d27e5 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
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
|
@claude review effort=max |
|
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 reviewPR Review: #26078SummaryFor prepacked
Code Quality
Testing
API Design
Performance
Specific Comments
RecommendationRequest Changes Two things block approval:
Settle the |
[ghstack-poisoned]
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]
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]
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]
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
| 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. |
There was a problem hiding this comment.
why we have 512 MB contraint?
[ghstack-poisoned]
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
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
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.
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.