Skip to content

[ET-VK] Cooperative-matrix kernels for 4-bit linear on Intel Xe2 and NVIDIA - #24000

Merged
SS-JIA merged 41 commits into
pytorch:mainfrom
sarc-acl:pr/wmma-families
Nov 19, 2026
Merged

SS-JIA merged 41 commits into
pytorch:mainfrom
sarc-acl:pr/wmma-families

Conversation

@xuyanwen2012

@xuyanwen2012 xuyanwen2012 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Today the cooperative-matrix path of q4gsw and dq8ca_q4gsw linear only runs on devices with subgroup size 64
whose name contains "Radeon" or "Xclipse". On Intel Xe2 (subgroup 16) and NVIDIA (subgroup 32) no
cooperative-matrix linear kernel runs, and prefill uses the tiled kernels.

This PR adds a cooperative-matrix path for 4-bit weight linear (q4gsw, 4w) and 8-bit-activation 4-bit-weight
linear (dq8ca_q4gsw, 8da4w) on two architecture families:

  • Intel Xe2 (Arc B580, Arc Pro B70) on Mesa ANV
  • NVIDIA (RTX 4070 Ti SUPER, Jetson Orin) on the proprietary driver

A device matches a family by four things, never by device name: vendor ID, driver ID, the cooperative-matrix
shapes it reports and the subgroup sizes it supports. Its logical device must also have what the kernels need
enabled: subgroup size control for compute, full subgroups and the Vulkan memory model. This holds for an
Adapter that creates its device and for one that borrows a shared device (#23151). A device that matches no
family keeps the kernels it runs today.

What changes

  1. vk_api:
    • Set REQUIRE_FULL_SUBGROUPS on pipelines with a required subgroup size when the device enabled
      computeFullSubgroups and the local size in X is a multiple of it (VUID-RuntimeSpirv-OpTypeCooperativeMatrixKHR-10770,
      VUID 02757).
    • Enable VK_KHR_vulkan_memory_model (and its device scope) whenever the device supports it, and map the
      VulkanMemoryModel / VulkanMemoryModelDeviceScope SPIR-V capabilities to it.
    • Record the memory-model features in SharedVulkanDeviceFeatures. Shared-device Adapters derive full
      subgroups and the memory model from the device's enabled extensions and features, as the owning Adapter
      does (vk_api/EnabledDeviceState.h). Adapters on an external VkDevice stay conservative.
    • Expose the driver ID (VkPhysicalDeviceDriverProperties, only with VK_KHR_driver_properties), the
      cooperative-matrix property list and the maximum compute shared memory.
    • Add kReadStorageImage, a read access that selects VK_IMAGE_LAYOUT_GENERAL. The graph dump lists it as
      a read.
  2. impl/gemm/linear/qw/wmma/CoopmatFamily.{h,cpp}: the family key and one table of kernel rows per family.
    • Each row names a shader variant, its tile geometry, the shared memory it declares per IO storage and an
      optional shape rule.
    • Selection checks op, layout, subgroup size, shared-memory limit and tile alignment. A shape that no row
      fits falls back to the existing kernel.
    • WmmaLinear.* builds the key (from an Adapter or a graph) and the shape.
  3. impl/gemm/linear/qw/q4gsw/wmma/Q4gswLinearWmma.*, impl/gemm/linear/qw/dq8ca_q4gsw/wmma/Dq8caQ4gswLinearWmma.*:
    dispatch, hooked into Q4gswLinear.cpp and Dq8caQ4gswLinear.cpp (7 lines each). Weight scales are
    converted to the output dtype, so fp32-scale and floating-zero-point models take the family kernels too.
  4. Shaders under glsl/gemm/linear/qw/{q4gsw,dq8ca_q4gsw}/wmma/:
    • Two cooperative-matrix linear templates, linear_q4gsw_wmma and linear_dq8ca_q4gsw_wmma, each with one
      *_body.glslh.
      • q4gsw flags: B_TEXEL, ACC_FP32, CSH_IN_ASH, FRAG_LAYOUT, IMG_A, CSH_BAND, B_COLMAJOR.
      • dq8ca flags: ROWMAJOR_A, ORDER_NB_MAX, A_MULTI_BLOCK.
    • 15 variants. The storage, dtype and zero-point suffixes come from generate_variant_forall. The
      templates define PRECISION highp themselves, so --auto-use-mediump does not change them.
    • The existing with-group-sums activation packer, now quantize_and_pack_with_group_sums.{glsl,yaml}, gains
      an OUTPUT_LAYOUT axis with two row-major variant names (quantize_and_pack_4w_with_group_sums_*). Its 16
      existing variants compile to the same SPIR-V as before.
  5. Tests:
    • test/custom_ops/coopmat_family_test.cpp: host-only gtest of the key and the selection (14 tests). It
      covers:

      • unmatched keys (e.g. llvmpipe);
      • logical-device prerequisites, and the enabled state a created or shared device yields;
      • the shared-memory limit of every row;
      • every row's tile geometry (WG_TILE_*, SG_GRID_*, subgroup size, MMA_M, IO storage, layout flags)
        against the yaml parameters of each variant it dispatches.

      It runs in test-vulkan-operators-linux.

    • vulkan_shared_device_test: an Adapter that borrows a shared device created by the backend has the
      owner's pipeline flags, memory model and family. An imported device without declared features has none.

    • benchmark_v2/operators/gemm/linear/qw/wmma/cases/correctness.json (88 cases). It runs on its own in
      test-vulkan-operators-linux (SwiftShader) and test-vulkan-nvidia.

      • Each case is a wmma_family_route check: operator_dynamic_resize steps that also assert the kernel
        each step dispatches for the device's family. The family is stated by ETVK_WMMA_EXPECTED_FAMILY
        (nvidia on the NVIDIA job, software on SwiftShader), not taken from the selector. In strict mode a
        case that does not run fails.
      • Coverage: every Xe2 and NVIDIA row, both IO storages, group sizes 32 / 64 / 128 / 256, [1, M, K]
        inputs, [2, M, K] (no family kernel), unaligned M, runtime shrink/grow down to decode and back,
        fp32 / bias graphs, fp32 scales and fp16 zero points.
      • Long-K q4gsw steps that dispatch a family kernel are validated at that family's measured bound (see
        Testing).
      • wmma_family_shared_memory checks the row table against the SPIR-V. wmma_memory_model_gate checks
        that family kernels pass the capability gate on family devices.
      • performance.json has the Llama 3.2 1B projections.
    • The Xe2 rows have no GitHub CI coverage (no runner has an Xe2 GPU).

Family 4w 8da4w
Xe2 (MMA 8x16x16 fp16, 8x16x32 int8, subgroup 16) t128x128k16g82s16m8flib (texture3d), t128x128k16g44s16m8fl (buffer) t128x128k64g84s16m8i; blocked workgroup order ...n13 when K*N >= 20e6
NVIDIA (MMA 16x16x16 fp16/fp32, 16x16x32 int8, subgroup 32) t256x128k16g42s32bt for K <= 8192; t128x128k16g22s32 where the 256-row tile does not fit; bx_t128x128k32g42s32f32c (fp32 accumulation) for K > 8192 rowmajor_t128x128k64g24s32mk32

The kernel sets were chosen from per-device tuned kernels by measuring each candidate on every member of its
family. The accepted set is within 3 % geomean of each member's own best set, with no projection more than 8 %
worse. The K > 8192 fp32-accumulation rule on NVIDIA is a correctness rule: the fp16-accumulate kernel exceeds
tolerance at K = 14336 (Llama 3.1 8B down projection).

Buffer tensors pad their packed dim to four (#24753). On the family route that dim is always a multiple of the
tile, so the padding is empty there.

Results

End-to-end prefill, Llama 3.2 1B, 512-token prompt, tokens/s (median of 3), this PR vs main. Measured
2026-10-19, before the rebases. Family kernel times were unchanged on 2026-11-10 (B580, 4070 Ti), and the
changes since then leave the family kernels' SPIR-V byte-identical:

Device 4w 8da4w
Arc B580 10667 vs 3066 (3.5x) 13474 vs 6737 (2.0x)
RTX 4070 Ti SUPER 21333 vs 6649 (3.2x) 32000 vs 7420 (4.3x)

Unaligned prompts (e.g. 511, 300, 129 tokens) take the family kernels through a partial last M tile. On the
4070 Ti, 1B 4w at 511 tokens goes from 6636 to 21292 tok/s.

Outside the Llama projections, I tested 30 projection shapes of Qwen2.5 0.5B / 1.5B, Gemma 2 2B, Qwen3 4B / 8B
and Phi-3 mini (M = 512 and 2048, group sizes 64, 128 and 256). They pass against the CPU reference on the
4070 Ti and the Orin and run 2.2x to 13.5x faster than the current kernels.

Testing

On the current head (221c089c33, base main 311d96d60d), 2026-11-13 (wmma set rerun 2026-11-16), etvk_ops_bench --validation_only:

Device wmma/correctness q4gsw/correctness coopmat_correctness fpa_correctness
Arc B580 (Mesa 26.2.6) 88/88 (xe2) 134/134 32/32 90/90
Ryzen 9600X iGPU (RADV, Mesa 26.2.6, no family) 88/88 (none) 134/134 not rerun not rerun
llvmpipe (Mesa 26.2.6, no family) 88/88 (software) 134/134 not rerun not rerun

On the same commits before the last rebase (base main 4d292c9733), 2026-11-13:

Device wmma/correctness q4gsw/correctness coopmat_correctness fpa_correctness
Arc Pro B70 (Mesa 26.2.6) 88/88 (xe2) 130/132 * 32/32 90/90
Jetson Orin Nano (595.78) 88/88 (nvidia) 132/132 32/32 90/90
Ryzen 9600X iGPU (RADV) 88/88 (none) 132/132 32/32 90/90
llvmpipe 88/88 (software and none) 132/132 32/32 90/90

* Two linear_dq8ca_q4gsw buffer cases that no family row takes failed on Intel on that base, as on main at
the time. They pass on the B580 on the current base.

The RTX 4070 Ti SUPER (615.71.09) passed an earlier head's 75 cases on 2026-11-10. It was not reachable for
this head. SwiftShader was last run on 2026-11-10 too (75/75, outside GitHub).

  • wmma runs. The wmma rows were run with ETVK_WMMA_EXPECTED_FAMILY set to the device's family. Every
    route case validates its outputs at every step, with one exception: the [2, M, K] cases check routing only,
    because the existing kernels compute only the first batch, on main too.

  • Host tests. vulkan_coopmat_family_test passes 14/14. vulkan_shared_device_test passes 41/41 on the
    B580, B70 and RADV, and 40/40 with 1 skipped on llvmpipe.

  • Kernel lists. Enabling the memory model wherever it is supported did not change the dispatched kernel of
    any case in the three q4gsw collections on the B580, RADV or llvmpipe. None of upstream's VulkanMemoryModel coopmat shaders is selected on these devices. They need
    a Radeon/Xclipse name or subgroup size 64.

  • Long K. Max |error| against the CPU reference over 5 seeds (M = 256):

    Kernel K = 9216 K = 14336
    Xe2 fp16 accumulation (B580) 0.13 0.23
    NVIDIA fp32 accumulation (Orin) 0.008 0.008
    main's q4gsw GEMM (B580) 0.51 0.77

    The family steps are validated at atol 0.3 (Xe2) and 0.03 (NVIDIA), rtol 0. Other devices keep atol 1.0.

Known limitations and open questions

  • Device reach. The Xe2 key requires Mesa ANV (the Intel Windows driver is not matched). The NVIDIA key
    matches any NVIDIA GPU on the proprietary driver that reports these shapes. It was measured on Ada and Ampere
    only (Turing, Hopper and Blackwell would match unmeasured). Happy to narrow it if you prefer.
  • External VkDevice. An Adapter on an external VkDevice does not know whether full subgroups and the
    memory model are enabled, so it keeps the existing kernels. Shared devices carry that state and match.
  • Memory model on other devices. The memory model is enabled wherever it is supported. Upstream's
    linear_coopmat*, matmul_coopmat* and Radeon/Xclipse linear_{,dq8ca_}q4gsw_coopmat_* shaders therefore
    pass the capability gate on such devices, as with [Vulkan] Enable coopmat for NVIDIA devices and do some tuning. #22899. Their own dispatch gates decide whether they run.
    RDNA3 / Xclipse were not run here.
  • Xe2 long K. The Xe2 4w rows keep fp16 accumulation at K > 8192. The error is measured above: within the
    0.25 every K <= 8192 case allows, and below main's kernel on the same device.
  • Xe2 8da4w threshold. The blocked order starts at K*N >= 20e6, the midpoint between the largest shape where
    it is slower (16.8e6) and the smallest where it is faster (21.2e6) on both Xe2 cards.
  • Image extents on Intel. Texture3d tensors at K = 14336 exceed ANV's reported 2048 image extent. This is the
    case on main as well and is not changed here.
  • AMD. RDNA3 under RADV (780M, RX 7600, RX 7900 XTX) and Xclipse are not covered. Their selection is
    unchanged. Folding the AMD coopmat route into the family table is a possible follow-up.
  • Weight layout. On a family device, decode and small-M prefill fall back to linear_q4gsw_{coop,tiled},
    which read the legacy layout the family kernels share.
    • On an Arc B580 those are faster than main's w_4x8_nc GEMV/GEMM for most Llama 3.2 1B projections
      (geomean 0.63–0.78 of main's time on texture3d). They are slower for k/v decode and for gate/up at
      M = 64 and 100.
    • On a Jetson Orin, main's kernels are faster from M = 64 on (fallback 1.19x / 1.36x at M = 64 / 100) and
      on par for decode.
    • Reading w_4x8_nc from the family kernels is a follow-up.
  • Upstream issue seen while testing (not changed here). On main, linear_q4gsw / linear_dq8ca_q4gsw
    with a [2, M, K] input compute only the first batch.
  • Teardown crash on NVIDIA x86 (pre-existing, not from this PR). With a cold driver shader cache,
    etvk_ops_bench on the 4070 Ti (driver 615.71) occasionally aborts at exit after all cases have passed
    (ComputePipelineCache::purge in ~Adapter racing the driver's background compiler thread).

Not in this PR: fused attention, decode kernels, fp16 linear.

Authored with Claude Code (AI).

🤖 Generated with Claude Code

@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 Oct 19, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⚠️ 4 Awaiting Approval

As of commit 0fa9530 with merge base 945838a (image):

AWAITING APPROVAL - The following workflows need approval before CI can run:

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

@github-actions

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.

@xuyanwen2012
xuyanwen2012 marked this pull request as ready for review October 24, 2026 04:52
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T18:42:37.000914Z 82f8988 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@xuyanwen2012

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@SS-JIA SS-JIA left a comment

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.

AI review (Codex): eight inline findings A1–A8, consolidated from three independent etvk-developer static reviews. A1–A5 require changes; A6–A8 are non-blocking maintenance suggestions. No project code was changed or executed.

Comment on lines +143 to +146
const ValueRef packed_weight =
prepack_quantized_linear_weight(graph, weight_quant_config, weight_data);
const ValueRef packed_weight_scales = prepack_standard(
graph, weight_scales_data, utils::kBuffer, utils::kWidthPacked);

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.

AI review (Codex) — A1 · High · Required change

For FP16 input/output with FP32 constant weight scales, prepack_standard() preserves FP32 storage, but the WMMA shaders read t_weight_scales as f16vec4. This reinterprets bytes instead of converting values: FP32 0.5 becomes half words 0 and 1.75, with incorrect group/channel offsets. Resize fallbacks reuse the same incorrectly typed buffer. The dq8ca family builder has the same problem.

Reuse one dtype-converting scale-prepack helper for the existing and both family routes, allocating the destination in output dtype. Existing prepack_q4_scales() and prepack_weight_scales_as() already implement this conversion. Add FP16 activation / FP32 scale cases for both ops, including a resize into fallback; the new cases currently create scales in activation dtype.

Static analysis only; no tests, builds, or device runs were performed.

Comment on lines +61 to +65
${layout_declare_tensor(B, "r", "t_int8_input_scales", "half", "texture3d")}
${layout_declare_tensor(B, "r", "t_int8_input_zps", "int8", "texture3d")}
${layout_declare_tensor(B, "r", "t_packed_weight", "int", WEIGHT_STORAGE, is_scalar_array=False)}
${layout_declare_tensor(B, "r", "t_weight_sums", "int", "buffer", is_scalar_array=True)}
${layout_declare_tensor(B, "r", "t_weight_scales", "half", "buffer", is_scalar_array=False)}

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.

AI review (Codex) — A2 · High · Required change

Supported floating per-row zero points, such as FP16 3.0 in the zpinherit mode, reach this path without a dtype guard. The builder preserves their image dtype and the activation packer selects zpinherit, but this consumer hard-codes an integer sampler. Sampling a floating-format image through that sampler violates the numeric-type contract and invalidates zero-point correction. The row-major WMMA shader does the same.

Decline the family route for non-kChar zero points until matching variants exist, preserving the ordinary zpinherit path. Alternatively reuse ZP_DTYPE_MODE in both family templates and select it consistently with the packer. Add floating zero-point coverage; the new cases use only kChar.

Static analysis only; no tests, builds, or device runs were performed.

Comment on lines +41 to +47
key.subgroup_size = adapter->subgroup_size();
key.min_subgroup_size = adapter->min_subgroup_size();
key.max_subgroup_size = adapter->max_subgroup_size();
key.subgroup_size_control = adapter->supports_subgroup_size_control();
key.coopmat = adapter->supports_cooperative_matrix();
key.int8_coopmat = adapter->supports_int8_cooperative_matrix();
key.max_shared_bytes = adapter->max_compute_shared_memory_size();

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.

AI review (Codex) — A3 · Medium · Required change

Family selection needs the logical device's pipeline prerequisites, beyond these physical-device properties. An external-device Adapter still creates its pipeline cache with the default full_subgroups=false; the new family route can select it, then omit REQUIRE_FULL_SUBGROUPS for its pre-SPIR-V-1.6 cooperative-matrix modules. Separately, subgroup_size_available() accepts a matching default width without compute-stage required-subgroup support, but resolve_required_subgroup_size() requires that support and throws after the family route has taken over.

Gate family eligibility on compute-stage required-subgroup support and enabled full subgroups. Propagate enabled features for external devices, or conservatively retain their existing kernels. Add selector cases for missing size control, missing compute stage and missing full-subgroup enablement. See the external cache construction and runtime resolver.

Static analysis of API/selector states only; no tests, builds, or device runs were performed.

Comment on lines +223 to +232
// The texture epilogue stages SG_GRID_Y * MMA_M rows x WG_TILE_N fp16 on
// top of the A/B tiles unless it reuses the A tile. A tile over the
// shared-memory limit must not reach pipeline creation.
if (!tile.csh_in_ash) {
const uint64_t csh_bytes =
uint64_t(tile.sg_grid_y) * tile.mma_m * tile.n * 2u;
if (csh_bytes >= device.max_shared_bytes) {
return false;
}
}

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.

AI review (Codex) — A4 · Medium · Required change

This compares C staging alone against the whole shared-memory limit and skips buffer/C-in-Ash routes entirely. An otherwise matching NVIDIA key with a 32-KiB limit and texture IO at M=256, K=N=2048, group_size=128 selects the 256-row q4 kernel because C uses only 8,192 bytes. Its declared arrays total 45,056 bytes: Ash 24,576 + BshT 12,288 + Csh 8,192. The 128-row alternative declares 29,184 bytes.

Carry each row's complete requirement in its descriptor: padded and double-buffered A/B arrays, parameter arrays, and optional/aliased/banded C storage. Check the total for every IO combination before selection. Add limit-boundary cases requiring a smaller row or fallback. Shared declarations.

This is a static accepted-key counterexample, not an observed failure on the author's measured cards. No tests, builds, or device runs were performed.


} // namespace

REGISTER_TEST_CASE_SET("q4gsw_linear", "wmma_correctness") {

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.

AI review (Codex) — A5 · Medium · Required change

Registration and compilation do not make this set run in GitHub CI. Both the NVIDIA workflow and SwiftShader job select exactly correctness,performance; set_selected() matches names exactly. A source search found no wmma_correctness invocation in .github or .ci/scripts. Its long-K, partial-M and broader-reference coverage therefore supplies no ongoing GPU gate. The standalone host family test also lacks an inspected GitHub invocation.

Select wmma_correctness in the NVIDIA job and arrange software fallback coverage. Explicitly invoke the host family test where GitHub coverage is intended. Assert family routing on matched hardware and add runtime shrink/grow, decode, row-major unaligned-M and mixed-dtype cases; the current unaligned cases cover only fresh 4w graphs.

Static source/CI review only; no tests, builds, or device runs were performed.

Comment on lines +26 to +29
WmmaShape q4gsw_runtime_shape(
ComputeGraph* graph,
const std::vector<ArgGroup>& args,
const std::vector<ValueRef>& resize_args) {

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.

AI review (Codex) — A6 · Low · Non-blocking maintenance suggestion

Build-time and runtime shape extraction repeat the same M/N/K, batch, GEMV, bias, dtype, IO-storage and packed-dimension logic in four functions across this file and Dq8caQ4gswLinearWmma.cpp. Future eligibility changes must update every copy, allowing build-time takeover and runtime fallback to drift.

Extract common WmmaShape construction into WmmaLinear.cpp, taking explicit input/output/group/bias refs and resolved weight storage. Keep argument decoding, predicted-versus-actual storage resolution and dq8ca's int8-layout annotation at the callers. No current wrong output is attributed to duplication alone.

Static analysis only; no tests, builds, or device runs were performed.

Comment on lines +90 to +96
void main() {
const int group_idx = int(gl_GlobalInvocationID.x);
const int m4 = int(gl_GlobalInvocationID.y);

const int worker_id = int(gl_LocalInvocationID.z);
const int group_offset = int(gl_LocalInvocationID.x);

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.

AI review (Codex) — A7 · Low · Non-blocking maintenance suggestion

This repeats the original quantize_and_pack_4h4w_with_group_sums group traversal, quantization, sum accumulation and reduction. Its substantive difference is the output block writer. The new C++ pack-node builder also duplicates the existing dispatch construction, so algorithm changes now need synchronized edits.

Share the quantization/reduction body with two small output writers, or parameterize the existing packer's output layout. Extend one C++ node builder to select the variant from packed-tensor layout. The doubled-sum recurrence is copied from the original shader; no new output failure from that recurrence is claimed here. Original loop.

Static analysis only; shader equivalence and performance of a refactor were not measured.

Comment on lines +62 to +69
${layout_declare_tensor(B, "r", "t_packed_int8_input", "int8", "buffer", is_scalar_array=True)}
// uvec4 view of binding 2 (t_packed_int8_input) for 16-byte A staging.
// Spelled layout(std430, set...) on purpose: gen_vulkan_spv.py collects the
// descriptor list from every line matching ^layout\(set, so the usual spelling
// would add a descriptor.
layout(std430, set = 0, binding = 2) buffer restrict readonly t_packed_int8_input_v4Buffer {
uvec4 t_packed_int8_input_v4[];
};

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.

AI review (Codex) — A8 · Low · Non-blocking maintenance suggestion

The scalar t_packed_int8_input resource is never read: both global A-load sites use t_packed_int8_input_v4, and cooperative-matrix A loads use shared memory. That leaves two declarations at binding 2 and unusual layout spelling solely to evade descriptor discovery. Changing the alias to conventional layout(set = ...) spelling would make the parser count another descriptor.

Declare the vector resource once through layout_declare_tensor() as a non-scalar int/uint buffer, casting to uvec4 where needed. Remove the unused scalar declaration, explicit alias/binding and parser workaround; retain the int8 arithmetic support used by shared MMA operands. See the vector load and descriptor matcher.

Static analysis only; no tests, builds, or device runs were performed.

@SS-JIA

SS-JIA commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Overall, the changes are quite clean, thank you for putting everything together 🙏

AI static review turned up reasonable comments. In addition to those, I have some requests from my side as well:

  1. I would recommend putting the wmma shaders and dispatch logic under a wmma/ subfolder, relative to where the files are currently placed. This is purely for the sake of file organization
  2. The test/ops/benchmark/ binary which you are currently using has been deprecated; I have sinced replaced it with a benchmark_v2 binary which uses JSON to define test cases. Please rebase the changes to the newest main and migrate the test cases to the benchmark_v2 format.

Other than that, we should be good to merge!

@SS-JIA

SS-JIA commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Oh, also, not sure if it's relevant to these shaders, but I recently merged #24753 which makes it so that all buffer backed tensors will internally pad their contiguous dim to 4. So this means that a tensor with shape (8, 13) will be internally represented as a tensor with shape (8, 16), with 3 zero padding values appended to each row.

I'm unsure if this impacts the wmma shaders at all, but just something to be aware of.

@xuyanwen2012

Copy link
Copy Markdown
Contributor Author

@codex review

@xuyanwen2012

Copy link
Copy Markdown
Contributor Author

Thanks for the review! Pushed an update, rebased on current main

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 82f898885f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@SS-JIA

SS-JIA commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

@xuyanwen2012 some additional context on how the wmma kernels interact with the current q4gsw dispatch on main. This is informational, not blocking.

Current behavior

When a family device (Xe2 / NVIDIA) takes over a q4gsw linear, the weight is prepacked in the legacy layout (pack_q4_linear_weight), since that is what the wmma shaders read. When the graph is later resized to M=1 (decode) or M<128, the node falls back to the legacy linear_q4gsw_coop / linear_q4gsw_tiled shaders, which read the same layout. Your resize cases in wmma/cases/correctness.json show this (M=100 → linear_q4gsw_tiled_*, M=1 → linear_q4gsw_coop_*) and validate the outputs, so correctness is fine.

On main, however, q4gsw_linear() no longer dispatches those legacy shaders. Prefill uses q4gsw_linear_gemm__w_4x8_nc / q4gsw_linear_gemm__tin__w_4x8_nc and decode uses q4gsw_linear_gemv_coop__w_4x8_nc_buffer_*, all of which read the w_4x8_nc weight layout. So on family devices, decode and small-M prefill now run on kernels that are otherwise unused and untuned.

Legacy vs w_4x8_nc weight layout

Both store the weight as 4K × 8N blocks, one ivec4 per block. Each int holds 4 K values for 2 N rows: byte k = (row A, k) in the low nibble | (row B, k) in the high nibble. They differ in where blocks are placed and which N rows share an int:

Legacy (pack_q4_linear_weight) w_4x8_nc (pack_q4_linear_weight__w_4x8)
Block index (buffer) n8 * K4 + k4 (K-contiguous) k4 * N8 + n8 (N-contiguous)
Block position (texture2d) (k4, n8) (n8, k4)
N rows paired in int i i and i + 4 2i and 2i + 1

So relative to a block at n = 0, the legacy block is [(N0,N4), (N1,N5), (N2,N6), (N3,N7)], while w_4x8 is [(N0,N1), (N2,N3), (N4,N5), (N6,N7)]. Converting between them requires changing both the block indexing and the in-block row unpacking, not just the strides.

Why w_4x8_nc was introduced (#19996)

  • One prepack serves prefill and decode. The fp32 GEMM reads the buffer as ivec4, the fp16 transposed-input GEMM reads it as ivec2, and the decode GEMV reads the same bytes as scalar ints, so there is no second copy of the weights. The adjacent-row pairing makes each ivec2 half of a block exactly one 4K × 4N tile.
  • Wider GEMM weight loads. With a 4M × 8N per-thread tile, the weights for one k4 step load as a single 16-byte ivec4 covering two adjacent 4×4 N blocks. That needs N-contiguous block placement.
  • Decode performance. The shape-adaptive nc-coop GEMV beat the previous subgroup GEMV by 3–56% on LLM decode shapes on Adreno 750, Adreno 830 and Mali-G715, and also runs on Mali, where the subgroup GEMV could not dispatch.

Proposal

I'm OK landing this as-is with respect to the above. As follow-ups:

  1. Measure decode (M=1) and small-M prefill on B580 / RTX 4070 Ti SUPER: this PR's legacy coop / tiled fallback vs main's w_4x8_nc GEMV / GEMM (family disabled).
  2. Check whether the wmma shaders can be rewritten to read w_4x8_nc directly, and what that costs in prefill performance. If it works, the fallback becomes main's current kernels and decode uses the nc-coop GEMV, with a single weight prepack.
  3. If K-contiguous block placement matters for wmma performance, we can introduce a w_4x8_kc format instead. pack_q4_linear_weight__w_4x8.glsl already has a WEIGHT_KC switch, but only the nc buffer variant is generated today.

Analysis drafted with AI assistance (Claude) from a static review of this PR and main.

@SS-JIA SS-JIA left a comment

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.

A few lower-severity comments from an AI-assisted static review (Claude) of the current head. None are blocking; see also the separate comment on the weight layout.

shader_cache_(device_.handle),
pipeline_layout_cache_(device_.handle),
// Full subgroups only on a device this Adapter created.
compute_pipeline_cache_(device_.handle, cache_data_path),

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.

A3: the family is always disabled on shared-device Adapters, though the needed state is known.

In shared-device mode (#23151), the VkDevice is created by create_vulkan_shared_device() through the owning Adapter ctor, which applies the memory-model policy and full subgroups. This wrapping Adapter then reports full_subgroups=false and supports_vulkan_memory_model()=false, so coopmat_family() returns kNone and shared-device users silently get main's kernels. Both facts are available here: enabled_device_extensions_ and enabled_device_features_.compute_full_subgroups are populated from the SharedVulkanDevice in this ctor, so the "known only for a device this Adapter created" comment in Adapter.h is not accurate for this path.

Suggested fix: pass enabled_device_features_.subgroup_size_control && enabled_device_features_.compute_full_subgroups to compute_pipeline_cache_, derive vulkan_memory_model_enabled_ from enabled_device_extensions_ as the owning ctor does, and carry vulkanMemoryModelDeviceScope in the enabled-features struct. The external-VkDevice ctor can stay conservative.

// needs VK_KHR_driver_properties.
VkPhysicalDeviceDriverProperties driver_properties{
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
bool query_driver_properties = properties.apiVersion >= VK_API_VERSION_1_2;

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.

A4: VkPhysicalDeviceDriverProperties is chained on a 1.1 instance without checking for the extension.

properties.apiVersion >= VK_API_VERSION_1_2 is the device's version, but the instance is created with VK_API_VERSION_1_1 (Runtime.cpp), so the effective API version is 1.1. Chaining a 1.2-core struct is then only valid if VK_KHR_driver_properties is supported. A device that reports 1.2+ without advertising the extension hits VUID-VkPhysicalDeviceProperties2-pNext-pNext (undefined behavior). The memory-model query above already checks the extension for exactly this reason.

Suggested fix: drop the apiVersion shortcut and always require VK_KHR_driver_properties via find_requested_device_extensions.

// stays off and shaders that declare the VulkanMemoryModel capability are
// rejected. Set before the first Adapter is created.
using VulkanMemoryModelPolicy = bool (*)(const PhysicalDevice& physical_device);
void set_vulkan_memory_model_policy(VulkanMemoryModelPolicy policy);

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.

A6: the memory-model policy hook inverts layering, and the gate check locks in an incidental limitation.

Device creation in vk_api now depends on a global function pointer that an op-layer translation unit (WmmaLinear.cpp) sets during static initialization. Whether the memory model is enabled therefore depends on link inclusion and init order, and a missing registration silently disables the family.

Separately, check_wmma_memory_model_gate in WmmaFamilyChecks.cpp asserts that every non-family device rejects linear_coopmat, matmul_coopmat and the q4gsw/dq8ca coopmat kernels. That rejection isn't a design goal: those AMD paths are unreachable on main only because supports_spirv_capability has no mapping for VulkanMemoryModel. The assertion would start failing as soon as that is fixed, for example by #22899, which enables the memory model whenever it is supported.

Suggested fix: enable VK_KHR_vulkan_memory_model (plus device scope) whenever the device supports it, inside create_logical_device, and drop the policy hook. Rely on the existing dispatch gates (subgroup size, family key) to choose kernels. Replace the "rejected on non-family devices" assertion with "family kernels pass the gate on family devices".

}

const std::vector<WmmaRow>& xe2_rows() {
static const std::vector<WmmaRow> rows = {

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.

A7: code volume and duplication.

  • The new wmma GLSL under {q4gsw,dq8ca_q4gsw}/wmma/ is about 2,750 lines across four templates. linear_q4gsw_wmma_bx differs from linear_q4gsw_wmma mainly in accumulator type and C staging, and linear_dq8ca_q4gsw_wmma_rowmajor differs from linear_dq8ca_q4gsw_wmma mainly in A staging. Each repeats B dequant, double-buffered staging and the MMA loop.
  • Tile geometry is stated twice, in the yaml variant parameters and in the WmmaTile rows here, and only the shared-memory bytes are cross-checked. A mismatched SG_GRID_* would give a wrong dispatch grid and wrong output.
  • Storage/dtype suffixes are hand-written into variant NAMEs instead of using generate_variant_forall.
  • There are now two parallel coopmat selection systems for the same two ops (the existing AMD can_use_q4gsw_coopmat path and this family table).

Suggested fix: merge _bx into linear_q4gsw_wmma behind flags (e.g. ACC_FP32 / C-in-shared), and merge row-major into linear_dq8ca_q4gsw_wmma behind an A-layout flag. Have the host test, which already reads the yamls, check each row's tile against its variant parameters. As a follow-up, fold the AMD coopmat route into this table as another family.

FRAG_LAYOUT: true
IMG_A: true
CSH_BAND: true
- NAME: linear_q4gsw_wmma_t128x128k16g44s16m8fli_buffer_texture2d_half

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.

A8 (nit): naming and stale description.

  • The i (IMG_A) suffix in ..._fli_buffer_* names is inactive for buffer IO.
  • quantize_and_pack_4h4w_with_group_sums.yaml now also emits quantize_and_pack_4w_* variants, which the file name doesn't suggest.
  • Args bound with vkapi::kReadStorageImage (Q4gswLinearWmma.cpp) are no longer listed as reads in the graph dump, because Logging.cpp checks access != MemoryAccessType::READ.
  • The PR description still refers to etvk_bench, q4gsw_linear:wmma_correctness, 11/11 host tests and base 43a7bc20bc.

Suggested fix: drop i from buffer variant names; rename the 4h4w yaml or split out the 4w variants; check access & READ && !(access & WRITE) in the logger; refresh the PR testing table for the rebased head.

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.

A5: coverage gaps in this case file. (AI-assisted static review, Claude)

  • The family rows accept any group_size % WG_TILE_K == 0, but only g64 and g128 are covered. There is no g32 case (accepted by every q4gsw row) and no g256 case (accepted by every row; the PR description says g256 projections pass).
  • All inputs are 2D. The common LLM shape [1, M, K] is accepted by the selector but untested, and no case asserts fallback for batch > 1.
  • For long-K q4gsw, Xe2 keeps fp16 accumulation while NVIDIA switches to fp32 for the same reason. The loosened atol 1.0 at K=9216 / 14336 hides that difference rather than testing it.
  • Xe2 rows have no CI coverage. That's unavoidable, but worth stating in the CI comment. The internal etvk-gpu-host-tests / etvk-eureka-tests workflows will also need a step for this directory when the PR is imported.

Suggested fix: add g32 (q4gsw) and g256 (both ops) cases, one [1, M, K] texture3d case per op, and one [2, M, K] case that must dispatch no _wmma kernel. Either document the Xe2 long-K error against the NVIDIA fp32 row, or add an fp32-accumulation Xe2 row for K > 8192.

@SS-JIA SS-JIA left a comment

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.

@xuyanwen2012 almost good to go! A couple small comments remaining. The point about weight layout and decode is non-blocking but it would be good to follow up on it 🙏 Doesn't have to be addressed in this PR, it can be done in a follow up.

RC for now; once this round of comments is addressed, I'll import the changes to Meta internal codebase, and if signals there pass, we're good to go!

@xuyanwen2012

Copy link
Copy Markdown
Contributor Author

Thanks! All six comments are addressed as suggested.

@meta-codesync

meta-codesync Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

@SS-JIA has imported this pull request. If you are a Meta employee, you can view this in D132418429.

// With READ: an image read through a storage image descriptor, which needs
// VK_IMAGE_LAYOUT_GENERAL (vk_layout gives it to every compute access other
// than a plain READ) but is not a write.
STORAGE_IMAGE = 1u << 2u,

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.

adding this field introduces a number of build errors in Meta internal repo, i.e.

xplat/executorch/backends/vulkan/runtime/vk_api/Runtime.cpp:28:11: error: enumeration value 'STORAGE_IMAGE' not handled in switch [-Werror,-Wswitch]
   28 |   switch (tag) {
      |           ^~~
1 error generated.

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.

I recommend adding -Werror and -Wswitch to the CMake build, and double checking that the build succeeds

xuyanwen2012 and others added 2 commits November 19, 2026 11:48
… in vk_api

- Pipelines with a required subgroup size are created with
  VK_PIPELINE_SHADER_STAGE_CREATE_REQUIRE_FULL_SUBGROUPS_BIT_EXT when the
  device enabled computeFullSubgroups and the local size in X (spec constant
  0) is a multiple of the subgroup size. Cooperative-matrix shaders below
  SPIR-V 1.6 need full subgroups (VUID-RuntimeSpirv-OpTypeCooperativeMatrixKHR-10770);
  the multiple-of condition keeps the flag valid (VUID 02757). The owned
  device passes what create_logical_device enabled; a device the embedder
  created keeps the previous behaviour (off).
- Query vulkanMemoryModel when VK_KHR_vulkan_memory_model is advertised and
  enable it on the logical device, so shaders that declare the
  VulkanMemoryModel capability can be created. Other devices are unchanged.
  supports_vulkan_memory_model() reports it for a device the Adapter created,
  and supports_spirv_capability() maps the VulkanMemoryModel and
  VulkanMemoryModelDeviceScope capabilities to it; without that mapping the
  capability check of pytorch#24340 rejects every shader that declares them.
- Keep the enumerated cooperative-matrix property list instead of reducing it
  to a bool, query VkPhysicalDeviceDriverProperties (Vulkan 1.2 or
  VK_KHR_driver_properties), and expose vendor_id(), driver_id(),
  cooperative_matrix_properties() and max_compute_shared_memory_size() on the
  Adapter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016AnsG4u2n3shZugcMcyUFm
Adds a selection layer for cooperative-matrix kernels of the 4-bit
quantized linear ops, keyed by architecture family instead of device name.

- CoopmatFamily.{h,cpp} (pure C++, host-testable): CoopmatDeviceKey (vendor
  ID, VkDriverId, subgroup size range, cooperative-matrix shapes, shared
  memory) and coopmat_family(), which maps a key to Xe2 (Intel, Mesa driver,
  fp16 8x16x16, int8 8x16x32, subgroup 16) or NVIDIA (proprietary driver,
  fp16 16x16x16 with fp16 and fp32 results, int8 16x16x32, subgroup 32).
  Each family has a short list of kernel rows with tile geometry, storage
  combinations and an optional shape rule; select_wmma_kernel() returns the
  first row that fits, or nothing.
- WmmaLinear.{h,cpp}: the ComputeGraph side (device key from the Adapter,
  storage mapping, predicted weight storage, workgroup grid per family tile).

A device that matches no family, or a shape no row of its family accepts,
gets no choice, and the ops keep their existing kernels. Nothing calls this
yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016AnsG4u2n3shZugcMcyUFm
xuyanwen2012 and others added 25 commits November 19, 2026 11:48
A4: selection compared the texture-IO C staging alone with
maxComputeSharedMemorySize and skipped buffer IO and the kernels that
stage C in the A tile. A device with, e.g., 32 KiB and the NVIDIA key
would select the 256-row 4w tile, which declares 45056 bytes (Ash 24576,
BshT 12288, Csh 8192).

Each row now carries the shared memory its kernel declares per IO
storage (A/B staging, parameter arrays and C staging: the Workgroup
variables of the SPIR-V), and a row fits only if that is within the
limit:

  Xe2     4w texture3d 18432, 4w buffer 16384,
          8da4w texture3d 43520, 8da4w buffer 35328
  NVIDIA  4w K > 8192 37888, 4w 256-row 45056, 4w 128-row 29184,
          8da4w row-major 35328

All are within the 48 KiB of the Arc B580, Arc Pro B70, RTX 4070 Ti
SUPER and Jetson Orin, so no measured device changes kernel. The unused
WmmaTile::csh_in_ash goes away.

Tests: coopmat_family_test SharedMemoryLimit checks the limit boundary of
every row (at the requirement the row fits, one byte below the next row
or the existing kernels take the shape, e.g. 32 KiB NVIDIA gives the
128-row 4w tile and no 8da4w kernel) and that every row fits 48 KiB.
benchmark_v2 wmma_family_shared_memory reflects the SPIR-V of every
family variant in the shader registry and requires it to equal the row
(no GPU work, so it also runs on SwiftShader). EveryRowHasShaderVariants
now fails instead of skipping when a yaml is missing. The route check
source becomes WmmaFamilyChecks.cpp.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A7: quantize_and_pack_4w_with_group_sums repeated the group traversal,
quantization and sum reduction of quantize_and_pack_4h4w_with_group_sums
and differed only in its block writer, and its C++ node builder repeated
add_quantize_and_pack_4h4w_with_group_sums_node.

The existing template gains an OUTPUT_LAYOUT axis (4h4w, the default, and
4w, which binds a scalar int array and writes each quantized row to its
row-major slot, dropping rows past M), and its yaml the two row-major
variants under their old names. add_quantize_and_pack_4h4w_with_group_sums_node
picks the variant from the packed tensor's layout, so the family builder
calls it for both layouts, and the separate shader, its builder and the
exported gwg picker go away.

The 16 existing 4h4w packer variants compile to the same SPIR-V as on
main (byte-identical), so devices without a family are unaffected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A8: the kernel declared binding 2 twice, as an unused scalar int8_t
array and as a hand-written uvec4 alias spelled to avoid the descriptor
parser of gen_vulkan_spv.py. It is now declared once through
layout_declare_tensor() as a uvec4 buffer, which both A staging loads
read; the cooperative-matrix A operands come from shared memory, so the
8-bit storage extension the scalar binding needed goes too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A6: the build-time and runtime shapes of both ops were extracted by four
copies of the same M/N/K, batch, GEMV, bias, dtype, IO storage and
packed-dim logic, so an eligibility change had to be made four times and
build-time takeover and runtime fallback could drift apart.

wmma_shape() in WmmaLinear.cpp builds the shape from explicit activation,
output, group size and bias refs and the weight storage. The callers keep
the argument decoding, the predicted (build time) versus actual (runtime)
weight storage and dq8ca's int8 layout. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
pytorch#24753 pads the packed dim of ordinary buffer tensors to a multiple of
four. In a graph the family kernels take, that dim is K for the
activations and N for the output, weight scales and weight sums, which
the rows require to be multiples of their tile (K of 16 or 64, N of 128),
and the takeover is decided once at build time, where K and N are final.
The padding is therefore empty for every buffer the family kernels and
their in-node fallbacks read or write; the dq8ca int8 activations are
kInt8x4, which pytorch#24753 leaves unchanged, and the bias placeholder (a 0-D
buffer, now four elements) is not read without a bias. Runtime resizes
change M only, which is not a packed dim. No code change is needed.

Tests: wmma/cases/correctness.json adds linear_dq8ca_q4gsw at N = 130
on buffer and texture3d IO, built at M = 256 and resized to 129, which
must keep the existing kernels on every device (linear_q4gsw requires
N % 4 == 0). Their output is not validated: the existing dq8ca kernels
are also off at N % 4 != 0 on main and before pytorch#24753, on an Arc B580
and llvmpipe. The buffer resize cases already cover M = 129 and 1, not
multiples of four, on the family kernels and fallbacks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Xe2 texture3d 4w kernel reads its input through a storage image,
which needs VK_IMAGE_LAYOUT_GENERAL, and the node got that layout by
declaring the input read-write. The input is not written, but the write
access made later readers of the same activation (e.g. the k and v
projections after q) wait on a write barrier, and benchmark_v2 infers the
input of such a case as an output: on an Arc B580 the texture3d cases
that take this kernel failed with "Unexpected output" on input (5 in
q4gsw/cases/coopmat_correctness.json, 2 in correctness.json).

vkapi gains MemoryAccessType::STORAGE_IMAGE and kReadStorageImage
(READ | STORAGE_IMAGE): a read, for barriers and hazards, that vk_layout
maps to VK_IMAGE_LAYOUT_GENERAL like every compute access other than a
plain read. The node binds the input with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The route check took the device's family from the selector it tests, so
a regression that classified an NVIDIA or Xe2 device as no family passed
on the fallback kernels; a step without profiling records passed with
route_asserted: false; and a family case whose shader or route became
unsupported reported SKIP, which leaves etvk_ops_bench's exit status 0.

ETVK_WMMA_EXPECTED_FAMILY now states the family independently of the
selector. With xe2, nvidia or none the device must match it, every step
needs profiling records, and an unsupported shader or route fails the
case. software is for devices without timestamp queries: no family, and
kernels are checked where records exist. Unset, the selector's family is
used and records are still required. GitHub CI runs the wmma collection
on its own with nvidia on the NVIDIA job and software on SwiftShader.

Checked on an Arc B580 (Mesa 26.2.6) with scratch builds: family
eligibility disabled fails 71 of 72 cases with xe2 ("Device matches
family none"), as does a build without profiling records; rejecting the
family shaders (memory-model capability unmapped) fails 52 cases ("Required
case did not run") where the unset run reported 52 SKIPs and exit status 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ETVK_WMMA_EXPECTED_FAMILY=software, which the SwiftShader job uses,
tolerated missing profiling records but also let an unsupported shader
or route reach run_case_check, which reports SKIP; etvk_ops_bench exits
0 on SKIP, so the job could pass without validating the cases.

Software runs are now strict about that like the family runs: a case
that does not run fails. Only the profiling records stay optional.

Checked on llvmpipe (Mesa 26.2.6) with a scratch build that rejects
every 4-bit linear kernel: software mode reported 71 SKIPs and exit 0
before this change, and fails the 71 cases with exit 1 after it. A
scratch build without profiling records (as on SwiftShader) passes all
72 cases in software mode with route_asserted: false.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The two N = 130 cases added for pytorch#24753 checked routing only: their
outputs were not validated, so they could not catch padded-row indexing
mistakes. They are replaced by four cases whose outputs are validated
at every step: linear_dq8ca_q4gsw at N = 130 (rows padded to 132 in the
output, weight scale and weight sum buffers), built at M = 256 and
resized to 129, on buffer and texture3d IO, with zero points 0 over four
quantization groups, or nonzero zero points with one group. Every device
runs the existing kernels for them (no family row takes N % 128 != 0).

Several groups with nonzero zero points stay out: the existing dq8ca
zero-point correction is wrong for N % 8 != 0 there (N = 129, 130, 132;
N = 136 passes), on main and before pytorch#24753 too.

Checked on an Arc B580 (Mesa 26.2.6) and llvmpipe with scratch builds of
linear_dq8ca_q4gsw_tiled that use the unpadded row length N / 4 instead
of N4: unpadded weight scale rows fail the two four-group cases (about
7300 mismatches each), unpadded output rows fail all four (about 18700
to 25500 mismatches with buffer output); the other 70 cases pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The vk_api commit enabled vulkanMemoryModel on every device that
advertises it and mapped the VulkanMemoryModel capability to it. On main
the capability gate rejects that capability, so this also let upstream
shaders that declare it (linear_coopmat, matmul_coopmat and the q4gsw /
dq8ca coopmat kernels, eligible on discrete subgroup-64 devices such as
RDNA3) pass the gate on devices that match no family: a change of
executable shaders outside the family devices.

vkapi::set_vulkan_memory_model_policy() now decides whether a logical
device the runtime creates enables the memory model; without a policy it
stays off, as on main. The family code registers one at static
initialization that enables it only when the device would match a family
(CoopmatFamily with the state the Adapter enables). Every other device keeps
main's device features and main's capability gate.

Tests: benchmark_v2 wmma_memory_model_gate. On a device that matches no
family the memory model must be neither enabled nor accepted and each of
the ten upstream VulkanMemoryModel kernels must be rejected by the gate; on
a family device it must be enabled and every family variant accepted.
With the previous behaviour (a scratch build enabling it wherever
advertised) it fails on a RADV iGPU and llvmpipe (Mesa 26.2.6); with this
change it passes there and on an Arc B580.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous commit enabled VK_KHR_vulkan_memory_model only on devices
that match a family, through a policy function that WmmaLinear.cpp
registered with vk_api during static initialization. Device creation
then depended on an op-layer translation unit being linked and
initialized first, and a missing registration silently disabled the
family.

create_logical_device now enables the extension, vulkanMemoryModel and
the device scope whenever the physical device supports them, and the
policy hook is gone. Kernel choice stays with the existing dispatch
gates (family key, subgroup size, device name). This makes upstream
shaders that declare VulkanMemoryModel (linear_coopmat, matmul_coopmat,
the q4gsw / dq8ca coopmat kernels) pass the capability gate on devices
that support the memory model and cooperative matrices, as pytorch#22899 does.

wmma_memory_model_gate now checks that a family device enables the
memory model and that every family variant passes the gate. On every
device it reports the gate's verdict on the upstream VulkanMemoryModel
shaders without asserting it.

Checked on an Arc B580 (xe2), a RADV Raphael iGPU and llvmpipe (Mesa
26.2.6): wmma/cases/correctness.json 75/75 on each. The memory model is
now enabled on all three; the ten upstream shaders pass the gate on the
B580 and llvmpipe and are rejected on RADV (no cooperative matrix).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An Adapter that borrows a shared device (pytorch#23151) built its pipeline
cache without full subgroups and reported the Vulkan memory model as
off, so coopmat_family() was none there and shared-device users got
main's kernels. Both facts are known: the SharedVulkanDevice carries the
extensions and features the VkDevice was created with, and a device the
backend creates through create_vulkan_shared_device() is created by an
owning Adapter.

SharedVulkanDeviceFeatures now also records vulkanMemoryModel and
vulkanMemoryModelDeviceScope, filled by create_logical_device. The
owning and the shared-device constructors derive full subgroups (subgroup
size control and computeFullSubgroups) and the memory model (the
extension and its feature) from the enabled extensions and features
through vk_api/EnabledDeviceState.h; shared_physical_device() masks the
memory-model features like the others. An Adapter on an external
VkDevice stays conservative: no full subgroups, no memory model.

Tests: host gtest EnabledDeviceState (the key from a created device's
state matches xe2 / nvidia; no declared features, no full subgroups, or
the memory-model extension without its feature, or the reverse, match
none). vulkan_shared_device_test gains CreatedDeviceKeepsCoopmatFamily
(a borrowing Adapter has the owner's full subgroups, memory model and
family) and ImportedDeviceHasNoCoopmatFamily. On an Arc B580 (Mesa
26.2.6) the borrowing Adapter reports xe2; with the previous constructor
the first test fails (none). The suite passes on the B580, a RADV iGPU
and llvmpipe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PhysicalDevice chained VkPhysicalDeviceDriverProperties whenever the
device reported apiVersion >= 1.2. The instance is created with Vulkan
1.1, so the effective version is 1.1 and the struct is only valid with
VK_KHR_driver_properties; a device that reports 1.2+ without advertising
the extension would hit VUID-VkPhysicalDeviceProperties2-pNext-pNext.
The query now always requires the extension, found through
find_requested_device_extensions like the memory-model query. Without it
the driver ID stays 0 and the device matches no family.

The Arc B580, Arc Pro B70, RADV, llvmpipe and Jetson Orin drivers all
advertise the extension; the B580 still matches xe2 (wmma correctness
75/75) and the RADV iGPU none.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
linear_q4gsw_wmma_bx differed from linear_q4gsw_wmma in three places
(texel-wise B staging, fp32 accumulation, the texture3d drain staged in
the A tile) and repeated the rest: B dequant, double-buffered staging
and the MMA loop. Those three are now flags of linear_q4gsw_wmma
(B_TEXEL, ACC_FP32, CSH_IN_ASH), and the NVIDIA long-K variant moves to
linear_q4gsw_wmma.yaml under its old name, so the dispatch and the
family rows are unchanged. Each flag keeps the code of the template it
came from, so every variant compiles as before.

Checked: all 992 SPIR-V modules of the build, including
linear_q4gsw_wmma_bx_t128x128k32g42s32f32c_texture3d_texture2d_half,
are byte-identical to the previous commit (glslc, shaderc 2026.2).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
linear_dq8ca_q4gsw_wmma_rowmajor differed from linear_dq8ca_q4gsw_wmma
in its A layout (row-major int8 staged as raw 16-byte vectors, a partial
last M tile, the drain band staged in the A tile) and in whole-texel B
staging, and repeated the rest: the activation and weight parameters,
the nested group / chunk loop, the int8 MMA, the group epilog and the
zero-point correction. The row-major code is now the ROWMAJOR_A branch
of linear_dq8ca_q4gsw_wmma (the int8 activation binding is uvec4
there), and the NVIDIA variant moves to linear_dq8ca_q4gsw_wmma.yaml
under its old name, so the dispatch and the family rows are unchanged.
The two bodies (1059 lines) become one of 742.

Checked: all 992 SPIR-V modules of the build, including both zero-point
variants of linear_dq8ca_q4gsw_wmma_rowmajor_t128x128k64g24s32mk32, are
byte-identical to the previous commit (glslc, shaderc 2026.2).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The i of linear_q4gsw_wmma_t128x128k16g44s16m8fli_buffer_texture2d_half
stood for IMG_A, which only applies to texture3d IO. The variant, its
family row and the tests that name it drop it (now ..._m8fl_buffer_...),
and the variant no longer sets IMG_A.

Checked: its SPIR-V is byte-identical to the old variant's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
quantize_and_pack_4h4w_with_group_sums.{glsl,yaml} also emits the
quantize_and_pack_4w_with_group_sums_* variants since the row-major
layout was folded into it, which the file name did not say. The
template is now quantize_and_pack_with_group_sums; its variant names,
and so the dispatch, are unchanged.

Checked: all 24 variants compile to the same SPIR-V as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
print_readable() listed an argument as read only when its access was
exactly MemoryAccessType::READ, so inputs bound with kReadStorageImage
(READ | STORAGE_IMAGE, the Xe2 texture3d q4gsw family kernel) appeared
in neither column. A read is now any access with READ and without WRITE.

Checked with a scratch call on an Arc B580: the family kernel's input
appears under READ_arg.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The variant NAMEs spelled out every storage and dtype suffix, and the
two Xe2 8da4w tiles were listed once per IO storage. The suffixes now
come from generate_variant_forall: WEIGHT_STORAGE (texture2d) and DTYPE
(half) in both yamls, and IO_STORAGE (texture3d, buffer) in the dq8ca
one, whose Xe2 tiles are listed once. A variant built for one IO
storage sets IO_STORAGE, which the generator then does not iterate, and
keeps the IO suffix in its NAME. Every generated name is unchanged.

The templates take DTYPE for their fp16 bindings and define PRECISION
as highp: DTYPE half would otherwise let --auto-use-mediump
(EXECUTORCH_VULKAN_USE_MEDIUMP_FOR_FP16) switch these kernels to
mediump, which they are not validated with.

EveryRowHasShaderVariants expands the yamls as gen_vulkan_spv.py does
(for the subset of the format they use) instead of searching for NAME
lines, and also checks the dq8ca zero-point variants.

Checked: all 992 SPIR-V modules are byte-identical to the previous
commit, under the same names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Tile geometry is stated twice, in the yaml variant parameters and in the
WmmaTile of each family row, and only the shared-memory bytes were
cross-checked (against the SPIR-V, in benchmark_v2). A mismatched
SG_GRID_* gives the dispatch a wrong workgroup size, a mismatched tile a
wrong grid; both give wrong outputs.

RowTilesMatchShaderVariants takes every kernel name each row can
dispatch (both IO storages, both zero-point dtypes) and requires the
expanded yaml parameters of that variant to equal the row:
WG_TILE_{M,N,K}, SG_GRID_{X,Y}, SUBGROUP_SIZE, MMA_M, the IO storage,
a texture2d weight and fp16, plus ROWMAJOR_A (dq8ca) or IMG_A on
texture3d (q4gsw) against the row's flags. 15 variants are checked.

Checked: a yaml with SG_GRID_X 2 instead of 4 for the NVIDIA 256-row
tile, and a row-major row with a 4 x 2 instead of 2 x 4 subgroup grid,
each fail the test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… family

wmma/cases/correctness.json covered g64 and g128 only, 2-D inputs only,
and checked K = 9216 / 14336 q4gsw at atol 1.0, which hid that Xe2 keeps
fp16 accumulation there while NVIDIA switches to fp32. Added:
- g32 q4gsw (every q4gsw row; also at K = 9216) on both IO storages, and
  g32 dq8ca, which no row takes;
- g256 for both ops on both IO storages;
- [1, M, K] texture3d per op (the family kernel), and [2, M, K] per op,
  which must dispatch no _wmma kernel.

Long K: max |error| against the CPU reference over 5 seeds (M = 256,
2026-11-13) is 0.23 at K = 14336 and 0.13 at K = 9216 for the Xe2 fp16
rows (Arc B580), 0.008 for the NVIDIA fp32 row (Jetson Orin), and 0.77
at K = 14336 for main's q4gsw GEMM on the B580. Xe2 keeps fp16
accumulation: its error is within the 0.25 every K <= 8192 case allows
both families, near the NVIDIA fp16 row's 0.14 at K = 8192, and smaller
than main's. The numbers are noted at the rows in CoopmatFamily.cpp.
Steps that dispatch a family kernel at K > 8192 are now validated at
that family's bound (xe2 atol 0.3, nvidia 0.03, rtol 0) through a new
per-step family_validation_method; other devices and fallback steps keep
atol 1.0, which main's kernel needs. operator_dynamic_resize takes a
per-step validation_method for it.

Two shapes are wrong with the existing kernels on main (4d292c9) on
an Arc B580, a RADV iGPU and llvmpipe: [2, M, K] for both ops computes
only the first batch (every mismatch is at index >= M * N), and
linear_dq8ca_q4gsw_tiled is wrong at group size 256 (max error 61; g128
passes). The [2, M, K] cases therefore check routing only, and the g256
dq8ca cases validate outputs only on family devices (a family entry
validates even when the step does not).

The CI comments say that the xe2 rows have no GitHub CI coverage.

Checked: 88/88 on an Arc B580 (xe2), a RADV iGPU (none) and llvmpipe
(software), Mesa 26.2.6; an xe2 atol of 0.05 fails the K = 14336 case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The owning Adapter took the pipeline cache's full-subgroups flag from
supports_subgroup_size_control() && supports_compute_full_subgroups(),
which return false under ETVK_FORCE_NO_EXTENSIONS. Deriving it from the
enabled device features (Family kernels on shared-device Adapters) made
it true there on devices that enable computeFullSubgroups. No pipeline
gets a required subgroup size in that mode, so nothing changed in
practice, but full_subgroups_enabled() now returns false under it, as
before.

Checked: both preprocessor branches; the default build's etvk_ops_bench
and vulkan_shared_device_test (both link Adapter.cpp) are byte-identical
to the previous commit's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
EnabledDeviceState expected the state a created Xe2 / NVIDIA device
enables to match its family in every configuration. Since full
subgroups stay off under ETVK_FORCE_NO_EXTENSIONS (backends/vulkan/
targets.bzl defines it for etvk.force_no_extensions=1), both
expectations failed there with kNone.

The test now asserts the configuration's behaviour: under
ETVK_FORCE_NO_EXTENSIONS full_subgroups_enabled() is false and both
keys match no family; otherwise it is true and the keys match xe2 and
nvidia, as before. The cases that must match no family are unchanged.

Checked: vulkan_coopmat_family_test 14/14 in a normal build and in a
build with -DETVK_FORCE_NO_EXTENSIONS; the previous test fails the
latter with two kNone mismatches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…vice

The two g256 dq8ca route cases validated their outputs on family devices
only, because linear_dq8ca_q4gsw_tiled was wrong at group size 256 on main.
c459886 fixed that, so the steps drop validate_output: false and the
family_validation_method that restated the case's method. Devices without a
family now validate the existing kernel's output there too.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Handle STORAGE_IMAGE in the MemoryAccessType printer and enable
-Wswitch and -Werror=switch in the Vulkan backend, benchmark, and
host family test builds.

Fully initialize the Vulkan feature and property structs, iterate
converted shader names by value, and give the benchmark callbacks
internal linkage to resolve the additional Clang warnings.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
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