Repository navigation
[ET-VK][runtime] Align buffer packed dimensions to four - #24753
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/24753
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (2 Unrelated Failures)As of commit 0617be1 with merge base 9517b6b ( BROKEN TRUNK - The following jobs failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This PR needs a
|
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * #24756 * #24755 * #24754 * #24753 * __->__ #24752 ## Ulterior Motive Prepare the unary and binary op helpers for fused ops, which may apply more than one op and so have no single `op_type` specialization constant. ## Rationale **What**: `apply_unary_op` and `apply_binary_op` take the op type as their first argument instead of reading the including shader's `op_type` specialization constant. **Why**: A fused shader can then pass a different op type to each call. ## Details - `apply_unary_op` / `apply_binary_op` - **Before**: `apply_unary_op(X, A, B)` and `apply_binary_op(X, Y, A)` read the global `op_type`, so every including shader had to declare it. - **After**: `apply_unary_op(op_type, X, A, B)` and `apply_binary_op(op_type, X, Y, A)`. Existing shaders pass their `op_type` specialization constant, so drivers still fold the switch. ```glsl // Fused binary + unary, each op selected independently vec4 sum = apply_binary_op(binary_op_type, a, b, alpha); vec4 out_texel = apply_unary_op(UNARY_OP_RELU, sum, 0.0, 0.0); ``` Authored with Claude Code. Differential Revision: D130297301 Pull Request resolved: #24752
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * #24756 * #24755 * __->__ #24754 * #24753 * #24752 ## Ulterior Motive Make buffer storage behave more like texture storage, so one shader can service both storage types and buffer tensors need only a single vectorized shader. Zero-valued padding lets later vectorized operators consume full vectors without masking. ## Rationale **What**: Unary operators keep the padding of their outputs zero, and buffer and texture tensors share one vectorized unary shader. **Why**: Buffer tensors now pad their packed dim to four, like textures. If every operator leaves that padding zero, consumers can load whole vec4s without masking. Padding to four also makes buffer vec4 loads always in bounds, so the per-element buffer shader is no longer needed. ## Details - Unary shader - **Before**: buffers used a scalar path, one element per thread; textures used a vec4 path. Neither kept padding zero. - **After**: one vec4 path for both. Buffers dispatch padded numel / 4 threads and index the buffer as vec4s. Math runs in `texel_type` (fp32 for half). Ops that map zero to zero skip masking. Others zero padding lanes when `op(0) != 0` for the given bounds, e.g. `clamp(0, 1, 2)`. - Input padding is assumed zero: an op that maps zero to zero keeps output padding zero only if its input's padding is zero. - `unary_op_preserves_zero(op_type)` in `unary_op.glslh` lists the ops that map zero to zero. Like `apply_unary_op`, it takes the op type as an argument. - Dispatch - New `default_pick_vec4_gwg` in `Common`: one thread per output vec4. Buffers get padded numel / 4 threads; textures keep the texel grid. - The output's hashed layout is passed as a spec constant. Input and output must match in storage type and dtype. Buffers must also match in hashed layout, since the shader reads and writes the same texel index; textures need standard axis maps and matching packed dims. - Padding helpers in `indexing.glslh` - `num_valid_lanes` and `mask_padding_lanes` take a buffer texel index, a texture position or a `TensorIndex`. When the packed dim needs no padding, `mask_padding_lanes` returns after one check that every thread evaluates the same way. - Generated correctness tests - **Before**: generated tests compared logical outputs only. - **After**: suites can opt into a physical padding check. `OutputPaddingCheck` poisons the output's padding through an aliased padded view before execution, then reads it back and checks it is zero, separately from the logical comparison. A packed dim beyond the tensor's rank is innermost in that view. Benchmark generation does not insert these checks. ```python suite.check_zero_padding = True ``` - Enabled for the unary suites, the dedicated `tan` suite and GELU, which now run width-, height- and channels-packed. - New padding-checked suites: `relu`, `sigmoid`, `tanh` and `abs` over [-2, 2]; `clamp` and `hardtanh` with bounds on both sides of zero; `clamp` with `None` bounds and int32 inputs; `bitwise_not` and `logical_not` on bool. Smaller changes: - Registering a second suite for an op adds to the first instead of replacing it. The dedicated `tan` suite gets a name suffix. - Optional scalar arguments generate `add_none()` or a scalar value. - New `test_generator` Python unit test target. - New `dynamic_clamp_zeroes_output_padding` test: clamp with SymInt bounds must zero output padding that was poisoned before execution. Review `unary.glsl`, `unary_op.glslh` and `indexing.glslh` first, then `UnaryOp.cpp` and `Common`, then the test generator. Authored with Codex and Claude Code. Differential Revision: D130297303 Pull Request resolved: #24754
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * #24756 * __->__ #24755 * #24754 * #24753 * #24752 ## Ulterior Motive Make buffer storage behave more like texture storage, so one shader can service both storage types and buffer tensors need only a single vectorized shader. This extends the unary zero-padding work to binary and permute outputs. ## Rationale **What**: Binary tensor-tensor and tensor-scalar ops, and texture permute, keep the padding of their outputs zero. Each binary op family now has one vectorized shader for buffers and textures. **Why**: Consumers can load whole vec4s only if every producer leaves padding zero. With buffers padded to four, the buffer binary shaders can also use vec4 loads, which makes them much faster. ## Details - Binary shaders - **Before**: `binary_op_{buffer,texture}` and `binary_scalar_{buffer,texture}`. Buffers ran one element per thread and computed in the storage type, so fp16 floor division rounded its quotient to fp16 before `floor`. - **After**: `binary` and `binary_scalar`, one vec4 per thread for both storage types, computing in `texel_type` (fp32 for half). Shader names are unchanged. `alpha` is cast to the component type, so int32 `add` and `sub` stay exact. - Floor division - **Before**: int32 floor division truncated toward zero, and `div.Tensor_mode` ran floor division for every rounding mode. - **After**: int32 floor division rounds toward negative infinity. Only `rounding_mode="floor"` is supported: the partitioner keeps other modes on CPU, and dispatch checks the mode. - Broadcast detection - **Before**: `should_broadcast` and the texture packed-dim broadcast flags were spec constants set at build time. Resizing an input to or from a broadcast shape gave wrong results. - **After**: both are computed at run time from tensor metadata. When both inputs match the output's sizes and strides (buffers) or sizes and layout (textures), texels load at the output's index. An input with `size_at(in, packed_dim) < size_at(out, packed_dim)` broadcasts along the packed dim; its lane 0 is copied to all lanes. - Buffer broadcasting - The texel's first element is decoded to a tensor index and clamped per input. The packed dim has stride 1 and is padded to four, so the clamped index starts an input texel. - Padding - `binary_op_preserves_zero(op_type, alpha)` in `binary_op.glslh` lists the tensor-tensor ops that map two zeros to zero. Like `apply_binary_op`, it takes the op type as an argument. `add` and `sub` qualify only for a finite `alpha`, since `0 * inf` is NaN. - Those ops mask padding lanes only when an input broadcasts along the packed dim, since the copied lane fills padding lanes. Other tensor-tensor ops and all tensor-scalar ops always mask; `mul` by an infinite scalar maps zero to NaN. This replaces the texture shader's division-only padding fix. The mask returns after one check when the packed dim needs no padding. - Permute - Textures that keep the packed dim still copy whole texels. Otherwise each output lane is gathered as before. Padding lanes re-read the last valid element, so every fetch stays in bounds, and are zeroed before the store. - Dispatch - Binary ops use `default_pick_vec4_gwg`. Texture dispatch for binary, tensor-scalar and permute checks standard axis maps. Tensor-scalar dispatch checks matching packed dims and passes the output's hashed layout as a spec constant. Smaller changes: - `size_at(TextureMetadata, dim)` mirrors the buffer accessor. - The unused `is_packed_dim_broadcasted` and `create_broadcast_params` are removed. - Tensor views set legacy uniforms only for ranks up to four, and derive logical limits from the view's axis map. - Generated tests: - Binary, comparison, bitwise, tensor-scalar and permute registrations check zero padding. - Comparison tests are re-enabled with int32 inputs. - Tensor `pow` and floor division use the binary case matrix. Floor division also runs int32, with operands in [-16, 17) from a new `make_nonzero_randint_tensor` generator, so floor and truncation differ. - New int32 `add`/`sub` suite with values in [2^24, 2^25), which fp32 cannot all represent. - New `add`/`sub` suite with an infinite `alpha`, and `mul.Scalar` suite with an infinite scalar. - Tensor-scalar cases cover zero and negative scalars. - `logical_and` uses the bitwise suite. - Optional string arguments, such as floor division's rounding mode, are generated. - `test_vulkan_shader_names.py` checks the merged `binary` template. - New `binary_packed_dim_broadcast_after_resize` test. - New `test_vulkan_backend_trunc_div_is_not_delegated` delegate test. Review `binary.glsl`, `binary_op.glslh` and `binary_scalar.glsl` first, then `permute_texture.glsl`, dispatch, `Tensor.cpp` and tests. Authored with Codex and Claude Code. Differential Revision: D130297306 Pull Request resolved: #24755
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * __->__ #24756 * #24755 * #24754 * #24753 * #24752 ## Ulterior Motive Make buffer storage behave more like texture storage, so one shader can service both storage types. Earlier commits in this stack gave unary and binary tensor-tensor ops one shader each, selected by an `op_type` specialization constant. This commit does the same for tensor-scalar ops. ## Rationale **What**: The tensor-scalar ops (`pow.Tensor_Scalar`, `mul.Scalar`, and `eq`, `ne`, `lt`, `le`, `gt`, `ge` `.Scalar`) share one arithmetic and one comparison shader variant family. The op is selected at dispatch through an `op_type` specialization constant. **Why**: Each op had its own variant family, which multiplied the number of compiled shaders by the number of ops for no change in the code each one runs. ## Details - Shader variants - **Before**: one family per op, `{op}_scalar_{storage}_{dtype}_{scalar}`, with the op inlined through an `OPERATOR` yaml parameter: 8 ops × 2 storages × 4 dtype pairs = 64 shaders. - **After**: `binary_scalar_op` (`pow`, `mul`) and `binary_scalar_cmp` (comparisons, which write uint8): 2 × 2 × 4 = 16 shaders. A host `dev` build of `etvk_ops_bench` shrinks by 514 KiB. - Op selection - `apply_binary_scalar_op(op_type, X, Y)` in `binary_scalar.glsl` switches on the spec constant, which the compiler folds. Each op computes what its `OPERATOR` expression did, in the same promoted type. - `op_type` takes `BinaryOpType` values, which gains `kNe`. Only the tensor-scalar shader implements `kNe`. - Dispatch - `add_binary_scalar_op_node` takes a `BinaryOpType` instead of an op name and picks the comparison family for every op other than `mul` and `pow`. - `test_vulkan_shader_names.py` checks that every name the tensor-scalar dispatch can build is generated. Authored with Claude Code. Differential Revision: D130297164 Pull Request resolved: #24756
Pull Request resolved: #24753 ## Ulterior Motive Make buffer storage behave more like texture storage, so one shader can service both storage types. Textures already pad the packed dimension to four elements; buffers now do the same. This also allows a single vectorized shader for buffer tensors instead of separate scalar and vector variants. ## Rationale **What**: Align the packed dimension of ordinary buffer tensors to four scalar elements. Update dispatch, indexing and tensor contracts for the physical padding. **Why**: Vector tail accesses on odd-sized rows could cross row or allocation boundaries. Aligned physical rows make those accesses safe without changing logical tensor shapes. ## Details - Buffer representation - **Before**: `packed_dim_align` was `1`, so logical and physical row lengths matched. - **After**: `packed_dim_align` is `4`; padded sizes, strides, metadata and allocations include row padding. `kInt8x4` is unchanged. - Implicit packed dim - **Before**: unpadded buffers had no storage for a packed dim beyond the tensor's rank. - **After**: as in textures, that dim is padded to four and innermost, so each element is followed by three padding lanes. `BufferMetadata` and the hashed layout list it first in the dim order with stride 1, so index decoding treats its padding as out of bounds. Such tensors are not contiguous. - Dispatch and indexing - **Before**: buffer kernels dispatched logical numel, and several shaders used logical widths as physical strides. - **After**: ordinary buffers dispatch physical numel. Layout-sensitive shaders index through `BufferMetadata`. - GEMM selection - **Before**: odd dimensions selected scalar linear and matmul shaders. - **After**: every ordinary buffer shape selects the vector shaders. Padding lanes may hold non-finite values, so the last partial K vector is masked after the main K loop; full vectors load unmasked. - SDPA head_dim tail - **Before**: LLM attention weights read the padding lanes of the last partial head_dim vector unmasked. Fused SDPA zeroed them on every loop iteration. - **After**: both paths mask the Q and K padding lanes of the last partial head_dim vector. The tiled kernel masks once after the main loop. The coop kernel masks inside the loop, since each worker covers about one vector. - Native backend views - **Before**: static view, squeeze, unsqueeze, permute, transpose and select of a buffer aliased their source. - **After**: they become copies when the source or view can carry padding, because a view pads its own sizes along its source's packed dim. Transpose runs as `permute_copy`, since ET-VK has no `transpose_copy`. `alias` keeps aliasing. Views in mutated alias groups must stay aliases, so such a buffer view that can carry padding is rejected at build time. - Tensor contracts - **Before**: Q4 embedding indices, fused CE logits and per-row reduction inputs had no layout checks. AdamW checked only that numels match. - **After**: each requires a contiguous width-packed buffer, matching the padded row stride its shader assumes. AdamW requires `m`, `v` and `grad` to match `param`'s sizes and hashed layout, since its shader indexes all four with one padded offset. Smaller changes: - `has_same_physical_element_order` keeps direct buffer copies when padding and element order match. - Unary shaders bound-check against output metadata instead of push constants, so buffers cover padded numel. - Unused scalar linear/matmul templates are removed. - Interleaved RoPE uses vector frequency loads. - Legacy 4W4C QDQ kernels use physical strides. - Direct-copy prepack sends padded buffers through standard prepack. - Q4 embedding reads indices by padded row, and reads 1-D per-row scales with stride 1. - Layer norm and RMS norm prepack buffer weights width-packed, since their shaders index them densely. - Buffer arange writes by logical index and zeroes padding. Zero-padding enforcement is deferred to follow-up commits. Review `Tensor.cpp` and `ComputeGraph.cpp` first, staging and layout-conversion shaders second, operator kernels third, then GEMM, the native backend and tests. Authored with Codex and Claude Code. ghstack-source-id: 467556304 @exported-using-ghexport Differential Revision: [D124585167](https://our.internmc.facebook.com/intern/diff/D124585167/)
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 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]>
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 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]>
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 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]>
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 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]>
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 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]>
…NVIDIA (#24000) ## 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 #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](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Stack from ghstack (oldest at bottom):
Ulterior Motive
Make buffer storage behave more like texture storage, so one shader can service
both storage types. Textures already pad the packed dimension to four elements;
buffers now do the same. This also allows a single vectorized shader for buffer
tensors instead of separate scalar and vector variants.
Rationale
What: Align the packed dimension of ordinary buffer tensors to four scalar
elements. Update dispatch, indexing and tensor contracts for the physical
padding.
Why: Vector tail accesses on odd-sized rows could cross row or allocation
boundaries. Aligned physical rows make those accesses safe without changing
logical tensor shapes.
Details
packed_dim_alignwas1, so logical and physical row lengthsmatched.
packed_dim_alignis4; padded sizes, strides, metadata andallocations include row padding.
kInt8x4is unchanged.tensor's rank.
each element is followed by three padding lanes.
BufferMetadataand thehashed layout list it first in the dim order with stride 1, so index
decoding treats its padding as out of bounds. Such tensors are not
contiguous.
used logical widths as physical strides.
shaders index through
BufferMetadata.lanes may hold non-finite values, so the last partial K vector is masked
after the main K loop; full vectors load unmasked.
partial head_dim vector unmasked. Fused SDPA zeroed them on every loop
iteration.
head_dim vector. The tiled kernel masks once after the main loop. The coop
kernel masks inside the loop, since each worker covers about one vector.
of a buffer aliased their source.
because a view pads its own sizes along its source's packed dim.
Transpose runs as
permute_copy, since ET-VK has notranspose_copy.aliaskeeps aliasing. Views in mutated alias groups must stay aliases,so such a buffer view that can carry padding is rejected at build time.
inputs had no layout checks. AdamW checked only that numels match.
padded row stride its shader assumes. AdamW requires
m,vandgradto match
param's sizes and hashed layout, since its shader indexes allfour with one padded offset.
Smaller changes:
has_same_physical_element_orderkeeps direct buffer copies when paddingand element order match.
constants, so buffers cover padded numel.
stride 1.
shaders index them densely.
Zero-padding enforcement is deferred to follow-up commits.
Review
Tensor.cppandComputeGraph.cppfirst, staging and layout-conversionshaders second, operator kernels third, then GEMM, the native backend and tests.
Authored with Codex and Claude Code.
Differential Revision: D124585167