Repository navigation
[ET-VK] Cooperative-matrix kernels for 4-bit linear on Intel Xe2 and NVIDIA - #24000
Conversation
🔗 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.
|
This PR needs a
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
left a comment
There was a problem hiding this comment.
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.
| 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); |
There was a problem hiding this comment.
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.
| ${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)} |
There was a problem hiding this comment.
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.
| 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(); |
There was a problem hiding this comment.
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.
| // 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; | ||
| } | ||
| } |
There was a problem hiding this comment.
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") { |
There was a problem hiding this comment.
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.
| WmmaShape q4gsw_runtime_shape( | ||
| ComputeGraph* graph, | ||
| const std::vector<ArgGroup>& args, | ||
| const std::vector<ValueRef>& resize_args) { |
There was a problem hiding this comment.
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.
| 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); | ||
|
|
There was a problem hiding this comment.
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.
| ${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[]; | ||
| }; |
There was a problem hiding this comment.
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.
|
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:
Other than that, we should be good to merge! |
|
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 I'm unsure if this impacts the wmma shaders at all, but just something to be aware of. |
742716f to
82f8988
Compare
|
@codex review |
|
Thanks for the review! Pushed an update, rebased on current main |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@xuyanwen2012 some additional context on how the wmma kernels interact with the current q4gsw dispatch on Current behaviorWhen a family device (Xe2 / NVIDIA) takes over a On Legacy vs
|
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 asivec2, 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 eachivec2half 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
ivec4covering 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:
- Measure decode (M=1) and small-M prefill on B580 / RTX 4070 Ti SUPER: this PR's legacy
coop/tiledfallback vsmain'sw_4x8_ncGEMV / GEMM (family disabled). - Check whether the wmma shaders can be rewritten to read
w_4x8_ncdirectly, and what that costs in prefill performance. If it works, the fallback becomesmain's current kernels and decode uses the nc-coop GEMV, with a single weight prepack. - If K-contiguous block placement matters for wmma performance, we can introduce a
w_4x8_kcformat instead.pack_q4_linear_weight__w_4x8.glslalready has aWEIGHT_KCswitch, but only thencbuffer variant is generated today.
Analysis drafted with AI assistance (Claude) from a static review of this PR and main.
SS-JIA
left a comment
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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 = { |
There was a problem hiding this comment.
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_bxdiffers fromlinear_q4gsw_wmmamainly in accumulator type and C staging, andlinear_dq8ca_q4gsw_wmma_rowmajordiffers fromlinear_dq8ca_q4gsw_wmmamainly 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
WmmaTilerows here, and only the shared-memory bytes are cross-checked. A mismatchedSG_GRID_*would give a wrong dispatch grid and wrong output. - Storage/dtype suffixes are hand-written into variant
NAMEs instead of usinggenerate_variant_forall. - There are now two parallel coopmat selection systems for the same two ops (the existing AMD
can_use_q4gsw_coopmatpath 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 |
There was a problem hiding this comment.
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.yamlnow also emitsquantize_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, becauseLogging.cppchecksaccess != MemoryAccessType::READ. - The PR description still refers to
etvk_bench,q4gsw_linear:wmma_correctness, 11/11 host tests and base43a7bc20bc.
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.
There was a problem hiding this comment.
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
atol1.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-testsworkflows 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
left a comment
There was a problem hiding this comment.
@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!
9a9fb25 to
b810ad0
Compare
|
Thanks! All six comments are addressed as suggested. |
|
@SS-JIA has imported this pull request. If you are a Meta employee, you can view this in D132418429. |
221c089 to
f789181
Compare
| // 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, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I recommend adding -Werror and -Wswitch to the CMake build, and double checking that the build succeeds
1ab7e41 to
ba621ef
Compare
… 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
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]>
ba621ef to
0fa9530
Compare
Summary
Today the cooperative-matrix path of
q4gswanddq8ca_q4gswlinear only runs on devices with subgroup size 64whose 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-weightlinear (
dq8ca_q4gsw, 8da4w) on two architecture families: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
vk_api:REQUIRE_FULL_SUBGROUPSon pipelines with a required subgroup size when the device enabledcomputeFullSubgroupsand the local size in X is a multiple of it (VUID-RuntimeSpirv-OpTypeCooperativeMatrixKHR-10770,VUID 02757).
VK_KHR_vulkan_memory_model(and its device scope) whenever the device supports it, and map theVulkanMemoryModel/VulkanMemoryModelDeviceScopeSPIR-V capabilities to it.SharedVulkanDeviceFeatures. Shared-device Adapters derive fullsubgroups and the memory model from the device's enabled extensions and features, as the owning Adapter
does (
vk_api/EnabledDeviceState.h). Adapters on an externalVkDevicestay conservative.VkPhysicalDeviceDriverProperties, only withVK_KHR_driver_properties), thecooperative-matrix property list and the maximum compute shared memory.
kReadStorageImage, a read access that selectsVK_IMAGE_LAYOUT_GENERAL. The graph dump lists it asa read.
impl/gemm/linear/qw/wmma/CoopmatFamily.{h,cpp}: the family key and one table of kernel rows per family.optional shape rule.
fits falls back to the existing kernel.
WmmaLinear.*builds the key (from an Adapter or a graph) and the shape.impl/gemm/linear/qw/q4gsw/wmma/Q4gswLinearWmma.*,impl/gemm/linear/qw/dq8ca_q4gsw/wmma/Dq8caQ4gswLinearWmma.*:dispatch, hooked into
Q4gswLinear.cppandDq8caQ4gswLinear.cpp(7 lines each). Weight scales areconverted to the output dtype, so fp32-scale and floating-zero-point models take the family kernels too.
glsl/gemm/linear/qw/{q4gsw,dq8ca_q4gsw}/wmma/:linear_q4gsw_wmmaandlinear_dq8ca_q4gsw_wmma, each with one*_body.glslh.B_TEXEL,ACC_FP32,CSH_IN_ASH,FRAG_LAYOUT,IMG_A,CSH_BAND,B_COLMAJOR.ROWMAJOR_A,ORDER_NB_MAX,A_MULTI_BLOCK.generate_variant_forall. Thetemplates define
PRECISION highpthemselves, so--auto-use-mediumpdoes not change them.quantize_and_pack_with_group_sums.{glsl,yaml}, gainsan
OUTPUT_LAYOUTaxis with two row-major variant names (quantize_and_pack_4w_with_group_sums_*). Its 16existing variants compile to the same SPIR-V as before.
test/custom_ops/coopmat_family_test.cpp: host-only gtest of the key and the selection (14 tests). Itcovers:
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 theowner'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 intest-vulkan-operators-linux(SwiftShader) andtest-vulkan-nvidia.wmma_family_routecheck:operator_dynamic_resizesteps that also assert the kerneleach step dispatches for the device's family. The family is stated by
ETVK_WMMA_EXPECTED_FAMILY(
nvidiaon the NVIDIA job,softwareon SwiftShader), not taken from the selector. In strict mode acase that does not run fails.
[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.
Testing).
wmma_family_shared_memorychecks the row table against the SPIR-V.wmma_memory_model_gatechecksthat family kernels pass the capability gate on family devices.
performance.jsonhas the Llama 3.2 1B projections.The Xe2 rows have no GitHub CI coverage (no runner has an Xe2 GPU).
t128x128k16g82s16m8flib(texture3d),t128x128k16g44s16m8fl(buffer)t128x128k64g84s16m8i; blocked workgroup order...n13when K*N >= 20e6t256x128k16g42s32btfor K <= 8192;t128x128k16g22s32where the 256-row tile does not fit;bx_t128x128k32g42s32f32c(fp32 accumulation) for K > 8192rowmajor_t128x128k64g24s32mk32The 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. Measured2026-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:
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, basemain311d96d60d), 2026-11-13 (wmma set rerun 2026-11-16),etvk_ops_bench --validation_only:wmma/correctnessq4gsw/correctnesscoopmat_correctnessfpa_correctnessxe2)none)software)On the same commits before the last rebase (base
main4d292c9733), 2026-11-13:wmma/correctnessq4gsw/correctnesscoopmat_correctnessfpa_correctnessxe2)nvidia)none)softwareandnone)* Two
linear_dq8ca_q4gswbuffer cases that no family row takes failed on Intel on that base, as onmainatthe 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_FAMILYset to the device's family. Everyroute 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
maintoo.Host tests.
vulkan_coopmat_family_testpasses 14/14.vulkan_shared_device_testpasses 41/41 on theB580, 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
VulkanMemoryModelcoopmat shaders is selected on these devices. They needa Radeon/Xclipse name or subgroup size 64.
Long K. Max |error| against the CPU reference over 5 seeds (M = 256):
main's q4gsw GEMM (B580)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
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.
VkDevice. An Adapter on an externalVkDevicedoes not know whether full subgroups and thememory model are enabled, so it keeps the existing kernels. Shared devices carry that state and match.
linear_coopmat*,matmul_coopmat*and Radeon/Xclipselinear_{,dq8ca_}q4gsw_coopmat_*shaders thereforepass 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.
0.25 every K <= 8192 case allows, and below
main's kernel on the same device.it is slower (16.8e6) and the smallest where it is faster (21.2e6) on both Xe2 cards.
case on
mainas well and is not changed here.unchanged. Folding the AMD coopmat route into the family table is a possible follow-up.
linear_q4gsw_{coop,tiled},which read the legacy layout the family kernels share.
main'sw_4x8_ncGEMV/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 atM = 64 and 100.
main's kernels are faster from M = 64 on (fallback 1.19x / 1.36x at M = 64 / 100) andon par for decode.
w_4x8_ncfrom the family kernels is a follow-up.main,linear_q4gsw/linear_dq8ca_q4gswwith a
[2, M, K]input compute only the first batch.etvk_ops_benchon the 4070 Ti (driver 615.71) occasionally aborts at exit after all cases have passed(
ComputePipelineCache::purgein~Adapterracing 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