Skip to content

[ET-VK] Activation transpose preprocess shaders + dispatch helper - #20055

Merged
SS-JIA merged 3 commits into
mainfrom
gh/SS-JIA/554/orig
Jun 5, 2026
Merged

SS-JIA merged 3 commits into
mainfrom
gh/SS-JIA/554/orig

Conversation

@pytorchbot

Copy link
Copy Markdown
Collaborator

Pull Request resolved: #19995

Adds a generic "preprocess" dispatch path for transposing/casting an activation tensor into a vectorized layout that downstream compute kernels can consume. This is split out from the upcoming q4gsw GEMM commit so the transpose machinery can be reused by other operators that consume pre-transposed activations.

Two compute shaders are added under `runtime/graph/ops/glsl/`:
- `transpose_cast_contig_to_vectorized` — transposes a contiguous `[M, K]` tensor into `[K, ceil(M/4)]` packed as a vec4 along the inner dim, with optional dtype cast.
- `transpose_cast_contig_to_vectorized_4x4` — same idea but produces a 4x4 vectorized tile per output element, used by tile-style GEMM kernels.

`runtime/graph/ops/impl/Preprocess.{cpp,h}` wraps these shaders behind `add_transpose_cast_node` (and a 4x4 variant). The dispatch self-gates to `{0, 0, 0}` when M==1 so that GEMV paths sharing a graph with a GEMM prefill can leave the preprocess in place as a no-op rather than rebuilding the graph at decode time. The matching `resize_transpose_cast_node` keeps the transposed tensor's virtual size in sync with the source activation across `virtual_resize`.

To support callers that want to invoke the standard prepack path for the activation directly, `Staging.h` now declares `add_prepack_standard_node` (previously file-private). `Transpose.cpp` is reduced to the includes it actually uses.

No new ops are dispatched yet; the next commit wires this infrastructure into `et_vk.q4gsw_linear.default`.
ghstack-source-id: 390109015
@exported-using-ghexport

Differential Revision: [D107447235](https://our.internmc.facebook.com/intern/diff/D107447235/)
@pytorchbot
pytorchbot requested a review from SS-JIA as a code owner June 5, 2026 00:24
@pytorch-bot

pytorch-bot Bot commented Jun 5, 2026

Copy link
Copy Markdown

🔗 Helpful Links

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

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

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 Jun 5, 2026
@linux-foundation-easycla

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

Copy link
Copy Markdown

CLA Missing ID

  • ✅ login: SS-JIA / name: Sicheng Stephen Jia (2bc561f)
  • ❌ The email address for the commit (a0d8b12, e0387c3) is not linked to the GitHub account, preventing the EasyCLA check. Consult this Help Article and GitHub Help to resolve. (To view the commit's email address, add .patch at the end of this PR page's URL.) For further assistance with EasyCLA, please visit our EasyCLA portal and chat with our support bot.

@github-actions

github-actions Bot commented Jun 5, 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.

…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
SS-JIA merged commit 8928480 into main Jun 5, 2026
169 of 171 checks passed
@SS-JIA
SS-JIA deleted the gh/SS-JIA/554/orig branch June 5, 2026 01:14
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/)
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. skip-url-lint

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants