Xenova HF Staff commited on
Commit
6325848
·
verified ·
1 Parent(s): d882115

sync 4385228f788d

Browse files
README.md CHANGED
@@ -12,10 +12,17 @@ tags:
12
 
13
  ## Description
14
 
15
- Single-token decode attention, self and cross, excluding the QKV projection. Cross attention reads whole encoder key and value tensors; self attention appends this token to a capacity-sized cache whose live length arrives in `past_sequence_length`. The mask is additive: a zero entry adds `mask_filter_value` rather than removing the key. The optional `qk` output is the scaled score row before the softmax, and is produced for cross attention only.
16
 
17
  See the [ONNX Runtime `DecoderMaskedMultiHeadAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.DecoderMaskedMultiHeadAttention) for the reference semantics.
18
 
 
 
 
 
 
 
 
19
  ## Inputs
20
 
21
  | Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |
@@ -47,7 +54,7 @@ Attributes and default values (overridable per request):
47
  | `mask_filter_value` | `-10000` | Value added to the score of a key whose mask entry is zero. |
48
  | `num_heads` | — | Number of attention heads. The head size is the query hidden size divided by this count. |
49
  | `output_qk` | — | Set to 1 to emit the pre-softmax `qk` output. It must agree with whether the caller supplies that output. |
50
- | `past_present_share_buffer` | — | Set to 1 when the past and present caches are one capacity-sized buffer. Self attention requires it; cross attention has no cache and leaves it at 0. |
51
  | `scale` | — | Multiplier applied to `Q * K^T`. Omitted or zero selects the default `1 / sqrt(head_size)`. |
52
 
53
  ## Type constraints
@@ -62,46 +69,62 @@ Attributes and default values (overridable per request):
62
 
63
  One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
64
 
65
- - `cross_direct` — A single key partition writes normalized attention directly, removing partial buffers and the merge dispatch while preserving masks and diagnostic-score outputs.
66
- - `cross_qk_direct` — A single key partition writes normalized attention directly, removing partial buffers and the merge dispatch while preserving masks and diagnostic-score outputs.
67
- - `cross_mask_direct` — A single key partition writes normalized attention directly, removing partial buffers and the merge dispatch while preserving masks and diagnostic-score outputs.
68
- - `cross_mask_qk_direct` — A single key partition writes normalized attention directly, removing partial buffers and the merge dispatch while preserving masks and diagnostic-score outputs.
69
- - `cross_nosg_direct` — A single key partition writes normalized attention directly, removing partial buffers and the merge dispatch while preserving masks and diagnostic-score outputs.
70
- - `cross_qk_nosg_direct` — A single key partition writes normalized attention directly, removing partial buffers and the merge dispatch while preserving masks and diagnostic-score outputs.
71
- - `cross_mask_nosg_direct` — A single key partition writes normalized attention directly, removing partial buffers and the merge dispatch while preserving masks and diagnostic-score outputs.
72
- - `cross_mask_qk_nosg_direct` — A single key partition writes normalized attention directly, removing partial buffers and the merge dispatch while preserving masks and diagnostic-score outputs.
73
 
74
  ## Device requirements
75
 
76
- Some implementation variants require `subgroups`. These are route-specific capabilities, not package-wide requirements; availability also depends on the request shape and dtype.
77
 
78
  ## Files
79
 
80
- - [`metadata.json`](build/webgpu/metadata.json) — kernel metadata (id, digests, per-variant templates, provenance)
81
- - [`manifest.json`](build/webgpu/manifest.json) — the op contract (source of truth)
82
- - [`test.json`](build/webgpu/test.json) — correctness cases
83
- - [`bench.json`](build/webgpu/bench.json) — benchmark cases
84
- - [`attn-flash-decode-splitk-merge.wgsl.jinja`](build/webgpu/attn-flash-decode-splitk-merge.wgsl.jinja)
85
- - [`attn-flash-decode-splitk.wgsl.jinja`](build/webgpu/attn-flash-decode-splitk.wgsl.jinja)
86
- - [`dmmha-present.wgsl.jinja`](build/webgpu/dmmha-present.wgsl.jinja)
87
 
88
  ## Use with `@huggingface/kernels`
89
 
90
  ```sh
91
- npm install --save-exact @huggingface/kernels@0.0.1-preview.3
92
  ```
93
 
 
 
94
  Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
95
 
96
  The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
97
  It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
98
 
99
- Replace each `*Data` placeholder with a typed array containing the corresponding input data.
100
-
101
  ```js
102
  import { getKernel } from "@huggingface/kernels";
103
 
104
  const kernel = await getKernel("webgpu-kernels/com.microsoft.DecoderMaskedMultiHeadAttention", { version: 1 });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  const { outputT } = await kernel({
106
  queryT: { data: queryTData, shape: [1, 1, 32] },
107
  keyT: { data: keyTData, shape: [1, 2, 1, 16] },
@@ -109,4 +132,5 @@ const { outputT } = await kernel({
109
  }, {
110
  attrs: { num_heads: 2 },
111
  });
 
112
  ```
 
12
 
13
  ## Description
14
 
15
+ Single-token self/cross decode attention without QKV projection. Cross attention reads encoder K/V; self attention appends to a cache allocated at `max_sequence_length`, of which `past_sequence_length` rows are filled. Zero mask entries add `mask_filter_value`. Cross attention can return scaled pre-softmax `qk`. Negative lengths yield an empty attention range and skip the append; lengths above the capacity are clamped to it. Lengths are range-checked as signed values before use as counts.
16
 
17
  See the [ONNX Runtime `DecoderMaskedMultiHeadAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.DecoderMaskedMultiHeadAttention) for the reference semantics.
18
 
19
+ ## Differences from the ONNX Runtime spec
20
+
21
+ - Input `beam_width`: Beam-search decoding is not implemented; the beam width is always one.
22
+ - Input `cache_indirection`: The per-position beam remap belongs to beam-search decoding, which is not implemented.
23
+ - Input `bias`: The packed Q/K/V projection bias is not implemented; fold it into the preceding projection, as decoder exports that emit this operator do.
24
+ - Input `keyT` (ONNX `key`), input `valueT` (ONNX `value`): Explicit key and value tensors are required; packed QKV input is not supported.
25
+
26
  ## Inputs
27
 
28
  | Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |
 
54
  | `mask_filter_value` | `-10000` | Value added to the score of a key whose mask entry is zero. |
55
  | `num_heads` | — | Number of attention heads. The head size is the query hidden size divided by this count. |
56
  | `output_qk` | — | Set to 1 to emit the pre-softmax `qk` output. It must agree with whether the caller supplies that output. |
57
+ | `past_present_share_buffer` | — | Set to 1 when the past and present caches are one buffer allocated at `max_sequence_length`. Self attention requires it; cross attention has no cache and leaves it at 0. |
58
  | `scale` | — | Multiplier applied to `Q * K^T`. Omitted or zero selects the default `1 / sqrt(head_size)`. |
59
 
60
  ## Type constraints
 
69
 
70
  One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
71
 
72
+ - `cross_direct`, `cross_nosg_direct` — A single key partition writes normalized attention directly, removing partial buffers and the merge dispatch while preserving masks and diagnostic-score outputs.
 
 
 
 
 
 
 
73
 
74
  ## Device requirements
75
 
76
+ Some implementation variants require `subgroups`. Other variants run without it; which variant runs also depends on the request's shapes and dtypes.
77
 
78
  ## Files
79
 
80
+ - [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.DecoderMaskedMultiHeadAttention/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)
81
+ - [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.DecoderMaskedMultiHeadAttention/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)
82
+ - [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.DecoderMaskedMultiHeadAttention/blob/v1/build/webgpu/test.json) — correctness cases
83
+ - [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.DecoderMaskedMultiHeadAttention/blob/v1/build/webgpu/bench.json) — benchmark cases
84
+ - [`attn-flash-decode-splitk-merge.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.DecoderMaskedMultiHeadAttention/blob/v1/build/webgpu/attn-flash-decode-splitk-merge.wgsl.jinja)
85
+ - [`attn-flash-decode-splitk.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.DecoderMaskedMultiHeadAttention/blob/v1/build/webgpu/attn-flash-decode-splitk.wgsl.jinja)
86
+ - [`dmmha-present.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.DecoderMaskedMultiHeadAttention/blob/v1/build/webgpu/dmmha-present.wgsl.jinja)
87
 
88
  ## Use with `@huggingface/kernels`
89
 
90
  ```sh
91
+ npm install --save-exact @huggingface/kernels@0.0.1-preview.4
92
  ```
93
 
94
+ Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.
95
+
96
  Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
97
 
98
  The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
99
  It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
100
 
 
 
101
  ```js
102
  import { getKernel } from "@huggingface/kernels";
103
 
104
  const kernel = await getKernel("webgpu-kernels/com.microsoft.DecoderMaskedMultiHeadAttention", { version: 1 });
105
+
106
+ const queryTData = Float32Array.of(
107
+ 0.17091933, 0.16533019, 0.15063293, 0.1313149, 0.11202312, 0.097040445, 0.08980678,
108
+ 0.092533216, 0.10594729, 0.12919523, 0.15991104, 0.19444641, 0.22823927, 0.25628528,
109
+ 0.2736664, 0.2760843, 0.2603464, 0.2247556, 0.16936424, 0.09606541, 0.008510161,
110
+ -0.08814437, -0.18763463, -0.28310272, -0.3676744, -0.43505034, -0.48005563,
111
+ -0.49909735, -0.49048677, -0.4545969, -0.3938397, -0.31246522,
112
+ );
113
+ const keyTData = Float32Array.of(
114
+ 0.18795393, 0.18723874, 0.17931889, 0.16589965, 0.14892825, 0.13047631, 0.11261654,
115
+ 0.09730019, 0.08624214, 0.08081959, 0.08198991, 0.09023206, 0.10551491, 0.12729393,
116
+ 0.1545368, 0.1857763, 0.21918805, 0.25268874, 0.28404972, 0.3110201, 0.33145243,
117
+ 0.3434246, 0.3453513, 0.33607924, 0.31496024, 0.28189945, 0.23737474, 0.18242685,
118
+ 0.11862041, 0.04797748, -0.027112655, -0.104003295,
119
+ );
120
+ const valueTData = Float32Array.of(
121
+ 0.7881646, 0.7279641, 0.66986233, 0.6268161, 0.609237, 0.6232503, 0.66966325,
122
+ 0.74381626, 0.83634037, 0.93469596, 1.0252374, 1.0954623, 1.1360711, 1.1424973,
123
+ 1.1156542, 1.0617731, 0.9913622, 0.917457, 0.8534525, 0.81087774, 0.79748005,
124
+ 0.81593734, 0.8634123, 0.9320213, 1.0101415, 1.0843385, 1.1415955, 1.1714747, 1.167852,
125
+ 1.1299378, 1.0624146, 0.97466904,
126
+ );
127
+
128
  const { outputT } = await kernel({
129
  queryT: { data: queryTData, shape: [1, 1, 32] },
130
  keyT: { data: keyTData, shape: [1, 2, 1, 16] },
 
132
  }, {
133
  attrs: { num_heads: 2 },
134
  });
135
+ console.log({ outputT });
136
  ```
build/webgpu/attn-flash-decode-splitk-merge.wgsl.jinja CHANGED
@@ -1,16 +1,24 @@
1
  {% if splitQueries is not defined %}{% set splitQueries = false %}{% endif %}
2
  {% set qSeq = 0 %}
 
3
  {{ env.wgsl.resourceDeclarations }}
4
 
 
 
 
 
5
  // Split-K flash decode, pass 2 of 2. Combines the per-split un-normalized online
6
  // states (max, denom, weighted V sum) written by the split pass into the final
7
  // attention output for each query token, using the online softmax merge:
8
  // globalMax = max_s partialMax[s]
9
  // globalDen = sum_s partialDenom[s] * exp(partialMax[s] - globalMax)
10
  // out[d] = (sum_s partialOut[s, d] * exp(partialMax[s] - globalMax)) / globalDen
11
- // One workgroup per (batch, head); one thread per output vec4 channel. The
12
- // per-split (max, denom) scan is tiny (NUM_SPLITS is small), so every thread
13
- // recomputes it locally and keeps the merge state in registers.
 
 
 
14
  // Output layout: rank-4 [batch, heads, seq, headDim], matching the split pass.
15
  const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;
16
  const Q_HEADS: u32 = {{ qNumHeads }}u;
@@ -41,7 +49,440 @@ fn shifted_value(value: f32, maxValue: f32) -> f32 {
41
  fn exp_shift(value: f32, maxValue: f32) -> f32 {
42
  return exp(shifted_value(value, maxValue));
43
  }
44
- @compute @workgroup_size(HEAD_DIM_V4, 1, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  fn main(
46
  @builtin(workgroup_id) wg: vec3<u32>,
47
  @builtin(local_invocation_id) lid: vec3<u32>
@@ -51,8 +492,15 @@ fn main(
51
  {% endif %}
52
  let h = wg.y;
53
  let b = wg.z;
 
 
 
 
54
  let d4 = lid.x;
55
- if (h >= Q_HEADS || d4 >= HEAD_DIM_V4{% if splitQueries %} || queryToken >= Q_SEQ{% endif %}) {
 
 
 
56
  return;
57
  }
58
 
@@ -61,23 +509,84 @@ fn main(
61
  {% else %}
62
  let mdBase = (b * Q_HEADS + h) * NUM_SPLITS;
63
  {% endif %}
 
 
 
 
 
 
 
64
  var globalMax = -FLT_MAX;
65
  for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {
66
- globalMax = max(globalMax, partial_stats[mdBase + s].x);
 
 
 
67
  }
 
68
  var globalDenom = 0.0;
 
69
  var outV = vec4<f32>(0.0);
 
70
  for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {
71
- let stats = partial_stats[mdBase + s];
72
- let w = exp_shift(stats.x, globalMax);
73
- globalDenom = globalDenom + stats.y * w;
74
- {% if splitQueries %}
75
- let pBase = (((b * Q_SEQ + queryToken) * Q_HEADS + h) * NUM_SPLITS + s) * HEAD_DIM_V4;
76
- {% else %}
77
- let pBase = ((b * Q_HEADS + h) * NUM_SPLITS + s) * HEAD_DIM_V4;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  {% endif %}
79
- outV = outV + partial_out[pBase + d4] * w;
 
 
 
 
 
80
  }
 
81
 
82
  {% if splitQueries %}
83
  let qBaseV4 = ((b * Q_HEADS + h) * Q_SEQ + queryToken) * HEAD_DIM_V4;
@@ -85,9 +594,9 @@ fn main(
85
  let qBaseV4 = (b * Q_HEADS + h) * HEAD_DIM_V4;
86
  {% endif %}
87
  // A split that covers no keys writes vec2(-FLT_MAX, 0), so when every split is empty —
88
- // a query whose window admits nothing — globalMax stays -FLT_MAX, exp_shift(x, x) is 1,
89
  // and globalDenom lands on exactly 0. Emit 0 rather than dividing so an all-empty
90
  // row has a defined zero result.
91
- var outValue = select(vec4<f32>(0.0), outV / globalDenom, globalDenom > 0.0);
92
  output[qBaseV4 + d4] = vec4<{{ scalar }}>(outValue);
93
  }
 
1
  {% if splitQueries is not defined %}{% set splitQueries = false %}{% endif %}
2
  {% set qSeq = 0 %}
3
+ {% set NORMALIZED_VALUES = normalizedPartialValues | default(false) %}
4
  {{ env.wgsl.resourceDeclarations }}
5
 
6
+ {% if NORMALIZED_VALUES %}
7
+ // Combines normalized partial means using their softmax statistical weights.
8
+ // Raw weighted products retain scaled exponents until the final division.
9
+ {% else %}
10
  // Split-K flash decode, pass 2 of 2. Combines the per-split un-normalized online
11
  // states (max, denom, weighted V sum) written by the split pass into the final
12
  // attention output for each query token, using the online softmax merge:
13
  // globalMax = max_s partialMax[s]
14
  // globalDen = sum_s partialDenom[s] * exp(partialMax[s] - globalMax)
15
  // out[d] = (sum_s partialOut[s, d] * exp(partialMax[s] - globalMax)) / globalDen
16
+ {% endif %}
17
+ // One workgroup per (batch, head), or per (batch, query token, head) when queries are split; one thread per
18
+ // output vec4 channel (per channel and split group when the splits are divided into groups). Each
19
+ // split's (max, denom) is read into workgroup memory once and its scale onto
20
+ // the global max computed once; every thread then sums the denominator in
21
+ // split order and keeps the merge state in registers.
22
  // Output layout: rank-4 [batch, heads, seq, headDim], matching the split pass.
23
  const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;
24
  const Q_HEADS: u32 = {{ qNumHeads }}u;
 
49
  fn exp_shift(value: f32, maxValue: f32) -> f32 {
50
  return exp(shifted_value(value, maxValue));
51
  }
52
+ {% if NORMALIZED_VALUES %}
53
+ {% macro sum_error_function(name, type="f32", protectDifference=false) %}
54
+ {% set bitsType = type | replace("f32", "u32") %}
55
+ // Observing the rounded sum as bits preserves FastTwoSum on backends
56
+ // that otherwise reassociate its subtractions. Both signs of zero contribute zero.
57
+ fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {
58
+ let bits = bitcast<{{ bitsType }}>(x);
59
+ return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));
60
+ }
61
+ fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {
62
+ let swap = abs(a) < abs(b);
63
+ let larger = select(a, b, swap);
64
+ let smaller = select(b, a, swap);
65
+ // Keep the rounded high-part difference observable before subtracting it
66
+ // from the smaller addend. Reassociation here erases the residual.
67
+ return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);
68
+ }
69
+ {% endmacro %}
70
+ {% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}
71
+ {% set N = 1 if type == "f32" else (type[3] | int) %}
72
+ {% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}
73
+ {% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}
74
+ {% set exact = add or rescale or merge %}
75
+ {% set boundNumerator = boundValueNumerator | default(false) %}
76
+ {% if boundNumerator and (exact or tile) %}
77
+ // Even a u32 key count times this magnitude leaves a bit of f32 exponent
78
+ // headroom for a partial sum. Larger terms use the exponent-aware path.
79
+ const VALUE_FAST_LIMIT: f32 = 0x1p94f;
80
+ {% endif %}
81
+ struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }
82
+ struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }
83
+
84
+ {% if exact %}
85
+ fn scaled_value_scalar_zero() -> ScaledValueScalar {
86
+ return ScaledValueScalar(0.0, 0.0, 0);
87
+ }
88
+ {% endif %}
89
+ fn scaled_value_scalar_finite(x: f32) -> bool {
90
+ return abs(x) <= 3.4028234663852886e38;
91
+ }
92
+ {% if exact or align %}
93
+ fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {
94
+ if (a.hi == 0.0) {
95
+ if (a.lo == 0.0) { return -1024; }
96
+ return a.exponent + frexp(a.lo).exp;
97
+ }
98
+ if (!scaled_value_scalar_finite(a.hi)) { return 1024; }
99
+ return a.exponent + frexp(a.hi).exp;
100
+ }
101
+ {% endif %}
102
+ // Scale the significand bits directly. WGSL ldexp may return zero for a
103
+ // shift <= -127 even when its input makes the final result normal; shifts
104
+ // above 128 are indeterminate. Neither limit applies to this exponent sum.
105
+ fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {
106
+ let bits = bitcast<u32>(value);
107
+ let sign = bits & 0x80000000u;
108
+ let fraction = bits & 0x007fffffu;
109
+ let inputExponent = i32((bits >> 23u) & 0xffu);
110
+ if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }
111
+ var significand = fraction | 0x00800000u;
112
+ var exponent = inputExponent + shift;
113
+ if (inputExponent == 0) {
114
+ let normalize = countLeadingZeros(fraction) - 8u;
115
+ significand = fraction << normalize;
116
+ exponent = 1 + shift - i32(normalize);
117
+ }
118
+ if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }
119
+ if (exponent > 0) {
120
+ return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));
121
+ }
122
+ let distance = u32(1 - exponent);
123
+ if (distance > 24u) { return bitcast<f32>(sign); }
124
+ let high = significand >> distance;
125
+ let remainder = significand & ((1u << distance) - 1u);
126
+ let halfway = 1u << (distance - 1u);
127
+ let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);
128
+ return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));
129
+ }
130
+ {% if exact or align %}
131
+ fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {
132
+ if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }
133
+ if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }
134
+ return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);
135
+ }
136
+ {% endif %}
137
+ {% if exact %}
138
+ {% if recoverSum %}
139
+ {{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}
140
+ {% endif %}
141
+ fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {
142
+ let nextHi = fma(hi, 1.0, lo);
143
+ let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};
144
+ if (nextHi == 0.0) { return scaled_value_scalar_zero(); }
145
+ if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }
146
+ let parts = frexp(nextHi);
147
+ let rawExponent = exponent + parts.exp;
148
+ // Ordinary magnitudes return to the unscaled fast path. The margin keeps
149
+ // boundary values away from overflow/underflow while scaling the low word.
150
+ if (rawExponent >= -120 && rawExponent <= 120) {
151
+ return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);
152
+ }
153
+ return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);
154
+ }
155
+ fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {
156
+ let sum = fma(a.hi, 1.0, product);
157
+ let bv = fma(-1.0, a.hi, sum);
158
+ let av = fma(-1.0, bv, sum);
159
+ let ae = fma(-1.0, av, a.hi);
160
+ let be = fma(-1.0, bv, product);
161
+ let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);
162
+ let hi = fma(sum, 1.0, residual);
163
+ return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);
164
+ }
165
+ fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {
166
+ if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||
167
+ !scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||
168
+ !scaled_value_scalar_finite(weight)) {
169
+ return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);
170
+ }
171
+ if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }
172
+ if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }
173
+ if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {
174
+ let product = fma(weight, b.hi, 0.0);
175
+ let lowProduct = fma(weight, b.lo, 0.0);
176
+ let rawSum = fma(a.hi, 1.0, product);
177
+ let productNormal = abs(product) >= 1.1754943508222875e-38;
178
+ if (productNormal && scaled_value_scalar_finite(product) &&
179
+ scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {
180
+ let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);
181
+ let result = scaled_value_scalar_add_words(a, product, error);
182
+ if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }
183
+ }
184
+ }
185
+ // Decompose BEFORE multiplying: a merge coefficient may exceed one, so
186
+ // its unscaled product with a finite partial mean need not fit in f32.
187
+ var other = b;
188
+ if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }
189
+ let wp = frexp(weight);
190
+ let vp = frexp(other.hi);
191
+ let productExponent = other.exponent + wp.exp + vp.exp;
192
+ let commonExponent = max(scaled_value_scalar_leading(a), productExponent);
193
+ let aligned = scaled_value_scalar_align(a, commonExponent);
194
+ let product = fma(wp.fract, vp.fract, 0.0);
195
+ let productError = fma(wp.fract, vp.fract, -product);
196
+ let shift = productExponent - commonExponent;
197
+ let highWord = scaled_value_scalar_shift(product, shift);
198
+ let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,
199
+ fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));
200
+ {% if recoverSum %}
201
+ let sum = aligned.hi + highWord;
202
+ let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;
203
+ return scaled_value_scalar_finish(sum, low, commonExponent);
204
+ {% else %}
205
+ let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);
206
+ return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);
207
+ {% endif %}
208
+ }
209
+ {% endif %}
210
+ fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {
211
+ if (denominator == 0.0) { return 0.0; }
212
+ if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }
213
+ if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {
214
+ return fma(a.hi, 1.0, a.lo) / denominator;
215
+ }
216
+ let valueParts = frexp(a.hi);
217
+ let denominatorParts = frexp(denominator);
218
+ let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));
219
+ let quotient = mantissa / denominatorParts.fract;
220
+ return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);
221
+ }
222
+ fn scaled_value_zero() -> ScaledValue {
223
+ return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));
224
+ }
225
+ {% if N > 1 or rescale or lean %}
226
+ // Vector form of scaled_value_scalar_add_words: applies it to every component at once.
227
+ fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {
228
+ let sum = fma(acc.hi, {{ type }}(1.0), product);
229
+ {% if magnitudeOrdered %}
230
+ // FastTwoSum recovers the rounding error with the larger magnitude first.
231
+ let takeProduct = abs(acc.hi) < abs(product);
232
+ let larger = select(acc.hi, product, takeProduct);
233
+ let smaller = select(product, acc.hi, takeProduct);
234
+ let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);
235
+ let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);
236
+ {% else %}
237
+ let bv = fma({{ type }}(-1.0), acc.hi, sum);
238
+ let av = fma({{ type }}(-1.0), bv, sum);
239
+ let ae = fma({{ type }}(-1.0), av, acc.hi);
240
+ let be = fma({{ type }}(-1.0), bv, product);
241
+ let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);
242
+ {% endif %}
243
+ let hi = fma(sum, {{ type }}(1.0), residual);
244
+ return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);
245
+ }
246
+ {% endif %}
247
+ {% if lean %}
248
+ // Lean folds: the compensated arithmetic of scaled_value_add_step with every
249
+ // check deferred to the fold's end. A fold that starts from a normalized pair at
250
+ // exponent zero (the high word is the words' rounded sum), ends with finite words
251
+ // (a non-finite word stays non-finite through the sum, so this covers the start
252
+ // too), and whose smallest nonzero weight times smallest nonzero value is normal
253
+ // took only steps whose result is scaled_value_add's, up to the sign of a zero
254
+ // word: each nonzero product was normal, every step leaves the pair normalized,
255
+ // and a zero product leaves a normalized pair unchanged.
256
+ fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {
257
+ let w = {{ type }}(weight);
258
+ let product = fma(w, value, {{ type }}(0.0));
259
+ return scaled_value_add_words(acc, product, fma(w, value, -product));
260
+ }
261
+ // The smallest nonzero magnitude among `low` and `value`, per component.
262
+ fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {
263
+ return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));
264
+ }
265
+ fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {
266
+ return all(start.exponent == {{ exponentType }}(0)) &&
267
+ all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &
268
+ (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &
269
+ ({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));
270
+ }
271
+ {% endif %}
272
+ {% if N > 1 and tile %}
273
+ {% set uType = "vec" ~ N ~ "<u32>" %}
274
+ // Offset tile folds. A tile's products, at most `bound` in total magnitude per
275
+ // component, add onto `offset`, the power of two above 2.25 * bound, so every
276
+ // partial sum stays within [offset / 2, 2 * offset): each step's change to it is
277
+ // exact, and the low word gathers each step's remainder, at most half an ulp of
278
+ // the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the
279
+ // offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A
280
+ // non-finite weight, value or bound leaves a non-finite word, and a bound past
281
+ // 2^126 an infinite offset, so a caller checks finiteness once, after its fold;
282
+ // scaled_value_tile_in_range checks what that cannot see.
283
+ struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }
284
+ fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {
285
+ let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));
286
+ let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));
287
+ return ScaledValueTile(offset, offset, {{ type }}(0.0));
288
+ }
289
+ fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {
290
+ let w = {{ type }}(weight);
291
+ let sum = fma(w, value, tile.sum);
292
+ let change = fma({{ type }}(-1.0), tile.sum, sum);
293
+ return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));
294
+ }
295
+ // The tile's words, normalized, added as scaled_value_add adds a product.
296
+ fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {
297
+ let high = fma({{ type }}(-1.0), tile.offset, tile.sum);
298
+ let sum = fma(high, {{ type }}(1.0), tile.low);
299
+ let bv = fma({{ type }}(-1.0), high, sum);
300
+ let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));
301
+ return scaled_value_add_words(acc, sum, error);
302
+ }
303
+ // An offset or start of at least 2^-76, or a zero bound, keeps every word a
304
+ // flush-to-zero device could drop below 2^-48 of the result.
305
+ fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {
306
+ return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&
307
+ {% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |
308
+ (bound == {{ type }}(0.0)));
309
+ }
310
+ {% endif %}
311
+ {% if N > 1 and add %}
312
+ // One compensated fold step without branches, for a caller that folds many
313
+ // steps before it can afford a branch. From finite words at exponent zero, a
314
+ // normal product and a finite low word imply every other condition of this
315
+ // arithmetic in scaled_value_add: the low word is finite only if the high word
316
+ // is, then the sum is, then the product, the weight and the value. A zero
317
+ // weight with a finite value is the step whose exact result is the accumulator
318
+ // itself. `exact` is false in any component whose step only scaled_value_add
319
+ // computes.
320
+ struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }
321
+ fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {
322
+ let w = {{ type }}(weight);
323
+ let product = fma(w, value, {{ type }}(0.0));
324
+ let sum = scaled_value_add_words(acc, product, fma(w, value, -product));
325
+ let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));
326
+ let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &
327
+ {% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));
328
+ return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),
329
+ fast | vec{{ N }}<bool>(keep));
330
+ }
331
+ {% endif %}
332
+ {% if add %}
333
+ fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {
334
+ {% if N > 1 %}
335
+ // Ordinary raw products use one vector compensated sum. Every exceptional
336
+ // component falls back to the same scalar exponent-aware implementation.
337
+ if (all(acc.exponent == {{ exponentType }}(0)) &&
338
+ all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&
339
+ all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {
340
+ let step = scaled_value_add_step(acc, weight, value);
341
+ if (all(step.exact)) { return step.value; }
342
+ }
343
+ {% endif %}
344
+ var result = scaled_value_zero();
345
+ {% for i in range(N) %}
346
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
347
+ 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));
348
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
349
+ {% endfor %}
350
+ return result;
351
+ }
352
+ {% endif %}
353
+ {% if rescale or tile %}
354
+ {% macro rescale_words() %}
355
+ let w = {{ type }}(correction);
356
+ let product = fma(w, acc.hi, {{ type }}(0.0));
357
+ let scaled = scaled_value_add_words(scaled_value_zero(), product,
358
+ fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));
359
+ let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);
360
+ let unit = correction == 1.0;
361
+ {% endmacro %}
362
+ {% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &
363
+ (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &
364
+ (zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &
365
+ (abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}
366
+ {% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),
367
+ select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}
368
+ {% endif %}
369
+ {% if tile %}
370
+ // scaled_value_rescale's vector path alone; `exact` is false where only its
371
+ // scalar path applies.
372
+ struct ScaledValueRescaled { value: ScaledValue, exact: bool }
373
+ fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {
374
+ {{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});
375
+ }
376
+ {% endif %}
377
+ {% if rescale %}
378
+ fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {
379
+ // From finite words at exponent zero, the scalar path below leaves zero
380
+ // words for a zero value or correction, the value itself for a unit
381
+ // correction, and otherwise this compensated product onto zero words when
382
+ // the product is normal and the low word finite (which bounds the rest, as
383
+ // in scaled_value_add_step).
384
+ {{ rescale_words() }} if ({{ rescale_vector_exact() }}) {
385
+ return {{ rescale_vector_value() }};
386
+ }
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_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.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
+ {% if merge %}
397
+ fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {
398
+ var result = scaled_value_zero();
399
+ {% for i in range(N) %}
400
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
401
+ 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 }}));
402
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
403
+ {% endfor %}
404
+ return result;
405
+ }
406
+ {% endif %}
407
+ fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {
408
+ // Words at exponent zero well inside the normal range, with a normal
409
+ // quotient: the scalar path below divides this same sum by this same
410
+ // denominator, each scaled by a power of two, so it rounds to this quotient
411
+ // wherever division is scale-invariant. Bounding the denominator above also
412
+ // keeps a division through its reciprocal clear of a subnormal reciprocal.
413
+ let d = {{ type }}(denominator);
414
+ let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);
415
+ let quotient = sum / d;
416
+ if (all((acc.exponent == {{ exponentType }}(0)) &
417
+ (abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &
418
+ (abs(acc.lo) <= abs(acc.hi)) &
419
+ (abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &
420
+ ((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {
421
+ return quotient;
422
+ }
423
+ var result = {{ type }}(0.0);
424
+ {% for i in range(N) %}
425
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
426
+ result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});
427
+ {% endfor %}
428
+ return result;
429
+ }
430
+ {% if align %}
431
+ fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {
432
+ var result = {{ exponentType }}(0);
433
+ {% for i in range(N) %}
434
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
435
+ result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));
436
+ {% endfor %}
437
+ return result;
438
+ }
439
+ fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {
440
+ var result = scaled_value_zero();
441
+ {% for i in range(N) %}
442
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
443
+ let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});
444
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
445
+ {% endfor %}
446
+ return result;
447
+ }
448
+ {% endif %}
449
+ {% endmacro %}
450
+ {{ scaled_value_functions("vec4<f32>", rescale=fusedNormAppend | default(false)) }}
451
+ {% set MERGE_GROUPS = max(1, min(4, numSplits, (256 / headDimV4) | int)) %}
452
+ {% set GROUP_SPLITS = ((numSplits + MERGE_GROUPS - 1) / MERGE_GROUPS) | int %}
453
+ {% if MERGE_GROUPS > 1 %}
454
+ // Joins a run's fold onto the folds before it: the same compensated sum of
455
+ // two word pairs, finite at exponent zero, with the run's high word normal.
456
+ fn join_runs(acc: ScaledValue, run: ScaledValue) -> ScaledValueStep {
457
+ let sum = fma(acc.hi, vec4<f32>(1.0), run.hi);
458
+ let bv = fma(vec4<f32>(-1.0), acc.hi, sum);
459
+ let av = fma(vec4<f32>(-1.0), bv, sum);
460
+ let ae = fma(vec4<f32>(-1.0), av, acc.hi);
461
+ let be = fma(vec4<f32>(-1.0), bv, run.hi);
462
+ let residual = fma(fma(fma(ae, vec4<f32>(1.0), be), vec4<f32>(1.0), acc.lo), vec4<f32>(1.0), run.lo);
463
+ let hi = fma(sum, vec4<f32>(1.0), residual);
464
+ let lo = fma(vec4<f32>(-1.0), fma(vec4<f32>(-1.0), sum, hi), residual);
465
+ let empty = all(run.hi == vec4<f32>(0.0)) && all(run.lo == vec4<f32>(0.0));
466
+ let fast = (abs(run.hi) >= vec4<f32>(1.1754943508222875e-38)) & (abs(lo) <= vec4<f32>(FLT_MAX));
467
+ return ScaledValueStep(ScaledValue(select(hi, acc.hi, empty), select(lo, acc.lo, empty), acc.exponent), fast | vec4<bool>(empty));
468
+ }
469
+ var<workgroup> run_hi: array<vec4<f32>, HEAD_DIM_V4 * {{ MERGE_GROUPS - 1 }}u>;
470
+ var<workgroup> run_lo: array<vec4<f32>, HEAD_DIM_V4 * {{ MERGE_GROUPS - 1 }}u>;
471
+ var<workgroup> run_exact: array<u32, HEAD_DIM_V4 * {{ MERGE_GROUPS - 1 }}u>;
472
+ {% endif %}
473
+ {% else %}
474
+ {% set MERGE_GROUPS = 1 %}
475
+ {% endif %}
476
+ // Every split's statistics, read once for the workgroup, and its scale onto
477
+ // the global max, computed once.
478
+ var<workgroup> split_max: array<f32, NUM_SPLITS>;
479
+ var<workgroup> split_denom: array<f32, NUM_SPLITS>;
480
+ var<workgroup> split_scale: array<f32, NUM_SPLITS>;
481
+ const MERGE_THREADS: u32 = HEAD_DIM_V4{% if MERGE_GROUPS > 1 %} * {{ MERGE_GROUPS }}u{% endif %};
482
+ // A split's partial row: its output vec4s, then its statistics when inline.
483
+ const PARTIAL_STRIDE: u32 = HEAD_DIM_V4;
484
+
485
+ @compute @workgroup_size(MERGE_THREADS, 1, 1)
486
  fn main(
487
  @builtin(workgroup_id) wg: vec3<u32>,
488
  @builtin(local_invocation_id) lid: vec3<u32>
 
492
  {% endif %}
493
  let h = wg.y;
494
  let b = wg.z;
495
+ {% if MERGE_GROUPS > 1 %}
496
+ let d4 = lid.x % HEAD_DIM_V4;
497
+ let group = lid.x / HEAD_DIM_V4;
498
+ {% else %}
499
  let d4 = lid.x;
500
+ {% endif %}
501
+ // The workgroup is HEAD_DIM_V4 lanes per group exactly, so the exit stays
502
+ // uniform ahead of the barriers below.
503
+ if (h >= Q_HEADS{% if splitQueries %} || queryToken >= Q_SEQ{% endif %}) {
504
  return;
505
  }
506
 
 
509
  {% else %}
510
  let mdBase = (b * Q_HEADS + h) * NUM_SPLITS;
511
  {% endif %}
512
+
513
+ for (var s = lid.x; s < NUM_SPLITS; s = s + MERGE_THREADS) {
514
+ let stats = partial_stats[mdBase + s];
515
+ split_max[s] = stats.x;
516
+ split_denom[s] = stats.y;
517
+ }
518
+ workgroupBarrier();
519
  var globalMax = -FLT_MAX;
520
  for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {
521
+ globalMax = max(globalMax, split_max[s]);
522
+ }
523
+ for (var s = lid.x; s < NUM_SPLITS; s = s + MERGE_THREADS) {
524
+ split_scale[s] = exp_shift(split_max[s], globalMax);
525
  }
526
+ workgroupBarrier();
527
  var globalDenom = 0.0;
528
+ {% if not NORMALIZED_VALUES %}
529
  var outV = vec4<f32>(0.0);
530
+ {% endif %}
531
  for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {
532
+ let w = split_scale[s];
533
+ globalDenom = globalDenom + split_denom[s] * w;
534
+ {% if not NORMALIZED_VALUES %}
535
+ outV = outV + partial_out[(mdBase + s) * PARTIAL_STRIDE + d4] * w;
536
+ {% endif %}
537
+ }
538
+ {% if NORMALIZED_VALUES %}
539
+ // These partials are means. Accumulate their raw statistical weights
540
+ // without materializing an overflowing product or a tiny probability. Each
541
+ // run folds only steps whose result is scaled_value_add's, and the runs join
542
+ // as compensated sums; a row with any other step folds again, in order, with
543
+ // scaled_value_add itself.
544
+ var mean = scaled_value_zero();
545
+ var exact = vec4<bool>(true);
546
+ for (var k: u32 = 0u; k < {{ GROUP_SPLITS }}u; k = k + 1u) {
547
+ let s = {% if MERGE_GROUPS > 1 %}group * {{ GROUP_SPLITS }}u + {% endif %}k;
548
+ {% if numSplits % MERGE_GROUPS != 0 %} if (s < NUM_SPLITS) {
549
+ {% else %} {
550
+ {% endif %}
551
+ let weight = split_denom[s] * split_scale[s];
552
+ let value = partial_out[(mdBase + s) * PARTIAL_STRIDE + d4];
553
+ // A zero weight on a finite value is the step that returns its
554
+ // accumulator. The weight is the workgroup's, so its lanes skip together.
555
+ if (weight == 0.0) {
556
+ exact = exact & vec4<bool>(all(abs(value) <= vec4<f32>(FLT_MAX)));
557
+ } else {
558
+ let step = scaled_value_add_step(mean, weight, value);
559
+ exact = exact & step.exact;
560
+ mean = step.value;
561
+ }
562
+ }
563
+ }
564
+ {% if MERGE_GROUPS > 1 %}
565
+ if (group > 0u) {
566
+ let slot = (group - 1u) * HEAD_DIM_V4 + d4;
567
+ run_hi[slot] = mean.hi;
568
+ run_lo[slot] = mean.lo;
569
+ run_exact[slot] = select(0u, 1u, all(exact));
570
+ }
571
+ workgroupBarrier();
572
+ if (group > 0u) {
573
+ return;
574
+ }
575
+ for (var g: u32 = 1u; g < {{ MERGE_GROUPS }}u; g = g + 1u) {
576
+ let slot = (g - 1u) * HEAD_DIM_V4 + d4;
577
+ let joined = join_runs(mean, ScaledValue(run_hi[slot], run_lo[slot], vec4<i32>(0)));
578
+ exact = exact & joined.exact & vec4<bool>(run_exact[slot] != 0u);
579
+ mean = joined.value;
580
+ }
581
  {% endif %}
582
+ if (!all(exact)) {
583
+ mean = scaled_value_zero();
584
+ for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {
585
+ mean = scaled_value_add(mean, split_denom[s] * split_scale[s],
586
+ partial_out[(mdBase + s) * PARTIAL_STRIDE + d4]);
587
+ }
588
  }
589
+ {% endif %}
590
 
591
  {% if splitQueries %}
592
  let qBaseV4 = ((b * Q_HEADS + h) * Q_SEQ + queryToken) * HEAD_DIM_V4;
 
594
  let qBaseV4 = (b * Q_HEADS + h) * HEAD_DIM_V4;
595
  {% endif %}
596
  // A split that covers no keys writes vec2(-FLT_MAX, 0), so when every split is empty —
597
+ // a query whose window contains no keys — globalMax stays -FLT_MAX, exp_shift(x, x) is 1,
598
  // and globalDenom lands on exactly 0. Emit 0 rather than dividing so an all-empty
599
  // row has a defined zero result.
600
+ var outValue = select(vec4<f32>(0.0), {% if NORMALIZED_VALUES %}scaled_value_mean(mean, globalDenom){% else %}outV / globalDenom{% endif %}, globalDenom > 0.0);
601
  output[qBaseV4 + d4] = vec4<{{ scalar }}>(outValue);
602
  }
build/webgpu/attn-flash-decode-splitk.wgsl.jinja CHANGED
@@ -1,17 +1,23 @@
 
 
 
 
1
  {% if useSubgroups is not defined %}{% set useSubgroups = true %}{% endif %}
2
  {% if splitQueries is not defined %}{% set splitQueries = false %}{% endif %}
3
  {% if cacheSeqlens is not defined %}{% set cacheSeqlens = false %}{% endif %}
4
  {% if hasMask is not defined %}{% set hasMask = false %}{% endif %}
5
- {% if hasKeyPadMask is not defined %}{% set hasKeyPadMask = false %}{% endif %}
6
  {% if emitQk is not defined %}{% set emitQk = false %}{% endif %}
7
  {% if cacheSeqlensIndex is not defined %}{% set cacheSeqlensIndex = "b" %}{% endif %}
8
  {% if maskFilterValue is not defined %}{% set maskFilterValue = 0.0 %}{% endif %}
9
  {% if qkScalar is not defined %}{% set qkScalar = "f32" %}{% endif %}
10
  {% set qSeq = 0 %}
11
- {% set splitKWorkgroupSize = workgroupSizeSpec if workgroupSizeSpec is defined else tunables.WORKGROUP_SIZE %}
12
  {% if useSubgroups %}
13
  enable subgroups;
14
  {% endif %}
 
 
15
  {{ env.wgsl.resourceDeclarations }}
16
 
17
  // Split-K flash attention. Single-partition direct output skips the merge pass.
@@ -22,10 +28,15 @@ enable subgroups;
22
  // sweeping the whole KV sequence serially in WG-key tiles. This pass splits the
23
  // KV sequence into `NUM_SPLITS` contiguous ranges and gives each range its own
24
  // workgroup, so `batch * numHeads * NUM_SPLITS` workgroups run the tiled online
25
- // softmax in parallel. Each workgroup emits the *un-normalized* online state for
26
- // its range — the running (max, denom) and the softmax-weighted V sum before the
27
- // final divide — and the merge pass combines the per-split states with the online
28
- // rule.
 
 
 
 
 
29
  // Layout: rank-4 [batch, heads, seq, headDim] for Q/K/V.
30
  const HEAD_DIM: u32 = {{ headDim }}u;
31
  const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;
@@ -61,11 +72,413 @@ fn exp_shift(value: f32, maxValue: f32) -> f32 {
61
  }
62
 
63
  var<workgroup> q_shared: array<vec4<f32>, HEAD_DIM_V4>;
 
64
  var<workgroup> running_out: array<vec4<f32>, HEAD_DIM_V4>;
 
65
  var<workgroup> probs: array<f32, WG>;
66
  {% set coopQk = useSubgroups and headDimV4 >= 8 and not (usesF16 and headDimV4 <= 32) and (allowCooperativeQk if allowCooperativeQk is defined else true) %}
67
  {% set jGroups = (splitKWorkgroupSize / headDimV4)|int %}
68
- {% set jSplitV = (splitKWorkgroupSize % headDimV4 == 0) and (jGroups >= 2) %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  {% if coopQk %}
70
  var<workgroup> sval_sh: array<f32, WG>;
71
  {% endif %}
@@ -94,19 +507,13 @@ var<workgroup> partialD: array<f32, WG>;
94
  var<workgroup> leaderMask: array<atomic<u32>, (WG + 31u) / 32u>;
95
  var<workgroup> combinedMD: vec2<f32>;
96
 
97
- // When the whole workgroup is one subgroup the subgroup reduce already covers
98
- // it (no barriers, no shared state). `subgroup_size` is the size of the current
99
- // subgroup and uniform, so the test is exact and may guard the barriers below.
100
- fn combine_partials(m: f32, d: f32, lidx: u32, sgSize: u32) -> vec2<f32> {
101
  let sgM = subgroupMax(m);
102
  // A lane with no elements contributes d == 0 (exact identity). A +inf
103
  // element made exp(inf - inf) = NaN stick in that lane's d; a NaN element
104
  // landed in d via exp(NaN); both survive the merge and are detected by the
105
  // code after the reduction.
106
  let sgD = subgroupAdd(d * exp_shift(m, sgM));
107
- if (sgSize == WG) {
108
- return vec2<f32>(sgM, sgD);
109
- }
110
  if (subgroupElect()) {
111
  partialM[lidx] = sgM;
112
  partialD[lidx] = sgD;
@@ -174,22 +581,19 @@ fn load_key4(indexV4: u32) -> vec4<f32> {
174
  return vec4<f32>(key[indexV4]);
175
  }
176
 
 
177
  fn load_value4(indexV4: u32) -> vec4<f32> {
178
  return vec4<f32>(value[indexV4]);
179
  }
 
180
 
181
  @compute @workgroup_size(WG, 1, 1)
182
  fn main(
183
  @builtin(workgroup_id) wg: vec3<u32>,
184
- @builtin(local_invocation_id) lid: vec3<u32>{% if useSubgroups %},
185
- @builtin(subgroup_size) sgSize: u32{% endif %}
 
186
  ) {
187
- {% if useSubgroups %}
188
- // Subgroup tiles partition the fixed workgroup exactly. The advertised range
189
- // is validated before dispatch; retain this uniform guard for implementations that
190
- // choose an intermediate width at pipeline execution time.
191
- if (sgSize == 0u || sgSize > WG || WG % sgSize != 0u) { return; }
192
- {% endif %}
193
  {% if splitQueries %}
194
  let queryToken = wg.x / NUM_SPLITS;
195
  let split = wg.x % NUM_SPLITS;
@@ -202,12 +606,42 @@ fn main(
202
  return;
203
  }
204
  let tid = lid.x;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  let hKv = h / (Q_HEADS / KV_HEADS);
206
  let cacheSeq = params.kvSeq;
207
  {% if cacheSeqlens %}
208
  // Buffer-sharing caches retain their capacity in the physical BNSH stride;
209
  // seqlens_k supplies the active end independently for each batch.
210
- let kvSeq = min(cacheSeq, u32(seqlens_k[{{ cacheSeqlensIndex }}]) + 1u);
211
  {% else %}
212
  let kvSeq = cacheSeq;
213
  {% endif %}
@@ -234,18 +668,25 @@ fn main(
234
  for (var d4 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {
235
  var qv = vec4<f32>(query[qBaseV4 + d4]);
236
  q_shared[d4] = qv;
 
237
  running_out[d4] = vec4<f32>(0.0);
 
238
  }
239
  workgroupBarrier();
240
  let scale = scale_value();
241
  var runningMax = -FLT_MAX;
242
  var runningDenom = 0.0;
243
 
 
 
 
 
244
  var kjBase = splitStart;
245
  loop {
246
  if (kjBase >= splitEnd) {
247
  break;
248
  }
 
249
  let kj = kjBase + tid;
250
  var keyAllowed = kj < splitEnd;
251
  let tileCount = min(WG, splitEnd - kjBase);
@@ -254,6 +695,7 @@ fn main(
254
  var m = -FLT_MAX;
255
  var dPart = 0.0;
256
  {% if coopQk %}
 
257
  // Cooperative Q.K: one subgroup per key, lanes splitting HEAD_DIM_V4, then a hardware
258
  // subgroupAdd — turns the per-thread HEAD_DIM_V4-long dependent dot chain into a few
259
  // strided vec4 dots + one reduce. Uniform trip count keeps subgroupAdd in uniform flow.
@@ -265,7 +707,7 @@ fn main(
265
  let j = rr * sgPerWg + sgInWg;
266
  var accS: f32 = 0.0;
267
  if (j < tileCount) {
268
- let kRowV4 = kvBaseV4 + (kjBase + j) * kvTokenStrideV4;
269
  for (var d4: u32 = lane; d4 < HEAD_DIM_V4; d4 = d4 + sgSize) {
270
  accS = accS + dot(q_shared[d4], load_key4(kRowV4 + d4));
271
  }
@@ -281,9 +723,21 @@ fn main(
281
  m = score;
282
  dPart = 1.0;
283
  }
 
 
 
 
 
 
 
 
 
 
 
 
284
  {% else %}
285
  if (keyAllowed) {
286
- let kRowV4 = kvBaseV4 + kj * kvTokenStrideV4;
287
  var acc: f32 = 0.0;
288
  for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {
289
  acc = acc + dot(q_shared[d4], load_key4(kRowV4 + d4));
@@ -293,7 +747,7 @@ fn main(
293
  dPart = 1.0;
294
  }
295
  {% endif %}
296
- {% if hasMask %}
297
  if (keyAllowed) {
298
  {% if splitQueries %}
299
  let maskQuery = queryToken;
@@ -319,7 +773,7 @@ fn main(
319
  qk[(b * Q_HEADS + h) * kvSeq + kj] = {{ qkScalar }}(score);
320
  }
321
  {% endif %}
322
- let tile = combine_partials(m, dPart, tid{% if useSubgroups %}, sgSize{% endif %});
323
 
324
  // Merge one key tile's online-softmax (maximum, denominator) partial into the
325
  // running state, then store the per-key probabilities consumed by V accumulation.
@@ -335,6 +789,50 @@ fn main(
335
  probs[tid] = prob;
336
  workgroupBarrier();
337
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
  {% if jSplitV %}
339
  // j-split V accumulation: thread (jg, d4v) sums keys j == jg mod
340
  // J_GROUPS for dim block d4v into a register, then the groups combine
@@ -347,7 +845,7 @@ fn main(
347
  loop {
348
  if (jj >= tileCount) { break; }
349
  vacc = vacc + probs[jj] * load_value4(
350
- kvBaseV4 + (kjBase + jj) * kvTokenStrideV4 + d4v );
351
  jj = jj + J_GROUPS;
352
  }
353
  vacc_sh[tid] = vacc;
@@ -365,37 +863,50 @@ fn main(
365
  var vSum = vec4<f32>(0.0);
366
  for (var i: u32 = 0u; i < tileCount; i = i + 1u) {
367
  vSum = vSum + probs[i] * load_value4(
368
- kvBaseV4 + (kjBase + i) * kvTokenStrideV4 + d4 );
369
  }
370
  running_out[d4] = running_out[d4] * correction + vSum;
371
  }
372
  workgroupBarrier();
373
  {% endif %}
 
374
 
 
375
  kjBase = kjBase + WG;
 
376
  }
377
 
378
  {% if directOutput is defined and directOutput %}
379
- // The manifest admits this epilogue only for one partition and no post-merge
380
- // bias or gate. Preserve the merge's finite/nonfinite weighting and zero-row
381
  // behavior before narrowing once to the output dtype.
382
  let finalWeight = exp_shift(runningMax, max(-FLT_MAX, runningMax));
383
  let finalDenom = runningDenom * finalWeight;
384
  for (var d4: u32 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {
385
- let finalOut = running_out[d4] * finalWeight;
386
  output[qBaseV4 + d4] = vec4<{{ "f16" if usesF16 else "f32" }}>(
387
- select(vec4<f32>(0.0), finalOut / finalDenom, finalDenom > 0.0));
388
  }
 
 
 
389
  {% else %}
390
  // Emit un-normalized partials for (b, h, split): the merge pass divides.
 
391
  {% if splitQueries %}
392
  let partialBase = (((b * Q_SEQ + queryToken) * Q_HEADS + h) * NUM_SPLITS + split) * HEAD_DIM_V4;
393
  {% else %}
394
  let partialBase = ((b * Q_HEADS + h) * NUM_SPLITS + split) * HEAD_DIM_V4;
395
  {% endif %}
 
 
 
 
 
396
  for (var d4: u32 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {
397
- partial_out[partialBase + d4] = running_out[d4];
398
  }
 
399
  if (tid == 0u) {
400
  {% if splitQueries %}
401
  let mdBase = ((b * Q_SEQ + queryToken) * Q_HEADS + h) * NUM_SPLITS + split;
 
1
+ {% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}
2
+ {% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {% if queryFloor %}max({{ queryFloor }}, {{ attn_seqlens_count(index) }}){% else %}{{ attn_seqlens_count(index) }}{% endif %}){% endmacro %}
3
+ {% set kvRing = false %}
4
+ {% set RING_MASK = "" %}
5
  {% if useSubgroups is not defined %}{% set useSubgroups = true %}{% endif %}
6
  {% if splitQueries is not defined %}{% set splitQueries = false %}{% endif %}
7
  {% if cacheSeqlens is not defined %}{% set cacheSeqlens = false %}{% endif %}
8
  {% if hasMask is not defined %}{% set hasMask = false %}{% endif %}
9
+ {% set maskIsBool = false %}{% if hasKeyPadMask is not defined %}{% set hasKeyPadMask = false %}{% endif %}
10
  {% if emitQk is not defined %}{% set emitQk = false %}{% endif %}
11
  {% if cacheSeqlensIndex is not defined %}{% set cacheSeqlensIndex = "b" %}{% endif %}
12
  {% if maskFilterValue is not defined %}{% set maskFilterValue = 0.0 %}{% endif %}
13
  {% if qkScalar is not defined %}{% set qkScalar = "f32" %}{% endif %}
14
  {% set qSeq = 0 %}
15
+ {% set splitKWorkgroupSize = tunables.WORKGROUP_SIZE %}
16
  {% if useSubgroups %}
17
  enable subgroups;
18
  {% endif %}
19
+ {% set NORMALIZED_VALUES = normalizedPartialValues | default(false) %}
20
+ {% set foldType = "f32" if componentFold else "vec4<f32>" %}
21
  {{ env.wgsl.resourceDeclarations }}
22
 
23
  // Split-K flash attention. Single-partition direct output skips the merge pass.
 
28
  // sweeping the whole KV sequence serially in WG-key tiles. This pass splits the
29
  // KV sequence into `NUM_SPLITS` contiguous ranges and gives each range its own
30
  // workgroup, so `batch * numHeads * NUM_SPLITS` workgroups run the tiled online
31
+ // softmax in parallel.
32
+ {% if NORMALIZED_VALUES %}
33
+ // Each workgroup emits the normalized partial mean for its range together with its softmax statistics (max,
34
+ // denom); the merge pass weights the means by those statistics.
35
+ {% else %}
36
+ // Each workgroup emits the *un-normalized* online state for its range — the running (max, denom) and the
37
+ // softmax-weighted V sum before the final divide — and the merge pass combines the per-split states with the
38
+ // online rule.
39
+ {% endif %}
40
  // Layout: rank-4 [batch, heads, seq, headDim] for Q/K/V.
41
  const HEAD_DIM: u32 = {{ headDim }}u;
42
  const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;
 
72
  }
73
 
74
  var<workgroup> q_shared: array<vec4<f32>, HEAD_DIM_V4>;
75
+ {% if not componentFold %}
76
  var<workgroup> running_out: array<vec4<f32>, HEAD_DIM_V4>;
77
+ {% endif %}
78
  var<workgroup> probs: array<f32, WG>;
79
  {% set coopQk = useSubgroups and headDimV4 >= 8 and not (usesF16 and headDimV4 <= 32) and (allowCooperativeQk if allowCooperativeQk is defined else true) %}
80
  {% set jGroups = (splitKWorkgroupSize / headDimV4)|int %}
81
+ {% set jSplitV = (splitKWorkgroupSize % headDimV4 == 0) and (jGroups >= 2) and not NORMALIZED_VALUES %}
82
+ {% if NORMALIZED_VALUES %}
83
+ {% macro sum_error_function(name, type="f32", protectDifference=false) %}
84
+ {% set bitsType = type | replace("f32", "u32") %}
85
+ // Observing the rounded sum as bits preserves FastTwoSum on backends
86
+ // that otherwise reassociate its subtractions. Both signs of zero contribute zero.
87
+ fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {
88
+ let bits = bitcast<{{ bitsType }}>(x);
89
+ return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));
90
+ }
91
+ fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {
92
+ let swap = abs(a) < abs(b);
93
+ let larger = select(a, b, swap);
94
+ let smaller = select(b, a, swap);
95
+ // Keep the rounded high-part difference observable before subtracting it
96
+ // from the smaller addend. Reassociation here erases the residual.
97
+ return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);
98
+ }
99
+ {% endmacro %}
100
+ {% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}
101
+ {% set N = 1 if type == "f32" else (type[3] | int) %}
102
+ {% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}
103
+ {% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}
104
+ {% set exact = add or rescale or merge %}
105
+ {% set boundNumerator = boundValueNumerator | default(false) %}
106
+ {% if boundNumerator and (exact or tile) %}
107
+ // Even a u32 key count times this magnitude leaves a bit of f32 exponent
108
+ // headroom for a partial sum. Larger terms use the exponent-aware path.
109
+ const VALUE_FAST_LIMIT: f32 = 0x1p94f;
110
+ {% endif %}
111
+ struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }
112
+ struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }
113
+
114
+ {% if exact %}
115
+ fn scaled_value_scalar_zero() -> ScaledValueScalar {
116
+ return ScaledValueScalar(0.0, 0.0, 0);
117
+ }
118
+ {% endif %}
119
+ fn scaled_value_scalar_finite(x: f32) -> bool {
120
+ return abs(x) <= 3.4028234663852886e38;
121
+ }
122
+ {% if exact or align %}
123
+ fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {
124
+ if (a.hi == 0.0) {
125
+ if (a.lo == 0.0) { return -1024; }
126
+ return a.exponent + frexp(a.lo).exp;
127
+ }
128
+ if (!scaled_value_scalar_finite(a.hi)) { return 1024; }
129
+ return a.exponent + frexp(a.hi).exp;
130
+ }
131
+ {% endif %}
132
+ // Scale the significand bits directly. WGSL ldexp may return zero for a
133
+ // shift <= -127 even when its input makes the final result normal; shifts
134
+ // above 128 are indeterminate. Neither limit applies to this exponent sum.
135
+ fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {
136
+ let bits = bitcast<u32>(value);
137
+ let sign = bits & 0x80000000u;
138
+ let fraction = bits & 0x007fffffu;
139
+ let inputExponent = i32((bits >> 23u) & 0xffu);
140
+ if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }
141
+ var significand = fraction | 0x00800000u;
142
+ var exponent = inputExponent + shift;
143
+ if (inputExponent == 0) {
144
+ let normalize = countLeadingZeros(fraction) - 8u;
145
+ significand = fraction << normalize;
146
+ exponent = 1 + shift - i32(normalize);
147
+ }
148
+ if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }
149
+ if (exponent > 0) {
150
+ return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));
151
+ }
152
+ let distance = u32(1 - exponent);
153
+ if (distance > 24u) { return bitcast<f32>(sign); }
154
+ let high = significand >> distance;
155
+ let remainder = significand & ((1u << distance) - 1u);
156
+ let halfway = 1u << (distance - 1u);
157
+ let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);
158
+ return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));
159
+ }
160
+ {% if exact or align %}
161
+ fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {
162
+ if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }
163
+ if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }
164
+ return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);
165
+ }
166
+ {% endif %}
167
+ {% if exact %}
168
+ {% if recoverSum %}
169
+ {{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}
170
+ {% endif %}
171
+ fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {
172
+ let nextHi = fma(hi, 1.0, lo);
173
+ let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};
174
+ if (nextHi == 0.0) { return scaled_value_scalar_zero(); }
175
+ if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }
176
+ let parts = frexp(nextHi);
177
+ let rawExponent = exponent + parts.exp;
178
+ // Ordinary magnitudes return to the unscaled fast path. The margin keeps
179
+ // boundary values away from overflow/underflow while scaling the low word.
180
+ if (rawExponent >= -120 && rawExponent <= 120) {
181
+ return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);
182
+ }
183
+ return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);
184
+ }
185
+ fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {
186
+ let sum = fma(a.hi, 1.0, product);
187
+ let bv = fma(-1.0, a.hi, sum);
188
+ let av = fma(-1.0, bv, sum);
189
+ let ae = fma(-1.0, av, a.hi);
190
+ let be = fma(-1.0, bv, product);
191
+ let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);
192
+ let hi = fma(sum, 1.0, residual);
193
+ return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);
194
+ }
195
+ fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {
196
+ if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||
197
+ !scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||
198
+ !scaled_value_scalar_finite(weight)) {
199
+ return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);
200
+ }
201
+ if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }
202
+ if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }
203
+ if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {
204
+ let product = fma(weight, b.hi, 0.0);
205
+ let lowProduct = fma(weight, b.lo, 0.0);
206
+ let rawSum = fma(a.hi, 1.0, product);
207
+ let productNormal = abs(product) >= 1.1754943508222875e-38;
208
+ if (productNormal && scaled_value_scalar_finite(product) &&
209
+ scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {
210
+ let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);
211
+ let result = scaled_value_scalar_add_words(a, product, error);
212
+ if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }
213
+ }
214
+ }
215
+ // Decompose BEFORE multiplying: a merge coefficient may exceed one, so
216
+ // its unscaled product with a finite partial mean need not fit in f32.
217
+ var other = b;
218
+ if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }
219
+ let wp = frexp(weight);
220
+ let vp = frexp(other.hi);
221
+ let productExponent = other.exponent + wp.exp + vp.exp;
222
+ let commonExponent = max(scaled_value_scalar_leading(a), productExponent);
223
+ let aligned = scaled_value_scalar_align(a, commonExponent);
224
+ let product = fma(wp.fract, vp.fract, 0.0);
225
+ let productError = fma(wp.fract, vp.fract, -product);
226
+ let shift = productExponent - commonExponent;
227
+ let highWord = scaled_value_scalar_shift(product, shift);
228
+ let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,
229
+ fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));
230
+ {% if recoverSum %}
231
+ let sum = aligned.hi + highWord;
232
+ let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;
233
+ return scaled_value_scalar_finish(sum, low, commonExponent);
234
+ {% else %}
235
+ let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);
236
+ return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);
237
+ {% endif %}
238
+ }
239
+ {% endif %}
240
+ fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {
241
+ if (denominator == 0.0) { return 0.0; }
242
+ if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }
243
+ if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {
244
+ return fma(a.hi, 1.0, a.lo) / denominator;
245
+ }
246
+ let valueParts = frexp(a.hi);
247
+ let denominatorParts = frexp(denominator);
248
+ let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));
249
+ let quotient = mantissa / denominatorParts.fract;
250
+ return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);
251
+ }
252
+ fn scaled_value_zero() -> ScaledValue {
253
+ return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));
254
+ }
255
+ {% if N > 1 or rescale or lean %}
256
+ // Vector form of scaled_value_scalar_add_words: applies it to every component at once.
257
+ fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {
258
+ let sum = fma(acc.hi, {{ type }}(1.0), product);
259
+ {% if magnitudeOrdered %}
260
+ // FastTwoSum recovers the rounding error with the larger magnitude first.
261
+ let takeProduct = abs(acc.hi) < abs(product);
262
+ let larger = select(acc.hi, product, takeProduct);
263
+ let smaller = select(product, acc.hi, takeProduct);
264
+ let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);
265
+ let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);
266
+ {% else %}
267
+ let bv = fma({{ type }}(-1.0), acc.hi, sum);
268
+ let av = fma({{ type }}(-1.0), bv, sum);
269
+ let ae = fma({{ type }}(-1.0), av, acc.hi);
270
+ let be = fma({{ type }}(-1.0), bv, product);
271
+ let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);
272
+ {% endif %}
273
+ let hi = fma(sum, {{ type }}(1.0), residual);
274
+ return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);
275
+ }
276
+ {% endif %}
277
+ {% if lean %}
278
+ // Lean folds: the compensated arithmetic of scaled_value_add_step with every
279
+ // check deferred to the fold's end. A fold that starts from a normalized pair at
280
+ // exponent zero (the high word is the words' rounded sum), ends with finite words
281
+ // (a non-finite word stays non-finite through the sum, so this covers the start
282
+ // too), and whose smallest nonzero weight times smallest nonzero value is normal
283
+ // took only steps whose result is scaled_value_add's, up to the sign of a zero
284
+ // word: each nonzero product was normal, every step leaves the pair normalized,
285
+ // and a zero product leaves a normalized pair unchanged.
286
+ fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {
287
+ let w = {{ type }}(weight);
288
+ let product = fma(w, value, {{ type }}(0.0));
289
+ return scaled_value_add_words(acc, product, fma(w, value, -product));
290
+ }
291
+ // The smallest nonzero magnitude among `low` and `value`, per component.
292
+ fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {
293
+ return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));
294
+ }
295
+ fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {
296
+ return all(start.exponent == {{ exponentType }}(0)) &&
297
+ all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &
298
+ (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &
299
+ ({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));
300
+ }
301
+ {% endif %}
302
+ {% if N > 1 and tile %}
303
+ {% set uType = "vec" ~ N ~ "<u32>" %}
304
+ // Offset tile folds. A tile's products, at most `bound` in total magnitude per
305
+ // component, add onto `offset`, the power of two above 2.25 * bound, so every
306
+ // partial sum stays within [offset / 2, 2 * offset): each step's change to it is
307
+ // exact, and the low word gathers each step's remainder, at most half an ulp of
308
+ // the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the
309
+ // offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A
310
+ // non-finite weight, value or bound leaves a non-finite word, and a bound past
311
+ // 2^126 an infinite offset, so a caller checks finiteness once, after its fold;
312
+ // scaled_value_tile_in_range checks what that cannot see.
313
+ struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }
314
+ fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {
315
+ let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));
316
+ let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));
317
+ return ScaledValueTile(offset, offset, {{ type }}(0.0));
318
+ }
319
+ fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {
320
+ let w = {{ type }}(weight);
321
+ let sum = fma(w, value, tile.sum);
322
+ let change = fma({{ type }}(-1.0), tile.sum, sum);
323
+ return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));
324
+ }
325
+ // The tile's words, normalized, added as scaled_value_add adds a product.
326
+ fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {
327
+ let high = fma({{ type }}(-1.0), tile.offset, tile.sum);
328
+ let sum = fma(high, {{ type }}(1.0), tile.low);
329
+ let bv = fma({{ type }}(-1.0), high, sum);
330
+ let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));
331
+ return scaled_value_add_words(acc, sum, error);
332
+ }
333
+ // An offset or start of at least 2^-76, or a zero bound, keeps every word a
334
+ // flush-to-zero device could drop below 2^-48 of the result.
335
+ fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {
336
+ return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&
337
+ {% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |
338
+ (bound == {{ type }}(0.0)));
339
+ }
340
+ {% endif %}
341
+ {% if N > 1 and add %}
342
+ // One compensated fold step without branches, for a caller that folds many
343
+ // steps before it can afford a branch. From finite words at exponent zero, a
344
+ // normal product and a finite low word imply every other condition of this
345
+ // arithmetic in scaled_value_add: the low word is finite only if the high word
346
+ // is, then the sum is, then the product, the weight and the value. A zero
347
+ // weight with a finite value is the step whose exact result is the accumulator
348
+ // itself. `exact` is false in any component whose step only scaled_value_add
349
+ // computes.
350
+ struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }
351
+ fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {
352
+ let w = {{ type }}(weight);
353
+ let product = fma(w, value, {{ type }}(0.0));
354
+ let sum = scaled_value_add_words(acc, product, fma(w, value, -product));
355
+ let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));
356
+ let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &
357
+ {% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));
358
+ return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),
359
+ fast | vec{{ N }}<bool>(keep));
360
+ }
361
+ {% endif %}
362
+ {% if add %}
363
+ fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {
364
+ {% if N > 1 %}
365
+ // Ordinary raw products use one vector compensated sum. Every exceptional
366
+ // component falls back to the same scalar exponent-aware implementation.
367
+ if (all(acc.exponent == {{ exponentType }}(0)) &&
368
+ all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&
369
+ all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {
370
+ let step = scaled_value_add_step(acc, weight, value);
371
+ if (all(step.exact)) { return step.value; }
372
+ }
373
+ {% endif %}
374
+ var result = scaled_value_zero();
375
+ {% for i in range(N) %}
376
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
377
+ 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));
378
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
379
+ {% endfor %}
380
+ return result;
381
+ }
382
+ {% endif %}
383
+ {% if rescale or tile %}
384
+ {% macro rescale_words() %}
385
+ let w = {{ type }}(correction);
386
+ let product = fma(w, acc.hi, {{ type }}(0.0));
387
+ let scaled = scaled_value_add_words(scaled_value_zero(), product,
388
+ fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));
389
+ let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);
390
+ let unit = correction == 1.0;
391
+ {% endmacro %}
392
+ {% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &
393
+ (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &
394
+ (zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &
395
+ (abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}
396
+ {% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),
397
+ select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}
398
+ {% endif %}
399
+ {% if tile %}
400
+ // scaled_value_rescale's vector path alone; `exact` is false where only its
401
+ // scalar path applies.
402
+ struct ScaledValueRescaled { value: ScaledValue, exact: bool }
403
+ fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {
404
+ {{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});
405
+ }
406
+ {% endif %}
407
+ {% if rescale %}
408
+ fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {
409
+ // From finite words at exponent zero, the scalar path below leaves zero
410
+ // words for a zero value or correction, the value itself for a unit
411
+ // correction, and otherwise this compensated product onto zero words when
412
+ // the product is normal and the low word finite (which bounds the rest, as
413
+ // in scaled_value_add_step).
414
+ {{ rescale_words() }} if ({{ rescale_vector_exact() }}) {
415
+ return {{ rescale_vector_value() }};
416
+ }
417
+ var result = scaled_value_zero();
418
+ {% for i in range(N) %}
419
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
420
+ let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));
421
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
422
+ {% endfor %}
423
+ return result;
424
+ }
425
+ {% endif %}
426
+ {% if merge %}
427
+ fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {
428
+ var result = scaled_value_zero();
429
+ {% for i in range(N) %}
430
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
431
+ 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 }}));
432
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
433
+ {% endfor %}
434
+ return result;
435
+ }
436
+ {% endif %}
437
+ fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {
438
+ // Words at exponent zero well inside the normal range, with a normal
439
+ // quotient: the scalar path below divides this same sum by this same
440
+ // denominator, each scaled by a power of two, so it rounds to this quotient
441
+ // wherever division is scale-invariant. Bounding the denominator above also
442
+ // keeps a division through its reciprocal clear of a subnormal reciprocal.
443
+ let d = {{ type }}(denominator);
444
+ let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);
445
+ let quotient = sum / d;
446
+ if (all((acc.exponent == {{ exponentType }}(0)) &
447
+ (abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &
448
+ (abs(acc.lo) <= abs(acc.hi)) &
449
+ (abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &
450
+ ((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {
451
+ return quotient;
452
+ }
453
+ var result = {{ type }}(0.0);
454
+ {% for i in range(N) %}
455
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
456
+ result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});
457
+ {% endfor %}
458
+ return result;
459
+ }
460
+ {% if align %}
461
+ fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {
462
+ var result = {{ exponentType }}(0);
463
+ {% for i in range(N) %}
464
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
465
+ result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));
466
+ {% endfor %}
467
+ return result;
468
+ }
469
+ fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {
470
+ var result = scaled_value_zero();
471
+ {% for i in range(N) %}
472
+ {% set c = "" if N == 1 else "[" ~ i ~ "]" %}
473
+ let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});
474
+ result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
475
+ {% endfor %}
476
+ return result;
477
+ }
478
+ {% endif %}
479
+ {% endmacro %}
480
+ {{ scaled_value_functions(foldType, rescale=true, lean=true, magnitudeOrdered=componentFold) }}
481
+ {% endif %}
482
  {% if coopQk %}
483
  var<workgroup> sval_sh: array<f32, WG>;
484
  {% endif %}
 
507
  var<workgroup> leaderMask: array<atomic<u32>, (WG + 31u) / 32u>;
508
  var<workgroup> combinedMD: vec2<f32>;
509
 
510
+ fn combine_partials(m: f32, d: f32, lidx: u32) -> vec2<f32> {
 
 
 
511
  let sgM = subgroupMax(m);
512
  // A lane with no elements contributes d == 0 (exact identity). A +inf
513
  // element made exp(inf - inf) = NaN stick in that lane's d; a NaN element
514
  // landed in d via exp(NaN); both survive the merge and are detected by the
515
  // code after the reduction.
516
  let sgD = subgroupAdd(d * exp_shift(m, sgM));
 
 
 
517
  if (subgroupElect()) {
518
  partialM[lidx] = sgM;
519
  partialD[lidx] = sgD;
 
581
  return vec4<f32>(key[indexV4]);
582
  }
583
 
584
+ {% if not componentFold %}
585
  fn load_value4(indexV4: u32) -> vec4<f32> {
586
  return vec4<f32>(value[indexV4]);
587
  }
588
+ {% endif %}
589
 
590
  @compute @workgroup_size(WG, 1, 1)
591
  fn main(
592
  @builtin(workgroup_id) wg: vec3<u32>,
593
+ @builtin(local_invocation_id) lid: vec3<u32>{% if coopQk %},
594
+ @builtin(subgroup_size) sgSize: u32,
595
+ @builtin(subgroup_invocation_id) sgLane: u32{% endif %}
596
  ) {
 
 
 
 
 
 
597
  {% if splitQueries %}
598
  let queryToken = wg.x / NUM_SPLITS;
599
  let split = wg.x % NUM_SPLITS;
 
606
  return;
607
  }
608
  let tid = lid.x;
609
+ {% if componentFold %}
610
+ var componentSum = scaled_value_zero();
611
+ {% elif NORMALIZED_VALUES %}
612
+ var value_error: array<vec4<f32>, {{ ceilDiv(headDimV4, splitKWorkgroupSize) }}>;
613
+ var value_exponent: array<vec4<i32>, {{ ceilDiv(headDimV4, splitKWorkgroupSize) }}>;
614
+ {% endif %}
615
+ {% if coopQk %}
616
+ // The fast Q.K body indexes keys by local subgroup blocks. Prove that every
617
+ // actual subgroup is full and owns exactly one such block before using it.
618
+ // Width alone does not prove membership. The online-softmax state is dead
619
+ // during this one-time check, so its mask and result carry the decision.
620
+ let physicalWidth = max(sgSize, 1u);
621
+ let population = subgroupBallot(true);
622
+ let populationCount = countOneBits(population.x) + countOneBits(population.y)
623
+ + countOneBits(population.z) + countOneBits(population.w);
624
+ let firstLocalIndex = subgroupBroadcastFirst(tid);
625
+ // Some drivers (Adreno 6xx) cannot create a pipeline that calls subgroupAll; a ballot builds wherever subgroups do.
626
+ // Every active member agrees when none disagrees: subgroupAll, expressed as a ballot.
627
+ let ownsLocalBlock = all(subgroupBallot(!(sgSize > 0u && populationCount == sgSize
628
+ && WG % physicalWidth == 0u && tid / physicalWidth == firstLocalIndex / physicalWidth
629
+ && sgLane == tid % physicalWidth)) == vec4<u32>(0u));
630
+ if (subgroupElect() && !ownsLocalBlock) {
631
+ atomicStore(&leaderMask[0], 1u);
632
+ }
633
+ workgroupBarrier();
634
+ if (tid == 0u) {
635
+ combinedMD = vec2<f32>(f32(atomicExchange(&leaderMask[0], 0u)), 0.0);
636
+ }
637
+ let coopQkAccepted = workgroupUniformLoad(&combinedMD).x == 0.0;
638
+ {% endif %}
639
  let hKv = h / (Q_HEADS / KV_HEADS);
640
  let cacheSeq = params.kvSeq;
641
  {% if cacheSeqlens %}
642
  // Buffer-sharing caches retain their capacity in the physical BNSH stride;
643
  // seqlens_k supplies the active end independently for each batch.
644
+ let kvSeq = {{ attn_seqlens_bound("cacheSeq", cacheSeqlensIndex, "1u" if seqlensQueryFloor | default(false) else "") }};
645
  {% else %}
646
  let kvSeq = cacheSeq;
647
  {% endif %}
 
668
  for (var d4 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {
669
  var qv = vec4<f32>(query[qBaseV4 + d4]);
670
  q_shared[d4] = qv;
671
+ {% if not (componentFold | default(false)) %}
672
  running_out[d4] = vec4<f32>(0.0);
673
+ {% endif %}
674
  }
675
  workgroupBarrier();
676
  let scale = scale_value();
677
  var runningMax = -FLT_MAX;
678
  var runningDenom = 0.0;
679
 
680
+ {% if singleKeyTile %}
681
+ let kjBase = splitStart;
682
+ if (kjBase < splitEnd) {
683
+ {% else %}
684
  var kjBase = splitStart;
685
  loop {
686
  if (kjBase >= splitEnd) {
687
  break;
688
  }
689
+ {% endif %}
690
  let kj = kjBase + tid;
691
  var keyAllowed = kj < splitEnd;
692
  let tileCount = min(WG, splitEnd - kjBase);
 
695
  var m = -FLT_MAX;
696
  var dPart = 0.0;
697
  {% if coopQk %}
698
+ if (coopQkAccepted) {
699
  // Cooperative Q.K: one subgroup per key, lanes splitting HEAD_DIM_V4, then a hardware
700
  // subgroupAdd — turns the per-thread HEAD_DIM_V4-long dependent dot chain into a few
701
  // strided vec4 dots + one reduce. Uniform trip count keeps subgroupAdd in uniform flow.
 
707
  let j = rr * sgPerWg + sgInWg;
708
  var accS: f32 = 0.0;
709
  if (j < tileCount) {
710
+ let kRowV4 = kvBaseV4 + {{ ("((kjBase + j) & " ~ RING_MASK ~ ")") if kvRing else "(kjBase + j)" }} * kvTokenStrideV4;
711
  for (var d4: u32 = lane; d4 < HEAD_DIM_V4; d4 = d4 + sgSize) {
712
  accS = accS + dot(q_shared[d4], load_key4(kRowV4 + d4));
713
  }
 
723
  m = score;
724
  dPart = 1.0;
725
  }
726
+ } else {
727
+ if (keyAllowed) {
728
+ let kRowV4 = kvBaseV4 + {{ ("(kj & " ~ RING_MASK ~ ")") if kvRing else "kj" }} * kvTokenStrideV4;
729
+ var acc: f32 = 0.0;
730
+ for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {
731
+ acc = acc + dot(q_shared[d4], load_key4(kRowV4 + d4));
732
+ }
733
+ score = acc * scale;
734
+ m = score;
735
+ dPart = 1.0;
736
+ }
737
+ }
738
  {% else %}
739
  if (keyAllowed) {
740
+ let kRowV4 = kvBaseV4 + {{ ("(kj & " ~ RING_MASK ~ ")") if kvRing else "kj" }} * kvTokenStrideV4;
741
  var acc: f32 = 0.0;
742
  for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {
743
  acc = acc + dot(q_shared[d4], load_key4(kRowV4 + d4));
 
747
  dPart = 1.0;
748
  }
749
  {% endif %}
750
+ {% if hasMask and not maskIsBool %}
751
  if (keyAllowed) {
752
  {% if splitQueries %}
753
  let maskQuery = queryToken;
 
773
  qk[(b * Q_HEADS + h) * kvSeq + kj] = {{ qkScalar }}(score);
774
  }
775
  {% endif %}
776
+ let tile = combine_partials(m, dPart, tid);
777
 
778
  // Merge one key tile's online-softmax (maximum, denominator) partial into the
779
  // running state, then store the per-key probabilities consumed by V accumulation.
 
789
  probs[tid] = prob;
790
  workgroupBarrier();
791
 
792
+ {% if NORMALIZED_VALUES %}
793
+ {% macro fold_value() -%}
794
+ {% set row = "kvBaseV4 + (kjBase + j) * kvTokenStrideV4" %}
795
+ {% if componentFold %}value[4u * ({{ row }}) + tid]{% else %}load_value4({{ row }} + d4){% endif %}
796
+ {%- endmacro %}
797
+ {% if componentFold %}
798
+ if (tid < HEAD_DIM) {
799
+ let start = scaled_value_rescale(componentSum, correction);
800
+ {% else %}
801
+ for (var d4 = tid; d4 < HEAD_DIM_V4; d4 += WG) {
802
+ let start = scaled_value_rescale(ScaledValue(running_out[d4], value_error[d4 / WG], value_exponent[d4 / WG]), correction);
803
+ {% endif %}
804
+ // A lean fold (scaled_value_lean_exact); a tile that leaves it folds
805
+ // again with scaled_value_add itself.
806
+ var acc = start;
807
+ var wLow = FLT_MAX;
808
+ var vLow = {{ foldType }}(FLT_MAX);
809
+ {% if boundValueNumerator | default(false) %}
810
+ var largest = abs(start.hi);
811
+ {% endif %}
812
+ for (var j = 0u; j < tileCount; j++) {
813
+ let w = probs[j];
814
+ let v = {{ fold_value() }};
815
+ wLow = select(wLow, min(wLow, w), w != 0.0);
816
+ vLow = scaled_value_nonzero_low(vLow, v);
817
+ {% if boundValueNumerator | default(false) %}
818
+ largest = max(largest, abs(v));
819
+ {% endif %}
820
+ acc = scaled_value_lean_step(acc, w, v);
821
+ }
822
+ if ({% if boundValueNumerator | default(false) %}any(largest > {{ foldType }}(VALUE_FAST_LIMIT)) || {% endif %}!scaled_value_lean_exact(start, acc, wLow, vLow)) {
823
+ acc = start;
824
+ for (var j = 0u; j < tileCount; j++) {
825
+ acc = scaled_value_add(acc, probs[j], {{ fold_value() }});
826
+ }
827
+ }
828
+ {% if componentFold %}
829
+ componentSum = acc;
830
+ {% else %}
831
+ running_out[d4] = acc.hi; value_error[d4 / WG] = acc.lo; value_exponent[d4 / WG] = acc.exponent;
832
+ {% endif %}
833
+ }
834
+ workgroupBarrier();
835
+ {% else %}
836
  {% if jSplitV %}
837
  // j-split V accumulation: thread (jg, d4v) sums keys j == jg mod
838
  // J_GROUPS for dim block d4v into a register, then the groups combine
 
845
  loop {
846
  if (jj >= tileCount) { break; }
847
  vacc = vacc + probs[jj] * load_value4(
848
+ kvBaseV4 + {{ ("((kjBase + jj) & " ~ RING_MASK ~ ")") if kvRing else "(kjBase + jj)" }} * kvTokenStrideV4 + d4v );
849
  jj = jj + J_GROUPS;
850
  }
851
  vacc_sh[tid] = vacc;
 
863
  var vSum = vec4<f32>(0.0);
864
  for (var i: u32 = 0u; i < tileCount; i = i + 1u) {
865
  vSum = vSum + probs[i] * load_value4(
866
+ kvBaseV4 + {{ ("((kjBase + i) & " ~ RING_MASK ~ ")") if kvRing else "(kjBase + i)" }} * kvTokenStrideV4 + d4 );
867
  }
868
  running_out[d4] = running_out[d4] * correction + vSum;
869
  }
870
  workgroupBarrier();
871
  {% endif %}
872
+ {% endif %}
873
 
874
+ {% if not singleKeyTile %}
875
  kjBase = kjBase + WG;
876
+ {% endif %}
877
  }
878
 
879
  {% if directOutput is defined and directOutput %}
880
+ // This direct epilogue handles one partition with no post-merge bias or gate.
881
+ // Preserve the merge's finite/nonfinite weighting and zero-row
882
  // behavior before narrowing once to the output dtype.
883
  let finalWeight = exp_shift(runningMax, max(-FLT_MAX, runningMax));
884
  let finalDenom = runningDenom * finalWeight;
885
  for (var d4: u32 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {
886
+ let finalOut = {% if NORMALIZED_VALUES %}scaled_value_mean(scaled_value_rescale(ScaledValue(running_out[d4], value_error[d4 / WG], value_exponent[d4 / WG]), finalWeight), finalDenom){% else %}running_out[d4] * finalWeight{% endif %};
887
  output[qBaseV4 + d4] = vec4<{{ "f16" if usesF16 else "f32" }}>(
888
+ select(vec4<f32>(0.0), finalOut{% if not NORMALIZED_VALUES %} / finalDenom{% endif %}, finalDenom > 0.0));
889
  }
890
+ {% else %}
891
+ {% if NORMALIZED_VALUES %}
892
+ // Emit normalized partial means for (b, h, split).
893
  {% else %}
894
  // Emit un-normalized partials for (b, h, split): the merge pass divides.
895
+ {% endif %}
896
  {% if splitQueries %}
897
  let partialBase = (((b * Q_SEQ + queryToken) * Q_HEADS + h) * NUM_SPLITS + split) * HEAD_DIM_V4;
898
  {% else %}
899
  let partialBase = ((b * Q_HEADS + h) * NUM_SPLITS + split) * HEAD_DIM_V4;
900
  {% endif %}
901
+ {% if componentFold %}
902
+ if (tid < HEAD_DIM) {
903
+ partial_out[4u * partialBase + tid] = scaled_value_mean(componentSum, runningDenom);
904
+ }
905
+ {% else %}
906
  for (var d4: u32 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {
907
+ partial_out[partialBase + d4] = {% if NORMALIZED_VALUES %}scaled_value_mean(ScaledValue(running_out[d4], value_error[d4 / WG], value_exponent[d4 / WG]), runningDenom){% else %}running_out[d4]{% endif %};
908
  }
909
+ {% endif %}
910
  if (tid == 0u) {
911
  {% if splitQueries %}
912
  let mdBase = ((b * Q_SEQ + queryToken) * Q_HEADS + h) * NUM_SPLITS + split;
build/webgpu/dmmha-present.wgsl.jinja CHANGED
@@ -1,21 +1,18 @@
1
- {% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}
2
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
3
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
4
  // per-axis workgroup fold width.
5
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
6
  if ({{ name }} >= {{ bound }}) {
7
  return;
8
- }{% endmacro %}
 
9
  {{ env.wgsl.resourceDeclarations }}
10
 
11
  // Cache maintenance for decode self attention, in two roles from one template.
12
  //
13
- // retain — copy the whole past buffer into the present buffer at capacity.
14
- // The rows beyond the live length are copied too: the operator's
15
- // contract is that present equals past everywhere except the one
16
- // appended row, and upstream's own kernel memcpys the full buffer.
17
- // The pass is a pure copy, so it declares `viewAlias`: it is elided
18
- // when `past_key` and `present_key` resolve to one buffer.
19
  // append — write this token's key and value rows at index past_sequence_length,
20
  // which arrives as tensor data and so is read here rather than baked.
21
  //
@@ -46,8 +43,8 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
46
  {% else %}
47
  // Each lane stages ITEMS words of each cache before storing any of them, so that
48
  // many loads are in flight before it has to wait. One word per lane leaves the
49
- // copy latency-bound wherever the caches stay resident in cache; where the copy is
50
- // DRAM-bound the depth is neutral. Consecutive lanes still read consecutive words;
51
  // the stride between a lane's own items is a whole workgroup. ITEMS is bounded so
52
  // the dispatch keeps a floor number of workgroups, since raising it divides them.
53
  const ITEMS: u32 = {{ itemsPerLane }}u;
 
1
+ {% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
2
  {% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
3
  // 2D-folded flat index: gid.y carries the high bits past the dispatch's
4
  // per-axis workgroup fold width.
5
  let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
6
  if ({{ name }} >= {{ bound }}) {
7
  return;
8
+ }
9
+ {% endmacro %}
10
  {{ env.wgsl.resourceDeclarations }}
11
 
12
  // Cache maintenance for decode self attention, in two roles from one template.
13
  //
14
+ // retain — copy the full past buffer, including rows beyond the live length;
15
+ // only the appended row differs in the present buffer.
 
 
 
 
16
  // append — write this token's key and value rows at index past_sequence_length,
17
  // which arrives as tensor data and so is read here rather than baked.
18
  //
 
43
  {% else %}
44
  // Each lane stages ITEMS words of each cache before storing any of them, so that
45
  // many loads are in flight before it has to wait. One word per lane leaves the
46
+ // copy latency-bound wherever the caches stay resident in cache. Consecutive lanes still read
47
+ // consecutive words;
48
  // the stride between a lane's own items is a whole workgroup. ITEMS is bounded so
49
  // the dispatch keeps a floor number of workgroups, since raising it divides them.
50
  const ITEMS: u32 = {{ itemsPerLane }}u;
build/webgpu/manifest.json CHANGED
@@ -1,1535 +1 @@
1
- {
2
- "domain": "com.microsoft",
3
- "name": "DecoderMaskedMultiHeadAttention",
4
- "sinceVersion": 1,
5
- "inputs": {
6
- "queryT": { "onnx": "query", "dtype": "T", "rank": 3 },
7
- "keyT": { "onnx": "key", "dtype": "T" },
8
- "valueT": { "onnx": "value", "dtype": "T" },
9
- "maskIndexT": { "onnx": "mask_index", "dtype": "M", "rank": 2, "optional": true },
10
- "attentionBiasT": { "onnx": "attention_bias", "dtype": "T", "rank": 4, "optional": true },
11
- "pastKeyT": { "onnx": "past_key", "dtype": "T", "rank": 4, "optional": true },
12
- "pastValueT": { "onnx": "past_value", "dtype": "T", "rank": 4, "optional": true },
13
- "pastSequenceLengthT": { "onnx": "past_sequence_length", "dtype": "M", "rank": 1, "optional": true }
14
- },
15
- "outputs": {
16
- "outputT": {
17
- "onnx": "output",
18
- "dtype": "T",
19
- "rank": 3,
20
- "shape": "[dim(shapes.queryT, 0), 1, dim(shapes.queryT, 2)]"
21
- },
22
- "presentKeyT": { "onnx": "present_key", "dtype": "T", "rank": 4, "optional": true, "shape": "shapes.pastKeyT" },
23
- "presentValueT": {
24
- "onnx": "present_value",
25
- "dtype": "T",
26
- "rank": 4,
27
- "optional": true,
28
- "shape": "shapes.pastValueT"
29
- },
30
- "qkT": {
31
- "onnx": "qk",
32
- "dtype": "QK",
33
- "rank": 4,
34
- "optional": true,
35
- "shape": "[dim(shapes.queryT, 0), attrs.num_heads, 1, dim(shapes.keyT, 2)]"
36
- }
37
- },
38
- "attributes": {
39
- "num_heads": {},
40
- "past_present_share_buffer": {},
41
- "scale": {},
42
- "mask_filter_value": { "default": -10000 },
43
- "output_qk": {}
44
- },
45
- "attributeConstraints": { "num_heads": { "required": true } },
46
- "typeConstraints": { "T": ["float32", "float16"], "QK": ["float32", "float16"], "M": ["int32"] },
47
- "tunables": {
48
- "WORKGROUP_SIZE": { "default": 256 },
49
- "COPY_WORKGROUP_SIZE": { "default": 256 },
50
- "COPY_ITEMS_PER_LANE": { "default": 8 },
51
- "COPY_MIN_WORKGROUPS": { "default": 64 },
52
- "MAX_SPLITS": { "default": 8 },
53
- "KEYS_PER_SPLIT": { "default": 256 },
54
- "THREAD_QK_OUTPUT_WORKGROUPS": { "default": 2 }
55
- },
56
- "derive": {
57
- "deviceWorkgroupCap": "min(device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX)",
58
- "narrowSubgroupRange": "has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize < device.adapterInfo.subgroupMaxSize and device.adapterInfo.subgroupMaxSize <= 16",
59
- "batchSize": "dim(shapes.queryT, 0)",
60
- "hiddenSize": "dim(shapes.queryT, 2)",
61
- "numHeads": "attrs.num_heads",
62
- "headSize": "hiddenSize / max(1, numHeads)",
63
- "headDimV4": "headSize / 4",
64
- "isCross": "not present.pastKeyT and not present.pastValueT",
65
- "crossKvLen": "dim(shapes.keyT, 2) if (isCross and ranks.keyT == 4) else 0",
66
- "cacheCapacity": "dim(shapes.pastKeyT, 2) if present.pastKeyT else 0",
67
- "physicalKeys": "crossKvLen if isCross else cacheCapacity",
68
- "qkRequested": "attrs.output_qk != 0 if has(attrs, \"output_qk\") else false",
69
- "floatDtypeOk": "(tensorDtypes.queryT == \"float32\" or tensorDtypes.queryT == \"float16\") and f16Ok(tensorDtypes.queryT) and tensorDtypes.keyT == tensorDtypes.queryT and tensorDtypes.valueT == tensorDtypes.queryT and tensorDtypes.outputT == tensorDtypes.queryT",
70
- "geometryOk": "ranks.queryT == 3 and dim(shapes.queryT, 1) == 1 and numHeads > 0 and hiddenSize > 0 and hiddenSize % numHeads == 0 and headSize > 0 and headSize % 4 == 0",
71
- "outputShapeOk": "ranks.outputT == 3 and dim(shapes.outputT, 0) == batchSize and dim(shapes.outputT, 1) == 1 and dim(shapes.outputT, 2) == hiddenSize",
72
- "workgroupOk": "tunables.WORKGROUP_SIZE > 0 and tunables.WORKGROUP_SIZE <= deviceWorkgroupCap and pow2ceil(tunables.WORKGROUP_SIZE) == tunables.WORKGROUP_SIZE and headDimV4 <= deviceWorkgroupCap and tunables.COPY_WORKGROUP_SIZE > 0 and tunables.COPY_WORKGROUP_SIZE <= deviceWorkgroupCap",
73
- "workgroupStorageOk": "32 * headDimV4 + 24 * tunables.WORKGROUP_SIZE <= device.limits.maxComputeWorkgroupStorageSize",
74
- "numSplits": "max(1, min(tunables.MAX_SPLITS, ceilDiv(physicalKeys, tunables.KEYS_PER_SPLIT)))",
75
- "splitScratchBytes": "batchSize * numHeads * numSplits * headSize * 4",
76
- "splitStatsBytes": "2 * batchSize * numHeads * numSplits * 4",
77
- "scratchFits": "splitScratchBytes <= device.limits.maxStorageBufferBindingSize and splitScratchBytes <= device.limits.maxBufferSize and splitStatsBytes <= device.limits.maxStorageBufferBindingSize and splitStatsBytes <= device.limits.maxBufferSize",
78
- "dispatchFits": "batchSize <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and numHeads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and numSplits <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)",
79
- "coreOk": "floatDtypeOk and geometryOk and outputShapeOk and workgroupOk and workgroupStorageOk and scratchFits and dispatchFits and physicalKeys > 0",
80
- "crossOk": "coreOk and isCross and ranks.keyT == 4 and ranks.valueT == 4 and dim(shapes.keyT, 0) == batchSize and dim(shapes.keyT, 1) == numHeads and dim(shapes.keyT, 3) == headSize and sameShape(shapes.valueT, shapes.keyT) and not present.attentionBiasT and not present.pastSequenceLengthT and not present.presentKeyT and not present.presentValueT",
81
- "cacheDtypeOk": "tensorDtypes.pastKeyT == tensorDtypes.queryT and tensorDtypes.pastValueT == tensorDtypes.queryT and tensorDtypes.presentKeyT == tensorDtypes.queryT and tensorDtypes.presentValueT == tensorDtypes.queryT and tensorDtypes.pastSequenceLengthT == \"int32\"",
82
- "selfOk": "coreOk and not isCross and present.pastValueT and present.pastSequenceLengthT and present.presentKeyT and present.presentValueT and attrs.past_present_share_buffer == 1 and ranks.keyT == 3 and ranks.valueT == 3 and dim(shapes.keyT, 0) == batchSize and dim(shapes.keyT, 1) == 1 and dim(shapes.keyT, 2) == hiddenSize and sameShape(shapes.valueT, shapes.keyT) and ranks.pastKeyT == 4 and dim(shapes.pastKeyT, 0) == batchSize and dim(shapes.pastKeyT, 1) == numHeads and dim(shapes.pastKeyT, 3) == headSize and cacheCapacity > 1 and sameShape(shapes.pastValueT, shapes.pastKeyT) and sameShape(shapes.presentKeyT, shapes.pastKeyT) and sameShape(shapes.presentValueT, shapes.pastKeyT) and numel(shapes.pastSequenceLengthT) == 1 and cacheDtypeOk and not present.qkT and not qkRequested",
83
- "maskShapeOk": "present.maskIndexT and ranks.maskIndexT == 2 and dim(shapes.maskIndexT, 0) == batchSize and tensorDtypes.maskIndexT == \"int32\" and (dim(shapes.maskIndexT, 1) == crossKvLen if isCross else (dim(shapes.maskIndexT, 1) >= 1 and dim(shapes.maskIndexT, 1) <= cacheCapacity))",
84
- "attnBiasShapeOk": "present.attentionBiasT and ranks.attentionBiasT == 4 and tensorDtypes.attentionBiasT == tensorDtypes.queryT and dim(shapes.attentionBiasT, 2) == 1 and (dim(shapes.attentionBiasT, 0) == 1 or dim(shapes.attentionBiasT, 0) == batchSize) and (dim(shapes.attentionBiasT, 1) == 1 or dim(shapes.attentionBiasT, 1) == numHeads) and dim(shapes.attentionBiasT, 3) >= 1 and dim(shapes.attentionBiasT, 3) <= cacheCapacity",
85
- "qkShapeOk": "present.qkT and qkRequested and ranks.qkT == 4 and (tensorDtypes.qkT == \"float32\" or tensorDtypes.qkT == \"float16\") and f16Ok(tensorDtypes.qkT) and dim(shapes.qkT, 0) == batchSize and dim(shapes.qkT, 1) == numHeads and dim(shapes.qkT, 2) == 1 and dim(shapes.qkT, 3) == crossKvLen",
86
- "crossPlainOk": "crossOk and not present.maskIndexT and not present.qkT and not qkRequested",
87
- "crossMaskOk": "crossOk and maskShapeOk and not present.qkT and not qkRequested",
88
- "crossQkOk": "crossOk and not present.maskIndexT and qkShapeOk",
89
- "crossMaskQkOk": "crossOk and maskShapeOk and qkShapeOk",
90
- "selfPlainOk": "selfOk and not present.maskIndexT and not present.attentionBiasT",
91
- "selfMaskOk": "selfOk and maskShapeOk and not present.attentionBiasT",
92
- "selfBiasOk": "selfOk and not present.maskIndexT and attnBiasShapeOk",
93
- "selfMaskBiasOk": "selfOk and maskShapeOk and attnBiasShapeOk",
94
- "subgroupSplitKOk": "device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize >= 8 and device.adapterInfo.subgroupMinSize % 8 == 0 and device.adapterInfo.subgroupMaxSize % 8 == 0 and device.adapterInfo.subgroupMaxSize <= tunables.WORKGROUP_SIZE and tunables.WORKGROUP_SIZE % device.adapterInfo.subgroupMinSize == 0 and tunables.WORKGROUP_SIZE % device.adapterInfo.subgroupMaxSize == 0",
95
- "subgroupSplitKPreferred": "subgroupSplitKOk and not narrowSubgroupRange",
96
- "attnScalar": "\"f16\" if tensorDtypes.queryT == \"float16\" else \"f32\"",
97
- "attnVec4": "\"vec4<f16>\" if tensorDtypes.queryT == \"float16\" else \"vec4<f32>\"",
98
- "attnMaskElement": "\"f16\" if tensorDtypes.queryT == \"float16\" else \"f32\"",
99
- "qkScalarType": "\"f16\" if tensorDtypes.qkT == \"float16\" else \"f32\"",
100
- "attnBiasWidth": "dim(shapes.attentionBiasT, 3) if present.attentionBiasT else 0",
101
- "attnBiasHeads": "dim(shapes.attentionBiasT, 1) if present.attentionBiasT else 0",
102
- "attnBiasBatch": "dim(shapes.attentionBiasT, 0) if present.attentionBiasT else 0",
103
- "cacheWordsV4": "numel(shapes.pastKeyT) / 4 if present.pastKeyT else 0",
104
- "retainBlockWords": "tunables.COPY_WORKGROUP_SIZE * tunables.COPY_MIN_WORKGROUPS",
105
- "retainOccupancyCap": "pick([[cacheWordsV4 >= 8 * retainBlockWords, 8], [cacheWordsV4 >= 4 * retainBlockWords, 4], [cacheWordsV4 >= 2 * retainBlockWords, 2]], 1)",
106
- "retainItemsPerLane": "max(1, min(tunables.COPY_ITEMS_PER_LANE, retainOccupancyCap))"
107
- },
108
- "bindings": {
109
- "query": { "arg": "queryT", "elementType": "$attnVec4" },
110
- "key_cross": { "arg": "keyT", "name": "key", "elementType": "$attnVec4" },
111
- "value_cross": { "arg": "valueT", "name": "value", "elementType": "$attnVec4" },
112
- "key_cache": { "arg": "presentKeyT", "name": "key", "buffer": "read-only-storage", "elementType": "$attnVec4" },
113
- "value_cache": {
114
- "arg": "presentValueT",
115
- "name": "value",
116
- "buffer": "read-only-storage",
117
- "elementType": "$attnVec4"
118
- },
119
- "key_row": { "arg": "keyT", "name": "key", "elementType": "$attnVec4" },
120
- "value_row": { "arg": "valueT", "name": "value", "elementType": "$attnVec4" },
121
- "past_key": { "arg": "pastKeyT", "elementType": "$attnVec4" },
122
- "past_value": { "arg": "pastValueT", "elementType": "$attnVec4" },
123
- "present_key": { "arg": "presentKeyT", "elementType": "$attnVec4" },
124
- "present_value": { "arg": "presentValueT", "elementType": "$attnVec4" },
125
- "seqlens_k": { "arg": "pastSequenceLengthT", "name": "seqlens_k", "elementType": "i32" },
126
- "past_sequence_length": { "arg": "pastSequenceLengthT", "elementType": "i32" },
127
- "key_pad_mask": { "arg": "maskIndexT", "name": "key_pad_mask", "elementType": "i32" },
128
- "attn_mask": { "arg": "attentionBiasT", "name": "attn_mask", "elementType": "$attnMaskElement" },
129
- "qk": { "arg": "qkT", "elementType": "$qkScalarType" },
130
- "partial_out": { "scratch": "partialOut", "elementType": "vec4<f32>" },
131
- "partial_stats": { "scratch": "partialStats", "elementType": "vec2<f32>" },
132
- "partial_out_read": {
133
- "scratch": "partialOut",
134
- "name": "partial_out",
135
- "buffer": "read-only-storage",
136
- "elementType": "vec4<f32>"
137
- },
138
- "partial_stats_read": {
139
- "scratch": "partialStats",
140
- "name": "partial_stats",
141
- "buffer": "read-only-storage",
142
- "elementType": "vec2<f32>"
143
- },
144
- "output": { "arg": "outputT", "elementType": "$attnVec4" },
145
- "params_cross": {
146
- "name": "params",
147
- "struct": [
148
- { "name": "kvSeq", "type": "u32", "value": "crossKvLen" },
149
- { "name": "scale", "type": "f32", "value": "attrs.scale if has(attrs, \"scale\") else 0" }
150
- ]
151
- },
152
- "params_self": {
153
- "name": "params",
154
- "struct": [
155
- { "name": "kvSeq", "type": "u32", "value": "cacheCapacity" },
156
- { "name": "scale", "type": "f32", "value": "attrs.scale if has(attrs, \"scale\") else 0" }
157
- ]
158
- },
159
- "params_self_bias": {
160
- "name": "params",
161
- "struct": [
162
- { "name": "kvSeq", "type": "u32", "value": "cacheCapacity" },
163
- { "name": "scale", "type": "f32", "value": "attrs.scale if has(attrs, \"scale\") else 0" },
164
- {
165
- "name": "maskBatchStride",
166
- "type": "u32",
167
- "value": "0 if attnBiasBatch == 1 else attnBiasHeads * attnBiasWidth"
168
- },
169
- { "name": "maskHeadStride", "type": "u32", "value": "0 if attnBiasHeads == 1 else attnBiasWidth" },
170
- { "name": "maskSeqStride", "type": "u32", "value": "0" }
171
- ]
172
- },
173
- "params_retain": {
174
- "name": "params",
175
- "struct": [{ "name": "countV4", "type": "u32", "value": "numel(shapes.pastKeyT) / 4" }]
176
- },
177
- "params_append": {
178
- "name": "params",
179
- "struct": [
180
- { "name": "rowCountV4", "type": "u32", "value": "batchSize * hiddenSize / 4" },
181
- { "name": "capacity", "type": "u32", "value": "cacheCapacity" }
182
- ]
183
- }
184
- },
185
- "variants": [
186
- {
187
- "id": "cross_direct",
188
- "priority": 31,
189
- "when": ["crossPlainOk", "subgroupSplitKOk", "numSplits == 1"],
190
- "demoteWhen": ["not subgroupSplitKPreferred"],
191
- "requires": { "features": ["subgroups"] },
192
- "passes": [
193
- {
194
- "id": "split_attention",
195
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitK",
196
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
197
- "derive": {
198
- "layout": "\"bhsd\"",
199
- "splitQueries": false,
200
- "qNumHeads": "numHeads",
201
- "kvNumHeads": "numHeads",
202
- "headDim": "headSize",
203
- "headDimV4": "headDimV4",
204
- "numSplits": "numSplits",
205
- "usesF16": "tensorDtypes.queryT == \"float16\"",
206
- "hasKeyPadMask": "present.maskIndexT",
207
- "emitQk": "present.qkT",
208
- "useSubgroups": true,
209
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
210
- },
211
- "bindings": ["query", "key_cross", "value_cross", "params_cross", "output"],
212
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
213
- }
214
- ],
215
- "derive": { "directOutput": true }
216
- },
217
- {
218
- "id": "cross",
219
- "priority": 30,
220
- "when": ["crossPlainOk", "subgroupSplitKOk"],
221
- "demoteWhen": ["not subgroupSplitKPreferred"],
222
- "requires": { "features": ["subgroups"] },
223
- "intermediates": [
224
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
225
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
226
- ],
227
- "passes": [
228
- {
229
- "id": "split_attention",
230
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitK",
231
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
232
- "derive": {
233
- "layout": "\"bhsd\"",
234
- "splitQueries": false,
235
- "qNumHeads": "numHeads",
236
- "kvNumHeads": "numHeads",
237
- "headDim": "headSize",
238
- "headDimV4": "headDimV4",
239
- "numSplits": "numSplits",
240
- "usesF16": "tensorDtypes.queryT == \"float16\"",
241
- "hasKeyPadMask": "present.maskIndexT",
242
- "emitQk": "present.qkT",
243
- "useSubgroups": true,
244
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
245
- },
246
- "bindings": ["query", "key_cross", "value_cross", "partial_out", "partial_stats", "params_cross"],
247
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
248
- },
249
- {
250
- "id": "merge",
251
- "name": "DecoderMaskedMultiHeadAttention.CrossMerge",
252
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
253
- "derive": {
254
- "layout": "\"bhsd\"",
255
- "splitQueries": false,
256
- "scalar": "attnScalar",
257
- "qNumHeads": "numHeads",
258
- "headDimV4": "headDimV4",
259
- "numSplits": "numSplits"
260
- },
261
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
262
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
263
- }
264
- ]
265
- },
266
- {
267
- "id": "cross_qk_direct",
268
- "priority": 31,
269
- "when": ["crossQkOk", "subgroupSplitKOk", "numSplits == 1"],
270
- "demoteWhen": ["not subgroupSplitKPreferred"],
271
- "requires": { "features": ["subgroups"] },
272
- "passes": [
273
- {
274
- "id": "split_attention",
275
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKQk",
276
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
277
- "derive": {
278
- "layout": "\"bhsd\"",
279
- "splitQueries": false,
280
- "qNumHeads": "numHeads",
281
- "kvNumHeads": "numHeads",
282
- "headDim": "headSize",
283
- "headDimV4": "headDimV4",
284
- "numSplits": "numSplits",
285
- "usesF16": "tensorDtypes.queryT == \"float16\"",
286
- "hasKeyPadMask": "present.maskIndexT",
287
- "emitQk": "present.qkT",
288
- "qkScalar": "qkScalarType",
289
- "useSubgroups": true,
290
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
291
- },
292
- "bindings": ["query", "key_cross", "value_cross", "qk", "params_cross", "output"],
293
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
294
- }
295
- ],
296
- "derive": { "directOutput": true }
297
- },
298
- {
299
- "id": "cross_qk",
300
- "priority": 30,
301
- "when": ["crossQkOk", "subgroupSplitKOk"],
302
- "demoteWhen": ["not subgroupSplitKPreferred"],
303
- "requires": { "features": ["subgroups"] },
304
- "intermediates": [
305
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
306
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
307
- ],
308
- "passes": [
309
- {
310
- "id": "split_attention",
311
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKQk",
312
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
313
- "derive": {
314
- "layout": "\"bhsd\"",
315
- "splitQueries": false,
316
- "qNumHeads": "numHeads",
317
- "kvNumHeads": "numHeads",
318
- "headDim": "headSize",
319
- "headDimV4": "headDimV4",
320
- "numSplits": "numSplits",
321
- "usesF16": "tensorDtypes.queryT == \"float16\"",
322
- "hasKeyPadMask": "present.maskIndexT",
323
- "emitQk": "present.qkT",
324
- "qkScalar": "qkScalarType",
325
- "useSubgroups": true,
326
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
327
- },
328
- "bindings": ["query", "key_cross", "value_cross", "qk", "partial_out", "partial_stats", "params_cross"],
329
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
330
- },
331
- {
332
- "id": "merge",
333
- "name": "DecoderMaskedMultiHeadAttention.CrossMerge",
334
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
335
- "derive": {
336
- "layout": "\"bhsd\"",
337
- "splitQueries": false,
338
- "scalar": "attnScalar",
339
- "qNumHeads": "numHeads",
340
- "headDimV4": "headDimV4",
341
- "numSplits": "numSplits"
342
- },
343
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
344
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
345
- }
346
- ]
347
- },
348
- {
349
- "id": "cross_mask_direct",
350
- "priority": 31,
351
- "when": ["crossMaskOk", "subgroupSplitKOk", "numSplits == 1"],
352
- "demoteWhen": ["not subgroupSplitKPreferred"],
353
- "requires": { "features": ["subgroups"] },
354
- "passes": [
355
- {
356
- "id": "split_attention",
357
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitK",
358
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
359
- "derive": {
360
- "layout": "\"bhsd\"",
361
- "splitQueries": false,
362
- "qNumHeads": "numHeads",
363
- "kvNumHeads": "numHeads",
364
- "headDim": "headSize",
365
- "headDimV4": "headDimV4",
366
- "numSplits": "numSplits",
367
- "usesF16": "tensorDtypes.queryT == \"float16\"",
368
- "hasKeyPadMask": "present.maskIndexT",
369
- "maskFilterValue": "attrs.mask_filter_value",
370
- "emitQk": "present.qkT",
371
- "useSubgroups": true,
372
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
373
- },
374
- "bindings": ["query", "key_cross", "value_cross", "key_pad_mask", "params_cross", "output"],
375
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
376
- }
377
- ],
378
- "derive": { "directOutput": true }
379
- },
380
- {
381
- "id": "cross_mask",
382
- "priority": 30,
383
- "when": ["crossMaskOk", "subgroupSplitKOk"],
384
- "demoteWhen": ["not subgroupSplitKPreferred"],
385
- "requires": { "features": ["subgroups"] },
386
- "intermediates": [
387
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
388
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
389
- ],
390
- "passes": [
391
- {
392
- "id": "split_attention",
393
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitK",
394
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
395
- "derive": {
396
- "layout": "\"bhsd\"",
397
- "splitQueries": false,
398
- "qNumHeads": "numHeads",
399
- "kvNumHeads": "numHeads",
400
- "headDim": "headSize",
401
- "headDimV4": "headDimV4",
402
- "numSplits": "numSplits",
403
- "usesF16": "tensorDtypes.queryT == \"float16\"",
404
- "hasKeyPadMask": "present.maskIndexT",
405
- "maskFilterValue": "attrs.mask_filter_value",
406
- "emitQk": "present.qkT",
407
- "useSubgroups": true,
408
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
409
- },
410
- "bindings": ["query", "key_cross", "value_cross", "key_pad_mask", "partial_out", "partial_stats", "params_cross"],
411
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
412
- },
413
- {
414
- "id": "merge",
415
- "name": "DecoderMaskedMultiHeadAttention.CrossMerge",
416
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
417
- "derive": {
418
- "layout": "\"bhsd\"",
419
- "splitQueries": false,
420
- "scalar": "attnScalar",
421
- "qNumHeads": "numHeads",
422
- "headDimV4": "headDimV4",
423
- "numSplits": "numSplits"
424
- },
425
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
426
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
427
- }
428
- ]
429
- },
430
- {
431
- "id": "cross_mask_qk_direct",
432
- "priority": 31,
433
- "when": ["crossMaskQkOk", "subgroupSplitKOk", "numSplits == 1"],
434
- "demoteWhen": ["not subgroupSplitKPreferred"],
435
- "requires": { "features": ["subgroups"] },
436
- "passes": [
437
- {
438
- "id": "split_attention",
439
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKQk",
440
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
441
- "derive": {
442
- "layout": "\"bhsd\"",
443
- "splitQueries": false,
444
- "qNumHeads": "numHeads",
445
- "kvNumHeads": "numHeads",
446
- "headDim": "headSize",
447
- "headDimV4": "headDimV4",
448
- "numSplits": "numSplits",
449
- "usesF16": "tensorDtypes.queryT == \"float16\"",
450
- "hasKeyPadMask": "present.maskIndexT",
451
- "maskFilterValue": "attrs.mask_filter_value",
452
- "emitQk": "present.qkT",
453
- "qkScalar": "qkScalarType",
454
- "useSubgroups": true,
455
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
456
- },
457
- "bindings": ["query", "key_cross", "value_cross", "key_pad_mask", "qk", "params_cross", "output"],
458
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
459
- }
460
- ],
461
- "derive": { "directOutput": true }
462
- },
463
- {
464
- "id": "cross_mask_qk",
465
- "priority": 30,
466
- "when": ["crossMaskQkOk", "subgroupSplitKOk"],
467
- "demoteWhen": ["not subgroupSplitKPreferred"],
468
- "requires": { "features": ["subgroups"] },
469
- "intermediates": [
470
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
471
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
472
- ],
473
- "passes": [
474
- {
475
- "id": "split_attention",
476
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKQk",
477
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
478
- "derive": {
479
- "layout": "\"bhsd\"",
480
- "splitQueries": false,
481
- "qNumHeads": "numHeads",
482
- "kvNumHeads": "numHeads",
483
- "headDim": "headSize",
484
- "headDimV4": "headDimV4",
485
- "numSplits": "numSplits",
486
- "usesF16": "tensorDtypes.queryT == \"float16\"",
487
- "hasKeyPadMask": "present.maskIndexT",
488
- "maskFilterValue": "attrs.mask_filter_value",
489
- "emitQk": "present.qkT",
490
- "qkScalar": "qkScalarType",
491
- "useSubgroups": true,
492
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
493
- },
494
- "bindings": ["query", "key_cross", "value_cross", "key_pad_mask", "qk", "partial_out", "partial_stats", "params_cross"],
495
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
496
- },
497
- {
498
- "id": "merge",
499
- "name": "DecoderMaskedMultiHeadAttention.CrossMerge",
500
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
501
- "derive": {
502
- "layout": "\"bhsd\"",
503
- "splitQueries": false,
504
- "scalar": "attnScalar",
505
- "qNumHeads": "numHeads",
506
- "headDimV4": "headDimV4",
507
- "numSplits": "numSplits"
508
- },
509
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
510
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
511
- }
512
- ]
513
- },
514
- {
515
- "id": "cross_nosg_direct",
516
- "priority": 21,
517
- "when": ["crossPlainOk", "numSplits == 1"],
518
- "requires": {},
519
- "passes": [
520
- {
521
- "id": "split_attention",
522
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKNoSg",
523
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
524
- "derive": {
525
- "layout": "\"bhsd\"",
526
- "splitQueries": false,
527
- "qNumHeads": "numHeads",
528
- "kvNumHeads": "numHeads",
529
- "headDim": "headSize",
530
- "headDimV4": "headDimV4",
531
- "numSplits": "numSplits",
532
- "usesF16": "tensorDtypes.queryT == \"float16\"",
533
- "hasKeyPadMask": "present.maskIndexT",
534
- "emitQk": "present.qkT",
535
- "useSubgroups": false,
536
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
537
- },
538
- "bindings": ["query", "key_cross", "value_cross", "params_cross", "output"],
539
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
540
- }
541
- ],
542
- "derive": { "directOutput": true }
543
- },
544
- {
545
- "id": "cross_nosg",
546
- "priority": 20,
547
- "when": ["crossPlainOk"],
548
- "requires": {},
549
- "intermediates": [
550
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
551
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
552
- ],
553
- "passes": [
554
- {
555
- "id": "split_attention",
556
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKNoSg",
557
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
558
- "derive": {
559
- "layout": "\"bhsd\"",
560
- "splitQueries": false,
561
- "qNumHeads": "numHeads",
562
- "kvNumHeads": "numHeads",
563
- "headDim": "headSize",
564
- "headDimV4": "headDimV4",
565
- "numSplits": "numSplits",
566
- "usesF16": "tensorDtypes.queryT == \"float16\"",
567
- "hasKeyPadMask": "present.maskIndexT",
568
- "emitQk": "present.qkT",
569
- "useSubgroups": false,
570
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
571
- },
572
- "bindings": ["query", "key_cross", "value_cross", "partial_out", "partial_stats", "params_cross"],
573
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
574
- },
575
- {
576
- "id": "merge",
577
- "name": "DecoderMaskedMultiHeadAttention.CrossMergeNoSg",
578
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
579
- "derive": {
580
- "layout": "\"bhsd\"",
581
- "splitQueries": false,
582
- "scalar": "attnScalar",
583
- "qNumHeads": "numHeads",
584
- "headDimV4": "headDimV4",
585
- "numSplits": "numSplits"
586
- },
587
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
588
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
589
- }
590
- ]
591
- },
592
- {
593
- "id": "cross_qk_nosg_direct",
594
- "priority": 21,
595
- "when": ["crossQkOk", "numSplits == 1"],
596
- "requires": {},
597
- "passes": [
598
- {
599
- "id": "split_attention",
600
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKQkNoSg",
601
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
602
- "derive": {
603
- "layout": "\"bhsd\"",
604
- "splitQueries": false,
605
- "qNumHeads": "numHeads",
606
- "kvNumHeads": "numHeads",
607
- "headDim": "headSize",
608
- "headDimV4": "headDimV4",
609
- "numSplits": "numSplits",
610
- "usesF16": "tensorDtypes.queryT == \"float16\"",
611
- "hasKeyPadMask": "present.maskIndexT",
612
- "emitQk": "present.qkT",
613
- "qkScalar": "qkScalarType",
614
- "useSubgroups": false,
615
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
616
- },
617
- "bindings": ["query", "key_cross", "value_cross", "qk", "params_cross", "output"],
618
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
619
- }
620
- ],
621
- "derive": { "directOutput": true }
622
- },
623
- {
624
- "id": "cross_qk_nosg",
625
- "priority": 20,
626
- "when": ["crossQkOk"],
627
- "requires": {},
628
- "intermediates": [
629
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
630
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
631
- ],
632
- "passes": [
633
- {
634
- "id": "split_attention",
635
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKQkNoSg",
636
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
637
- "derive": {
638
- "layout": "\"bhsd\"",
639
- "splitQueries": false,
640
- "qNumHeads": "numHeads",
641
- "kvNumHeads": "numHeads",
642
- "headDim": "headSize",
643
- "headDimV4": "headDimV4",
644
- "numSplits": "numSplits",
645
- "usesF16": "tensorDtypes.queryT == \"float16\"",
646
- "hasKeyPadMask": "present.maskIndexT",
647
- "emitQk": "present.qkT",
648
- "qkScalar": "qkScalarType",
649
- "useSubgroups": false,
650
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
651
- },
652
- "bindings": ["query", "key_cross", "value_cross", "qk", "partial_out", "partial_stats", "params_cross"],
653
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
654
- },
655
- {
656
- "id": "merge",
657
- "name": "DecoderMaskedMultiHeadAttention.CrossMergeNoSg",
658
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
659
- "derive": {
660
- "layout": "\"bhsd\"",
661
- "splitQueries": false,
662
- "scalar": "attnScalar",
663
- "qNumHeads": "numHeads",
664
- "headDimV4": "headDimV4",
665
- "numSplits": "numSplits"
666
- },
667
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
668
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
669
- }
670
- ]
671
- },
672
- {
673
- "id": "cross_mask_nosg_direct",
674
- "priority": 21,
675
- "when": ["crossMaskOk", "numSplits == 1"],
676
- "requires": {},
677
- "passes": [
678
- {
679
- "id": "split_attention",
680
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKNoSg",
681
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
682
- "derive": {
683
- "layout": "\"bhsd\"",
684
- "splitQueries": false,
685
- "qNumHeads": "numHeads",
686
- "kvNumHeads": "numHeads",
687
- "headDim": "headSize",
688
- "headDimV4": "headDimV4",
689
- "numSplits": "numSplits",
690
- "usesF16": "tensorDtypes.queryT == \"float16\"",
691
- "hasKeyPadMask": "present.maskIndexT",
692
- "maskFilterValue": "attrs.mask_filter_value",
693
- "emitQk": "present.qkT",
694
- "useSubgroups": false,
695
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
696
- },
697
- "bindings": ["query", "key_cross", "value_cross", "key_pad_mask", "params_cross", "output"],
698
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
699
- }
700
- ],
701
- "derive": { "directOutput": true }
702
- },
703
- {
704
- "id": "cross_mask_nosg",
705
- "priority": 20,
706
- "when": ["crossMaskOk"],
707
- "requires": {},
708
- "intermediates": [
709
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
710
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
711
- ],
712
- "passes": [
713
- {
714
- "id": "split_attention",
715
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKNoSg",
716
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
717
- "derive": {
718
- "layout": "\"bhsd\"",
719
- "splitQueries": false,
720
- "qNumHeads": "numHeads",
721
- "kvNumHeads": "numHeads",
722
- "headDim": "headSize",
723
- "headDimV4": "headDimV4",
724
- "numSplits": "numSplits",
725
- "usesF16": "tensorDtypes.queryT == \"float16\"",
726
- "hasKeyPadMask": "present.maskIndexT",
727
- "maskFilterValue": "attrs.mask_filter_value",
728
- "emitQk": "present.qkT",
729
- "useSubgroups": false,
730
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
731
- },
732
- "bindings": ["query", "key_cross", "value_cross", "key_pad_mask", "partial_out", "partial_stats", "params_cross"],
733
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
734
- },
735
- {
736
- "id": "merge",
737
- "name": "DecoderMaskedMultiHeadAttention.CrossMergeNoSg",
738
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
739
- "derive": {
740
- "layout": "\"bhsd\"",
741
- "splitQueries": false,
742
- "scalar": "attnScalar",
743
- "qNumHeads": "numHeads",
744
- "headDimV4": "headDimV4",
745
- "numSplits": "numSplits"
746
- },
747
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
748
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
749
- }
750
- ]
751
- },
752
- {
753
- "id": "cross_mask_qk_nosg_direct",
754
- "priority": 21,
755
- "when": ["crossMaskQkOk", "numSplits == 1"],
756
- "requires": {},
757
- "passes": [
758
- {
759
- "id": "split_attention",
760
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKQkNoSg",
761
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
762
- "derive": {
763
- "layout": "\"bhsd\"",
764
- "splitQueries": false,
765
- "qNumHeads": "numHeads",
766
- "kvNumHeads": "numHeads",
767
- "headDim": "headSize",
768
- "headDimV4": "headDimV4",
769
- "numSplits": "numSplits",
770
- "usesF16": "tensorDtypes.queryT == \"float16\"",
771
- "hasKeyPadMask": "present.maskIndexT",
772
- "maskFilterValue": "attrs.mask_filter_value",
773
- "emitQk": "present.qkT",
774
- "qkScalar": "qkScalarType",
775
- "useSubgroups": false,
776
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
777
- },
778
- "bindings": ["query", "key_cross", "value_cross", "key_pad_mask", "qk", "params_cross", "output"],
779
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
780
- }
781
- ],
782
- "derive": { "directOutput": true }
783
- },
784
- {
785
- "id": "cross_mask_qk_nosg",
786
- "priority": 20,
787
- "when": ["crossMaskQkOk"],
788
- "requires": {},
789
- "intermediates": [
790
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
791
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
792
- ],
793
- "passes": [
794
- {
795
- "id": "split_attention",
796
- "name": "DecoderMaskedMultiHeadAttention.CrossSplitKQkNoSg",
797
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
798
- "derive": {
799
- "layout": "\"bhsd\"",
800
- "splitQueries": false,
801
- "qNumHeads": "numHeads",
802
- "kvNumHeads": "numHeads",
803
- "headDim": "headSize",
804
- "headDimV4": "headDimV4",
805
- "numSplits": "numSplits",
806
- "usesF16": "tensorDtypes.queryT == \"float16\"",
807
- "hasKeyPadMask": "present.maskIndexT",
808
- "maskFilterValue": "attrs.mask_filter_value",
809
- "emitQk": "present.qkT",
810
- "qkScalar": "qkScalarType",
811
- "useSubgroups": false,
812
- "allowCooperativeQk": "not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"
813
- },
814
- "bindings": ["query", "key_cross", "value_cross", "key_pad_mask", "qk", "partial_out", "partial_stats", "params_cross"],
815
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
816
- },
817
- {
818
- "id": "merge",
819
- "name": "DecoderMaskedMultiHeadAttention.CrossMergeNoSg",
820
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
821
- "derive": {
822
- "layout": "\"bhsd\"",
823
- "splitQueries": false,
824
- "scalar": "attnScalar",
825
- "qNumHeads": "numHeads",
826
- "headDimV4": "headDimV4",
827
- "numSplits": "numSplits"
828
- },
829
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
830
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
831
- }
832
- ]
833
- },
834
- {
835
- "id": "self",
836
- "priority": 30,
837
- "when": ["selfPlainOk", "subgroupSplitKOk"],
838
- "demoteWhen": ["not subgroupSplitKPreferred"],
839
- "requires": { "features": ["subgroups"] },
840
- "intermediates": [
841
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
842
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
843
- ],
844
- "passes": [
845
- {
846
- "id": "present_retain",
847
- "name": "DecoderMaskedMultiHeadAttention.PresentRetain",
848
- "shader": "dmmha-present.wgsl.jinja",
849
- "derive": {
850
- "appendRow": false,
851
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
852
- "itemsPerLane": "retainItemsPerLane",
853
- "cacheScalar": "attnScalar"
854
- },
855
- "bindings": ["past_key", "past_value", "present_key", "present_value", "params_retain"],
856
- "dispatch": {
857
- "x": "min(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
858
- "y": "ceilDiv(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
859
- "z": 1
860
- },
861
- "viewAlias": [
862
- { "input": "past_key", "output": "present_key" },
863
- { "input": "past_value", "output": "present_value" }
864
- ]
865
- },
866
- {
867
- "id": "present_append",
868
- "name": "DecoderMaskedMultiHeadAttention.PresentAppend",
869
- "shader": "dmmha-present.wgsl.jinja",
870
- "derive": {
871
- "appendRow": true,
872
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
873
- "headSizeV4": "headDimV4",
874
- "numHeads": "numHeads"
875
- },
876
- "bindings": ["key_row", "value_row", "past_sequence_length", "present_key", "present_value", "params_append"],
877
- "dispatch": {
878
- "x": "min(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
879
- "y": "ceilDiv(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
880
- "z": 1
881
- }
882
- },
883
- {
884
- "id": "split_attention",
885
- "name": "DecoderMaskedMultiHeadAttention.SelfSplitK",
886
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
887
- "derive": {
888
- "layout": "\"bhsd\"",
889
- "splitQueries": false,
890
- "qNumHeads": "numHeads",
891
- "kvNumHeads": "numHeads",
892
- "headDim": "headSize",
893
- "headDimV4": "headDimV4",
894
- "numSplits": "numSplits",
895
- "usesF16": "tensorDtypes.queryT == \"float16\"",
896
- "cacheSeqlens": true,
897
- "cacheSeqlensIndex": "\"0u\"",
898
- "hasKeyPadMask": "present.maskIndexT",
899
- "hasMask": "present.attentionBiasT"
900
- },
901
- "bindings": ["query", "key_cache", "value_cache", "seqlens_k", "partial_out", "partial_stats", "params_self"],
902
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
903
- },
904
- {
905
- "id": "merge",
906
- "name": "DecoderMaskedMultiHeadAttention.SelfMerge",
907
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
908
- "derive": {
909
- "layout": "\"bhsd\"",
910
- "splitQueries": false,
911
- "scalar": "attnScalar",
912
- "qNumHeads": "numHeads",
913
- "headDimV4": "headDimV4",
914
- "numSplits": "numSplits"
915
- },
916
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
917
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
918
- }
919
- ]
920
- },
921
- {
922
- "id": "self_bias",
923
- "priority": 30,
924
- "when": ["selfBiasOk", "subgroupSplitKOk"],
925
- "demoteWhen": ["not subgroupSplitKPreferred"],
926
- "requires": { "features": ["subgroups"] },
927
- "intermediates": [
928
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
929
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
930
- ],
931
- "passes": [
932
- {
933
- "id": "present_retain",
934
- "name": "DecoderMaskedMultiHeadAttention.PresentRetain",
935
- "shader": "dmmha-present.wgsl.jinja",
936
- "derive": {
937
- "appendRow": false,
938
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
939
- "itemsPerLane": "retainItemsPerLane",
940
- "cacheScalar": "attnScalar"
941
- },
942
- "bindings": ["past_key", "past_value", "present_key", "present_value", "params_retain"],
943
- "dispatch": {
944
- "x": "min(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
945
- "y": "ceilDiv(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
946
- "z": 1
947
- },
948
- "viewAlias": [
949
- { "input": "past_key", "output": "present_key" },
950
- { "input": "past_value", "output": "present_value" }
951
- ]
952
- },
953
- {
954
- "id": "present_append",
955
- "name": "DecoderMaskedMultiHeadAttention.PresentAppend",
956
- "shader": "dmmha-present.wgsl.jinja",
957
- "derive": {
958
- "appendRow": true,
959
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
960
- "headSizeV4": "headDimV4",
961
- "numHeads": "numHeads"
962
- },
963
- "bindings": ["key_row", "value_row", "past_sequence_length", "present_key", "present_value", "params_append"],
964
- "dispatch": {
965
- "x": "min(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
966
- "y": "ceilDiv(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
967
- "z": 1
968
- }
969
- },
970
- {
971
- "id": "split_attention",
972
- "name": "DecoderMaskedMultiHeadAttention.SelfSplitK",
973
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
974
- "derive": {
975
- "layout": "\"bhsd\"",
976
- "splitQueries": false,
977
- "qNumHeads": "numHeads",
978
- "kvNumHeads": "numHeads",
979
- "headDim": "headSize",
980
- "headDimV4": "headDimV4",
981
- "numSplits": "numSplits",
982
- "usesF16": "tensorDtypes.queryT == \"float16\"",
983
- "cacheSeqlens": true,
984
- "cacheSeqlensIndex": "\"0u\"",
985
- "hasKeyPadMask": "present.maskIndexT",
986
- "hasMask": "present.attentionBiasT"
987
- },
988
- "bindings": ["query", "key_cache", "value_cache", "seqlens_k", "attn_mask", "partial_out", "partial_stats", "params_self_bias"],
989
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
990
- },
991
- {
992
- "id": "merge",
993
- "name": "DecoderMaskedMultiHeadAttention.SelfMerge",
994
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
995
- "derive": {
996
- "layout": "\"bhsd\"",
997
- "splitQueries": false,
998
- "scalar": "attnScalar",
999
- "qNumHeads": "numHeads",
1000
- "headDimV4": "headDimV4",
1001
- "numSplits": "numSplits"
1002
- },
1003
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
1004
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1005
- }
1006
- ]
1007
- },
1008
- {
1009
- "id": "self_mask",
1010
- "priority": 30,
1011
- "when": ["selfMaskOk", "subgroupSplitKOk"],
1012
- "demoteWhen": ["not subgroupSplitKPreferred"],
1013
- "requires": { "features": ["subgroups"] },
1014
- "intermediates": [
1015
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
1016
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
1017
- ],
1018
- "passes": [
1019
- {
1020
- "id": "present_retain",
1021
- "name": "DecoderMaskedMultiHeadAttention.PresentRetain",
1022
- "shader": "dmmha-present.wgsl.jinja",
1023
- "derive": {
1024
- "appendRow": false,
1025
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1026
- "itemsPerLane": "retainItemsPerLane",
1027
- "cacheScalar": "attnScalar"
1028
- },
1029
- "bindings": ["past_key", "past_value", "present_key", "present_value", "params_retain"],
1030
- "dispatch": {
1031
- "x": "min(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1032
- "y": "ceilDiv(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1033
- "z": 1
1034
- },
1035
- "viewAlias": [
1036
- { "input": "past_key", "output": "present_key" },
1037
- { "input": "past_value", "output": "present_value" }
1038
- ]
1039
- },
1040
- {
1041
- "id": "present_append",
1042
- "name": "DecoderMaskedMultiHeadAttention.PresentAppend",
1043
- "shader": "dmmha-present.wgsl.jinja",
1044
- "derive": {
1045
- "appendRow": true,
1046
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1047
- "headSizeV4": "headDimV4",
1048
- "numHeads": "numHeads"
1049
- },
1050
- "bindings": ["key_row", "value_row", "past_sequence_length", "present_key", "present_value", "params_append"],
1051
- "dispatch": {
1052
- "x": "min(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1053
- "y": "ceilDiv(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1054
- "z": 1
1055
- }
1056
- },
1057
- {
1058
- "id": "split_attention",
1059
- "name": "DecoderMaskedMultiHeadAttention.SelfSplitK",
1060
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
1061
- "derive": {
1062
- "layout": "\"bhsd\"",
1063
- "splitQueries": false,
1064
- "qNumHeads": "numHeads",
1065
- "kvNumHeads": "numHeads",
1066
- "headDim": "headSize",
1067
- "headDimV4": "headDimV4",
1068
- "numSplits": "numSplits",
1069
- "usesF16": "tensorDtypes.queryT == \"float16\"",
1070
- "cacheSeqlens": true,
1071
- "cacheSeqlensIndex": "\"0u\"",
1072
- "hasKeyPadMask": "present.maskIndexT",
1073
- "maskFilterValue": "attrs.mask_filter_value",
1074
- "hasMask": "present.attentionBiasT"
1075
- },
1076
- "bindings": ["query", "key_cache", "value_cache", "seqlens_k", "key_pad_mask", "partial_out", "partial_stats", "params_self"],
1077
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1078
- },
1079
- {
1080
- "id": "merge",
1081
- "name": "DecoderMaskedMultiHeadAttention.SelfMerge",
1082
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
1083
- "derive": {
1084
- "layout": "\"bhsd\"",
1085
- "splitQueries": false,
1086
- "scalar": "attnScalar",
1087
- "qNumHeads": "numHeads",
1088
- "headDimV4": "headDimV4",
1089
- "numSplits": "numSplits"
1090
- },
1091
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
1092
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1093
- }
1094
- ]
1095
- },
1096
- {
1097
- "id": "self_mask_bias",
1098
- "priority": 30,
1099
- "when": ["selfMaskBiasOk", "subgroupSplitKOk"],
1100
- "demoteWhen": ["not subgroupSplitKPreferred"],
1101
- "requires": { "features": ["subgroups"] },
1102
- "intermediates": [
1103
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
1104
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
1105
- ],
1106
- "passes": [
1107
- {
1108
- "id": "present_retain",
1109
- "name": "DecoderMaskedMultiHeadAttention.PresentRetain",
1110
- "shader": "dmmha-present.wgsl.jinja",
1111
- "derive": {
1112
- "appendRow": false,
1113
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1114
- "itemsPerLane": "retainItemsPerLane",
1115
- "cacheScalar": "attnScalar"
1116
- },
1117
- "bindings": ["past_key", "past_value", "present_key", "present_value", "params_retain"],
1118
- "dispatch": {
1119
- "x": "min(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1120
- "y": "ceilDiv(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1121
- "z": 1
1122
- },
1123
- "viewAlias": [
1124
- { "input": "past_key", "output": "present_key" },
1125
- { "input": "past_value", "output": "present_value" }
1126
- ]
1127
- },
1128
- {
1129
- "id": "present_append",
1130
- "name": "DecoderMaskedMultiHeadAttention.PresentAppend",
1131
- "shader": "dmmha-present.wgsl.jinja",
1132
- "derive": {
1133
- "appendRow": true,
1134
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1135
- "headSizeV4": "headDimV4",
1136
- "numHeads": "numHeads"
1137
- },
1138
- "bindings": ["key_row", "value_row", "past_sequence_length", "present_key", "present_value", "params_append"],
1139
- "dispatch": {
1140
- "x": "min(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1141
- "y": "ceilDiv(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1142
- "z": 1
1143
- }
1144
- },
1145
- {
1146
- "id": "split_attention",
1147
- "name": "DecoderMaskedMultiHeadAttention.SelfSplitK",
1148
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
1149
- "derive": {
1150
- "layout": "\"bhsd\"",
1151
- "splitQueries": false,
1152
- "qNumHeads": "numHeads",
1153
- "kvNumHeads": "numHeads",
1154
- "headDim": "headSize",
1155
- "headDimV4": "headDimV4",
1156
- "numSplits": "numSplits",
1157
- "usesF16": "tensorDtypes.queryT == \"float16\"",
1158
- "cacheSeqlens": true,
1159
- "cacheSeqlensIndex": "\"0u\"",
1160
- "hasKeyPadMask": "present.maskIndexT",
1161
- "maskFilterValue": "attrs.mask_filter_value",
1162
- "hasMask": "present.attentionBiasT"
1163
- },
1164
- "bindings": ["query", "key_cache", "value_cache", "seqlens_k", "key_pad_mask", "attn_mask", "partial_out", "partial_stats", "params_self_bias"],
1165
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1166
- },
1167
- {
1168
- "id": "merge",
1169
- "name": "DecoderMaskedMultiHeadAttention.SelfMerge",
1170
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
1171
- "derive": {
1172
- "layout": "\"bhsd\"",
1173
- "splitQueries": false,
1174
- "scalar": "attnScalar",
1175
- "qNumHeads": "numHeads",
1176
- "headDimV4": "headDimV4",
1177
- "numSplits": "numSplits"
1178
- },
1179
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
1180
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1181
- }
1182
- ]
1183
- },
1184
- {
1185
- "id": "self_nosg",
1186
- "priority": 20,
1187
- "when": ["selfPlainOk"],
1188
- "requires": {},
1189
- "intermediates": [
1190
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
1191
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
1192
- ],
1193
- "passes": [
1194
- {
1195
- "id": "present_retain",
1196
- "name": "DecoderMaskedMultiHeadAttention.PresentRetain",
1197
- "shader": "dmmha-present.wgsl.jinja",
1198
- "derive": {
1199
- "appendRow": false,
1200
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1201
- "itemsPerLane": "retainItemsPerLane",
1202
- "cacheScalar": "attnScalar"
1203
- },
1204
- "bindings": ["past_key", "past_value", "present_key", "present_value", "params_retain"],
1205
- "dispatch": {
1206
- "x": "min(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1207
- "y": "ceilDiv(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1208
- "z": 1
1209
- },
1210
- "viewAlias": [
1211
- { "input": "past_key", "output": "present_key" },
1212
- { "input": "past_value", "output": "present_value" }
1213
- ]
1214
- },
1215
- {
1216
- "id": "present_append",
1217
- "name": "DecoderMaskedMultiHeadAttention.PresentAppend",
1218
- "shader": "dmmha-present.wgsl.jinja",
1219
- "derive": {
1220
- "appendRow": true,
1221
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1222
- "headSizeV4": "headDimV4",
1223
- "numHeads": "numHeads"
1224
- },
1225
- "bindings": ["key_row", "value_row", "past_sequence_length", "present_key", "present_value", "params_append"],
1226
- "dispatch": {
1227
- "x": "min(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1228
- "y": "ceilDiv(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1229
- "z": 1
1230
- }
1231
- },
1232
- {
1233
- "id": "split_attention",
1234
- "name": "DecoderMaskedMultiHeadAttention.SelfSplitKNoSg",
1235
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
1236
- "derive": {
1237
- "layout": "\"bhsd\"",
1238
- "splitQueries": false,
1239
- "qNumHeads": "numHeads",
1240
- "kvNumHeads": "numHeads",
1241
- "headDim": "headSize",
1242
- "headDimV4": "headDimV4",
1243
- "numSplits": "numSplits",
1244
- "usesF16": "tensorDtypes.queryT == \"float16\"",
1245
- "cacheSeqlens": true,
1246
- "cacheSeqlensIndex": "\"0u\"",
1247
- "hasKeyPadMask": "present.maskIndexT",
1248
- "hasMask": "present.attentionBiasT",
1249
- "useSubgroups": false
1250
- },
1251
- "bindings": ["query", "key_cache", "value_cache", "seqlens_k", "partial_out", "partial_stats", "params_self"],
1252
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1253
- },
1254
- {
1255
- "id": "merge",
1256
- "name": "DecoderMaskedMultiHeadAttention.SelfMergeNoSg",
1257
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
1258
- "derive": {
1259
- "layout": "\"bhsd\"",
1260
- "splitQueries": false,
1261
- "scalar": "attnScalar",
1262
- "qNumHeads": "numHeads",
1263
- "headDimV4": "headDimV4",
1264
- "numSplits": "numSplits"
1265
- },
1266
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
1267
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1268
- }
1269
- ]
1270
- },
1271
- {
1272
- "id": "self_bias_nosg",
1273
- "priority": 20,
1274
- "when": ["selfBiasOk"],
1275
- "requires": {},
1276
- "intermediates": [
1277
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
1278
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
1279
- ],
1280
- "passes": [
1281
- {
1282
- "id": "present_retain",
1283
- "name": "DecoderMaskedMultiHeadAttention.PresentRetain",
1284
- "shader": "dmmha-present.wgsl.jinja",
1285
- "derive": {
1286
- "appendRow": false,
1287
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1288
- "itemsPerLane": "retainItemsPerLane",
1289
- "cacheScalar": "attnScalar"
1290
- },
1291
- "bindings": ["past_key", "past_value", "present_key", "present_value", "params_retain"],
1292
- "dispatch": {
1293
- "x": "min(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1294
- "y": "ceilDiv(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1295
- "z": 1
1296
- },
1297
- "viewAlias": [
1298
- { "input": "past_key", "output": "present_key" },
1299
- { "input": "past_value", "output": "present_value" }
1300
- ]
1301
- },
1302
- {
1303
- "id": "present_append",
1304
- "name": "DecoderMaskedMultiHeadAttention.PresentAppend",
1305
- "shader": "dmmha-present.wgsl.jinja",
1306
- "derive": {
1307
- "appendRow": true,
1308
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1309
- "headSizeV4": "headDimV4",
1310
- "numHeads": "numHeads"
1311
- },
1312
- "bindings": ["key_row", "value_row", "past_sequence_length", "present_key", "present_value", "params_append"],
1313
- "dispatch": {
1314
- "x": "min(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1315
- "y": "ceilDiv(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1316
- "z": 1
1317
- }
1318
- },
1319
- {
1320
- "id": "split_attention",
1321
- "name": "DecoderMaskedMultiHeadAttention.SelfSplitKNoSg",
1322
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
1323
- "derive": {
1324
- "layout": "\"bhsd\"",
1325
- "splitQueries": false,
1326
- "qNumHeads": "numHeads",
1327
- "kvNumHeads": "numHeads",
1328
- "headDim": "headSize",
1329
- "headDimV4": "headDimV4",
1330
- "numSplits": "numSplits",
1331
- "usesF16": "tensorDtypes.queryT == \"float16\"",
1332
- "cacheSeqlens": true,
1333
- "cacheSeqlensIndex": "\"0u\"",
1334
- "hasKeyPadMask": "present.maskIndexT",
1335
- "hasMask": "present.attentionBiasT",
1336
- "useSubgroups": false
1337
- },
1338
- "bindings": ["query", "key_cache", "value_cache", "seqlens_k", "attn_mask", "partial_out", "partial_stats", "params_self_bias"],
1339
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1340
- },
1341
- {
1342
- "id": "merge",
1343
- "name": "DecoderMaskedMultiHeadAttention.SelfMergeNoSg",
1344
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
1345
- "derive": {
1346
- "layout": "\"bhsd\"",
1347
- "splitQueries": false,
1348
- "scalar": "attnScalar",
1349
- "qNumHeads": "numHeads",
1350
- "headDimV4": "headDimV4",
1351
- "numSplits": "numSplits"
1352
- },
1353
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
1354
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1355
- }
1356
- ]
1357
- },
1358
- {
1359
- "id": "self_mask_nosg",
1360
- "priority": 20,
1361
- "when": ["selfMaskOk"],
1362
- "requires": {},
1363
- "intermediates": [
1364
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
1365
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
1366
- ],
1367
- "passes": [
1368
- {
1369
- "id": "present_retain",
1370
- "name": "DecoderMaskedMultiHeadAttention.PresentRetain",
1371
- "shader": "dmmha-present.wgsl.jinja",
1372
- "derive": {
1373
- "appendRow": false,
1374
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1375
- "itemsPerLane": "retainItemsPerLane",
1376
- "cacheScalar": "attnScalar"
1377
- },
1378
- "bindings": ["past_key", "past_value", "present_key", "present_value", "params_retain"],
1379
- "dispatch": {
1380
- "x": "min(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1381
- "y": "ceilDiv(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1382
- "z": 1
1383
- },
1384
- "viewAlias": [
1385
- { "input": "past_key", "output": "present_key" },
1386
- { "input": "past_value", "output": "present_value" }
1387
- ]
1388
- },
1389
- {
1390
- "id": "present_append",
1391
- "name": "DecoderMaskedMultiHeadAttention.PresentAppend",
1392
- "shader": "dmmha-present.wgsl.jinja",
1393
- "derive": {
1394
- "appendRow": true,
1395
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1396
- "headSizeV4": "headDimV4",
1397
- "numHeads": "numHeads"
1398
- },
1399
- "bindings": ["key_row", "value_row", "past_sequence_length", "present_key", "present_value", "params_append"],
1400
- "dispatch": {
1401
- "x": "min(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1402
- "y": "ceilDiv(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1403
- "z": 1
1404
- }
1405
- },
1406
- {
1407
- "id": "split_attention",
1408
- "name": "DecoderMaskedMultiHeadAttention.SelfSplitKNoSg",
1409
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
1410
- "derive": {
1411
- "layout": "\"bhsd\"",
1412
- "splitQueries": false,
1413
- "qNumHeads": "numHeads",
1414
- "kvNumHeads": "numHeads",
1415
- "headDim": "headSize",
1416
- "headDimV4": "headDimV4",
1417
- "numSplits": "numSplits",
1418
- "usesF16": "tensorDtypes.queryT == \"float16\"",
1419
- "cacheSeqlens": true,
1420
- "cacheSeqlensIndex": "\"0u\"",
1421
- "hasKeyPadMask": "present.maskIndexT",
1422
- "maskFilterValue": "attrs.mask_filter_value",
1423
- "hasMask": "present.attentionBiasT",
1424
- "useSubgroups": false
1425
- },
1426
- "bindings": ["query", "key_cache", "value_cache", "seqlens_k", "key_pad_mask", "partial_out", "partial_stats", "params_self"],
1427
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1428
- },
1429
- {
1430
- "id": "merge",
1431
- "name": "DecoderMaskedMultiHeadAttention.SelfMergeNoSg",
1432
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
1433
- "derive": {
1434
- "layout": "\"bhsd\"",
1435
- "splitQueries": false,
1436
- "scalar": "attnScalar",
1437
- "qNumHeads": "numHeads",
1438
- "headDimV4": "headDimV4",
1439
- "numSplits": "numSplits"
1440
- },
1441
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
1442
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1443
- }
1444
- ]
1445
- },
1446
- {
1447
- "id": "self_mask_bias_nosg",
1448
- "priority": 20,
1449
- "when": ["selfMaskBiasOk"],
1450
- "requires": {},
1451
- "intermediates": [
1452
- { "id": "partialOut", "dtype": "float32", "shape": "[batchSize * numHeads * numSplits * headSize]" },
1453
- { "id": "partialStats", "dtype": "float32", "shape": "[2 * batchSize * numHeads * numSplits]" }
1454
- ],
1455
- "passes": [
1456
- {
1457
- "id": "present_retain",
1458
- "name": "DecoderMaskedMultiHeadAttention.PresentRetain",
1459
- "shader": "dmmha-present.wgsl.jinja",
1460
- "derive": {
1461
- "appendRow": false,
1462
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1463
- "itemsPerLane": "retainItemsPerLane",
1464
- "cacheScalar": "attnScalar"
1465
- },
1466
- "bindings": ["past_key", "past_value", "present_key", "present_value", "params_retain"],
1467
- "dispatch": {
1468
- "x": "min(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1469
- "y": "ceilDiv(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)",
1470
- "z": 1
1471
- },
1472
- "viewAlias": [
1473
- { "input": "past_key", "output": "present_key" },
1474
- { "input": "past_value", "output": "present_value" }
1475
- ]
1476
- },
1477
- {
1478
- "id": "present_append",
1479
- "name": "DecoderMaskedMultiHeadAttention.PresentAppend",
1480
- "shader": "dmmha-present.wgsl.jinja",
1481
- "derive": {
1482
- "appendRow": true,
1483
- "workgroupSize": "tunables.COPY_WORKGROUP_SIZE",
1484
- "headSizeV4": "headDimV4",
1485
- "numHeads": "numHeads"
1486
- },
1487
- "bindings": ["key_row", "value_row", "past_sequence_length", "present_key", "present_value", "params_append"],
1488
- "dispatch": {
1489
- "x": "min(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1490
- "y": "ceilDiv(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)",
1491
- "z": 1
1492
- }
1493
- },
1494
- {
1495
- "id": "split_attention",
1496
- "name": "DecoderMaskedMultiHeadAttention.SelfSplitKNoSg",
1497
- "shader": "attn-flash-decode-splitk.wgsl.jinja",
1498
- "derive": {
1499
- "layout": "\"bhsd\"",
1500
- "splitQueries": false,
1501
- "qNumHeads": "numHeads",
1502
- "kvNumHeads": "numHeads",
1503
- "headDim": "headSize",
1504
- "headDimV4": "headDimV4",
1505
- "numSplits": "numSplits",
1506
- "usesF16": "tensorDtypes.queryT == \"float16\"",
1507
- "cacheSeqlens": true,
1508
- "cacheSeqlensIndex": "\"0u\"",
1509
- "hasKeyPadMask": "present.maskIndexT",
1510
- "maskFilterValue": "attrs.mask_filter_value",
1511
- "hasMask": "present.attentionBiasT",
1512
- "useSubgroups": false
1513
- },
1514
- "bindings": ["query", "key_cache", "value_cache", "seqlens_k", "key_pad_mask", "attn_mask", "partial_out", "partial_stats", "params_self_bias"],
1515
- "dispatch": { "x": "numSplits", "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1516
- },
1517
- {
1518
- "id": "merge",
1519
- "name": "DecoderMaskedMultiHeadAttention.SelfMergeNoSg",
1520
- "shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
1521
- "derive": {
1522
- "layout": "\"bhsd\"",
1523
- "splitQueries": false,
1524
- "scalar": "attnScalar",
1525
- "qNumHeads": "numHeads",
1526
- "headDimV4": "headDimV4",
1527
- "numSplits": "numSplits"
1528
- },
1529
- "bindings": ["partial_out_read", "partial_stats_read", "output"],
1530
- "dispatch": { "x": 1, "y": "attrs.num_heads", "z": "dim(shapes.queryT, 0)" }
1531
- }
1532
- ]
1533
- }
1534
- ]
1535
- }
 
1
+ {"domain":"com.microsoft","name":"DecoderMaskedMultiHeadAttention","sinceVersion":1,"inputs":{"queryT":{"onnx":"query","dtype":"T","rank":3},"keyT":{"onnx":"key","dtype":"T"},"valueT":{"onnx":"value","dtype":"T"},"maskIndexT":{"onnx":"mask_index","dtype":"M","rank":2,"optional":true},"attentionBiasT":{"onnx":"attention_bias","dtype":"T","rank":4,"optional":true},"pastKeyT":{"onnx":"past_key","dtype":"T","rank":4,"optional":true},"pastValueT":{"onnx":"past_value","dtype":"T","rank":4,"optional":true},"pastSequenceLengthT":{"onnx":"past_sequence_length","dtype":"M","rank":1,"optional":true}},"outputs":{"outputT":{"onnx":"output","dtype":"T","rank":3,"shape":"[dim(shapes.queryT, 0), 1, dim(shapes.queryT, 2)]"},"presentKeyT":{"onnx":"present_key","dtype":"T","rank":4,"optional":true,"shape":"shapes.pastKeyT"},"presentValueT":{"onnx":"present_value","dtype":"T","rank":4,"optional":true,"shape":"shapes.pastValueT"},"qkT":{"onnx":"qk","dtype":"QK","rank":4,"optional":true,"shape":"[dim(shapes.queryT, 0), attrs.num_heads, 1, dim(shapes.keyT, 2)]"}},"attributes":{"num_heads":{},"past_present_share_buffer":{},"scale":{},"mask_filter_value":{"default":-10000},"output_qk":{}},"attributeConstraints":{"num_heads":{"required":true}},"typeConstraints":{"T":["float32","float16"],"QK":["float32","float16"],"M":["int32"]},"tunables":{"WORKGROUP_SIZE":{"default":256},"COPY_WORKGROUP_SIZE":{"default":256},"COPY_ITEMS_PER_LANE":{"default":8},"COPY_MIN_WORKGROUPS":{"default":64},"MAX_SPLITS":{"default":8},"KEYS_PER_SPLIT":{"default":256},"THREAD_QK_OUTPUT_WORKGROUPS":{"default":2}},"derive":{"deviceWorkgroupCap":"min(device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX)","wave32Adapter":"has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize == 32 and device.adapterInfo.subgroupMaxSize == 32","subgroupsWave32":"device.features.has(\"subgroups\") and wave32Adapter","narrowSubgroupRange":"has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize < device.adapterInfo.subgroupMaxSize and device.adapterInfo.subgroupMaxSize <= 16","variableSubgroup16To32":"device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize == 16 and device.adapterInfo.subgroupMaxSize == 32","boundValueNumerator":"tensorDtypes.queryT == \"float32\" and not device.features.has(\"shader-f16\")","batchSize":"dim(shapes.queryT, 0)","hiddenSize":"dim(shapes.queryT, 2)","numHeads":"attrs.num_heads","headSize":"hiddenSize / max(1, numHeads)","headDimV4":"headSize / 4","isCross":"not present.pastKeyT and not present.pastValueT","crossKvLen":"dim(shapes.keyT, 2) if (isCross and ranks.keyT == 4) else 0","cacheCapacity":"dim(shapes.pastKeyT, 2) if present.pastKeyT else 0","physicalKeys":"crossKvLen if isCross else cacheCapacity","qkRequested":"attrs.output_qk != 0 if has(attrs, \"output_qk\") else false","floatDtypeOk":"(tensorDtypes.queryT == \"float32\" or tensorDtypes.queryT == \"float16\") and f16Ok(tensorDtypes.queryT) and tensorDtypes.keyT == tensorDtypes.queryT and tensorDtypes.valueT == tensorDtypes.queryT and tensorDtypes.outputT == tensorDtypes.queryT","geometryOk":"ranks.queryT == 3 and dim(shapes.queryT, 1) == 1 and numHeads > 0 and hiddenSize > 0 and hiddenSize % numHeads == 0 and headSize > 0 and headSize % 4 == 0","outputShapeOk":"ranks.outputT == 3 and dim(shapes.outputT, 0) == batchSize and dim(shapes.outputT, 1) == 1 and dim(shapes.outputT, 2) == hiddenSize","workgroupOk":"tunables.WORKGROUP_SIZE > 0 and tunables.WORKGROUP_SIZE <= deviceWorkgroupCap and pow2ceil(tunables.WORKGROUP_SIZE) == tunables.WORKGROUP_SIZE and headDimV4 <= deviceWorkgroupCap and tunables.COPY_WORKGROUP_SIZE > 0 and tunables.COPY_WORKGROUP_SIZE <= deviceWorkgroupCap","numSplits":"max(1, min(tunables.MAX_SPLITS, ceilDiv(physicalKeys, tunables.KEYS_PER_SPLIT)))","crossMatrixTier":"subgroupsWave32 and device.features.has(\"chromium-experimental-subgroup-matrix\")","singleTileTier":"variableSubgroup16To32 or (crossMatrixTier and subgroupMatrixConfigAvailable(\"f16\", \"f32\", 16, 16, 16))","occupiedComponentTier":"crossMatrixTier and subgroupMatrixConfigAvailable(\"f32\", \"f32\", 8, 8, 8) and batchSize * numHeads >= 2 * ceilDiv(tunables.WORKGROUP_SIZE, device.adapterInfo.subgroupMinSize)","splitCross":"isCross and numSplits > 1","componentFold":"splitCross and tensorDtypes.valueT == \"float32\" and (singleTileTier or occupiedComponentTier) and headSize >= 2 * device.adapterInfo.subgroupMinSize and headSize <= tunables.WORKGROUP_SIZE","singleKeyTile":"splitCross and (componentFold or (singleTileTier and tensorDtypes.valueT == \"float16\")) and ceilDiv(crossKvLen, numSplits) <= tunables.WORKGROUP_SIZE","splitScratchBytes":"batchSize * numHeads * numSplits * headSize * 4","splitStatsBytes":"2 * batchSize * numHeads * numSplits * 4","scratchFits":"splitScratchBytes <= device.limits.maxStorageBufferBindingSize and splitScratchBytes <= device.limits.maxBufferSize and splitStatsBytes <= device.limits.maxStorageBufferBindingSize and splitStatsBytes <= device.limits.maxBufferSize","dispatchFits":"batchSize <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and numHeads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and numSplits <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","coreOk":"floatDtypeOk and geometryOk and outputShapeOk and workgroupOk and scratchFits and dispatchFits and physicalKeys > 0","crossOk":"coreOk and isCross and ranks.keyT == 4 and ranks.valueT == 4 and dim(shapes.keyT, 0) == batchSize and dim(shapes.keyT, 1) == numHeads and dim(shapes.keyT, 3) == headSize and sameShape(shapes.valueT, shapes.keyT) and not present.attentionBiasT and not present.pastSequenceLengthT and not present.presentKeyT and not present.presentValueT","cacheDtypeOk":"tensorDtypes.pastKeyT == tensorDtypes.queryT and tensorDtypes.pastValueT == tensorDtypes.queryT and tensorDtypes.presentKeyT == tensorDtypes.queryT and tensorDtypes.presentValueT == tensorDtypes.queryT and tensorDtypes.pastSequenceLengthT == \"int32\"","selfOk":"coreOk and not isCross and present.pastValueT and present.pastSequenceLengthT and present.presentKeyT and present.presentValueT and attrs.past_present_share_buffer == 1 and ranks.keyT == 3 and ranks.valueT == 3 and dim(shapes.keyT, 0) == batchSize and dim(shapes.keyT, 1) == 1 and dim(shapes.keyT, 2) == hiddenSize and sameShape(shapes.valueT, shapes.keyT) and ranks.pastKeyT == 4 and dim(shapes.pastKeyT, 0) == batchSize and dim(shapes.pastKeyT, 1) == numHeads and dim(shapes.pastKeyT, 3) == headSize and cacheCapacity > 1 and sameShape(shapes.pastValueT, shapes.pastKeyT) and sameShape(shapes.presentKeyT, shapes.pastKeyT) and sameShape(shapes.presentValueT, shapes.pastKeyT) and numel(shapes.pastSequenceLengthT) == 1 and cacheDtypeOk and not present.qkT and not qkRequested","maskShapeOk":"not present.maskIndexT or (ranks.maskIndexT == 2 and dim(shapes.maskIndexT, 0) == batchSize and tensorDtypes.maskIndexT == \"int32\" and (dim(shapes.maskIndexT, 1) == crossKvLen if isCross else (dim(shapes.maskIndexT, 1) >= 1 and dim(shapes.maskIndexT, 1) <= cacheCapacity)))","attnBiasShapeOk":"not present.attentionBiasT or (ranks.attentionBiasT == 4 and tensorDtypes.attentionBiasT == tensorDtypes.queryT and dim(shapes.attentionBiasT, 2) == 1 and (dim(shapes.attentionBiasT, 0) == 1 or dim(shapes.attentionBiasT, 0) == batchSize) and (dim(shapes.attentionBiasT, 1) == 1 or dim(shapes.attentionBiasT, 1) == numHeads) and dim(shapes.attentionBiasT, 3) >= 1 and dim(shapes.attentionBiasT, 3) <= cacheCapacity)","qkShapeOk":"(not present.qkT and not qkRequested) or (present.qkT and qkRequested and ranks.qkT == 4 and (tensorDtypes.qkT == \"float32\" or tensorDtypes.qkT == \"float16\") and f16Ok(tensorDtypes.qkT) and dim(shapes.qkT, 0) == batchSize and dim(shapes.qkT, 1) == numHeads and dim(shapes.qkT, 2) == 1 and dim(shapes.qkT, 3) == crossKvLen)","subgroupSplitKOk":"device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize >= 8 and device.adapterInfo.subgroupMinSize % 8 == 0 and device.adapterInfo.subgroupMaxSize % 8 == 0 and device.adapterInfo.subgroupMaxSize <= tunables.WORKGROUP_SIZE and tunables.WORKGROUP_SIZE % device.adapterInfo.subgroupMinSize == 0 and tunables.WORKGROUP_SIZE % device.adapterInfo.subgroupMaxSize == 0","subgroupSplitKPreferred":"subgroupSplitKOk and not narrowSubgroupRange","attnScalar":"\"f16\" if tensorDtypes.queryT == \"float16\" else \"f32\"","attnVec4":"\"vec4<f16>\" if tensorDtypes.queryT == \"float16\" else \"vec4<f32>\"","crossValueElement":"\"f32\" if componentFold else attnVec4","crossPartialElement":"\"f32\" if componentFold else \"vec4<f32>\"","attnMaskElement":"\"f16\" if tensorDtypes.queryT == \"float16\" else \"f32\"","qkScalarType":"\"f16\" if tensorDtypes.qkT == \"float16\" else \"f32\"","attnBiasWidth":"dim(shapes.attentionBiasT, 3) if present.attentionBiasT else 0","attnBiasHeads":"dim(shapes.attentionBiasT, 1) if present.attentionBiasT else 0","attnBiasBatch":"dim(shapes.attentionBiasT, 0) if present.attentionBiasT else 0","cacheWordsV4":"numel(shapes.pastKeyT) / 4 if present.pastKeyT else 0","retainBlockWords":"tunables.COPY_WORKGROUP_SIZE * tunables.COPY_MIN_WORKGROUPS","retainOccupancyCap":"pick([[cacheWordsV4 >= 8 * retainBlockWords, 8], [cacheWordsV4 >= 4 * retainBlockWords, 4], [cacheWordsV4 >= 2 * retainBlockWords, 2]], 1)","retainItemsPerLane":"max(1, min(tunables.COPY_ITEMS_PER_LANE, retainOccupancyCap))","splitKStorageSgBytes":"(headSize) * 8 + (tunables.WORKGROUP_SIZE) * 12 + (16 * (tunables.WORKGROUP_SIZE) if (tunables.WORKGROUP_SIZE) % ((headSize) / 4) == 0 and (tunables.WORKGROUP_SIZE) / ((headSize) / 4) >= 2 else 0) + (4 * (tunables.WORKGROUP_SIZE) if (true) and ((headSize) / 4) >= 8 and not ((tensorDtypes.queryT == \"float16\") and ((headSize) / 4) <= 32) and (not isCross or tensorDtypes.queryT == \"float16\" or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE) else 0) + (ceilDiv((tunables.WORKGROUP_SIZE), 32) * 4 + 8 if (true) else 0) if (headSize) >= 4 and (tunables.WORKGROUP_SIZE) > 0 else 0","splitKStorageNoSgBytes":"(headSize) * 8 + (tunables.WORKGROUP_SIZE) * 12 + (16 * (tunables.WORKGROUP_SIZE) if (tunables.WORKGROUP_SIZE) % ((headSize) / 4) == 0 and (tunables.WORKGROUP_SIZE) / ((headSize) / 4) >= 2 else 0) + (4 * (tunables.WORKGROUP_SIZE) if (false) and ((headSize) / 4) >= 8 and not ((tensorDtypes.queryT == \"float16\") and ((headSize) / 4) <= 32) and (not isCross or tensorDtypes.queryT == \"float16\" or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE) else 0) + (ceilDiv((tunables.WORKGROUP_SIZE), 32) * 4 + 8 if (false) else 0) if (headSize) >= 4 and (tunables.WORKGROUP_SIZE) > 0 else 0","splitKStorageSgOk":"(headSize) >= 4 and (tunables.WORKGROUP_SIZE) > 0 and (tunables.WORKGROUP_SIZE) <= deviceWorkgroupCap and (pow2ceil(tunables.WORKGROUP_SIZE) == (tunables.WORKGROUP_SIZE) or (true)) and (splitKStorageSgBytes) <= device.limits.maxComputeWorkgroupStorageSize","splitKStorageNoSgOk":"(headSize) >= 4 and (tunables.WORKGROUP_SIZE) > 0 and (tunables.WORKGROUP_SIZE) <= deviceWorkgroupCap and (pow2ceil(tunables.WORKGROUP_SIZE) == (tunables.WORKGROUP_SIZE) or (false)) and (splitKStorageNoSgBytes) <= device.limits.maxComputeWorkgroupStorageSize"},"bindings":{"query":{"arg":"queryT","elementType":"$attnVec4"},"key_cross":{"arg":"keyT","name":"key","elementType":"$attnVec4"},"value_cross":{"arg":"valueT","name":"value","elementType":"$crossValueElement"},"key_cache":{"arg":"presentKeyT","name":"key","buffer":"read-only-storage","elementType":"$attnVec4"},"value_cache":{"arg":"presentValueT","name":"value","buffer":"read-only-storage","elementType":"$attnVec4"},"key_row":{"arg":"keyT","name":"key","elementType":"$attnVec4"},"value_row":{"arg":"valueT","name":"value","elementType":"$attnVec4"},"past_key":{"arg":"pastKeyT","elementType":"$attnVec4"},"past_value":{"arg":"pastValueT","elementType":"$attnVec4"},"present_key":{"arg":"presentKeyT","elementType":"$attnVec4"},"present_value":{"arg":"presentValueT","elementType":"$attnVec4"},"seqlens_k":{"arg":"pastSequenceLengthT","name":"seqlens_k","elementType":"i32"},"past_sequence_length":{"arg":"pastSequenceLengthT","elementType":"i32"},"key_pad_mask":{"arg":"maskIndexT","name":"key_pad_mask","elementType":"i32","when":"present.maskIndexT"},"attn_mask":{"arg":"attentionBiasT","name":"attn_mask","elementType":"$attnMaskElement","when":"present.attentionBiasT"},"qk":{"arg":"qkT","elementType":"$qkScalarType","when":"present.qkT"},"partial_out":{"scratch":"partialOut","elementType":"$crossPartialElement"},"partial_stats":{"scratch":"partialStats","elementType":"vec2<f32>"},"partial_out_read":{"scratch":"partialOut","name":"partial_out","buffer":"read-only-storage","elementType":"vec4<f32>"},"partial_stats_read":{"scratch":"partialStats","name":"partial_stats","buffer":"read-only-storage","elementType":"vec2<f32>"},"output":{"arg":"outputT","elementType":"$attnVec4"},"params_cross":{"name":"params","struct":[{"name":"kvSeq","type":"u32","value":"crossKvLen"},{"name":"scale","type":"f32","value":"attrs.scale if has(attrs, \"scale\") else 0"}]},"params_self":{"name":"params","struct":[{"name":"kvSeq","type":"u32","value":"cacheCapacity"},{"name":"scale","type":"f32","value":"attrs.scale if has(attrs, \"scale\") else 0"}],"when":"not present.attentionBiasT"},"params_self_bias":{"name":"params","struct":[{"name":"kvSeq","type":"u32","value":"cacheCapacity"},{"name":"scale","type":"f32","value":"attrs.scale if has(attrs, \"scale\") else 0"},{"name":"maskBatchStride","type":"u32","value":"0 if attnBiasBatch == 1 else attnBiasHeads * attnBiasWidth"},{"name":"maskHeadStride","type":"u32","value":"0 if attnBiasHeads == 1 else attnBiasWidth"},{"name":"maskSeqStride","type":"u32","value":"0"}],"when":"present.attentionBiasT"},"params_retain":{"name":"params","struct":[{"name":"countV4","type":"u32","value":"numel(shapes.pastKeyT) / 4"}]},"params_append":{"name":"params","struct":[{"name":"rowCountV4","type":"u32","value":"batchSize * hiddenSize / 4"},{"name":"capacity","type":"u32","value":"cacheCapacity"}]}},"variants":[{"id":"cross_direct","priority":31,"when":["crossOk","maskShapeOk","qkShapeOk","subgroupSplitKOk","numSplits == 1","splitKStorageSgOk"],"demoteWhen":["not subgroupSplitKPreferred"],"requires":{"features":["subgroups"]},"passes":[{"id":"split_attention","name":"DecoderMaskedMultiHeadAttention.CrossSplitK","shader":"attn-flash-decode-splitk.wgsl.jinja","derive":{"layout":"\"bhsd\"","splitQueries":false,"qNumHeads":"numHeads","kvNumHeads":"numHeads","headDim":"headSize","headDimV4":"headDimV4","numSplits":"numSplits","usesF16":"tensorDtypes.queryT == \"float16\"","hasKeyPadMask":"present.maskIndexT","maskFilterValue":"attrs.mask_filter_value","emitQk":"present.qkT","qkScalar":"qkScalarType","useSubgroups":true,"allowCooperativeQk":"not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"},"bindings":["query","key_cross","value_cross","key_pad_mask","qk","params_cross","output"],"dispatch":{"x":"numSplits","y":"attrs.num_heads","z":"dim(shapes.queryT, 0)"}}],"derive":{"directOutput":true,"normalizedPartialValues":"tensorDtypes.outputT == \"float32\" and ((present.pastValueT and tensorDtypes.pastValueT != \"float16\") or (present.valueT and tensorDtypes.valueT != \"float16\"))"}},{"id":"cross","priority":30,"when":["crossOk","maskShapeOk","qkShapeOk","subgroupSplitKOk","splitKStorageSgOk"],"demoteWhen":["not subgroupSplitKPreferred"],"requires":{"features":["subgroups"]},"intermediates":[{"id":"partialOut","dtype":"float32","shape":"[batchSize * numHeads * numSplits * headSize]"},{"id":"partialStats","dtype":"float32","shape":"[2 * batchSize * numHeads * numSplits]"}],"passes":[{"id":"split_attention","name":"DecoderMaskedMultiHeadAttention.CrossSplitK","shader":"attn-flash-decode-splitk.wgsl.jinja","derive":{"layout":"\"bhsd\"","splitQueries":false,"qNumHeads":"numHeads","kvNumHeads":"numHeads","headDim":"headSize","headDimV4":"headDimV4","numSplits":"numSplits","usesF16":"tensorDtypes.queryT == \"float16\"","hasKeyPadMask":"present.maskIndexT","maskFilterValue":"attrs.mask_filter_value","emitQk":"present.qkT","qkScalar":"qkScalarType","useSubgroups":true,"allowCooperativeQk":"not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"},"bindings":["query","key_cross","value_cross","key_pad_mask","qk","partial_out","partial_stats","params_cross"],"dispatch":{"x":"numSplits","y":"attrs.num_heads","z":"dim(shapes.queryT, 0)"}},{"id":"merge","name":"DecoderMaskedMultiHeadAttention.CrossMerge","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bhsd\"","splitQueries":false,"scalar":"attnScalar","qNumHeads":"numHeads","headDimV4":"headDimV4","numSplits":"numSplits"},"bindings":["partial_out_read","partial_stats_read","output"],"dispatch":{"x":1,"y":"attrs.num_heads","z":"dim(shapes.queryT, 0)"}}],"derive":{"normalizedPartialValues":"tensorDtypes.outputT == \"float32\" and ((present.pastValueT and tensorDtypes.pastValueT != \"float16\") or (present.valueT and tensorDtypes.valueT != \"float16\"))"}},{"id":"cross_nosg_direct","priority":21,"when":["crossOk","maskShapeOk","qkShapeOk","numSplits == 1","splitKStorageNoSgOk"],"requires":{},"passes":[{"id":"split_attention","name":"DecoderMaskedMultiHeadAttention.CrossSplitKNoSg","shader":"attn-flash-decode-splitk.wgsl.jinja","derive":{"layout":"\"bhsd\"","splitQueries":false,"qNumHeads":"numHeads","kvNumHeads":"numHeads","headDim":"headSize","headDimV4":"headDimV4","numSplits":"numSplits","usesF16":"tensorDtypes.queryT == \"float16\"","hasKeyPadMask":"present.maskIndexT","maskFilterValue":"attrs.mask_filter_value","emitQk":"present.qkT","qkScalar":"qkScalarType","useSubgroups":false,"allowCooperativeQk":"not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"},"bindings":["query","key_cross","value_cross","key_pad_mask","qk","params_cross","output"],"dispatch":{"x":"numSplits","y":"attrs.num_heads","z":"dim(shapes.queryT, 0)"}}],"derive":{"directOutput":true,"normalizedPartialValues":"tensorDtypes.outputT == \"float32\" and ((present.pastValueT and tensorDtypes.pastValueT != \"float16\") or (present.valueT and tensorDtypes.valueT != \"float16\"))"}},{"id":"cross_nosg","priority":20,"when":["crossOk","maskShapeOk","qkShapeOk","splitKStorageNoSgOk"],"requires":{},"intermediates":[{"id":"partialOut","dtype":"float32","shape":"[batchSize * numHeads * numSplits * headSize]"},{"id":"partialStats","dtype":"float32","shape":"[2 * batchSize * numHeads * numSplits]"}],"passes":[{"id":"split_attention","name":"DecoderMaskedMultiHeadAttention.CrossSplitKNoSg","shader":"attn-flash-decode-splitk.wgsl.jinja","derive":{"layout":"\"bhsd\"","splitQueries":false,"qNumHeads":"numHeads","kvNumHeads":"numHeads","headDim":"headSize","headDimV4":"headDimV4","numSplits":"numSplits","usesF16":"tensorDtypes.queryT == \"float16\"","hasKeyPadMask":"present.maskIndexT","maskFilterValue":"attrs.mask_filter_value","emitQk":"present.qkT","qkScalar":"qkScalarType","useSubgroups":false,"allowCooperativeQk":"not useSubgroups or usesF16 or headDimV4 < 8 or batchSize * hiddenSize / 4 > tunables.THREAD_QK_OUTPUT_WORKGROUPS * tunables.WORKGROUP_SIZE"},"bindings":["query","key_cross","value_cross","key_pad_mask","qk","partial_out","partial_stats","params_cross"],"dispatch":{"x":"numSplits","y":"attrs.num_heads","z":"dim(shapes.queryT, 0)"}},{"id":"merge","name":"DecoderMaskedMultiHeadAttention.CrossMergeNoSg","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bhsd\"","splitQueries":false,"scalar":"attnScalar","qNumHeads":"numHeads","headDimV4":"headDimV4","numSplits":"numSplits"},"bindings":["partial_out_read","partial_stats_read","output"],"dispatch":{"x":1,"y":"attrs.num_heads","z":"dim(shapes.queryT, 0)"}}],"derive":{"normalizedPartialValues":"tensorDtypes.outputT == \"float32\" and ((present.pastValueT and tensorDtypes.pastValueT != \"float16\") or (present.valueT and tensorDtypes.valueT != \"float16\"))"}},{"id":"self","priority":30,"when":["selfOk","maskShapeOk","attnBiasShapeOk","subgroupSplitKOk","splitKStorageSgOk"],"demoteWhen":["not subgroupSplitKPreferred"],"requires":{"features":["subgroups"]},"intermediates":[{"id":"partialOut","dtype":"float32","shape":"[batchSize * numHeads * numSplits * headSize]"},{"id":"partialStats","dtype":"float32","shape":"[2 * batchSize * numHeads * numSplits]"}],"passes":[{"id":"present_retain","name":"DecoderMaskedMultiHeadAttention.PresentRetain","shader":"dmmha-present.wgsl.jinja","derive":{"appendRow":false,"workgroupSize":"tunables.COPY_WORKGROUP_SIZE","itemsPerLane":"retainItemsPerLane","cacheScalar":"attnScalar"},"bindings":["past_key","past_value","present_key","present_value","params_retain"],"dispatch":{"x":"min(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)","y":"ceilDiv(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)","z":1},"viewAlias":[{"input":"past_key","output":"present_key"},{"input":"past_value","output":"present_value"}]},{"id":"present_append","name":"DecoderMaskedMultiHeadAttention.PresentAppend","shader":"dmmha-present.wgsl.jinja","derive":{"appendRow":true,"workgroupSize":"tunables.COPY_WORKGROUP_SIZE","headSizeV4":"headDimV4","numHeads":"numHeads"},"bindings":["key_row","value_row","past_sequence_length","present_key","present_value","params_append"],"dispatch":{"x":"min(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"split_attention","name":"DecoderMaskedMultiHeadAttention.SelfSplitK","shader":"attn-flash-decode-splitk.wgsl.jinja","derive":{"layout":"\"bhsd\"","splitQueries":false,"qNumHeads":"numHeads","kvNumHeads":"numHeads","headDim":"headSize","headDimV4":"headDimV4","numSplits":"numSplits","usesF16":"tensorDtypes.queryT == \"float16\"","cacheSeqlens":true,"cacheSeqlensIndex":"\"0u\"","hasKeyPadMask":"present.maskIndexT","maskFilterValue":"attrs.mask_filter_value","hasMask":"present.attentionBiasT"},"bindings":["query","key_cache","value_cache","seqlens_k","key_pad_mask","attn_mask","partial_out","partial_stats","params_self","params_self_bias"],"dispatch":{"x":"numSplits","y":"attrs.num_heads","z":"dim(shapes.queryT, 0)"}},{"id":"merge","name":"DecoderMaskedMultiHeadAttention.SelfMerge","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bhsd\"","splitQueries":false,"scalar":"attnScalar","qNumHeads":"numHeads","headDimV4":"headDimV4","numSplits":"numSplits"},"bindings":["partial_out_read","partial_stats_read","output"],"dispatch":{"x":1,"y":"attrs.num_heads","z":"dim(shapes.queryT, 0)"}}],"derive":{"normalizedPartialValues":"tensorDtypes.outputT == \"float32\" and ((present.pastValueT and tensorDtypes.pastValueT != \"float16\") or (present.valueT and tensorDtypes.valueT != \"float16\"))"}},{"id":"self_nosg","priority":20,"when":["selfOk","maskShapeOk","attnBiasShapeOk","splitKStorageNoSgOk"],"requires":{},"intermediates":[{"id":"partialOut","dtype":"float32","shape":"[batchSize * numHeads * numSplits * headSize]"},{"id":"partialStats","dtype":"float32","shape":"[2 * batchSize * numHeads * numSplits]"}],"passes":[{"id":"present_retain","name":"DecoderMaskedMultiHeadAttention.PresentRetain","shader":"dmmha-present.wgsl.jinja","derive":{"appendRow":false,"workgroupSize":"tunables.COPY_WORKGROUP_SIZE","itemsPerLane":"retainItemsPerLane","cacheScalar":"attnScalar"},"bindings":["past_key","past_value","present_key","present_value","params_retain"],"dispatch":{"x":"min(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)","y":"ceilDiv(ceilDiv(cacheWordsV4, tunables.COPY_WORKGROUP_SIZE * retainItemsPerLane), 65535)","z":1},"viewAlias":[{"input":"past_key","output":"present_key"},{"input":"past_value","output":"present_value"}]},{"id":"present_append","name":"DecoderMaskedMultiHeadAttention.PresentAppend","shader":"dmmha-present.wgsl.jinja","derive":{"appendRow":true,"workgroupSize":"tunables.COPY_WORKGROUP_SIZE","headSizeV4":"headDimV4","numHeads":"numHeads"},"bindings":["key_row","value_row","past_sequence_length","present_key","present_value","params_append"],"dispatch":{"x":"min(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((batchSize * hiddenSize / 4), (tunables.COPY_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"split_attention","name":"DecoderMaskedMultiHeadAttention.SelfSplitKNoSg","shader":"attn-flash-decode-splitk.wgsl.jinja","derive":{"layout":"\"bhsd\"","splitQueries":false,"qNumHeads":"numHeads","kvNumHeads":"numHeads","headDim":"headSize","headDimV4":"headDimV4","numSplits":"numSplits","usesF16":"tensorDtypes.queryT == \"float16\"","cacheSeqlens":true,"cacheSeqlensIndex":"\"0u\"","hasKeyPadMask":"present.maskIndexT","maskFilterValue":"attrs.mask_filter_value","hasMask":"present.attentionBiasT","useSubgroups":false},"bindings":["query","key_cache","value_cache","seqlens_k","key_pad_mask","attn_mask","partial_out","partial_stats","params_self","params_self_bias"],"dispatch":{"x":"numSplits","y":"attrs.num_heads","z":"dim(shapes.queryT, 0)"}},{"id":"merge","name":"DecoderMaskedMultiHeadAttention.SelfMergeNoSg","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bhsd\"","splitQueries":false,"scalar":"attnScalar","qNumHeads":"numHeads","headDimV4":"headDimV4","numSplits":"numSplits"},"bindings":["partial_out_read","partial_stats_read","output"],"dispatch":{"x":1,"y":"attrs.num_heads","z":"dim(shapes.queryT, 0)"}}],"derive":{"normalizedPartialValues":"tensorDtypes.outputT == \"float32\" and ((present.pastValueT and tensorDtypes.pastValueT != \"float16\") or (present.valueT and tensorDtypes.valueT != \"float16\"))"}}]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/webgpu/metadata.json CHANGED
@@ -1,48 +1 @@
1
- {
2
- "name": "com.microsoft.DecoderMaskedMultiHeadAttention",
3
- "id": "_com_microsoft_decodermaskedmultiheadattention_webgpu_d93bf4a",
4
- "version": 1,
5
- "license": "Apache-2.0",
6
- "backend": { "type": "webgpu" },
7
- "digest": {
8
- "algorithm": "sha256",
9
- "files": {
10
- "attn-flash-decode-splitk-merge.wgsl.jinja": "7fi0SKKDfYjYG+l9OHNcodIeSFH5zXKMIJi9iv32rZo=",
11
- "attn-flash-decode-splitk.wgsl.jinja": "BFL68/1x2lxrN/lTCgC5cy0bmEnkeKQksPtZKwhLE7A=",
12
- "bench.json": "Kow9t33DDsCfO1hnX4CBJ3bKQkH284pj5sKvwirbabA=",
13
- "dmmha-present.wgsl.jinja": "OCydRlEFGVeylOtabFeuAxrofZ/c+uqe5o1RgyWx9fU=",
14
- "manifest.json": "OemoYbwPetpiqBxosVOlV2e20zGYfgzT4zv0y4HdcOc=",
15
- "test.json": "2CVKz1jxKg77lGzgcrIBiv1FqPQNSORMuRdC2qRXNyw="
16
- }
17
- },
18
- "provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },
19
- "webgpu": {
20
- "manifestSpec": "2.1",
21
- "variants": {
22
- "cross_direct": ["attn-flash-decode-splitk.wgsl.jinja"],
23
- "cross": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja"],
24
- "cross_qk_direct": ["attn-flash-decode-splitk.wgsl.jinja"],
25
- "cross_qk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja"],
26
- "cross_mask_direct": ["attn-flash-decode-splitk.wgsl.jinja"],
27
- "cross_mask": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja"],
28
- "cross_mask_qk_direct": ["attn-flash-decode-splitk.wgsl.jinja"],
29
- "cross_mask_qk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja"],
30
- "cross_nosg_direct": ["attn-flash-decode-splitk.wgsl.jinja"],
31
- "cross_nosg": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja"],
32
- "cross_qk_nosg_direct": ["attn-flash-decode-splitk.wgsl.jinja"],
33
- "cross_qk_nosg": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja"],
34
- "cross_mask_nosg_direct": ["attn-flash-decode-splitk.wgsl.jinja"],
35
- "cross_mask_nosg": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja"],
36
- "cross_mask_qk_nosg_direct": ["attn-flash-decode-splitk.wgsl.jinja"],
37
- "cross_mask_qk_nosg": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja"],
38
- "self": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "dmmha-present.wgsl.jinja"],
39
- "self_bias": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "dmmha-present.wgsl.jinja"],
40
- "self_mask": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "dmmha-present.wgsl.jinja"],
41
- "self_mask_bias": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "dmmha-present.wgsl.jinja"],
42
- "self_nosg": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "dmmha-present.wgsl.jinja"],
43
- "self_bias_nosg": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "dmmha-present.wgsl.jinja"],
44
- "self_mask_nosg": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "dmmha-present.wgsl.jinja"],
45
- "self_mask_bias_nosg": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "dmmha-present.wgsl.jinja"]
46
- }
47
- }
48
- }
 
1
+ {"name":"com.microsoft.DecoderMaskedMultiHeadAttention","id":"_com_microsoft_decodermaskedmultiheadattention_webgpu_c003048","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"attn-flash-decode-splitk-merge.wgsl.jinja":"691VPNUex1kO1wAWv654SNtsxbAp3LJiHau0nwR3RJo=","attn-flash-decode-splitk.wgsl.jinja":"ofPMWzqtMfjQ0XuwTaVDae2DSMGjf1Wvcl4WAGydVo4=","bench.json":"Kow9t33DDsCfO1hnX4CBJ3bKQkH284pj5sKvwirbabA=","dmmha-present.wgsl.jinja":"+N/Kr4rArQpFCxxnpwjNUbwE2715cAurJpMcXdb8JRs=","manifest.json":"7/gA6pq8gTmpo84Kcm3FWYswyJBPUrvVgXs9wefFleI=","test.json":"EjJC0pnr/bnrLRxL9vZ21CT5I1PRqDEDkuMK0F5NSQ8="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
build/webgpu/test.json CHANGED
@@ -291,7 +291,7 @@
291
  {
292
  "name": "cross_plain_f16_b1_h4_kv16_d16",
293
  "provenance": {
294
- "notes": "The float16 twin of the plain cross route: operands and output narrow, while the score and online softmax stay float32."
295
  },
296
  "attrs": { "num_heads": 4 },
297
  "inputs": {
@@ -713,7 +713,7 @@
713
  {
714
  "name": "self_scale_b1_h4_cap8_d16_past3",
715
  "provenance": {
716
- "notes": "An explicit scale on the self route, overriding the reciprocal square root of the head size."
717
  },
718
  "attrs": { "num_heads": 4, "past_present_share_buffer": 1, "scale": 0.2 },
719
  "inputs": {
@@ -872,7 +872,7 @@
872
  {
873
  "name": "self_retain_stage8_f16_b4_h8_cap448_d64_past223",
874
  "provenance": {
875
- "notes": "A cache large enough for the retain copy to stage the full eight words per lane, the deepest rung, in float16."
876
  },
877
  "attrs": { "num_heads": 8, "past_present_share_buffer": 1 },
878
  "inputs": {
@@ -912,7 +912,7 @@
912
  {
913
  "name": "self_plain_f16_b1_h4_cap8_d16_past3",
914
  "provenance": {
915
- "notes": "The float16 twin of the plain self route, including the float16 cache the append pass writes."
916
  },
917
  "attrs": { "num_heads": 4, "past_present_share_buffer": 1 },
918
  "inputs": {
@@ -1575,6 +1575,205 @@
1575
  "outputT": { "dtype": "float32", "shape": [1, 1, 384], "tolerance": 0.00002 },
1576
  "qkT": { "dtype": "float16", "shape": [1, 6, 1, 257], "tolerance": 0.002 }
1577
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1578
  }
1579
  ]
1580
  }
 
291
  {
292
  "name": "cross_plain_f16_b1_h4_kv16_d16",
293
  "provenance": {
294
+ "notes": "float16 cross-attention: a [1,1,64] query over 16 keys and values with 4 heads of size 16, float16 operands and output."
295
  },
296
  "attrs": { "num_heads": 4 },
297
  "inputs": {
 
713
  {
714
  "name": "self_scale_b1_h4_cap8_d16_past3",
715
  "provenance": {
716
+ "notes": "An explicit scale of 0.2 overriding the default reciprocal square root of the head size (0.25), with 4 heads of size 16, a past of 3 tokens and a cache of capacity 8."
717
  },
718
  "attrs": { "num_heads": 4, "past_present_share_buffer": 1, "scale": 0.2 },
719
  "inputs": {
 
872
  {
873
  "name": "self_retain_stage8_f16_b4_h8_cap448_d64_past223",
874
  "provenance": {
875
+ "notes": "Float16 shared-buffer decode with batch 4, 8 heads of size 64, cache capacity 448 and past length 223."
876
  },
877
  "attrs": { "num_heads": 8, "past_present_share_buffer": 1 },
878
  "inputs": {
 
912
  {
913
  "name": "self_plain_f16_b1_h4_cap8_d16_past3",
914
  "provenance": {
915
+ "notes": "float16 self-attention with 4 heads of size 16 and a past of 3 tokens in a cache of capacity 8; the new key and value are appended to the float16 cache."
916
  },
917
  "attrs": { "num_heads": 4, "past_present_share_buffer": 1 },
918
  "inputs": {
 
1575
  "outputT": { "dtype": "float32", "shape": [1, 1, 384], "tolerance": 0.00002 },
1576
  "qkT": { "dtype": "float16", "shape": [1, 6, 1, 257], "tolerance": 0.002 }
1577
  }
1578
+ },
1579
+ {
1580
+ "name": "device_bounds_negative_sequence_count",
1581
+ "provenance": {
1582
+ "notes": "Negative device sequence metadata yields zero attention, no append, and complete preserved cache outputs. Handling this invalid input goes beyond the ONNX Runtime spec; the expected values define that behavior."
1583
+ },
1584
+ "attrs": { "num_heads": 4, "past_present_share_buffer": 1 },
1585
+ "inputs": {
1586
+ "queryT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 0.0 } },
1587
+ "keyT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 0.0 } },
1588
+ "valueT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 8.0 } },
1589
+ "pastKeyT": { "dtype": "float32", "shape": [1, 4, 8, 16], "data": { "kind": "constant", "value": 3.0 } },
1590
+ "pastValueT": { "dtype": "float32", "shape": [1, 4, 8, 16], "data": { "kind": "constant", "value": 4.0 } },
1591
+ "pastSequenceLengthT": { "dtype": "int32", "shape": [1], "data": { "kind": "constant", "value": -2 } }
1592
+ },
1593
+ "outputs": {
1594
+ "outputT": {
1595
+ "dtype": "float32",
1596
+ "shape": [1, 1, 64],
1597
+ "tolerance": 0.00002,
1598
+ "data": { "kind": "constant", "value": 0.0 }
1599
+ },
1600
+ "presentKeyT": {
1601
+ "dtype": "float32",
1602
+ "shape": [1, 4, 8, 16],
1603
+ "tolerance": 0.000001,
1604
+ "data": { "kind": "constant", "value": 3.0 }
1605
+ },
1606
+ "presentValueT": {
1607
+ "dtype": "float32",
1608
+ "shape": [1, 4, 8, 16],
1609
+ "tolerance": 0.000001,
1610
+ "data": { "kind": "constant", "value": 4.0 }
1611
+ }
1612
+ }
1613
+ },
1614
+ {
1615
+ "name": "device_bounds_empty_sentinel",
1616
+ "provenance": {
1617
+ "notes": "pastSequenceLength is -1, outside the valid range, on a cache of capacity 8 (zero query and key, value 8, cached keys 3 and values 4): the expected output is all zeros and the cache equals the input cache."
1618
+ },
1619
+ "attrs": { "num_heads": 4, "past_present_share_buffer": 1 },
1620
+ "inputs": {
1621
+ "queryT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 0.0 } },
1622
+ "keyT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 0.0 } },
1623
+ "valueT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 8.0 } },
1624
+ "pastKeyT": { "dtype": "float32", "shape": [1, 4, 8, 16], "data": { "kind": "constant", "value": 3.0 } },
1625
+ "pastValueT": { "dtype": "float32", "shape": [1, 4, 8, 16], "data": { "kind": "constant", "value": 4.0 } },
1626
+ "pastSequenceLengthT": { "dtype": "int32", "shape": [1], "data": { "kind": "constant", "value": -1 } }
1627
+ },
1628
+ "outputs": {
1629
+ "outputT": {
1630
+ "dtype": "float32",
1631
+ "shape": [1, 1, 64],
1632
+ "tolerance": 0.00002,
1633
+ "data": { "kind": "constant", "value": 0.0 }
1634
+ },
1635
+ "presentKeyT": {
1636
+ "dtype": "float32",
1637
+ "shape": [1, 4, 8, 16],
1638
+ "tolerance": 0.000001,
1639
+ "data": { "kind": "constant", "value": 3.0 }
1640
+ },
1641
+ "presentValueT": {
1642
+ "dtype": "float32",
1643
+ "shape": [1, 4, 8, 16],
1644
+ "tolerance": 0.000001,
1645
+ "data": { "kind": "constant", "value": 4.0 }
1646
+ }
1647
+ }
1648
+ },
1649
+ {
1650
+ "name": "device_bounds_sequence_int32_min",
1651
+ "provenance": {
1652
+ "notes": "pastSequenceLength is the int32 minimum on a cache of capacity 8 (zero query and key, value 8, cached keys 3 and values 4): the expected output is all zeros and the cache equals the input cache."
1653
+ },
1654
+ "attrs": { "num_heads": 4, "past_present_share_buffer": 1 },
1655
+ "inputs": {
1656
+ "queryT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 0.0 } },
1657
+ "keyT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 0.0 } },
1658
+ "valueT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 8.0 } },
1659
+ "pastKeyT": { "dtype": "float32", "shape": [1, 4, 8, 16], "data": { "kind": "constant", "value": 3.0 } },
1660
+ "pastValueT": { "dtype": "float32", "shape": [1, 4, 8, 16], "data": { "kind": "constant", "value": 4.0 } },
1661
+ "pastSequenceLengthT": { "dtype": "int32", "shape": [1], "data": { "kind": "constant", "value": -2147483648 } }
1662
+ },
1663
+ "outputs": {
1664
+ "outputT": {
1665
+ "dtype": "float32",
1666
+ "shape": [1, 1, 64],
1667
+ "tolerance": 0.00002,
1668
+ "data": { "kind": "constant", "value": 0.0 }
1669
+ },
1670
+ "presentKeyT": {
1671
+ "dtype": "float32",
1672
+ "shape": [1, 4, 8, 16],
1673
+ "tolerance": 0.000001,
1674
+ "data": { "kind": "constant", "value": 3.0 }
1675
+ },
1676
+ "presentValueT": {
1677
+ "dtype": "float32",
1678
+ "shape": [1, 4, 8, 16],
1679
+ "tolerance": 0.000001,
1680
+ "data": { "kind": "constant", "value": 4.0 }
1681
+ }
1682
+ }
1683
+ },
1684
+ {
1685
+ "name": "device_bounds_sequence_int32_max",
1686
+ "provenance": {
1687
+ "notes": "pastSequenceLength is the int32 maximum, far above the cache capacity of 8 (zero query and key, value 8, cached keys 3 and values 4): the expected output is 4, the cached value, and the cache equals the input cache."
1688
+ },
1689
+ "attrs": { "num_heads": 4, "past_present_share_buffer": 1 },
1690
+ "inputs": {
1691
+ "queryT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 0.0 } },
1692
+ "keyT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 0.0 } },
1693
+ "valueT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "constant", "value": 8.0 } },
1694
+ "pastKeyT": { "dtype": "float32", "shape": [1, 4, 8, 16], "data": { "kind": "constant", "value": 3.0 } },
1695
+ "pastValueT": { "dtype": "float32", "shape": [1, 4, 8, 16], "data": { "kind": "constant", "value": 4.0 } },
1696
+ "pastSequenceLengthT": { "dtype": "int32", "shape": [1], "data": { "kind": "constant", "value": 2147483647 } }
1697
+ },
1698
+ "outputs": {
1699
+ "outputT": {
1700
+ "dtype": "float32",
1701
+ "shape": [1, 1, 64],
1702
+ "tolerance": 0.00002,
1703
+ "data": { "kind": "constant", "value": 4.0 }
1704
+ },
1705
+ "presentKeyT": {
1706
+ "dtype": "float32",
1707
+ "shape": [1, 4, 8, 16],
1708
+ "tolerance": 0.000001,
1709
+ "data": { "kind": "constant", "value": 3.0 }
1710
+ },
1711
+ "presentValueT": {
1712
+ "dtype": "float32",
1713
+ "shape": [1, 4, 8, 16],
1714
+ "tolerance": 0.000001,
1715
+ "data": { "kind": "constant", "value": 4.0 }
1716
+ }
1717
+ }
1718
+ },
1719
+ {
1720
+ "name": "cross_mixed_component_means_512",
1721
+ "provenance": {
1722
+ "notes": "Uniform, power-of-two probabilities average alternating keys. A head of 68 components shifts the eight-value cycle four places per key. Adjacent components cancel, exceed the f32 range in an unscaled sum, or retain a small finite mean."
1723
+ },
1724
+ "attrs": { "num_heads": 1 },
1725
+ "inputs": {
1726
+ "queryT": { "dtype": "float32", "shape": [1, 1, 68], "data": { "kind": "cycle", "values": [0.0] } },
1727
+ "keyT": { "dtype": "float32", "shape": [1, 1, 512, 68], "data": { "kind": "cycle", "values": [0.0] } },
1728
+ "valueT": {
1729
+ "dtype": "float32",
1730
+ "shape": [1, 1, 512, 68],
1731
+ "data": {
1732
+ "kind": "cycle",
1733
+ "values": [3.32306998946229e+35, 4.0, 8.507059173023462e+37, 8.470329472543003e-22, -3.32306998946229e+35, -4.0, 8.507059173023462e+37, 8.470329472543003e-22]
1734
+ }
1735
+ }
1736
+ },
1737
+ "outputs": {
1738
+ "outputT": {
1739
+ "dtype": "float32",
1740
+ "shape": [1, 1, 68],
1741
+ "data": { "kind": "cycle", "values": [0.0, 0.0, 8.507059173023462e+37, 8.470329472543003e-22] },
1742
+ "tolerance": 0,
1743
+ "relTolerance": 0.000002
1744
+ }
1745
+ }
1746
+ },
1747
+ {
1748
+ "name": "cross_mixed_component_means_4096",
1749
+ "provenance": {
1750
+ "notes": "Uniform probabilities average 1,365 complete three-key cycles and one extra key. A 64-component row advances the twelve-value cycle by four. Each cancellation channel retains the contribution of its first key divided by 4,096, while the large and small constant channels retain their values."
1751
+ },
1752
+ "attrs": { "num_heads": 1 },
1753
+ "inputs": {
1754
+ "queryT": { "dtype": "float32", "shape": [1, 1, 64], "data": { "kind": "cycle", "values": [0.0] } },
1755
+ "keyT": { "dtype": "float32", "shape": [1, 1, 4096, 64], "data": { "kind": "cycle", "values": [0.0] } },
1756
+ "valueT": {
1757
+ "dtype": "float32",
1758
+ "shape": [1, 1, 4096, 64],
1759
+ "data": {
1760
+ "kind": "cycle",
1761
+ "values": [3.32306998946229e+35, 4.0, 8.507059173023462e+37, 8.470329472543003e-22, -3.32306998946229e+35, -4.0, 8.507059173023462e+37, 8.470329472543003e-22, 0.0, 0.0, 8.507059173023462e+37, 8.470329472543003e-22]
1762
+ }
1763
+ }
1764
+ },
1765
+ "outputs": {
1766
+ "outputT": {
1767
+ "dtype": "float32",
1768
+ "shape": [1, 1, 64],
1769
+ "data": {
1770
+ "kind": "cycle",
1771
+ "values": [8.112963841460668e+31, 0.0009765625, 8.507059173023462e+37, 8.470329472543003e-22, -8.112963841460668e+31, -0.0009765625, 8.507059173023462e+37, 8.470329472543003e-22, 0.0, 0.0, 8.507059173023462e+37, 8.470329472543003e-22]
1772
+ },
1773
+ "tolerance": 0,
1774
+ "relTolerance": 0.000002
1775
+ }
1776
+ }
1777
  }
1778
  ]
1779
  }