Xenova HF Staff commited on
Commit
2c6000e
·
verified ·
1 Parent(s): 641e8a1

sync 4385228f788d

Browse files
README.md CHANGED
@@ -12,10 +12,14 @@ tags:
12
 
13
  ## Description
14
 
15
- Multi-head self-attention over a padding-removed token stream. The `token_offset` and `cumulative_sequence_length` schedule maps every packed token to its sequence, and a token attends only the keys of that sequence. Query is either packed `[T, N, 3, H]` with key and value absent, or a separate `[T, hidden]` triple. The optional attention bias is indexed in PADDED coordinates. Float32 and float16 only; bfloat16 is not implemented.
16
 
17
  See the [ONNX Runtime `PackedMultiHeadAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.PackedMultiHeadAttention) for the reference semantics.
18
 
 
 
 
 
19
  ## Inputs
20
 
21
  | Name | Upstream name | Logical dtype | WebGPU storage | Rank | Shape | Description | Presence |
@@ -25,7 +29,7 @@ See the [ONNX Runtime `PackedMultiHeadAttention` contrib-operator spec](https://
25
  | `valueT` | `value` | `T` | same as logical dtype | `2` | — | Values with shape `[token_count, v_hidden_size]`. Present only in the separate form. | optional |
26
  | `biasT` | `bias` | `T` | same as logical dtype | `1` | — | Optional packed input-projection bias with shape `[hidden_size + hidden_size + v_hidden_size]`, added to Q, K and V. | optional |
27
  | `tokenOffsetT` | `token_offset` | `M` | `int32` | `2` | — | Shape `[batch_size, sequence_length]`. The first `token_count` entries hold each packed token's flat index in the padded grid; the rest hold the padding positions. This tensor carries the padded `sequence_length`. | required |
28
- | `cumulativeSequenceLengthT` | `cumulative_sequence_length` | `M` | `int32` | `1` | — | Exclusive prefix sums with shape `[batch_size + 1]`, starting at 0 and ending at `token_count`. Sequence `i` owns packed tokens `[cum[i], cum[i + 1])`. Outputs are unspecified for a malformed schedule. | required |
29
  | `attentionBiasT` | `attention_bias` | `T` | same as logical dtype | `4` | — | Optional additive score bias with shape `[batch_size or 1, num_heads or 1, sequence_length, sequence_length]`. Its trailing axes are PADDED positions inside a sequence, not packed indices. | optional |
30
 
31
  ## Outputs
@@ -54,68 +58,55 @@ Attributes and default values (overridable per request):
54
 
55
  One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
56
 
57
- - `packed_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.
58
- - `packed_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.
59
- - `packed_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.
60
- - `packed_attn_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.
61
- - `packed_attn_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.
62
- - `packed_attn_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.
63
- - `packed_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.
64
- - `packed_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.
65
- - `packed_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.
66
- - `packed_bias_attn_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.
67
- - `packed_bias_attn_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.
68
- - `packed_bias_attn_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.
69
- - `separate_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.
70
- - `separate_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.
71
- - `separate_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.
72
- - `separate_attn_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.
73
- - `separate_attn_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.
74
- - `separate_attn_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.
75
- - `separate_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.
76
- - `separate_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.
77
- - `separate_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.
78
- - `separate_bias_attn_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.
79
- - `separate_bias_attn_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.
80
- - `separate_bias_attn_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.
81
 
82
  ## Device requirements
83
 
84
- Some implementation variants require `subgroups`. These are route-specific capabilities, not package-wide requirements; availability also depends on the request shape and dtype.
85
 
86
  ## Files
87
 
88
- - [`metadata.json`](build/webgpu/metadata.json) — kernel metadata (id, digests, per-variant templates, provenance)
89
- - [`manifest.json`](build/webgpu/manifest.json) — the op contract (source of truth)
90
- - [`test.json`](build/webgpu/test.json) — correctness cases
91
- - [`bench.json`](build/webgpu/bench.json) — benchmark cases
92
- - [`attn-packed-varlen-cluster.wgsl.jinja`](build/webgpu/attn-packed-varlen-cluster.wgsl.jinja)
93
- - [`attn-packed-varlen-scalar.wgsl.jinja`](build/webgpu/attn-packed-varlen-scalar.wgsl.jinja)
94
 
95
  ## Use with `@huggingface/kernels`
96
 
97
  ```sh
98
- npm install --save-exact @huggingface/kernels@0.0.1-preview.3
99
  ```
100
 
 
 
101
  Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
102
 
103
  The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
104
  It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
105
 
106
- Replace each `*Data` placeholder with a typed array containing the corresponding input data.
107
-
108
  ```js
109
  import { getKernel } from "@huggingface/kernels";
110
 
111
  const kernel = await getKernel("webgpu-kernels/com.microsoft.PackedMultiHeadAttention", { version: 1 });
 
 
 
 
 
 
 
112
  const { outputT } = await kernel({
113
- queryT: { data: queryTData, shape: [1, 16] },
114
- keyT: { data: keyTData, shape: [1, 16] },
115
- valueT: { data: valueTData, shape: [1, 20] },
116
- tokenOffsetT: { data: tokenOffsetTData, shape: [1, 1] },
117
- cumulativeSequenceLengthT: { data: cumulativeSequenceLengthTData, shape: [2] },
118
  }, {
119
  attrs: { num_heads: 1 },
120
  });
 
121
  ```
 
12
 
13
  ## Description
14
 
15
+ Self-attention over a padding-removed token stream. `token_offset` and `cumulative_sequence_length` map tokens to sequences; each token attends only its sequence. Query is packed `[T, N, 3, H]` or a separate `[T, hidden]` Q/K/V triple. Attention bias uses padded coordinates. Supports float32/float16. Malformed cumulative prefixes yield zero output; offsets inconsistent with a valid prefix yield zero rows. These inputs are validated on the GPU before use as unsigned indices, with nothing read back to the CPU. Bfloat16 is unsupported.
16
 
17
  See the [ONNX Runtime `PackedMultiHeadAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.PackedMultiHeadAttention) for the reference semantics.
18
 
19
+ ## Differences from the ONNX Runtime spec
20
+
21
+ - Attribute `mask_filter_value`: Has no effect, because this operator has no mask input.
22
+
23
  ## Inputs
24
 
25
  | Name | Upstream name | Logical dtype | WebGPU storage | Rank | Shape | Description | Presence |
 
29
  | `valueT` | `value` | `T` | same as logical dtype | `2` | — | Values with shape `[token_count, v_hidden_size]`. Present only in the separate form. | optional |
30
  | `biasT` | `bias` | `T` | same as logical dtype | `1` | — | Optional packed input-projection bias with shape `[hidden_size + hidden_size + v_hidden_size]`, added to Q, K and V. | optional |
31
  | `tokenOffsetT` | `token_offset` | `M` | `int32` | `2` | — | Shape `[batch_size, sequence_length]`. The first `token_count` entries hold each packed token's flat index in the padded grid; the rest hold the padding positions. This tensor carries the padded `sequence_length`. | required |
32
+ | `cumulativeSequenceLengthT` | `cumulative_sequence_length` | `M` | `int32` | `1` | — | Exclusive prefix sums with shape `[batch_size + 1]`, starting at 0 and ending at `token_count`. Sequence `i` owns packed tokens `[cum[i], cum[i + 1])`. Outputs are unspecified for malformed prefix sums. | required |
33
  | `attentionBiasT` | `attention_bias` | `T` | same as logical dtype | `4` | — | Optional additive score bias with shape `[batch_size or 1, num_heads or 1, sequence_length, sequence_length]`. Its trailing axes are PADDED positions inside a sequence, not packed indices. | optional |
34
 
35
  ## Outputs
 
58
 
59
  One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
60
 
61
+ - `flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count.
62
+ - `flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.
63
+ - `serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
  ## Device requirements
66
 
67
+ Some implementation variants require `subgroups`. Other variants run without it; which variant runs also depends on the request's shapes and dtypes.
68
 
69
  ## Files
70
 
71
+ - [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)
72
+ - [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)
73
+ - [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/test.json) — correctness cases
74
+ - [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/bench.json) — benchmark cases
75
+ - [`attn-packed-varlen-cluster.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/attn-packed-varlen-cluster.wgsl.jinja)
76
+ - [`attn-packed-varlen-scalar.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/attn-packed-varlen-scalar.wgsl.jinja)
77
 
78
  ## Use with `@huggingface/kernels`
79
 
80
  ```sh
81
+ npm install --save-exact @huggingface/kernels@0.0.1-preview.4
82
  ```
83
 
84
+ Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.
85
+
86
  Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
87
 
88
  The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
89
  It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
90
 
 
 
91
  ```js
92
  import { getKernel } from "@huggingface/kernels";
93
 
94
  const kernel = await getKernel("webgpu-kernels/com.microsoft.PackedMultiHeadAttention", { version: 1 });
95
+
96
+ const queryTData = new Float32Array(16);
97
+ const keyTData = new Float32Array(16);
98
+ const valueTData = new Float32Array(16).fill(4);
99
+ const tokenOffsetTData = Int32Array.of(0, 2, 1, 3);
100
+ const cumulativeSequenceLengthTData = Int32Array.of(0, 3, 2);
101
+
102
  const { outputT } = await kernel({
103
+ queryT: { data: queryTData, shape: [2, 8] },
104
+ keyT: { data: keyTData, shape: [2, 8] },
105
+ valueT: { data: valueTData, shape: [2, 8] },
106
+ tokenOffsetT: { data: tokenOffsetTData, shape: [2, 2] },
107
+ cumulativeSequenceLengthT: { data: cumulativeSequenceLengthTData, shape: [3] },
108
  }, {
109
  attrs: { num_heads: 1 },
110
  });
111
+ console.log({ outputT });
112
  ```
build/webgpu/attn-packed-varlen-cluster.wgsl.jinja CHANGED
@@ -1,8 +1,401 @@
1
  {% set parallelSoftmax = distributedSoftmax is defined and distributedSoftmax and not useSubgroups %}
 
2
  {% if useSubgroups %}
3
  enable subgroups;
4
  {% endif %}
5
  {{ env.wgsl.resourceDeclarations }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  {% set QBUF = "query" %}
7
  {% set KBUF = "query" if packedQkv else "key" %}
8
  {% set VBUF = "query" if packedQkv else "value" %}
@@ -13,10 +406,21 @@ enable subgroups;
13
  {% set queryTail = headDimV4 % LPQ != 0 %}
14
  {% set VALUE_DIM_V4 = ((vHeadDim / 4) | int) %}
15
  {% set VALUE_SLICES = (((VALUE_DIM_V4 + LPQ - 1) / LPQ) | int) %}
 
16
  {% set unequalValue = vHeadDim != headDim %}
17
  {% set valueTail = VALUE_DIM_V4 % LPQ != 0 %}
18
  {% set valueWidth = "VALUE_HEAD_DIM_V4" if unequalValue else "HEAD_DIM_V4" %}
19
  {% set valueLane = "valueLaneSlice" if unequalValue else "laneSlice" %}
 
 
 
 
 
 
 
 
 
 
20
 
21
  // Tiled flash attention over a padding-removed packed token stream. One
22
  // workgroup covers TILE_Q consecutive packed tokens for one head, with an
@@ -82,7 +486,7 @@ const BIAS_V: u32 = {{ BIAS_V_ROW }}u;
82
  {% endif %}
83
  const TILE_Q: u32 = {{ TILE_Q }}u;
84
  const TILE_K: u32 = {{ TILE_K }}u;
85
- // Lanes per token cluster, sized by the manifest for query and value ownership.
86
  const LPQ: u32 = {{ LPQ }}u;
87
  const SLICE: u32 = {% if queryTail %}{{ SLICE_COUNT }}u{% else %}HEAD_DIM_V4 / LPQ{% endif %}; // query vec4s per lane slice
88
  const WG: u32 = TILE_Q * LPQ;
@@ -91,11 +495,50 @@ const NEG_INF: f32 = -3.4028234663852886e38;
91
  var<workgroup> k_tile: array<vec4<{{ ST }}>, TILE_K * HEAD_DIM_V4>;
92
  var<workgroup> v_tile: array<vec4<{{ ST }}>, TILE_K * {{ valueWidth }}>;
93
  {% if not useSubgroups %}
94
- // Reuse scratch for dot fragments, maxima, sums and probabilities when the
95
- // manifest admits the full tile; otherwise retain one key's reduction slots.
96
  var<workgroup> red: array<f32, {% if parallelSoftmax %}{{ TILE_Q * (LPQ * TILE_K if LPQ * TILE_K > 2 * LPQ + TILE_K else 2 * LPQ + TILE_K) }}{% else %}WG{% endif %}>;
97
  {% endif %}
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  {% set ATTN_SCALE_DIM = "HEAD_DIM" %}fn scale_value() -> f32 {
100
  if (params.scale != 0.0) { return params.scale; }
101
  return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));
@@ -114,19 +557,39 @@ struct PackedToken {
114
  }
115
 
116
  fn packed_token_of(token: u32, seqPad: u32) -> PackedToken {
117
- let flat = u32(token_offset[token]);
118
  var info: PackedToken;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  info.sequence = flat / seqPad;
120
  info.position = flat - info.sequence * seqPad;
121
- info.keyStart = token - info.position;
122
- info.keyEnd = u32(cumulative_sequence_length[info.sequence + 1u]);
 
 
 
 
 
123
  return info;
124
  }
125
  {% if hasBias %}
126
 
127
  {% set biasScalarWiden = usesF16 %}
128
- {% set BW = "f32(" if biasScalarWiden is defined and biasScalarWiden else "" %}
129
- {% set BC = ")" if biasScalarWiden is defined and biasScalarWiden else "" %}
 
130
  fn load_bias4(base: u32, d4: u32) -> vec4<f32> {
131
  let offset = base + d4 * 4u;
132
  return vec4<f32>({{ BW }}bias[offset]{{ BC }}, {{ BW }}bias[offset + 1u]{{ BC }}, {{ BW }}bias[offset + 2u]{{ BC }}, {{ BW }}bias[offset + 3u]{{ BC }});
@@ -135,12 +598,16 @@ fn load_bias4(base: u32, d4: u32) -> vec4<f32> {
135
 
136
  {% macro packed_dot_fragment() %}
137
  var part: f32 = 0.0;
 
 
 
138
  let kb = kk * HEAD_DIM_V4 + laneSlice;
 
139
  {% for c in range(SLICE_COUNT) %}
140
  {% if queryTail %}
141
  if (laneSlice + {{ c }}u < HEAD_DIM_V4) {
142
  {% endif %}
143
- part = part + dot(qr{{ c }}, vec4<f32>(k_tile[kb + {{ c }}u]));
144
  {% if queryTail %}
145
  }
146
  {% endif %}
@@ -152,7 +619,7 @@ fn load_bias4(base: u32, d4: u32) -> vec4<f32> {
152
  {% if valueTail %}
153
  if ({{ valueLane }} + {{ c }}u < {{ valueWidth }}) {
154
  {% endif %}
155
- o{{ c }} = o{{ c }} + p * vec4<f32>(v_tile[vRow + {{ c }}u]);
156
  {% if valueTail %}
157
  }
158
  {% endif %}
@@ -174,7 +641,8 @@ fn load_bias4(base: u32, d4: u32) -> vec4<f32> {
174
  fn main(
175
  @builtin(workgroup_id) wg: vec3<u32>,
176
  @builtin(local_invocation_id) lid: vec3<u32>{% if useSubgroups %},
177
- @builtin(subgroup_size) sgSize: u32{% endif %}
 
178
  ) {
179
  let h = wg.y;
180
  // The query-tile axis is folded over x and z with a baked stride; z is 1
@@ -185,9 +653,13 @@ fn main(
185
  return;
186
  }
187
  {% if useSubgroups %}
188
- // The subgroupShuffleXor butterfly requires every LPQ-lane cluster to fit in,
189
- // and align with, one subgroup. Keep a uniform guard for defensive portability.
190
- if (sgSize < LPQ || sgSize % LPQ != 0u) { return; }
 
 
 
 
191
  {% endif %}
192
 
193
  let tid = lid.x;
@@ -204,11 +676,21 @@ fn main(
204
  // token's sequence start and the last token's sequence end bound every token
205
  // in the tile.
206
  let lastToken = min(firstToken + TILE_Q - 1u, params.tokenCount - 1u);
207
- let wgStart = packed_token_of(firstToken, params.seqPad).keyStart;
208
- let wgEnd = packed_token_of(lastToken, params.seqPad).keyEnd;
 
 
 
 
 
 
209
 
210
  let SCALE = scale_value();
211
  let laneSlice = lane * SLICE;
 
 
 
 
212
  {% if unequalValue %}
213
  let valueLaneSlice = lane * {{ VALUE_SLICES }}u;
214
  {% endif %}
@@ -228,16 +710,20 @@ fn main(
228
  qr{{ c }} = qr{{ c }} + load_bias4(h * HEAD_DIM, laneSlice + {{ c }}u);
229
  {% endif %}
230
  {% endif %}
231
- {% if not unequalValue %}
232
- var o{{ c }} = vec4<f32>(0.0);
233
  {% endif %}
234
  {% endfor %}
235
  {% if unequalValue %}
236
  {% for c in range(VALUE_SLICES) %}
237
- var o{{ c }} = vec4<f32>(0.0);
238
  {% endfor %}
239
  {% endif %}
240
 
 
 
 
 
241
  var m: f32 = NEG_INF;
242
  var l: f32 = 0.0;
243
 
@@ -262,9 +748,9 @@ fn main(
262
  {% if hasBias %}
263
  word = word + load_bias4({{ biasRow }} + h * {{ biasWidth }}, d4);
264
  {% endif %}
265
- {{ tile }}[i] = vec4<{{ ST }}>(word);
266
  } else {
267
- {{ tile }}[i] = vec4<{{ ST }}>(0.0);
268
  }
269
  }
270
  {% endfor %}
@@ -280,11 +766,11 @@ fn main(
280
  kWord = kWord + load_bias4(BIAS_K + h * HEAD_DIM, d4);
281
  vWord = vWord + load_bias4(BIAS_V + h * HEAD_DIM, d4);
282
  {% endif %}
283
- k_tile[i] = vec4<{{ ST }}>(kWord);
284
- v_tile[i] = vec4<{{ ST }}>(vWord);
285
  } else {
286
- k_tile[i] = vec4<{{ ST }}>(0.0);
287
- v_tile[i] = vec4<{{ ST }}>(0.0);
288
  }
289
  }
290
  {% endif %}
@@ -348,14 +834,24 @@ fn main(
348
  s[kk] = NEG_INF;
349
  {{ packed_dot_fragment() }}
350
  {% if useSubgroups %}
351
- // log2(LPQ) butterfly all-reduce inside the cluster: every lane ends with
352
- // the full dot.
 
353
  part = part + subgroupShuffleXor(part, 1u);
354
  {% for shift in [2, 4, 8, 16, 32] %}
355
- {% if LPQ > shift %}
356
  part = part + subgroupShuffleXor(part, {{ shift }}u);
357
  {% endif %}
358
  {% endfor %}
 
 
 
 
 
 
 
 
 
359
  {% else %}
360
  red[tid] = part;
361
  workgroupBarrier();
@@ -388,14 +884,27 @@ fn main(
388
 
389
  {% endif %}
390
 
391
- // A boundary tile addresses V rows outside this token's sequence. Because
392
- // 0 * NaN is NaN, the guarded loop skips the V read entirely for a key with
393
- // no probability mass; an interior tile runs the unguarded FMA chain. One
394
- // range test covers the whole lane slice, and one probability load feeds
395
- // every vec4 of it.
396
  let tileInterior = kStart >= minKj && kStart + TILE_K <= maxKj;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
397
  {% for c in range(VALUE_SLICES) %}
398
- o{{ c }} = o{{ c }} * corr;
399
  {% endfor %}
400
  if (tileInterior) {
401
  for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {
@@ -405,11 +914,13 @@ fn main(
405
  } else {
406
  for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {
407
  let p = {% if parallelSoftmax %}red[2u * WG + qSub * TILE_K + kk]{% else %}s[kk]{% endif %};
408
- if (p != 0.0) {
 
409
  {{ packed_value_accumulate() }}
410
  }
411
  }
412
  }
 
413
 
414
  kStart = kStart + TILE_K;
415
  }
@@ -417,16 +928,25 @@ fn main(
417
  if (qValid) {
418
  // l == 0 means this token had no probability-bearing key. Emit 0 rather
419
  // than 0/0.
 
420
  let inv = select(0.0, 1.0 / l, l > 0.0);
 
421
  let outBase4 = qIdx * O_ROW_V4 + h * O_HEAD_V4 + {{ valueLane }};
 
 
 
 
 
 
422
  {% for c in range(VALUE_SLICES) %}
423
  {% if valueTail %}
424
  if ({{ valueLane }} + {{ c }}u < {{ valueWidth }}) {
425
  {% endif %}
426
- output[outBase4 + {{ c }}u] = vec4<{{ scalar }}>(o{{ c }} * inv);
427
  {% if valueTail %}
428
  }
429
  {% endif %}
430
  {% endfor %}
 
431
  }
432
  }
 
1
  {% set parallelSoftmax = distributedSoftmax is defined and distributedSoftmax and not useSubgroups %}
2
+ {% set normalizedValues = scalar == "f32" %}
3
  {% if useSubgroups %}
4
  enable subgroups;
5
  {% endif %}
6
  {{ env.wgsl.resourceDeclarations }}
7
+ {% if normalizedValues %}
8
+ {% macro sum_error_function(name, type="f32", protectDifference=false) %}
9
+ {% set bitsType = type | replace("f32", "u32") %}
10
+ // Observing the rounded sum as bits preserves FastTwoSum on backends
11
+ // that otherwise reassociate its subtractions. Both signs of zero contribute zero.
12
+ fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {
13
+ let bits = bitcast<{{ bitsType }}>(x);
14
+ return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));
15
+ }
16
+ fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {
17
+ let swap = abs(a) < abs(b);
18
+ let larger = select(a, b, swap);
19
+ let smaller = select(b, a, swap);
20
+ // Keep the rounded high-part difference observable before subtracting it
21
+ // from the smaller addend. Reassociation here erases the residual.
22
+ return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);
23
+ }
24
+ {% endmacro %}
25
+ {% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}
26
+ {% set N = 1 if type == "f32" else (type[3] | int) %}
27
+ {% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}
28
+ {% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}
29
+ {% set exact = add or rescale or merge %}
30
+ struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }
31
+ struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }
32
+
33
+ {% if exact %}
34
+ fn scaled_value_scalar_zero() -> ScaledValueScalar {
35
+ return ScaledValueScalar(0.0, 0.0, 0);
36
+ }
37
+ {% endif %}
38
+ fn scaled_value_scalar_finite(x: f32) -> bool {
39
+ return abs(x) <= 3.4028234663852886e38;
40
+ }
41
+ {% if exact or align %}
42
+ fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {
43
+ if (a.hi == 0.0) {
44
+ if (a.lo == 0.0) { return -1024; }
45
+ return a.exponent + frexp(a.lo).exp;
46
+ }
47
+ if (!scaled_value_scalar_finite(a.hi)) { return 1024; }
48
+ return a.exponent + frexp(a.hi).exp;
49
+ }
50
+ {% endif %}
51
+ // Scale the significand bits directly. WGSL ldexp may return zero for a
52
+ // shift <= -127 even when its input makes the final result normal; shifts
53
+ // above 128 are indeterminate. Neither limit applies to this exponent sum.
54
+ fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {
55
+ let bits = bitcast<u32>(value);
56
+ let sign = bits & 0x80000000u;
57
+ let fraction = bits & 0x007fffffu;
58
+ let inputExponent = i32((bits >> 23u) & 0xffu);
59
+ if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }
60
+ var significand = fraction | 0x00800000u;
61
+ var exponent = inputExponent + shift;
62
+ if (inputExponent == 0) {
63
+ let normalize = countLeadingZeros(fraction) - 8u;
64
+ significand = fraction << normalize;
65
+ exponent = 1 + shift - i32(normalize);
66
+ }
67
+ if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }
68
+ if (exponent > 0) {
69
+ return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));
70
+ }
71
+ let distance = u32(1 - exponent);
72
+ if (distance > 24u) { return bitcast<f32>(sign); }
73
+ let high = significand >> distance;
74
+ let remainder = significand & ((1u << distance) - 1u);
75
+ let halfway = 1u << (distance - 1u);
76
+ let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);
77
+ return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));
78
+ }
79
+ {% if exact or align %}
80
+ fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {
81
+ if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }
82
+ if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }
83
+ return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);
84
+ }
85
+ {% endif %}
86
+ {% if exact %}
87
+ {% if recoverSum %}
88
+ {{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}
89
+ {% endif %}
90
+ fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {
91
+ let nextHi = fma(hi, 1.0, lo);
92
+ let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};
93
+ if (nextHi == 0.0) { return scaled_value_scalar_zero(); }
94
+ if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }
95
+ let parts = frexp(nextHi);
96
+ let rawExponent = exponent + parts.exp;
97
+ // Ordinary magnitudes return to the unscaled fast path. The margin keeps
98
+ // boundary values away from overflow/underflow while scaling the low word.
99
+ if (rawExponent >= -120 && rawExponent <= 120) {
100
+ return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);
101
+ }
102
+ return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);
103
+ }
104
+ fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {
105
+ let sum = fma(a.hi, 1.0, product);
106
+ let bv = fma(-1.0, a.hi, sum);
107
+ let av = fma(-1.0, bv, sum);
108
+ let ae = fma(-1.0, av, a.hi);
109
+ let be = fma(-1.0, bv, product);
110
+ let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);
111
+ let hi = fma(sum, 1.0, residual);
112
+ return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);
113
+ }
114
+ fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {
115
+ if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||
116
+ !scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||
117
+ !scaled_value_scalar_finite(weight)) {
118
+ return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);
119
+ }
120
+ if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }
121
+ if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }
122
+ if (a.exponent == 0 && b.exponent == 0) {
123
+ let product = fma(weight, b.hi, 0.0);
124
+ let lowProduct = fma(weight, b.lo, 0.0);
125
+ let rawSum = fma(a.hi, 1.0, product);
126
+ let productNormal = abs(product) >= 1.1754943508222875e-38;
127
+ if (productNormal && scaled_value_scalar_finite(product) &&
128
+ scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {
129
+ let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);
130
+ let result = scaled_value_scalar_add_words(a, product, error);
131
+ if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }
132
+ }
133
+ }
134
+ // Decompose BEFORE multiplying: a merge coefficient may exceed one, so
135
+ // its unscaled product with a finite partial mean need not fit in f32.
136
+ var other = b;
137
+ if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }
138
+ let wp = frexp(weight);
139
+ let vp = frexp(other.hi);
140
+ let productExponent = other.exponent + wp.exp + vp.exp;
141
+ let commonExponent = max(scaled_value_scalar_leading(a), productExponent);
142
+ let aligned = scaled_value_scalar_align(a, commonExponent);
143
+ let product = fma(wp.fract, vp.fract, 0.0);
144
+ let productError = fma(wp.fract, vp.fract, -product);
145
+ let shift = productExponent - commonExponent;
146
+ let highWord = scaled_value_scalar_shift(product, shift);
147
+ let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,
148
+ fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));
149
+ {% if recoverSum %}
150
+ let sum = aligned.hi + highWord;
151
+ let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;
152
+ return scaled_value_scalar_finish(sum, low, commonExponent);
153
+ {% else %}
154
+ let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);
155
+ return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);
156
+ {% endif %}
157
+ }
158
+ {% endif %}
159
+ fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {
160
+ if (denominator == 0.0) { return 0.0; }
161
+ if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }
162
+ if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {
163
+ return fma(a.hi, 1.0, a.lo) / denominator;
164
+ }
165
+ let valueParts = frexp(a.hi);
166
+ let denominatorParts = frexp(denominator);
167
+ let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));
168
+ let quotient = mantissa / denominatorParts.fract;
169
+ return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);
170
+ }
171
+ fn scaled_value_zero() -> ScaledValue {
172
+ return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));
173
+ }
174
+ {% if N > 1 or rescale or lean %}
175
+ // Vector form of scaled_value_scalar_add_words: applies it to every component at once.
176
+ fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {
177
+ let sum = fma(acc.hi, {{ type }}(1.0), product);
178
+ {% if magnitudeOrdered %}
179
+ // FastTwoSum recovers the rounding error with the larger magnitude first.
180
+ let takeProduct = abs(acc.hi) < abs(product);
181
+ let larger = select(acc.hi, product, takeProduct);
182
+ let smaller = select(product, acc.hi, takeProduct);
183
+ let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);
184
+ let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);
185
+ {% else %}
186
+ let bv = fma({{ type }}(-1.0), acc.hi, sum);
187
+ let av = fma({{ type }}(-1.0), bv, sum);
188
+ let ae = fma({{ type }}(-1.0), av, acc.hi);
189
+ let be = fma({{ type }}(-1.0), bv, product);
190
+ let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);
191
+ {% endif %}
192
+ let hi = fma(sum, {{ type }}(1.0), residual);
193
+ return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);
194
+ }
195
+ {% endif %}
196
+ {% if lean %}
197
+ // Lean folds: the compensated arithmetic of scaled_value_add_step with every
198
+ // check deferred to the fold's end. A fold that starts from a normalized pair at
199
+ // exponent zero (the high word is the words' rounded sum), ends with finite words
200
+ // (a non-finite word stays non-finite through the sum, so this covers the start
201
+ // too), and whose smallest nonzero weight times smallest nonzero value is normal
202
+ // took only steps whose result is scaled_value_add's, up to the sign of a zero
203
+ // word: each nonzero product was normal, every step leaves the pair normalized,
204
+ // and a zero product leaves a normalized pair unchanged.
205
+ fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {
206
+ let w = {{ type }}(weight);
207
+ let product = fma(w, value, {{ type }}(0.0));
208
+ return scaled_value_add_words(acc, product, fma(w, value, -product));
209
+ }
210
+ // The smallest nonzero magnitude among `low` and `value`, per component.
211
+ fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {
212
+ return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));
213
+ }
214
+ fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {
215
+ return all(start.exponent == {{ exponentType }}(0)) &&
216
+ all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &
217
+ (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &
218
+ ({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));
219
+ }
220
+ {% endif %}
221
+ {% if N > 1 and tile %}
222
+ {% set uType = "vec" ~ N ~ "<u32>" %}
223
+ // Offset tile folds. A tile's products, at most `bound` in total magnitude per
224
+ // component, add onto `offset`, the power of two above 2.25 * bound, so every
225
+ // partial sum stays within [offset / 2, 2 * offset): each step's change to it is
226
+ // exact, and the low word gathers each step's remainder, at most half an ulp of
227
+ // the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the
228
+ // offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A
229
+ // non-finite weight, value or bound leaves a non-finite word, and a bound past
230
+ // 2^126 an infinite offset, so a caller checks finiteness once, after its fold;
231
+ // scaled_value_tile_in_range checks what that cannot see.
232
+ struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }
233
+ fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {
234
+ let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));
235
+ let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));
236
+ return ScaledValueTile(offset, offset, {{ type }}(0.0));
237
+ }
238
+ fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {
239
+ let w = {{ type }}(weight);
240
+ let sum = fma(w, value, tile.sum);
241
+ let change = fma({{ type }}(-1.0), tile.sum, sum);
242
+ return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));
243
+ }
244
+ // The tile's words, normalized, added as scaled_value_add adds a product.
245
+ fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {
246
+ let high = fma({{ type }}(-1.0), tile.offset, tile.sum);
247
+ let sum = fma(high, {{ type }}(1.0), tile.low);
248
+ let bv = fma({{ type }}(-1.0), high, sum);
249
+ let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));
250
+ return scaled_value_add_words(acc, sum, error);
251
+ }
252
+ // An offset or start of at least 2^-76, or a zero bound, keeps every word a
253
+ // flush-to-zero device could drop below 2^-48 of the result.
254
+ fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}) -> bool {
255
+ return all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |
256
+ (bound == {{ type }}(0.0)));
257
+ }
258
+ {% endif %}
259
+ {% if N > 1 and add %}
260
+ // One compensated fold step without branches, for a caller that folds many
261
+ // steps before it can afford a branch. From finite words at exponent zero, a
262
+ // normal product and a finite low word imply every other condition of this
263
+ // arithmetic in scaled_value_add: the low word is finite only if the high word
264
+ // is, then the sum is, then the product, the weight and the value. A zero
265
+ // weight with a finite value is the step whose exact result is the accumulator
266
+ // itself. `exact` is false in any component whose step only scaled_value_add
267
+ // computes.
268
+ struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }
269
+ fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {
270
+ let w = {{ type }}(weight);
271
+ let product = fma(w, value, {{ type }}(0.0));
272
+ let sum = scaled_value_add_words(acc, product, fma(w, value, -product));
273
+ let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));
274
+ let fast = (abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));
275
+ return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),
276
+ fast | vec{{ N }}<bool>(keep));
277
+ }
278
+ {% endif %}
279
+ {% if add %}
280
+ fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {
281
+ {% if N > 1 %}
282
+ // Ordinary raw products use one vector compensated sum. Every exceptional
283
+ // component falls back to the same scalar exponent-aware implementation.
284
+ if (all(acc.exponent == {{ exponentType }}(0)) &&
285
+ all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&
286
+ all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {
287
+ let step = scaled_value_add_step(acc, weight, value);
288
+ if (all(step.exact)) { return step.value; }
289
+ }
290
+ {% endif %}
291
+ var result = scaled_value_zero();
292
+ {% for i in range(N) %}
293
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
294
+ let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), weight{% if coefficientType != "f32" %}[{{ i }}]{% endif %}, ScaledValueScalar(value{{ c }}, 0.0, 0));
295
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
296
+ {% endfor %}
297
+ return result;
298
+ }
299
+ {% endif %}
300
+ {% if rescale or tile %}
301
+ {% macro rescale_words() %}
302
+ let w = {{ type }}(correction);
303
+ let product = fma(w, acc.hi, {{ type }}(0.0));
304
+ let scaled = scaled_value_add_words(scaled_value_zero(), product,
305
+ fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));
306
+ let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);
307
+ let unit = correction == 1.0;
308
+ {% endmacro %}
309
+ {% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &
310
+ (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &
311
+ (zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &
312
+ (abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}
313
+ {% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),
314
+ select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}
315
+ {% endif %}
316
+ {% if tile %}
317
+ // scaled_value_rescale's vector path alone; `exact` is false where only its
318
+ // scalar path applies.
319
+ struct ScaledValueRescaled { value: ScaledValue, exact: bool }
320
+ fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {
321
+ {{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});
322
+ }
323
+ {% endif %}
324
+ {% if rescale %}
325
+ fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {
326
+ // From finite words at exponent zero, the scalar path below leaves zero
327
+ // words for a zero value or correction, the value itself for a unit
328
+ // correction, and otherwise this compensated product onto zero words when
329
+ // the product is normal and the low word finite (which bounds the rest, as
330
+ // in scaled_value_add_step).
331
+ {{ rescale_words() }} if ({{ rescale_vector_exact() }}) {
332
+ return {{ rescale_vector_value() }};
333
+ }
334
+ var result = scaled_value_zero();
335
+ {% for i in range(N) %}
336
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
337
+ let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));
338
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
339
+ {% endfor %}
340
+ return result;
341
+ }
342
+ {% endif %}
343
+ {% if merge %}
344
+ fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {
345
+ var result = scaled_value_zero();
346
+ {% for i in range(N) %}
347
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
348
+ let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), 1.0, ScaledValueScalar(other.hi{{ c }}, other.lo{{ c }}, other.exponent{{ c }}));
349
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
350
+ {% endfor %}
351
+ return result;
352
+ }
353
+ {% endif %}
354
+ fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {
355
+ // Words at exponent zero well inside the normal range, with a normal
356
+ // quotient: the scalar path below divides this same sum by this same
357
+ // denominator, each scaled by a power of two, so it rounds to this quotient
358
+ // wherever division is scale-invariant. Bounding the denominator above also
359
+ // keeps a division through its reciprocal clear of a subnormal reciprocal.
360
+ let d = {{ type }}(denominator);
361
+ let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);
362
+ let quotient = sum / d;
363
+ if (all((acc.exponent == {{ exponentType }}(0)) &
364
+ (abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &
365
+ (abs(acc.lo) <= abs(acc.hi)) &
366
+ (abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &
367
+ ((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {
368
+ return quotient;
369
+ }
370
+ var result = {{ type }}(0.0);
371
+ {% for i in range(N) %}
372
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
373
+ result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});
374
+ {% endfor %}
375
+ return result;
376
+ }
377
+ {% if align %}
378
+ fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {
379
+ var result = {{ exponentType }}(0);
380
+ {% for i in range(N) %}
381
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
382
+ result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));
383
+ {% endfor %}
384
+ return result;
385
+ }
386
+ fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {
387
+ var result = scaled_value_zero();
388
+ {% for i in range(N) %}
389
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
390
+ let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});
391
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
392
+ {% endfor %}
393
+ return result;
394
+ }
395
+ {% endif %}
396
+ {% endmacro %}
397
+ {{ scaled_value_functions("vec4<f32>", "f32", true) }}
398
+ {% endif %}
399
  {% set QBUF = "query" %}
400
  {% set KBUF = "query" if packedQkv else "key" %}
401
  {% set VBUF = "query" if packedQkv else "value" %}
 
406
  {% set queryTail = headDimV4 % LPQ != 0 %}
407
  {% set VALUE_DIM_V4 = ((vHeadDim / 4) | int) %}
408
  {% set VALUE_SLICES = (((VALUE_DIM_V4 + LPQ - 1) / LPQ) | int) %}
409
+ {% set loopValues = resourceDistributed | default(false) %}
410
  {% set unequalValue = vHeadDim != headDim %}
411
  {% set valueTail = VALUE_DIM_V4 % LPQ != 0 %}
412
  {% set valueWidth = "VALUE_HEAD_DIM_V4" if unequalValue else "HEAD_DIM_V4" %}
413
  {% set valueLane = "valueLaneSlice" if unequalValue else "laneSlice" %}
414
+ {% set BANK_SWIZZLE = (device.adapterInfo.vendor | default("")) == "nvidia" and ST == "f32" %}
415
+ {% set K_SWZ = 8 if SLICE_COUNT % 8 == 0 else (4 if SLICE_COUNT % 4 == 0 else (2 if SLICE_COUNT % 2 == 0 else 1)) %}
416
+ {% set V_SWZ = 8 if VALUE_SLICES % 8 == 0 else (4 if VALUE_SLICES % 4 == 0 else (2 if VALUE_SLICES % 2 == 0 else 1)) %}
417
+ {% set K_SWIZZLE = BANK_SWIZZLE and K_SWZ > 1 and LPQ * K_SWZ > 8 and headDimV4 % K_SWZ == 0 %}
418
+ {% set V_SWIZZLE = BANK_SWIZZLE and V_SWZ > 1 and LPQ * V_SWZ > 8 and VALUE_DIM_V4 % V_SWZ == 0 %}
419
+ {% set HOIST_K_COLUMNS = useSubgroups and K_SWIZZLE and LPQ * K_SWZ == 16 and not V_SWIZZLE %}
420
+ {% macro kswz(d4) %}{% if K_SWIZZLE %} ^ (((({{ d4 }}) / SLICE) % 8u) * {{ K_SWZ }}u / 8u){% endif %}{% endmacro %}
421
+ {% macro vswz(d4) %}{% if V_SWIZZLE %} ^ (((({{ d4 }}) / {{ VALUE_SLICES }}u) % 8u) * {{ V_SWZ }}u / 8u){% endif %}{% endmacro %}
422
+ {% macro kc(c) %}{% if K_SWIZZLE %}({{ c }}u ^ kSwz){% else %}{{ c }}u{% endif %}{% endmacro %}
423
+ {% macro vc(c) %}{% if V_SWIZZLE %}({{ c }}u ^ vSwz){% else %}{{ c }}u{% endif %}{% endmacro %}
424
 
425
  // Tiled flash attention over a padding-removed packed token stream. One
426
  // workgroup covers TILE_Q consecutive packed tokens for one head, with an
 
486
  {% endif %}
487
  const TILE_Q: u32 = {{ TILE_Q }}u;
488
  const TILE_K: u32 = {{ TILE_K }}u;
489
+ // Lanes per token cluster partition the query and value vectors.
490
  const LPQ: u32 = {{ LPQ }}u;
491
  const SLICE: u32 = {% if queryTail %}{{ SLICE_COUNT }}u{% else %}HEAD_DIM_V4 / LPQ{% endif %}; // query vec4s per lane slice
492
  const WG: u32 = TILE_Q * LPQ;
 
495
  var<workgroup> k_tile: array<vec4<{{ ST }}>, TILE_K * HEAD_DIM_V4>;
496
  var<workgroup> v_tile: array<vec4<{{ ST }}>, TILE_K * {{ valueWidth }}>;
497
  {% if not useSubgroups %}
498
+ // Reuse scratch for dot fragments, maxima, sums and probabilities when the full
499
+ // tile fits in workgroup storage; otherwise retain one key's reduction slots.
500
  var<workgroup> red: array<f32, {% if parallelSoftmax %}{{ TILE_Q * (LPQ * TILE_K if LPQ * TILE_K > 2 * LPQ + TILE_K else 2 * LPQ + TILE_K) }}{% else %}WG{% endif %}>;
501
  {% endif %}
502
 
503
+ {% if useSubgroups %}
504
+ {% set localFoldWorkgroupSize = TILE_Q * LPQ %}
505
+ {% set localFoldWidth = LPQ %}
506
+ // One entry-point proof for algorithms that assign data using local-ID lane
507
+ // blocks. Every subgroup checks all active members; the workgroup accepts only
508
+ // when every subgroup has a valid complete layout. Call once in uniform flow.
509
+ // The rejection flag starts zero through WGSL workgroup initialization.
510
+ // Some Adreno 6xx drivers cannot create a pipeline that calls subgroupAll; a ballot builds wherever subgroups do.
511
+ // A subgroup is valid when no active member is invalid. That is subgroupAll, expressed as a ballot so the shader
512
+ // does not depend on subgroupAll.
513
+ var<workgroup> subgroupLocalLayoutRejected: atomic<u32>;
514
+ var<workgroup> subgroupLocalLayoutAcceptedState: u32;
515
+
516
+ fn subgroupLocalLayoutAccepted(localIndex: u32, memberValid: bool) -> bool {
517
+ let valid = all(subgroupBallot(!memberValid) == vec4<u32>(0u));
518
+ if (subgroupElect() && !valid) {
519
+ atomicStore(&subgroupLocalLayoutRejected, 1u);
520
+ }
521
+ workgroupBarrier();
522
+ if (localIndex == 0u) {
523
+ subgroupLocalLayoutAcceptedState = select(0u, 1u, atomicLoad(&subgroupLocalLayoutRejected) == 0u);
524
+ }
525
+ return workgroupUniformLoad(&subgroupLocalLayoutAcceptedState) != 0u;
526
+ }
527
+ var<workgroup> localFoldValues: array<f32, {{ localFoldWorkgroupSize }}>;
528
+ fn sumLocalSubgroup(value: f32, tid: u32, nativeTopology: bool) -> f32 {
529
+ if (nativeTopology) { return subgroupAdd(value); }
530
+ localFoldValues[tid] = value;
531
+ workgroupBarrier();
532
+ let first = (tid / {{ localFoldWidth }}u) * {{ localFoldWidth }}u;
533
+ var total = 0.0;
534
+ for (var i = 0u; i < {{ localFoldWidth }}u; i += 1u) {
535
+ total += localFoldValues[first + i];
536
+ }
537
+ workgroupBarrier();
538
+ return total;
539
+ }
540
+ {% endif %}
541
+ {% set clusterShuffleLimit = 16 if (device.adapterInfo.subgroupMinSize | default(0)) > 32 else 64 %}
542
  {% set ATTN_SCALE_DIM = "HEAD_DIM" %}fn scale_value() -> f32 {
543
  if (params.scale != 0.0) { return params.scale; }
544
  return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));
 
557
  }
558
 
559
  fn packed_token_of(token: u32, seqPad: u32) -> PackedToken {
 
560
  var info: PackedToken;
561
+ // An invalid prefix or mapping denotes an empty key range, so every consumer
562
+ // writes a zero row. Check signed endpoints before unsigned subtraction and
563
+ // keep all ranges inside this packed stream and its padded bias grid.
564
+ if (cumulative_sequence_length[0] != 0
565
+ || cumulative_sequence_length[{{ batchSize }}u] != {{ tokenCount }}i) { return info; }
566
+ var previous = 0i;
567
+ for (var b = 1u; b <= {{ batchSize }}u; b++) {
568
+ let end = cumulative_sequence_length[b];
569
+ if (end < previous || end > {{ tokenCount }}i || u32(end - previous) > seqPad) { return info; }
570
+ previous = end;
571
+ }
572
+ let signedFlat = token_offset[token];
573
+ if (signedFlat < 0) { return info; }
574
+ let flat = u32(signedFlat);
575
+ if (flat / seqPad >= {{ batchSize }}u) { return info; }
576
  info.sequence = flat / seqPad;
577
  info.position = flat - info.sequence * seqPad;
578
+ let start = u32(cumulative_sequence_length[info.sequence]);
579
+ let end = u32(cumulative_sequence_length[info.sequence + 1u]);
580
+ if (info.position > token || token - info.position != start || token >= end) {
581
+ return PackedToken();
582
+ }
583
+ info.keyStart = start;
584
+ info.keyEnd = end;
585
  return info;
586
  }
587
  {% if hasBias %}
588
 
589
  {% set biasScalarWiden = usesF16 %}
590
+ {% set widenBias = biasScalarWiden if biasScalarWiden is defined else (inputScalar is defined and inputScalar == "f16") %}
591
+ {% set BW = "f32(" if widenBias else "" %}
592
+ {% set BC = ")" if widenBias else "" %}
593
  fn load_bias4(base: u32, d4: u32) -> vec4<f32> {
594
  let offset = base + d4 * 4u;
595
  return vec4<f32>({{ BW }}bias[offset]{{ BC }}, {{ BW }}bias[offset + 1u]{{ BC }}, {{ BW }}bias[offset + 2u]{{ BC }}, {{ BW }}bias[offset + 3u]{{ BC }});
 
598
 
599
  {% macro packed_dot_fragment() %}
600
  var part: f32 = 0.0;
601
+ {% if HOIST_K_COLUMNS %}
602
+ let kb = kk * HEAD_DIM_V4;
603
+ {% else %}
604
  let kb = kk * HEAD_DIM_V4 + laneSlice;
605
+ {% endif %}
606
  {% for c in range(SLICE_COUNT) %}
607
  {% if queryTail %}
608
  if (laneSlice + {{ c }}u < HEAD_DIM_V4) {
609
  {% endif %}
610
+ part = part + dot(qr{{ c }}, vec4<f32>(k_tile[kb + {{ "kCol" ~ c if HOIST_K_COLUMNS else kc(c) }}]));
611
  {% if queryTail %}
612
  }
613
  {% endif %}
 
619
  {% if valueTail %}
620
  if ({{ valueLane }} + {{ c }}u < {{ valueWidth }}) {
621
  {% endif %}
622
+ o{{ c }} = {% if normalizedValues %}scaled_value_add(o{{ c }}, p, {% else %}o{{ c }} + p * {% endif %}vec4<f32>(v_tile[vRow + {{ vc(c) }}]){% if normalizedValues %}){% endif %};
623
  {% if valueTail %}
624
  }
625
  {% endif %}
 
641
  fn main(
642
  @builtin(workgroup_id) wg: vec3<u32>,
643
  @builtin(local_invocation_id) lid: vec3<u32>{% if useSubgroups %},
644
+ @builtin(subgroup_size) sgSize: u32,
645
+ @builtin(subgroup_invocation_id) sgLane: u32{% endif %}
646
  ) {
647
  let h = wg.y;
648
  // The query-tile axis is folded over x and z with a baked stride; z is 1
 
653
  return;
654
  }
655
  {% if useSubgroups %}
656
+ let populationMask = subgroupBallot(true);
657
+ let population = countOneBits(populationMask.x) + countOneBits(populationMask.y)
658
+ + countOneBits(populationMask.z) + countOneBits(populationMask.w);
659
+ let firstLocal = subgroupBroadcastFirst(lid.x);
660
+ let nativeLayout = subgroupLocalLayoutAccepted(lid.x,
661
+ population == sgSize && sgSize % LPQ == 0u && sgLane == lid.x % sgSize
662
+ && firstLocal == lid.x - sgLane);
663
  {% endif %}
664
 
665
  let tid = lid.x;
 
676
  // token's sequence start and the last token's sequence end bound every token
677
  // in the tile.
678
  let lastToken = min(firstToken + TILE_Q - 1u, params.tokenCount - 1u);
679
+ let firstInfo = packed_token_of(firstToken, params.seqPad);
680
+ let lastInfo = packed_token_of(lastToken, params.seqPad);
681
+ // A bad endpoint token must not truncate valid queries inside the tile.
682
+ // The fallback union is bounded by the stream, while each query still masks
683
+ // to its own validated sequence. Valid schedules retain the narrow union.
684
+ let validEndpoints = firstInfo.keyEnd > firstInfo.keyStart && lastInfo.keyEnd > lastInfo.keyStart;
685
+ let wgStart = select(0u, firstInfo.keyStart, validEndpoints);
686
+ let wgEnd = select(params.tokenCount, lastInfo.keyEnd, validEndpoints);
687
 
688
  let SCALE = scale_value();
689
  let laneSlice = lane * SLICE;
690
+ {% if K_SWIZZLE %} let kSwz = ((lane % 8u) * {{ K_SWZ }}u) / 8u;
691
+ {% endif %}{% if HOIST_K_COLUMNS %}{% for c in range(SLICE_COUNT) %} let kCol{{ c }} = laneSlice + ({{ c }}u ^ kSwz);
692
+ {% endfor %}{% endif %}{% if V_SWIZZLE and not loopValues %} let vSwz = ((lane % 8u) * {{ V_SWZ }}u) / 8u;
693
+ {% endif %}
694
  {% if unequalValue %}
695
  let valueLaneSlice = lane * {{ VALUE_SLICES }}u;
696
  {% endif %}
 
710
  qr{{ c }} = qr{{ c }} + load_bias4(h * HEAD_DIM, laneSlice + {{ c }}u);
711
  {% endif %}
712
  {% endif %}
713
+ {% if not unequalValue and not loopValues %}
714
+ var o{{ c }} = {{ "scaled_value_zero()" if normalizedValues else "vec4<f32>(0.0)" }};
715
  {% endif %}
716
  {% endfor %}
717
  {% if unequalValue %}
718
  {% for c in range(VALUE_SLICES) %}
719
+ var o{{ c }} = {{ "scaled_value_zero()" if normalizedValues else "vec4<f32>(0.0)" }};
720
  {% endfor %}
721
  {% endif %}
722
 
723
+ {% if loopValues %}
724
+ var valueOut: array<ScaledValue, SLICE>;
725
+ let valueEnd = min(laneSlice + SLICE, HEAD_DIM_V4);
726
+ {% endif %}
727
  var m: f32 = NEG_INF;
728
  var l: f32 = 0.0;
729
 
 
748
  {% if hasBias %}
749
  word = word + load_bias4({{ biasRow }} + h * {{ biasWidth }}, d4);
750
  {% endif %}
751
+ {{ tile }}[i{{ vswz("d4") if tile == "v_tile" else kswz("d4") }}] = vec4<{{ ST }}>(word);
752
  } else {
753
+ {{ tile }}[i{{ vswz("d4") if tile == "v_tile" else kswz("d4") }}] = vec4<{{ ST }}>(0.0);
754
  }
755
  }
756
  {% endfor %}
 
766
  kWord = kWord + load_bias4(BIAS_K + h * HEAD_DIM, d4);
767
  vWord = vWord + load_bias4(BIAS_V + h * HEAD_DIM, d4);
768
  {% endif %}
769
+ k_tile[i{{ kswz("d4") }}] = vec4<{{ ST }}>(kWord);
770
+ v_tile[i{{ vswz("d4") }}] = vec4<{{ ST }}>(vWord);
771
  } else {
772
+ k_tile[i{{ kswz("d4") }}] = vec4<{{ ST }}>(0.0);
773
+ v_tile[i{{ vswz("d4") }}] = vec4<{{ ST }}>(0.0);
774
  }
775
  }
776
  {% endif %}
 
834
  s[kk] = NEG_INF;
835
  {{ packed_dot_fragment() }}
836
  {% if useSubgroups %}
837
+ // Reconverge query tails before the proved native or local-ID fold.
838
+ workgroupBarrier();
839
+ if (nativeLayout) {
840
  part = part + subgroupShuffleXor(part, 1u);
841
  {% for shift in [2, 4, 8, 16, 32] %}
842
+ {% if LPQ > shift and shift < clusterShuffleLimit %}
843
  part = part + subgroupShuffleXor(part, {{ shift }}u);
844
  {% endif %}
845
  {% endfor %}
846
+ {% if LPQ > clusterShuffleLimit %}
847
+ localFoldValues[tid] = part;
848
+ workgroupBarrier();
849
+ part = {% for i in range((LPQ / clusterShuffleLimit) | int) %}{{ " + " if not loop.first else "" }}localFoldValues[tid - lane + {{ i * clusterShuffleLimit }}u]{% endfor %};
850
+ workgroupBarrier();
851
+ {% endif %}
852
+ } else {
853
+ part = sumLocalSubgroup(part, tid, false);
854
+ }
855
  {% else %}
856
  red[tid] = part;
857
  workgroupBarrier();
 
884
 
885
  {% endif %}
886
 
887
+ // Exclude V rows outside the query's sequence. Include in-range rows even
888
+ // when their probability underflows so that NaN and infinity propagate.
 
 
 
889
  let tileInterior = kStart >= minKj && kStart + TILE_K <= maxKj;
890
+ {% if loopValues %}
891
+ {% set valueColumn = ("(d4" ~ vswz("d4") ~ ")") if V_SWIZZLE else "d4" %}
892
+ for (var d4 = laneSlice; d4 < valueEnd; d4++) {
893
+ let c = d4 - laneSlice;
894
+ var acc = scaled_value_rescale(valueOut[c], corr);
895
+ for (var kk = 0u; kk < TILE_K; kk++) {
896
+ let keyToken = kStart + kk;
897
+ if (tileInterior || (keyToken >= minKj && keyToken < maxKj)) {
898
+ let p = red[2u * WG + qSub * TILE_K + kk];
899
+ let v = v_tile[kk * HEAD_DIM_V4 + {{ valueColumn }}];
900
+ acc = scaled_value_add(acc, p, v);
901
+ }
902
+ }
903
+ valueOut[c] = acc;
904
+ }
905
+ {% else %}
906
  {% for c in range(VALUE_SLICES) %}
907
+ o{{ c }} = {% if normalizedValues %}scaled_value_rescale(o{{ c }}, corr){% else %}o{{ c }} * corr{% endif %};
908
  {% endfor %}
909
  if (tileInterior) {
910
  for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {
 
914
  } else {
915
  for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {
916
  let p = {% if parallelSoftmax %}red[2u * WG + qSub * TILE_K + kk]{% else %}s[kk]{% endif %};
917
+ let key_token = kStart + kk;
918
+ if (key_token >= minKj && key_token < maxKj) {
919
  {{ packed_value_accumulate() }}
920
  }
921
  }
922
  }
923
+ {% endif %}
924
 
925
  kStart = kStart + TILE_K;
926
  }
 
928
  if (qValid) {
929
  // l == 0 means this token had no probability-bearing key. Emit 0 rather
930
  // than 0/0.
931
+ {% if not normalizedValues %}
932
  let inv = select(0.0, 1.0 / l, l > 0.0);
933
+ {% endif %}
934
  let outBase4 = qIdx * O_ROW_V4 + h * O_HEAD_V4 + {{ valueLane }};
935
+ {% if loopValues %}
936
+ for (var d4 = laneSlice; d4 < valueEnd; d4++) {
937
+ let c = d4 - laneSlice;
938
+ output[outBase4 + c] = scaled_value_mean(valueOut[c], l);
939
+ }
940
+ {% else %}
941
  {% for c in range(VALUE_SLICES) %}
942
  {% if valueTail %}
943
  if ({{ valueLane }} + {{ c }}u < {{ valueWidth }}) {
944
  {% endif %}
945
+ output[outBase4 + {{ c }}u] = vec4<{{ scalar }}>({% if normalizedValues %}scaled_value_mean(o{{ c }}, l){% else %}o{{ c }} * inv{% endif %});
946
  {% if valueTail %}
947
  }
948
  {% endif %}
949
  {% endfor %}
950
+ {% endif %}
951
  }
952
  }
build/webgpu/attn-packed-varlen-scalar.wgsl.jinja CHANGED
@@ -1,4 +1,397 @@
1
  {{ env.wgsl.resourceDeclarations }}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  {% set QBUF = "query" %}
3
  {% set KBUF = "query" if packedQkv else "key" %}
4
  {% set VBUF = "query" if packedQkv else "value" %}
@@ -17,8 +410,8 @@
17
  // Source: separate token-major `[T, hidden]` query, key and value buffers.
18
  {% endif %}
19
  {% if hasBias %}
20
- // Packed `[Q; K; V]` bias rows are added to Q, K and V during the key walk,
21
- // which is where the reference adds them.
22
  {% endif %}
23
  {% if hasAttnBias %}
24
  // The additive attention bias lives in PADDED coordinates: its trailing two
@@ -48,7 +441,8 @@ const WG: u32 = {{ workgroupSize }}u;
48
  var<workgroup> partial: array<f32, WG>;
49
  var<workgroup> running_max: f32;
50
  var<workgroup> running_denom: f32;
51
- var<workgroup> running_out: array<f32, V_HEAD_DIM>;
 
52
  var<workgroup> previous_scale: f32;
53
  {% macro wgsl_tree_reduce_f32(name, mode, buffer="partial", wg="WG", trailingBarrier=true, valueType="f32") %}
54
  fn {{ name }}(value: {{ valueType }}, tid: u32) -> {{ valueType }} {
@@ -69,10 +463,9 @@ fn {{ name }}(value: {{ valueType }}, tid: u32) -> {{ valueType }} {
69
  break;
70
  }
71
  }
72
- // The default trailing barrier makes this helper safe for back-to-back calls: every lane reads
73
- // slot 0 here, so the next call's first store must not run until all lanes have read it.
74
- // `trailingBarrier=false` is safe only when the buffer is never written again before kernel exit.
75
  let reduced = {{ buffer }}[0];
 
 
76
  workgroupBarrier();
77
  return reduced;
78
  }
@@ -96,12 +489,31 @@ struct PackedToken {
96
  }
97
 
98
  fn packed_token_of(token: u32, seqPad: u32) -> PackedToken {
99
- let flat = u32(token_offset[token]);
100
  var info: PackedToken;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  info.sequence = flat / seqPad;
102
  info.position = flat - info.sequence * seqPad;
103
- info.keyStart = token - info.position;
104
- info.keyEnd = u32(cumulative_sequence_length[info.sequence + 1u]);
 
 
 
 
 
105
  return info;
106
  }
107
 
@@ -119,6 +531,10 @@ fn main(
119
  }
120
 
121
  let tid = lid.x;
 
 
 
 
122
  let info = packed_token_of(token, params.seqPad);
123
  let qBase = token * Q_ROW + h * Q_HEAD;
124
  let oBase = token * O_ROW + h * O_HEAD;
@@ -127,9 +543,10 @@ fn main(
127
  running_max = -3.4028234663852886e38;
128
  running_denom = 0.0;
129
  }
130
- for (var d: u32 = tid; d < V_HEAD_DIM; d = d + WG) {
131
  running_out[d] = 0.0;
132
  }
 
133
  workgroupBarrier();
134
 
135
  for (var keyToken: u32 = info.keyStart; keyToken < info.keyEnd; keyToken = keyToken + 1u) {
@@ -173,15 +590,21 @@ fn main(
173
  {% if hasBias %}
174
  v_value = v_value + f32(bias[BIAS_V + h * V_HEAD_DIM + d]);
175
  {% endif %}
 
 
 
176
  running_out[d] = running_out[d] * previous_scale + probability_numerator * v_value;
 
177
  }
178
  workgroupBarrier();
179
  }
180
 
181
  // A token whose sequence carries no key leaves running_denom at zero; emit a
182
  // zero row rather than 0 * (1/0) = NaN.
 
183
  let inv_denom = select(0.0, 1.0 / running_denom, running_denom > 0.0);
 
184
  for (var d: u32 = tid; d < V_HEAD_DIM; d = d + WG) {
185
- output[oBase + d] = {{ outputScalar }}(running_out[d] * inv_denom);
186
  }
187
  }
 
1
  {{ env.wgsl.resourceDeclarations }}
2
+ {% set normalizedValues = scalar == "f32" %}
3
+ {% if normalizedValues %}
4
+ {% macro sum_error_function(name, type="f32", protectDifference=false) %}
5
+ {% set bitsType = type | replace("f32", "u32") %}
6
+ // Observing the rounded sum as bits preserves FastTwoSum on backends
7
+ // that otherwise reassociate its subtractions. Both signs of zero contribute zero.
8
+ fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {
9
+ let bits = bitcast<{{ bitsType }}>(x);
10
+ return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));
11
+ }
12
+ fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {
13
+ let swap = abs(a) < abs(b);
14
+ let larger = select(a, b, swap);
15
+ let smaller = select(b, a, swap);
16
+ // Keep the rounded high-part difference observable before subtracting it
17
+ // from the smaller addend. Reassociation here erases the residual.
18
+ return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);
19
+ }
20
+ {% endmacro %}
21
+ {% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}
22
+ {% set N = 1 if type == "f32" else (type[3] | int) %}
23
+ {% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}
24
+ {% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}
25
+ {% set exact = add or rescale or merge %}
26
+ struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }
27
+ struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }
28
+
29
+ {% if exact %}
30
+ fn scaled_value_scalar_zero() -> ScaledValueScalar {
31
+ return ScaledValueScalar(0.0, 0.0, 0);
32
+ }
33
+ {% endif %}
34
+ fn scaled_value_scalar_finite(x: f32) -> bool {
35
+ return abs(x) <= 3.4028234663852886e38;
36
+ }
37
+ {% if exact or align %}
38
+ fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {
39
+ if (a.hi == 0.0) {
40
+ if (a.lo == 0.0) { return -1024; }
41
+ return a.exponent + frexp(a.lo).exp;
42
+ }
43
+ if (!scaled_value_scalar_finite(a.hi)) { return 1024; }
44
+ return a.exponent + frexp(a.hi).exp;
45
+ }
46
+ {% endif %}
47
+ // Scale the significand bits directly. WGSL ldexp may return zero for a
48
+ // shift <= -127 even when its input makes the final result normal; shifts
49
+ // above 128 are indeterminate. Neither limit applies to this exponent sum.
50
+ fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {
51
+ let bits = bitcast<u32>(value);
52
+ let sign = bits & 0x80000000u;
53
+ let fraction = bits & 0x007fffffu;
54
+ let inputExponent = i32((bits >> 23u) & 0xffu);
55
+ if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }
56
+ var significand = fraction | 0x00800000u;
57
+ var exponent = inputExponent + shift;
58
+ if (inputExponent == 0) {
59
+ let normalize = countLeadingZeros(fraction) - 8u;
60
+ significand = fraction << normalize;
61
+ exponent = 1 + shift - i32(normalize);
62
+ }
63
+ if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }
64
+ if (exponent > 0) {
65
+ return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));
66
+ }
67
+ let distance = u32(1 - exponent);
68
+ if (distance > 24u) { return bitcast<f32>(sign); }
69
+ let high = significand >> distance;
70
+ let remainder = significand & ((1u << distance) - 1u);
71
+ let halfway = 1u << (distance - 1u);
72
+ let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);
73
+ return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));
74
+ }
75
+ {% if exact or align %}
76
+ fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {
77
+ if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }
78
+ if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }
79
+ return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);
80
+ }
81
+ {% endif %}
82
+ {% if exact %}
83
+ {% if recoverSum %}
84
+ {{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}
85
+ {% endif %}
86
+ fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {
87
+ let nextHi = fma(hi, 1.0, lo);
88
+ let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};
89
+ if (nextHi == 0.0) { return scaled_value_scalar_zero(); }
90
+ if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }
91
+ let parts = frexp(nextHi);
92
+ let rawExponent = exponent + parts.exp;
93
+ // Ordinary magnitudes return to the unscaled fast path. The margin keeps
94
+ // boundary values away from overflow/underflow while scaling the low word.
95
+ if (rawExponent >= -120 && rawExponent <= 120) {
96
+ return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);
97
+ }
98
+ return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);
99
+ }
100
+ fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {
101
+ let sum = fma(a.hi, 1.0, product);
102
+ let bv = fma(-1.0, a.hi, sum);
103
+ let av = fma(-1.0, bv, sum);
104
+ let ae = fma(-1.0, av, a.hi);
105
+ let be = fma(-1.0, bv, product);
106
+ let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);
107
+ let hi = fma(sum, 1.0, residual);
108
+ return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);
109
+ }
110
+ fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {
111
+ if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||
112
+ !scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||
113
+ !scaled_value_scalar_finite(weight)) {
114
+ return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);
115
+ }
116
+ if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }
117
+ if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }
118
+ if (a.exponent == 0 && b.exponent == 0) {
119
+ let product = fma(weight, b.hi, 0.0);
120
+ let lowProduct = fma(weight, b.lo, 0.0);
121
+ let rawSum = fma(a.hi, 1.0, product);
122
+ let productNormal = abs(product) >= 1.1754943508222875e-38;
123
+ if (productNormal && scaled_value_scalar_finite(product) &&
124
+ scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {
125
+ let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);
126
+ let result = scaled_value_scalar_add_words(a, product, error);
127
+ if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }
128
+ }
129
+ }
130
+ // Decompose BEFORE multiplying: a merge coefficient may exceed one, so
131
+ // its unscaled product with a finite partial mean need not fit in f32.
132
+ var other = b;
133
+ if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }
134
+ let wp = frexp(weight);
135
+ let vp = frexp(other.hi);
136
+ let productExponent = other.exponent + wp.exp + vp.exp;
137
+ let commonExponent = max(scaled_value_scalar_leading(a), productExponent);
138
+ let aligned = scaled_value_scalar_align(a, commonExponent);
139
+ let product = fma(wp.fract, vp.fract, 0.0);
140
+ let productError = fma(wp.fract, vp.fract, -product);
141
+ let shift = productExponent - commonExponent;
142
+ let highWord = scaled_value_scalar_shift(product, shift);
143
+ let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,
144
+ fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));
145
+ {% if recoverSum %}
146
+ let sum = aligned.hi + highWord;
147
+ let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;
148
+ return scaled_value_scalar_finish(sum, low, commonExponent);
149
+ {% else %}
150
+ let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);
151
+ return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);
152
+ {% endif %}
153
+ }
154
+ {% endif %}
155
+ fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {
156
+ if (denominator == 0.0) { return 0.0; }
157
+ if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }
158
+ if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {
159
+ return fma(a.hi, 1.0, a.lo) / denominator;
160
+ }
161
+ let valueParts = frexp(a.hi);
162
+ let denominatorParts = frexp(denominator);
163
+ let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));
164
+ let quotient = mantissa / denominatorParts.fract;
165
+ return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);
166
+ }
167
+ fn scaled_value_zero() -> ScaledValue {
168
+ return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));
169
+ }
170
+ {% if N > 1 or rescale or lean %}
171
+ // Vector form of scaled_value_scalar_add_words: applies it to every component at once.
172
+ fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {
173
+ let sum = fma(acc.hi, {{ type }}(1.0), product);
174
+ {% if magnitudeOrdered %}
175
+ // FastTwoSum recovers the rounding error with the larger magnitude first.
176
+ let takeProduct = abs(acc.hi) < abs(product);
177
+ let larger = select(acc.hi, product, takeProduct);
178
+ let smaller = select(product, acc.hi, takeProduct);
179
+ let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);
180
+ let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);
181
+ {% else %}
182
+ let bv = fma({{ type }}(-1.0), acc.hi, sum);
183
+ let av = fma({{ type }}(-1.0), bv, sum);
184
+ let ae = fma({{ type }}(-1.0), av, acc.hi);
185
+ let be = fma({{ type }}(-1.0), bv, product);
186
+ let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);
187
+ {% endif %}
188
+ let hi = fma(sum, {{ type }}(1.0), residual);
189
+ return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);
190
+ }
191
+ {% endif %}
192
+ {% if lean %}
193
+ // Lean folds: the compensated arithmetic of scaled_value_add_step with every
194
+ // check deferred to the fold's end. A fold that starts from a normalized pair at
195
+ // exponent zero (the high word is the words' rounded sum), ends with finite words
196
+ // (a non-finite word stays non-finite through the sum, so this covers the start
197
+ // too), and whose smallest nonzero weight times smallest nonzero value is normal
198
+ // took only steps whose result is scaled_value_add's, up to the sign of a zero
199
+ // word: each nonzero product was normal, every step leaves the pair normalized,
200
+ // and a zero product leaves a normalized pair unchanged.
201
+ fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {
202
+ let w = {{ type }}(weight);
203
+ let product = fma(w, value, {{ type }}(0.0));
204
+ return scaled_value_add_words(acc, product, fma(w, value, -product));
205
+ }
206
+ // The smallest nonzero magnitude among `low` and `value`, per component.
207
+ fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {
208
+ return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));
209
+ }
210
+ fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {
211
+ return all(start.exponent == {{ exponentType }}(0)) &&
212
+ all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &
213
+ (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &
214
+ ({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));
215
+ }
216
+ {% endif %}
217
+ {% if N > 1 and tile %}
218
+ {% set uType = "vec" ~ N ~ "<u32>" %}
219
+ // Offset tile folds. A tile's products, at most `bound` in total magnitude per
220
+ // component, add onto `offset`, the power of two above 2.25 * bound, so every
221
+ // partial sum stays within [offset / 2, 2 * offset): each step's change to it is
222
+ // exact, and the low word gathers each step's remainder, at most half an ulp of
223
+ // the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the
224
+ // offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A
225
+ // non-finite weight, value or bound leaves a non-finite word, and a bound past
226
+ // 2^126 an infinite offset, so a caller checks finiteness once, after its fold;
227
+ // scaled_value_tile_in_range checks what that cannot see.
228
+ struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }
229
+ fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {
230
+ let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));
231
+ let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));
232
+ return ScaledValueTile(offset, offset, {{ type }}(0.0));
233
+ }
234
+ fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {
235
+ let w = {{ type }}(weight);
236
+ let sum = fma(w, value, tile.sum);
237
+ let change = fma({{ type }}(-1.0), tile.sum, sum);
238
+ return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));
239
+ }
240
+ // The tile's words, normalized, added as scaled_value_add adds a product.
241
+ fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {
242
+ let high = fma({{ type }}(-1.0), tile.offset, tile.sum);
243
+ let sum = fma(high, {{ type }}(1.0), tile.low);
244
+ let bv = fma({{ type }}(-1.0), high, sum);
245
+ let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));
246
+ return scaled_value_add_words(acc, sum, error);
247
+ }
248
+ // An offset or start of at least 2^-76, or a zero bound, keeps every word a
249
+ // flush-to-zero device could drop below 2^-48 of the result.
250
+ fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}) -> bool {
251
+ return all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |
252
+ (bound == {{ type }}(0.0)));
253
+ }
254
+ {% endif %}
255
+ {% if N > 1 and add %}
256
+ // One compensated fold step without branches, for a caller that folds many
257
+ // steps before it can afford a branch. From finite words at exponent zero, a
258
+ // normal product and a finite low word imply every other condition of this
259
+ // arithmetic in scaled_value_add: the low word is finite only if the high word
260
+ // is, then the sum is, then the product, the weight and the value. A zero
261
+ // weight with a finite value is the step whose exact result is the accumulator
262
+ // itself. `exact` is false in any component whose step only scaled_value_add
263
+ // computes.
264
+ struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }
265
+ fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {
266
+ let w = {{ type }}(weight);
267
+ let product = fma(w, value, {{ type }}(0.0));
268
+ let sum = scaled_value_add_words(acc, product, fma(w, value, -product));
269
+ let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));
270
+ let fast = (abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));
271
+ return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),
272
+ fast | vec{{ N }}<bool>(keep));
273
+ }
274
+ {% endif %}
275
+ {% if add %}
276
+ fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {
277
+ {% if N > 1 %}
278
+ // Ordinary raw products use one vector compensated sum. Every exceptional
279
+ // component falls back to the same scalar exponent-aware implementation.
280
+ if (all(acc.exponent == {{ exponentType }}(0)) &&
281
+ all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&
282
+ all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {
283
+ let step = scaled_value_add_step(acc, weight, value);
284
+ if (all(step.exact)) { return step.value; }
285
+ }
286
+ {% endif %}
287
+ var result = scaled_value_zero();
288
+ {% for i in range(N) %}
289
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
290
+ let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), weight{% if coefficientType != "f32" %}[{{ i }}]{% endif %}, ScaledValueScalar(value{{ c }}, 0.0, 0));
291
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
292
+ {% endfor %}
293
+ return result;
294
+ }
295
+ {% endif %}
296
+ {% if rescale or tile %}
297
+ {% macro rescale_words() %}
298
+ let w = {{ type }}(correction);
299
+ let product = fma(w, acc.hi, {{ type }}(0.0));
300
+ let scaled = scaled_value_add_words(scaled_value_zero(), product,
301
+ fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));
302
+ let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);
303
+ let unit = correction == 1.0;
304
+ {% endmacro %}
305
+ {% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &
306
+ (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &
307
+ (zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &
308
+ (abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}
309
+ {% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),
310
+ select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}
311
+ {% endif %}
312
+ {% if tile %}
313
+ // scaled_value_rescale's vector path alone; `exact` is false where only its
314
+ // scalar path applies.
315
+ struct ScaledValueRescaled { value: ScaledValue, exact: bool }
316
+ fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {
317
+ {{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});
318
+ }
319
+ {% endif %}
320
+ {% if rescale %}
321
+ fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {
322
+ // From finite words at exponent zero, the scalar path below leaves zero
323
+ // words for a zero value or correction, the value itself for a unit
324
+ // correction, and otherwise this compensated product onto zero words when
325
+ // the product is normal and the low word finite (which bounds the rest, as
326
+ // in scaled_value_add_step).
327
+ {{ rescale_words() }} if ({{ rescale_vector_exact() }}) {
328
+ return {{ rescale_vector_value() }};
329
+ }
330
+ var result = scaled_value_zero();
331
+ {% for i in range(N) %}
332
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
333
+ let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));
334
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
335
+ {% endfor %}
336
+ return result;
337
+ }
338
+ {% endif %}
339
+ {% if merge %}
340
+ fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {
341
+ var result = scaled_value_zero();
342
+ {% for i in range(N) %}
343
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
344
+ let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), 1.0, ScaledValueScalar(other.hi{{ c }}, other.lo{{ c }}, other.exponent{{ c }}));
345
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
346
+ {% endfor %}
347
+ return result;
348
+ }
349
+ {% endif %}
350
+ fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {
351
+ // Words at exponent zero well inside the normal range, with a normal
352
+ // quotient: the scalar path below divides this same sum by this same
353
+ // denominator, each scaled by a power of two, so it rounds to this quotient
354
+ // wherever division is scale-invariant. Bounding the denominator above also
355
+ // keeps a division through its reciprocal clear of a subnormal reciprocal.
356
+ let d = {{ type }}(denominator);
357
+ let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);
358
+ let quotient = sum / d;
359
+ if (all((acc.exponent == {{ exponentType }}(0)) &
360
+ (abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &
361
+ (abs(acc.lo) <= abs(acc.hi)) &
362
+ (abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &
363
+ ((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {
364
+ return quotient;
365
+ }
366
+ var result = {{ type }}(0.0);
367
+ {% for i in range(N) %}
368
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
369
+ result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});
370
+ {% endfor %}
371
+ return result;
372
+ }
373
+ {% if align %}
374
+ fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {
375
+ var result = {{ exponentType }}(0);
376
+ {% for i in range(N) %}
377
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
378
+ result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));
379
+ {% endfor %}
380
+ return result;
381
+ }
382
+ fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {
383
+ var result = scaled_value_zero();
384
+ {% for i in range(N) %}
385
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
386
+ let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});
387
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
388
+ {% endfor %}
389
+ return result;
390
+ }
391
+ {% endif %}
392
+ {% endmacro %}
393
+ {{ scaled_value_functions("f32", "f32", true) }}
394
+ {% endif %}
395
  {% set QBUF = "query" %}
396
  {% set KBUF = "query" if packedQkv else "key" %}
397
  {% set VBUF = "query" if packedQkv else "value" %}
 
410
  // Source: separate token-major `[T, hidden]` query, key and value buffers.
411
  {% endif %}
412
  {% if hasBias %}
413
+ // Add packed `[Q; K; V]` bias rows to Q, K and V during the key walk,
414
+ // before computing scores and accumulating values.
415
  {% endif %}
416
  {% if hasAttnBias %}
417
  // The additive attention bias lives in PADDED coordinates: its trailing two
 
441
  var<workgroup> partial: array<f32, WG>;
442
  var<workgroup> running_max: f32;
443
  var<workgroup> running_denom: f32;
444
+ {% if not normalizedValues %}var<workgroup> running_out: array<f32, V_HEAD_DIM>;
445
+ {% endif %}
446
  var<workgroup> previous_scale: f32;
447
  {% macro wgsl_tree_reduce_f32(name, mode, buffer="partial", wg="WG", trailingBarrier=true, valueType="f32") %}
448
  fn {{ name }}(value: {{ valueType }}, tid: u32) -> {{ valueType }} {
 
463
  break;
464
  }
465
  }
 
 
 
466
  let reduced = {{ buffer }}[0];
467
+ // Every lane reads slot 0 above, so a following reduction's first store must not run until
468
+ // all lanes have read it.
469
  workgroupBarrier();
470
  return reduced;
471
  }
 
489
  }
490
 
491
  fn packed_token_of(token: u32, seqPad: u32) -> PackedToken {
 
492
  var info: PackedToken;
493
+ // An invalid prefix or mapping denotes an empty key range, so every consumer
494
+ // writes a zero row. Check signed endpoints before unsigned subtraction and
495
+ // keep all ranges inside this packed stream and its padded bias grid.
496
+ if (cumulative_sequence_length[0] != 0
497
+ || cumulative_sequence_length[{{ batchSize }}u] != {{ tokenCount }}i) { return info; }
498
+ var previous = 0i;
499
+ for (var b = 1u; b <= {{ batchSize }}u; b++) {
500
+ let end = cumulative_sequence_length[b];
501
+ if (end < previous || end > {{ tokenCount }}i || u32(end - previous) > seqPad) { return info; }
502
+ previous = end;
503
+ }
504
+ let signedFlat = token_offset[token];
505
+ if (signedFlat < 0) { return info; }
506
+ let flat = u32(signedFlat);
507
+ if (flat / seqPad >= {{ batchSize }}u) { return info; }
508
  info.sequence = flat / seqPad;
509
  info.position = flat - info.sequence * seqPad;
510
+ let start = u32(cumulative_sequence_length[info.sequence]);
511
+ let end = u32(cumulative_sequence_length[info.sequence + 1u]);
512
+ if (info.position > token || token - info.position != start || token >= end) {
513
+ return PackedToken();
514
+ }
515
+ info.keyStart = start;
516
+ info.keyEnd = end;
517
  return info;
518
  }
519
 
 
531
  }
532
 
533
  let tid = lid.x;
534
+ {% if normalizedValues %}
535
+ var output_acc: array<ScaledValue, (V_HEAD_DIM + WG - 1u) / WG>;
536
+ for (var i = 0u; i < (V_HEAD_DIM + WG - 1u) / WG; i++) { output_acc[i] = scaled_value_zero(); }
537
+ {% endif %}
538
  let info = packed_token_of(token, params.seqPad);
539
  let qBase = token * Q_ROW + h * Q_HEAD;
540
  let oBase = token * O_ROW + h * O_HEAD;
 
543
  running_max = -3.4028234663852886e38;
544
  running_denom = 0.0;
545
  }
546
+ {% if not normalizedValues %} for (var d: u32 = tid; d < V_HEAD_DIM; d = d + WG) {
547
  running_out[d] = 0.0;
548
  }
549
+ {% endif %}
550
  workgroupBarrier();
551
 
552
  for (var keyToken: u32 = info.keyStart; keyToken < info.keyEnd; keyToken = keyToken + 1u) {
 
590
  {% if hasBias %}
591
  v_value = v_value + f32(bias[BIAS_V + h * V_HEAD_DIM + d]);
592
  {% endif %}
593
+ {% if normalizedValues %}
594
+ output_acc[d / WG] = scaled_value_add(scaled_value_rescale(output_acc[d / WG], previous_scale), probability_numerator, v_value);
595
+ {% else %}
596
  running_out[d] = running_out[d] * previous_scale + probability_numerator * v_value;
597
+ {% endif %}
598
  }
599
  workgroupBarrier();
600
  }
601
 
602
  // A token whose sequence carries no key leaves running_denom at zero; emit a
603
  // zero row rather than 0 * (1/0) = NaN.
604
+ {% if not normalizedValues %}
605
  let inv_denom = select(0.0, 1.0 / running_denom, running_denom > 0.0);
606
+ {% endif %}
607
  for (var d: u32 = tid; d < V_HEAD_DIM; d = d + WG) {
608
+ output[oBase + d] = {{ outputScalar }}({% if normalizedValues %}scaled_value_mean(output_acc[d / WG], running_denom){% else %}running_out[d] * inv_denom{% endif %});
609
  }
610
  }
build/webgpu/bench.json CHANGED
@@ -46,7 +46,7 @@
46
  "fragment_schedule_326ff2747fbb": [0, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 131, 132, 133],
47
  "fragment_schedule_eb0c4a513a9e": [345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 1032, 1033, 1034]
48
  },
49
- "tunableSpace": { "CLUSTER_TILE_K": [8, 16], "SCALAR_WORKGROUP_SIZE": [64, 128] },
50
  "cases": [
51
  {
52
  "name": "pmha-minilm-b16-pad-f16",
 
46
  "fragment_schedule_326ff2747fbb": [0, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 131, 132, 133],
47
  "fragment_schedule_eb0c4a513a9e": [345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 1032, 1033, 1034]
48
  },
49
+ "tunableSpace": { "SCALAR_WORKGROUP_SIZE": [64, 128] },
50
  "cases": [
51
  {
52
  "name": "pmha-minilm-b16-pad-f16",
build/webgpu/manifest.json CHANGED
@@ -1,667 +1 @@
1
- {
2
- "domain": "com.microsoft",
3
- "name": "PackedMultiHeadAttention",
4
- "sinceVersion": 1,
5
- "inputs": {
6
- "queryT": { "onnx": "query", "dtype": "T" },
7
- "keyT": { "onnx": "key", "dtype": "T", "rank": 2, "optional": true },
8
- "valueT": { "onnx": "value", "dtype": "T", "rank": 2, "optional": true },
9
- "biasT": { "onnx": "bias", "dtype": "T", "rank": 1, "optional": true },
10
- "tokenOffsetT": { "onnx": "token_offset", "dtype": "M", "rank": 2, "storage": "int32" },
11
- "cumulativeSequenceLengthT": { "onnx": "cumulative_sequence_length", "dtype": "M", "rank": 1, "storage": "int32" },
12
- "attentionBiasT": { "onnx": "attention_bias", "dtype": "T", "rank": 4, "optional": true }
13
- },
14
- "outputs": { "outputT": { "onnx": "output", "dtype": "T", "rank": 2, "shape": "[tokenCount, vHiddenSize]" } },
15
- "attributes": { "num_heads": {}, "scale": {} },
16
- "attributeConstraints": { "num_heads": { "required": true } },
17
- "typeConstraints": { "T": ["float32", "float16"], "M": ["int32"] },
18
- "tunables": { "CLUSTER_TILE_K": { "default": 16 }, "SCALAR_WORKGROUP_SIZE": { "default": 64 } },
19
- "derive": {
20
- "numHeads": "attrs.num_heads",
21
- "qNumHeads": "numHeads",
22
- "packedQkv": "ranks.queryT == 4",
23
- "tokenCount": "dim(shapes.queryT, 0)",
24
- "batchSize": "dim(shapes.tokenOffsetT, 0) if ranks.tokenOffsetT == 2 else 0",
25
- "seqPad": "dim(shapes.tokenOffsetT, 1) if ranks.tokenOffsetT == 2 else 0",
26
- "packedHeadDim": "dim(shapes.queryT, 3) if packedQkv else 0",
27
- "hiddenSize": "numHeads * packedHeadDim if packedQkv else (dim(shapes.queryT, 1) if ranks.queryT == 2 else 0)",
28
- "vHiddenSize": "hiddenSize if packedQkv else (dim(shapes.valueT, 1) if present.valueT and ranks.valueT == 2 else 0)",
29
- "headDim": "hiddenSize / numHeads if numHeads > 0 and hiddenSize % numHeads == 0 else 0",
30
- "vHeadDim": "vHiddenSize / numHeads if numHeads > 0 and vHiddenSize % numHeads == 0 else 0",
31
- "attentionScale": "attrs.scale if has(attrs, \"scale\") else 0",
32
- "qRowStride": "numHeads * 3 * headDim if packedQkv else hiddenSize",
33
- "qHeadStride": "3 * headDim if packedQkv else headDim",
34
- "kRowStride": "qRowStride if packedQkv else hiddenSize",
35
- "kHeadStride": "qHeadStride if packedQkv else headDim",
36
- "kOffset": "headDim if packedQkv else 0",
37
- "vRowStride": "qRowStride if packedQkv else vHiddenSize",
38
- "vHeadStride": "qHeadStride if packedQkv else vHeadDim",
39
- "vOffset": "2 * headDim if packedQkv else 0",
40
- "oRowStride": "vHiddenSize",
41
- "oHeadStride": "vHeadDim",
42
- "biasKOffset": "hiddenSize",
43
- "biasVOffset": "2 * hiddenSize",
44
- "attnBiasHeads": "dim(shapes.attentionBiasT, 1) if present.attentionBiasT and ranks.attentionBiasT == 4 else 0",
45
- "maskSeqStride": "seqPad",
46
- "maskHeadStride": "0 if attnBiasHeads == 1 else seqPad * seqPad",
47
- "maskBatchStride": "0 if (not present.attentionBiasT) or ranks.attentionBiasT != 4 or dim(shapes.attentionBiasT, 0) == 1 else attnBiasHeads * seqPad * seqPad",
48
- "dtypeOk": "tensorDtypes.outputT == tensorDtypes.queryT and (tensorDtypes.queryT == \"float32\" or tensorDtypes.queryT == \"float16\") and f16Ok(dtypes.T)",
49
- "packedShapeOk": "packedQkv and not present.keyT and not present.valueT and dim(shapes.queryT, 1) == numHeads and dim(shapes.queryT, 2) == 3 and packedHeadDim > 0",
50
- "separateShapeOk": "ranks.queryT == 2 and present.keyT and present.valueT and ranks.keyT == 2 and ranks.valueT == 2 and sameShape(shapes.keyT, shapes.queryT) and dim(shapes.valueT, 0) == tokenCount and tensorDtypes.keyT == tensorDtypes.queryT and tensorDtypes.valueT == tensorDtypes.queryT",
51
- "scheduleOk": "ranks.tokenOffsetT == 2 and ranks.cumulativeSequenceLengthT == 1 and dim(shapes.cumulativeSequenceLengthT, 0) == batchSize + 1 and batchSize > 0 and seqPad > 0 and numel(shapes.tokenOffsetT) >= tokenCount",
52
- "outputShapeOk": "ranks.outputT == 2 and dim(shapes.outputT, 0) == tokenCount and dim(shapes.outputT, 1) == vHiddenSize",
53
- "biasOk": "present.biasT and ranks.biasT == 1 and dim(shapes.biasT, 0) == 2 * hiddenSize + vHiddenSize and tensorDtypes.biasT == tensorDtypes.queryT",
54
- "attnBiasOk": "present.attentionBiasT and ranks.attentionBiasT == 4 and (dim(shapes.attentionBiasT, 0) == 1 or dim(shapes.attentionBiasT, 0) == batchSize) and (attnBiasHeads == 1 or attnBiasHeads == numHeads) and dim(shapes.attentionBiasT, 2) == seqPad and dim(shapes.attentionBiasT, 3) == seqPad and tensorDtypes.attentionBiasT == tensorDtypes.queryT",
55
- "hasBias": "present.biasT",
56
- "hasAttnBias": "present.attentionBiasT",
57
- "baseContract": "dtypeOk and scheduleOk and outputShapeOk and numHeads > 0 and headDim > 0 and vHeadDim > 0 and tokenCount > 0 and (packedShapeOk or separateShapeOk)",
58
- "usesF16": "tensorDtypes.queryT == \"float16\"",
59
- "scalar": "\"f16\" if usesF16 else \"f32\"",
60
- "outputScalar": "scalar",
61
- "inputVec4": "\"vec4<f16>\" if usesF16 else \"vec4<f32>\"",
62
- "qkvBytes": "2 if usesF16 else 4",
63
- "packedStageBytes": "4 if usesF16 and present.biasT and vHeadDim != headDim else qkvBytes",
64
- "clusterWidthAligned": "headDim % 16 == 0 and vHeadDim % 4 == 0",
65
- "headDimV4": "headDim / 4",
66
- "qRowStrideV4": "qRowStride / 4",
67
- "qHeadStrideV4": "qHeadStride / 4",
68
- "kRowStrideV4": "kRowStride / 4",
69
- "kHeadStrideV4": "kHeadStride / 4",
70
- "kOffsetV4": "kOffset / 4",
71
- "vRowStrideV4": "vRowStride / 4",
72
- "vHeadStrideV4": "vHeadStride / 4",
73
- "vOffsetV4": "vOffset / 4",
74
- "oRowStrideV4": "oRowStride / 4",
75
- "oHeadStrideV4": "oHeadStride / 4",
76
- "scalarWg": "tunables.SCALAR_WORKGROUP_SIZE",
77
- "scalarBytes": "4 * scalarWg + 4 * vHeadDim + 12",
78
- "scalarOk": "scalarWg <= device.limits.maxComputeInvocationsPerWorkgroup and scalarWg <= device.limits.maxComputeWorkgroupSizeX and scalarBytes <= device.limits.maxComputeWorkgroupStorageSize and numHeads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)",
79
- "clusterTileQ": "min(16, pow2ceil(tokenCount)) if vHeadDim != headDim else 16",
80
- "clusterBaseLpq": "8 if headDim % 32 == 0 else 4",
81
- "clusterTileK": "min(tunables.CLUSTER_TILE_K, pow2ceil(tokenCount)) if vHeadDim != headDim else tunables.CLUSTER_TILE_K",
82
- "clusterTileBytes": "clusterTileK * (headDim + vHeadDim) * packedStageBytes",
83
- "clusterLaneTarget": "min(32, max(clusterBaseLpq, pow2ceil(headDim / 16)), device.adapterInfo.subgroupMinSize, pow2ceil(floor(min(device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX) / clusterTileQ) + 1) / 2) if vHeadDim == headDim and clusterWidthAligned and clusterTileBytes <= device.limits.maxComputeWorkgroupStorageSize and device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and device.adapterInfo.subgroupMinSize >= clusterBaseLpq else clusterBaseLpq",
84
- "clusterLpq": "clusterLaneTarget if ceilDiv(headDim, 4 * clusterBaseLpq) >= 2 * ceilDiv(headDim, 4 * clusterLaneTarget) else clusterBaseLpq",
85
- "clusterWg": "clusterTileQ * clusterLpq",
86
- "clusterNosgBytes": "clusterTileBytes + 4 * clusterWg",
87
- "clusterTiles": "ceilDiv(tokenCount, clusterTileQ)",
88
- "clusterShapeOk": "clusterWidthAligned and clusterWg <= device.limits.maxComputeInvocationsPerWorkgroup and clusterWg <= device.limits.maxComputeWorkgroupSizeX and numHeads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)",
89
- "clusterOk": "clusterShapeOk and clusterTileBytes <= device.limits.maxComputeWorkgroupStorageSize",
90
- "clusterNosgOk": "clusterShapeOk and clusterNosgBytes <= device.limits.maxComputeWorkgroupStorageSize",
91
- "clusterSubgroupsOk": "has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize >= clusterLpq and device.adapterInfo.subgroupMinSize % clusterLpq == 0 and device.adapterInfo.subgroupMaxSize >= device.adapterInfo.subgroupMinSize and device.adapterInfo.subgroupMaxSize % clusterLpq == 0",
92
- "portableLaneTarget": "min(64, pow2ceil(max(headDimV4, vHeadDim / 4) / 4), device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX)",
93
- "portableLpq": "max(clusterLpq, pow2ceil(portableLaneTarget + 1) / 2) if vHeadDim != headDim else (64 if portableLaneTarget >= 64 and headDimV4 % 64 == 0 else (32 if portableLaneTarget >= 32 and headDimV4 % 32 == 0 else (16 if portableLaneTarget >= 16 and headDimV4 % 16 == 0 else clusterLpq)))",
94
- "portableTileQ": "min(clusterTileQ, pow2ceil(tokenCount), max(1, floor(min(clusterWg, device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX) / portableLpq)))",
95
- "portableWg": "portableTileQ * portableLpq",
96
- "portableKeyCapacity": "max(1, floor(device.limits.maxComputeWorkgroupStorageSize / ((headDim + vHeadDim) * packedStageBytes + 4 * portableWg)))",
97
- "portableTileK": "min(clusterTileK, pow2ceil(tokenCount), pow2ceil(portableKeyCapacity + 1) / 2)",
98
- "clusterDistributedBytes": "portableTileK * (headDim + vHeadDim) * packedStageBytes + 4 * max(portableWg * portableTileK, 2 * portableWg + portableTileQ * portableTileK)",
99
- "clusterDistributedOk": "clusterDistributedBytes <= device.limits.maxComputeWorkgroupStorageSize",
100
- "clusterUseDistributed": "clusterDistributedOk and (clusterLpq > 4 or vHeadDim != headDim)",
101
- "portableTiles": "ceilDiv(tokenCount, portableTileQ if clusterUseDistributed else clusterTileQ)",
102
- "clusterPortableOk": "clusterShapeOk and (clusterUseDistributed or clusterNosgOk) and portableWg <= device.limits.maxComputeInvocationsPerWorkgroup and portableWg <= device.limits.maxComputeWorkgroupSizeX and ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)"
103
- },
104
- "bindings": {
105
- "query": { "arg": "queryT", "name": "query" },
106
- "key": { "arg": "keyT", "name": "key" },
107
- "value": { "arg": "valueT", "name": "value" },
108
- "bias": { "arg": "biasT", "name": "bias" },
109
- "tokenOffset": { "arg": "tokenOffsetT", "name": "token_offset" },
110
- "cumSeqLen": { "arg": "cumulativeSequenceLengthT", "name": "cumulative_sequence_length" },
111
- "attnBias": { "arg": "attentionBiasT", "name": "attn_bias" },
112
- "output": { "arg": "outputT", "name": "output" },
113
- "query4": { "arg": "queryT", "name": "query", "elementType": "$inputVec4" },
114
- "key4": { "arg": "keyT", "name": "key", "elementType": "$inputVec4" },
115
- "value4": { "arg": "valueT", "name": "value", "elementType": "$inputVec4" },
116
- "output4": { "arg": "outputT", "name": "output", "elementType": "$inputVec4" },
117
- "params": {
118
- "name": "params",
119
- "struct": [
120
- { "name": "tokenCount", "type": "u32", "value": "tokenCount" },
121
- { "name": "seqPad", "type": "u32", "value": "seqPad" },
122
- { "name": "scale", "type": "f32", "value": "attentionScale" }
123
- ]
124
- },
125
- "paramsMask": {
126
- "name": "params",
127
- "struct": [
128
- { "name": "tokenCount", "type": "u32", "value": "tokenCount" },
129
- { "name": "seqPad", "type": "u32", "value": "seqPad" },
130
- { "name": "scale", "type": "f32", "value": "attentionScale" },
131
- { "name": "maskBatchStride", "type": "u32", "value": "maskBatchStride" },
132
- { "name": "maskHeadStride", "type": "u32", "value": "maskHeadStride" },
133
- { "name": "maskSeqStride", "type": "u32", "value": "maskSeqStride" }
134
- ]
135
- }
136
- },
137
- "variants": [
138
- {
139
- "id": "packed_flash",
140
- "priority": 40,
141
- "when": ["baseContract", "packedShapeOk", "not present.biasT", "not present.attentionBiasT", "clusterOk", "clusterSubgroupsOk"],
142
- "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" },
143
- "passes": [
144
- {
145
- "id": "main",
146
- "name": "PackedMultiHeadAttention.Cluster",
147
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
148
- "bindings": ["query4", "tokenOffset", "cumSeqLen", "output4", "params"],
149
- "dispatch": {
150
- "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)",
151
- "y": "numHeads",
152
- "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)"
153
- }
154
- }
155
- ],
156
- "requires": { "features": ["subgroups"] },
157
- "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"]
158
- },
159
- {
160
- "id": "packed_flash_nosg",
161
- "priority": 20,
162
- "when": ["baseContract", "packedShapeOk", "not present.biasT", "not present.attentionBiasT", "clusterPortableOk"],
163
- "derive": {
164
- "useSubgroups": false,
165
- "LPQ": "portableLpq if clusterUseDistributed else clusterLpq",
166
- "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ",
167
- "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK",
168
- "distributedSoftmax": "clusterUseDistributed"
169
- },
170
- "passes": [
171
- {
172
- "id": "main",
173
- "name": "PackedMultiHeadAttention.Cluster",
174
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
175
- "bindings": ["query4", "tokenOffset", "cumSeqLen", "output4", "params"],
176
- "dispatch": {
177
- "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)",
178
- "y": "numHeads",
179
- "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)"
180
- }
181
- }
182
- ],
183
- "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"]
184
- },
185
- {
186
- "id": "packed_serial",
187
- "priority": 0,
188
- "when": ["baseContract", "packedShapeOk", "not present.biasT", "not present.attentionBiasT", "scalarOk"],
189
- "derive": { "workgroupSize": "scalarWg" },
190
- "passes": [
191
- {
192
- "id": "main",
193
- "name": "PackedMultiHeadAttention.Serial",
194
- "shader": "attn-packed-varlen-scalar.wgsl.jinja",
195
- "bindings": ["query", "tokenOffset", "cumSeqLen", "output", "params"],
196
- "dispatch": {
197
- "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)",
198
- "y": "numHeads",
199
- "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)"
200
- }
201
- }
202
- ]
203
- },
204
- {
205
- "id": "packed_attn_bias_flash",
206
- "priority": 40,
207
- "when": ["baseContract", "packedShapeOk", "not present.biasT", "attnBiasOk", "clusterOk", "clusterSubgroupsOk"],
208
- "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" },
209
- "passes": [
210
- {
211
- "id": "main",
212
- "name": "PackedMultiHeadAttention.Cluster",
213
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
214
- "bindings": ["query4", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"],
215
- "dispatch": {
216
- "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)",
217
- "y": "numHeads",
218
- "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)"
219
- }
220
- }
221
- ],
222
- "requires": { "features": ["subgroups"] },
223
- "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"]
224
- },
225
- {
226
- "id": "packed_attn_bias_flash_nosg",
227
- "priority": 20,
228
- "when": ["baseContract", "packedShapeOk", "not present.biasT", "attnBiasOk", "clusterPortableOk"],
229
- "derive": {
230
- "useSubgroups": false,
231
- "LPQ": "portableLpq if clusterUseDistributed else clusterLpq",
232
- "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ",
233
- "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK",
234
- "distributedSoftmax": "clusterUseDistributed"
235
- },
236
- "passes": [
237
- {
238
- "id": "main",
239
- "name": "PackedMultiHeadAttention.Cluster",
240
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
241
- "bindings": ["query4", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"],
242
- "dispatch": {
243
- "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)",
244
- "y": "numHeads",
245
- "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)"
246
- }
247
- }
248
- ],
249
- "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"]
250
- },
251
- {
252
- "id": "packed_attn_bias_serial",
253
- "priority": 0,
254
- "when": ["baseContract", "packedShapeOk", "not present.biasT", "attnBiasOk", "scalarOk"],
255
- "derive": { "workgroupSize": "scalarWg" },
256
- "passes": [
257
- {
258
- "id": "main",
259
- "name": "PackedMultiHeadAttention.Serial",
260
- "shader": "attn-packed-varlen-scalar.wgsl.jinja",
261
- "bindings": ["query", "tokenOffset", "cumSeqLen", "attnBias", "output", "paramsMask"],
262
- "dispatch": {
263
- "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)",
264
- "y": "numHeads",
265
- "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)"
266
- }
267
- }
268
- ]
269
- },
270
- {
271
- "id": "packed_bias_flash",
272
- "priority": 40,
273
- "when": ["baseContract", "packedShapeOk", "biasOk", "not present.attentionBiasT", "clusterOk", "clusterSubgroupsOk"],
274
- "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" },
275
- "passes": [
276
- {
277
- "id": "main",
278
- "name": "PackedMultiHeadAttention.Cluster",
279
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
280
- "bindings": ["query4", "bias", "tokenOffset", "cumSeqLen", "output4", "params"],
281
- "dispatch": {
282
- "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)",
283
- "y": "numHeads",
284
- "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)"
285
- }
286
- }
287
- ],
288
- "requires": { "features": ["subgroups"] },
289
- "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"]
290
- },
291
- {
292
- "id": "packed_bias_flash_nosg",
293
- "priority": 20,
294
- "when": ["baseContract", "packedShapeOk", "biasOk", "not present.attentionBiasT", "clusterPortableOk"],
295
- "derive": {
296
- "useSubgroups": false,
297
- "LPQ": "portableLpq if clusterUseDistributed else clusterLpq",
298
- "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ",
299
- "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK",
300
- "distributedSoftmax": "clusterUseDistributed"
301
- },
302
- "passes": [
303
- {
304
- "id": "main",
305
- "name": "PackedMultiHeadAttention.Cluster",
306
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
307
- "bindings": ["query4", "bias", "tokenOffset", "cumSeqLen", "output4", "params"],
308
- "dispatch": {
309
- "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)",
310
- "y": "numHeads",
311
- "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)"
312
- }
313
- }
314
- ],
315
- "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"]
316
- },
317
- {
318
- "id": "packed_bias_serial",
319
- "priority": 0,
320
- "when": ["baseContract", "packedShapeOk", "biasOk", "not present.attentionBiasT", "scalarOk"],
321
- "derive": { "workgroupSize": "scalarWg" },
322
- "passes": [
323
- {
324
- "id": "main",
325
- "name": "PackedMultiHeadAttention.Serial",
326
- "shader": "attn-packed-varlen-scalar.wgsl.jinja",
327
- "bindings": ["query", "bias", "tokenOffset", "cumSeqLen", "output", "params"],
328
- "dispatch": {
329
- "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)",
330
- "y": "numHeads",
331
- "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)"
332
- }
333
- }
334
- ]
335
- },
336
- {
337
- "id": "packed_bias_attn_bias_flash",
338
- "priority": 40,
339
- "when": ["baseContract", "packedShapeOk", "biasOk", "attnBiasOk", "clusterOk", "clusterSubgroupsOk"],
340
- "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" },
341
- "passes": [
342
- {
343
- "id": "main",
344
- "name": "PackedMultiHeadAttention.Cluster",
345
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
346
- "bindings": ["query4", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"],
347
- "dispatch": {
348
- "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)",
349
- "y": "numHeads",
350
- "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)"
351
- }
352
- }
353
- ],
354
- "requires": { "features": ["subgroups"] },
355
- "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"]
356
- },
357
- {
358
- "id": "packed_bias_attn_bias_flash_nosg",
359
- "priority": 20,
360
- "when": ["baseContract", "packedShapeOk", "biasOk", "attnBiasOk", "clusterPortableOk"],
361
- "derive": {
362
- "useSubgroups": false,
363
- "LPQ": "portableLpq if clusterUseDistributed else clusterLpq",
364
- "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ",
365
- "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK",
366
- "distributedSoftmax": "clusterUseDistributed"
367
- },
368
- "passes": [
369
- {
370
- "id": "main",
371
- "name": "PackedMultiHeadAttention.Cluster",
372
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
373
- "bindings": ["query4", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"],
374
- "dispatch": {
375
- "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)",
376
- "y": "numHeads",
377
- "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)"
378
- }
379
- }
380
- ],
381
- "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"]
382
- },
383
- {
384
- "id": "packed_bias_attn_bias_serial",
385
- "priority": 0,
386
- "when": ["baseContract", "packedShapeOk", "biasOk", "attnBiasOk", "scalarOk"],
387
- "derive": { "workgroupSize": "scalarWg" },
388
- "passes": [
389
- {
390
- "id": "main",
391
- "name": "PackedMultiHeadAttention.Serial",
392
- "shader": "attn-packed-varlen-scalar.wgsl.jinja",
393
- "bindings": ["query", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output", "paramsMask"],
394
- "dispatch": {
395
- "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)",
396
- "y": "numHeads",
397
- "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)"
398
- }
399
- }
400
- ]
401
- },
402
- {
403
- "id": "separate_flash",
404
- "priority": 40,
405
- "when": ["baseContract", "separateShapeOk", "not present.biasT", "not present.attentionBiasT", "clusterOk", "clusterSubgroupsOk"],
406
- "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" },
407
- "passes": [
408
- {
409
- "id": "main",
410
- "name": "PackedMultiHeadAttention.Cluster",
411
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
412
- "bindings": ["query4", "key4", "value4", "tokenOffset", "cumSeqLen", "output4", "params"],
413
- "dispatch": {
414
- "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)",
415
- "y": "numHeads",
416
- "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)"
417
- }
418
- }
419
- ],
420
- "requires": { "features": ["subgroups"] },
421
- "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"]
422
- },
423
- {
424
- "id": "separate_flash_nosg",
425
- "priority": 20,
426
- "when": ["baseContract", "separateShapeOk", "not present.biasT", "not present.attentionBiasT", "clusterPortableOk"],
427
- "derive": {
428
- "useSubgroups": false,
429
- "LPQ": "portableLpq if clusterUseDistributed else clusterLpq",
430
- "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ",
431
- "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK",
432
- "distributedSoftmax": "clusterUseDistributed"
433
- },
434
- "passes": [
435
- {
436
- "id": "main",
437
- "name": "PackedMultiHeadAttention.Cluster",
438
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
439
- "bindings": ["query4", "key4", "value4", "tokenOffset", "cumSeqLen", "output4", "params"],
440
- "dispatch": {
441
- "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)",
442
- "y": "numHeads",
443
- "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)"
444
- }
445
- }
446
- ],
447
- "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"]
448
- },
449
- {
450
- "id": "separate_serial",
451
- "priority": 0,
452
- "when": ["baseContract", "separateShapeOk", "not present.biasT", "not present.attentionBiasT", "scalarOk"],
453
- "derive": { "workgroupSize": "scalarWg" },
454
- "passes": [
455
- {
456
- "id": "main",
457
- "name": "PackedMultiHeadAttention.Serial",
458
- "shader": "attn-packed-varlen-scalar.wgsl.jinja",
459
- "bindings": ["query", "key", "value", "tokenOffset", "cumSeqLen", "output", "params"],
460
- "dispatch": {
461
- "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)",
462
- "y": "numHeads",
463
- "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)"
464
- }
465
- }
466
- ]
467
- },
468
- {
469
- "id": "separate_attn_bias_flash",
470
- "priority": 40,
471
- "when": ["baseContract", "separateShapeOk", "not present.biasT", "attnBiasOk", "clusterOk", "clusterSubgroupsOk"],
472
- "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" },
473
- "passes": [
474
- {
475
- "id": "main",
476
- "name": "PackedMultiHeadAttention.Cluster",
477
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
478
- "bindings": ["query4", "key4", "value4", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"],
479
- "dispatch": {
480
- "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)",
481
- "y": "numHeads",
482
- "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)"
483
- }
484
- }
485
- ],
486
- "requires": { "features": ["subgroups"] },
487
- "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"]
488
- },
489
- {
490
- "id": "separate_attn_bias_flash_nosg",
491
- "priority": 20,
492
- "when": ["baseContract", "separateShapeOk", "not present.biasT", "attnBiasOk", "clusterPortableOk"],
493
- "derive": {
494
- "useSubgroups": false,
495
- "LPQ": "portableLpq if clusterUseDistributed else clusterLpq",
496
- "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ",
497
- "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK",
498
- "distributedSoftmax": "clusterUseDistributed"
499
- },
500
- "passes": [
501
- {
502
- "id": "main",
503
- "name": "PackedMultiHeadAttention.Cluster",
504
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
505
- "bindings": ["query4", "key4", "value4", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"],
506
- "dispatch": {
507
- "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)",
508
- "y": "numHeads",
509
- "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)"
510
- }
511
- }
512
- ],
513
- "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"]
514
- },
515
- {
516
- "id": "separate_attn_bias_serial",
517
- "priority": 0,
518
- "when": ["baseContract", "separateShapeOk", "not present.biasT", "attnBiasOk", "scalarOk"],
519
- "derive": { "workgroupSize": "scalarWg" },
520
- "passes": [
521
- {
522
- "id": "main",
523
- "name": "PackedMultiHeadAttention.Serial",
524
- "shader": "attn-packed-varlen-scalar.wgsl.jinja",
525
- "bindings": ["query", "key", "value", "tokenOffset", "cumSeqLen", "attnBias", "output", "paramsMask"],
526
- "dispatch": {
527
- "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)",
528
- "y": "numHeads",
529
- "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)"
530
- }
531
- }
532
- ]
533
- },
534
- {
535
- "id": "separate_bias_flash",
536
- "priority": 40,
537
- "when": ["baseContract", "separateShapeOk", "biasOk", "not present.attentionBiasT", "clusterOk", "clusterSubgroupsOk"],
538
- "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" },
539
- "passes": [
540
- {
541
- "id": "main",
542
- "name": "PackedMultiHeadAttention.Cluster",
543
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
544
- "bindings": ["query4", "key4", "value4", "bias", "tokenOffset", "cumSeqLen", "output4", "params"],
545
- "dispatch": {
546
- "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)",
547
- "y": "numHeads",
548
- "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)"
549
- }
550
- }
551
- ],
552
- "requires": { "features": ["subgroups"] },
553
- "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"]
554
- },
555
- {
556
- "id": "separate_bias_flash_nosg",
557
- "priority": 20,
558
- "when": ["baseContract", "separateShapeOk", "biasOk", "not present.attentionBiasT", "clusterPortableOk"],
559
- "derive": {
560
- "useSubgroups": false,
561
- "LPQ": "portableLpq if clusterUseDistributed else clusterLpq",
562
- "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ",
563
- "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK",
564
- "distributedSoftmax": "clusterUseDistributed"
565
- },
566
- "passes": [
567
- {
568
- "id": "main",
569
- "name": "PackedMultiHeadAttention.Cluster",
570
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
571
- "bindings": ["query4", "key4", "value4", "bias", "tokenOffset", "cumSeqLen", "output4", "params"],
572
- "dispatch": {
573
- "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)",
574
- "y": "numHeads",
575
- "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)"
576
- }
577
- }
578
- ],
579
- "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"]
580
- },
581
- {
582
- "id": "separate_bias_serial",
583
- "priority": 0,
584
- "when": ["baseContract", "separateShapeOk", "biasOk", "not present.attentionBiasT", "scalarOk"],
585
- "derive": { "workgroupSize": "scalarWg" },
586
- "passes": [
587
- {
588
- "id": "main",
589
- "name": "PackedMultiHeadAttention.Serial",
590
- "shader": "attn-packed-varlen-scalar.wgsl.jinja",
591
- "bindings": ["query", "key", "value", "bias", "tokenOffset", "cumSeqLen", "output", "params"],
592
- "dispatch": {
593
- "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)",
594
- "y": "numHeads",
595
- "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)"
596
- }
597
- }
598
- ]
599
- },
600
- {
601
- "id": "separate_bias_attn_bias_flash",
602
- "priority": 40,
603
- "when": ["baseContract", "separateShapeOk", "biasOk", "attnBiasOk", "clusterOk", "clusterSubgroupsOk"],
604
- "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" },
605
- "passes": [
606
- {
607
- "id": "main",
608
- "name": "PackedMultiHeadAttention.Cluster",
609
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
610
- "bindings": ["query4", "key4", "value4", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"],
611
- "dispatch": {
612
- "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)",
613
- "y": "numHeads",
614
- "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)"
615
- }
616
- }
617
- ],
618
- "requires": { "features": ["subgroups"] },
619
- "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"]
620
- },
621
- {
622
- "id": "separate_bias_attn_bias_flash_nosg",
623
- "priority": 20,
624
- "when": ["baseContract", "separateShapeOk", "biasOk", "attnBiasOk", "clusterPortableOk"],
625
- "derive": {
626
- "useSubgroups": false,
627
- "LPQ": "portableLpq if clusterUseDistributed else clusterLpq",
628
- "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ",
629
- "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK",
630
- "distributedSoftmax": "clusterUseDistributed"
631
- },
632
- "passes": [
633
- {
634
- "id": "main",
635
- "name": "PackedMultiHeadAttention.Cluster",
636
- "shader": "attn-packed-varlen-cluster.wgsl.jinja",
637
- "bindings": ["query4", "key4", "value4", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"],
638
- "dispatch": {
639
- "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)",
640
- "y": "numHeads",
641
- "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)"
642
- }
643
- }
644
- ],
645
- "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"]
646
- },
647
- {
648
- "id": "separate_bias_attn_bias_serial",
649
- "priority": 0,
650
- "when": ["baseContract", "separateShapeOk", "biasOk", "attnBiasOk", "scalarOk"],
651
- "derive": { "workgroupSize": "scalarWg" },
652
- "passes": [
653
- {
654
- "id": "main",
655
- "name": "PackedMultiHeadAttention.Serial",
656
- "shader": "attn-packed-varlen-scalar.wgsl.jinja",
657
- "bindings": ["query", "key", "value", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output", "paramsMask"],
658
- "dispatch": {
659
- "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)",
660
- "y": "numHeads",
661
- "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)"
662
- }
663
- }
664
- ]
665
- }
666
- ]
667
- }
 
1
+ {"domain":"com.microsoft","name":"PackedMultiHeadAttention","sinceVersion":1,"inputs":{"queryT":{"onnx":"query","dtype":"T"},"keyT":{"onnx":"key","dtype":"T","rank":2,"optional":true},"valueT":{"onnx":"value","dtype":"T","rank":2,"optional":true},"biasT":{"onnx":"bias","dtype":"T","rank":1,"optional":true},"tokenOffsetT":{"onnx":"token_offset","dtype":"M","rank":2,"storage":"int32"},"cumulativeSequenceLengthT":{"onnx":"cumulative_sequence_length","dtype":"M","rank":1,"storage":"int32"},"attentionBiasT":{"onnx":"attention_bias","dtype":"T","rank":4,"optional":true}},"outputs":{"outputT":{"onnx":"output","dtype":"T","rank":2,"shape":"[tokenCount, vHiddenSize]"}},"attributes":{"num_heads":{},"scale":{}},"attributeConstraints":{"num_heads":{"required":true}},"typeConstraints":{"T":["float32","float16"],"M":["int32"]},"tunables":{"CLUSTER_TILE_K":{"default":16},"SCALAR_WORKGROUP_SIZE":{"default":64}},"derive":{"numHeads":"attrs.num_heads","qNumHeads":"numHeads","packedQkv":"ranks.queryT == 4","tokenCount":"dim(shapes.queryT, 0)","batchSize":"dim(shapes.tokenOffsetT, 0) if ranks.tokenOffsetT == 2 else 0","seqPad":"dim(shapes.tokenOffsetT, 1) if ranks.tokenOffsetT == 2 else 0","packedHeadDim":"dim(shapes.queryT, 3) if packedQkv else 0","hiddenSize":"numHeads * packedHeadDim if packedQkv else (dim(shapes.queryT, 1) if ranks.queryT == 2 else 0)","vHiddenSize":"hiddenSize if packedQkv else (dim(shapes.valueT, 1) if present.valueT and ranks.valueT == 2 else 0)","headDim":"hiddenSize / numHeads if numHeads > 0 and hiddenSize % numHeads == 0 else 0","vHeadDim":"vHiddenSize / numHeads if numHeads > 0 and vHiddenSize % numHeads == 0 else 0","attentionScale":"attrs.scale if has(attrs, \"scale\") else 0","qRowStride":"numHeads * 3 * headDim if packedQkv else hiddenSize","qHeadStride":"3 * headDim if packedQkv else headDim","kRowStride":"qRowStride if packedQkv else hiddenSize","kHeadStride":"qHeadStride if packedQkv else headDim","kOffset":"headDim if packedQkv else 0","vRowStride":"qRowStride if packedQkv else vHiddenSize","vHeadStride":"qHeadStride if packedQkv else vHeadDim","vOffset":"2 * headDim if packedQkv else 0","oRowStride":"vHiddenSize","oHeadStride":"vHeadDim","biasKOffset":"hiddenSize","biasVOffset":"2 * hiddenSize","attnBiasHeads":"dim(shapes.attentionBiasT, 1) if present.attentionBiasT and ranks.attentionBiasT == 4 else 0","maskSeqStride":"seqPad","maskHeadStride":"0 if attnBiasHeads == 1 else seqPad * seqPad","maskBatchStride":"0 if (not present.attentionBiasT) or ranks.attentionBiasT != 4 or dim(shapes.attentionBiasT, 0) == 1 else attnBiasHeads * seqPad * seqPad","dtypeOk":"tensorDtypes.outputT == tensorDtypes.queryT and (tensorDtypes.queryT == \"float32\" or tensorDtypes.queryT == \"float16\") and f16Ok(dtypes.T)","packedShapeOk":"packedQkv and not present.keyT and not present.valueT and dim(shapes.queryT, 1) == numHeads and dim(shapes.queryT, 2) == 3 and packedHeadDim > 0","separateShapeOk":"ranks.queryT == 2 and present.keyT and present.valueT and ranks.keyT == 2 and ranks.valueT == 2 and sameShape(shapes.keyT, shapes.queryT) and dim(shapes.valueT, 0) == tokenCount and tensorDtypes.keyT == tensorDtypes.queryT and tensorDtypes.valueT == tensorDtypes.queryT","scheduleOk":"ranks.tokenOffsetT == 2 and ranks.cumulativeSequenceLengthT == 1 and dim(shapes.cumulativeSequenceLengthT, 0) == batchSize + 1 and batchSize > 0 and seqPad > 0 and numel(shapes.tokenOffsetT) >= tokenCount and tokenCount <= 2147483647","outputShapeOk":"ranks.outputT == 2 and dim(shapes.outputT, 0) == tokenCount and dim(shapes.outputT, 1) == vHiddenSize","biasOk":"present.biasT and ranks.biasT == 1 and dim(shapes.biasT, 0) == 2 * hiddenSize + vHiddenSize and tensorDtypes.biasT == tensorDtypes.queryT","attnBiasOk":"present.attentionBiasT and ranks.attentionBiasT == 4 and (dim(shapes.attentionBiasT, 0) == 1 or dim(shapes.attentionBiasT, 0) == batchSize) and (attnBiasHeads == 1 or attnBiasHeads == numHeads) and dim(shapes.attentionBiasT, 2) == seqPad and dim(shapes.attentionBiasT, 3) == seqPad and tensorDtypes.attentionBiasT == tensorDtypes.queryT","hasBias":"present.biasT","hasAttnBias":"present.attentionBiasT","baseContract":"dtypeOk and scheduleOk and outputShapeOk and numHeads > 0 and headDim > 0 and vHeadDim > 0 and tokenCount > 0 and (packedShapeOk or separateShapeOk)","usesF16":"tensorDtypes.queryT == \"float16\"","scalar":"\"f16\" if usesF16 else \"f32\"","outputScalar":"scalar","inputVec4":"\"vec4<f16>\" if usesF16 else \"vec4<f32>\"","qkvBytes":"2 if usesF16 else 4","packedStageBytes":"4 if usesF16 and present.biasT and vHeadDim != headDim else qkvBytes","clusterWidthAligned":"headDim % 16 == 0 and vHeadDim % 4 == 0","nvidiaAdapter":"has(device.adapterInfo, \"vendor\") and device.adapterInfo.vendor == \"nvidia\"","adreno6xxAdapter":"has(device.adapterInfo, \"architecture\") and device.adapterInfo.architecture == \"adreno-6xx\"","headDimV4":"headDim / 4","qRowStrideV4":"qRowStride / 4","qHeadStrideV4":"qHeadStride / 4","kRowStrideV4":"kRowStride / 4","kHeadStrideV4":"kHeadStride / 4","kOffsetV4":"kOffset / 4","vRowStrideV4":"vRowStride / 4","vHeadStrideV4":"vHeadStride / 4","vOffsetV4":"vOffset / 4","oRowStrideV4":"oRowStride / 4","oHeadStrideV4":"oHeadStride / 4","scalarWg":"tunables.SCALAR_WORKGROUP_SIZE","scalarBytes":"4 * scalarWg + 4 * vHeadDim + 12","scalarOk":"scalarWg <= device.limits.maxComputeInvocationsPerWorkgroup and scalarWg <= device.limits.maxComputeWorkgroupSizeX and scalarBytes <= device.limits.maxComputeWorkgroupStorageSize and numHeads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","clusterTileQ":"min(16, pow2ceil(tokenCount)) if vHeadDim != headDim else 16","clusterBaseLpq":"8 if headDim % 32 == 0 else 4","clusterTileK":"min(tunables.CLUSTER_TILE_K, pow2ceil(tokenCount)) if vHeadDim != headDim else tunables.CLUSTER_TILE_K","clusterTileBytes":"clusterTileK * (headDim + vHeadDim) * packedStageBytes","clusterLaneTarget":"min(32, max(clusterBaseLpq, pow2ceil(headDim / 16)), device.adapterInfo.subgroupMinSize, pow2ceil(floor(min(device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX) / clusterTileQ) + 1) / 2) if vHeadDim == headDim and clusterWidthAligned and clusterTileBytes <= device.limits.maxComputeWorkgroupStorageSize and device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and device.adapterInfo.subgroupMinSize >= clusterBaseLpq else clusterBaseLpq","clusterLpq":"clusterLaneTarget if ceilDiv(headDim, 4 * clusterBaseLpq) >= 2 * ceilDiv(headDim, 4 * clusterLaneTarget) else clusterBaseLpq","clusterWg":"clusterTileQ * clusterLpq","clusterNosgBytes":"clusterTileBytes + 4 * clusterWg","clusterTiles":"ceilDiv(tokenCount, clusterTileQ)","clusterShapeOk":"clusterWidthAligned and clusterWg <= device.limits.maxComputeInvocationsPerWorkgroup and clusterWg <= device.limits.maxComputeWorkgroupSizeX and numHeads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","clusterOk":"clusterShapeOk and clusterTileBytes + 4 * clusterWg + 8 <= device.limits.maxComputeWorkgroupStorageSize","clusterNosgOk":"clusterShapeOk and clusterNosgBytes <= device.limits.maxComputeWorkgroupStorageSize","clusterSubgroupsOk":"has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize >= clusterLpq and device.adapterInfo.subgroupMinSize % clusterLpq == 0 and device.adapterInfo.subgroupMaxSize >= device.adapterInfo.subgroupMinSize and device.adapterInfo.subgroupMaxSize % clusterLpq == 0 and not adreno6xxAdapter","portableLaneTarget":"min(64, pow2ceil(max(headDimV4, vHeadDim / 4) / 4), device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX)","portableLpq":"max(clusterLpq, pow2ceil(portableLaneTarget + 1) / 2) if vHeadDim != headDim else (64 if portableLaneTarget >= 64 and headDimV4 % 64 == 0 else (32 if portableLaneTarget >= 32 and headDimV4 % 32 == 0 else (16 if portableLaneTarget >= 16 and headDimV4 % 16 == 0 else clusterLpq)))","portableTileQ":"min(clusterTileQ, pow2ceil(tokenCount), max(1, floor(min(clusterWg, device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX) / portableLpq)))","portableWg":"portableTileQ * portableLpq","portableKeyCapacity":"max(1, floor(device.limits.maxComputeWorkgroupStorageSize / ((headDim + vHeadDim) * packedStageBytes + 4 * portableWg)))","portableTileK":"min(clusterTileK, pow2ceil(tokenCount), pow2ceil(portableKeyCapacity + 1) / 2)","clusterDistributedBytes":"portableTileK * (headDim + vHeadDim) * packedStageBytes + 4 * max(portableWg * portableTileK, 2 * portableWg + portableTileQ * portableTileK)","clusterDistributedOk":"clusterDistributedBytes <= device.limits.maxComputeWorkgroupStorageSize","clusterUseDistributed":"clusterDistributedOk and (clusterLpq > 4 or vHeadDim != headDim)","portableTiles":"ceilDiv(tokenCount, portableTileQ if clusterUseDistributed else clusterTileQ)","clusterPortableOk":"clusterShapeOk and (clusterUseDistributed or clusterNosgOk) and portableWg <= device.limits.maxComputeInvocationsPerWorkgroup and portableWg <= device.limits.maxComputeWorkgroupSizeX and ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","clusterDistributedPreferred":"vHeadDim == headDim and clusterUseDistributed and clusterPortableOk and clusterTiles * numHeads < 32 and (not usesF16 or (clusterDistributedBytes <= clusterTileBytes + 4 * clusterWg + 8 and clusterTiles * numHeads < 16)) and (present.attentionBiasT or headDimV4 > clusterLpq or clusterTiles == 1)","blackwellAdapter":"nvidiaAdapter and has(device.adapterInfo, \"architecture\") and device.adapterInfo.architecture == \"blackwell\"","storageLimitedF32":"blackwellAdapter and not usesF16 and vHeadDim == headDim and not clusterNosgOk","wideLanes":"min(portableWg, pow2ceil(portableLaneTarget + 1) / 2)","wideTileQ":"portableWg / wideLanes","wideQueryTiles":"ceilDiv(tokenCount, wideTileQ)","valueSlicesNeedLanes":"wideLanes > portableLpq and headDimV4 > portableLpq * portableTileK","spreadValueSlices":"storageLimitedF32 and valueSlicesNeedLanes and ceilDiv(wideQueryTiles, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","portableQueryTiles":"wideQueryTiles if spreadValueSlices else portableTiles","resourceDistributedShapeOk":"clusterLpq == 4 and portableLpq == clusterLpq and headDimV4 > clusterLpq","resourceDistributedStorageOk":"clusterShapeOk and clusterDistributedOk and portableTileK >= 1 and portableTileK == floor(portableTileK)","resourceDistributedOk":"storageLimitedF32 and resourceDistributedShapeOk and resourceDistributedStorageOk"},"when":["baseContract","biasOk or not hasBias","attnBiasOk or not hasAttnBias"],"bindings":{"query":{"arg":"queryT","name":"query"},"key":{"arg":"keyT","name":"key","when":"present.keyT"},"value":{"arg":"valueT","name":"value","when":"present.valueT"},"bias":{"arg":"biasT","name":"bias","when":"hasBias"},"tokenOffset":{"arg":"tokenOffsetT","name":"token_offset"},"cumSeqLen":{"arg":"cumulativeSequenceLengthT","name":"cumulative_sequence_length"},"attnBias":{"arg":"attentionBiasT","name":"attn_bias","when":"hasAttnBias"},"output":{"arg":"outputT","name":"output"},"query4":{"arg":"queryT","name":"query","elementType":"$inputVec4"},"key4":{"arg":"keyT","name":"key","elementType":"$inputVec4","when":"present.keyT"},"value4":{"arg":"valueT","name":"value","elementType":"$inputVec4","when":"present.valueT"},"output4":{"arg":"outputT","name":"output","elementType":"$inputVec4"},"params":{"name":"params","struct":[{"name":"tokenCount","type":"u32","value":"tokenCount"},{"name":"seqPad","type":"u32","value":"seqPad"},{"name":"scale","type":"f32","value":"attentionScale"}],"when":"not hasAttnBias"},"paramsMask":{"name":"params","struct":[{"name":"tokenCount","type":"u32","value":"tokenCount"},{"name":"seqPad","type":"u32","value":"seqPad"},{"name":"scale","type":"f32","value":"attentionScale"},{"name":"maskBatchStride","type":"u32","value":"maskBatchStride"},{"name":"maskHeadStride","type":"u32","value":"maskHeadStride"},{"name":"maskSeqStride","type":"u32","value":"maskSeqStride"}],"when":"hasAttnBias"}},"variants":[{"id":"flash","priority":40,"when":["clusterOk","clusterSubgroupsOk"],"derive":{"useSubgroups":true,"LPQ":"clusterLpq","TILE_Q":"clusterTileQ","TILE_K":"clusterTileK"},"passes":[{"id":"main","name":"PackedMultiHeadAttention.Cluster","shader":"attn-packed-varlen-cluster.wgsl.jinja","bindings":["query4","key4","value4","bias","tokenOffset","cumSeqLen","attnBias","output4","params","paramsMask"],"dispatch":{"x":"min(clusterTiles, DISPATCH_FOLD_WIDTH)","y":"numHeads","z":"ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)"}}],"requires":{"features":["subgroups"]},"demoteWhen":["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))","clusterDistributedPreferred","vHeadDim == headDim and clusterPortableOk and device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize == 16 and device.adapterInfo.subgroupMaxSize == 32 and 2 * clusterTileBytes >= device.limits.maxComputeWorkgroupStorageSize and (clusterLpq == clusterBaseLpq or tokenCount >= clusterTileQ * clusterLpq) and (not usesF16 or tokenCount >= clusterTileQ * clusterLpq) and (not usesF16 or (clusterUseDistributed and clusterDistributedBytes + packedStageBytes * portableWg * portableTileK <= clusterTileBytes + 4 * clusterWg + 8))"]},{"id":"flash_nosg","priority":20,"when":["clusterPortableOk or resourceDistributedOk"],"derive":{"resourceDistributed":"not clusterPortableOk or spreadValueSlices","useSubgroups":false,"distributedSoftmax":"clusterUseDistributed or resourceDistributed","LPQ":"wideLanes if spreadValueSlices else (portableLpq if distributedSoftmax else clusterLpq)","TILE_Q":"wideTileQ if spreadValueSlices else (portableTileQ if distributedSoftmax else clusterTileQ)","TILE_K":"portableTileK if distributedSoftmax else clusterTileK"},"passes":[{"id":"main","name":"PackedMultiHeadAttention.Cluster","shader":"attn-packed-varlen-cluster.wgsl.jinja","bindings":["query4","key4","value4","bias","tokenOffset","cumSeqLen","attnBias","output4","params","paramsMask"],"dispatch":{"x":"min(portableQueryTiles, DISPATCH_FOLD_WIDTH)","y":"numHeads","z":"ceilDiv(portableQueryTiles, DISPATCH_FOLD_WIDTH)"}}],"demoteWhen":["vHeadDim != headDim and tokenCount < clusterLpq"]},{"id":"serial","priority":0,"when":["scalarOk"],"derive":{"workgroupSize":"scalarWg"},"passes":[{"id":"main","name":"PackedMultiHeadAttention.Serial","shader":"attn-packed-varlen-scalar.wgsl.jinja","bindings":["query","key","value","bias","tokenOffset","cumSeqLen","attnBias","output","params","paramsMask"],"dispatch":{"x":"min(tokenCount, DISPATCH_FOLD_WIDTH)","y":"numHeads","z":"ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)"}}]}]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/webgpu/metadata.json CHANGED
@@ -1,47 +1 @@
1
- {
2
- "name": "com.microsoft.PackedMultiHeadAttention",
3
- "id": "_com_microsoft_packedmultiheadattention_webgpu_96b8ba0",
4
- "version": 1,
5
- "license": "Apache-2.0",
6
- "backend": { "type": "webgpu" },
7
- "digest": {
8
- "algorithm": "sha256",
9
- "files": {
10
- "attn-packed-varlen-cluster.wgsl.jinja": "p9O8Y9FODuK+3sS5XCmt34ubccsQ1rHO8KyYdKFbox8=",
11
- "attn-packed-varlen-scalar.wgsl.jinja": "6gm8Q90Uq/Fwm53KBabaxD39SZDE/XPt93lhHeOKEKo=",
12
- "bench.json": "QU1tbtEXCd2xke0vrPrixj1rlwWltGZXLr8StqGlVuM=",
13
- "manifest.json": "CImYmm6QB0MSplEddT1DpForRg78IeIsHWzBijr+yks=",
14
- "test.json": "Y3VjrtppOZI+cmCpPGhsEdWnF8qd981T9VIMTNux648="
15
- }
16
- },
17
- "provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },
18
- "webgpu": {
19
- "manifestSpec": "2.1",
20
- "variants": {
21
- "packed_flash": ["attn-packed-varlen-cluster.wgsl.jinja"],
22
- "packed_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"],
23
- "packed_serial": ["attn-packed-varlen-scalar.wgsl.jinja"],
24
- "packed_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"],
25
- "packed_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"],
26
- "packed_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"],
27
- "packed_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"],
28
- "packed_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"],
29
- "packed_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"],
30
- "packed_bias_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"],
31
- "packed_bias_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"],
32
- "packed_bias_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"],
33
- "separate_flash": ["attn-packed-varlen-cluster.wgsl.jinja"],
34
- "separate_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"],
35
- "separate_serial": ["attn-packed-varlen-scalar.wgsl.jinja"],
36
- "separate_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"],
37
- "separate_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"],
38
- "separate_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"],
39
- "separate_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"],
40
- "separate_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"],
41
- "separate_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"],
42
- "separate_bias_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"],
43
- "separate_bias_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"],
44
- "separate_bias_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"]
45
- }
46
- }
47
- }
 
1
+ {"name":"com.microsoft.PackedMultiHeadAttention","id":"_com_microsoft_packedmultiheadattention_webgpu_17a5f5c","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"attn-packed-varlen-cluster.wgsl.jinja":"uy6sVyGKPRfrloKCXZfcTcQDqjbaQAO07P/KMOPyOP4=","attn-packed-varlen-scalar.wgsl.jinja":"uV47zEaYCCHM8wGvHrctI8XIyMtEI072DMw4eKCp62k=","bench.json":"MiMPAxLiavb6A+R4tkJFaDfoEa85U0gqggFHVGCrWH4=","manifest.json":"SmdtEioZt9Ysg6ybDSMCgwVTH7XqpfdqcvJc9tQJVao=","test.json":"RggkJ/lGkIPqjHBx2YP7j0NKdzyNEQDhhR1JlGUEDos="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/webgpu/test.json CHANGED
The diff for this file is too large to render. See raw diff