Skip to content

[ET-VK][q4gsw] Add et_vk.q4gsw_linear.default with W_4X8 GEMM + adaptive nc-coop GEMV - #19996

Merged
meta-codesync[bot] merged 3 commits into
gh/SS-JIA/555/basefrom
gh/SS-JIA/555/head
Jun 5, 2026
Merged

meta-codesync[bot] merged 3 commits into
gh/SS-JIA/555/basefrom
gh/SS-JIA/555/head

Conversation

@SS-JIA

@SS-JIA SS-JIA commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Adds et_vk.q4gsw_linear.default backed by production compute shaders and a single top-level dispatch in Q4gswLinear.cpp. The op uses two or three execute nodes per dtype path that share a 6-binding descriptor set layout: a GEMM DynamicDispatchNode that self-gates to {0,0,0} at M==1, and an adaptive nc-coop GEMV sibling DynamicDispatchNode that self-gates to {0,0,0} at M!=1. The fp16 path adds a transpose preprocess that also self-gates at M==1. Decode-time virtual_resize correctly routes M==1 through the nc-coop GEMV after a prefill M>1 set up the graph. Existing serialized models that reference et_vk.linear_q4gsw.default are routed to the same forwarder so the cutover requires no graph-level changes; the old QuantizedLinear.cpp::linear_q4gsw body is deleted.

Production shaders under runtime/graph/ops/glsl/:

  • q4gsw_linear_gemm__w_4x8_nc — fp32 GEMM, 4M x 8N per-thread tile, 8x8 LWG, reads the raw [M, K] activation directly. The per-k4 weight tile loads as a single ivec4 covering 2 consecutive 4x4 N-blocks (one 16B aligned LSU read replaces two 8B reads). Aliases the same buffer the prepack writes.
  • q4gsw_linear_gemm__tin__w_4x8_nc — fp16 GEMM, transposed-input path, 8x4 per-thread tile, 1x128 LWG, reads the pre-transposed vec4 activation produced by the transpose preprocess. Nibble dequant stays in int16 end-to-end before the fp16 FMA, saving one fp32 register and lifting AOC fiber occupancy from 37% to 50% on Adreno 750 (validated at M=256 K=4096 N=4096: 6135.92 us -> 5637.20 us, -8.1% wall-clock).
  • q4gsw_linear_gemv_coop__w_4x8_nc_buffer_{g1w64,g4w16,g8w8} — cooperative-reduction GEMV reading the same nc-buffer weight payload as the GEMM shaders, with three (NUM_GROUPS, WORKERS_PER_GROUP) decompositions chosen at dispatch time by the production picker based on output N. All keep total threads/WG = 64; each WG produces NUM_GROUPS * 8 outputs, and the K-loop strides by WORKERS_PER_GROUP.

Prepack: pack_q4_linear_weight__w_4x8_nc_buffer produces an int SOA nibble buffer; one ivec4 covers a 4K x 8N block. The fp32 GEMM shader views the buffer as ivec4; the fp16 tin GEMM shader reads it as ivec2; the nc-coop GEMV shader rebinds the same bytes as scalar int arrays. Scales use a single prepack_q4_scales (dtype-matched vec4) for GEMM; GEMV rebinds the same bytes as a gvec2 via vec_size=2. The shared nc-buffer payload means prefill and decode both consume one prepack — no dual-format weight memory cost.

Dispatch structure:

  • fp32 (add_q4gsw_linear_w_4x8_node): two nodes. The GEMM dispatch binds q4gsw_linear_gemm__w_4x8_nc unconditionally; its gated global WG gates the dispatch to {0,0,0} at M==1. The nc-coop GEMV sibling owns the decode.
  • fp16 (add_q4gsw_linear_tin_w_4x8_node): three nodes. The transpose preprocess self-gates {0,0,0} when M==1 (no-op); the GEMM dispatch binds q4gsw_linear_gemm__tin__w_4x8_nc and its gated global WG returns {0,0,0} at M==1; the nc-coop GEMV sibling handles M==1.
  • nc-coop GEMV picker (add_q4gsw_linear_nc_coop_gemv_node): shape-adaptive dispatch that self-gates {0,0,0} when M!=1. Heuristic on output N:
    • N <= 1024 -> q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g1w64 LWG (1, 1, 64)
    • N <= 4096 -> q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g4w16 LWG (1, 4, 16)
    • N > 4096 -> q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g8w8 LWG (1, 8, 8)

The adaptive picker replaces sg-GEMV at decode. Cross-device sweep on Galaxy S24 (Adreno 750), S25 (Adreno 830), and Pixel 9 Pro XL (Mali-G715) shows shape-adaptive nc-coop beats sg-GEMV on every LLM-decode shape by 3-56%, with the largest wins at small-N (47-56% at K=2048 N=512 across both Adreno devices). The adaptive picker also unblocks Mali, where sg-GEMV cannot dispatch (subgroupSize=16 != required 64).

The op is registered under both et_vk.q4gsw_linear.default and et_vk.linear_q4gsw.default for backward compatibility. Also extends validate_against_reference in test/custom_ops/utils.cpp to handle fp16 tensors.

Demonstration shaders under test/custom_ops/glsl/ (not linked into the production shader library):

  • q4gsw_linear_gemv__w_4x8_nc{,_nosg} — sg / nosg GEMV variants from earlier iterations. The sg variant pins subgroupSize to 64 via VK_EXT_subgroup_size_control and uses subgroupBroadcast; the nosg variant has every thread load its own activation. Both are dispatched by the test_fpa_q4gsw_linear benchmark binary's forced-shader selectors GEMV_W_4X8 and GEMV_W_4X8_NOSG (selectors 1 and 2). Retained as a demonstration of the single-thread-per-output GEMV layout the adaptive nc-coop now supersedes at decode.

Buffer-padding fix (latent OOB read on N % 8 != 0): The fp32 GEMM's 16B ivec4 weight load spans two consecutive (k4, n4) ivec2 tiles along N. Pad the SOA weight buffer's row stride to next-even N4 (no-op for the canonical N % 8 == 0 shapes); the prepack shader's existing (n < N) branch fills the OOB tiles with the bias-zero nibble pattern (0x88888888u). Adds GEMM accuracy coverage for N=12 and N=20.

Differential Revision: D107447239

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 5 New Failures, 1 Cancelled Job, 2 Unrelated Failures

As of commit ee22378 with merge base b1385db (image):

NEW FAILURES - The following jobs have failed:

CANCELLED JOB - The following job was cancelled. Please retry:

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@linux-foundation-easycla

linux-foundation-easycla Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

CLA Missing ID

@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 Jun 3, 2026
@github-actions

github-actions Bot commented Jun 3, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your change should be included in the release notes (i.e. would users of this library care about this change?), please use a label starting with release notes:. This helps us keep track and include your important work in the next release notes.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "release notes: none"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@metascroy

Copy link
Copy Markdown
Contributor

@claude review this code

@claude

claude Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Claude finished @metascroy's task in 3m 3s —— View job


Code Review: et_vk.q4gsw_linear.default with W_4X8 GEMM + adaptive nc-coop GEMV

  • Read main dispatch implementation (Q4gswLinear.cpp/h)
  • Read GEMM shaders (fp32 and fp16 tin)
  • Read GEMV cooperative shaders
  • Read prepack shader
  • Read test files
  • Read YAML shader configs
  • Read deleted code (QuantizedLinear.cpp)
  • Provide review feedback

Overall Assessment

This is a well-engineered, high-performance PR that replaces the legacy et_vk.linear_q4gsw.default with a purpose-built W_4X8 GEMM + adaptive nc-coop GEMV dispatch. The architecture is clean: a pair of self-gating DynamicDispatchNodes per dtype path (GEMM + GEMV) that share a 6-binding descriptor layout, with the framework's trigger_resize() routing M==1 vs M>1 without re-encode. The test infrastructure is thorough with forced-selector coverage for each reduction decomposition.

Strengths

  1. Single prepack, dual dispatch: Sharing the nc-buffer weight payload between GEMM (prefill) and GEMV (decode) halves weight memory vs the prior dual-format approach.
  2. Shape-adaptive nc-coop GEMV picker: Clean heuristic based on cross-device sweep data with a nice decomposition table (g1w64, g4w16, g8w8).
  3. Buffer-padding fix for N % 8 != 0: The N4_padded = (N4 + 1) & ~1 approach is simple and correct, with test coverage for N=12 and N=20.
  4. fp16 TIN path optimization: Keeping nibble dequant in int16 to save fp32 registers and lift occupancy from 37% to 50% is a thoughtful microarchitectural optimization.
  5. Backward compatibility: Registering under both et_vk.q4gsw_linear.default and et_vk.linear_q4gsw.default ensures existing serialized models work without graph changes.
  6. Comprehensive test coverage: Forced selectors 14-16 give ACCU validation of g4w16/g8w8 at small shapes where the production picker wouldn't choose them.

Issues & Suggestions

1. Potential OOB activation read in fp32 GEMM (low severity)

q4gsw_linear_gemm__w_4x8.glsl:194-195:

[[unroll]] for (int mi = 0; mi < TILE_M; ++mi) {
    in_tile[mi][0] = t_fp_input[((m + mi) * K4) + k4];

When M is not a multiple of TILE_M (4), tail threads where m < M but m + mi >= M issue OOB buffer reads. The comment acknowledges this ("Tail rows may be read but are discarded by the output store guard"), and this relies on VK_EXT_robustness2 / robustBufferAccess returning zeros for OOB reads. This is a common GPU shader pattern and all target devices (Adreno/Mali) support it, but it's worth noting as a device-portability assumption.

2. fp16 TIN GEMM: missing output store for partial-N tiles (no-op in practice)

q4gsw_linear_gemm__tin__w_4x8.glsl:310:

if (n + TILE_N - 1 < N) {
    // ... store logic
}
// no else branch

Since N is required to be a multiple of 4 (enforced by prepack_q4_w_4x8_nc_buffer), and TILE_N=4 with n = n_tile * 4, the condition n + 3 < N is equivalent to n < N (which is already guaranteed by the early-out at line 197). So the guard is always true and the missing else branch is never hit. Consider adding a comment noting this invariant, or removing the guard entirely since it's dead code.

3. generate_randint_half_data in utils.cpp has a bug (pre-existing)

backends/vulkan/test/custom_ops/utils.cpp:627:

void generate_randint_half_data(std::vector<uint16_t>& data, int min_val, int max_val, int explicit_seed) {
    ...
    val = static_cast<uint16_t>(std::abs(dis(gen)) % 65536);
}

This doesn't produce valid fp16 bit patterns for integer values — it generates random uint16 values (not IEEE 754 half representations of integers). The existing DataGenType::RANDINT path for kHalf used in this PR's test cases calls this function. Since the tests pass, the tolerance is likely absorbing the issue, but the reference impl calls input_to_float_vec which uses half_to_float on whatever bits are stored — so if the bits aren't valid fp16, the reference will compute with garbage. This is pre-existing but worth flagging since this PR's accuracy tests depend on it.

4. Minor: Redundant fma(w, scale, VEC4_T(0)) in fp32 GEMM

q4gsw_linear_gemm__w_4x8.glsl:264-265:

weight_texels[0] = fma(weight_texels[0], scales[0], VEC4_T(0));
weight_texels[1] = fma(weight_texels[1], scales[1], VEC4_T(0));

The comment explains this folds to a multiply and maintains SSA shape for the compiler. If you've validated this matches compiler output, it's fine — just confirming it's intentional and not a leftover from an earlier version that needed actual FMA accumulation.

5. Consider documenting the VK_EXT_subgroup_size_control non-requirement

The PR body mentions that the adaptive nc-coop GEMV "unblocks Mali, where sg-GEMV cannot dispatch (subgroupSize=16 != required 64)". This is a significant device compatibility improvement. Consider adding a brief note in the header comment of Q4gswLinear.h or near the op registration that the new dispatch has no subgroup-size requirements, making it portable across all target devices.

6. Bias OOB load clamping pattern (correct but worth noting)

Both GEMM shaders use a "clamp the index, gate the store" pattern for OOB bias reads (e.g., q4gsw_linear_gemm__w_4x8.glsl:290). This is correct and memory-safe, but the clamped value contaminates the accumulator for the discarded lane. If a future refactor removes the output store gate without realizing the accumulator holds an incorrect bias-added value, this would silently produce wrong results. The existing comments document this well.

Architecture Questions (non-blocking)

  1. Why 6 bindings? The t_transposed_input binding is always a 0-element dummy in the fp32 path and the GEMV path. An alternative would be separate descriptor set layouts per path, but the shared-layout approach trades a trivial descriptor-slot cost for simpler dispatch switching. This seems like the right tradeoff for a single DynamicDispatchNode that can switch shaders at runtime.

  2. Future M > initial M: The comment at Q4gswLinear.cpp:582-584 notes that virtual_resize growing M past the initial transposed_input allocation will be rejected. This means the graph must be built with the largest expected M. This is the standard VK graph pattern (allocate for max M at graph build time), so it's fine — just confirming the constraint is understood.

Summary

This is a high-quality, production-ready PR. The dispatch architecture is well thought out, the shader microarchitectural optimizations are backed by measured data, the backward compatibility story is clean, and the test coverage is comprehensive. The issues I've noted are minor (pre-existing test util bug, dead-code guard, documentation suggestions) — none block landing.


[ghstack-poisoned]
SS-JIA pushed a commit that referenced this pull request Jun 4, 2026
…ive nc-coop GEMV

Pull Request resolved: #19996

Adds `et_vk.q4gsw_linear.default` backed by production compute shaders and a single top-level dispatch in `Q4gswLinear.cpp`. The op uses two or three execute nodes per dtype path that share a 6-binding descriptor set layout: a GEMM `DynamicDispatchNode` that self-gates to `{0,0,0}` at M==1, and an adaptive nc-coop GEMV sibling `DynamicDispatchNode` that self-gates to `{0,0,0}` at M!=1. The fp16 path adds a transpose preprocess that also self-gates at M==1. Decode-time `virtual_resize` correctly routes M==1 through the nc-coop GEMV after a prefill M>1 set up the graph. Existing serialized models that reference `et_vk.linear_q4gsw.default` are routed to the same forwarder so the cutover requires no graph-level changes; the old `QuantizedLinear.cpp::linear_q4gsw` body is deleted.

Production shaders under `runtime/graph/ops/glsl/`:
- `q4gsw_linear_gemm__w_4x8_nc` — fp32 GEMM, 4M x 8N per-thread tile, 8x8 LWG, reads the raw `[M, K]` activation directly. The per-k4 weight tile loads as a single `ivec4` covering 2 consecutive 4x4 N-blocks (one 16B aligned LSU read replaces two 8B reads). Aliases the same buffer the prepack writes.
- `q4gsw_linear_gemm__tin__w_4x8_nc` — fp16 GEMM, transposed-input path, 8x4 per-thread tile, 1x128 LWG, reads the pre-transposed vec4 activation produced by the transpose preprocess. Nibble dequant stays in int16 end-to-end before the fp16 FMA, saving one fp32 register and lifting AOC fiber occupancy from 37% to 50% on Adreno 750 (validated at M=256 K=4096 N=4096: 6135.92 us -> 5637.20 us, -8.1% wall-clock).
- `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_{g1w64,g4w16,g8w8}` — cooperative-reduction GEMV reading the same nc-buffer weight payload as the GEMM shaders, with three (NUM_GROUPS, WORKERS_PER_GROUP) decompositions chosen at dispatch time by the production picker based on output N. All keep total threads/WG = 64; each WG produces NUM_GROUPS * 8 outputs, and the K-loop strides by WORKERS_PER_GROUP.

Prepack: `pack_q4_linear_weight__w_4x8_nc_buffer` produces an int SOA nibble buffer; one `ivec4` covers a 4K x 8N block. The fp32 GEMM shader views the buffer as `ivec4`; the fp16 tin GEMM shader reads it as `ivec2`; the nc-coop GEMV shader rebinds the same bytes as scalar int arrays. Scales use a single `prepack_q4_scales` (dtype-matched vec4) for GEMM; GEMV rebinds the same bytes as a gvec2 via `vec_size=2`. The shared nc-buffer payload means prefill and decode both consume one prepack — no dual-format weight memory cost.

Dispatch structure:
- fp32 (`add_q4gsw_linear_w_4x8_node`): two nodes. The GEMM dispatch binds `q4gsw_linear_gemm__w_4x8_nc` unconditionally; its gated global WG gates the dispatch to `{0,0,0}` at M==1. The nc-coop GEMV sibling owns the decode.
- fp16 (`add_q4gsw_linear_tin_w_4x8_node`): three nodes. The transpose preprocess self-gates `{0,0,0}` when M==1 (no-op); the GEMM dispatch binds `q4gsw_linear_gemm__tin__w_4x8_nc` and its gated global WG returns `{0,0,0}` at M==1; the nc-coop GEMV sibling handles M==1.
- nc-coop GEMV picker (`add_q4gsw_linear_nc_coop_gemv_node`): shape-adaptive dispatch that self-gates `{0,0,0}` when M!=1. Heuristic on output N:
  * N <= 1024  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g1w64`  LWG (1, 1, 64)
  * N <= 4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g4w16`  LWG (1, 4, 16)
  * N >  4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g8w8`   LWG (1, 8, 8)

The adaptive picker replaces sg-GEMV at decode. Cross-device sweep on Galaxy S24 (Adreno 750), S25 (Adreno 830), and Pixel 9 Pro XL (Mali-G715) shows shape-adaptive nc-coop beats sg-GEMV on every LLM-decode shape by 3-56%, with the largest wins at small-N (47-56% at K=2048 N=512 across both Adreno devices). The adaptive picker also unblocks Mali, where sg-GEMV cannot dispatch (subgroupSize=16 != required 64).

The op is registered under both `et_vk.q4gsw_linear.default` and `et_vk.linear_q4gsw.default` for backward compatibility. Also extends `validate_against_reference` in `test/custom_ops/utils.cpp` to handle fp16 tensors.

Demonstration shaders under `test/custom_ops/glsl/` (not linked into the production shader library):
- `q4gsw_linear_gemv__w_4x8_nc{,_nosg}` — sg / nosg GEMV variants from earlier iterations. The sg variant pins subgroupSize to 64 via `VK_EXT_subgroup_size_control` and uses `subgroupBroadcast`; the nosg variant has every thread load its own activation. Both are dispatched by the `test_fpa_q4gsw_linear` benchmark binary's forced-shader selectors `GEMV_W_4X8` and `GEMV_W_4X8_NOSG` (selectors 1 and 2). Retained as a demonstration of the single-thread-per-output GEMV layout the adaptive nc-coop now supersedes at decode.

Buffer-padding fix (latent OOB read on N % 8 != 0): The fp32 GEMM's 16B ivec4 weight load spans two consecutive (k4, n4) ivec2 tiles along N. Pad the SOA weight buffer's row stride to next-even N4 (no-op for the canonical N % 8 == 0 shapes); the prepack shader's existing `(n < N)` branch fills the OOB tiles with the bias-zero nibble pattern (0x88888888u). Adds GEMM accuracy coverage for N=12 and N=20.
ghstack-source-id: 389959259
@exported-using-ghexport

Differential Revision: [D107447239](https://our.internmc.facebook.com/intern/diff/D107447239/)
[ghstack-poisoned]
SS-JIA pushed a commit that referenced this pull request Jun 4, 2026
…ive nc-coop GEMV

Pull Request resolved: #19996

Adds `et_vk.q4gsw_linear.default` backed by production compute shaders and a single top-level dispatch in `Q4gswLinear.cpp`. The op uses two or three execute nodes per dtype path that share a 6-binding descriptor set layout: a GEMM `DynamicDispatchNode` that self-gates to `{0,0,0}` at M==1, and an adaptive nc-coop GEMV sibling `DynamicDispatchNode` that self-gates to `{0,0,0}` at M!=1. The fp16 path adds a transpose preprocess that also self-gates at M==1. Decode-time `virtual_resize` correctly routes M==1 through the nc-coop GEMV after a prefill M>1 set up the graph. Existing serialized models that reference `et_vk.linear_q4gsw.default` are routed to the same forwarder so the cutover requires no graph-level changes; the old `QuantizedLinear.cpp::linear_q4gsw` body is deleted.

Production shaders under `runtime/graph/ops/glsl/`:
- `q4gsw_linear_gemm__w_4x8_nc` — fp32 GEMM, 4M x 8N per-thread tile, 8x8 LWG, reads the raw `[M, K]` activation directly. The per-k4 weight tile loads as a single `ivec4` covering 2 consecutive 4x4 N-blocks (one 16B aligned LSU read replaces two 8B reads). Aliases the same buffer the prepack writes.
- `q4gsw_linear_gemm__tin__w_4x8_nc` — fp16 GEMM, transposed-input path, 8x4 per-thread tile, 1x128 LWG, reads the pre-transposed vec4 activation produced by the transpose preprocess. Nibble dequant stays in int16 end-to-end before the fp16 FMA, saving one fp32 register and lifting AOC fiber occupancy from 37% to 50% on Adreno 750 (validated at M=256 K=4096 N=4096: 6135.92 us -> 5637.20 us, -8.1% wall-clock).
- `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_{g1w64,g4w16,g8w8}` — cooperative-reduction GEMV reading the same nc-buffer weight payload as the GEMM shaders, with three (NUM_GROUPS, WORKERS_PER_GROUP) decompositions chosen at dispatch time by the production picker based on output N. All keep total threads/WG = 64; each WG produces NUM_GROUPS * 8 outputs, and the K-loop strides by WORKERS_PER_GROUP.

Prepack: `pack_q4_linear_weight__w_4x8_nc_buffer` produces an int SOA nibble buffer; one `ivec4` covers a 4K x 8N block. The fp32 GEMM shader views the buffer as `ivec4`; the fp16 tin GEMM shader reads it as `ivec2`; the nc-coop GEMV shader rebinds the same bytes as scalar int arrays. Scales use a single `prepack_q4_scales` (dtype-matched vec4) for GEMM; GEMV rebinds the same bytes as a gvec2 via `vec_size=2`. The shared nc-buffer payload means prefill and decode both consume one prepack — no dual-format weight memory cost.

Dispatch structure:
- fp32 (`add_q4gsw_linear_w_4x8_node`): two nodes. The GEMM dispatch binds `q4gsw_linear_gemm__w_4x8_nc` unconditionally; its gated global WG gates the dispatch to `{0,0,0}` at M==1. The nc-coop GEMV sibling owns the decode.
- fp16 (`add_q4gsw_linear_tin_w_4x8_node`): three nodes. The transpose preprocess self-gates `{0,0,0}` when M==1 (no-op); the GEMM dispatch binds `q4gsw_linear_gemm__tin__w_4x8_nc` and its gated global WG returns `{0,0,0}` at M==1; the nc-coop GEMV sibling handles M==1.
- nc-coop GEMV picker (`add_q4gsw_linear_nc_coop_gemv_node`): shape-adaptive dispatch that self-gates `{0,0,0}` when M!=1. Heuristic on output N:
  * N <= 1024  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g1w64`  LWG (1, 1, 64)
  * N <= 4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g4w16`  LWG (1, 4, 16)
  * N >  4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g8w8`   LWG (1, 8, 8)

The adaptive picker replaces sg-GEMV at decode. Cross-device sweep on Galaxy S24 (Adreno 750), S25 (Adreno 830), and Pixel 9 Pro XL (Mali-G715) shows shape-adaptive nc-coop beats sg-GEMV on every LLM-decode shape by 3-56%, with the largest wins at small-N (47-56% at K=2048 N=512 across both Adreno devices). The adaptive picker also unblocks Mali, where sg-GEMV cannot dispatch (subgroupSize=16 != required 64).

The op is registered under both `et_vk.q4gsw_linear.default` and `et_vk.linear_q4gsw.default` for backward compatibility. Also extends `validate_against_reference` in `test/custom_ops/utils.cpp` to handle fp16 tensors.

Demonstration shaders under `test/custom_ops/glsl/` (not linked into the production shader library):
- `q4gsw_linear_gemv__w_4x8_nc{,_nosg}` — sg / nosg GEMV variants from earlier iterations. The sg variant pins subgroupSize to 64 via `VK_EXT_subgroup_size_control` and uses `subgroupBroadcast`; the nosg variant has every thread load its own activation. Both are dispatched by the `test_fpa_q4gsw_linear` benchmark binary's forced-shader selectors `GEMV_W_4X8` and `GEMV_W_4X8_NOSG` (selectors 1 and 2). Retained as a demonstration of the single-thread-per-output GEMV layout the adaptive nc-coop now supersedes at decode.

Buffer-padding fix (latent OOB read on N % 8 != 0): The fp32 GEMM's 16B ivec4 weight load spans two consecutive (k4, n4) ivec2 tiles along N. Pad the SOA weight buffer's row stride to next-even N4 (no-op for the canonical N % 8 == 0 shapes); the prepack shader's existing `(n < N)` branch fills the OOB tiles with the bias-zero nibble pattern (0x88888888u). Adds GEMM accuracy coverage for N=12 and N=20.
ghstack-source-id: 390049363
@exported-using-ghexport

Differential Revision: [D107447239](https://our.internmc.facebook.com/intern/diff/D107447239/)
SS-JIA pushed a commit that referenced this pull request Jun 4, 2026
…ive nc-coop GEMV

Pull Request resolved: #19996

Adds `et_vk.q4gsw_linear.default` backed by production compute shaders and a single top-level dispatch in `Q4gswLinear.cpp`. The op uses two or three execute nodes per dtype path that share a 6-binding descriptor set layout: a GEMM `DynamicDispatchNode` that self-gates to `{0,0,0}` at M==1, and an adaptive nc-coop GEMV sibling `DynamicDispatchNode` that self-gates to `{0,0,0}` at M!=1. The fp16 path adds a transpose preprocess that also self-gates at M==1. Decode-time `virtual_resize` correctly routes M==1 through the nc-coop GEMV after a prefill M>1 set up the graph. Existing serialized models that reference `et_vk.linear_q4gsw.default` are routed to the same forwarder so the cutover requires no graph-level changes; the old `QuantizedLinear.cpp::linear_q4gsw` body is deleted.

Production shaders under `runtime/graph/ops/glsl/`:
- `q4gsw_linear_gemm__w_4x8_nc` — fp32 GEMM, 4M x 8N per-thread tile, 8x8 LWG, reads the raw `[M, K]` activation directly. The per-k4 weight tile loads as a single `ivec4` covering 2 consecutive 4x4 N-blocks (one 16B aligned LSU read replaces two 8B reads). Aliases the same buffer the prepack writes.
- `q4gsw_linear_gemm__tin__w_4x8_nc` — fp16 GEMM, transposed-input path, 8x4 per-thread tile, 1x128 LWG, reads the pre-transposed vec4 activation produced by the transpose preprocess. Nibble dequant stays in int16 end-to-end before the fp16 FMA, saving one fp32 register and lifting AOC fiber occupancy from 37% to 50% on Adreno 750 (validated at M=256 K=4096 N=4096: 6135.92 us -> 5637.20 us, -8.1% wall-clock).
- `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_{g1w64,g4w16,g8w8}` — cooperative-reduction GEMV reading the same nc-buffer weight payload as the GEMM shaders, with three (NUM_GROUPS, WORKERS_PER_GROUP) decompositions chosen at dispatch time by the production picker based on output N. All keep total threads/WG = 64; each WG produces NUM_GROUPS * 8 outputs, and the K-loop strides by WORKERS_PER_GROUP.

Prepack: `pack_q4_linear_weight__w_4x8_nc_buffer` produces an int SOA nibble buffer; one `ivec4` covers a 4K x 8N block. The fp32 GEMM shader views the buffer as `ivec4`; the fp16 tin GEMM shader reads it as `ivec2`; the nc-coop GEMV shader rebinds the same bytes as scalar int arrays. Scales use a single `prepack_q4_scales` (dtype-matched vec4) for GEMM; GEMV rebinds the same bytes as a gvec2 via `vec_size=2`. The shared nc-buffer payload means prefill and decode both consume one prepack — no dual-format weight memory cost.

Dispatch structure:
- fp32 (`add_q4gsw_linear_w_4x8_node`): two nodes. The GEMM dispatch binds `q4gsw_linear_gemm__w_4x8_nc` unconditionally; its gated global WG gates the dispatch to `{0,0,0}` at M==1. The nc-coop GEMV sibling owns the decode.
- fp16 (`add_q4gsw_linear_tin_w_4x8_node`): three nodes. The transpose preprocess self-gates `{0,0,0}` when M==1 (no-op); the GEMM dispatch binds `q4gsw_linear_gemm__tin__w_4x8_nc` and its gated global WG returns `{0,0,0}` at M==1; the nc-coop GEMV sibling handles M==1.
- nc-coop GEMV picker (`add_q4gsw_linear_nc_coop_gemv_node`): shape-adaptive dispatch that self-gates `{0,0,0}` when M!=1. Heuristic on output N:
  * N <= 1024  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g1w64`  LWG (1, 1, 64)
  * N <= 4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g4w16`  LWG (1, 4, 16)
  * N >  4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g8w8`   LWG (1, 8, 8)

The adaptive picker replaces sg-GEMV at decode. Cross-device sweep on Galaxy S24 (Adreno 750), S25 (Adreno 830), and Pixel 9 Pro XL (Mali-G715) shows shape-adaptive nc-coop beats sg-GEMV on every LLM-decode shape by 3-56%, with the largest wins at small-N (47-56% at K=2048 N=512 across both Adreno devices). The adaptive picker also unblocks Mali, where sg-GEMV cannot dispatch (subgroupSize=16 != required 64).

The op is registered under both `et_vk.q4gsw_linear.default` and `et_vk.linear_q4gsw.default` for backward compatibility. Also extends `validate_against_reference` in `test/custom_ops/utils.cpp` to handle fp16 tensors.

Demonstration shaders under `test/custom_ops/glsl/` (not linked into the production shader library):
- `q4gsw_linear_gemv__w_4x8_nc{,_nosg}` — sg / nosg GEMV variants from earlier iterations. The sg variant pins subgroupSize to 64 via `VK_EXT_subgroup_size_control` and uses `subgroupBroadcast`; the nosg variant has every thread load its own activation. Both are dispatched by the `test_fpa_q4gsw_linear` benchmark binary's forced-shader selectors `GEMV_W_4X8` and `GEMV_W_4X8_NOSG` (selectors 1 and 2). Retained as a demonstration of the single-thread-per-output GEMV layout the adaptive nc-coop now supersedes at decode.

Buffer-padding fix (latent OOB read on N % 8 != 0): The fp32 GEMM's 16B ivec4 weight load spans two consecutive (k4, n4) ivec2 tiles along N. Pad the SOA weight buffer's row stride to next-even N4 (no-op for the canonical N % 8 == 0 shapes); the prepack shader's existing `(n < N)` branch fills the OOB tiles with the bias-zero nibble pattern (0x88888888u). Adds GEMM accuracy coverage for N=12 and N=20.
ghstack-source-id: 390109017
@exported-using-ghexport

Differential Revision: [D107447239](https://our.internmc.facebook.com/intern/diff/D107447239/)
@meta-codesync
meta-codesync Bot merged commit db460a5 into gh/SS-JIA/555/base Jun 5, 2026
169 of 178 checks passed
@meta-codesync
meta-codesync Bot deleted the gh/SS-JIA/555/head branch June 5, 2026 00:23
@meta-codesync
meta-codesync Bot temporarily deployed to cherry-pick-bot June 5, 2026 00:23 Inactive
SS-JIA pushed a commit that referenced this pull request Jun 5, 2026
…ive nc-coop GEMV

Pull Request resolved: #19996

Adds `et_vk.q4gsw_linear.default` backed by production compute shaders and a single top-level dispatch in `Q4gswLinear.cpp`. The op uses two or three execute nodes per dtype path that share a 6-binding descriptor set layout: a GEMM `DynamicDispatchNode` that self-gates to `{0,0,0}` at M==1, and an adaptive nc-coop GEMV sibling `DynamicDispatchNode` that self-gates to `{0,0,0}` at M!=1. The fp16 path adds a transpose preprocess that also self-gates at M==1. Decode-time `virtual_resize` correctly routes M==1 through the nc-coop GEMV after a prefill M>1 set up the graph. Existing serialized models that reference `et_vk.linear_q4gsw.default` are routed to the same forwarder so the cutover requires no graph-level changes; the old `QuantizedLinear.cpp::linear_q4gsw` body is deleted.

Production shaders under `runtime/graph/ops/glsl/`:
- `q4gsw_linear_gemm__w_4x8_nc` — fp32 GEMM, 4M x 8N per-thread tile, 8x8 LWG, reads the raw `[M, K]` activation directly. The per-k4 weight tile loads as a single `ivec4` covering 2 consecutive 4x4 N-blocks (one 16B aligned LSU read replaces two 8B reads). Aliases the same buffer the prepack writes.
- `q4gsw_linear_gemm__tin__w_4x8_nc` — fp16 GEMM, transposed-input path, 8x4 per-thread tile, 1x128 LWG, reads the pre-transposed vec4 activation produced by the transpose preprocess. Nibble dequant stays in int16 end-to-end before the fp16 FMA, saving one fp32 register and lifting AOC fiber occupancy from 37% to 50% on Adreno 750 (validated at M=256 K=4096 N=4096: 6135.92 us -> 5637.20 us, -8.1% wall-clock).
- `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_{g1w64,g4w16,g8w8}` — cooperative-reduction GEMV reading the same nc-buffer weight payload as the GEMM shaders, with three (NUM_GROUPS, WORKERS_PER_GROUP) decompositions chosen at dispatch time by the production picker based on output N. All keep total threads/WG = 64; each WG produces NUM_GROUPS * 8 outputs, and the K-loop strides by WORKERS_PER_GROUP.

Prepack: `pack_q4_linear_weight__w_4x8_nc_buffer` produces an int SOA nibble buffer; one `ivec4` covers a 4K x 8N block. The fp32 GEMM shader views the buffer as `ivec4`; the fp16 tin GEMM shader reads it as `ivec2`; the nc-coop GEMV shader rebinds the same bytes as scalar int arrays. Scales use a single `prepack_q4_scales` (dtype-matched vec4) for GEMM; GEMV rebinds the same bytes as a gvec2 via `vec_size=2`. The shared nc-buffer payload means prefill and decode both consume one prepack — no dual-format weight memory cost.

Dispatch structure:
- fp32 (`add_q4gsw_linear_w_4x8_node`): two nodes. The GEMM dispatch binds `q4gsw_linear_gemm__w_4x8_nc` unconditionally; its gated global WG gates the dispatch to `{0,0,0}` at M==1. The nc-coop GEMV sibling owns the decode.
- fp16 (`add_q4gsw_linear_tin_w_4x8_node`): three nodes. The transpose preprocess self-gates `{0,0,0}` when M==1 (no-op); the GEMM dispatch binds `q4gsw_linear_gemm__tin__w_4x8_nc` and its gated global WG returns `{0,0,0}` at M==1; the nc-coop GEMV sibling handles M==1.
- nc-coop GEMV picker (`add_q4gsw_linear_nc_coop_gemv_node`): shape-adaptive dispatch that self-gates `{0,0,0}` when M!=1. Heuristic on output N:
  * N <= 1024  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g1w64`  LWG (1, 1, 64)
  * N <= 4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g4w16`  LWG (1, 4, 16)
  * N >  4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g8w8`   LWG (1, 8, 8)

The adaptive picker replaces sg-GEMV at decode. Cross-device sweep on Galaxy S24 (Adreno 750), S25 (Adreno 830), and Pixel 9 Pro XL (Mali-G715) shows shape-adaptive nc-coop beats sg-GEMV on every LLM-decode shape by 3-56%, with the largest wins at small-N (47-56% at K=2048 N=512 across both Adreno devices). The adaptive picker also unblocks Mali, where sg-GEMV cannot dispatch (subgroupSize=16 != required 64).

The op is registered under both `et_vk.q4gsw_linear.default` and `et_vk.linear_q4gsw.default` for backward compatibility. Also extends `validate_against_reference` in `test/custom_ops/utils.cpp` to handle fp16 tensors.

Demonstration shaders under `test/custom_ops/glsl/` (not linked into the production shader library):
- `q4gsw_linear_gemv__w_4x8_nc{,_nosg}` — sg / nosg GEMV variants from earlier iterations. The sg variant pins subgroupSize to 64 via `VK_EXT_subgroup_size_control` and uses `subgroupBroadcast`; the nosg variant has every thread load its own activation. Both are dispatched by the `test_fpa_q4gsw_linear` benchmark binary's forced-shader selectors `GEMV_W_4X8` and `GEMV_W_4X8_NOSG` (selectors 1 and 2). Retained as a demonstration of the single-thread-per-output GEMV layout the adaptive nc-coop now supersedes at decode.

Buffer-padding fix (latent OOB read on N % 8 != 0): The fp32 GEMM's 16B ivec4 weight load spans two consecutive (k4, n4) ivec2 tiles along N. Pad the SOA weight buffer's row stride to next-even N4 (no-op for the canonical N % 8 == 0 shapes); the prepack shader's existing `(n < N)` branch fills the OOB tiles with the bias-zero nibble pattern (0x88888888u). Adds GEMM accuracy coverage for N=12 and N=20.
ghstack-source-id: 390109017
@exported-using-ghexport

Differential Revision: [D107447239](https://our.internmc.facebook.com/intern/diff/D107447239/)
SS-JIA pushed a commit that referenced this pull request Jun 5, 2026
…0055)

[ET-VK][q4gsw] Add et_vk.q4gsw_linear.default with W_4X8 GEMM + adaptive nc-coop GEMV
Pull Request resolved: #19996

Adds `et_vk.q4gsw_linear.default` backed by production compute shaders and a single top-level dispatch in `Q4gswLinear.cpp`. The op uses two or three execute nodes per dtype path that share a 6-binding descriptor set layout: a GEMM `DynamicDispatchNode` that self-gates to `{0,0,0}` at M==1, and an adaptive nc-coop GEMV sibling `DynamicDispatchNode` that self-gates to `{0,0,0}` at M!=1. The fp16 path adds a transpose preprocess that also self-gates at M==1. Decode-time `virtual_resize` correctly routes M==1 through the nc-coop GEMV after a prefill M>1 set up the graph. Existing serialized models that reference `et_vk.linear_q4gsw.default` are routed to the same forwarder so the cutover requires no graph-level changes; the old `QuantizedLinear.cpp::linear_q4gsw` body is deleted.

Production shaders under `runtime/graph/ops/glsl/`:
- `q4gsw_linear_gemm__w_4x8_nc` — fp32 GEMM, 4M x 8N per-thread tile, 8x8 LWG, reads the raw `[M, K]` activation directly. The per-k4 weight tile loads as a single `ivec4` covering 2 consecutive 4x4 N-blocks (one 16B aligned LSU read replaces two 8B reads). Aliases the same buffer the prepack writes.
- `q4gsw_linear_gemm__tin__w_4x8_nc` — fp16 GEMM, transposed-input path, 8x4 per-thread tile, 1x128 LWG, reads the pre-transposed vec4 activation produced by the transpose preprocess. Nibble dequant stays in int16 end-to-end before the fp16 FMA, saving one fp32 register and lifting AOC fiber occupancy from 37% to 50% on Adreno 750 (validated at M=256 K=4096 N=4096: 6135.92 us -> 5637.20 us, -8.1% wall-clock).
- `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_{g1w64,g4w16,g8w8}` — cooperative-reduction GEMV reading the same nc-buffer weight payload as the GEMM shaders, with three (NUM_GROUPS, WORKERS_PER_GROUP) decompositions chosen at dispatch time by the production picker based on output N. All keep total threads/WG = 64; each WG produces NUM_GROUPS * 8 outputs, and the K-loop strides by WORKERS_PER_GROUP.

Prepack: `pack_q4_linear_weight__w_4x8_nc_buffer` produces an int SOA nibble buffer; one `ivec4` covers a 4K x 8N block. The fp32 GEMM shader views the buffer as `ivec4`; the fp16 tin GEMM shader reads it as `ivec2`; the nc-coop GEMV shader rebinds the same bytes as scalar int arrays. Scales use a single `prepack_q4_scales` (dtype-matched vec4) for GEMM; GEMV rebinds the same bytes as a gvec2 via `vec_size=2`. The shared nc-buffer payload means prefill and decode both consume one prepack — no dual-format weight memory cost.

Dispatch structure:
- fp32 (`add_q4gsw_linear_w_4x8_node`): two nodes. The GEMM dispatch binds `q4gsw_linear_gemm__w_4x8_nc` unconditionally; its gated global WG gates the dispatch to `{0,0,0}` at M==1. The nc-coop GEMV sibling owns the decode.
- fp16 (`add_q4gsw_linear_tin_w_4x8_node`): three nodes. The transpose preprocess self-gates `{0,0,0}` when M==1 (no-op); the GEMM dispatch binds `q4gsw_linear_gemm__tin__w_4x8_nc` and its gated global WG returns `{0,0,0}` at M==1; the nc-coop GEMV sibling handles M==1.
- nc-coop GEMV picker (`add_q4gsw_linear_nc_coop_gemv_node`): shape-adaptive dispatch that self-gates `{0,0,0}` when M!=1. Heuristic on output N:
  * N <= 1024  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g1w64`  LWG (1, 1, 64)
  * N <= 4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g4w16`  LWG (1, 4, 16)
  * N >  4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g8w8`   LWG (1, 8, 8)

The adaptive picker replaces sg-GEMV at decode. Cross-device sweep on Galaxy S24 (Adreno 750), S25 (Adreno 830), and Pixel 9 Pro XL (Mali-G715) shows shape-adaptive nc-coop beats sg-GEMV on every LLM-decode shape by 3-56%, with the largest wins at small-N (47-56% at K=2048 N=512 across both Adreno devices). The adaptive picker also unblocks Mali, where sg-GEMV cannot dispatch (subgroupSize=16 != required 64).

The op is registered under both `et_vk.q4gsw_linear.default` and `et_vk.linear_q4gsw.default` for backward compatibility. Also extends `validate_against_reference` in `test/custom_ops/utils.cpp` to handle fp16 tensors.

Demonstration shaders under `test/custom_ops/glsl/` (not linked into the production shader library):
- `q4gsw_linear_gemv__w_4x8_nc{,_nosg}` — sg / nosg GEMV variants from earlier iterations. The sg variant pins subgroupSize to 64 via `VK_EXT_subgroup_size_control` and uses `subgroupBroadcast`; the nosg variant has every thread load its own activation. Both are dispatched by the `test_fpa_q4gsw_linear` benchmark binary's forced-shader selectors `GEMV_W_4X8` and `GEMV_W_4X8_NOSG` (selectors 1 and 2). Retained as a demonstration of the single-thread-per-output GEMV layout the adaptive nc-coop now supersedes at decode.

Buffer-padding fix (latent OOB read on N % 8 != 0): The fp32 GEMM's 16B ivec4 weight load spans two consecutive (k4, n4) ivec2 tiles along N. Pad the SOA weight buffer's row stride to next-even N4 (no-op for the canonical N % 8 == 0 shapes); the prepack shader's existing `(n < N)` branch fills the OOB tiles with the bias-zero nibble pattern (0x88888888u). Adds GEMM accuracy coverage for N=12 and N=20.
ghstack-source-id: 390109017
@exported-using-ghexport

Differential Revision: [D107447239](https://our.internmc.facebook.com/intern/diff/D107447239/)
Gasoonjia pushed a commit that referenced this pull request Jun 8, 2026
…0055)

[ET-VK][q4gsw] Add et_vk.q4gsw_linear.default with W_4X8 GEMM + adaptive nc-coop GEMV
Pull Request resolved: #19996

Adds `et_vk.q4gsw_linear.default` backed by production compute shaders and a single top-level dispatch in `Q4gswLinear.cpp`. The op uses two or three execute nodes per dtype path that share a 6-binding descriptor set layout: a GEMM `DynamicDispatchNode` that self-gates to `{0,0,0}` at M==1, and an adaptive nc-coop GEMV sibling `DynamicDispatchNode` that self-gates to `{0,0,0}` at M!=1. The fp16 path adds a transpose preprocess that also self-gates at M==1. Decode-time `virtual_resize` correctly routes M==1 through the nc-coop GEMV after a prefill M>1 set up the graph. Existing serialized models that reference `et_vk.linear_q4gsw.default` are routed to the same forwarder so the cutover requires no graph-level changes; the old `QuantizedLinear.cpp::linear_q4gsw` body is deleted.

Production shaders under `runtime/graph/ops/glsl/`:
- `q4gsw_linear_gemm__w_4x8_nc` — fp32 GEMM, 4M x 8N per-thread tile, 8x8 LWG, reads the raw `[M, K]` activation directly. The per-k4 weight tile loads as a single `ivec4` covering 2 consecutive 4x4 N-blocks (one 16B aligned LSU read replaces two 8B reads). Aliases the same buffer the prepack writes.
- `q4gsw_linear_gemm__tin__w_4x8_nc` — fp16 GEMM, transposed-input path, 8x4 per-thread tile, 1x128 LWG, reads the pre-transposed vec4 activation produced by the transpose preprocess. Nibble dequant stays in int16 end-to-end before the fp16 FMA, saving one fp32 register and lifting AOC fiber occupancy from 37% to 50% on Adreno 750 (validated at M=256 K=4096 N=4096: 6135.92 us -> 5637.20 us, -8.1% wall-clock).
- `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_{g1w64,g4w16,g8w8}` — cooperative-reduction GEMV reading the same nc-buffer weight payload as the GEMM shaders, with three (NUM_GROUPS, WORKERS_PER_GROUP) decompositions chosen at dispatch time by the production picker based on output N. All keep total threads/WG = 64; each WG produces NUM_GROUPS * 8 outputs, and the K-loop strides by WORKERS_PER_GROUP.

Prepack: `pack_q4_linear_weight__w_4x8_nc_buffer` produces an int SOA nibble buffer; one `ivec4` covers a 4K x 8N block. The fp32 GEMM shader views the buffer as `ivec4`; the fp16 tin GEMM shader reads it as `ivec2`; the nc-coop GEMV shader rebinds the same bytes as scalar int arrays. Scales use a single `prepack_q4_scales` (dtype-matched vec4) for GEMM; GEMV rebinds the same bytes as a gvec2 via `vec_size=2`. The shared nc-buffer payload means prefill and decode both consume one prepack — no dual-format weight memory cost.

Dispatch structure:
- fp32 (`add_q4gsw_linear_w_4x8_node`): two nodes. The GEMM dispatch binds `q4gsw_linear_gemm__w_4x8_nc` unconditionally; its gated global WG gates the dispatch to `{0,0,0}` at M==1. The nc-coop GEMV sibling owns the decode.
- fp16 (`add_q4gsw_linear_tin_w_4x8_node`): three nodes. The transpose preprocess self-gates `{0,0,0}` when M==1 (no-op); the GEMM dispatch binds `q4gsw_linear_gemm__tin__w_4x8_nc` and its gated global WG returns `{0,0,0}` at M==1; the nc-coop GEMV sibling handles M==1.
- nc-coop GEMV picker (`add_q4gsw_linear_nc_coop_gemv_node`): shape-adaptive dispatch that self-gates `{0,0,0}` when M!=1. Heuristic on output N:
  * N <= 1024  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g1w64`  LWG (1, 1, 64)
  * N <= 4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g4w16`  LWG (1, 4, 16)
  * N >  4096  -> `q4gsw_linear_gemv_coop__w_4x8_nc_buffer_g8w8`   LWG (1, 8, 8)

The adaptive picker replaces sg-GEMV at decode. Cross-device sweep on Galaxy S24 (Adreno 750), S25 (Adreno 830), and Pixel 9 Pro XL (Mali-G715) shows shape-adaptive nc-coop beats sg-GEMV on every LLM-decode shape by 3-56%, with the largest wins at small-N (47-56% at K=2048 N=512 across both Adreno devices). The adaptive picker also unblocks Mali, where sg-GEMV cannot dispatch (subgroupSize=16 != required 64).

The op is registered under both `et_vk.q4gsw_linear.default` and `et_vk.linear_q4gsw.default` for backward compatibility. Also extends `validate_against_reference` in `test/custom_ops/utils.cpp` to handle fp16 tensors.

Demonstration shaders under `test/custom_ops/glsl/` (not linked into the production shader library):
- `q4gsw_linear_gemv__w_4x8_nc{,_nosg}` — sg / nosg GEMV variants from earlier iterations. The sg variant pins subgroupSize to 64 via `VK_EXT_subgroup_size_control` and uses `subgroupBroadcast`; the nosg variant has every thread load its own activation. Both are dispatched by the `test_fpa_q4gsw_linear` benchmark binary's forced-shader selectors `GEMV_W_4X8` and `GEMV_W_4X8_NOSG` (selectors 1 and 2). Retained as a demonstration of the single-thread-per-output GEMV layout the adaptive nc-coop now supersedes at decode.

Buffer-padding fix (latent OOB read on N % 8 != 0): The fp32 GEMM's 16B ivec4 weight load spans two consecutive (k4, n4) ivec2 tiles along N. Pad the SOA weight buffer's row stride to next-even N4 (no-op for the canonical N % 8 == 0 shapes); the prepack shader's existing `(n < N)` branch fills the OOB tiles with the bias-zero nibble pattern (0x88888888u). Adds GEMM accuracy coverage for N=12 and N=20.
ghstack-source-id: 390109017
@exported-using-ghexport

Differential Revision: [D107447239](https://our.internmc.facebook.com/intern/diff/D107447239/)

This branch was previously deployed

1 inactive deployment
cherry-pick-bot — ee22378f Deployed Jun 5, 2026 by meta-codesync[bot] via Try to create a PR with ghstack /orig branch #1266
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. fb-exported meta-exported

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants