sync 4385228f788d
Browse filesFiles changed (29)
- README.md+107-55
- build/webgpu/attention-flash-sgmat16.wgsl.jinjaAdded+1095
- build/webgpu/attention-prepare-f32.wgsl.jinjaAdded+18
- build/webgpu/attention-rank4-tiled.wgsl.jinja+551-17
- build/webgpu/attn-decode-gqa-splitk-merge.wgsl.jinjaAdded+477
- build/webgpu/attn-decode-gqa-splitk.wgsl.jinjaAdded+640
- build/webgpu/attn-flash-decode-splitk-merge.wgsl.jinja+568-27
- build/webgpu/attn-flash-decode-splitk.wgsl.jinja+718-64
- build/webgpu/attn-flash-online.wgsl.jinja+547-48
- build/webgpu/attn-flash-prefill-cluster.wgsl.jinja+897-140
- build/webgpu/attn-flash-q32-broadcast.wgsl.jinja+517-59
- build/webgpu/attn-materialized-rowstats-combine-f32.wgsl.jinja+6-3
- build/webgpu/attn-materialized-score-f32.wgsl.jinjaAdded+295
- build/webgpu/attn-materialized-sgmat-f32.wgsl.jinja+720-140
- build/webgpu/attn-materialized-shaped.wgsl.jinjaAdded+768
- build/webgpu/attn-materialized-softmax-f32.wgsl.jinjaAdded+119
- build/webgpu/attn-online-scalar.wgsl.jinja+503-39
- build/webgpu/bench.json
- build/webgpu/gqa-attention.wgsl.jinja+528-59
- build/webgpu/gqa-norm-rotate-rows.wgsl.jinjaAdded+89
- build/webgpu/gqa-present.wgsl.jinja+38-112
- build/webgpu/gqa-qprep.wgsl.jinja+40-6
- build/webgpu/gqa-score-matrix.wgsl.jinjaAdded+182
- build/webgpu/gqa-score-range.wgsl.jinjaAdded+79
- build/webgpu/gqa-stream-matrix8.wgsl.jinjaAdded+206
- build/webgpu/gqa-window-cache.wgsl.jinjaAdded+156
- build/webgpu/manifest.json
- build/webgpu/metadata.json+1-89
- build/webgpu/test.json
15 unmodified lines1617181920213 unmodified lines25262728293031323334355 unmodified lines4142434445464711 unmodified lines5960616263646511 unmodified lines77787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461474 unmodified lines1521531541551561571581591601611621638 unmodified lines17217317417515 unmodified linesSee the [ONNX Runtime `GroupQueryAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.GroupQueryAttention) for the reference semantics.## Inputs| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |3 unmodified lines| `valueT` | `value` | `T` | `3` | — | Value tensor of shape `(batch_size, kv_sequence_length, kv_num_heads * head_size)`. | required || `pastKeyT` | `past_key` | `T_CACHE` | `4` | — | Optional cached key state in BNSH format. Its sequence axis is `max_sequence_length` when the past and present buffers are shared, otherwise `past_sequence_length`; int4 stores each signed value as a +8-biased nibble, with the even head coordinate low, packing two values per logical uint8 element and widening each byte to one u32 WebGPU buffer word. | optional || `pastValueT` | `past_value` | `T_CACHE` | `4` | — | Optional cached value state in BNSH format with the same length and packing semantics as `past_key`. | optional || `seqlensKT` | `seqlens_k` | `M` | `1` | — | Int32 tensor of shape `(batch_size)` containing each sample's total sequence length minus one. | required || `totalSequenceLengthT` | `total_sequence_length` | `M` | `1` | — | Length-one int32 tensor containing the maximum total sequence length (past plus new) in the batch. | required || `cosCacheT` | `cos_cache` | `T` | `2` | — | Optional cosine cache for rotary embeddings with shape `(max_sequence_length, head_size / 2)`. | optional || `sinCacheT` | `sin_cache` | `T` | `2` | — | Optional sine cache for rotary embeddings with shape `(max_sequence_length, head_size / 2)`. | optional || `attentionBiasT` | `attention_bias` | `T` | `4` | — | Optional additive term for QK scores with shape `(batch_size or 1, num_heads or 1, sequence_length, total_sequence_length)`; the first two dimensions broadcast. | optional || `headSinkT` | `head_sink` | `T` | `1` | — | Optional per-head smooth factor of shape `(num_heads)` added to the softmax denominator. | optional || `kScaleT` | `k_scale` | `T_KV_SCALE` | `1` | — | Optional float32 key-cache scale: one value for `PER_TENSOR`, or `kv_num_heads * head_size` values for `PER_CHANNEL`. | optional || `vScaleT` | `v_scale` | `T_KV_SCALE` | `1` | — | Optional float32 value-cache scale with the same shape convention as `k_scale`. | optional |5 unmodified lines| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence || --- | --- | --- | --- | --- | --- | --- || `outputT` | `output` | `T` | `3` | same as `queryT` | Attention output of shape `(batch_size, sequence_length, hidden_size)`. | required || `presentKeyT` | `present_key` | `T_CACHE` | `4` | — | Updated key cache in BNSH format. Its sequence axis is `max_sequence_length` for a shared buffer, otherwise `past_sequence_length + kv_sequence_length`; int4 stores each signed value as a +8-biased nibble, with the even head coordinate low, packing two values per logical uint8 element and widening each byte to one u32 WebGPU buffer word. | required || `presentValueT` | `present_value` | `T_CACHE` | `4` | — | Updated value cache in BNSH format with the same length and packing semantics as `present_key`. | required |## Attributes11 unmodified lines| `num_heads` | — | Number of query attention heads. || `qk_norm_epsilon` | `0.000001` | Epsilon for the per-head Q/K RMS normalization applied when both normalization weights are provided. || `scale` | — | Optional QK score scale; zero or omission selects `1 / sqrt(head_size)`. || `sliding_window_cache` | `0` | Set to 1 when past/present caches are fixed-size window buffers that evict old tokens from the front. Requires `local_window_size > 0` and enough cache capacity. || `smooth_softmax` | `-1` | Set to 1 to enable the smooth-softmax denominator term. || `softcap` | `0` | Positive softcap applied to attention scores. The default 0 disables soft-capping. || `v_quant_type` | `"NONE"` | Value-cache quantization mode: `NONE`, `PER_TENSOR`, or `PER_CHANNEL`. |11 unmodified linesOne implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.- `qkv_present_materialized_sgmat_f32` — Materialized float32 subgroup-matrix prefill for bidirectional QKV without past state. `seqlens_k` is metadata-only; the score pass emits per-row softmax statistics, the apply pass normalizes and applies the scores, and the present copy preserves the supplied key and value tensors.- `past_kv_materialized_sgmat_f32` — Materializes the causal score matrix with float32 subgroup-matrix tiles over the shared float cache, then applies the softmax-normalized weights with subgroup-matrix tiles. Both passes skip key tiles beyond each query tile's causal bound.- `past_kv_bias_materialized_sgmat_f32` — Materializes causal scores with float32 subgroup-matrix tiles, broadcasts and adds the attention bias across batch and head dimensions, folds the biased scores into row statistics, and applies the normalized weights with subgroup-matrix tiles.- `past_kv_materialized_sgmat_f16` — Materializes the causal score matrix with `f16` operand tiles feeding `f32`-accumulating subgroup matrices over the shared cache and applies the softmax-normalized weights the same way; scores and row statistics stay `f32`. The score pass skips key tiles past each query tile's causal bound and the apply pass stops its reduction there.- `past_kv_rotary_materialized_sgmat_f32` — Rotates each query block at its absolute positions, then materializes causal scores against rotary-transformed cached keys and applies the normalized weights. The score and apply passes skip tiles beyond each query tile's causal bound.- `past_kv_rotary_materialized_sgmat_f16` — Materializes the causal score matrix with `f16` operand tiles feeding `f32`-accumulating subgroup matrices over the shared cache and applies the softmax-normalized weights the same way; scores and row statistics stay `f32`. The score pass skips key tiles past each query tile's causal bound and the apply pass stops its reduction there.- `new_kv_past_materialized_sgmat_f32` — For chunked prefill, merges the past cache with new key/value rows, materializes causal scores over the merged cache, and applies the normalized weights using the same right-aligned causal bound.- `window_shift_materialized_sgmat_f32` — Materializes causal chunked-prefill attention with a windowed cache. The shift pass compacts surviving rows and appends the chunk; score and apply passes enforce both the sliding-window floor and causal bound.- `share_append_materialized_sgmat_f32` — Materializes causal chunked-prefill attention while updating a shared-capacity cache in place. Score and apply passes bound every causal tile by the live length from `seqlens_k`, not the buffer capacity, so right-padded batches remain left-aligned.- `new_kv_share_append_split` — Retains the existing cache and appends new key/value rows in separate passes before portable attention. It avoids rebuilding unchanged cache positions when the past and present allocations share capacity.- `new_kv_share_append_bidirectional_split` — Bidirectional (`causal = 0`) attention over a shared-capacity cache: the new key/value rows are appended exactly as in the causal sibling, then every query attends to the whole live range `[0, seqlens_k[b] + 1)` instead of stopping at its own position. ONNX Runtime forbids `causal = 0` with a local window, so the window floor never applies here.- `qkv_present_tiled_nosg` — Portable tiled prefill route that computes attention online and writes the present cache separately. It is used when the flash shape is valid but no suitable subgroup route is admissible.- `qkv_present_flash_causal` — Causal prefill without a past cache and without a sliding window (`causal=1`, `local_window_size=-1`): the spelling onnxruntime's GroupQueryAttention tests use for a first prompt. The twin of `qkv_present_flash` with the causal ceiling enabled; the key sequence equals the query sequence, so the upper-left ceiling is the right one.- `qkv_present_causal` — Causal prefill without a past cache and without a sliding window (`causal=1`, `local_window_size=-1`): the spelling onnxruntime's GroupQueryAttention tests use for a first prompt. The twin of `qkv_present` with the causal ceiling enabled; the key sequence equals the query sequence, so the upper-left ceiling is the right one.- `quant_int8_decode_splitk` — Appends int8-quantized key/value rows, partitions cached decode across the key axis, and merges partial online-softmax results. Used when one workgroup per head exposes too little independent work.- `qkv_present_flash_splitk` — Partitions direct Q/K/V attention across the key axis, merges partial online-softmax results, and writes the present cache separately. It serves short-query shapes needing more key-axis parallelism.- `qkv_present_flash_cluster` — Computes clustered online-softmax prefill directly from Q/K/V and writes the present cache separately. The family provides subgroup and portable reductions for the same tiled algorithm.- `past_kv_decode_splitk` — Updates the float cache in copy, merge, or window-shift mode, then partitions cached decode across the key axis and combines partial online-softmax results. The family includes subgroup and portable forms.- `new_kv_past_decode_splitk` — Updates the float cache in copy, merge, or window-shift mode, then partitions cached decode across the key axis and combines partial online-softmax results. The family includes subgroup and portable forms.- `window_shift_decode_splitk` — Updates the float cache in copy, merge, or window-shift mode, then partitions cached decode across the key axis and combines partial online-softmax results. The family includes subgroup and portable forms.- `past_kv_flash_prefill` — Updates the float cache in the selected mode and applies clustered online-softmax causal prefill with the configured cache, mask, rotary, softcap, bias, or head-sink features.- `new_kv_past_flash_prefill` — Updates the float cache in the selected mode and applies clustered online-softmax causal prefill with the configured cache, mask, rotary, softcap, bias, or head-sink features.- `past_kv_rotary_flash_prefill` — Updates the float cache in the selected mode and applies clustered online-softmax causal prefill with the configured cache, mask, rotary, softcap, bias, or head-sink features.- `past_kv_softcap_flash_prefill` — Updates the float cache in the selected mode and applies clustered online-softmax causal prefill with the configured cache, mask, rotary, softcap, bias, or head-sink features.- `past_kv_headsink_flash_prefill` — Updates the float cache in the selected mode and applies clustered online-softmax causal prefill with the configured cache, mask, rotary, softcap, bias, or head-sink features.- `past_kv_bias_headsink_flash_prefill` — Updates the float cache in the selected mode and applies clustered online-softmax causal prefill with the configured cache, mask, rotary, softcap, bias, or head-sink features.- `window_shift_flash_prefill` — Updates the float cache in the selected mode and applies clustered online-softmax causal prefill with the configured cache, mask, rotary, softcap, bias, or head-sink features.- `window_shift_rotary_append` — Windowed cache with rotary embeddings. The shift pass slides surviving rows down by the eviction count and clears what left the window; the append pass writes the new key/value rows and rotates K at its ABSOLUTE position (window origin plus row, not the cache row); attention rotates Q at the same absolute position and masks cache-relative.- `window_shift_rotary_headsink_append` — Windowed rotary cache with a per-head softmax sink (the gpt-oss attention layer). The sink contributes `exp(sink - m)` to the denominator once per query row and nothing to the numerator.- `window_shift_rotary_bias_append` — Windowed rotary cache with an additive attention bias. The bias row is indexed by ABSOLUTE key position with the tensor's own last dimension as the stride (ONNX spells it `total_sequence_length`, which keeps counting past the cache capacity), so resident cache row j reads bias column `origin + j`.- `quant_int8_flash_prefill` — Builds an int8 or int4 cache and applies clustered online-softmax prefill directly from the packed values. The family supplies subgroup and portable reductions.- `quant_int4_flash_prefill` — Builds an int8 or int4 cache and applies clustered online-softmax prefill directly from the packed values. The family supplies subgroup and portable reductions.- `share_append_split_decode_splitk` — Retains shared-capacity cache rows, appends new rows separately, then partitions decode across the key axis. It avoids rebuilding unchanged cache positions while exposing split-key parallelism.- `share_append_split_flash_prefill` — Retains shared-capacity cache rows, appends new rows separately, then applies clustered causal prefill. It avoids rebuilding unchanged cache positions and includes subgroup and portable forms.- `share_append_bidirectional_flash_prefill` — Retains and appends a shared-capacity cache, then applies clustered bidirectional prefill to the full live key range.## Device requirementsSome implementation variants require `subgroup-matrix`, `shader-f16`, and `subgroups`. These are route-specific capabilities, not package-wide requirements; availability also depends on the request shape and dtype.## Files- [`metadata.json`](build/webgpu/metadata.json) — kernel metadata (id, digests, per-variant templates, provenance)- [`manifest.json`](build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](build/webgpu/test.json) — correctness cases- [`bench.json`](build/webgpu/bench.json) — benchmark cases- [`attention-rank4-tiled.wgsl.jinja`](build/webgpu/attention-rank4-tiled.wgsl.jinja)- [`attn-flash-decode-splitk-merge.wgsl.jinja`](build/webgpu/attn-flash-decode-splitk-merge.wgsl.jinja)- [`attn-flash-decode-splitk.wgsl.jinja`](build/webgpu/attn-flash-decode-splitk.wgsl.jinja)- [`attn-flash-online.wgsl.jinja`](build/webgpu/attn-flash-online.wgsl.jinja)- [`attn-flash-prefill-cluster.wgsl.jinja`](build/webgpu/attn-flash-prefill-cluster.wgsl.jinja)- [`attn-flash-q32-broadcast.wgsl.jinja`](build/webgpu/attn-flash-q32-broadcast.wgsl.jinja)- [`attn-materialized-rowstats-combine-f32.wgsl.jinja`](build/webgpu/attn-materialized-rowstats-combine-f32.wgsl.jinja)- [`attn-materialized-sgmat-f32.wgsl.jinja`](build/webgpu/attn-materialized-sgmat-f32.wgsl.jinja)- [`attn-online-scalar.wgsl.jinja`](build/webgpu/attn-online-scalar.wgsl.jinja)- [`gqa-attention.wgsl.jinja`](build/webgpu/gqa-attention.wgsl.jinja)- [`gqa-present.wgsl.jinja`](build/webgpu/gqa-present.wgsl.jinja)- [`gqa-qprep.wgsl.jinja`](build/webgpu/gqa-qprep.wgsl.jinja)## Use with `@huggingface/kernels````shnpm install --save-exact @huggingface/kernels@0.0.1-preview.3```Outputs with inferable metadata are allocated automatically. Explicit `outputs` entries request optional results or provide metadata that cannot be inferred from the supplied inputs and attributes.This example supplies explicit metadata for:4 unmodified linesThe `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.Replace each `*Data` placeholder with a typed array containing the corresponding input data.```jsimport { getKernel } from "@huggingface/kernels";const kernel = await getKernel("webgpu-kernels/com.microsoft.GroupQueryAttention", { version: 1 });// Explicit destinations request optional results or supply metadata that cannot be inferred.const { outputT, presentKeyT, presentValueT } = await kernel({queryT: { data: queryTData, shape: [1, 2, 8] },8 unmodified linespresentValueT: { shape: [1, 1, 2, 8], dtype: "float32" },},});```15 unmodified lines16171819202122232425262728293031323 unmodified lines36373839404142434445465 unmodified lines5253545556575811 unmodified lines7071727374757611 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921934 unmodified lines1981992002012022032042052062072082092102112122132148 unmodified lines22322422522622715 unmodified linesSee the [ONNX Runtime `GroupQueryAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.GroupQueryAttention) for the reference semantics.## Differences from the ONNX Runtime spec- Input `position_ids`: Positions are derived from `seqlens_k`; explicit position IDs are unsupported.- Output `output_qk`: The package does not expose the optional diagnostic QK matrix output.- Attribute `qk_output`: The package does not expose `output_qk`, so diagnostic QK output selection is not implemented.- Attribute `rotary_interleaved`: Only the non-interleaved rotary layout is supported.- Input `keyT` (ONNX `key`): This package requires an explicit key tensor; packed QKV input is unsupported.- Input `valueT` (ONNX `value`): This package requires an explicit value tensor; packed QKV input is unsupported.- Output `presentKeyT` (ONNX `present_key`): The package always materializes the updated key cache.- Output `presentValueT` (ONNX `present_value`): The package always materializes the updated value cache.## Inputs| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |3 unmodified lines| `valueT` | `value` | `T` | `3` | — | Value tensor of shape `(batch_size, kv_sequence_length, kv_num_heads * head_size)`. | required || `pastKeyT` | `past_key` | `T_CACHE` | `4` | — | Optional cached key state in BNSH format. Its sequence axis is `max_sequence_length` when the past and present buffers are shared, otherwise `past_sequence_length`; int4 stores each signed value as a +8-biased nibble, with the even head coordinate low, packing two values per logical uint8 element and widening each byte to one u32 WebGPU buffer word. | optional || `pastValueT` | `past_value` | `T_CACHE` | `4` | — | Optional cached value state in BNSH format with the same length and packing semantics as `past_key`. | optional || `seqlensKT` | `seqlens_k` | `M` | `1` | — | Int32 tensor of shape `(batch_size)` containing each sample's total sequence length minus one. Windowed caches keep absolute positions however many rows the cache holds. In windowed mode, a negative value or a total smaller than the new chunk zeroes that sample's attention output and present cache, even where its queries contain NaN. A `seqlens_k` value of `INT32_MAX` is handled without overflow, which goes beyond the ONNX Runtime spec. | required || `totalSequenceLengthT` | `total_sequence_length` | `M` | `1` | — | Length-one int32 tensor containing the maximum total sequence length (past plus new) in the batch. The cache shaders use `seqlens_k` for addressing and do not read this scalar's contents; callers must supply a consistent maximum under the ORT contract. | required || `cosCacheT` | `cos_cache` | `T` | `2` | — | Optional cosine cache for rotary embeddings with shape `(max_sequence_length, head_size / 2)`. | optional || `sinCacheT` | `sin_cache` | `T` | `2` | — | Optional sine cache for rotary embeddings with shape `(max_sequence_length, head_size / 2)`. | optional || `attentionBiasT` | `attention_bias` | `T` | `4` | — | Optional additive term for QK scores with shape `(batch_size or 1, num_heads or 1, sequence_length, total_sequence_length)`; the first two dimensions broadcast. Windowed-cache columns use absolute key positions. If a bias row is narrower than the key count, the missing columns contribute zero and no other query row is read. | optional || `headSinkT` | `head_sink` | `T` | `1` | — | Optional per-head smooth factor of shape `(num_heads)` added to the softmax denominator. | optional || `kScaleT` | `k_scale` | `T_KV_SCALE` | `1` | — | Optional float32 key-cache scale: one value for `PER_TENSOR`, or `kv_num_heads * head_size` values for `PER_CHANNEL`. | optional || `vScaleT` | `v_scale` | `T_KV_SCALE` | `1` | — | Optional float32 value-cache scale with the same shape convention as `k_scale`. | optional |5 unmodified lines| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence || --- | --- | --- | --- | --- | --- | --- || `outputT` | `output` | `T` | `3` | same as `queryT` | Attention output of shape `(batch_size, sequence_length, hidden_size)`. | required || `presentKeyT` | `present_key` | `T_CACHE` | `4` | — | Updated key cache in BNSH format. Its sequence axis is `max_sequence_length` for a shared buffer, otherwise `past_sequence_length + kv_sequence_length`; int4 stores each signed value as a +8-biased nibble, with the even head coordinate low, packing two values per logical uint8 element and widening each byte to one u32 WebGPU buffer word. In `sliding_window_cache` mode, capacity is fixed and only the block-eviction prefix described by that attribute is kept. | required || `presentValueT` | `present_value` | `T_CACHE` | `4` | — | Updated value cache in BNSH format with the same length and packing semantics as `present_key`. | required |## Attributes11 unmodified lines| `num_heads` | — | Number of query attention heads. || `qk_norm_epsilon` | `0.000001` | Epsilon for the per-head Q/K RMS normalization applied when both normalization weights are provided. || `scale` | — | Optional QK score scale; zero or omission selects `1 / sqrt(head_size)`. || `sliding_window_cache` | `0` | Set to 1 for fixed-capacity block-eviction caches. Requires positive `local_window_size` W and capacity C>=W. With T=`seqlens_k[b]`+1, the defined prefix has L(T)=T for T<=C, otherwise W+((T-C-1) mod (C-W+1)); row i holds position T-L(T)+i. Attention stages the rows already cached plus the new chunk before compaction, including chunks larger than C. Rows after the prefix, which ONNX Runtime leaves undefined, are zeroed. Uneven multi-token batches go beyond what ONNX Runtime's CPU provider accepts. Rollback without editing is exact only if L(T-k)=L(T)-k; otherwise the caller must restore history. || `smooth_softmax` | `-1` | Set to 1 to enable the smooth-softmax denominator term. || `softcap` | `0` | Positive softcap applied to attention scores. The default 0 disables soft-capping. || `v_quant_type` | `"NONE"` | Value-cache quantization mode: `NONE`, `PER_TENSOR`, or `PER_CHANNEL`. |11 unmodified linesOne implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.- `qkv_present_materialized_sgmat_f32` — Bidirectional float32 prefill without past state. Subgroup matrices score queries and apply values. A per-tile roundoff check recomputes tiles whose query-key products are sensitive to rounding with compensated accumulation.- `cached_materialized_sgmat_f32` — Updates the cache (a copy of the shared past, or the past merged with new rows), materializes causal scores with input-dtype subgroup-matrix tiles and `f32` accumulation, optionally adds the broadcast attention bias, and applies the normalized weights. Both passes skip key tiles past each query tile's right-aligned causal bound.- `past_kv_rotary_materialized_sgmat_f32` — Rotates each query block at its absolute positions, then materializes causal scores against rotary-transformed cached keys and applies the normalized weights. The score and apply passes skip tiles beyond each query tile's causal bound.- `past_kv_rotary_materialized_sgmat_f16` — Materializes the causal score matrix with `f16` operand tiles feeding `f32`-accumulating subgroup matrices over the shared cache and applies the softmax-normalized weights the same way; scores and row statistics stay `f32`. The score pass skips key tiles past each query tile's causal bound and the apply pass stops its reduction there.- `share_append_materialized_sgmat_f32` — Materializes causal chunked-prefill attention while updating a shared-capacity cache in place. Score and apply passes bound every causal tile by the live length from `seqlens_k`, not the buffer capacity, so right-padded batches remain left-aligned.- `new_kv_share_append_split` — Retains a shared-capacity cache and appends new key/value rows in separate passes (rotating K when rotary is on), then runs portable attention with an optional per-head sink. Bidirectional (`causal = 0`) attention covers the whole live range `[0, seqlens_k[b] + 1)`; the operator requires `local_window_size = -1` when `causal = 0`.- `qkv_present_tiled_nosg` — Tiled prefill without subgroups that computes attention online and writes the present cache separately. Used when the flash shape fits but no subgroup variant applies.- `qkv_stream_matrix8` — Fuses bidirectional prefill scores, online softmax and value reduction within each 32-query tile. The 8×8 matrix contractions accumulate in float32 and keep probabilities and widened values in workgroup memory.- `qkv_present_flash_sgmat16_f16` — Half prefill from direct query, key and value on 16x16x16 subgroup matrices with float32 accumulation: each workgroup sweeps one head's keys once for 64 queries with an online softmax over staged key and value tiles, bounded by each batch's sequence length; a separate pass writes the present cache.- `qkv_present_flash_sgmat16_split_f32` — Float32 online attention after a pass that stores the query as float32. Query-key products, softmax probabilities and value accumulation remain float32, including wide-range and cancellation-sensitive inputs.- `qkv_present_flash`, `qkv_present` — Computes online-softmax attention directly from Q/K/V and writes the present cache separately. `causal=1` with `local_window_size=-1` and no past cache applies the causal mask; keys then equal queries, so upper-left alignment is correct.- `append_decode_splitk` — Appends the new key/value rows to the cache (int8-quantized for a quantized cache, or after the retained rows of a shared-capacity cache), partitions decode across the key axis, and merges partial online-softmax results. Used when one workgroup per head exposes too little independent work.- `qkv_present_flash_splitk` — Partitions direct Q/K/V attention across the key axis, merges partial online-softmax results, and writes the present cache separately. It serves short-query shapes needing more key-axis parallelism.- `qkv_present_flash_cluster` — Computes clustered online-softmax prefill directly from Q/K/V and writes the present cache separately. The family provides subgroup and portable reductions for the same tiled algorithm.- `qkv_present_flash_cluster_causal` — Compute causal prompt prefill with subgroup query clusters and shared key/value tiles. Scores, softmax and weighted values accumulate in f32; keys beyond each query are excluded, and a separate pass writes the complete present cache.- `cached_decode_gqa` — Updates the float cache in copy or merge mode, then one workgroup per key/value head and key range reads each cached row once for every query head of its group; a merge combines the ranges the live keys reach.- `cached_decode_splitk` — Updates the float cache (a copy of the shared past, or the past merged with the new rows), then partitions cached decode across the key axis and combines partial online-softmax results. The family includes subgroup and portable forms.- `cached_flash_sgmat16_f16` — Updates the float cache in the selected mode, then runs causal half prefill over the whole cache on 16x16x16 subgroup matrices with float32 accumulation: each workgroup sweeps one head's cached keys once for 64 queries with an online softmax over staged key and value tiles.- `past_kv_rotary_flash_sgmat16_f16` — Copies the float cache, rotates the half queries once into a temporary buffer at their absolute positions (the cached keys are already rotated), then runs causal half prefill over the whole cache on 16x16x16 subgroup matrices with float32 accumulation.- `past_kv_flash_sgmat16_split_f32`, `new_kv_past_flash_sgmat16_split_f32` — Updates the float cache in the selected mode, stores the query as float32, then runs causal float32 online attention over the cache. Products, softmax probabilities and value accumulation remain float32.- `cached_flash_prefill` — Updates the float cache (a copy of the shared past, or the past merged with the new rows) and applies clustered online-softmax causal prefill, with optional fused rotary, softcap, additive bias, or head sink.- `qkv_present_flash_q32_broadcast`, `qkv_present_flash_q32_shared` — Prefill over half QKV storage. Query-key products, probabilities and probability-value products use float32 arithmetic. Subgroup clusters are preferred when their complete workgroup fits; the shared-memory and broadcast variants remain available for devices with tighter limits.- `quant_flash_prefill` — Builds an int8 or int4 cache and applies clustered online-softmax prefill directly from the packed values. The family supplies subgroup and portable reductions.- `share_append_split_flash_prefill` — Retains shared-capacity cache rows, appends new rows separately, then applies clustered prefill: causal, or bidirectional (`causal = 0`) over the full live key range. It avoids rebuilding unchanged cache positions and includes subgroup and portable forms.- `share_append_split_flash_prefill_wide_cluster` — Retains and appends shared-capacity caches, then increases the lanes cooperating on each query when fixed subgroup width, head divisibility and the workgroup budget permit. A proportionally smaller query tile preserves the invocation count.- `share_append_qnorm_rotary_decode_splitk` — One-token decode over a shared-capacity float32 cache with paired Q/K RMS norms and rotary embeddings: a workgroup per new key head normalizes, rotates and appends it with its value; split-K decode then normalizes and rotates each query head in every split and merges partials stored beside their outputs.- `share_append_qnorm_rotary_decode_splitk_fused` — One-token shared-cache decode with paired Q/K norms and rotary: the split owning the new position prepares its key and passes its unnormalized compensated value state to the merge, which adds the new value before normalizing that split and appends K/V once per KV head, using two attention dispatches and at most ten storage buffers.- `share_append_qnorm_rotary_flash_prefill` — Causal prefill of a query block over a shared-capacity float32 cache with paired Q/K RMS norms and rotary embeddings: the new keys are normalized, rotated and appended, the queries prepared in a temporary buffer at their absolute positions, and clustered flash attention reads the live range.- `share_append_qnorm_rotary_split` — Paired Q/K RMS normalization and rotary embeddings over a shared-capacity float32 cache for any query count: the normalized, rotated new keys are appended with their values, the queries prepared in a temporary buffer, and portable attention reads the live cache range. The fallback for blocks shorter than a flash query tile.- `window_shift_materialized_sgmat_f32` — Stages cached history plus the new chunk, then materializes causal attention with the local-window mask. The score and value passes read the staged rows over the live length. Final compaction writes the block-eviction prefix and clears the suffix.- `window_shift_decode_splitk` — Stages cached history and the new token, partitions decode across the staged key axis, then combines partial online-softmax results. Subgroup and portable forms preserve the block-eviction prefix during final compaction and clear the suffix.- `window_shift_decode_splitk_f16` — Stages cached history and the new token in float16 storage, partitions decode across the staged key axis, then combines partial online-softmax results. Subgroup and portable forms preserve the block-eviction prefix during final compaction and clear the suffix.- `window_shift_flash_prefill` — Stages cached history plus the new chunk for clustered online-softmax causal prefill with the local-window mask. Final compaction writes the block-eviction prefix and clears the suffix.- `window_shift_flash_prefill_f16` — Stages cached history plus the new chunk in float16 storage for clustered online-softmax causal prefill with the local-window mask. Final compaction writes the block-eviction prefix and clears the suffix.- `window_shift_rotary_append` — Stages cached history and appends new key/value rows, rotating K at its absolute position. Attention rotates Q likewise and applies cache-relative masks, an optional bias indexed by absolute key position, or a per-head softmax sink; compaction writes the block-eviction prefix and clears the suffix.- `window_shift_append`, `window_shift_append_f16` — Windowed cached attention with optional additive bias or per-head softmax sink. Stages cached history plus the new chunk for attention, then writes the current block-eviction prefix and clears the suffix.- `matrix_shape_16x16x16_qkv_present_materialized_sgmat_f32` — Experimental 16x16x16 value product for bidirectional float32 prefill. Uses compensated query-key scores and per-sample live key lengths.- `matrix_shape_16x8x16_qkv_present_materialized_sgmat_f32` — Experimental 16x8x16 value product for bidirectional float32 prefill. Uses compensated query-key scores and per-sample live key lengths.- `matrix_shape_8x16x16_qkv_present_materialized_sgmat_f32` — Experimental 8x16x16 value product for bidirectional float32 prefill. Uses compensated query-key scores and per-sample live key lengths.- `matrix_shape_16x16x32_qkv_present_materialized_sgmat_f32` — Experimental 16x16x32 value product for bidirectional float32 prefill. Uses compensated query-key scores and per-sample live key lengths.- `matrix_shape_16x8x32_qkv_present_materialized_sgmat_f32` — Experimental 16x8x32 value product for bidirectional float32 prefill. Uses compensated query-key scores and per-sample live key lengths.- `matrix_shape_16x16x16_cached_materialized_sgmat`, `matrix_shape_16x16x16_past_kv_rotary_materialized_sgmat` — Experimental 16x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_16x8x16_cached_materialized_sgmat`, `matrix_shape_16x8x16_past_kv_rotary_materialized_sgmat` — Experimental 16x8x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_8x16x16_cached_materialized_sgmat`, `matrix_shape_8x16x16_past_kv_rotary_materialized_sgmat` — Experimental 8x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_16x16x32_cached_materialized_sgmat`, `matrix_shape_16x16x32_past_kv_rotary_materialized_sgmat` — Experimental 16x16x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_16x8x32_cached_materialized_sgmat`, `matrix_shape_16x8x32_past_kv_rotary_materialized_sgmat` — Experimental 16x8x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_16x16x16_share_append_materialized_sgmat_f32` — Experimental 16x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_16x8x16_share_append_materialized_sgmat_f32` — Experimental 16x8x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_8x16x16_share_append_materialized_sgmat_f32` — Experimental 8x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_16x16x32_share_append_materialized_sgmat_f32` — Experimental 16x16x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_16x8x32_share_append_materialized_sgmat_f32` — Experimental 16x8x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_16x16x16_window_shift_materialized_sgmat_f32` — Experimental 16x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_16x8x16_window_shift_materialized_sgmat_f32` — Experimental 16x8x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_8x16x16_window_shift_materialized_sgmat_f32` — Experimental 8x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_16x16x32_window_shift_materialized_sgmat_f32` — Experimental 16x16x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.- `matrix_shape_16x8x32_window_shift_materialized_sgmat_f32` — Experimental 16x8x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.## Device requirementsSome implementation variants require `subgroup-matrix`, `shader-f16`, and `subgroups`. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.## Files- [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)- [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/test.json) — correctness cases- [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/bench.json) — benchmark cases- [`attention-flash-sgmat16.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attention-flash-sgmat16.wgsl.jinja)- [`attention-prepare-f32.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attention-prepare-f32.wgsl.jinja)- [`attention-rank4-tiled.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attention-rank4-tiled.wgsl.jinja)- [`attn-decode-gqa-splitk-merge.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-decode-gqa-splitk-merge.wgsl.jinja)- [`attn-decode-gqa-splitk.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-decode-gqa-splitk.wgsl.jinja)- [`attn-flash-decode-splitk-merge.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-flash-decode-splitk-merge.wgsl.jinja)- [`attn-flash-decode-splitk.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-flash-decode-splitk.wgsl.jinja)- [`attn-flash-online.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-flash-online.wgsl.jinja)- [`attn-flash-prefill-cluster.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-flash-prefill-cluster.wgsl.jinja)- [`attn-flash-q32-broadcast.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-flash-q32-broadcast.wgsl.jinja)- [`attn-materialized-rowstats-combine-f32.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-materialized-rowstats-combine-f32.wgsl.jinja)- [`attn-materialized-score-f32.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-materialized-score-f32.wgsl.jinja)- [`attn-materialized-sgmat-f32.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-materialized-sgmat-f32.wgsl.jinja)- [`attn-materialized-shaped.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-materialized-shaped.wgsl.jinja)- [`attn-materialized-softmax-f32.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-materialized-softmax-f32.wgsl.jinja)- [`attn-online-scalar.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/attn-online-scalar.wgsl.jinja)- [`gqa-attention.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/gqa-attention.wgsl.jinja)- [`gqa-norm-rotate-rows.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/gqa-norm-rotate-rows.wgsl.jinja)- [`gqa-present.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/gqa-present.wgsl.jinja)- [`gqa-qprep.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/gqa-qprep.wgsl.jinja)- [`gqa-score-matrix.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/gqa-score-matrix.wgsl.jinja)- [`gqa-score-range.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/gqa-score-range.wgsl.jinja)- [`gqa-stream-matrix8.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/gqa-stream-matrix8.wgsl.jinja)- [`gqa-window-cache.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.GroupQueryAttention/blob/v1/build/webgpu/gqa-window-cache.wgsl.jinja)## Use with `@huggingface/kernels````shnpm install --save-exact @huggingface/kernels@0.0.1-preview.4```Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.Outputs with inferable metadata are allocated automatically. Explicit `outputs` entries request optional results or provide metadata that cannot be inferred from the supplied inputs and attributes.This example supplies explicit metadata for:4 unmodified linesThe `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.```jsimport { getKernel } from "@huggingface/kernels";const kernel = await getKernel("webgpu-kernels/com.microsoft.GroupQueryAttention", { version: 1 });const queryTData = Float32Array.of(1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0);const keyTData = Float32Array.of(0, 0, 0, 0, 0, 0, 0, 0, 3.1073449, 0, 0, 0, 0, 0, 0, 0);const valueTData = Float32Array.of(1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3);const seqlensKTData = Int32Array.of(1);const totalSequenceLengthTData = Int32Array.of(2);// Explicit destinations request optional results or supply metadata that cannot be inferred.const { outputT, presentKeyT, presentValueT } = await kernel({queryT: { data: queryTData, shape: [1, 2, 8] },8 unmodified linespresentValueT: { shape: [1, 1, 2, 8], dtype: "float32" },},});console.log({ outputT, presentKeyT, presentValueT });```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095{% if attnFullF32 is defined and attnFullF32 %}{% set Q_BHSD = (attnQLayout | default(attnLayout | default("bsh"))) == "bhsd" %}{% set KV_BHSD = (attnKvLayout | default(attnLayout | default("bsh"))) == "bhsd" %}{% set CAUSAL = attnCausal is defined and attnCausal %}{% set AT_END = CAUSAL and attnCausalAtEnd is defined and attnCausalAtEnd %}{% set SEQLENS = attnSeqlens is defined and attnSeqlens %}
{% set KV_SPLIT = false %}{% set WG = 32 * (attnWaves | default(4)) %}{% set LPR = (WG / 64) | int %}{% set VPL = (attnHeadDim / LPR) | int %}{% set OUT = "f32" %}{{ env.wgsl.resourceDeclarations }}
const HEAD_DIM: u32 = {{ attnHeadDim }}u;const Q_STRIDE: u32 = {{ attnHeadDim if Q_BHSD else attnQHeads * attnHeadDim }}u;const KV_STRIDE: u32 = {{ attnHeadDim if KV_BHSD else attnKvHeads * attnHeadDim }}u;const GROUP: u32 = {{ (attnQHeads / attnKvHeads) | int }}u;const TILE: u32 = 64u;{% if SEQLENS %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {% if queryFloor %}max({{ queryFloor }}, {{ attn_seqlens_count(index) }}){% else %}{{ attn_seqlens_count(index) }}{% endif %}){% endmacro %}{% endif %}// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret// a zero final denominator according to their public semantics. Using -inf// here changes +inf-row behavior.const FLT_MAX: f32 = 3.4028234663852886e38;
fn is_finite_f32(value: f32) -> bool { return select(false, value <= FLT_MAX, value >= -FLT_MAX);}
// x - m that is exactly 0 when x equals a finite m, so exp(shifted) == 1// exactly at the row max. `x - x` on an infinite max is a legal fast-math// fold to 0, which would silently turn +inf rows finite — the explicit// equality test keeps the NaN propagation of the serial kernels.fn shifted_value(value: f32, maxValue: f32) -> f32 { let equalFiniteMax = select(false, value == maxValue, is_finite_f32(maxValue)); return select(value - maxValue, 0.0, equalFiniteMax);}
fn exp_shift(value: f32, maxValue: f32) -> f32 { return exp(shifted_value(value, maxValue));}
{% set dotGuardNonfinite = true %}{% set dotType = "f32" %}{% set protectDifference = false %}{% set PROTECTED_SUM = false %}{% set SELECT_NONFINITE = false %}{% set ORDERED_SUM = false %}// Retain product and addition residuals across a dot product. Explicit fma// boundaries preserve the addition error transform under reassociation.struct DotAccumulator { hi: {{ dotType }}, lo: {{ dotType }},}{% if dotRecoverProductResidual | default(false) %}{% set dotBitsType = "u32" %}// Recover an inexact product when a backend returns a zero fma residual.{% set dotExponentType = "i32" %}{% macro dot_parts() -%}let aBits = bitcast<{{ dotBitsType }}>(a);let bBits = bitcast<{{ dotBitsType }}>(b);let pBits = bitcast<{{ dotBitsType }}>(product);let ae = (aBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let be = (bBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let pe = (pBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);{% endmacro %}fn dot_product_error(a: {{ dotType }}, b: {{ dotType }}, product: {{ dotType }}) -> {{ dotType }} { // Twelve-bit significand parts make each split product exactly representable. let nativeError = fma(a, b, -product); if (nativeError == 0.0) {{{ dot_parts() | indent(4, true) }} let lowProduct = (((aBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u)) * ((bBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u))) & {{ dotBitsType }}(0x00ffffffu); let recover = (nativeError == {{ dotType }}(0.0)) && (lowProduct != {{ dotBitsType }}(0u)) && (ae > {{ dotBitsType }}(0u)) && (ae < {{ dotBitsType }}(255u)) && (be > {{ dotBitsType }}(0u)) && (be < {{ dotBitsType }}(255u)) && (pe > {{ dotBitsType }}(0u)) && (pe < {{ dotBitsType }}(255u)); if (recover) { // Normalize before splitting: a normal input can otherwise produce a // subnormal low word that a conformant backend is allowed to flush. let an = bitcast<{{ dotType }}>((aBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u)); let bn = bitcast<{{ dotType }}>((bBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u)); let exponent = select({{ dotExponentType }}(0), {{ dotExponentType }}(ae) + {{ dotExponentType }}(be) - {{ dotExponentType }}(254), recover); let pnExponent = select({{ dotBitsType }}(127u), {{ dotBitsType }}({{ dotExponentType }}(pe) - exponent), recover); let pn = bitcast<{{ dotType }}>((pBits & {{ dotBitsType }}(0x807fffffu)) | (pnExponent << {{ dotBitsType }}(23u))); let ah = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(an) & {{ dotBitsType }}(0xfffff000u)); let bh = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(bn) & {{ dotBitsType }}(0xfffff000u)); let al = fma({{ dotType }}(-1.0), ah, an); let bl = fma({{ dotType }}(-1.0), bh, bn); let e0 = fma(ah, bh, -pn); let e1 = fma(al, bh, e0); let e2 = fma(ah, bl, e1); let recovered = ldexp(fma(al, bl, e2), exponent); return select(nativeError, recovered, recover); } } return nativeError;}{% endif %}{% macro dot_step(name, dotGuardNonfinite) %}fn {{ name }}(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator { let product = fma(a, b, {{ dotType }}(0.0));{% if dotGuardNonfinite | default(false) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);{% if not SELECT_NONFINITE %} // Nonfinite sums retain ordinary f32 addition classes; Inf-Inf residuals // must not poison a valid infinite dot accumulator.{% if ORDERED_SUM %} if (!(abs(sum) <= 3.4028234663852886e38 && abs(acc.lo) <= 3.4028234663852886e38)) {{% else %} if (!(abs(acc.hi) <= 3.4028234663852886e38) || !(abs(acc.lo) <= 3.4028234663852886e38) || !(abs(product) <= 3.4028234663852886e38) || !(abs(sum) <= 3.4028234663852886e38)) {{% endif %} return DotAccumulator(sum, {{ dotType }}(0.0)); }{% endif %}{% endif %} let productError = {% if dotRecoverProductResidual | default(false) %}dot_product_error(a, b, product){% else %}fma(a, b, -product){% endif %};{% if not (dotGuardNonfinite | default(false)) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);{% endif %}{% if PROTECTED_SUM %} let roundoff = dot_sum_error(acc.hi, product, sum); let error = (acc.lo + roundoff) + productError;{% elif ORDERED_SUM %} let productLarger = abs(acc.hi) < abs(product); let larger = select(acc.hi, product, productLarger); let smaller = select(product, acc.hi, productLarger); let roundoff = fma(-1.0, fma(-1.0, larger, sum), smaller); let error = fma(fma(roundoff, 1.0, acc.lo), 1.0, productError);{% else %} let bv = fma({{ dotType }}(-1.0), acc.hi, sum); let av = fma({{ dotType }}(-1.0), bv, sum); let ae = fma({{ dotType }}(-1.0), av, acc.hi); let be = fma({{ dotType }}(-1.0), bv, product); let error = fma(fma(fma(ae, {{ dotType }}(1.0), be), {{ dotType }}(1.0), acc.lo), {{ dotType }}(1.0), productError);{% endif %}{% if PROTECTED_SUM %} // Carry the residual to the end of the dot. Renormalizing each step can // round a recovered product bit out of the low word on relaxed backends. return DotAccumulator(sum, error);{% else %} let hi = fma(sum, {{ dotType }}(1.0), error);{% if SELECT_NONFINITE %} let sumValid = abs(sum) <= 3.4028234663852886e38 && abs(acc.lo) <= 3.4028234663852886e38; let nextLo = fma(-1.0, fma(-1.0, sum, hi), error); return DotAccumulator(select(sum, hi, sumValid), select(0.0, nextLo, sumValid && abs(hi) <= 3.4028234663852886e38));{% else %}{% if dotGuardNonfinite | default(false) %} if (!(abs(hi) <= 3.4028234663852886e38)) { return DotAccumulator(hi, {{ dotType }}(0.0)); }{% endif %} return DotAccumulator(hi, fma({{ dotType }}(-1.0), fma({{ dotType }}(-1.0), sum, hi), error));{% endif %}{% endif %}}{% endmacro %}{{ dot_step("dot_accumulate", dotGuardNonfinite | default(false)) }}fn dot_value(acc: DotAccumulator) -> {{ dotType }} { return fma(acc.hi, {{ dotType }}(1.0), acc.lo);}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} { let bits = bitcast<{{ bitsType }}>(x); return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} { let swap = abs(a) < abs(b); let larger = select(a, b, swap); let smaller = select(b, a, swap); // Keep the rounded high-part difference observable before subtracting it // from the smaller addend. Reassociation here erases the residual. return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }
{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar { return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool { return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 { if (a.hi == 0.0) { if (a.lo == 0.0) { return -1024; } return a.exponent + frexp(a.lo).exp; } if (!scaled_value_scalar_finite(a.hi)) { return 1024; } return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 { let bits = bitcast<u32>(value); let sign = bits & 0x80000000u; let fraction = bits & 0x007fffffu; let inputExponent = i32((bits >> 23u) & 0xffu); if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; } var significand = fraction | 0x00800000u; var exponent = inputExponent + shift; if (inputExponent == 0) { let normalize = countLeadingZeros(fraction) - 8u; significand = fraction << normalize; exponent = 1 + shift - i32(normalize); } if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); } if (exponent > 0) { return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu)); } let distance = u32(1 - exponent); if (distance > 24u) { return bitcast<f32>(sign); } let high = significand >> distance; let remainder = significand & ((1u << distance) - 1u); let halfway = 1u << (distance - 1u); let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u); return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar { if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); } if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); } return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar { let nextHi = fma(hi, 1.0, lo); let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %}; if (nextHi == 0.0) { return scaled_value_scalar_zero(); } if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); } let parts = frexp(nextHi); let rawExponent = exponent + parts.exp; // Ordinary magnitudes return to the unscaled fast path. The margin keeps // boundary values away from overflow/underflow while scaling the low word. if (rawExponent >= -120 && rawExponent <= 120) { return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0); } return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar { let sum = fma(a.hi, 1.0, product); let bv = fma(-1.0, a.hi, sum); let av = fma(-1.0, bv, sum); let ae = fma(-1.0, av, a.hi); let be = fma(-1.0, bv, product); let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error); let hi = fma(sum, 1.0, residual); return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar { if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) || !scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) || !scaled_value_scalar_finite(weight)) { return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0); } if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; } if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; } if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) { let product = fma(weight, b.hi, 0.0); let lowProduct = fma(weight, b.lo, 0.0); let rawSum = fma(a.hi, 1.0, product); let productNormal = abs(product) >= 1.1754943508222875e-38; if (productNormal && scaled_value_scalar_finite(product) && scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) { let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct); let result = scaled_value_scalar_add_words(a, product, error); if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; } } } // Decompose BEFORE multiplying: a merge coefficient may exceed one, so // its unscaled product with a finite partial mean need not fit in f32. var other = b; if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); } let wp = frexp(weight); let vp = frexp(other.hi); let productExponent = other.exponent + wp.exp + vp.exp; let commonExponent = max(scaled_value_scalar_leading(a), productExponent); let aligned = scaled_value_scalar_align(a, commonExponent); let product = fma(wp.fract, vp.fract, 0.0); let productError = fma(wp.fract, vp.fract, -product); let shift = productExponent - commonExponent; let highWord = scaled_value_scalar_shift(product, shift); let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0, fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %} let sum = aligned.hi + highWord; let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord; return scaled_value_scalar_finish(sum, low, commonExponent);{% else %} let result = scaled_value_scalar_add_words(aligned, highWord, lowWord); return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 { if (denominator == 0.0) { return 0.0; } if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; } if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) { return fma(a.hi, 1.0, a.lo) / denominator; } let valueParts = frexp(a.hi); let denominatorParts = frexp(denominator); let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp)); let quotient = mantissa / denominatorParts.fract; return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue { return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue { let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %} // FastTwoSum recovers the rounding error with the larger magnitude first. let takeProduct = abs(acc.hi) < abs(product); let larger = select(acc.hi, product, takeProduct); let smaller = select(product, acc.hi, takeProduct); let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller); let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %} let bv = fma({{ type }}(-1.0), acc.hi, sum); let av = fma({{ type }}(-1.0), bv, sum); let ae = fma({{ type }}(-1.0), av, acc.hi); let be = fma({{ type }}(-1.0), bv, product); let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %} let hi = fma(sum, {{ type }}(1.0), residual); return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue { let w = {{ type }}(weight); let product = fma(w, value, {{ type }}(0.0)); return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} { return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool { return all(start.exponent == {{ exponentType }}(0)) && all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) & (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) & ({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile { let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37))); let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u)); return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile { let w = {{ type }}(weight); let sum = fma(w, value, tile.sum); let change = fma({{ type }}(-1.0), tile.sum, sum); return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue { let high = fma({{ type }}(-1.0), tile.offset, tile.sum); let sum = fma(high, {{ type }}(1.0), tile.low); let bv = fma({{ type }}(-1.0), high, sum); let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low)); return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool { return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) && {% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) | (bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep { let w = {{ type }}(weight); let product = fma(w, value, {{ type }}(0.0)); let sum = scaled_value_add_words(acc, product, fma(w, value, -product)); let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38)); let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) & {% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38)); return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent), fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %} // Ordinary raw products use one vector compensated sum. Every exceptional // component falls back to the same scalar exponent-aware implementation. if (all(acc.exponent == {{ exponentType }}(0)) && all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) && all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) { let step = scaled_value_add_step(acc, weight, value); if (all(step.exact)) { return step.value; } }{% endif %} var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} 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)); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %} let w = {{ type }}(correction); let product = fma(w, acc.hi, {{ type }}(0.0)); let scaled = scaled_value_add_words(scaled_value_zero(), product, fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0)))); let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0); let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) & (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) & (zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero), select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue { // From finite words at exponent zero, the scalar path below leaves zero // words for a zero value or correction, the value itself for a unit // correction, and otherwise this compensated product onto zero words when // the product is normal and the low word finite (which bounds the rest, as // in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) { return {{ rescale_vector_value() }}; } var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }})); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue { var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} 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 }})); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} { // Words at exponent zero well inside the normal range, with a normal // quotient: the scalar path below divides this same sum by this same // denominator, each scaled by a power of two, so it rounds to this quotient // wherever division is scale-invariant. Bounding the denominator above also // keeps a division through its reciprocal clear of a subnormal reciprocal. let d = {{ type }}(denominator); let sum = fma(acc.hi, {{ type }}(1.0), acc.lo); let quotient = sum / d; if (all((acc.exponent == {{ exponentType }}(0)) & (abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) & (abs(acc.lo) <= abs(acc.hi)) & (abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) & ((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) { return quotient; } var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %} return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} { var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %} return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue { var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }}); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("f32", rescale=true) }}
// Keep the residual while an online-softmax maximum rescales a running sum.fn rescale_sum(acc: DotAccumulator, scale: f32) -> DotAccumulator { return dot_accumulate(dot_accumulate(DotAccumulator(0.0, 0.0), acc.hi, scale), acc.lo, scale);}
// One lane group owns a query row. Products, probabilities and accumulated// values stay float32 throughout, including small terms next to large ones.@compute @workgroup_size({{ WG }}, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32) { let qSeq = params.qSeq; let kvSeq = params.kvSeq; let scale = {{ attentionScaleExpression }}; let head = wid.y; let kvHead = head / GROUP;{% if Q_BHSD %} let qBase = (wid.z * {{ attnQHeads }}u + head) * qSeq * HEAD_DIM;{% else %} let qBase = wid.z * qSeq * Q_STRIDE + head * HEAD_DIM;{% endif %}{% if KV_BHSD %} let kvBase = (wid.z * {{ attnKvHeads }}u + kvHead) * kvSeq * HEAD_DIM;{% else %} let kvBase = wid.z * kvSeq * KV_STRIDE + kvHead * HEAD_DIM;{% endif %}{% if SEQLENS %} let kvEnd = {{ attn_seqlens_bound("kvSeq", "wid.z", "qSeq" if attnSeqlensQueryFloor | default(false) else "") }};{% else %} let kvEnd = kvSeq;{% endif %} let qFull = qSeq / TILE; if (wid.x > qFull) { return; } let q0 = select(wid.x * TILE, max(qSeq, TILE) - TILE, wid.x == qFull); let qFresh = select(0u, qFull * TILE - q0, wid.x == qFull); let row = tid / {{ LPR }}u; let rowLane = tid % {{ LPR }}u; let queryRow = q0 + row; if (row < qFresh || queryRow >= qSeq) { return; } let qAt = qBase + queryRow * Q_STRIDE;{% if AT_END %} let keyEnd = u32(clamp(i32(queryRow) + i32(kvEnd) - i32(qSeq) + 1, 0, i32(kvEnd)));{% elif CAUSAL %} let keyEnd = min(kvEnd, queryRow + 1u);{% else %} let keyEnd = kvEnd;{% endif %}
let keyBegin = 0u; let keyStop = keyEnd; var m = -FLT_MAX; var denom = DotAccumulator(0.0, 0.0); var acc: array<ScaledValue, {{ VPL }}>; for (var j = keyBegin; j < keyStop; j++) { let kAt = kvBase + j * KV_STRIDE; var score = DotAccumulator(0.0, 0.0); for (var d = 0u; d < HEAD_DIM; d++) { let at = kAt + d; score = dot_accumulate(score, query[qAt + d], key[at / 4u][at % 4u]); } let s = dot_value(score) * scale; let next = max(m, s); let rescale = exp_shift(m, next); let weight = exp_shift(s, next); let oldDenom = rescale_sum(denom, rescale); denom = dot_accumulate(oldDenom, weight, 1.0); // Keep the raw weighted numerator until the complete row is available. for (var d = 0u; d < {{ VPL }}u; d++) { let at = kAt + rowLane * {{ VPL }}u + d; acc[d] = scaled_value_add(scaled_value_rescale(acc[d], rescale), weight, value[at / 4u][at % 4u]); } m = next; } let l = dot_value(denom); for (var d = 0u; d < {{ VPL }}u; d++) { let col = rowLane * {{ VPL }}u + d; let o = select(scaled_value_mean(acc[d], l), 0.0, l == 0.0); output[qAt + col] = {{ OUT }}(o); }}{% else %}{%- set Q_BHSD = (attnQLayout | default(attnLayout | default("bsh"))) == "bhsd" -%}{%- set KV_BHSD = (attnKvLayout | default(attnLayout | default("bsh"))) == "bhsd" -%}{%- set CAUSAL = attnCausal is defined and attnCausal -%}{%- set AT_END = CAUSAL and attnCausalAtEnd is defined and attnCausalAtEnd -%}{%- set SEQLENS = attnSeqlens is defined and attnSeqlens -%}{%- set OFFSET = false -%}{%- set WINDOW = false -%}{%- set KV_SPLIT = false -%}{%- set PV_COLS = false -%}{%- set VSPLIT = 1 -%}{%- set W = attnWaves | default(4) -%}{%- set WG = 32 * W -%}{%- set LPR = (WG / 64) | int -%}{%- set S_RB = 2 if W == 4 else 1 -%}{%- set PV_KEYS = 64 if W == 4 or PV_COLS else 32 -%}{%- set ROUND = 4 if W == 4 else 2 -%}{%- set KSTEPS = (attnHeadDim / 16) | int -%}{%- set VDIM = (attnHeadDim / VSPLIT) | int -%}{%- set VSTEPS = (VDIM / 16) | int -%}{%- set NACC = (VSTEPS / 2) | int if PV_COLS else VSTEPS -%}{%- set ROUND32 = false -%}{%- set F32KV = false -%}{%- set QIN = "Q_STRIDE" -%}{%- set T_BEGIN = "0u" -%}{%- set T_END = "kvTiles" -%}{%- set CHUNK = 64 -%}{%- set KPC = 4 -%}{%- set CHUNKS = ((attnHeadDim + CHUNK - 1) / CHUNK) | int -%}{%- set VCHUNKS = ((VDIM + CHUNK - 1) / CHUNK) | int -%}{%- set WPL = ((64 * (CHUNK / 8)) / WG) | int -%}{%- set OUT = "f16" -%}{%- set V_BASE = "kvBase" -%}{%- if SEQLENS %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {% if queryFloor %}max({{ queryFloor }}, {{ attn_seqlens_count(index) }}){% else %}{{ attn_seqlens_count(index) }}{% endif %}){% endmacro %}{% endif -%}enable subgroups;{% if pinSubgroupSize32 %}enable subgroup_size_control;{% endif %}enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);
{{ env.wgsl.resourceDeclarations }}
// One workgroup owns 64 queries of one head and sweeps its keys once in 64-key tiles with// an online softmax. Each tile's keys and values are staged in workgroup memory in chunks of// head columns, the next chunk's words loading into registers while the current one// multiplies. Scores pass through workgroup memory as float32 and probabilities as halves.//// A row's softmax reference rises only when a tile's maximum beats it by more than TAU, so// probabilities stay below exp(TAU) and the accumulated output rarely needs rescaling;// when any row's reference rises, the whole workgroup scales the output rows through// workgroup memory. Each probability, scaled by P_SCALE so its low part stays a normal// half, splits into a half and the half of its remainder; both multiply V, so P.V keeps// float32-like probability precision.//// A sequence that is not a whole number of tiles ends its last tile AT the sequence end,// overlapping the tile before, so every load stays in bounds: overlapped keys are masked// (the earlier tile counted them) and overlapped query rows are not stored.const HEAD_DIM: u32 = {{ attnHeadDim }}u;// Elements between consecutive sequence rows of one head.const Q_STRIDE: u32 = {{ attnHeadDim if Q_BHSD else attnQHeads * attnHeadDim }}u;const KV_STRIDE: u32 = {{ attnHeadDim if KV_BHSD else attnKvHeads * attnHeadDim }}u;const GROUP: u32 = {{ (attnQHeads / attnKvHeads) | int }}u;const TILE: u32 = 64u;const S_STRIDE: u32 = 68u;const P_STRIDE: u32 = 72u;// Words per staged key row: {{ CHUNK }} head columns plus one pad word.const C_STRIDE: u32 = {{ (CHUNK / 8 + 1) | int }}u;
const NEG_INF: f32 = -3.4028234663852886e38;const P_SCALE: f32 = 1024.0;const TAU: f32 = 4.0;
// One staged chunk: 64 keys by up to {{ CHUNK }} head columns of K or V.var<workgroup> tile_c: array<vec4<u32>, {{ 64 * ((CHUNK / 8 + 1) | int) }}>;
// Float32 scores, reused for output rows when rescaling and storing.var<workgroup> tile_s: array<f32, {{ 64 * 68 }}>;// Scaled probabilities as a half and the half of its remainder: the left operands of P.V.var<workgroup> tile_p: array<f16, {{ 64 * 72 }}>;var<workgroup> tile_p_low: array<f16, {{ 64 * 72 }}>;// Never written, so it stays zero: accumulators start from a load of it, because a// zero-initialized matrix declared inside a loop is not reliably re-zeroed per iteration.var<workgroup> tile_zero: array<f32, 256>;// Per-lane row maxima, then per-lane denominators.var<workgroup> part_m: array<f32, {{ WG }}>;// Per-row rescale factors, then per-row output scales.var<workgroup> row_alpha: array<f32, 64>;var<workgroup> rescale_flag: u32;// Set when a staged value tile held a non-finite half.var<workgroup> value_flag: u32;
// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}
// Zeroes the non-finite halves of a value word. A masked key's probability is zero, and// zero times NaN would still poison the product, so such values multiply as zero and the// rows that do attend them add their exact contribution separately.fn finite_word(word: vec4<u32>) -> vec4<u32> { let low = (word & vec4<u32>(0x7c00u)) == vec4<u32>(0x7c00u); let high = (word & vec4<u32>(0x7c000000u)) == vec4<u32>(0x7c000000u); return word & select(vec4<u32>(0xffffffffu), vec4<u32>(0xffff0000u), low) & select(vec4<u32>(0xffffffffu), vec4<u32>(0x0000ffffu), high);}{% macro cw(c) %}{{ ((min(CHUNK, attnHeadDim - c * CHUNK)) / 8) | int }}{% endmacro %}{% macro load_chunk(src, c, kStart) %}{% set B = V_BASE if src == "value" else "kvBase" %}{% for i in range(WPL) %}{% set guarded = 64 * (cw(c) | int) < (i + 1) * WG %}{% if not guarded or 64 * (cw(c) | int) > i * WG %} {% if guarded %}if (tid + {{ i * WG }}u < {{ 64 * (cw(c) | int) }}u) { {% endif %}{% if F32KV %}{ let at = ({{ B }} + ({{ kStart }} + (tid + {{ i * WG }}u) / {{ cw(c) }}u) * KV_STRIDE + {{ c * CHUNK }}u) / 4u + 2u * ((tid + {{ i * WG }}u) % {{ cw(c) }}u); staged{{ i }} = {{ src }}[at]; stagedUpper{{ i }} = {{ src }}[at + 1u]; }{% else %}staged{{ i }} = {{ src }}[({{ B }} + ({{ kStart }} + (tid + {{ i * WG }}u) / {{ cw(c) }}u) * KV_STRIDE) / 8u + {{ c * 8 }}u + (tid + {{ i * WG }}u) % {{ cw(c) }}u];{% endif %}{% if guarded %} }{% endif %}{% endif %}{% endfor %}{% endmacro %}{% macro stage(c, isValue, nextSrc, nextC, nextK) %} workgroupBarrier();{% for i in range(WPL) %}{% if 64 * (cw(c) | int) > i * WG %}{% set HI = "rounded" if ROUND32 else "staged" ~ i %} {% if 64 * (cw(c) | int) < (i + 1) * WG %}if (tid + {{ i * WG }}u < {{ 64 * (cw(c) | int) }}u) {% endif %}{ let r = (tid + {{ i * WG }}u) / {{ cw(c) }}u;{% if ROUND32 %} let rounded = round_word(staged{{ i }}, stagedUpper{{ i }}, {{ "true" if isValue else "false" }});{% endif %}{% if isValue %} let word = finite_word({{ HI }}); if (any(word != {{ HI }})) { value_flag = 1u; } tile_c[r * C_STRIDE + (tid + {{ i * WG }}u) % {{ cw(c) }}u] = word;{% else %} tile_c[r * C_STRIDE + (tid + {{ i * WG }}u) % {{ cw(c) }}u] = {{ HI }};{% endif %} }{% endif %}{% endfor %} workgroupBarrier();{% if nextK == "k0" %}{{ load_chunk(nextSrc, nextC, "k0") }}{% else %} if (nextLive) {{{ load_chunk(nextSrc, nextC, nextK) }} }{% endif %}{% endmacro %}{% macro output_slot(n, r0) %}pvRow * S_STRIDE + {% if PV_COLS %}pvCol + {{ (n - r0) * 16 }}u{% else %}{% if W == 8 %}pvKey + {% endif %}{{ (n - r0) * 16 }}u{% endif %}{% endmacro %}
@compute @workgroup_size({{ WG }}, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32, @builtin(subgroup_size) width: u32) { let role = min(claimMatrixSubgroupRole(width, 32u), {{ W - 1 }}u); let qSeq = params.qSeq; let kvSeq = params.kvSeq; // A zero scale selects the default 1 / sqrt(headDim). let scale = select(params.scale, inverseSqrt(f32(HEAD_DIM)), params.scale == 0.0); let head = wid.y; let kvHead = head / GROUP; // Each head's first element; rows then advance by Q_STRIDE and KV_STRIDE.{% if Q_BHSD %} let qBase = (wid.z * {{ attnQHeads }}u + head) * qSeq * HEAD_DIM;{% else %} let qBase = wid.z * qSeq * Q_STRIDE + head * HEAD_DIM;{% endif %}{% if KV_BHSD %} let kvBase = (wid.z * {{ attnKvHeads }}u + kvHead) * kvSeq * HEAD_DIM;{% else %} let kvBase = wid.z * kvSeq * KV_STRIDE + kvHead * HEAD_DIM;{% endif %}{% if SEQLENS %} let kvEnd = {{ attn_seqlens_bound("kvSeq", "wid.z", "qSeq" if attnSeqlensQueryFloor | default(false) else "") }};{% else %} let kvEnd = kvSeq;{% endif %}{% if AT_END %} // Query row i sits at key position i + kvEnd - qSeq. let causalShift = i32(kvEnd) - i32(qSeq);{% endif %} let qFull = qSeq / TILE; let q0 = select(wid.x * TILE, qSeq - TILE, wid.x == qFull); let qFresh = select(0u, qFull * TILE - q0, wid.x == qFull); let kvTiles = (kvEnd + TILE - 1u) / TILE; let lastK0 = max(kvEnd, TILE) - TILE; // Softmax lanes: {{ LPR }} per query row, interleaved over its 64 scores. let row = tid / {{ LPR }}u; let rowLane = tid % {{ LPR }}u;{%- macro live() -%}k0 + c >= {% if WINDOW %}max(t * TILE, keyLo){% else %}t * TILE{% endif %}{% if SEQLENS or OFFSET %} && k0 + c < kvEnd{% endif %}{% if AT_END %} && i32(k0 + c) <= i32(q0 + row) + causalShift{% elif CAUSAL %} && k0 + c <= q0 + row{% endif %}{%- endmacro %}{%- macro score(c) -%}tile_s[row * S_STRIDE + {{ c }}] * scale{%- endmacro %}{%- macro past_tile(k) -%}{% if AT_END %}i32({{ k }}) > i32(q0 + TILE - 1u) + causalShift{% else %}{{ k }} > q0 + TILE - 1u{% endif %}{%- endmacro %} if (matrixTopologyAccepted(tid, {{ W }}u)) { // Q.K^T: each subgroup owns {{ 16 * S_RB }} query rows by 32 keys of the score tile. let sRow = (role / 2u) * {{ 16 * S_RB }}u; let sCol = (role % 2u) * 32u;{% if W == 4 %} // P.V: each subgroup owns 16 query rows across every key and head column. let pvRow = role * 16u;{% else %} // P.V: each subgroup owns 16 query rows over one half of the tile's keys. let pvRow = (role / 2u) * 16u; let pvKey = (role % 2u) * 32u;{% endif %} // The workgroup's query fragments stay in registers for the whole sweep.{% for ks in range(KSTEPS) %}{% for i in range(S_RB) %} let q{{ i }}_{{ ks }} = subgroupMatrixLoad<subgroup_matrix_left<f16, 16, 16>, row_major>(&query, qBase + (q0 + sRow + {{ i * 16 }}u) * {{ QIN }} + {{ ks * 16 }}u, {{ QIN }});{% endfor %}{% endfor %}
{% for n in range(NACC) %} var o{{ n }} = subgroupMatrixLoad<subgroup_matrix_result<f32, 16, 16>, row_major>(&tile_zero, 0u, 16u);{% endfor %}{% for i in range(WPL) %}{% if 64 * (cw(0) | int) > i * WG %} var staged{{ i }} = vec4<u32>(0u);{% endif %}{% endfor %} var mRef = NEG_INF; // This lane's share of its row's denominator, at the row's reference max. var lPart = 0.0; { let k0 = {{ "min(tBegin * TILE, lastK0)" if KV_SPLIT else "0u" }};{{ load_chunk("key", 0, "k0") }} } for (var t = {{ T_BEGIN }}; t < {{ T_END }}; t++) { let k0 = min(t * TILE, lastK0);{% if CAUSAL and not OFFSET %} // Tiles start in increasing order, so the first one past the tile's last query ends the sweep. if ({{ past_tile("k0") }}) { break; }{% endif %} let nextK0 = min((t + 1u) * TILE, lastK0); let nextLive = t + 1u < {{ T_END }}{% if CAUSAL and not OFFSET %} && !({{ past_tile("nextK0") }}){% endif %};{% for i in range(S_RB) %}{% for j in range(2) %} var s{{ i }}{{ j }} = subgroupMatrixLoad<subgroup_matrix_result<f32, 16, 16>, row_major>(&tile_zero, 0u, 16u);{% endfor %}{% endfor %}{% for c in range(CHUNKS) %}{% if c + 1 < CHUNKS %}{{ stage(c, false, "key", c + 1, "k0") }}{% else %}{{ stage(c, false, "value", 0, "k0") }}{% endif %}{% for kk in range(cw(c) | int // 2) %}{% set ks = c * KPC + kk %}{% for j in range(2) %} let k{{ j }}_{{ ks }} = subgroupMatrixLoad<subgroup_matrix_right<f16, 16, 16>, col_major>(&tile_c, (sCol + {{ j * 16 }}u) * C_STRIDE + {{ kk * 2 }}u, C_STRIDE);
{% endfor %}{% for i in range(S_RB) %}{% for j in range(2) %} s{{ i }}{{ j }} = subgroupMatrixMultiplyAccumulate(q{{ i }}_{{ ks }}, k{{ j }}_{{ ks }}, s{{ i }}{{ j }});
{% endfor %}{% endfor %}{% endfor %}{% endfor %}{% for i in range(S_RB) %}{% for j in range(2) %} subgroupMatrixStore<row_major>(&tile_s, (sRow + {{ i * 16 }}u) * S_STRIDE + sCol + {{ j * 16 }}u, s{{ i }}{{ j }}, S_STRIDE);{% endfor %}{% endfor %} workgroupBarrier(); var laneMax = NEG_INF; for (var j = 0u; j < {{ (64 / LPR) | int }}u; j++) { let c = {{ LPR }}u * j + rowLane; laneMax = max(laneMax, select(NEG_INF, {{ score("c") }}, {{ live() }})); } part_m[tid] = laneMax; if (tid == 0u) { rescale_flag = 0u; value_flag = 0u; } workgroupBarrier(); var tileMax = part_m[{{ LPR }}u * row];{% for x in range(1, LPR) %} tileMax = max(tileMax, part_m[{{ LPR }}u * row + {{ x }}u]);{% endfor %} let nextRef = select(mRef, tileMax, tileMax > mRef + TAU); let alpha = exp(mRef - nextRef); if (rowLane == 0u) { row_alpha[row] = alpha; } if (nextRef != mRef && mRef != NEG_INF) { rescale_flag = 1u; } mRef = nextRef; var laneSum = 0.0; for (var j = 0u; j < {{ (64 / LPR) | int }}u; j++) { let c = {{ LPR }}u * j + rowLane; let e = select(0.0, exp({{ score("c") }} - nextRef), {{ live() }}); laneSum += e; // Clearing the low 13 mantissa bits leaves a value a half holds exactly, so the // remainder is exact too; a conversion round trip may be folded away instead. let pv = e * P_SCALE; let high = bitcast<f32>(bitcast<u32>(pv) & 0xffffe000u); tile_p[row * P_STRIDE + c] = f16(high); tile_p_low[row * P_STRIDE + c] = f16(pv - high); } lPart = lPart * alpha + laneSum; // The uniform load is also the barrier that publishes P and the row factors. if (workgroupUniformLoad(&rescale_flag) != 0u) {{% for r0 in range(0, NACC, ROUND) %}{% for n in range(r0, min(r0 + ROUND, NACC)) %} subgroupMatrixStore<row_major>(&tile_s, {{ output_slot(n, r0) }}, o{{ n }}, S_STRIDE);{% endfor %} workgroupBarrier(); for (var e = tid; e < TILE * 64u; e += {{ WG }}u) { tile_s[(e / 64u) * S_STRIDE + e % 64u] *= row_alpha[e / 64u]; } workgroupBarrier();{% for n in range(r0, min(r0 + ROUND, NACC)) %} o{{ n }} = subgroupMatrixLoad<subgroup_matrix_result<f32, 16, 16>, row_major>(&tile_s, {{ output_slot(n, r0) }}, S_STRIDE);{% endfor %} workgroupBarrier();{% endfor %} }{% for c in range(VCHUNKS) %}{% if c + 1 < VCHUNKS %}{{ stage(c, true, "value", c + 1, "k0") }}{% else %}{{ stage(c, true, "key", 0, "nextK0") }}{% endif %} for (var kk = 0u; kk < {{ PV_KEYS }}u; kk += 16u) { let p = subgroupMatrixLoad<subgroup_matrix_left<f16, 16, 16>, row_major>(&tile_p, pvRow * P_STRIDE + {% if W == 8 and not PV_COLS %}pvKey + {% endif %}kk, P_STRIDE); let pLow = subgroupMatrixLoad<subgroup_matrix_left<f16, 16, 16>, row_major>(&tile_p_low, pvRow * P_STRIDE + {% if W == 8 and not PV_COLS %}pvKey + {% endif %}kk, P_STRIDE);{% for n in range(cw(c) | int // 2) %}{% set o = "o" ~ (c * KPC + n) %} let v{{ n }} = subgroupMatrixLoad<subgroup_matrix_right<f16, 16, 16>, row_major>(&tile_c, ({% if W == 8 %}pvKey + {% endif %}kk) * C_STRIDE + {{ n * 2 }}u, C_STRIDE); {{ o }} = subgroupMatrixMultiplyAccumulate(p, v{{ n }}, {{ o }}); {{ o }} = subgroupMatrixMultiplyAccumulate(pLow, v{{ n }}, {{ o }});
{% endfor %} }{% endfor %} if (workgroupUniformLoad(&value_flag) != 0u) {{% for r0 in range(0, NACC, ROUND) %}{% set w = 64 if PV_COLS else min(ROUND, VSTEPS - r0) * 16 %}{% set base = r0 * 32 if PV_COLS else r0 * 16 %}{% for n in range(r0, min(r0 + ROUND, NACC)) %} subgroupMatrixStore<row_major>(&tile_s, {{ output_slot(n, r0) }}, o{{ n }}, S_STRIDE);{% endfor %} workgroupBarrier(); for (var e = tid; e < TILE * {{ w }}u; e += {{ WG }}u) { let r = e / {{ w }}u; let d = e % {{ w }}u; var extra = 0.0; for (var c = 0u; c < TILE; c++) { let at = {{ V_BASE }} + (k0 + c) * KV_STRIDE + {{ base }}u + d; let word = value[at / 8u][(at % 8u) / 2u]; let p = f32(tile_p[r * P_STRIDE + c]) + f32(tile_p_low[r * P_STRIDE + c]); if (((word >> (16u * (at % 2u))) & 0x7c00u) == 0x7c00u && p != 0.0) { extra += p * f32(bitcast<vec2<f16>>(word)[at % 2u]); } } tile_s[r * S_STRIDE + d] += extra; } workgroupBarrier();{% for n in range(r0, min(r0 + ROUND, NACC)) %} o{{ n }} = subgroupMatrixLoad<subgroup_matrix_result<f32, 16, 16>, row_major>(&tile_s, {{ output_slot(n, r0) }}, S_STRIDE);{% endfor %} workgroupBarrier();{% endfor %} } } part_m[tid] = lPart; workgroupBarrier(); if (rowLane == 0u) { var l = part_m[{{ LPR }}u * row];{% for x in range(1, LPR) %} l += part_m[{{ LPR }}u * row + {{ x }}u];{% endfor %} // A row with no live key stores zeros. row_alpha[row] = select(0.0, 1.0 / (l * P_SCALE), l > 0.0); }{% for r0 in range(0, NACC, ROUND) %}{% set w = 64 if PV_COLS else min(ROUND, VSTEPS - r0) * 16 %}{% set base = r0 * 32 if PV_COLS else r0 * 16 %} workgroupBarrier();{% for n in range(r0, min(r0 + ROUND, NACC)) %} subgroupMatrixStore<row_major>(&tile_s, {{ output_slot(n, r0) }}, o{{ n }}, S_STRIDE);{% endfor %} workgroupBarrier(); for (var e = tid; e < TILE * {{ w }}u; e += {{ WG }}u) { let r = e / {{ w }}u; let d = e % {{ w }}u; if (r >= qFresh) {{% set val = "(tile_s[r * S_STRIDE + d] + tile_s[r * S_STRIDE + 32u + d]) * row_alpha[r]" if W == 8 and not PV_COLS else "tile_s[r * S_STRIDE + d] * row_alpha[r]" %}{% if W == 8 and not PV_COLS %} // The row's two key halves accumulated separately; their sum is the output.{% endif %} output[qBase + (q0 + r) * Q_STRIDE + {{ base }}u + d] = {{ OUT }}({{ val }}); } }{% endfor %} } else { // Portable fallback when the subgroup topology proof fails: each query row runs an // online softmax over its keys, its lanes splitting the head's output columns. if (row >= qFresh) {{% set VPL = (VDIM / LPR) | int %}{% set QA = "qAt" %} let qAt = qBase + (q0 + row) * Q_STRIDE;{% if AT_END %} let keyEnd = u32(clamp(i32(q0 + row) + causalShift + 1, 0, i32(kvEnd)));{% elif CAUSAL %} let keyEnd = min(kvEnd, q0 + row + 1u);{% else %} let keyEnd = kvEnd;{% endif %} var m = NEG_INF; var l = 0.0; var acc: array<f32, {{ VPL }}>; for (var j = {{ "keyBegin" if KV_SPLIT else "0u" }}; j < {{ "keyStop" if KV_SPLIT else "keyEnd" }}; j++) { let kAt = kvBase + j * KV_STRIDE; var s = 0.0; for (var d = 0u; d < HEAD_DIM / 8u; d++) { let word = key[kAt / 8u + d]; for (var x = 0u; x < 4u; x++) { let pair = bitcast<vec2<f16>>(word[x]); s += f32(query[{{ QA }} + 8u * d + 2u * x]) * f32(pair.x) + f32(query[{{ QA }} + 8u * d + 2u * x + 1u]) * f32(pair.y); } } s *= scale; let next = max(m, s); let rescale = exp(m - next); let w = exp(s - next); l = l * rescale + w; for (var d = 0u; d < {{ VPL }}u; d++) { let at = kAt + rowLane * {{ VPL }}u + d; let pair = bitcast<vec2<f16>>(value[at / 8u][(at % 8u) / 2u]); acc[d] = acc[d] * rescale + w * f32(pair[at % 2u]); } m = next; } for (var d = 0u; d < {{ VPL }}u; d++) { output[qAt + rowLane * {{ VPL }}u + d] = {{ OUT }}(select(0.0, acc[d] / l, l > 0.0)); } } }}{% endif %}123456789101112131415161718{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %} // 2D-folded flat index: gid.y carries the high bits past the dispatch's // per-axis workgroup fold width. let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% if bound != "" %} if ({{ name }} >= {{ bound }}) { return; }{% endif %}{% endmacro %}{{ env.wgsl.resourceDeclarations }}
@compute @workgroup_size(64, 1, 1)fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d(64, "i", prepareQElements) }} prepared_query[i] = query[i];}1234567891011121314151617181933 unmodified lines5354555657585960616263646566677 unmodified lines75767778798081828384858687888990919293949596979899100101102103104105106107108{% set maskIsBool = false %}{{ env.wgsl.resourceDeclarations }}// Thread-per-query online-softmax flash fallback for rank-4 (BNSH) attention with// no optional feature requirements. Each invocation owns one full query row and walks the keys// independently, avoiding per-key workgroup barriers and tree reductions.//// BLOCK_M consecutive queries of one (batch, q_head) are tiled into a workgroup,// so adjacent query threads reuse the same K/V row at each key index. The per-query online// accumulator lives in shared memory laid out d-major (d*BLOCK_M + tid) so the// BLOCK_M threads touch consecutive addresses for a fixed d. The value-head// width is capped so the accumulator fits in the workgroup-storage budget;// larger heads use the scalar online-attention fallback.const BLOCK_M: u32 = {{ blockM }}u;var<workgroup> acc: array<f32, {{ vHeadCap * blockM }}>;{% set ATTN_SCALE_DIM = "params.headSize" %}fn scale_value() -> f32 {33 unmodified lineslet qBase = (batch * params.qSeq + qs) * params.qHidden + qh * params.headSize;let scale = scale_value();for (var d: u32 = 0u; d < params.vHeadSize; d = d + 1u) {acc[d * BLOCK_M + tid] = 0.0;}var running_max: f32 = -3.4028234663852886e38;var running_denom: f32 = 0.0;// Causal: query qs attends keys [0, qs]. Per-thread bound — threads in the tile// diverge on trip count, which is fine (no barriers).var maxKj = params.kvSeq;if (params.isCausal != 0u) {maxKj = min(maxKj, qs + 1u);}7 unmodified linesvar score: f32 = -3.4028234663852886e38;if (!masked) {let kRow = (batch * params.kvSeq + ks) * params.kvHidden + kh * params.headSize;var dot: f32 = 0.0;for (var d: u32 = 0u; d < params.headSize; d = d + 1u) {dot = dot + f32(q[qBase + d]) * f32(k[kRow + d]);}score = dot * scale;if (params.softcap != 0.0) {score = params.softcap * tanh(score / params.softcap);}{% if hasMask and not maskIsBool %}let mIdxA = batch * params.maskBatchStride + qh * params.maskHeadStride + qs * params.maskSeqStride + ks;score = score + f32(attn_mask[mIdxA]);{% endif %}}let next_max = max(running_max, score);let prev_scale = exp(running_max - next_max);let weight = exp(score - next_max);running_max = next_max;running_denom = running_denom * prev_scale + weight;let vRow = (batch * params.kvSeq + ks) * params.vHidden + kh * params.vHeadSize;for (var d: u32 = 0u; d < params.vHeadSize; d = d + 1u) {acc[d * BLOCK_M + tid] = acc[d * BLOCK_M + tid] * prev_scale + weight * f32(v[vRow + d]);}}let inv_denom = select(0.0, 1.0 / running_denom, running_denom > 0.0);let yBase = (batch * params.qSeq + qs) * (params.qHeads * params.vHeadSize) + qh * params.vHeadSize;for (var d: u32 = 0u; d < params.vHeadSize; d = d + 1u) {y[yBase + d] = {{ scalar }}(acc[d * BLOCK_M + tid] * inv_denom);}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054133 unmodified lines5755765775785795805815825835845855865875885895905915925937 unmodified lines601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642fn attention_softcap(value: f32, limit: f32) -> f32 {let normalized = value / limit;if ((bitcast<u32>(normalized) & 0x7fffffffu) > 0x7f800000u) {return normalized;}// Beyond this range tanh is already saturated at f32 precision.return limit * tanh(clamp(normalized, -30.0, 30.0));}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {{ attn_seqlens_count(index) }}){% endmacro %}{% set cacheRow = false %}{% set normalizedValues = scalar == "f32" %}{{ env.wgsl.resourceDeclarations }}{% set COMP_SCORE = (compensatedScoreDot | default(false)) and scalar == "f32" %}{% set COMP_DENOM = (compensatedOnlineDenominator | default(false)) and COMP_SCORE %}{% macro accumulate_score(query, key) %}{% if COMP_SCORE %}score_acc = dot_accumulate(score_acc, {{ query }}, {{ key }});{% else %}dot = dot + {{ query }} * {{ key }};{% endif %}{% endmacro %}{% if COMP_SCORE %}{% set dotGuardNonfinite = true %}{% set dotType = "f32" %}{% set protectDifference = false %}{% set PROTECTED_SUM = false %}{% set SELECT_NONFINITE = false %}{% set ORDERED_SUM = false %}// Retain product and addition residuals across a dot product. Explicit fma// boundaries preserve the addition error transform under reassociation.struct DotAccumulator {hi: {{ dotType }},lo: {{ dotType }},}{% if dotRecoverProductResidual | default(false) %}{% set dotBitsType = "u32" %}// Recover an inexact product when a backend returns a zero fma residual.{% set dotExponentType = "i32" %}{% macro dot_parts() -%}let aBits = bitcast<{{ dotBitsType }}>(a);let bBits = bitcast<{{ dotBitsType }}>(b);let pBits = bitcast<{{ dotBitsType }}>(product);let ae = (aBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let be = (bBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let pe = (pBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);{% endmacro %}fn dot_product_error(a: {{ dotType }}, b: {{ dotType }}, product: {{ dotType }}) -> {{ dotType }} {// Twelve-bit significand parts make each split product exactly representable.let nativeError = fma(a, b, -product);if (nativeError == 0.0) {{{ dot_parts() | indent(4, true) }}let lowProduct = (((aBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u)) *((bBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u))) & {{ dotBitsType }}(0x00ffffffu);let recover = (nativeError == {{ dotType }}(0.0)) && (lowProduct != {{ dotBitsType }}(0u)) && (ae > {{ dotBitsType }}(0u)) && (ae < {{ dotBitsType }}(255u)) && (be > {{ dotBitsType }}(0u)) && (be < {{ dotBitsType }}(255u)) && (pe > {{ dotBitsType }}(0u)) && (pe < {{ dotBitsType }}(255u));if (recover) {// Normalize before splitting: a normal input can otherwise produce a// subnormal low word that a conformant backend is allowed to flush.let an = bitcast<{{ dotType }}>((aBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u));let bn = bitcast<{{ dotType }}>((bBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u));let exponent = select({{ dotExponentType }}(0), {{ dotExponentType }}(ae) + {{ dotExponentType }}(be) - {{ dotExponentType }}(254), recover);let pnExponent = select({{ dotBitsType }}(127u), {{ dotBitsType }}({{ dotExponentType }}(pe) - exponent), recover);let pn = bitcast<{{ dotType }}>((pBits & {{ dotBitsType }}(0x807fffffu)) | (pnExponent << {{ dotBitsType }}(23u)));let ah = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(an) & {{ dotBitsType }}(0xfffff000u));let bh = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(bn) & {{ dotBitsType }}(0xfffff000u));let al = fma({{ dotType }}(-1.0), ah, an);let bl = fma({{ dotType }}(-1.0), bh, bn);let e0 = fma(ah, bh, -pn);let e1 = fma(al, bh, e0);let e2 = fma(ah, bl, e1);let recovered = ldexp(fma(al, bl, e2), exponent);return select(nativeError, recovered, recover);}}return nativeError;}{% endif %}{% macro dot_step(name, dotGuardNonfinite) %}fn {{ name }}(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator {let product = fma(a, b, {{ dotType }}(0.0));{% if dotGuardNonfinite | default(false) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);{% if not SELECT_NONFINITE %} // Nonfinite sums retain ordinary f32 addition classes; Inf-Inf residuals// must not poison a valid infinite dot accumulator.{% if ORDERED_SUM %} if (!(abs(sum) <= 3.4028234663852886e38 && abs(acc.lo) <= 3.4028234663852886e38)) {{% else %} if (!(abs(acc.hi) <= 3.4028234663852886e38) ||!(abs(acc.lo) <= 3.4028234663852886e38) ||!(abs(product) <= 3.4028234663852886e38) ||!(abs(sum) <= 3.4028234663852886e38)) {{% endif %} return DotAccumulator(sum, {{ dotType }}(0.0));}{% endif %}{% endif %} let productError = {% if dotRecoverProductResidual | default(false) %}dot_product_error(a, b, product){% else %}fma(a, b, -product){% endif %};{% if not (dotGuardNonfinite | default(false)) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);{% endif %}{% if PROTECTED_SUM %}let roundoff = dot_sum_error(acc.hi, product, sum);let error = (acc.lo + roundoff) + productError;{% elif ORDERED_SUM %} let productLarger = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, productLarger);let smaller = select(product, acc.hi, productLarger);let roundoff = fma(-1.0, fma(-1.0, larger, sum), smaller);let error = fma(fma(roundoff, 1.0, acc.lo), 1.0, productError);{% else %} let bv = fma({{ dotType }}(-1.0), acc.hi, sum);let av = fma({{ dotType }}(-1.0), bv, sum);let ae = fma({{ dotType }}(-1.0), av, acc.hi);let be = fma({{ dotType }}(-1.0), bv, product);let error = fma(fma(fma(ae, {{ dotType }}(1.0), be), {{ dotType }}(1.0), acc.lo), {{ dotType }}(1.0), productError);{% endif %}{% if PROTECTED_SUM %}// Carry the residual to the end of the dot. Renormalizing each step can// round a recovered product bit out of the low word on relaxed backends.return DotAccumulator(sum, error);{% else %} let hi = fma(sum, {{ dotType }}(1.0), error);{% if SELECT_NONFINITE %} let sumValid = abs(sum) <= 3.4028234663852886e38 && abs(acc.lo) <= 3.4028234663852886e38;let nextLo = fma(-1.0, fma(-1.0, sum, hi), error);return DotAccumulator(select(sum, hi, sumValid), select(0.0, nextLo, sumValid && abs(hi) <= 3.4028234663852886e38));{% else %}{% if dotGuardNonfinite | default(false) %} if (!(abs(hi) <= 3.4028234663852886e38)) {return DotAccumulator(hi, {{ dotType }}(0.0));}{% endif %} return DotAccumulator(hi, fma({{ dotType }}(-1.0), fma({{ dotType }}(-1.0), sum, hi), error));{% endif %}{% endif %}}{% endmacro %}{{ dot_step("dot_accumulate", dotGuardNonfinite | default(false)) }}fn dot_value(acc: DotAccumulator) -> {{ dotType }} {return fma(acc.hi, {{ dotType }}(1.0), acc.lo);}{% endif %}{% if COMP_DENOM %}fn attention_denom_update(acc: DotAccumulator, correction: f32, weight: f32) -> DotAccumulator {var scaled = acc;if (correction != 1.0) {scaled = dot_accumulate(DotAccumulator(0.0, 0.0), acc.hi, correction);scaled = dot_accumulate(scaled, acc.lo, correction);}return dot_accumulate(scaled, weight, 1.0);}{% endif %}{% if normalizedValues %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&{% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &{% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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 }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("f32", "f32", true) }}{% endif %}// Thread-per-query online-softmax flash fallback for rank-4 (BNSH) attention with// no optional feature requirements. Each invocation owns one full query row and walks the keys// independently, avoiding per-key workgroup barriers and tree reductions.//// BLOCK_M consecutive queries of one (batch, q_head) are tiled into a workgroup,{% if normalizedValues %}// so adjacent query threads reuse the same K/V row at each key index.// Exponent-aware value state stays private, with one update loop body.// Optional query caching keeps statically named f32 query registers.{% else %}// so adjacent query threads reuse the same K/V row at each key index. The per-query online// accumulator lives in shared memory laid out d-major (d*BLOCK_M + tid) so the// BLOCK_M threads touch consecutive addresses for a fixed d. The value-head// width is capped so the accumulator fits in the workgroup-storage budget;// larger heads use the scalar online-attention fallback.{% endif %}const BLOCK_M: u32 = {{ blockM }}u;{% if not cacheRow and not normalizedValues %}var<workgroup> acc: array<f32, {{ vHeadCap * blockM }}>;{% endif %}{% set ATTN_SCALE_DIM = "params.headSize" %}fn scale_value() -> f32 {33 unmodified lineslet qBase = (batch * params.qSeq + qs) * params.qHidden + qh * params.headSize;let scale = scale_value();{% if normalizedValues %}var acc: array<ScaledValue, {{ vHeadCap }}>;for (var d = 0u; d < params.vHeadSize; d++) { acc[d] = scaled_value_zero(); }{% else %} for (var d: u32 = 0u; d < params.vHeadSize; d = d + 1u) {acc[d * BLOCK_M + tid] = 0.0;}{% endif %}var running_max: f32 = -3.4028234663852886e38;var running_denom: {% if COMP_DENOM %}DotAccumulator = DotAccumulator(0.0, 0.0){% else %}f32 = 0.0{% endif %};// Causal: query qs attends keys [0, qs]. Per-thread bound — threads in the tile// diverge on trip count, which is fine (no barriers).var maxKj = {{ attn_seqlens_bound("params.kvSeq", "batch") }};if (params.isCausal != 0u) {maxKj = min(maxKj, qs + 1u);}7 unmodified linesvar score: f32 = -3.4028234663852886e38;if (!masked) {let kRow = (batch * params.kvSeq + ks) * params.kvHidden + kh * params.headSize;{% if COMP_SCORE %} var score_acc = DotAccumulator(0.0, 0.0);{% else %} var dot: f32 = 0.0;{% endif %}for (var d: u32 = 0u; d < params.headSize; d = d + 1u) {{{ accumulate_score("f32(q[qBase + d])", "f32(k[kRow + d])") }}}{% if COMP_SCORE %} let dot = dot_value(score_acc);{% endif %} score = dot * scale;if (params.softcap != 0.0) {score = attention_softcap(score, params.softcap);}}let next_max = max(running_max, score);let prev_scale = exp(running_max - next_max);let weight = exp(score - next_max);running_max = next_max;{% if COMP_DENOM %} running_denom = attention_denom_update(running_denom, prev_scale, weight);{% else %} running_denom = running_denom * prev_scale + weight;{% endif %}let vRow = (batch * params.kvSeq + ks) * params.vHidden + kh * params.vHeadSize;for (var d: u32 = 0u; d < params.vHeadSize; d = d + 1u) {{% if normalizedValues %}acc[d] = scaled_value_add(scaled_value_rescale(acc[d], prev_scale), weight, f32(v[vRow + d]));{% else %}acc[d * BLOCK_M + tid] = acc[d * BLOCK_M + tid] * prev_scale + weight * f32(v[vRow + d]);{% endif %}}}{% if COMP_DENOM %} let denominator = dot_value(running_denom);{% endif %}{% if not normalizedValues %}let inv_denom = select(0.0, 1.0 / running_denom, running_denom > 0.0);{% endif %}let yBase = (batch * params.qSeq + qs) * (params.qHeads * params.vHeadSize) + qh * params.vHeadSize;for (var d: u32 = 0u; d < params.vHeadSize; d = d + 1u) {y[yBase + d] = {{ scalar }}({% if normalizedValues %}scaled_value_mean(acc[d], {% if COMP_DENOM %}denominator{% else %}running_denom{% endif %}){% else %}acc[d * BLOCK_M + tid] * inv_denom{% endif %});}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477{%- set BHSD = true -%}{%- set SEQLENS = BHSD and gqaSeqlens is defined and gqaSeqlens -%}{%- set OUT16 = (gqaOutScalar | default("f32")) == "f16" -%}{%- if SEQLENS %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {{ attn_seqlens_count(index) }}){% endmacro %}{% endif %}{% set NORMALIZED_VALUES = gqaNormalizedValues | default(false) %}{{ env.wgsl.resourceDeclarations }}{% if NORMALIZED_VALUES %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} { let bits = bitcast<{{ bitsType }}>(x); return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} { let swap = abs(a) < abs(b); let larger = select(a, b, swap); let smaller = select(b, a, swap); // Keep the rounded high-part difference observable before subtracting it // from the smaller addend. Reassociation here erases the residual. return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }
{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar { return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool { return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 { if (a.hi == 0.0) { if (a.lo == 0.0) { return -1024; } return a.exponent + frexp(a.lo).exp; } if (!scaled_value_scalar_finite(a.hi)) { return 1024; } return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 { let bits = bitcast<u32>(value); let sign = bits & 0x80000000u; let fraction = bits & 0x007fffffu; let inputExponent = i32((bits >> 23u) & 0xffu); if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; } var significand = fraction | 0x00800000u; var exponent = inputExponent + shift; if (inputExponent == 0) { let normalize = countLeadingZeros(fraction) - 8u; significand = fraction << normalize; exponent = 1 + shift - i32(normalize); } if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); } if (exponent > 0) { return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu)); } let distance = u32(1 - exponent); if (distance > 24u) { return bitcast<f32>(sign); } let high = significand >> distance; let remainder = significand & ((1u << distance) - 1u); let halfway = 1u << (distance - 1u); let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u); return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar { if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); } if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); } return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar { let nextHi = fma(hi, 1.0, lo); let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %}; if (nextHi == 0.0) { return scaled_value_scalar_zero(); } if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); } let parts = frexp(nextHi); let rawExponent = exponent + parts.exp; // Ordinary magnitudes return to the unscaled fast path. The margin keeps // boundary values away from overflow/underflow while scaling the low word. if (rawExponent >= -120 && rawExponent <= 120) { return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0); } return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar { let sum = fma(a.hi, 1.0, product); let bv = fma(-1.0, a.hi, sum); let av = fma(-1.0, bv, sum); let ae = fma(-1.0, av, a.hi); let be = fma(-1.0, bv, product); let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error); let hi = fma(sum, 1.0, residual); return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar { if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) || !scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) || !scaled_value_scalar_finite(weight)) { return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0); } if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; } if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; } if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) { let product = fma(weight, b.hi, 0.0); let lowProduct = fma(weight, b.lo, 0.0); let rawSum = fma(a.hi, 1.0, product); let productNormal = abs(product) >= 1.1754943508222875e-38; if (productNormal && scaled_value_scalar_finite(product) && scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) { let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct); let result = scaled_value_scalar_add_words(a, product, error); if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; } } } // Decompose BEFORE multiplying: a merge coefficient may exceed one, so // its unscaled product with a finite partial mean need not fit in f32. var other = b; if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); } let wp = frexp(weight); let vp = frexp(other.hi); let productExponent = other.exponent + wp.exp + vp.exp; let commonExponent = max(scaled_value_scalar_leading(a), productExponent); let aligned = scaled_value_scalar_align(a, commonExponent); let product = fma(wp.fract, vp.fract, 0.0); let productError = fma(wp.fract, vp.fract, -product); let shift = productExponent - commonExponent; let highWord = scaled_value_scalar_shift(product, shift); let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0, fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %} let sum = aligned.hi + highWord; let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord; return scaled_value_scalar_finish(sum, low, commonExponent);{% else %} let result = scaled_value_scalar_add_words(aligned, highWord, lowWord); return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 { if (denominator == 0.0) { return 0.0; } if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; } if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) { return fma(a.hi, 1.0, a.lo) / denominator; } let valueParts = frexp(a.hi); let denominatorParts = frexp(denominator); let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp)); let quotient = mantissa / denominatorParts.fract; return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue { return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue { let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %} // FastTwoSum recovers the rounding error with the larger magnitude first. let takeProduct = abs(acc.hi) < abs(product); let larger = select(acc.hi, product, takeProduct); let smaller = select(product, acc.hi, takeProduct); let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller); let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %} let bv = fma({{ type }}(-1.0), acc.hi, sum); let av = fma({{ type }}(-1.0), bv, sum); let ae = fma({{ type }}(-1.0), av, acc.hi); let be = fma({{ type }}(-1.0), bv, product); let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %} let hi = fma(sum, {{ type }}(1.0), residual); return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue { let w = {{ type }}(weight); let product = fma(w, value, {{ type }}(0.0)); return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} { return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool { return all(start.exponent == {{ exponentType }}(0)) && all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) & (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) & ({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile { let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37))); let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u)); return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile { let w = {{ type }}(weight); let sum = fma(w, value, tile.sum); let change = fma({{ type }}(-1.0), tile.sum, sum); return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue { let high = fma({{ type }}(-1.0), tile.offset, tile.sum); let sum = fma(high, {{ type }}(1.0), tile.low); let bv = fma({{ type }}(-1.0), high, sum); let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low)); return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool { return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) && {% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) | (bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep { let w = {{ type }}(weight); let product = fma(w, value, {{ type }}(0.0)); let sum = scaled_value_add_words(acc, product, fma(w, value, -product)); let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38)); let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) & {% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38)); return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent), fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %} // Ordinary raw products use one vector compensated sum. Every exceptional // component falls back to the same scalar exponent-aware implementation. if (all(acc.exponent == {{ exponentType }}(0)) && all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) && all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) { let step = scaled_value_add_step(acc, weight, value); if (all(step.exact)) { return step.value; } }{% endif %} var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} 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)); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %} let w = {{ type }}(correction); let product = fma(w, acc.hi, {{ type }}(0.0)); let scaled = scaled_value_add_words(scaled_value_zero(), product, fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0)))); let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0); let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) & (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) & (zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero), select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue { // From finite words at exponent zero, the scalar path below leaves zero // words for a zero value or correction, the value itself for a unit // correction, and otherwise this compensated product onto zero words when // the product is normal and the low word finite (which bounds the rest, as // in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) { return {{ rescale_vector_value() }}; } var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }})); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue { var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} 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 }})); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} { // Words at exponent zero well inside the normal range, with a normal // quotient: the scalar path below divides this same sum by this same // denominator, each scaled by a power of two, so it rounds to this quotient // wherever division is scale-invariant. Bounding the denominator above also // keeps a division through its reciprocal clear of a subnormal reciprocal. let d = {{ type }}(denominator); let sum = fma(acc.hi, {{ type }}(1.0), acc.lo); let quotient = sum / d; if (all((acc.exponent == {{ exponentType }}(0)) & (abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) & (abs(acc.lo) <= abs(acc.hi)) & (abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) & ((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) { return quotient; } var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %} return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} { var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %} return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue { var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }}); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("vec4<f32>") }}{% endif %}
// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret// a zero final denominator according to their public semantics. Using -inf// here changes +inf-row behavior.const FLT_MAX: f32 = 3.4028234663852886e38;
fn is_finite_f32(value: f32) -> bool { return select(false, value <= FLT_MAX, value >= -FLT_MAX);}
// x - m that is exactly 0 when x equals a finite m, so exp(shifted) == 1// exactly at the row max. `x - x` on an infinite max is a legal fast-math// fold to 0, which would silently turn +inf rows finite — the explicit// equality test keeps the NaN propagation of the serial kernels.fn shifted_value(value: f32, maxValue: f32) -> f32 { let equalFiniteMax = select(false, value == maxValue, is_finite_f32(maxValue)); return select(value - maxValue, 0.0, equalFiniteMax);}
fn exp_shift(value: f32, maxValue: f32) -> f32 { return exp(shifted_value(value, maxValue));}
const HEAD_DIM_V4: u32 = {{ (headDim / 4) | int }}u;const NUM_SPLITS: u32 = {{ numSplits }}u;const MIN_KEYS: u32 = {{ gqaMinKeys }}u;const Q_HEADS: u32 = {{ numHeads | default(1) }}u;
// One workgroup per query head; one lane per output vec4.@compute @workgroup_size({{ (headDim / 4) | int }}, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) d4: u32) { let h = wid.z * Q_HEADS + wid.y;{% if SEQLENS %} let kvSeq = {{ attn_seqlens_bound("params.kvSeq", "wid.z") }};{% else %} let kvSeq = params.kvSeq;{% endif %} let keysPerSplit = max((kvSeq + NUM_SPLITS - 1u) / NUM_SPLITS, MIN_KEYS); let live = (kvSeq + keysPerSplit - 1u) / keysPerSplit; var globalMax = -FLT_MAX; for (var s = 0u; s < live; s++) { globalMax = max(globalMax, partial_stats[h * NUM_SPLITS + s].x); } var globalDenom = 0.0;{% if not NORMALIZED_VALUES %} var outV = vec4<f32>(0.0);{% endif %} for (var s = 0u; s < live; s++) { let stats = partial_stats[h * NUM_SPLITS + s]; let w = exp_shift(stats.x, globalMax); globalDenom += stats.y * w;{% if not NORMALIZED_VALUES %} outV += partial_out[(h * NUM_SPLITS + s) * HEAD_DIM_V4 + d4] * w;{% endif %} }{% if NORMALIZED_VALUES %} var raw = scaled_value_zero(); for (var s = 0u; s < live; s++) { let stats = partial_stats[h * NUM_SPLITS + s]; let mass = stats.y * exp_shift(stats.x, globalMax); raw = scaled_value_add(raw, mass, partial_out[(h * NUM_SPLITS + s) * HEAD_DIM_V4 + d4]); } let outV = scaled_value_mean(raw, globalDenom);{% endif %} let outValue = select(vec4<f32>(0.0), outV{% if not NORMALIZED_VALUES %} / globalDenom{% endif %}, globalDenom > 0.0); output[h * HEAD_DIM_V4 + d4] = {{ "vec4<f16>(outValue)" if OUT16 else "outValue" }};}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640{%- set BHSD = true -%}{%- set SEQLENS = BHSD and gqaSeqlens is defined and gqaSeqlens -%}{%- if SEQLENS %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {{ attn_seqlens_count(index) }}){% endmacro %}{% endif %}{% set NORMALIZED_VALUES = gqaNormalizedValues | default(false) %}{{ env.wgsl.resourceDeclarations }}{% if NORMALIZED_VALUES %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} { let bits = bitcast<{{ bitsType }}>(x); return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} { let swap = abs(a) < abs(b); let larger = select(a, b, swap); let smaller = select(b, a, swap); // Keep the rounded high-part difference observable before subtracting it // from the smaller addend. Reassociation here erases the residual. return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }
{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar { return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool { return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 { if (a.hi == 0.0) { if (a.lo == 0.0) { return -1024; } return a.exponent + frexp(a.lo).exp; } if (!scaled_value_scalar_finite(a.hi)) { return 1024; } return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 { let bits = bitcast<u32>(value); let sign = bits & 0x80000000u; let fraction = bits & 0x007fffffu; let inputExponent = i32((bits >> 23u) & 0xffu); if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; } var significand = fraction | 0x00800000u; var exponent = inputExponent + shift; if (inputExponent == 0) { let normalize = countLeadingZeros(fraction) - 8u; significand = fraction << normalize; exponent = 1 + shift - i32(normalize); } if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); } if (exponent > 0) { return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu)); } let distance = u32(1 - exponent); if (distance > 24u) { return bitcast<f32>(sign); } let high = significand >> distance; let remainder = significand & ((1u << distance) - 1u); let halfway = 1u << (distance - 1u); let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u); return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar { if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); } if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); } return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar { let nextHi = fma(hi, 1.0, lo); let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %}; if (nextHi == 0.0) { return scaled_value_scalar_zero(); } if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); } let parts = frexp(nextHi); let rawExponent = exponent + parts.exp; // Ordinary magnitudes return to the unscaled fast path. The margin keeps // boundary values away from overflow/underflow while scaling the low word. if (rawExponent >= -120 && rawExponent <= 120) { return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0); } return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar { let sum = fma(a.hi, 1.0, product); let bv = fma(-1.0, a.hi, sum); let av = fma(-1.0, bv, sum); let ae = fma(-1.0, av, a.hi); let be = fma(-1.0, bv, product); let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error); let hi = fma(sum, 1.0, residual); return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar { if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) || !scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) || !scaled_value_scalar_finite(weight)) { return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0); } if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; } if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; } if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) { let product = fma(weight, b.hi, 0.0); let lowProduct = fma(weight, b.lo, 0.0); let rawSum = fma(a.hi, 1.0, product); let productNormal = abs(product) >= 1.1754943508222875e-38; if (productNormal && scaled_value_scalar_finite(product) && scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) { let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct); let result = scaled_value_scalar_add_words(a, product, error); if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; } } } // Decompose BEFORE multiplying: a merge coefficient may exceed one, so // its unscaled product with a finite partial mean need not fit in f32. var other = b; if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); } let wp = frexp(weight); let vp = frexp(other.hi); let productExponent = other.exponent + wp.exp + vp.exp; let commonExponent = max(scaled_value_scalar_leading(a), productExponent); let aligned = scaled_value_scalar_align(a, commonExponent); let product = fma(wp.fract, vp.fract, 0.0); let productError = fma(wp.fract, vp.fract, -product); let shift = productExponent - commonExponent; let highWord = scaled_value_scalar_shift(product, shift); let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0, fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %} let sum = aligned.hi + highWord; let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord; return scaled_value_scalar_finish(sum, low, commonExponent);{% else %} let result = scaled_value_scalar_add_words(aligned, highWord, lowWord); return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 { if (denominator == 0.0) { return 0.0; } if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; } if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) { return fma(a.hi, 1.0, a.lo) / denominator; } let valueParts = frexp(a.hi); let denominatorParts = frexp(denominator); let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp)); let quotient = mantissa / denominatorParts.fract; return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue { return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue { let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %} // FastTwoSum recovers the rounding error with the larger magnitude first. let takeProduct = abs(acc.hi) < abs(product); let larger = select(acc.hi, product, takeProduct); let smaller = select(product, acc.hi, takeProduct); let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller); let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %} let bv = fma({{ type }}(-1.0), acc.hi, sum); let av = fma({{ type }}(-1.0), bv, sum); let ae = fma({{ type }}(-1.0), av, acc.hi); let be = fma({{ type }}(-1.0), bv, product); let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %} let hi = fma(sum, {{ type }}(1.0), residual); return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue { let w = {{ type }}(weight); let product = fma(w, value, {{ type }}(0.0)); return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} { return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool { return all(start.exponent == {{ exponentType }}(0)) && all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) & (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) & ({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile { let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37))); let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u)); return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile { let w = {{ type }}(weight); let sum = fma(w, value, tile.sum); let change = fma({{ type }}(-1.0), tile.sum, sum); return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue { let high = fma({{ type }}(-1.0), tile.offset, tile.sum); let sum = fma(high, {{ type }}(1.0), tile.low); let bv = fma({{ type }}(-1.0), high, sum); let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low)); return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool { return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) && {% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) | (bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep { let w = {{ type }}(weight); let product = fma(w, value, {{ type }}(0.0)); let sum = scaled_value_add_words(acc, product, fma(w, value, -product)); let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38)); let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) & {% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38)); return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent), fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %} // Ordinary raw products use one vector compensated sum. Every exceptional // component falls back to the same scalar exponent-aware implementation. if (all(acc.exponent == {{ exponentType }}(0)) && all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) && all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) { let step = scaled_value_add_step(acc, weight, value); if (all(step.exact)) { return step.value; } }{% endif %} var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} 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)); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %} let w = {{ type }}(correction); let product = fma(w, acc.hi, {{ type }}(0.0)); let scaled = scaled_value_add_words(scaled_value_zero(), product, fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0)))); let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0); let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) & (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) & (zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero), select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue { // From finite words at exponent zero, the scalar path below leaves zero // words for a zero value or correction, the value itself for a unit // correction, and otherwise this compensated product onto zero words when // the product is normal and the low word finite (which bounds the rest, as // in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) { return {{ rescale_vector_value() }}; } var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }})); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue { var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} 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 }})); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} { // Words at exponent zero well inside the normal range, with a normal // quotient: the scalar path below divides this same sum by this same // denominator, each scaled by a power of two, so it rounds to this quotient // wherever division is scale-invariant. Bounding the denominator above also // keeps a division through its reciprocal clear of a subnormal reciprocal. let d = {{ type }}(denominator); let sum = fma(acc.hi, {{ type }}(1.0), acc.lo); let quotient = sum / d; if (all((acc.exponent == {{ exponentType }}(0)) & (abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) & (abs(acc.lo) <= abs(acc.hi)) & (abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) & ((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) { return quotient; } var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %} return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} { var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %} return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue { var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }}); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("vec4<f32>", rescale=true, align=true) }}{% endif %}
// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret// a zero final denominator according to their public semantics. Using -inf// here changes +inf-row behavior.const FLT_MAX: f32 = 3.4028234663852886e38;
fn is_finite_f32(value: f32) -> bool { return select(false, value <= FLT_MAX, value >= -FLT_MAX);}
// x - m that is exactly 0 when x equals a finite m, so exp(shifted) == 1// exactly at the row max. `x - x` on an infinite max is a legal fast-math// fold to 0, which would silently turn +inf rows finite — the explicit// equality test keeps the NaN propagation of the serial kernels.fn shifted_value(value: f32, maxValue: f32) -> f32 { let equalFiniteMax = select(false, value == maxValue, is_finite_f32(maxValue)); return select(value - maxValue, 0.0, equalFiniteMax);}
fn exp_shift(value: f32, maxValue: f32) -> f32 { return exp(shifted_value(value, maxValue));}
const HEAD_DIM_V4: u32 = {{ (headDim / 4) | int }}u;const GROUP: u32 = {{ gqaGroup }}u;const KV_HEADS: u32 = {{ numKvHeads }}u;const NUM_SPLITS: u32 = {{ numSplits }}u;const MIN_KEYS: u32 = {{ gqaMinKeys }}u;const Q_HEADS: u32 = {{ numKvHeads * gqaGroup }}u;const WG: u32 = 256u;// Q.K: eight lanes per key, interleaved over its vec4s, so a block holds 32 keys.const PARTS: u32 = 8u;const BLOCK: u32 = WG / PARTS;// P.V: one lane per output vec4, WG / HEAD_DIM_V4 lanes per vec4 over the block's keys.const KEY_LANES: u32 = WG / HEAD_DIM_V4;
var<workgroup> q_sh: array<vec4<f32>, {{ gqaGroup * ((headDim / 4) | int) }}>;// Per key, part and head: partial dots.var<workgroup> part_sh: array<f32, {{ 256 * gqaGroup }}>;// Per head and key: scores, then probabilities.var<workgroup> p_sh: array<f32, {{ 32 * gqaGroup }}>;// Per head: running maximum and sum, and this block's rescale factor.var<workgroup> m_sh: array<f32, {{ gqaGroup }}>;var<workgroup> l_sh: array<f32, {{ gqaGroup }}>;var<workgroup> alpha_sh: array<f32, {{ gqaGroup }}>;// Per key lane, head and vec4: output sums reduced at the end.var<workgroup> o_sh: array<vec4<f32>, {{ 256 * gqaGroup }}>;
@compute @workgroup_size(256, 1, 1)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32) { let split = wid.x; let kvHead = wid.y; let b = wid.z; let cacheSeq = params.kvSeq;{% if SEQLENS %} let kvSeq = {{ attn_seqlens_bound("cacheSeq", "b") }};{% else %} let kvSeq = cacheSeq;{% endif %} let keysPerSplit = max((kvSeq + NUM_SPLITS - 1u) / NUM_SPLITS, MIN_KEYS); let splitStart = min(split * keysPerSplit, kvSeq); let splitEnd = min(splitStart + keysPerSplit, kvSeq); // Ranges past the live keys write nothing; the merge reads only the live ones. if (splitStart >= splitEnd) { return; } let kvBaseV4 = (b * KV_HEADS + kvHead) * cacheSeq * HEAD_DIM_V4; let kvStrideV4 = HEAD_DIM_V4; let headBase = b * Q_HEADS + kvHead * GROUP; let qBaseV4 = headBase * HEAD_DIM_V4; let scale = select(params.scale, inverseSqrt(f32(HEAD_DIM_V4 * 4u)), params.scale == 0.0); for (var e = tid; e < GROUP * HEAD_DIM_V4; e += WG) { q_sh[e] = vec4<f32>(query[qBaseV4 + e]); } if (tid < GROUP) { m_sh[tid] = -FLT_MAX; l_sh[tid] = 0.0; } let keyIndex = tid / PARTS; let part = tid % PARTS; let d4 = tid % HEAD_DIM_V4; let keyLane = tid / HEAD_DIM_V4; var o: array<{% if NORMALIZED_VALUES %}ScaledValue{% else %}vec4<f32>{% endif %}, {{ gqaGroup }}>; workgroupBarrier(); for (var blockStart = splitStart; blockStart < splitEnd; blockStart += BLOCK) { let blockKeys = min(BLOCK, splitEnd - blockStart); // Partial dots of this lane's interleaved vec4s with every head of the group. var dots: array<f32, {{ gqaGroup }}>; for (var g = 0u; g < GROUP; g++) { dots[g] = 0.0; } if (keyIndex < blockKeys) { let row = kvBaseV4 + (blockStart + keyIndex) * kvStrideV4; for (var i = part; i < HEAD_DIM_V4; i += PARTS) { let k = vec4<f32>(key_cache[row + i]); for (var g = 0u; g < GROUP; g++) { dots[g] += dot(q_sh[g * HEAD_DIM_V4 + i], k); } } } for (var g = 0u; g < GROUP; g++) { part_sh[tid * GROUP + g] = dots[g]; } workgroupBarrier(); // Scores, per head and key. var score = -FLT_MAX; if (tid < GROUP * BLOCK) { let g = tid / BLOCK; let k = tid % BLOCK; if (k < blockKeys) { var s = 0.0; for (var x = 0u; x < PARTS; x++) { s += part_sh[(k * PARTS + x) * GROUP + g]; } score = s * {{ "scale" if BHSD else "ATTN_SCALE" }}; } p_sh[tid] = score; } workgroupBarrier(); // Each head's new running maximum and the rescale of its sums. if (tid < GROUP) { var blockMax = -FLT_MAX; for (var k = 0u; k < blockKeys; k++) { blockMax = max(blockMax, p_sh[tid * BLOCK + k]); } let next = max(m_sh[tid], blockMax); alpha_sh[tid] = exp_shift(m_sh[tid], next); m_sh[tid] = next; } workgroupBarrier(); if (tid < GROUP * BLOCK && tid % BLOCK < blockKeys) { p_sh[tid] = exp_shift(score, m_sh[tid / BLOCK]); } workgroupBarrier(); if (tid < GROUP) { var sum = 0.0; for (var k = 0u; k < blockKeys; k++) { sum += p_sh[tid * BLOCK + k]; } l_sh[tid] = l_sh[tid] * alpha_sh[tid] + sum; }{% if NORMALIZED_VALUES %} workgroupBarrier();{% endif %} // P.V: this lane's vec4 over every KEY_LANES-th key, for every head. for (var g = 0u; g < GROUP; g++) {{% if NORMALIZED_VALUES %} o[g] = scaled_value_rescale(o[g], alpha_sh[g]);{% else %} o[g] *= alpha_sh[g];{% endif %} } for (var k = keyLane; k < blockKeys; k += KEY_LANES) { let v = vec4<f32>(value_cache[kvBaseV4 + (blockStart + k) * kvStrideV4 + d4]); for (var g = 0u; g < GROUP; g++) {{% if NORMALIZED_VALUES %} o[g] = scaled_value_add(o[g], p_sh[g * BLOCK + k], v);{% else %} o[g] += p_sh[g * BLOCK + k] * v;{% endif %} } } workgroupBarrier(); }{% if NORMALIZED_VALUES %} // Reuse the output scratch for exponents, high words, and low words in // successive barrier-separated phases. Keep raw states until the lane fold // is complete, so individually subnormal normalized terms remain visible. for (var g = 0u; g < GROUP; g++) { o_sh[(keyLane * GROUP + g) * HEAD_DIM_V4 + d4] = vec4<f32>(scaled_value_leading_exponent(o[g])); } workgroupBarrier(); var commonExponent: array<vec4<i32>, {{ ceilDiv(gqaGroup * ((headDim / 4) | int), 256) }}>; for (var e = tid; e < GROUP * HEAD_DIM_V4; e += WG) { let g = e / HEAD_DIM_V4; var leading = vec4<f32>(-1024.0); for (var lane = 0u; lane < KEY_LANES; lane++) { leading = max(leading, o_sh[(lane * GROUP + g) * HEAD_DIM_V4 + e % HEAD_DIM_V4]); } commonExponent[e / WG] = vec4<i32>(leading); o_sh[e] = leading; } workgroupBarrier(); var aligned: array<ScaledValue, {{ gqaGroup }}>; for (var g = 0u; g < GROUP; g++) { aligned[g] = scaled_value_align(o[g], vec4<i32>(o_sh[g * HEAD_DIM_V4 + d4])); } workgroupBarrier(); for (var g = 0u; g < GROUP; g++) { o_sh[(keyLane * GROUP + g) * HEAD_DIM_V4 + d4] = aligned[g].hi; } workgroupBarrier(); var highWord: array<vec4<f32>, {{ ceilDiv(gqaGroup * ((headDim / 4) | int), 256) }}>; for (var e = tid; e < GROUP * HEAD_DIM_V4; e += WG) { let g = e / HEAD_DIM_V4; for (var lane = 0u; lane < KEY_LANES; lane++) { highWord[e / WG] += o_sh[(lane * GROUP + g) * HEAD_DIM_V4 + e % HEAD_DIM_V4]; } } workgroupBarrier(); for (var g = 0u; g < GROUP; g++) { o_sh[(keyLane * GROUP + g) * HEAD_DIM_V4 + d4] = aligned[g].lo; } workgroupBarrier(); for (var e = tid; e < GROUP * HEAD_DIM_V4; e += WG) { let g = e / HEAD_DIM_V4; var lowWord = vec4<f32>(0.0); for (var lane = 0u; lane < KEY_LANES; lane++) { lowWord += o_sh[(lane * GROUP + g) * HEAD_DIM_V4 + e % HEAD_DIM_V4]; } let sum = scaled_value_mean(ScaledValue(highWord[e / WG], lowWord, commonExponent[e / WG]), l_sh[g]); partial_out[(({{ "headBase" if BHSD else "kvHead * GROUP" }} + g) * NUM_SPLITS + split) * HEAD_DIM_V4 + e % HEAD_DIM_V4] = sum; }{% else %} for (var g = 0u; g < GROUP; g++) { o_sh[(keyLane * GROUP + g) * HEAD_DIM_V4 + d4] = o[g]; } workgroupBarrier(); for (var e = tid; e < GROUP * HEAD_DIM_V4; e += WG) { let g = e / HEAD_DIM_V4; var sum = vec4<f32>(0.0); for (var lane = 0u; lane < KEY_LANES; lane++) { sum += o_sh[(lane * GROUP + g) * HEAD_DIM_V4 + e % HEAD_DIM_V4]; } partial_out[(({{ "headBase" if BHSD else "kvHead * GROUP" }} + g) * NUM_SPLITS + split) * HEAD_DIM_V4 + e % HEAD_DIM_V4] = sum; }{% endif %} if (tid < GROUP) { partial_stats[({{ "headBase" if BHSD else "kvHead * GROUP" }} + tid) * NUM_SPLITS + split] = vec2<f32>(m_sh[tid], l_sh[tid]); }}12345678910111213141516177 unmodified lines2526272829303132333435363717 unmodified lines5556575859606162636465666768697071727374757677787980818283848586872 unmodified lines90919293949596979899100101102103{% set qHiddenV4 = qHiddenV4 | default(0) %}{% set qHidden = qHidden | default(0) %}{% set hasBias = hasBias is defined and hasBias %}{{ env.wgsl.resourceDeclarations }}// Split-K flash decode, pass 2 of 2. Combines the per-split un-normalized online// states (max, denom, weighted V sum) written by the split pass into the final// attention output for each query token, using the online softmax merge:// globalMax = max_s partialMax[s]// globalDen = sum_s partialDenom[s] * exp(partialMax[s] - globalMax)// out[d] = (sum_s partialOut[s, d] * exp(partialMax[s] - globalMax)) / globalDen// One workgroup per (batch, head); one thread per output vec4 channel. The// per-split (max, denom) scan is tiny (NUM_SPLITS is small), so every thread// recomputes it locally and keeps the merge state in registers.{% if layout == "bhsd" %}// Output layout: rank-4 [batch, heads, seq, headDim], matching the split pass.{% elif layout == "layer_cache" %}7 unmodified lines{% if layout == "bsh" %}const Q_HIDDEN_V4: u32 = {{ qHiddenV4 }}u;{% endif %}{% if hasBias %}// Packed [Q; K; V] bias rows. The V bias is token-independent, so the split// pass leaves it off and it is added here once after the final normalize,// matching the non-split flash-decode semantics exactly.const HEAD_DIM: u32 = {{ headDim }}u;const Q_HIDDEN: u32 = {{ qHidden }}u;{% endif %}// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret17 unmodified linesfn exp_shift(value: f32, maxValue: f32) -> f32 {return exp(shifted_value(value, maxValue));}@compute @workgroup_size(HEAD_DIM_V4, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>) {let h = wg.y;let b = wg.z;let d4 = lid.x;if (h >= Q_HEADS || d4 >= HEAD_DIM_V4) {return;}let mdBase = (b * Q_HEADS + h) * NUM_SPLITS;var globalMax = -FLT_MAX;for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {globalMax = max(globalMax, partial_stats[mdBase + s].x);}var globalDenom = 0.0;var outV = vec4<f32>(0.0);for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {let stats = partial_stats[mdBase + s];let w = exp_shift(stats.x, globalMax);globalDenom = globalDenom + stats.y * w;let pBase = ((b * Q_HEADS + h) * NUM_SPLITS + s) * HEAD_DIM_V4;outV = outV + partial_out[pBase + d4] * w;}{% if layout == "bsh" %}let qBaseV4 = b * Q_HIDDEN_V4 + h * HEAD_DIM_V4;{% elif layout == "layer_cache" %}2 unmodified lineslet qBaseV4 = (b * Q_HEADS + h) * HEAD_DIM_V4;{% endif %}// A split that covers no keys writes vec2(-FLT_MAX, 0), so when every split is empty —// a query whose window admits nothing — globalMax stays -FLT_MAX, exp_shift(x, x) is 1,// and globalDenom lands on exactly 0. Emit 0 rather than dividing so an all-empty// row has a defined zero result.var outValue = select(vec4<f32>(0.0), outV / globalDenom, globalDenom > 0.0);{% if hasBias %}// V bias row base: 2 * qHidden (skip the packed Q and K bias blocks) + this head.let vBiasBase = 2u * Q_HIDDEN + h * HEAD_DIM + d4 * 4u;outValue = outValue + vec4<f32>(bias[vBiasBase], bias[vBiasBase + 1u], bias[vBiasBase + 2u], bias[vBiasBase + 3u]);{% endif %}output[qBaseV4 + d4] = vec4<{{ scalar }}>(outValue);}1234567891011121314151617181920212223242526277 unmodified lines35363738394017 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326332 unmodified lines636637638639640641642643644{% set appendScratchBaseV4 = appendScratchBaseV4 | default(0) %}{% set appendStateBaseV4 = appendStateBaseV4 | default(0) %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, max({{ queryFloor }}, {{ attn_seqlens_count(index) }})){% endmacro %}{% set qHiddenV4 = qHiddenV4 | default(0) %}{% set NORMALIZED_VALUES = normalizedPartialValues | default(false) %}{{ env.wgsl.resourceDeclarations }}{% if NORMALIZED_VALUES %}// Combines normalized partial means using their softmax statistical weights.// Raw weighted products retain scaled exponents until the final division.{% else %}// Split-K flash decode, pass 2 of 2. Combines the per-split un-normalized online// states (max, denom, weighted V sum) written by the split pass into the final// attention output for each query token, using the online softmax merge:// globalMax = max_s partialMax[s]// globalDen = sum_s partialDenom[s] * exp(partialMax[s] - globalMax)// out[d] = (sum_s partialOut[s, d] * exp(partialMax[s] - globalMax)) / globalDen{% endif %}// One workgroup per (batch, head), or per (batch, query token, head) when queries are split; one thread per// output vec4 channel (per channel and split group when the splits are divided into groups). Each// split's (max, denom) is read into workgroup memory once and its scale onto// the global max computed once; every thread then sums the denominator in// split order and keeps the merge state in registers.{% if layout == "bhsd" %}// Output layout: rank-4 [batch, heads, seq, headDim], matching the split pass.{% elif layout == "layer_cache" %}7 unmodified lines{% if layout == "bsh" %}const Q_HIDDEN_V4: u32 = {{ qHiddenV4 }}u;{% endif %}// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret17 unmodified linesfn exp_shift(value: f32, maxValue: f32) -> f32 {return exp(shifted_value(value, maxValue));}{% if NORMALIZED_VALUES %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&{% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &{% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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 }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("vec4<f32>", rescale=fusedNormAppend | default(false)) }}{% set MERGE_GROUPS = max(1, min(4, numSplits, (256 / headDimV4) | int)) %}{% set GROUP_SPLITS = ((numSplits + MERGE_GROUPS - 1) / MERGE_GROUPS) | int %}{% if MERGE_GROUPS > 1 %}// Joins a run's fold onto the folds before it: the same compensated sum of// two word pairs, finite at exponent zero, with the run's high word normal.fn join_runs(acc: ScaledValue, run: ScaledValue) -> ScaledValueStep {let sum = fma(acc.hi, vec4<f32>(1.0), run.hi);let bv = fma(vec4<f32>(-1.0), acc.hi, sum);let av = fma(vec4<f32>(-1.0), bv, sum);let ae = fma(vec4<f32>(-1.0), av, acc.hi);let be = fma(vec4<f32>(-1.0), bv, run.hi);let residual = fma(fma(fma(ae, vec4<f32>(1.0), be), vec4<f32>(1.0), acc.lo), vec4<f32>(1.0), run.lo);let hi = fma(sum, vec4<f32>(1.0), residual);let lo = fma(vec4<f32>(-1.0), fma(vec4<f32>(-1.0), sum, hi), residual);let empty = all(run.hi == vec4<f32>(0.0)) && all(run.lo == vec4<f32>(0.0));let fast = (abs(run.hi) >= vec4<f32>(1.1754943508222875e-38)) & (abs(lo) <= vec4<f32>(FLT_MAX));return ScaledValueStep(ScaledValue(select(hi, acc.hi, empty), select(lo, acc.lo, empty), acc.exponent), fast | vec4<bool>(empty));}var<workgroup> run_hi: array<vec4<f32>, HEAD_DIM_V4 * {{ MERGE_GROUPS - 1 }}u>;var<workgroup> run_lo: array<vec4<f32>, HEAD_DIM_V4 * {{ MERGE_GROUPS - 1 }}u>;var<workgroup> run_exact: array<u32, HEAD_DIM_V4 * {{ MERGE_GROUPS - 1 }}u>;{% endif %}{% else %}{% set MERGE_GROUPS = 1 %}{% endif %}// Every split's statistics, read once for the workgroup, and its scale onto// the global max, computed once.var<workgroup> split_max: array<f32, NUM_SPLITS>;var<workgroup> split_denom: array<f32, NUM_SPLITS>;var<workgroup> split_scale: array<f32, NUM_SPLITS>;const MERGE_THREADS: u32 = HEAD_DIM_V4{% if MERGE_GROUPS > 1 %} * {{ MERGE_GROUPS }}u{% endif %};// A split's partial row: its output vec4s, then its statistics when inline.const PARTIAL_STRIDE: u32 = HEAD_DIM_V4{% if inlinePartialStats is defined and inlinePartialStats %} + 1u{% endif %};{% if fusedNormAppend | default(false) %}fn load_completed_partial4(mdBase: u32, s: u32, d4: u32, appendSplit: u32,rawBase: u32, oldScale: f32, newScale: f32, localDenom: f32) -> vec4<f32> {let hi = partial_out[(mdBase + s) * PARTIAL_STRIDE + d4];if (s != appendSplit) { return hi; }let stateBase = {{ appendStateBaseV4 }}u + (mdBase / NUM_SPLITS) * 2u * HEAD_DIM_V4;let lo = partial_out[stateBase + d4];let exponent = vec4<i32>(partial_out[stateBase + HEAD_DIM_V4 + d4]);let prior = scaled_value_rescale(ScaledValue(hi, lo, exponent), oldScale);let completed = scaled_value_add(prior, newScale, new_value[rawBase + d4]);return scaled_value_mean(completed, localDenom);}{% endif %}@compute @workgroup_size(MERGE_THREADS, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>) {let h = wg.y;let b = wg.z;{% if MERGE_GROUPS > 1 %}let d4 = lid.x % HEAD_DIM_V4;let group = lid.x / HEAD_DIM_V4;{% else %}let d4 = lid.x;{% endif %}// The workgroup is HEAD_DIM_V4 lanes per group exactly, so the exit stays// uniform ahead of the barriers below.if (h >= Q_HEADS) {return;}let mdBase = (b * Q_HEADS + h) * NUM_SPLITS;{% if fusedNormAppend | default(false) %}let live = {{ attn_seqlens_bound("params.kvSeq", "b", "1u") }};let appendPos = live - 1u;let appendSplit = appendPos / max((live + NUM_SPLITS - 1u) / NUM_SPLITS, 8u);let appended = partial_out[(mdBase + appendSplit) * PARTIAL_STRIDE + HEAD_DIM_V4];let localMax = max(appended.x, appended.z);let oldScale = exp_shift(appended.x, localMax);let newScale = exp_shift(appended.z, localMax);let localDenom = appended.y * oldScale + newScale;let kvHead = h / (Q_HEADS / {{ kvNumHeads }}u);let rawBase = (b * {{ kvNumHeads }}u + kvHead) * HEAD_DIM_V4;{% endif %}for (var s = lid.x; s < NUM_SPLITS; s = s + MERGE_THREADS) {{% if inlinePartialStats is defined and inlinePartialStats %}let stats = partial_out[(mdBase + s) * PARTIAL_STRIDE + HEAD_DIM_V4].xy;{% else %}let stats = partial_stats[mdBase + s];{% endif %}split_max[s] = {% if fusedNormAppend | default(false) %}select(stats.x, localMax, s == appendSplit){% else %}stats.x{% endif %};split_denom[s] = {% if fusedNormAppend | default(false) %}select(stats.y, localDenom, s == appendSplit){% else %}stats.y{% endif %};}workgroupBarrier();var globalMax = -FLT_MAX;for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {globalMax = max(globalMax, split_max[s]);}for (var s = lid.x; s < NUM_SPLITS; s = s + MERGE_THREADS) {split_scale[s] = exp_shift(split_max[s], globalMax);}workgroupBarrier();var globalDenom = 0.0;{% if not NORMALIZED_VALUES %}var outV = vec4<f32>(0.0);{% endif %}for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {let w = split_scale[s];globalDenom = globalDenom + split_denom[s] * w;{% if not NORMALIZED_VALUES %}outV = outV + partial_out[(mdBase + s) * PARTIAL_STRIDE + d4] * w;{% endif %}}{% if NORMALIZED_VALUES %}// These partials are means. Accumulate their raw statistical weights// without materializing an overflowing product or a tiny probability. Each// run folds only steps whose result is scaled_value_add's, and the runs join// as compensated sums; a row with any other step folds again, in order, with// scaled_value_add itself.var mean = scaled_value_zero();var exact = vec4<bool>(true);for (var k: u32 = 0u; k < {{ GROUP_SPLITS }}u; k = k + 1u) {let s = {% if MERGE_GROUPS > 1 %}group * {{ GROUP_SPLITS }}u + {% endif %}k;{% if numSplits % MERGE_GROUPS != 0 %} if (s < NUM_SPLITS) {{% else %} {{% endif %}let weight = split_denom[s] * split_scale[s];let value = {% if fusedNormAppend | default(false) %}load_completed_partial4(mdBase, s, d4, appendSplit, rawBase, oldScale, newScale, localDenom){% else %}partial_out[(mdBase + s) * PARTIAL_STRIDE + d4]{% endif %};// A zero weight on a finite value is the step that returns its// accumulator. The weight is the workgroup's, so its lanes skip together.if (weight == 0.0) {exact = exact & vec4<bool>(all(abs(value) <= vec4<f32>(FLT_MAX)));} else {let step = scaled_value_add_step(mean, weight, value);exact = exact & step.exact;mean = step.value;}}}{% if MERGE_GROUPS > 1 %}if (group > 0u) {let slot = (group - 1u) * HEAD_DIM_V4 + d4;run_hi[slot] = mean.hi;run_lo[slot] = mean.lo;run_exact[slot] = select(0u, 1u, all(exact));}workgroupBarrier();if (group > 0u) {return;}for (var g: u32 = 1u; g < {{ MERGE_GROUPS }}u; g = g + 1u) {let slot = (g - 1u) * HEAD_DIM_V4 + d4;let joined = join_runs(mean, ScaledValue(run_hi[slot], run_lo[slot], vec4<i32>(0)));exact = exact & joined.exact & vec4<bool>(run_exact[slot] != 0u);mean = joined.value;}{% endif %}if (!all(exact)) {mean = scaled_value_zero();for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {mean = scaled_value_add(mean, split_denom[s] * split_scale[s],{% if fusedNormAppend | default(false) %}load_completed_partial4(mdBase, s, d4, appendSplit, rawBase, oldScale, newScale, localDenom){% else %}partial_out[(mdBase + s) * PARTIAL_STRIDE + d4]{% endif %});}}{% endif %}{% if fusedNormAppend | default(false) %}if (h % (Q_HEADS / {{ kvNumHeads }}u) == 0u) {let appendBase = {{ appendScratchBaseV4 }}u + rawBase;let dst = ((b * {{ kvNumHeads }}u + kvHead) * params.kvSeq + appendPos) * HEAD_DIM_V4 + d4;key[dst] = partial_out[appendBase + d4];value[dst] = new_value[rawBase + d4];}{% endif %}{% if layout == "bsh" %}let qBaseV4 = b * Q_HIDDEN_V4 + h * HEAD_DIM_V4;{% elif layout == "layer_cache" %}2 unmodified lineslet qBaseV4 = (b * Q_HEADS + h) * HEAD_DIM_V4;{% endif %}// A split that covers no keys writes vec2(-FLT_MAX, 0), so when every split is empty —// a query whose window contains no keys — globalMax stays -FLT_MAX, exp_shift(x, x) is 1,// and globalDenom lands on exactly 0. Emit 0 rather than dividing so an all-empty// row has a defined zero result.var outValue = select(vec4<f32>(0.0), {% if NORMALIZED_VALUES %}scaled_value_mean(mean, globalDenom){% else %}outV / globalDenom{% endif %}, globalDenom > 0.0);output[qBaseV4 + d4] = vec4<{{ scalar }}>(outValue);}
1234567891011121314151617184 unmodified lines232425262728293031323 unmodified lines363738394041428 unmodified lines51525354555621 unmodified lines78798081828384858622 unmodified lines10911011111211311411511611711811912012112212312412512612793 unmodified lines2212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582 unmodified lines2612622632642652662672 unmodified lines27027127227327427527613 unmodified lines2902912922932942952962972982993003013023031 unmodified line30530630730830931031131231331431531631731831932032110 unmodified lines3323333343353363375 unmodified lines3433443453463473483499 unmodified lines3593603613623633643653663672 unmodified lines3703713723733743753763773783793803813823833849 unmodified lines3943953963973983996 unmodified lines40640740840941041141241341441511 unmodified lines427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456{% if useSubgroups is not defined %}{% set useSubgroups = true %}{% endif %}{% if quantizedCache is not defined %}{% set quantizedCache = false %}{% endif %}{% if cacheSeqlens is not defined %}{% set cacheSeqlens = false %}{% endif %}{% if hasMask is not defined %}{% set hasMask = false %}{% endif %}{% set cacheSeqlensIndex = "b" %}{% set layer = 0 %}{% set cacheLen = 0 %}{% set scale = "0.0" %}{% if hasRotary is not defined %}{% set hasRotary = false %}{% endif %}{% set qHiddenV4 = qHiddenV4 | default(0) %}{% set kvHiddenV4 = kvHiddenV4 | default(0) %}{% set hasBias = hasBias is defined and hasBias %}{% set splitKWorkgroupSize = workgroupSizeSpec if workgroupSizeSpec is defined else tunables.WORKGROUP_SIZE %}{% if useSubgroups %}enable subgroups;{% endif %}{{ env.wgsl.resourceDeclarations }}// Split-K flash attention. Single-partition direct output skips the merge pass.4 unmodified lines// sweeping the whole KV sequence serially in WG-key tiles. This pass splits the// KV sequence into `NUM_SPLITS` contiguous ranges and gives each range its own// workgroup, so `batch * numHeads * NUM_SPLITS` workgroups run the tiled online// softmax in parallel. Each workgroup emits the *un-normalized* online state for// its range — the running (max, denom) and the softmax-weighted V sum before the// final divide — and the merge pass combines the per-split states with the online// rule.{% if layout == "bhsd" %}// Layout: rank-4 [batch, heads, seq, headDim] for Q/K/V.{% elif layout == "layer_cache" %}3 unmodified lines// Layout: token-major [batch, seq, heads * headDim]; Q and KV hidden strides// are compiled constants.{% endif %}{% if (fusedQNormRope is defined and fusedQNormRope) or layout != "layer_cache" %}const HEAD_DIM: u32 = {{ headDim }}u;{% endif %}const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;const Q_HEADS: u32 = {{ qNumHeads }}u;8 unmodified lines{% endif %}const WG: u32 = {{ splitKWorkgroupSize }}u;const NUM_SPLITS: u32 = {{ numSplits }}u;// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret21 unmodified linesvar<workgroup> q_shared: array<vec4<f32>, HEAD_DIM_V4>;var<workgroup> running_out: array<vec4<f32>, HEAD_DIM_V4>;var<workgroup> probs: array<f32, WG>;{% set coopQk = useSubgroups and headDimV4 >= 8 and not (usesF16 and headDimV4 <= 32) and (allowCooperativeQk if allowCooperativeQk is defined else true) %}{% set jGroups = (splitKWorkgroupSize / headDimV4)|int %}{% set jSplitV = (splitKWorkgroupSize % headDimV4 == 0) and (jGroups >= 2) %}{% if coopQk %}var<workgroup> sval_sh: array<f32, WG>;{% endif %}22 unmodified linesvar<workgroup> leaderMask: array<atomic<u32>, (WG + 31u) / 32u>;var<workgroup> combinedMD: vec2<f32>;// When the whole workgroup is one subgroup the subgroup reduce already covers// it (no barriers, no shared state). `subgroup_size` is the size of the current// subgroup and uniform, so the test is exact and may guard the barriers below.fn combine_partials(m: f32, d: f32, lidx: u32, sgSize: u32) -> vec2<f32> {let sgM = subgroupMax(m);// A lane with no elements contributes d == 0 (exact identity). A +inf// element made exp(inf - inf) = NaN stick in that lane's d; a NaN element// landed in d via exp(NaN); both survive the merge and are detected by the// code after the reduction.let sgD = subgroupAdd(d * exp_shift(m, sgM));if (sgSize == WG) {return vec2<f32>(sgM, sgD);}if (subgroupElect()) {partialM[lidx] = sgM;partialD[lidx] = sgD;93 unmodified lines}{% endif %}{% if hasBias %}// Packed [Q; K; V] bias rows (token-independent). The Q bias folds into the// query row before the Q.K dots; the K bias adds a constant to every key score// that softmax cancels, so it is skipped; the V bias is token-independent and// is applied once in the merge pass after the final normalize.{% set BW = "" %}{% set BC = "" %}fn load_bias4(base: u32, d4: u32) -> vec4<f32> {let offset = base + d4 * 4u;return vec4<f32>({{ BW }}bias[offset]{{ BC }}, {{ BW }}bias[offset + 1u]{{ BC }}, {{ BW }}bias[offset + 2u]{{ BC }}, {{ BW }}bias[offset + 3u]{{ BC }});}{% endif %}@compute @workgroup_size(WG, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>{% if useSubgroups %},@builtin(subgroup_size) sgSize: u32{% endif %}) {{% if useSubgroups %}// Subgroup tiles partition the fixed workgroup exactly. The advertised range// is validated before dispatch; retain this uniform guard for implementations that// choose an intermediate width at pipeline execution time.if (sgSize == 0u || sgSize > WG || WG % sgSize != 0u) { return; }{% endif %}let split = wg.x;let h = wg.y;let b = wg.z;if (h >= Q_HEADS || split >= NUM_SPLITS{% if layout == "layer_cache" %} || params.past_len >= CACHE_LEN{% endif %}) {return;}let tid = lid.x;let hKv = h / (Q_HEADS / KV_HEADS);{% if layout == "layer_cache" %}let kvSeq = params.past_len + 1u;2 unmodified lines{% if cacheSeqlens %}// Buffer-sharing caches retain their capacity in the physical BNSH stride;// seqlens_k supplies the active end independently for each batch.let kvSeq = min(cacheSeq, u32(seqlens_k[{{ cacheSeqlensIndex }}]) + 1u);{% else %}let kvSeq = cacheSeq;{% endif %}2 unmodified lines// Query row (decode uses token zero; short-query prefill folds the token into wg.x).{% if layout == "bsh" %}let qBaseV4 = b * Q_HIDDEN_V4 + h * HEAD_DIM_V4;let kvBaseV4 = b * kvSeq * KV_HIDDEN_V4 + hKv * HEAD_DIM_V4;let kvTokenStrideV4 = KV_HIDDEN_V4;{% elif layout == "layer_cache" %}let qBaseV4 = h * HEAD_DIM_V4;13 unmodified lines// kvSeq-1): it attends only the last `windowSize` keys, so split the// contiguous [windowStart, kvSeq) range instead of the whole cache.var windowStart: u32 = 0u;if (kvSeq > params.windowSize) {windowStart = kvSeq - params.windowSize;}let activeKeys = kvSeq - windowStart;let keysPerSplit = (activeKeys + NUM_SPLITS - 1u) / NUM_SPLITS;let splitStart = windowStart + split * keysPerSplit;{% else %}let keysPerSplit = (kvSeq + NUM_SPLITS - 1u) / NUM_SPLITS;let splitStart = split * keysPerSplit;{% endif %}var splitEnd = splitStart + keysPerSplit;1 unmodified linesplitEnd = kvSeq;}{% set hasBias = hasBias is defined and hasBias %}for (var d4 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {var qv = vec4<f32>(query[qBaseV4 + d4]);{% if hasBias %}qv = qv + load_bias4(h * HEAD_DIM, d4);{% endif %}q_shared[d4] = qv;running_out[d4] = vec4<f32>(0.0);}workgroupBarrier();let scale = scale_value();var runningMax = -FLT_MAX;var runningDenom = 0.0;10 unmodified linesvar m = -FLT_MAX;var dPart = 0.0;{% if coopQk %}// Cooperative Q.K: one subgroup per key, lanes splitting HEAD_DIM_V4, then a hardware// subgroupAdd — turns the per-thread HEAD_DIM_V4-long dependent dot chain into a few// strided vec4 dots + one reduce. Uniform trip count keeps subgroupAdd in uniform flow.5 unmodified lineslet j = rr * sgPerWg + sgInWg;var accS: f32 = 0.0;if (j < tileCount) {let kRowV4 = kvBaseV4 + (kjBase + j) * kvTokenStrideV4;for (var d4: u32 = lane; d4 < HEAD_DIM_V4; d4 = d4 + sgSize) {accS = accS + dot(q_shared[d4], load_key4(kRowV4 + d4{% if quantizedCache %}, d4, hKv{% endif %}));}9 unmodified linesm = score;dPart = 1.0;}{% else %}if (keyAllowed) {let kRowV4 = kvBaseV4 + kj * kvTokenStrideV4;var acc: f32 = 0.0;for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {acc = acc + dot(q_shared[d4], load_key4(kRowV4 + d4{% if quantizedCache %}, d4, hKv{% endif %}));2 unmodified linesm = score;dPart = 1.0;}{% endif %}{% if hasMask %}if (keyAllowed) {let maskQuery = 0u;let maskIndex = b * params.maskBatchStride + h * params.maskHeadStride + maskQuery * params.maskSeqStride + kj;score = score + f32(attn_mask[maskIndex]);m = score;}{% endif %} let tile = combine_partials(m, dPart, tid{% if useSubgroups %}, sgSize{% endif %});// Merge one key tile's online-softmax (maximum, denominator) partial into the// running state, then store the per-key probabilities consumed by V accumulation.9 unmodified linesprobs[tid] = prob;workgroupBarrier();{% if jSplitV %}// j-split V accumulation: thread (jg, d4v) sums keys j == jg mod// J_GROUPS for dim block d4v into a register, then the groups combine6 unmodified linesloop {if (jj >= tileCount) { break; }vacc = vacc + probs[jj] * load_value4(kvBaseV4 + (kjBase + jj) * kvTokenStrideV4 + d4v{% if quantizedCache %},d4v,hKv{% endif %});jj = jj + J_GROUPS;}vacc_sh[tid] = vacc;11 unmodified linesvar vSum = vec4<f32>(0.0);for (var i: u32 = 0u; i < tileCount; i = i + 1u) {vSum = vSum + probs[i] * load_value4(kvBaseV4 + (kjBase + i) * kvTokenStrideV4 + d4{% if quantizedCache %},d4,hKv{% endif %});}running_out[d4] = running_out[d4] * correction + vSum;}workgroupBarrier();{% endif %}kjBase = kjBase + WG;}// Emit un-normalized partials for (b, h, split): the merge pass divides.let partialBase = ((b * Q_HEADS + h) * NUM_SPLITS + split) * HEAD_DIM_V4;for (var d4: u32 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {partial_out[partialBase + d4] = running_out[d4];}if (tid == 0u) {let mdBase = (b * Q_HEADS + h) * NUM_SPLITS + split;// (max, denom) travel together to the merge, so they share one buffer as an// interleaved vec2 rather than costing two bindings. Interleaved, not two// halves, so the index needs no region size — and the merge reads both// fields of a split in a single load.partial_stats[mdBase] = vec2<f32>(runningMax, runningDenom);}}123456789101112131415161718192021222324252627282930313233343536374 unmodified lines4243444546474849505152535455563 unmodified lines606162636465668 unmodified lines757677787980818283848521 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751822 unmodified lines54154254354454554654754854955055155255393 unmodified lines6476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936942 unmodified lines6976986997007017027032 unmodified lines70670770870971071171213 unmodified lines7267277287297307317327337347357367377387397407417427437441 unmodified line74674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591610 unmodified lines9279289299309319329335 unmodified lines9399409419429439449459 unmodified lines9559569579589599609619629632 unmodified lines9669679689699709719729739749759769779789799809819829839849859 unmodified lines995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310346 unmodified lines104110421043104410451046104711 unmodified lines1059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110{% set appendScratchBaseV4 = appendScratchBaseV4 | default(0) %}{% set appendStateBaseV4 = appendStateBaseV4 | default(0) %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {% if queryFloor %}max({{ queryFloor }}, {{ attn_seqlens_count(index) }}){% else %}{{ attn_seqlens_count(index) }}{% endif %}){% endmacro %}{% macro elect_publish(slot, identity, value) -%}{% if env.device.adapterInfo.vendor == "qualcomm" %}{{ slot }} = {{ identity }};workgroupBarrier();if (subgroupElect()) { {{ slot }} = {{ value }}; }{%- else %}{{ slot }} = select({{ identity }}, {{ value }}, subgroupElect());{%- endif %}{%- endmacro %}{% set WINDOW_SIZE = "params.windowSize" %}{% set kvRing = false %}{% set RING_MASK = "" %}{% if useSubgroups is not defined %}{% set useSubgroups = true %}{% endif %}{% if quantizedCache is not defined %}{% set quantizedCache = false %}{% endif %}{% if cacheSeqlens is not defined %}{% set cacheSeqlens = false %}{% endif %}{% set cacheSeqlensIndex = "b" %}{% set layer = 0 %}{% set cacheLen = 0 %}{% set scale = "0.0" %}{% if hasRotary is not defined %}{% set hasRotary = false %}{% endif %}{% set qkEps = qkEps | default("0.0") %}{% set fusedKvAppend = false %}{% set qHiddenV4 = qHiddenV4 | default(0) %}{% set kvHiddenV4 = kvHiddenV4 | default(0) %}{% set splitKWorkgroupSize = workgroupSizeSpec if workgroupSizeSpec is defined else tunables.WORKGROUP_SIZE %}{% if useSubgroups %}enable subgroups;{% endif %}{% set NORMALIZED_VALUES = normalizedPartialValues | default(false) %}{% set componentFold = false %}{% set foldType = "vec4<f32>" %}{{ env.wgsl.resourceDeclarations }}// Split-K flash attention. Single-partition direct output skips the merge pass.4 unmodified lines// sweeping the whole KV sequence serially in WG-key tiles. This pass splits the// KV sequence into `NUM_SPLITS` contiguous ranges and gives each range its own// workgroup, so `batch * numHeads * NUM_SPLITS` workgroups run the tiled online// softmax in parallel.{% if NORMALIZED_VALUES %}// Each workgroup emits the normalized partial mean for its range together with its softmax statistics (max,// denom); the merge pass weights the means by those statistics.{% else %}// Each workgroup emits the *un-normalized* online state for its range — the running (max, denom) and the// softmax-weighted V sum before the final divide — and the merge pass combines the per-split states with the// online rule.{% endif %}{% if layout == "bhsd" %}// Layout: rank-4 [batch, heads, seq, headDim] for Q/K/V.{% elif layout == "layer_cache" %}3 unmodified lines// Layout: token-major [batch, seq, heads * headDim]; Q and KV hidden strides// are compiled constants.{% endif %}{% if (fusedQNormRope is defined and fusedQNormRope) or fusedKvAppend or layout != "layer_cache" %}const HEAD_DIM: u32 = {{ headDim }}u;{% endif %}const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;const Q_HEADS: u32 = {{ qNumHeads }}u;8 unmodified lines{% endif %}const WG: u32 = {{ splitKWorkgroupSize }}u;const NUM_SPLITS: u32 = {{ numSplits }}u;{% if fusedQNormRope is defined and fusedQNormRope %}{% if hasRotary and headDim % 8 != 0 %}const HALF_DIM: u32 = HEAD_DIM / 2u;{% endif %}{% if hasRotary and headDim % 8 == 0 %}const HALF_DIM_V4: u32 = HEAD_DIM_V4 / 2u;{% endif %}const QK_EPS: f32 = {{ qkEps }};{% endif %}// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret21 unmodified linesvar<workgroup> q_shared: array<vec4<f32>, HEAD_DIM_V4>;var<workgroup> running_out: array<vec4<f32>, HEAD_DIM_V4>;var<workgroup> probs: array<f32, WG>;{% if fusedQNormRope is defined and fusedQNormRope %}var<workgroup> fused_q_inv: f32;{% if useSubgroups %}var<workgroup> fused_q_partials: array<f32, WG>;{% else %}var<workgroup> fused_q_partials: array<f32, 32>;{% endif %}{% endif %}{% set coopQk = useSubgroups and headDimV4 >= 8 and not (usesF16 and headDimV4 <= 32) and (allowCooperativeQk if allowCooperativeQk is defined else true) %}{% set jGroups = (splitKWorkgroupSize / headDimV4)|int %}{% set jSplitV = (splitKWorkgroupSize % headDimV4 == 0) and (jGroups >= 2) and not NORMALIZED_VALUES %}{% if NORMALIZED_VALUES %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&{% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &{% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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 }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{{ scaled_value_functions(foldType, rescale=true, lean=true, magnitudeOrdered=componentFold) }}{% endif %}{% if coopQk %}var<workgroup> sval_sh: array<f32, WG>;{% endif %}22 unmodified linesvar<workgroup> leaderMask: array<atomic<u32>, (WG + 31u) / 32u>;var<workgroup> combinedMD: vec2<f32>;fn combine_partials(m: f32, d: f32, lidx: u32) -> vec2<f32> {let sgM = subgroupMax(m);// A lane with no elements contributes d == 0 (exact identity). A +inf// element made exp(inf - inf) = NaN stick in that lane's d; a NaN element// landed in d via exp(NaN); both survive the merge and are detected by the// code after the reduction.let sgD = subgroupAdd(d * exp_shift(m, sgM));if (subgroupElect()) {partialM[lidx] = sgM;partialD[lidx] = sgD;93 unmodified lines}{% endif %}@compute @workgroup_size(WG, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>{% if coopQk %},@builtin(subgroup_size) sgSize: u32,@builtin(subgroup_invocation_id) sgLane: u32{% endif %}) {let split = wg.x;let h = wg.y;let b = wg.z;if (h >= Q_HEADS || split >= NUM_SPLITS{% if layout == "layer_cache" and not kvRing %} || params.past_len >= CACHE_LEN{% endif %}) {return;}let tid = lid.x;{% if NORMALIZED_VALUES %}var value_error: array<vec4<f32>, {{ ceilDiv(headDimV4, splitKWorkgroupSize) }}>;var value_exponent: array<vec4<i32>, {{ ceilDiv(headDimV4, splitKWorkgroupSize) }}>;{% endif %}{% if coopQk %}// The fast Q.K body indexes keys by local subgroup blocks. Prove that every// actual subgroup is full and owns exactly one such block before using it.// Width alone does not prove membership. The online-softmax state is dead// during this one-time check, so its mask and result carry the decision.let physicalWidth = max(sgSize, 1u);let population = subgroupBallot(true);let populationCount = countOneBits(population.x) + countOneBits(population.y)+ countOneBits(population.z) + countOneBits(population.w);let firstLocalIndex = subgroupBroadcastFirst(tid);// Some drivers (Adreno 6xx) cannot create a pipeline that calls subgroupAll; a ballot builds wherever subgroups do.// Every active member agrees when none disagrees: subgroupAll, expressed as a ballot.let ownsLocalBlock = all(subgroupBallot(!(sgSize > 0u && populationCount == sgSize&& WG % physicalWidth == 0u && tid / physicalWidth == firstLocalIndex / physicalWidth&& sgLane == tid % physicalWidth)) == vec4<u32>(0u));if (subgroupElect() && !ownsLocalBlock) {atomicStore(&leaderMask[0], 1u);}workgroupBarrier();if (tid == 0u) {combinedMD = vec2<f32>(f32(atomicExchange(&leaderMask[0], 0u)), 0.0);}let coopQkAccepted = workgroupUniformLoad(&combinedMD).x == 0.0;{% endif %}let hKv = h / (Q_HEADS / KV_HEADS);{% if layout == "layer_cache" %}let kvSeq = params.past_len + 1u;2 unmodified lines{% if cacheSeqlens %}// Buffer-sharing caches retain their capacity in the physical BNSH stride;// seqlens_k supplies the active end independently for each batch.let kvSeq = {{ attn_seqlens_bound("cacheSeq", cacheSeqlensIndex, "1u" if seqlensQueryFloor | default(false) else "") }};{% else %}let kvSeq = cacheSeq;{% endif %}2 unmodified lines// Query row (decode uses token zero; short-query prefill folds the token into wg.x).{% if layout == "bsh" %}let qBaseV4 = b * Q_HIDDEN_V4 + h * HEAD_DIM_V4;let kvBaseV4 = b * cacheSeq * KV_HIDDEN_V4 + hKv * HEAD_DIM_V4;let kvTokenStrideV4 = KV_HIDDEN_V4;{% elif layout == "layer_cache" %}let qBaseV4 = h * HEAD_DIM_V4;13 unmodified lines// kvSeq-1): it attends only the last `windowSize` keys, so split the// contiguous [windowStart, kvSeq) range instead of the whole cache.var windowStart: u32 = 0u;if (kvSeq > {{ WINDOW_SIZE }}) {windowStart = kvSeq - {{ WINDOW_SIZE }};}let activeKeys = kvSeq - windowStart;let keysPerSplit = (activeKeys + NUM_SPLITS - 1u) / NUM_SPLITS;let splitStart = windowStart + split * keysPerSplit;{% else %}{% if minKeysPerChunk is defined %}let evenKeysPerSplit = (kvSeq + NUM_SPLITS - 1u) / NUM_SPLITS;let keysPerSplit = max(evenKeysPerSplit, {{ minKeysPerChunk }}u);{% else %}let keysPerSplit = (kvSeq + NUM_SPLITS - 1u) / NUM_SPLITS;{% endif %}let splitStart = split * keysPerSplit;{% endif %}var splitEnd = splitStart + keysPerSplit;1 unmodified linesplitEnd = kvSeq;}{% if fusedQNormRope is defined and fusedQNormRope %}// Sum squares with a fixed 32-lane reduction, then materialize// the f32 norm output before the optional half-split RoPE.var q_acc = 0.0;if (tid < 32u) {for (var d4 = tid; d4 < HEAD_DIM_V4; d4 = d4 + 32u) {let q4 = vec4<f32>(query[qBaseV4 + d4]);q_acc = q_acc + dot(q4, q4);}}{% if useSubgroups %}// Rejoin the lane-dependent Q load before the subgroup sum.workgroupBarrier();// Elected subgroup sums occupy their own local-ID slots.// Every other invocation writes zero, so arbitrary masks and populations// cannot alias slots or omit a subgroup; summing the slots in ascending// index order gives a fixed fold order.let q_sg = subgroupAdd(q_acc);{{ elect_publish("fused_q_partials[tid]", "0.0", "q_sg") }}workgroupBarrier();if (tid == 0u) {var q_total = 0.0;for (var s = 0u; s < WG; s = s + 1u) {q_total = q_total + fused_q_partials[s];}fused_q_inv = inverseSqrt(q_total / f32(HEAD_DIM) + QK_EPS);}{% else %}if (tid < 32u) {fused_q_partials[tid] = q_acc;}workgroupBarrier();var q_stride = 16u;loop {if (q_stride == 0u) { break; }if (tid < q_stride) {fused_q_partials[tid] = fused_q_partials[tid] + fused_q_partials[tid + q_stride];}workgroupBarrier();q_stride = q_stride >> 1u;}if (tid == 0u) {fused_q_inv = inverseSqrt(fused_q_partials[0] / f32(HEAD_DIM) + QK_EPS);}{% endif %}workgroupBarrier();for (var d4 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {q_shared[d4] = fma(vec4<f32>(query[qBaseV4 + d4]) * fused_q_inv * q_norm_weight[d4],vec4<f32>(1.0),vec4<f32>(0.0));running_out[d4] = vec4<f32>(0.0);}workgroupBarrier();{% if hasRotary %}{% if headDim % 8 == 0 %}// Rotate with the vectorized half-split path, giving each lane whole// vec4 stores; concurrent component writes to one workgroup vector race.for (var d4 = tid; d4 < HALF_DIM_V4; d4 = d4 + WG) {let x0 = q_shared[d4];let x1 = q_shared[d4 + HALF_DIM_V4];let d = {% if qRopeAtPosition is defined and qRopeAtPosition %}(kvSeq - 1u) * HALF_DIM_V4 * 4u + {% endif %}d4 * 4u;let c = vec4<f32>(cos_cache[d], cos_cache[d + 1u], cos_cache[d + 2u], cos_cache[d + 3u]);let s = vec4<f32>(sin_cache[d], sin_cache[d + 1u], sin_cache[d + 2u], sin_cache[d + 3u]);q_shared[d4] = x0 * c - x1 * s;q_shared[d4 + HALF_DIM_V4] = x1 * c + x0 * s;}{% else %}if (tid == 0u) {for (var d = 0u; d < HALF_DIM; d = d + 1u) {let hi_d = d + HALF_DIM;let lo_i = d / 4u;let hi_i = hi_d / 4u;let lo_lane = d & 3u;let hi_lane = hi_d & 3u;let x0 = q_shared[lo_i][lo_lane];let x1 = q_shared[hi_i][hi_lane];let c = cos_cache[d];let s = sin_cache[d];q_shared[lo_i][lo_lane] = x0 * c - x1 * s;q_shared[hi_i][hi_lane] = x1 * c + x0 * s;}}{% endif %}workgroupBarrier();{% endif %}{% else %}for (var d4 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {var qv = vec4<f32>(query[qBaseV4 + d4]);q_shared[d4] = qv;running_out[d4] = vec4<f32>(0.0);}workgroupBarrier();{% endif %}let scale = scale_value();{% if fusedNormAppend | default(false) %}// The append leaves the split boundaries unchanged. Prepare the newest key here;// the merge pass folds its value into the owning split before either cache row is published.let appendPos = max(kvSeq, 1u) - 1u;let ownsAppend = (appendPos >= splitStart && appendPos < splitEnd) || (kvSeq == 0u && split == 0u);var appendScore = -FLT_MAX;if (ownsAppend) {let rawBase = (b * KV_HEADS + hKv) * HEAD_DIM_V4;var squares = 0.0;for (var d = tid; d < HEAD_DIM; d += WG) {let x = new_key[rawBase + d / 4u][d % 4u];squares += x * x;}{% if headDim < splitKWorkgroupSize %}workgroupBarrier();{% endif %}let k_sg = subgroupAdd(squares);{{ elect_publish("probs[tid]", "0.0", "k_sg") }}workgroupBarrier();if (tid == 0u) {var total = 0.0;for (var s = 0u; s < WG; s++) { total += probs[s]; }fused_q_inv = inverseSqrt(total / f32(HEAD_DIM) + QK_EPS);}workgroupBarrier();let inv = fused_q_inv;for (var d4 = tid; d4 < HALF_DIM_V4; d4 += WG) {let x0 = new_key[rawBase + d4] * inv * k_norm_weight[d4];let x1 = new_key[rawBase + d4 + HALF_DIM_V4] * inv * k_norm_weight[d4 + HALF_DIM_V4];let d = appendPos * HALF_DIM_V4 * 4u + d4 * 4u;let c = vec4<f32>(cos_cache[d], cos_cache[d + 1u], cos_cache[d + 2u], cos_cache[d + 3u]);let s = vec4<f32>(sin_cache[d], sin_cache[d + 1u], sin_cache[d + 2u], sin_cache[d + 3u]);running_out[d4] = x0 * c - x1 * s;running_out[d4 + HALF_DIM_V4] = x1 * c + x0 * s;}workgroupBarrier();{% if coopQk %}if (coopQkAccepted) {var dotPart = 0.0;for (var d4 = sgLane; d4 < HEAD_DIM_V4; d4 += sgSize) {dotPart += dot(q_shared[d4], running_out[d4]);}appendScore = subgroupAdd(dotPart) * scale;} else {{% endif %}if (tid == 0u) {appendScore = 0.0;for (var d4 = 0u; d4 < HEAD_DIM_V4; d4++) {appendScore += dot(q_shared[d4], running_out[d4]);}appendScore *= scale;}{% if coopQk %}}{% endif %}// One query head per KV head publishes the prepared key for merge.if (h % (Q_HEADS / KV_HEADS) == 0u) {let appendBase = {{ appendScratchBaseV4 }}u + rawBase;for (var d4 = tid; d4 < HEAD_DIM_V4; d4 += WG) {partial_out[appendBase + d4] = running_out[d4];}}workgroupBarrier();for (var d4 = tid; d4 < HEAD_DIM_V4; d4 += WG) { running_out[d4] = vec4<f32>(0.0); }workgroupBarrier();}splitEnd = min(splitEnd, appendPos);{% endif %}var runningMax = -FLT_MAX;var runningDenom = 0.0;10 unmodified linesvar m = -FLT_MAX;var dPart = 0.0;{% if coopQk %}if (coopQkAccepted) {// Cooperative Q.K: one subgroup per key, lanes splitting HEAD_DIM_V4, then a hardware// subgroupAdd — turns the per-thread HEAD_DIM_V4-long dependent dot chain into a few// strided vec4 dots + one reduce. Uniform trip count keeps subgroupAdd in uniform flow.5 unmodified lineslet j = rr * sgPerWg + sgInWg;var accS: f32 = 0.0;if (j < tileCount) {let kRowV4 = kvBaseV4 + {{ ("((kjBase + j) & " ~ RING_MASK ~ ")") if kvRing else "(kjBase + j)" }} * kvTokenStrideV4;for (var d4: u32 = lane; d4 < HEAD_DIM_V4; d4 = d4 + sgSize) {accS = accS + dot(q_shared[d4], load_key4(kRowV4 + d4{% if quantizedCache %}, d4, hKv{% endif %}));}9 unmodified linesm = score;dPart = 1.0;}} else {if (keyAllowed) {let kRowV4 = kvBaseV4 + {{ ("(kj & " ~ RING_MASK ~ ")") if kvRing else "kj" }} * kvTokenStrideV4;var acc: f32 = 0.0;for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {acc = acc + dot(q_shared[d4], load_key4(kRowV4 + d4{% if quantizedCache %}, d4, hKv{% endif %}));2 unmodified linesm = score;dPart = 1.0;}}{% else %}if (keyAllowed) {let kRowV4 = kvBaseV4 + {{ ("(kj & " ~ RING_MASK ~ ")") if kvRing else "kj" }} * kvTokenStrideV4;var acc: f32 = 0.0;for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {acc = acc + dot(q_shared[d4], load_key4(kRowV4 + d4{% if quantizedCache %}, d4, hKv{% endif %}));}score = acc * scale;m = score;dPart = 1.0;}{% endif %}let tile = combine_partials(m, dPart, tid);// Merge one key tile's online-softmax (maximum, denominator) partial into the// running state, then store the per-key probabilities consumed by V accumulation.9 unmodified linesprobs[tid] = prob;workgroupBarrier();{% if NORMALIZED_VALUES %}{% macro fold_value() -%}{% set row = "kvBaseV4 + (kjBase + j) * kvTokenStrideV4" %}load_value4({{ row }} + d4{% if quantizedCache %}, d4, hKv{% endif %}){%- endmacro %}for (var d4 = tid; d4 < HEAD_DIM_V4; d4 += WG) {let start = scaled_value_rescale(ScaledValue(running_out[d4], value_error[d4 / WG], value_exponent[d4 / WG]), correction);// A lean fold (scaled_value_lean_exact); a tile that leaves it folds// again with scaled_value_add itself.var acc = start;var wLow = FLT_MAX;var vLow = {{ foldType }}(FLT_MAX);{% if boundValueNumerator | default(false) %}var largest = abs(start.hi);{% endif %}for (var j = 0u; j < tileCount; j++) {let w = probs[j];let v = {{ fold_value() }};wLow = select(wLow, min(wLow, w), w != 0.0);vLow = scaled_value_nonzero_low(vLow, v);{% if boundValueNumerator | default(false) %}largest = max(largest, abs(v));{% endif %}acc = scaled_value_lean_step(acc, w, v);}if ({% if boundValueNumerator | default(false) %}any(largest > {{ foldType }}(VALUE_FAST_LIMIT)) || {% endif %}!scaled_value_lean_exact(start, acc, wLow, vLow)) {acc = start;for (var j = 0u; j < tileCount; j++) {acc = scaled_value_add(acc, probs[j], {{ fold_value() }});}}running_out[d4] = acc.hi; value_error[d4 / WG] = acc.lo; value_exponent[d4 / WG] = acc.exponent;}workgroupBarrier();{% else %}{% if jSplitV %}// j-split V accumulation: thread (jg, d4v) sums keys j == jg mod// J_GROUPS for dim block d4v into a register, then the groups combine6 unmodified linesloop {if (jj >= tileCount) { break; }vacc = vacc + probs[jj] * load_value4(kvBaseV4 + {{ ("((kjBase + jj) & " ~ RING_MASK ~ ")") if kvRing else "(kjBase + jj)" }} * kvTokenStrideV4 + d4v );jj = jj + J_GROUPS;}vacc_sh[tid] = vacc;11 unmodified linesvar vSum = vec4<f32>(0.0);for (var i: u32 = 0u; i < tileCount; i = i + 1u) {vSum = vSum + probs[i] * load_value4(kvBaseV4 + {{ ("((kjBase + i) & " ~ RING_MASK ~ ")") if kvRing else "(kjBase + i)" }} * kvTokenStrideV4 + d4 );}running_out[d4] = running_out[d4] * correction + vSum;}workgroupBarrier();{% endif %}{% endif %}kjBase = kjBase + WG;}{% if NORMALIZED_VALUES %}// Emit normalized partial means for (b, h, split).{% else %}// Emit un-normalized partials for (b, h, split): the merge pass divides.{% endif %}{% if inlinePartialStats is defined and inlinePartialStats %}let partialBase = ((b * Q_HEADS + h) * NUM_SPLITS + split) * (HEAD_DIM_V4 + 1u);{% else %}let partialBase = ((b * Q_HEADS + h) * NUM_SPLITS + split) * HEAD_DIM_V4;{% endif %}for (var d4: u32 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {{% if fusedNormAppend | default(false) %}if (ownsAppend) {let stateBase = {{ appendStateBaseV4 }}u + (b * Q_HEADS + h) * 2u * HEAD_DIM_V4;// Keep the high and low words and the exponent until the newest V has joined this split.partial_out[partialBase + d4] = running_out[d4];partial_out[stateBase + d4] = value_error[d4 / WG];partial_out[stateBase + HEAD_DIM_V4 + d4] = vec4<f32>(value_exponent[d4 / WG]);} else {{% endif %}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 %};{% if fusedNormAppend | default(false) %}}{% endif %}}if (tid == 0u) {{% if inlinePartialStats is defined and inlinePartialStats %}partial_out[partialBase + HEAD_DIM_V4] = vec4<f32>(runningMax, runningDenom, {% if fusedNormAppend | default(false) %}appendScore{% else %}0.0{% endif %}, 0.0);{% else %}let mdBase = (b * Q_HEADS + h) * NUM_SPLITS + split;// (max, denom) travel together to the merge, so they share one buffer as an// interleaved vec2 rather than costing two bindings. Interleaved, not two// halves, so the index needs no region size — and the merge reads both// fields of a split in a single load.partial_stats[mdBase] = vec2<f32>(runningMax, runningDenom);{% endif %}}}
123455 unmodified lines11121314151617181920212223242528 unmodified lines5455565758596014 unmodified lines7576777879808182838485868788899091929325 unmodified lines11912012112212312412512612712812913013113213313413513613713813910 unmodified lines15015115215315415515615715815916016116216316416511 unmodified lines17717817918018118222 unmodified lines20520620720820921021121221321421521621721821922022122222322422522622714 unmodified lines2422432442452462472482492502512522 unmodified lines255256257258259260261262263264enable subgroups;{{ env.wgsl.resourceDeclarations }}// Flash-style tiled online-softmax attention for vec4-aligned head dimensions.// One workgroup per5 unmodified lines// per tile; the full score matrix is never materialized.// Layout: token-major [batch, seq, heads * headDim]; Q and KV hidden strides// are compiled constants.{% if hasBias %}// Packed [Q; K; V] bias rows. The K bias adds the same dot(q, biasK) to every// key score, which softmax cancels, so only the Q and V biases are applied.{% endif %}{% if hasMask %}// Per-score mask uses broadcast strides. A stride of 0 broadcasts that axis;// rank-2 [q, k] masks set batch/head strides to 0. A rejected bool-mask key// contributes no softmax mass, and a fully masked row emits zero.{% endif %}const HEAD_DIM: u32 = {{ headDim }}u;const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;const Q_HIDDEN_V4: u32 = {{ qHiddenV4 }}u;28 unmodified lines}var<workgroup> q_shared: array<vec4<f32>, HEAD_DIM_V4>;var<workgroup> running_out: array<vec4<f32>, HEAD_DIM_V4>;var<workgroup> probs: array<f32, WG>;// Workgroup-cooperative merge of per-thread online-softmax (m, d) partials:// mNew = max(m1, m2)14 unmodified linesvar<workgroup> leaderMask: array<atomic<u32>, (WG + 31u) / 32u>;var<workgroup> combinedMD: vec2<f32>;// When the whole workgroup is one subgroup the subgroup reduce already covers// it (no barriers, no shared state). `subgroup_size` is the size of the current// subgroup and uniform, so the test is exact and may guard the barriers below.fn combine_partials(m: f32, d: f32, lidx: u32, sgSize: u32) -> vec2<f32> {let sgM = subgroupMax(m);// A lane with no elements contributes d == 0 (exact identity). A +inf// element made exp(inf - inf) = NaN stick in that lane's d; a NaN element// landed in d via exp(NaN); both survive the merge and are detected by the// code after the reduction.let sgD = subgroupAdd(d * exp_shift(m, sgM));if (sgSize == WG) {return vec2<f32>(sgM, sgD);}if (subgroupElect()) {partialM[lidx] = sgM;partialD[lidx] = sgD;25 unmodified linesif (params.scale != 0.0) { return params.scale; }return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));}{% if hasBias %}{% set BW = "" %}{% set BC = "" %}fn load_bias4(base: u32, d4: u32) -> vec4<f32> {let offset = base + d4 * 4u;return vec4<f32>({{ BW }}bias[offset]{{ BC }}, {{ BW }}bias[offset + 1u]{{ BC }}, {{ BW }}bias[offset + 2u]{{ BC }}, {{ BW }}bias[offset + 3u]{{ BC }});}{% endif %}@compute @workgroup_size(WG, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>,@builtin(subgroup_size) sgSize: u32) {let qi = wg.x;let h = wg.y;let b = wg.z;10 unmodified lineslet kvTokenStrideV4 = KV_HIDDEN_V4;// Cooperative vec4 Q-row load; init the output accumulator.{% set hasBias = hasBias is defined and hasBias %}for (var d4 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {var qv = vec4<f32>(query[qBaseV4 + d4]);{% if hasBias %}qv = qv + load_bias4(h * HEAD_DIM, d4);{% endif %}q_shared[d4] = qv;running_out[d4] = vec4<f32>(0.0);}workgroupBarrier();let scale = scale_value();11 unmodified lines{% else %}var keyBoundV = params.kvSeq;{% endif %}var keyFloor: u32 = 0u;{% if hasWindow %}// Sliding window: query qi sits at absolute position p = kvSeq - qSeq22 unmodified linesvar keyAllowed = kj < keyBound{% if hasCausal %} && (params.isCausal == 0u || kj <= qi){% endif %}{% if hasWindow %} && kj >= keyFloor{% endif %};if (keyAllowed) {let kRowV4 = kvBaseV4 + kj * kvTokenStrideV4;{% if hasMask %}// Broadcast-strided mask address; a 0 stride collapses that axis (rank-2// [q, k] masks set batch/head strides to 0).let maskIndex = b * params.maskBatchStride + h * params.maskHeadStride + qi * params.maskSeqStride + kj;{% endif %}var acc: f32 = 0.0;for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {acc = acc + dot(q_shared[d4], vec4<f32>(key[kRowV4 + d4]));}score = acc * scale;{% if hasMask %}score = score + f32(attn_mask[maskIndex]);{% endif %}m = score;dPart = select(0.0, 1.0, keyAllowed);}let tile = combine_partials(m, dPart, tid, sgSize);// Online merge of the tile into the running state (softmax-online rule).// Merge one key tile's online-softmax (maximum, denominator) partial into the14 unmodified lines// tiles, so the rescale-and-accumulate below is race-free; vec4 V loads.let tileCount = min(WG, keyBound - kjBase);for (var d4: u32 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {var vSum = vec4<f32>(0.0);for (var i: u32 = 0u; i < tileCount; i = i + 1u) {vSum = vSum + probs[i] * vec4<f32>(value[kvBaseV4 + (kjBase + i) * kvTokenStrideV4 + d4]);}running_out[d4] = running_out[d4] * correction + vSum;}// Orders this tile's probs reads before the next tile's probs writes.workgroupBarrier();2 unmodified lines}// The output shares Q's layout and row base.let hasMass = runningDenom > 0.0;let invDenom = select(0.0, 1.0 / runningDenom, hasMass);for (var d4: u32 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {var outValue = running_out[d4] * invDenom;{% if hasBias %}// V bias is token-independent, so add it once after the softmax-weighted sum.outValue = outValue + load_bias4(2u * {{ qHidden }}u + h * HEAD_DIM, d4)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185 unmodified lines52452552652752852928 unmodified lines55855956056156256356456514 unmodified lines58058158258358458558658758858959059159225 unmodified lines61861962062162262362462562662762810 unmodified lines63964064164264364464564664764864965065165265365465565665765865966066111 unmodified lines67367467567667767867922 unmodified lines70270370470570670770870971071171271314 unmodified lines7287297307317327337347357367377387397407417427437447457467472 unmodified lines750751752753754755756757758759760761762763{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {% if queryFloor %}max({{ queryFloor }}, {{ attn_seqlens_count(index) }}){% else %}{{ attn_seqlens_count(index) }}{% endif %}){% endmacro %}enable subgroups;{% set normalizedValues = scalar == "f32" %}{{ env.wgsl.resourceDeclarations }}{% set COMP_SCORE = (compensatedScoreDot | default(false)) and scalar == "f32" %}{% if COMP_SCORE %}{% set dotGuardNonfinite = true %}{% set dotType = "f32" %}{% set protectDifference = false %}{% set PROTECTED_SUM = false %}{% set SELECT_NONFINITE = false %}{% set ORDERED_SUM = false %}// Retain product and addition residuals across a dot product. Explicit fma// boundaries preserve the addition error transform under reassociation.struct DotAccumulator {hi: {{ dotType }},lo: {{ dotType }},}{% if dotRecoverProductResidual | default(false) %}{% set dotBitsType = "u32" %}// Recover an inexact product when a backend returns a zero fma residual.{% set dotExponentType = "i32" %}{% macro dot_parts() -%}let aBits = bitcast<{{ dotBitsType }}>(a);let bBits = bitcast<{{ dotBitsType }}>(b);let pBits = bitcast<{{ dotBitsType }}>(product);let ae = (aBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let be = (bBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let pe = (pBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);{% endmacro %}fn dot_product_error(a: {{ dotType }}, b: {{ dotType }}, product: {{ dotType }}) -> {{ dotType }} {// Twelve-bit significand parts make each split product exactly representable.let nativeError = fma(a, b, -product);if (nativeError == 0.0) {{{ dot_parts() | indent(4, true) }}let lowProduct = (((aBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u)) *((bBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u))) & {{ dotBitsType }}(0x00ffffffu);let recover = (nativeError == {{ dotType }}(0.0)) && (lowProduct != {{ dotBitsType }}(0u)) && (ae > {{ dotBitsType }}(0u)) && (ae < {{ dotBitsType }}(255u)) && (be > {{ dotBitsType }}(0u)) && (be < {{ dotBitsType }}(255u)) && (pe > {{ dotBitsType }}(0u)) && (pe < {{ dotBitsType }}(255u));if (recover) {// Normalize before splitting: a normal input can otherwise produce a// subnormal low word that a conformant backend is allowed to flush.let an = bitcast<{{ dotType }}>((aBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u));let bn = bitcast<{{ dotType }}>((bBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u));let exponent = select({{ dotExponentType }}(0), {{ dotExponentType }}(ae) + {{ dotExponentType }}(be) - {{ dotExponentType }}(254), recover);let pnExponent = select({{ dotBitsType }}(127u), {{ dotBitsType }}({{ dotExponentType }}(pe) - exponent), recover);let pn = bitcast<{{ dotType }}>((pBits & {{ dotBitsType }}(0x807fffffu)) | (pnExponent << {{ dotBitsType }}(23u)));let ah = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(an) & {{ dotBitsType }}(0xfffff000u));let bh = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(bn) & {{ dotBitsType }}(0xfffff000u));let al = fma({{ dotType }}(-1.0), ah, an);let bl = fma({{ dotType }}(-1.0), bh, bn);let e0 = fma(ah, bh, -pn);let e1 = fma(al, bh, e0);let e2 = fma(ah, bl, e1);let recovered = ldexp(fma(al, bl, e2), exponent);return select(nativeError, recovered, recover);}}return nativeError;}{% endif %}{% macro dot_step(name, dotGuardNonfinite) %}fn {{ name }}(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator {let product = fma(a, b, {{ dotType }}(0.0));{% if dotGuardNonfinite | default(false) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);{% if not SELECT_NONFINITE %} // Nonfinite sums retain ordinary f32 addition classes; Inf-Inf residuals// must not poison a valid infinite dot accumulator.{% if ORDERED_SUM %} if (!(abs(sum) <= 3.4028234663852886e38 && abs(acc.lo) <= 3.4028234663852886e38)) {{% else %} if (!(abs(acc.hi) <= 3.4028234663852886e38) ||!(abs(acc.lo) <= 3.4028234663852886e38) ||!(abs(product) <= 3.4028234663852886e38) ||!(abs(sum) <= 3.4028234663852886e38)) {{% endif %} return DotAccumulator(sum, {{ dotType }}(0.0));}{% endif %}{% endif %} let productError = {% if dotRecoverProductResidual | default(false) %}dot_product_error(a, b, product){% else %}fma(a, b, -product){% endif %};{% if not (dotGuardNonfinite | default(false)) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);{% endif %}{% if PROTECTED_SUM %}let roundoff = dot_sum_error(acc.hi, product, sum);let error = (acc.lo + roundoff) + productError;{% elif ORDERED_SUM %} let productLarger = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, productLarger);let smaller = select(product, acc.hi, productLarger);let roundoff = fma(-1.0, fma(-1.0, larger, sum), smaller);let error = fma(fma(roundoff, 1.0, acc.lo), 1.0, productError);{% else %} let bv = fma({{ dotType }}(-1.0), acc.hi, sum);let av = fma({{ dotType }}(-1.0), bv, sum);let ae = fma({{ dotType }}(-1.0), av, acc.hi);let be = fma({{ dotType }}(-1.0), bv, product);let error = fma(fma(fma(ae, {{ dotType }}(1.0), be), {{ dotType }}(1.0), acc.lo), {{ dotType }}(1.0), productError);{% endif %}{% if PROTECTED_SUM %}// Carry the residual to the end of the dot. Renormalizing each step can// round a recovered product bit out of the low word on relaxed backends.return DotAccumulator(sum, error);{% else %} let hi = fma(sum, {{ dotType }}(1.0), error);{% if SELECT_NONFINITE %} let sumValid = abs(sum) <= 3.4028234663852886e38 && abs(acc.lo) <= 3.4028234663852886e38;let nextLo = fma(-1.0, fma(-1.0, sum, hi), error);return DotAccumulator(select(sum, hi, sumValid), select(0.0, nextLo, sumValid && abs(hi) <= 3.4028234663852886e38));{% else %}{% if dotGuardNonfinite | default(false) %} if (!(abs(hi) <= 3.4028234663852886e38)) {return DotAccumulator(hi, {{ dotType }}(0.0));}{% endif %} return DotAccumulator(hi, fma({{ dotType }}(-1.0), fma({{ dotType }}(-1.0), sum, hi), error));{% endif %}{% endif %}}{% endmacro %}{{ dot_step("dot_accumulate", dotGuardNonfinite | default(false)) }}fn dot_value(acc: DotAccumulator) -> {{ dotType }} {return fma(acc.hi, {{ dotType }}(1.0), acc.lo);}fn score_dot_accumulate4(acc: DotAccumulator, q: vec4<f32>, k: vec4<f32>) -> DotAccumulator {var next = acc;{% for component in ["x", "y", "z", "w"] %} next = {{ "dot_accumulate" }}(next, q.{{ component }}, k.{{ component }});{% endfor %} return next;}{% endif %}{% macro query_key_dot() %}{% if COMP_SCORE %} var score_acc = DotAccumulator(0.0, 0.0);for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {score_acc = score_dot_accumulate4(score_acc, q_shared[d4], vec4<f32>(key[kRowV4 + d4]));}let acc = dot_value(score_acc);{% else %} var acc: f32 = 0.0;for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {acc = acc + dot(q_shared[d4], vec4<f32>(key[kRowV4 + d4]));}{% endif %}{% endmacro %}{% if normalizedValues %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&{% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &{% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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 }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("vec4<f32>", "f32", true) }}{% endif %}// Flash-style tiled online-softmax attention for vec4-aligned head dimensions.// One workgroup per5 unmodified lines// per tile; the full score matrix is never materialized.// Layout: token-major [batch, seq, heads * headDim]; Q and KV hidden strides// are compiled constants.const HEAD_DIM: u32 = {{ headDim }}u;const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;const Q_HIDDEN_V4: u32 = {{ qHiddenV4 }}u;28 unmodified lines}var<workgroup> q_shared: array<vec4<f32>, HEAD_DIM_V4>;{% if not normalizedValues %}var<workgroup> running_out: array<vec4<f32>, HEAD_DIM_V4>;{% endif %}var<workgroup> probs: array<f32, WG>;// Workgroup-cooperative merge of per-thread online-softmax (m, d) partials:// mNew = max(m1, m2)14 unmodified linesvar<workgroup> leaderMask: array<atomic<u32>, (WG + 31u) / 32u>;var<workgroup> combinedMD: vec2<f32>;fn combine_partials(m: f32, d: f32, lidx: u32) -> vec2<f32> {let sgM = subgroupMax(m);// A lane with no elements contributes d == 0 (exact identity). A +inf// element made exp(inf - inf) = NaN stick in that lane's d; a NaN element// landed in d via exp(NaN); both survive the merge and are detected by the// code after the reduction.let sgD = subgroupAdd(d * exp_shift(m, sgM));if (subgroupElect()) {partialM[lidx] = sgM;partialD[lidx] = sgD;25 unmodified linesif (params.scale != 0.0) { return params.scale; }return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));}@compute @workgroup_size(WG, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>) {let qi = wg.x;let h = wg.y;let b = wg.z;10 unmodified lineslet kvTokenStrideV4 = KV_HIDDEN_V4;// Cooperative vec4 Q-row load; init the output accumulator.{% if normalizedValues %}var output_acc: array<ScaledValue, (HEAD_DIM_V4 + WG - 1u) / WG>;for (var i = 0u; i < (HEAD_DIM_V4 + WG - 1u) / WG; i++) { output_acc[i] = scaled_value_zero(); }for (var d4 = tid; d4 < HEAD_DIM_V4; d4 += WG) {var qv = vec4<f32>(query[qBaseV4 + d4]);q_shared[d4] = qv;}workgroupBarrier();{% else %}{% set hasBias = false %}for (var d4 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {var qv = vec4<f32>(query[qBaseV4 + d4]);q_shared[d4] = qv;running_out[d4] = vec4<f32>(0.0);}workgroupBarrier();{% endif %}let scale = scale_value();11 unmodified lines{% else %}var keyBoundV = params.kvSeq;{% endif %}keyBoundV = min(keyBoundV, {{ attn_seqlens_bound("params.kvSeq", "b", "params.qSeq" if seqlensQueryFloor | default(false) else "") }});var keyFloor: u32 = 0u;{% if hasWindow %}// Sliding window: query qi sits at absolute position p = kvSeq - qSeq22 unmodified linesvar keyAllowed = kj < keyBound{% if hasCausal %} && (params.isCausal == 0u || kj <= qi){% endif %}{% if hasWindow %} && kj >= keyFloor{% endif %};if (keyAllowed) {let kRowV4 = kvBaseV4 + kj * kvTokenStrideV4;{{ query_key_dot() }}score = acc * scale;m = score;dPart = select(0.0, 1.0, keyAllowed);}let tile = combine_partials(m, dPart, tid);// Online merge of the tile into the running state (softmax-online rule).// Merge one key tile's online-softmax (maximum, denominator) partial into the14 unmodified lines// tiles, so the rescale-and-accumulate below is race-free; vec4 V loads.let tileCount = min(WG, keyBound - kjBase);for (var d4: u32 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {{% if normalizedValues %}// Preserve a raw weighted numerator with a separate exponent range.var vSum = scaled_value_rescale(output_acc[d4 / WG], correction);{% else %}var vSum = vec4<f32>(0.0);{% endif %}for (var i: u32 = 0u; i < tileCount; i = i + 1u) {vSum = {% if normalizedValues %}scaled_value_add(vSum, probs[i], {% else %}vSum + probs[i] * {% endif %}vec4<f32>(value[kvBaseV4 + (kjBase + i) * kvTokenStrideV4 + d4]){% if normalizedValues %}){% endif %};}{% if normalizedValues %}output_acc[d4 / WG] = vSum;{% else %}running_out[d4] = running_out[d4] * correction + vSum;{% endif %}}// Orders this tile's probs reads before the next tile's probs writes.workgroupBarrier();2 unmodified lines}// The output shares Q's layout and row base.{% if hasBias or not normalizedValues %}let hasMass = runningDenom > 0.0;{% endif %}{% if not normalizedValues %}let invDenom = select(0.0, 1.0 / runningDenom, hasMass);{% endif %}for (var d4: u32 = tid; d4 < HEAD_DIM_V4; d4 = d4 + WG) {var outValue = {% if normalizedValues %}scaled_value_mean(output_acc[d4 / WG], runningDenom){% else %}running_out[d4] * invDenom{% endif %};{% if hasBias %}// V bias is token-independent, so add it once after the softmax-weighted sum.outValue = outValue + load_bias4(2u * {{ qHidden }}u + h * HEAD_DIM, d4)
1232 unmodified lines67891011121314151617181 unmodified line20212223242526272829303132333435363738394041424344454647484950515222 unmodified lines757677787980818283844 unmodified lines8990919293949519 unmodified lines11511611711811912012112212312412512612712812913013113213313413513639 unmodified lines1761771781791801811821831841851861871881891903 unmodified lines1941951961971981996 unmodified lines2062072082092102112122132142152162172182192202 unmodified lines22322422522622722822923023123223323439 unmodified lines2742752762772782792802812822832842852862874 unmodified lines29229329429529629729825 unmodified lines32432532632732832933033133233333433511 unmodified lines3473483493503513523534 unmodified lines3583593603613623633643653663673683 unmodified lines37237337437537637737837938038138238338438538638738838939039139210 unmodified lines4034044054064074084095 unmodified lines4154164174184194204217 unmodified lines42943043143243343443543643743843944044111 unmodified lines45345445545645745845946046146246346446546617 unmodified lines48448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554630 unmodified lines5775785795805815825835845855865875885895905915925935945955962 unmodified lines5996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586593 unmodified lines663664665666667668669670671672673674675676677678679{% set QSEQ = "params.qSeq" %}{% set KVSEQ = "params.kvSeq" %}{% set IS_CAUSAL = "params.isCausal" %}2 unmodified lines{% set KEY = "key" %}{% set VALUE = "value" %}{% set OUTPUT = "output" %}{% if useSubgroups is not defined %}{% set useSubgroups = true %}{% endif %}{% if batchNoSgReduction is not defined %}{% set batchNoSgReduction = false %}{% endif %}{% set SHARE_PROB = shareNoSgProb is defined and shareNoSgProb %}{% if hasMask is not defined %}{% set hasMask = false %}{% endif %}{% set maskIsKeyKeep = false %}{% set maskIsBool = false %}{% if hasSoftcap is not defined %}{% set hasSoftcap = false %}{% endif %}{% if hasHeadSink is not defined %}{% set hasHeadSink = false %}{% endif %}{% set Q_HIDDEN = qHidden | default(0) %}{% if quantCacheFormat is not defined %}{% set quantCacheFormat = "" %}{% endif %}{% if useSeqlens is not defined %}{% set useSeqlens = false %}{% endif %}// A windowed cache binds a fixed CAPACITY but keeps only the most recent1 unmodified line// count, which is still the right batch stride but the wrong attention bound, so// the bounds read kvActive instead. Modes without seqlens use `params.kvSeq`// in both roles.{% if hasKeyLimit is not defined %}{% set hasKeyLimit = false %}{% endif %}{% if useSeqlens %}{% set KVA = "kvActive" %}{% elif hasKeyLimit %}{% set KVA = "select(params.kvSeq, min(params.keyLimit, params.kvSeq), params.keyLimit > 0u)" %}{% else %}{% set KVA = KVSEQ %}{% endif %}{% macro score_expr(part) %}{% if hasSoftcap %}params.softcap * tanh(clamp(({{ part }} * SCALE) / params.softcap, -30.0, 30.0)){% else %}{{ part }} * SCALE{% endif %}{% endmacro %}{% if useSubgroups %}enable subgroups;{% endif %}{{ env.wgsl.resourceDeclarations }}{% set ST = "f16" if usesF16 else "f32" %}// K/V tiles are staged as f16 when this specialization uses f16, reducing// workgroup storage; values widen to f32 when read. Other specializations stage// them as f32. Score and weighted-value accumulation remain in f32 throughout.{% set FUSED_ROTARY = fusedRotary is defined and fusedRotary %}{% set STAGE_MASK = hasMask and useSubgroups and stageMask is defined and stageMask %}{% set MASK_IS_INT = hasMask and (maskIsKeyKeep or maskIsBool) %}{% set MASK_TILE_TYPE = "u32" if MASK_IS_INT else "f32" %}{% set MASK_TILE_LOAD = "attn_mask[maskIndex]" if MASK_IS_INT else "f32(attn_mask[maskIndex])" %}{% set MASK_TILE_ZERO = "0u" if MASK_IS_INT else "0.0" %}{% set MASK_ADDITIVE = "maskValue" if STAGE_MASK else "f32(attn_mask[maskIndex])" %}{% set SLICE_COUNT = ((headDimV4 / LPQ) | int) %}{% set QPL = (2 if (not usesF16 and SLICE_COUNT <= 4 and TILE_K <= 16 and TILE_Q % 2 == 0) else 1) if useSubgroups else 1 %}{% macro qn(name, qi) %}{{ name }}{% if qi > 0 %}_q{{ qi }}{% endif %}{% endmacro %}{% macro emit_tile_softmax() %}// Per-thread online softmax over the tile. s[kk] is reused to hold the// exponentiated probabilities for the PV accumulation below.22 unmodified lines// Tiled flash prefill attention with configurable-width query clusters for// token-major [batch, seq, heads*headDim] attention ops. Each workgroup covers// TILE_Q queries with one LPQ-lane cluster per query; K/V are staged in// workgroup memory once per TILE_K tile. Within a cluster, each lane holds named// q/o slices of HEAD_DIM/LPQ dimensions. Per-lane dot fragments are// combined with subgroup shuffles when available, or shared-memory reductions// on compatibility variants. Dot products, online softmax, and weighted-value// sums accumulate in f32. Optional masks are broadcast-strided; the// maskIsKeyKeep specialization supports 1=keep key-padding masks directly.// hasCausal: params.isCausal masks keys after the query token (qSeq==kvSeq).4 unmodified lines// SLICE contiguous head-dim vec4s starting at lane8*SLICE.const HEAD_DIM: u32 = {{ headDim }}u;const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;{% if QL != "bhsd" %}const Q_HIDDEN_V4: u32 = {{ qHiddenV4 }}u; // bsh token-major hidden stride{% endif %}{% if KL != "bhsd" %}19 unmodified linesconst NEG_INF: f32 = -3.4028234663852886e38;var<workgroup> k_tile: array<vec4<{{ ST }}>, TILE_K * (HEAD_DIM / 4u)>;var<workgroup> v_tile: array<vec4<{{ ST }}>, TILE_K * (HEAD_DIM / 4u)>;{% if STAGE_MASK %}// Each LPQ cluster consumes one mask value per (query,key), so stage the// TILE_Q x TILE_K mask tile once instead of issuing LPQ duplicate global loads.var<workgroup> mask_tile: array<{{ MASK_TILE_TYPE }}, TILE_Q * TILE_K>;{% endif %}{% if not useSubgroups %}{% if batchNoSgReduction %}// No-subgroups cluster reduction scratch for a whole K tile. Staging every// lane's partial for every key lets the workgroup synchronize once per tile,// instead of twice per key. This path requires TILE_K*WG f32 scratch elements.var<workgroup> red: array<f32, TILE_K * WG>;{% else %}// One-key reduction path: reuse a single key's scratch across the tile.var<workgroup> red: array<f32, WG>;{% endif %}{% endif %}{% set ATTN_SCALE_DIM = "HEAD_DIM" %}fn scale_value() -> f32 {39 unmodified lines{{ emit_quant_load4(quantCacheFormat, "value", VALUE, "v_scale") }}{% endif %}{% if hasBias %}{% set BW = "" %}{% set BC = "" %}fn load_bias4(base: u32, d4: u32) -> vec4<f32> {let offset = base + d4 * 4u;return vec4<f32>({{ BW }}bias[offset]{{ BC }}, {{ BW }}bias[offset + 1u]{{ BC }}, {{ BW }}bias[offset + 2u]{{ BC }}, {{ BW }}bias[offset + 3u]{{ BC }});}{% endif %}@compute @workgroup_size(WG, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>,3 unmodified lineslet h = wg.y;let b = wg.z;let tid = lid.x;{% if useSubgroups %}// The subgroupShuffleXor butterfly requires every LPQ-lane query cluster to// fit in, and align with, one subgroup. Keep a uniform guard for defensive6 unmodified lineslet qSub = tid / LPQ;{% endif %}let lane8 = tid % LPQ;{% for qi in range(QPL) %}let {{ qn("qIdx", qi) }} = wg.x * TILE_Q + qSub{% if qi > 0 %} + {{ qi }}u{% endif %};let {{ qn("qValid", qi) }} = {{ qn("qIdx", qi) }} < {{ QSEQ }} && h < Q_HEADS;{% endfor %}let hKv = h / (Q_HEADS / KV_HEADS);let SCALE = scale_value();// Per-thread q slice and output accumulator, each stored in SLICE named vec4 values.{% for qi in range(QPL) %}let {{ qn("qClamped", qi) }} = min({{ qn("qIdx", qi) }}, {{ QSEQ }} - 1u);{% if QL == "bhsd" %}let {{ qn("qBase4", qi) }} = ((b * Q_HEADS + h) * {{ QSEQ }} + {{ qn("qClamped", qi) }}) * HEAD_DIM_V4 + lane8 * SLICE;2 unmodified lines{% endif %}{% for c in range(SLICE_COUNT) %}var {{ qn("qr" ~ c, qi) }} = vec4<f32>({{ QUERY }}[{{ qn("qBase4", qi) }} + {{ c }}u]);{% if hasBias %}{{ qn("qr" ~ c, qi) }} = {{ qn("qr" ~ c, qi) }} + load_bias4(h * HEAD_DIM, lane8 * SLICE + {{ c }}u);{% endif %}var {{ qn("o" ~ c, qi) }} = vec4<f32>(0.0);{% endfor %}{% endfor %}{% if FUSED_ROTARY %}// The present-cache keys are already rotary transformed. Transform Q once// before the K loop, avoiding a separate full-size Q scratch pass. NeoX39 unmodified lines{% endfor %}{% if useSeqlens %}// Resident rows of a windowed cache: the survivors were shifted down to [0, kvActive),// so query/key DISTANCE is unchanged and every bound below reads as if the cache were// exactly kvActive long. Rotary is excluded from this path (it would need the absolute// position, not the cache-relative one), so pastLenForRope keeps the physical length.// Clamping below by the query count matches the cache-update passes and the scalar// path: a right-padded batch (seqlens_k[b]+1 < qSeq) still appends its whole chunk,// so its queries score against all of it.let kvActive = min({{ KVSEQ }}, max({{ QSEQ }}, u32(seqlens_k[b]) + 1u));{% endif %}// Causal ceiling per query; the key loop runs over the workgroup's union range// (uniform trip count), masking out-of-range (query, key) pairs.4 unmodified lines// windowed, the floor p+1-windowSize. The key loop runs over the workgroup's// union range [wgStart, wgEnd); out-of-range (query,key) pairs mask to NEG_INF.// pastLen = kvSeq - qSeq: query tokens are the last qSeq positions of the cache;// saturate so an out-of-contract qSeq > kvSeq can't underflow u32. Used for the// sliding window always, and for the causal ceiling only when right-aligned.{% if RIGHT or hasWindow %}let pastLen = select(0u, {{ KVA }} - {{ QSEQ }}, {{ KVA }} >= {{ QSEQ }});25 unmodified lines{% for qi in range(QPL) %}let {{ qn("qAbsP1", qi) }} = pastLen + {{ qn("qIdx", qi) }} + 1u;{{ qn("maxKjV", qi) }} = min({{ qn("maxKjV", qi) }}, {{ qn("qAbsP1", qi) }});if ({{ qn("qAbsP1", qi) }} > params.windowSize) { {{ qn("minKjV", qi) }} = {{ qn("qAbsP1", qi) }} - params.windowSize; }{% endfor %}let lastQAbsP1 = pastLen + lastQ + 1u;wgEndV = min(wgEndV, lastQAbsP1);let firstQAbsP1 = pastLen + wg.x * TILE_Q + 1u;if (firstQAbsP1 > params.windowSize) { wgStartV = firstQAbsP1 - params.windowSize; }{% endif %}{% for qi in range(QPL) %}let {{ qn("maxKj", qi) }} = {{ qn("maxKjV", qi) }};11 unmodified lineslet {{ qn("minKj", qi) }} = minKj;{% endfor %}{% endif %}{% if KL == "bhsd" %}{% if quantCacheFormat == "int4" %}let kvRowStride4 = HEAD_DIM_V4 * 2u;{% else %}4 unmodified lineslet kvBatch4 = b * {{ KVSEQ }} * KV_HIDDEN_V4 + hKv * HEAD_DIM_V4;{% endif %}var kStart: u32 = wgStart;loop {if (kStart >= wgEnd) { break; }// Cooperative K/V tile load with out-of-bounds keys zero-filled.workgroupBarrier();for (var i: u32 = tid; i < TILE_K * HEAD_DIM_V4; i = i + WG) {let slot = i / HEAD_DIM_V4;3 unmodified lines{% if KL == "bhsd" %}let base4 = kvBatch4 + kj * kvRowStride4 + d4;{% else %}let base4 = kvBatch4 + kj * KV_HIDDEN_V4 + d4;{% endif %}{% if quantCacheFormat %}k_tile[i] = vec4<{{ ST }}>(load_key4(base4, d4, hKv));v_tile[i] = vec4<{{ ST }}>(load_value4(base4, d4, hKv));{% else %}k_tile[i] = vec4<{{ ST }}>({{ KEY }}[base4]);v_tile[i] = vec4<{{ ST }}>({{ VALUE }}[base4]);{% endif %}} else {k_tile[i] = vec4<{{ ST }}>(0.0);v_tile[i] = vec4<{{ ST }}>(0.0);}}{% if STAGE_MASK %}// The K/V load barrier also publishes this compact mask tile.for (var i: u32 = tid; i < TILE_Q * TILE_K; i = i + WG) {let qSlot = i / TILE_K;10 unmodified lines{% endif %}workgroupBarrier();// TILE_K is a small shader constant; the loop updates the named q/o slices in place.{% if not useSubgroups and batchNoSgReduction %}// First publish every key's partial dot without intervening barriers.{% if not SHARE_PROB %}var s: array<f32, TILE_K>;5 unmodified linesvar part: f32 = 0.0;let kb = kk * HEAD_DIM_V4 + lane8 * SLICE;{% for c in range(SLICE_COUNT) %}part = part + dot(qr{{ c }}, vec4<f32>(k_tile[kb + {{ c }}u]));{% endfor %}red[kk * WG + tid] = part;}7 unmodified lines{% for j in range(LPQ) %}let r{{ j }} = red[kk * WG + cbase + {{ j }}u];{% endfor %}{% if LPQ == 8 %}let part = ((r0 + r1) + (r2 + r3)) + ((r4 + r5) + (r6 + r7));{% elif LPQ == 4 %}let part = (r0 + r1) + (r2 + r3);{% else %}let part = r0 + r1;{% endif %}red[kk * WG + cbase] = part;}workgroupBarrier();11 unmodified lines{% if SHARE_PROB %}s[kk] = NEG_INF;{% endif %}if (kj >= minKj && kj < maxKj) {{% if hasMask %}let maskIndex = b * params.maskBatchStride + h * params.maskHeadStride + qClamped * params.maskSeqStride + kj;s[kk] = {{ score_expr("part") }} + f32(attn_mask[maskIndex]);{% else %}s[kk] = {{ score_expr("part") }};{% endif %}}}{% if SHARE_PROB %}{{ emit_tile_softmax() }}17 unmodified lineslet kj = kStart + kk;{% for qi in range(QPL) %}{{ qn("s", qi) }}[kk] = NEG_INF;var {{ qn("part", qi) }}: f32 = 0.0;{% endfor %}let kb = kk * HEAD_DIM_V4 + lane8 * SLICE;{% for c in range(SLICE_COUNT) %}let kw{{ c }} = vec4<f32>(k_tile[kb + {{ c }}u]);{% for qi in range(QPL) %}{{ qn("part", qi) }} = {{ qn("part", qi) }} + dot({{ qn("qr" ~ c, qi) }}, kw{{ c }});{% endfor %}{% endfor %}// One butterfly carries every query's partial: the shuffles cost the same// whether the payload is one score or QPL of them.var partv = vec{{ QPL }}<f32>({% for qi in range(QPL) %}{{ qn("part", qi) }}{% if not loop.last %}, {% endif %}{% endfor %});partv = partv + subgroupShuffleXor(partv, 1u);{% for shift in [2, 4] %}{% if LPQ > shift %}partv = partv + subgroupShuffleXor(partv, {{ shift }}u);{% endif %}{% endfor %}{% for qi in range(QPL) %}{let sc = partv[{{ qi }}];if (kj >= {{ qn("minKj", qi) }} && kj < {{ qn("maxKj", qi) }}) {{% if hasMask %}{% if STAGE_MASK %}let maskValue = mask_tile[(qSub + {{ qi }}u) * TILE_K + kk];{% else %}// Broadcast-strided mask address (a 0 stride collapses that axis; rank-2// [q, k] masks set batch/head strides to 0). {{ qn("qClamped", qi) }} keeps the seq index// in-bounds for padding queries in the last tile (their output is dropped).let maskIndex = b * params.maskBatchStride + h * params.maskHeadStride + {{ qn("qClamped", qi) }} * params.maskSeqStride + kj;{% endif %}{{ qn("s", qi) }}[kk] = {{ score_expr("sc") }} + {{ MASK_ADDITIVE }};{% else %}{{ qn("s", qi) }}[kk] = {{ score_expr("sc") }};{% endif %}}}{% endfor %}}{% else %}var s: array<f32, TILE_K>;for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let kj = kStart + kk;s[kk] = NEG_INF;var part: f32 = 0.0;let kb = kk * HEAD_DIM_V4 + lane8 * SLICE;{% for c in range(SLICE_COUNT) %}part = part + dot(qr{{ c }}, vec4<f32>(k_tile[kb + {{ c }}u]));{% endfor %}{% if useSubgroups %}// log2(LPQ) butterfly all-reduce within the LPQ-lane cluster (each lane ends with the full dot).part = part + subgroupShuffleXor(part, 1u);{% for shift in [2, 4] %}{% if LPQ > shift %}part = part + subgroupShuffleXor(part, {{ shift }}u);{% endif %}{% endfor %}{% else %}red[tid] = part;workgroupBarrier();30 unmodified lines// NaN, the guarded loop selects the V operand away for range-excluded keys.// Interior tiles use the unguarded FMA chain. Mask exclusion applies to// materialized V rows and does not require this range guard.{% if SHARE_PROB %}{% macro shared_pv(masked) %}for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let weight = red[kk * WG + cbase];let vb = kk * HEAD_DIM_V4 + lane8 * SLICE;{% for c in range(SLICE_COUNT) %}o{{ c }} = o{{ c }} + weight * {% if masked %}select(vec4<f32>(), {% endif %}vec4<f32>(v_tile[vb + {{ c }}u]){% if masked %}, weight != 0.0){% endif %};{% endfor %}}{% endmacro %}// Consume each shared probability once across all output slices. This// retains the key order of every output accumulator without a private tile.{% for c in range(SLICE_COUNT) %}o{{ c }} = o{{ c }} * corr;{% endfor %}let tileInterior = kStart >= minKj && kStart + TILE_K <= maxKj;if (tileInterior) {2 unmodified lines{{ shared_pv(true) }}}{% elif QPL > 1 %}let tileInterior = {% for qi in range(QPL) %}(kStart >= {{ qn("minKj", qi) }} && kStart + TILE_K <= {{ qn("maxKj", qi) }}){% if not loop.last %} && {% endif %}{% endfor %};{% for c in range(SLICE_COUNT) %}{{% for qi in range(QPL) %}var {{ qn("acc", qi) }} = {{ qn("o" ~ c, qi) }} * {{ qn("corr", qi) }};{% endfor %}if (tileInterior) {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let vw = vec4<f32>(v_tile[kk * HEAD_DIM_V4 + lane8 * SLICE + {{ c }}u]);{% for qi in range(QPL) %}{{ qn("acc", qi) }} = {{ qn("acc", qi) }} + {{ qn("s", qi) }}[kk] * vw;{% endfor %}}} else {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let vw = vec4<f32>(v_tile[kk * HEAD_DIM_V4 + lane8 * SLICE + {{ c }}u]);{% for qi in range(QPL) %}{{ qn("acc", qi) }} = {{ qn("acc", qi) }} + {{ qn("s", qi) }}[kk] * select(vec4<f32>(), vw, {{ qn("s", qi) }}[kk] != 0.0);{% endfor %}}}{% for qi in range(QPL) %}{{ qn("o" ~ c, qi) }} = {{ qn("acc", qi) }};{% endfor %}}{% endfor %}{% else %}let tileInterior = kStart >= minKj && kStart + TILE_K <= maxKj;{% for c in range(SLICE_COUNT) %}{var acc = o{{ c }} * corr;if (tileInterior) {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {acc = acc + s[kk] * vec4<f32>(v_tile[kk * HEAD_DIM_V4 + lane8 * SLICE + {{ c }}u]);}} else {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {acc = acc + s[kk] * select(vec4<f32>(), vec4<f32>(v_tile[kk * HEAD_DIM_V4 + lane8 * SLICE + {{ c }}u]), s[kk] != 0.0);}}o{{ c }} = acc;}{% endfor %}{% endif %}kStart = kStart + TILE_K;}{% macro attention_value(c, qi) %}{{ qn("o" ~ c, qi) }} * inv{% if hasBias %} + load_bias4(2u * {{ Q_HIDDEN }}u + h * HEAD_DIM, lane8 * SLICE + {{ c }}u){% endif %}{% endmacro %}{% for qi in range(QPL) %}if ({{ qn("qValid", qi) }}) {{% if QL == "bhsd" %}let outBase4 = ((b * Q_HEADS + h) * {{ QSEQ }} + {{ qn("qIdx", qi) }}) * HEAD_DIM_V4 + lane8 * SLICE;{% else %}let outBase4 = (b * {{ QSEQ }} + {{ qn("qIdx", qi) }}) * Q_HIDDEN_V4 + h * HEAD_DIM_V4 + lane8 * SLICE;{% endif %}{% if hasHeadSink %}// The head sink is a learned logit that competes with the keys but carries3 unmodified lineslet sink = f32(head_sink[h]);let finalM = max({{ qn("m", qi) }}, sink);let accScale = exp({{ qn("m", qi) }} - finalM);let inv = accScale / (exp(sink - finalM) + {{ qn("l", qi) }} * accScale);{% else %}// {{ qn("l", qi) }} == 0 means this query had no probability-bearing key: either its// causal/window range is empty or its logical bool mask rejects every key.// Emit 0 rather than 0/0. Other attention paths enforce the same empty-row// contract by selecting on positive global mass.let inv = select(0.0, 1.0 / {{ qn("l", qi) }}, {{ qn("l", qi) }} > 0.0);{% endif %}{% for c in range(SLICE_COUNT) %}{{ OUTPUT }}[outBase4 + {{ c }}u] = vec4<{{ scalar }}>({{ attention_value(c, qi) }});{% endfor %}}{% endfor %}}12345678910111213142 unmodified lines17181920212223242526272829301 unmodified line323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261322 unmodified lines6366376386396406416426436446456466474 unmodified lines65265365465565665765865966066119 unmodified lines68168268368468568668768868969069169269369439 unmodified lines7347357367377387397407413 unmodified lines7457467477487497507517527537547557567577587597607617627637647657667677687696 unmodified lines7767777787797807817827837847857867877887897907917927932 unmodified lines79679779879980080180280380480580680739 unmodified lines8478488498508518528538548558568578588598608618624 unmodified lines86786886987087187287325 unmodified lines89990090190290390490590690790890991011 unmodified lines9229239249259269279284 unmodified lines9339349359369379389399409419429439449459469479489499509519529539549559569579589599609619623 unmodified lines96696796896997097197297397497597697797897998098198298398498598610 unmodified lines997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010615 unmodified lines10671068106910701071107210737 unmodified lines108110821083108410851086108711 unmodified lines109911001101110211031104110517 unmodified lines1123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117230 unmodified lines120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012612 unmodified lines12641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813993 unmodified lines1403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436{% set PAIRED_PARTIALS = false %}{% set SCORE_KEYS = portableScoreKeys | default(1) %}{% set COMP_SCORE = (compensatedScoreDot | default(false)) and not usesF16 and scalar == "f32" %}{% set VALUE_HEAD = valueHeadDim | default(headDim) %}{% set VALUE_SPLIT = VALUE_HEAD != headDim %}{% set VALUE_DIM_NAME = "VALUE_DIM" if VALUE_SPLIT else "HEAD_DIM" %}{% set VALUE_DIM_V4_NAME = "VALUE_DIM_V4" if VALUE_SPLIT else "HEAD_DIM_V4" %}{% set VALUE_SLICE_NAME = "VALUE_SLICE" if VALUE_SPLIT else "SLICE" %}{% set WINDOW_SIZE = "params.windowSize" %}{% set KV_ROW = "kj" %}{% macro cluster_shuffle_sum(value, width) %}{% for stage in range(log2ceil(width)) %}{{ value }} = {{ value }} + subgroupShuffleXor({{ value }}, {{ pow(2, stage)|int }}u);{% endfor %}{% endmacro %}{% macro cluster_tree_sum(prefix, offset, count) %}{% if count == 1 %}{{ prefix }}{{ offset }}{% else %}{% set left = ((count + 1) / 2)|int %}({{ cluster_tree_sum(prefix, offset, left) }} + {{ cluster_tree_sum(prefix, offset + left, count - left) }}){% endif %}{% endmacro %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {% if queryFloor %}max({{ queryFloor }}, {{ attn_seqlens_count(index) }}){% else %}{{ attn_seqlens_count(index) }}{% endif %}){% endmacro %}{% set QSEQ = "params.qSeq" %}{% set KVSEQ = "params.kvSeq" %}{% set IS_CAUSAL = "params.isCausal" %}2 unmodified lines{% set KEY = "key" %}{% set VALUE = "value" %}{% set OUTPUT = "output" %}{% set NORMALIZED_VALUES = not usesF16 and scalar == "f32" %}{% if useSubgroups is not defined %}{% set useSubgroups = true %}{% endif %}{% if not useSubgroups %}{% set clusterPin = 0 %}{% endif %}{% if batchNoSgReduction is not defined %}{% set batchNoSgReduction = false %}{% endif %}{% set SHARE_PROB = shareNoSgProb is defined and shareNoSgProb and not (COMP_SCORE and not useSubgroups) %}{% if hasMask is not defined %}{% set hasMask = false %}{% endif %}{% set maskIsKeyKeep = false %}{% set maskIsBool = false %}{% if hasSoftcap is not defined %}{% set hasSoftcap = false %}{% endif %}{% if hasHeadSink is not defined %}{% set hasHeadSink = false %}{% endif %}{% if quantCacheFormat is not defined %}{% set quantCacheFormat = "" %}{% endif %}{% if useSeqlens is not defined %}{% set useSeqlens = false %}{% endif %}// A windowed cache binds a fixed CAPACITY but keeps only the most recent1 unmodified line// count, which is still the right batch stride but the wrong attention bound, so// the bounds read kvActive instead. Modes without seqlens use `params.kvSeq`// in both roles.{% if useSeqlens %}{% set KVA = "kvActive" %}{% else %}{% set KVA = KVSEQ %}{% endif %}{% macro score_expr(part) %}{% if hasSoftcap %}params.softcap * tanh(clamp(({{ part }} * SCALE) / params.softcap, -30.0, 30.0)){% else %}{{ part }} * SCALE{% endif %}{% endmacro %}{% if useSubgroups %}enable subgroups;{% if clusterPin > 0 %}enable subgroup_size_control;{% endif %}{% endif %}{{ env.wgsl.resourceDeclarations }}{% if COMP_SCORE %}{% set dotGuardNonfinite = true %}{% set dotType = "f32" %}{% set protectDifference = false %}{% set PROTECTED_SUM = false %}{% set SELECT_NONFINITE = false %}{% set ORDERED_SUM = false %}// Retain product and addition residuals across a dot product. Explicit fma// boundaries preserve the addition error transform under reassociation.struct DotAccumulator {hi: {{ dotType }},lo: {{ dotType }},}{% if dotRecoverProductResidual | default(false) %}{% set dotBitsType = "u32" %}// Recover an inexact product when a backend returns a zero fma residual.{% set dotExponentType = "i32" %}{% macro dot_parts() -%}let aBits = bitcast<{{ dotBitsType }}>(a);let bBits = bitcast<{{ dotBitsType }}>(b);let pBits = bitcast<{{ dotBitsType }}>(product);let ae = (aBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let be = (bBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let pe = (pBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);{% endmacro %}fn dot_product_error(a: {{ dotType }}, b: {{ dotType }}, product: {{ dotType }}) -> {{ dotType }} {// Twelve-bit significand parts make each split product exactly representable.let nativeError = fma(a, b, -product);if (nativeError == 0.0) {{{ dot_parts() | indent(4, true) }}let lowProduct = (((aBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u)) *((bBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u))) & {{ dotBitsType }}(0x00ffffffu);let recover = (nativeError == {{ dotType }}(0.0)) && (lowProduct != {{ dotBitsType }}(0u)) && (ae > {{ dotBitsType }}(0u)) && (ae < {{ dotBitsType }}(255u)) && (be > {{ dotBitsType }}(0u)) && (be < {{ dotBitsType }}(255u)) && (pe > {{ dotBitsType }}(0u)) && (pe < {{ dotBitsType }}(255u));if (recover) {// Normalize before splitting: a normal input can otherwise produce a// subnormal low word that a conformant backend is allowed to flush.let an = bitcast<{{ dotType }}>((aBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u));let bn = bitcast<{{ dotType }}>((bBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u));let exponent = select({{ dotExponentType }}(0), {{ dotExponentType }}(ae) + {{ dotExponentType }}(be) - {{ dotExponentType }}(254), recover);let pnExponent = select({{ dotBitsType }}(127u), {{ dotBitsType }}({{ dotExponentType }}(pe) - exponent), recover);let pn = bitcast<{{ dotType }}>((pBits & {{ dotBitsType }}(0x807fffffu)) | (pnExponent << {{ dotBitsType }}(23u)));let ah = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(an) & {{ dotBitsType }}(0xfffff000u));let bh = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(bn) & {{ dotBitsType }}(0xfffff000u));let al = fma({{ dotType }}(-1.0), ah, an);let bl = fma({{ dotType }}(-1.0), bh, bn);let e0 = fma(ah, bh, -pn);let e1 = fma(al, bh, e0);let e2 = fma(ah, bl, e1);let recovered = ldexp(fma(al, bl, e2), exponent);return select(nativeError, recovered, recover);}}return nativeError;}{% endif %}{% macro dot_step(name, dotGuardNonfinite) %}fn {{ name }}(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator {let product = fma(a, b, {{ dotType }}(0.0));{% if dotGuardNonfinite | default(false) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);{% if not SELECT_NONFINITE %} // Nonfinite sums retain ordinary f32 addition classes; Inf-Inf residuals// must not poison a valid infinite dot accumulator.{% if ORDERED_SUM %} if (!(abs(sum) <= 3.4028234663852886e38 && abs(acc.lo) <= 3.4028234663852886e38)) {{% else %} if (!(abs(acc.hi) <= 3.4028234663852886e38) ||!(abs(acc.lo) <= 3.4028234663852886e38) ||!(abs(product) <= 3.4028234663852886e38) ||!(abs(sum) <= 3.4028234663852886e38)) {{% endif %} return DotAccumulator(sum, {{ dotType }}(0.0));}{% endif %}{% endif %} let productError = {% if dotRecoverProductResidual | default(false) %}dot_product_error(a, b, product){% else %}fma(a, b, -product){% endif %};{% if not (dotGuardNonfinite | default(false)) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);{% endif %}{% if PROTECTED_SUM %}let roundoff = dot_sum_error(acc.hi, product, sum);let error = (acc.lo + roundoff) + productError;{% elif ORDERED_SUM %} let productLarger = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, productLarger);let smaller = select(product, acc.hi, productLarger);let roundoff = fma(-1.0, fma(-1.0, larger, sum), smaller);let error = fma(fma(roundoff, 1.0, acc.lo), 1.0, productError);{% else %} let bv = fma({{ dotType }}(-1.0), acc.hi, sum);let av = fma({{ dotType }}(-1.0), bv, sum);let ae = fma({{ dotType }}(-1.0), av, acc.hi);let be = fma({{ dotType }}(-1.0), bv, product);let error = fma(fma(fma(ae, {{ dotType }}(1.0), be), {{ dotType }}(1.0), acc.lo), {{ dotType }}(1.0), productError);{% endif %}{% if PROTECTED_SUM %}// Carry the residual to the end of the dot. Renormalizing each step can// round a recovered product bit out of the low word on relaxed backends.return DotAccumulator(sum, error);{% else %} let hi = fma(sum, {{ dotType }}(1.0), error);{% if SELECT_NONFINITE %} let sumValid = abs(sum) <= 3.4028234663852886e38 && abs(acc.lo) <= 3.4028234663852886e38;let nextLo = fma(-1.0, fma(-1.0, sum, hi), error);return DotAccumulator(select(sum, hi, sumValid), select(0.0, nextLo, sumValid && abs(hi) <= 3.4028234663852886e38));{% else %}{% if dotGuardNonfinite | default(false) %} if (!(abs(hi) <= 3.4028234663852886e38)) {return DotAccumulator(hi, {{ dotType }}(0.0));}{% endif %} return DotAccumulator(hi, fma({{ dotType }}(-1.0), fma({{ dotType }}(-1.0), sum, hi), error));{% endif %}{% endif %}}{% endmacro %}{{ dot_step("dot_accumulate", dotGuardNonfinite | default(false)) }}fn dot_value(acc: DotAccumulator) -> {{ dotType }} {return fma(acc.hi, {{ dotType }}(1.0), acc.lo);}fn score_dot_accumulate4(acc: DotAccumulator, q: vec4<f32>, k: vec4<f32>) -> DotAccumulator {var next = acc;{% for component in ["x", "y", "z", "w"] %} next = {{ "dot_accumulate" }}(next, q.{{ component }}, k.{{ component }});{% endfor %} return next;}fn score_dot_join(a: DotAccumulator, b: DotAccumulator) -> DotAccumulator {return dot_accumulate(dot_accumulate(a, b.hi, 1.0), b.lo, 1.0);}{% endif %}{% set ST = "f16" if usesF16 else "f32" %}// K/V tiles are staged as f16 when this specialization uses f16, reducing// workgroup storage; values widen to f32 when read. Other specializations stage// them as f32. Score and weighted-value accumulation remain in f32 throughout.{% set FUSED_ROTARY = fusedRotary is defined and fusedRotary %}{% set STAGE_MASK = hasMask and useSubgroups and stageMask is defined and stageMask %}{% set MASK_KEY_RANGE = hasMask and maskIsBool and (maskKeyRange | default(false)) %}{% set MASK_IS_INT = hasMask and (maskIsKeyKeep or maskIsBool) %}{% set MASK_TILE_TYPE = "u32" if MASK_IS_INT else "f32" %}{% set MASK_TILE_LOAD = "attn_mask[maskIndex]" if MASK_IS_INT else "f32(attn_mask[maskIndex])" %}{% set MASK_TILE_ZERO = "0u" if MASK_IS_INT else "0.0" %}{% set MASK_ADDITIVE = "maskValue" if STAGE_MASK else "f32(attn_mask[maskIndex])" %}{% set SLICE_COUNT = ((headDimV4 / LPQ) | int) %}{% set VALUE_SLICE_COUNT = ((VALUE_HEAD / (4 * LPQ)) | int) if VALUE_SPLIT else SLICE_COUNT %}{% set MAX_SLICE_COUNT = max(SLICE_COUNT, VALUE_SLICE_COUNT) %}{% set COMPACT_VALUES = false %}{% set COMPACT_REPAIR = false %}{% set LOOP_VALUES = NORMALIZED_VALUES and (VALUE_SLICE_COUNT >= 8 or COMPACT_REPAIR) %}{% set BANK_SWIZZLE = (device.adapterInfo.vendor | default("")) == "nvidia" %}{% set K_SWZ = 8 if SLICE_COUNT % 8 == 0 else (4 if SLICE_COUNT % 4 == 0 else (2 if SLICE_COUNT % 2 == 0 else 1)) %}{% set V_SWZ = 8 if VALUE_SLICE_COUNT % 8 == 0 else (4 if VALUE_SLICE_COUNT % 4 == 0 else (2 if VALUE_SLICE_COUNT % 2 == 0 else 1)) %}{% set K_SWIZZLE = BANK_SWIZZLE and K_SWZ > 1 and LPQ * K_SWZ > 16 %}{% set V_SWIZZLE = BANK_SWIZZLE and V_SWZ > 1 and LPQ * V_SWZ > 16 %}{% macro kswz(d4) %}{% if K_SWIZZLE %} ^ ((({{ d4 }}) / SLICE) * {{ K_SWZ }}u / 8u){% endif %}{% endmacro %}{% macro vswz(d4) %}{% if V_SWIZZLE %} ^ ((({{ d4 }}) / {{ VALUE_SLICE_NAME }}) * {{ V_SWZ }}u / 8u){% endif %}{% endmacro %}{% macro kc(c) %}{% if K_SWIZZLE %}({{ c }}u ^ kSwz){% else %}{{ c }}u{% endif %}{% endmacro %}{% macro vc(c, suffix="u") %}{% if V_SWIZZLE %}({{ c }}{{ suffix }} ^ vSwz){% else %}{{ c }}{{ suffix }}{% endif %}{% endmacro %}{% set K_FULL_INDEX = K_SWIZZLE and SLICE_COUNT % (LPQ * K_SWZ / 8) != 0 %}{% set V_FULL_INDEX = V_SWIZZLE and VALUE_SLICE_COUNT % (LPQ * V_SWZ / 8) != 0 %}{% macro shared_k_index(base, c) %}{% if K_FULL_INDEX %}({{ base }} + {{ c }}u) ^ kSwz{% else %}{{ base }} + {{ kc(c) }}{% endif %}{% endmacro %}{% macro shared_v_index(base, c, suffix="u") %}{% if V_FULL_INDEX %}({{ base }} + {{ c }}{{ suffix }}) ^ vSwz{% else %}{{ base }} + {{ vc(c, suffix) }}{% endif %}{% endmacro %}{% set QPL = (2 if (not usesF16 and not (singleQueryPerLane | default(false)) and not COMPACT_VALUES and MAX_SLICE_COUNT <= 4 and TILE_K <= 16 and TILE_Q % 2 == 0) else 1) if useSubgroups else 1 %}{% macro qn(name, qi) %}{{ name }}{% if qi > 0 %}_q{{ qi }}{% endif %}{% endmacro %}{% set FOLD_STEP = foldStep if foldStep is defined else -1 %}{% set FOLD_MARKS = NORMALIZED_VALUES and (not LOOP_VALUES or COMPACT_REPAIR) and not SHARE_PROB and physicalHeadDim is not defined %}{% set OFFSET_FOLDS = FOLD_MARKS and FOLD_STEP == 0 %}{% set FOLD_REPAIR = NORMALIZED_VALUES and FOLD_STEP == 1 %}{% set FOLD_MARK_BUFFER = "output" %}{% macro fold_mark_index(q, lane) %}{% if QL == "bhsd" %}((b * Q_HEADS + h) * {{ QSEQ }} + {{ q }}) * {{ VALUE_DIM_V4_NAME }} + {{ lane }} * {{ VALUE_SLICE_NAME }}{% else %}(b * {{ QSEQ }} + {{ q }}) * Q_HIDDEN_V4 + h * {{ VALUE_DIM_V4_NAME }} + {{ lane }} * {{ VALUE_SLICE_NAME }}{% endif %}{% endmacro %}{% if NORMALIZED_VALUES %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&{% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &{% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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 }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("vec4<f32>", rescale=not OFFSET_FOLDS or hasHeadSink, tile=OFFSET_FOLDS, add=not OFFSET_FOLDS or PAIRED_PARTIALS) }}{% endif %}{% macro emit_score(part, qi, queryRow) %}if (kj >= {{ qn("minKj", qi) }} && kj < {{ qn("maxKj", qi) }}) {{% if hasMask %}{% if STAGE_MASK %}let maskValue = mask_tile[{{ queryRow }} * TILE_K + kk];{% else %}// Broadcast-strided mask address (a 0 stride collapses that axis; rank-2// [q, k] masks set batch/head strides to 0). {{ qn("qClamped", qi) }} keeps the seq index// in-bounds for padding queries in the last tile (their output is dropped).let maskIndex = b * params.maskBatchStride + h * params.maskHeadStride + {{ qn("qClamped", qi) }} * params.maskSeqStride + kj;{% endif %}{{ qn("s", qi) }}[kk] = {{ score_expr(part) }} + {{ MASK_ADDITIVE }};{% else %}{{ qn("s", qi) }}[kk] = {{ score_expr(part) }};{% endif %}}{% endmacro %}{% macro emit_pair_scores() %}{% for qi in range(QPL) %}{let sc = partv[{{ qi }}];{{ emit_score("sc", qi, "(qSub + " ~ qi ~ "u)") }}}{% endfor %}{% endmacro %}{% macro emit_tile_softmax() %}// Per-thread online softmax over the tile. s[kk] is reused to hold the// exponentiated probabilities for the PV accumulation below.22 unmodified lines// Tiled flash prefill attention with configurable-width query clusters for// token-major [batch, seq, heads*headDim] attention ops. Each workgroup covers// TILE_Q queries with one LPQ-lane cluster per query; K/V are staged in{% if LOOP_VALUES %}// workgroup memory once per TILE_K tile. Each lane keeps named query slices// and indexed scaled output states. Per-lane dot fragments are{% else %}// workgroup memory once per TILE_K tile. Within a cluster, each lane holds named// q/o slices of HEAD_DIM/LPQ dimensions. Per-lane dot fragments are{% endif %}// combined with subgroup shuffles when available, or shared-memory reductions// on variants without subgroups. Dot products, online softmax, and weighted-value// sums accumulate in f32. Optional masks are broadcast-strided; the// maskIsKeyKeep specialization supports 1=keep key-padding masks directly.// hasCausal: params.isCausal masks keys after the query token (qSeq==kvSeq).4 unmodified lines// SLICE contiguous head-dim vec4s starting at lane8*SLICE.const HEAD_DIM: u32 = {{ headDim }}u;const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;{% if VALUE_SPLIT %}const VALUE_DIM: u32 = {{ VALUE_HEAD }}u;const VALUE_DIM_V4: u32 = {{ (VALUE_HEAD / 4) | int }}u;const VALUE_SLICE: u32 = VALUE_DIM / (4u * LPQ);{% endif %}{% if QL != "bhsd" %}const Q_HIDDEN_V4: u32 = {{ qHiddenV4 }}u; // bsh token-major hidden stride{% endif %}{% if KL != "bhsd" %}19 unmodified linesconst NEG_INF: f32 = -3.4028234663852886e38;var<workgroup> k_tile: array<vec4<{{ ST }}>, TILE_K * (HEAD_DIM / 4u)>;var<workgroup> v_tile: array<vec4<{{ ST }}>, TILE_K * ({{ VALUE_DIM_NAME }} / 4u)>;{% if STAGE_MASK %}// Each LPQ cluster consumes one mask value per (query,key), so stage the// TILE_Q x TILE_K mask tile once instead of issuing LPQ duplicate global loads.var<workgroup> mask_tile: array<{{ MASK_TILE_TYPE }}, TILE_Q * TILE_K>;{% endif %}{% if not useSubgroups %}var<workgroup> red: array<f32, {{ (2 * SCORE_KEYS) ~ "u * WG" if COMP_SCORE else ("TILE_K * WG" if batchNoSgReduction else "WG") }}>;{% endif %}{% set ATTN_SCALE_DIM = "HEAD_DIM" %}fn scale_value() -> f32 {39 unmodified lines{{ emit_quant_load4(quantCacheFormat, "value", VALUE, "v_scale") }}{% endif %}{% if clusterPin > 0 %}@subgroup_size({{ clusterPin }}){% endif %}@compute @workgroup_size(WG, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>,3 unmodified lineslet h = wg.y;let b = wg.z;let tid = lid.x;{% if FOLD_REPAIR %}// Fold again only where step 0 marked a lane: its first output is NaN. The// K/V arena is unused until the first tile.if (tid == 0u) {var marked = false;{% if FOLD_MARKS %}for (var t: u32 = 0u; t < WG; t = t + 1u) {let markQuery = wg.x * TILE_Q + (t / LPQ){% if QPL > 1 %} * QPL{% endif %};if (markQuery < {{ QSEQ }} && h < Q_HEADS) {let mark = bitcast<u32>({{ FOLD_MARK_BUFFER }}[{{ fold_mark_index("markQuery", "(t % LPQ)") }}].x);marked = marked | ((mark & 0x7fffffffu) > 0x7f800000u);}}{% endif %}v_tile[0] = vec4<{{ ST }}>(select(0.0, 1.0, marked));}workgroupBarrier();if (workgroupUniformLoad(&v_tile[0]).x == 0.0) { return; }{% endif %}{% if useSubgroups %}// The subgroupShuffleXor butterfly requires every LPQ-lane query cluster to// fit in, and align with, one subgroup. Keep a uniform guard for defensive6 unmodified lineslet qSub = tid / LPQ;{% endif %}let lane8 = tid % LPQ;{% if K_SWIZZLE %} let kSwz = (lane8 * {{ K_SWZ }}u) / 8u;{% endif %}{% if V_SWIZZLE %} let vSwz = (lane8 * {{ V_SWZ }}u) / 8u;{% endif %}{% for qi in range(QPL) %}let {{ qn("qIdx", qi) }} = wg.x * TILE_Q + qSub{% if qi > 0 %} + {{ qi }}u{% endif %};let {{ qn("qValid", qi) }} = {{ qn("qIdx", qi) }} < {{ QSEQ }} && h < Q_HEADS;{% endfor %}let hKv = h / (Q_HEADS / KV_HEADS);let SCALE = scale_value();{% if LOOP_VALUES %} // Named query slices and runtime-indexed wide output states are private to each lane.{% else %} // Per-thread q slice and output accumulator, each stored in SLICE named vec4 values.{% endif %}{% for qi in range(QPL) %}let {{ qn("qClamped", qi) }} = min({{ qn("qIdx", qi) }}, {{ QSEQ }} - 1u);{% if QL == "bhsd" %}let {{ qn("qBase4", qi) }} = ((b * Q_HEADS + h) * {{ QSEQ }} + {{ qn("qClamped", qi) }}) * HEAD_DIM_V4 + lane8 * SLICE;2 unmodified lines{% endif %}{% for c in range(SLICE_COUNT) %}var {{ qn("qr" ~ c, qi) }} = vec4<f32>({{ QUERY }}[{{ qn("qBase4", qi) }} + {{ c }}u]);{% if not VALUE_SPLIT and not LOOP_VALUES %} var {{ qn("o" ~ c, qi) }} = {% if NORMALIZED_VALUES %}scaled_value_zero(){% else %}vec4<f32>(0.0){% endif %};{% endif %}{% endfor %}{% if VALUE_SPLIT and not LOOP_VALUES %}{% for c in range(VALUE_SLICE_COUNT) %} var {{ qn("o" ~ c, qi) }} = {% if NORMALIZED_VALUES %}scaled_value_zero(){% else %}vec4<f32>(0.0){% endif %};{% endfor %}{% endif %}{% endfor %}{% if LOOP_VALUES %} var value_out: array<ScaledValue, {{ VALUE_SLICE_COUNT }}>;{% endif %}{% if FUSED_ROTARY %}// The present-cache keys are already rotary transformed. Transform Q once// before the K loop, avoiding a separate full-size Q scratch pass. NeoX39 unmodified lines{% endfor %}{% if useSeqlens %}// Active rows occupy [0, kvActive), independently of the physical KVSEQ stride.// Windowed callers stage resident history plus the new chunk before compaction,// preserving query/key distance. Rotary is excluded from this path because it// needs absolute positions; pastLenForRope keeps the physical length.{% if seqlensQueryFloor | default(true) %}// Cache updates retain the complete appended query chunk.{% else %}// Direct bidirectional queries may outnumber the live key rows.{% endif %}let kvActive = {{ attn_seqlens_bound(KVSEQ, "b", QSEQ if seqlensQueryFloor | default(true) else "") }};{% endif %}// Causal ceiling per query; the key loop runs over the workgroup's union range// (uniform trip count), masking out-of-range (query, key) pairs.4 unmodified lines// windowed, the floor p+1-windowSize. The key loop runs over the workgroup's// union range [wgStart, wgEnd); out-of-range (query,key) pairs mask to NEG_INF.// pastLen = kvSeq - qSeq: query tokens are the last qSeq positions of the cache;// saturate so an invalid qSeq > kvSeq can't underflow u32. Used for the// sliding window always, and for the causal ceiling only when right-aligned.{% if RIGHT or hasWindow %}let pastLen = select(0u, {{ KVA }} - {{ QSEQ }}, {{ KVA }} >= {{ QSEQ }});25 unmodified lines{% for qi in range(QPL) %}let {{ qn("qAbsP1", qi) }} = pastLen + {{ qn("qIdx", qi) }} + 1u;{{ qn("maxKjV", qi) }} = min({{ qn("maxKjV", qi) }}, {{ qn("qAbsP1", qi) }});if ({{ qn("qAbsP1", qi) }} > {{ WINDOW_SIZE }}) { {{ qn("minKjV", qi) }} = {{ qn("qAbsP1", qi) }} - {{ WINDOW_SIZE }}; }{% endfor %}let lastQAbsP1 = pastLen + lastQ + 1u;wgEndV = min(wgEndV, lastQAbsP1);let firstQAbsP1 = pastLen + wg.x * TILE_Q + 1u;if (firstQAbsP1 > {{ WINDOW_SIZE }}) { wgStartV = firstQAbsP1 - {{ WINDOW_SIZE }}; }{% endif %}{% for qi in range(QPL) %}let {{ qn("maxKj", qi) }} = {{ qn("maxKjV", qi) }};11 unmodified lineslet {{ qn("minKj", qi) }} = minKj;{% endfor %}{% endif %}{% if not VALUE_SPLIT %}{% if KL == "bhsd" %}{% if quantCacheFormat == "int4" %}let kvRowStride4 = HEAD_DIM_V4 * 2u;{% else %}4 unmodified lineslet kvBatch4 = b * {{ KVSEQ }} * KV_HIDDEN_V4 + hKv * HEAD_DIM_V4;{% endif %}{% endif %}{% if OFFSET_FOLDS %} var foldExact = true;{% endif %} var kStart: u32 = {{ "keyRangeStart" if MASK_KEY_RANGE else "wgStart" }};loop {if (kStart >= {{ "keyRangeEnd" if MASK_KEY_RANGE else "wgEnd" }}) { break; }{% if VALUE_SPLIT %} // Stage each stream with its own virtual width; the following barrier// publishes both arenas before any query consumes the tile.workgroupBarrier();{% for stream in ["key", "value"] %}{% set isValue = stream == "value" %}{% set dim4 = "VALUE_DIM_V4" if isValue else "HEAD_DIM_V4" %}for (var i: u32 = tid; i < TILE_K * {{ dim4 }}; i = i + WG) {let slot = i / {{ dim4 }};let d4 = i % {{ dim4 }};let kj = kStart + slot;if (kj < wgEnd) {let base4 = ((b * KV_HEADS + hKv) * {{ KVSEQ }} + kj) * {{ dim4 }} + d4;{{ "v_tile" if isValue else "k_tile" }}[i{{ vswz("d4") if isValue else kswz("d4") }}] = vec4<{{ ST }}>(padded_load_{{ stream }}(base4));} else {{{ "v_tile" if isValue else "k_tile" }}[i{{ vswz("d4") if isValue else kswz("d4") }}] = vec4<{{ ST }}>(0.0);}}{% endfor %}{% else %} // Cooperative K/V tile load with out-of-bounds keys zero-filled.workgroupBarrier();for (var i: u32 = tid; i < TILE_K * HEAD_DIM_V4; i = i + WG) {let slot = i / HEAD_DIM_V4;3 unmodified lines{% if KL == "bhsd" %}let base4 = kvBatch4 + kj * kvRowStride4 + d4;{% else %}let base4 = kvBatch4 + {{ KV_ROW }} * KV_HIDDEN_V4 + d4;{% endif %}{% if quantCacheFormat %}k_tile[i{{ kswz("d4") }}] = vec4<{{ ST }}>(load_key4(base4, d4, hKv));v_tile[i{{ vswz("d4") }}] = vec4<{{ ST }}>(load_value4(base4, d4, hKv));{% else %}k_tile[i{{ kswz("d4") }}] = vec4<{{ ST }}>({{ KEY }}[base4]);v_tile[i{{ vswz("d4") }}] = vec4<{{ ST }}>({{ VALUE }}[base4]);{% endif %}} else {k_tile[i{{ kswz("d4") }}] = vec4<{{ ST }}>(0.0);v_tile[i{{ vswz("d4") }}] = vec4<{{ ST }}>(0.0);}}{% endif %}{% if STAGE_MASK %}// The K/V load barrier also publishes this compact mask tile.for (var i: u32 = tid; i < TILE_Q * TILE_K; i = i + WG) {let qSlot = i / TILE_K;10 unmodified lines{% endif %}workgroupBarrier();// TILE_K is a small shader constant; the loop updates the named q/o slices in place.{% if SCORE_KEYS > 1 and COMP_SCORE and not useSubgroups %}// Each query lane reduces one key in the original lane order. Two words// per partial fit half as many keys in the existing workgroup storage.var s: array<f32, TILE_K>;let cbase = tid - lane8;for (var first = 0u; first < TILE_K; first += {{ SCORE_KEYS }}u) {let count = min({{ SCORE_KEYS }}u, TILE_K - first);for (var key = 0u; key < count; key++) {let kb = (first + key) * HEAD_DIM_V4 + lane8 * SLICE;var part = DotAccumulator(0.0, 0.0);{% for c in range(SLICE_COUNT) %} part = score_dot_accumulate4(part, qr{{ c }}, vec4<f32>(k_tile[{{ shared_k_index("kb", c) }}]));{% endfor %} let at = 2u * (key * WG + tid);red[at] = part.hi;red[at + 1u] = part.lo;}workgroupBarrier();if (lane8 < count) {let base = 2u * (lane8 * WG + cbase);var sum = DotAccumulator(0.0, 0.0);for (var lane = 0u; lane < LPQ; lane++) {let at = base + 2u * lane;sum = score_dot_join(sum, DotAccumulator(red[at], red[at + 1u]));}red[base] = dot_value(sum);}workgroupBarrier();for (var key = 0u; key < count; key++) {let kk = first + key;let kj = kStart + kk;s[kk] = NEG_INF;{{ emit_score("red[2u * (key * WG + cbase)]", 0, "qSub") }}}workgroupBarrier();}{% elif COMP_SCORE and not useSubgroups %}var s: array<f32, TILE_K>;var score_parts: array<DotAccumulator, TILE_K>;for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {var local_acc = DotAccumulator(0.0, 0.0);let kb = kk * HEAD_DIM_V4 + lane8 * SLICE;{% for c in range(SLICE_COUNT) %} local_acc = score_dot_accumulate4(local_acc, qr{{ c }}, vec4<f32>(k_tile[{{ shared_k_index("kb", c) }}]));{% endfor %} score_parts[kk] = local_acc;}for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {red[2u * tid] = score_parts[kk].hi;red[2u * tid + 1u] = score_parts[kk].lo;workgroupBarrier();let cbase = tid - lane8;var cluster_acc = DotAccumulator(0.0, 0.0);for (var lane: u32 = 0u; lane < LPQ; lane = lane + 1u) {let at = 2u * (cbase + lane);cluster_acc = score_dot_join(cluster_acc, DotAccumulator(red[at], red[at + 1u]));}workgroupBarrier();s[kk] = NEG_INF;let kj = kStart + kk;{{ emit_score("dot_value(cluster_acc)", 0, "qSub") }}}{% elif not useSubgroups and batchNoSgReduction %}// First publish every key's partial dot without intervening barriers.{% if not SHARE_PROB %}var s: array<f32, TILE_K>;5 unmodified linesvar part: f32 = 0.0;let kb = kk * HEAD_DIM_V4 + lane8 * SLICE;{% for c in range(SLICE_COUNT) %}part = part + dot(qr{{ c }}, vec4<f32>(k_tile[{{ shared_k_index("kb", c) }}]));{% endfor %}red[kk * WG + tid] = part;}7 unmodified lines{% for j in range(LPQ) %}let r{{ j }} = red[kk * WG + cbase + {{ j }}u];{% endfor %}let part = {{ cluster_tree_sum("r", 0, LPQ) }};red[kk * WG + cbase] = part;}workgroupBarrier();11 unmodified lines{% if SHARE_PROB %}s[kk] = NEG_INF;{% endif %}{{ emit_score("part", 0, "qSub") }}}{% if SHARE_PROB %}{{ emit_tile_softmax() }}17 unmodified lineslet kj = kStart + kk;{% for qi in range(QPL) %}{{ qn("s", qi) }}[kk] = NEG_INF;{% if COMP_SCORE %} var {{ qn("part_acc", qi) }} = DotAccumulator(0.0, 0.0);{% else %} var {{ qn("part", qi) }}: f32 = 0.0;{% endif %}{% endfor %}let kb = kk * HEAD_DIM_V4 + lane8 * SLICE;{% for c in range(SLICE_COUNT) %}let kw{{ c }} = vec4<f32>(k_tile[{{ shared_k_index("kb", c) }}]);{% for qi in range(QPL) %}{% if COMP_SCORE %} {{ qn("part_acc", qi) }} = score_dot_accumulate4({{ qn("part_acc", qi) }}, {{ qn("qr" ~ c, qi) }}, kw{{ c }});{% else %} {{ qn("part", qi) }} = {{ qn("part", qi) }} + dot({{ qn("qr" ~ c, qi) }}, kw{{ c }});{% endif %}{% endfor %}{% endfor %}// One butterfly carries every query's partial: the shuffles cost the same// whether the payload is one score or QPL of them.{% if COMP_SCORE %}{% for qi in range(QPL) %}{% for stage in range(log2ceil(LPQ)) %} let {{ qn("score_hi" ~ stage, qi) }} = subgroupShuffleXor({{ qn("part_acc", qi) }}.hi, {{ pow(2, stage) | int }}u);let {{ qn("score_lo" ~ stage, qi) }} = subgroupShuffleXor({{ qn("part_acc", qi) }}.lo, {{ pow(2, stage) | int }}u);{{ qn("part_acc", qi) }} = score_dot_join({{ qn("part_acc", qi) }}, DotAccumulator({{ qn("score_hi" ~ stage, qi) }}, {{ qn("score_lo" ~ stage, qi) }}));{% endfor %}{% endfor %} let partv = vec{{ QPL }}<f32>({% for qi in range(QPL) %}dot_value({{ qn("part_acc", qi) }}){% if not loop.last %}, {% endif %}{% endfor %});{% else %} var partv = vec{{ QPL }}<f32>({% for qi in range(QPL) %}{{ qn("part", qi) }}{% if not loop.last %}, {% endif %}{% endfor %});{{ cluster_shuffle_sum("partv", LPQ) | indent(6, true) }}{% endif %}{{ emit_pair_scores() }}}{% else %}var s: array<f32, TILE_K>;for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let kj = kStart + kk;s[kk] = NEG_INF;{% if COMP_SCORE %} var part_acc = DotAccumulator(0.0, 0.0);{% else %} var part: f32 = 0.0;{% endif %} let kb = kk * HEAD_DIM_V4 + lane8 * SLICE;{% for c in range(SLICE_COUNT) %}{% if COMP_SCORE %} part_acc = score_dot_accumulate4(part_acc, qr{{ c }}, vec4<f32>(k_tile[{{ shared_k_index("kb", c) }}]));{% else %} part = part + dot(qr{{ c }}, vec4<f32>(k_tile[{{ shared_k_index("kb", c) }}]));{% endif %}{% endfor %}{% if COMP_SCORE and useSubgroups %}{% for stage in range(log2ceil(LPQ)) %} let score_hi{{ stage }} = subgroupShuffleXor(part_acc.hi, {{ pow(2, stage) | int }}u);let score_lo{{ stage }} = subgroupShuffleXor(part_acc.lo, {{ pow(2, stage) | int }}u);part_acc = score_dot_join(part_acc, DotAccumulator(score_hi{{ stage }}, score_lo{{ stage }}));{% endfor %} let part = dot_value(part_acc);{% elif useSubgroups %}// log2(LPQ) butterfly all-reduce within the LPQ-lane cluster (each lane ends with the full dot).{{ cluster_shuffle_sum("part", LPQ) | indent(6, true) }}{% else %}red[tid] = part;workgroupBarrier();30 unmodified lines// NaN, the guarded loop selects the V operand away for range-excluded keys.// Interior tiles use the unguarded FMA chain. Mask exclusion applies to// materialized V rows and does not require this range guard.{% if LOOP_VALUES %}{% if SHARE_PROB %}{% macro shared_pv_loop(masked) %}for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let weight = red[kk * WG + cbase];let vb = kk * {{ VALUE_DIM_V4_NAME }} + lane8 * {{ VALUE_SLICE_NAME }};for (var cv: u32 = 0u; cv < {{ VALUE_SLICE_NAME }}; cv = cv + 1u) {value_out[cv] = scaled_value_add(value_out[cv], weight, {% if masked %}select(vec4<f32>(), {% endif %}vec4<f32>(v_tile[{{ shared_v_index("vb", "cv", "") }}]){% if masked %}, kStart + kk >= minKj && kStart + kk < maxKj){% endif %});}}{% endmacro %}for (var cv: u32 = 0u; cv < {{ VALUE_SLICE_NAME }}; cv = cv + 1u) {value_out[cv] = scaled_value_rescale(value_out[cv], corr);}let tileInterior = kStart >= minKj && kStart + TILE_K <= maxKj;if (tileInterior) {{{ shared_pv_loop(false) }}} else {{{ shared_pv_loop(true) }}}{% else %}let tileInterior = (kStart >= minKj && kStart + TILE_K <= maxKj);for (var cv: u32 = 0u; cv < {{ VALUE_SLICE_NAME }}; cv = cv + 1u) {var acc = scaled_value_rescale(value_out[cv], corr);if (tileInterior) {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let vw = vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, "cv", "") }}]);acc = scaled_value_add(acc, s[kk], vw);}} else {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let vw = vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, "cv", "") }}]);acc = scaled_value_add(acc, s[kk], select(vec4<f32>(), vw, kStart + kk >= minKj && kStart + kk < maxKj));}}value_out[cv] = acc;}{% endif %}{% else %}{% if SHARE_PROB %}{% macro shared_pv(masked) %}for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let weight = red[kk * WG + cbase];let vb = kk * {{ VALUE_DIM_V4_NAME }} + lane8 * {{ VALUE_SLICE_NAME }};{% for c in range(VALUE_SLICE_COUNT) %}o{{ c }} = scaled_value_add(o{{ c }}, weight, {% if masked %}select(vec4<f32>(), {% endif %}vec4<f32>(v_tile[{{ shared_v_index("vb", c) }}]){% if masked %}, kStart + kk >= minKj && kStart + kk < maxKj){% endif %});{% endfor %}}{% endmacro %}// Consume each shared probability once across all output slices. This// retains the key order of every output accumulator without a private tile.{% for c in range(VALUE_SLICE_COUNT) %}o{{ c }} = scaled_value_rescale(o{{ c }}, corr);{% endfor %}let tileInterior = kStart >= minKj && kStart + TILE_K <= maxKj;if (tileInterior) {2 unmodified lines{{ shared_pv(true) }}}{% elif QPL > 1 %}{% if OFFSET_FOLDS %}let tileInterior = {% for qi in range(QPL) %}(kStart >= {{ qn("minKj", qi) }} && kStart + TILE_K <= {{ qn("maxKj", qi) }}){% if not loop.last %} && {% endif %}{% endfor %};// Each query's products total at most its probability sum times the largest// value magnitude among the keys either query attends to.{% for c in range(VALUE_SLICE_COUNT) %}{var vHigh = vec4<f32>(0.0);for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let admitted = tileInterior || {% for qi in range(QPL) %}(kStart + kk >= {{ qn("minKj", qi) }} && kStart + kk < {{ qn("maxKj", qi) }}){% if not loop.last %} || {% endif %}{% endfor %};vHigh = max(vHigh, select(vec4<f32>(), abs(vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, c) }}])), admitted));}{% for qi in range(QPL) %}var {{ qn("start", qi) }} = {{ qn("o" ~ c, qi) }};if ({{ qn("corr", qi) }} != 1.0) {let rescaled = scaled_value_rescale_step({{ qn("o" ~ c, qi) }}, {{ qn("corr", qi) }});{{ qn("start", qi) }} = rescaled.value;foldExact = foldExact & rescaled.exact;}let {{ qn("bound", qi) }} = vHigh * {{ qn("pSum", qi) }};var {{ qn("tile", qi) }} = scaled_value_tile({{ qn("bound", qi) }});{% endfor %}if (tileInterior) {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let vw = vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, c) }}]);{% for qi in range(QPL) %}{{ qn("tile", qi) }} = scaled_value_tile_step({{ qn("tile", qi) }}, {{ qn("s", qi) }}[kk], vw);{% endfor %}}} else {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let vw = vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, c) }}]);{% for qi in range(QPL) %}{{ qn("tile", qi) }} = scaled_value_tile_step({{ qn("tile", qi) }}, {{ qn("s", qi) }}[kk], select(vec4<f32>(), vw, kStart + kk >= {{ qn("minKj", qi) }} && kStart + kk < {{ qn("maxKj", qi) }}));{% endfor %}}}{% for qi in range(QPL) %}foldExact = foldExact & scaled_value_tile_in_range({{ qn("start", qi) }}, {{ qn("tile", qi) }}, {{ qn("bound", qi) }}{% if boundValueNumerator | default(false) %}, vHigh{% endif %});{{ qn("o" ~ c, qi) }} = scaled_value_tile_join({{ qn("start", qi) }}, {{ qn("tile", qi) }});{% endfor %}}{% endfor %}{% else %}// Every key of an interior tile is in range, so the guarded form serves both.{% for c in range(VALUE_SLICE_COUNT) %}{% for qi in range(QPL) %}{{ qn("o" ~ c, qi) }} = scaled_value_rescale({{ qn("o" ~ c, qi) }}, {{ qn("corr", qi) }});{% endfor %}for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let vw = vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, c) }}]);{% for qi in range(QPL) %}{{ qn("o" ~ c, qi) }} = scaled_value_add({{ qn("o" ~ c, qi) }}, {{ qn("s", qi) }}[kk], select(vec4<f32>(), vw, kStart + kk >= {{ qn("minKj", qi) }} && kStart + kk < {{ qn("maxKj", qi) }}));{% endfor %}}{% endfor %}{% endif %}{% else %}{% if OFFSET_FOLDS or not NORMALIZED_VALUES %}let tileInterior = kStart >= minKj && kStart + TILE_K <= maxKj;{% endif %}{% for c in range(VALUE_SLICE_COUNT) %}{{% if OFFSET_FOLDS %}// The products total at most the probability sum times the largest// value magnitude among the attended keys.var vHigh = vec4<f32>(0.0);for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {vHigh = max(vHigh, select(vec4<f32>(), abs(vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, c) }}])), kStart + kk >= minKj && kStart + kk < maxKj));}var start = o{{ c }};if (corr != 1.0) {let rescaled = scaled_value_rescale_step(o{{ c }}, corr);start = rescaled.value;foldExact = foldExact & rescaled.exact;}let bound = vHigh * pSum;var tile = scaled_value_tile(bound);if (tileInterior) {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {tile = scaled_value_tile_step(tile, s[kk], vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, c) }}]));}} else {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {tile = scaled_value_tile_step(tile, s[kk], select(vec4<f32>(), vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, c) }}]), kStart + kk >= minKj && kStart + kk < maxKj));}}foldExact = foldExact & scaled_value_tile_in_range(start, tile, bound{% if boundValueNumerator | default(false) %}, vHigh{% endif %});let acc = scaled_value_tile_join(start, tile);{% elif NORMALIZED_VALUES %}// Every key of an interior tile is in range, so the guarded form serves both.var acc = scaled_value_rescale(o{{ c }}, corr);for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {acc = scaled_value_add(acc, s[kk], select(vec4<f32>(), vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, c) }}]), kStart + kk >= minKj && kStart + kk < maxKj));}{% else %}var acc = o{{ c }} * corr;if (tileInterior) {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {acc = acc + s[kk] * vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, c) }}]);}} else {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {acc = acc + s[kk] * select(vec4<f32>(), vec4<f32>(v_tile[{{ shared_v_index("kk * " ~ VALUE_DIM_V4_NAME ~ " + lane8 * " ~ VALUE_SLICE_NAME, c) }}]), kStart + kk >= minKj && kStart + kk < maxKj);}}{% endif %}o{{ c }} = acc;}{% endfor %}{% endif %}{% endif %}kStart = kStart + TILE_K;}{% if OFFSET_FOLDS %}// A non-finite word stays non-finite through every later step, and a// non-finite high word leaves a non-finite low word, so finite final low// words complete each tile's check.foldExact = foldExact & all({% for c in range(VALUE_SLICE_COUNT) %}{% for qi in range(QPL) %}(abs({{ qn("o" ~ c, qi) }}.lo) <= vec4<f32>(3.4028234663852886e38)){% if not loop.last %} & {% endif %}{% endfor %}{% if not loop.last %} & {% endif %}{% endfor %});{% endif %}{% macro output_state(c, qi) %}{% if LOOP_VALUES %}value_out[{{ c }}u]{% else %}{{ qn("o" ~ c, qi) }}{% endif %}{% endmacro %}{% macro value_mean(c, qi, sink=false) %}{% if NORMALIZED_VALUES %}scaled_value_mean({% if sink %}scaled_value_rescale({% endif %}{{ output_state(c, qi) }}{% if sink %}, accScale){% endif %}, {% if sink %}finalDenom{% else %}{{ qn("l", qi) }}{% endif %}){% else %}{{ output_state(c, qi) }}{% endif %}{% endmacro %}{% macro attention_value(c, qi) %}{% if hasHeadSink %}select({% endif %}select({% if NORMALIZED_VALUES %}{{ value_mean(c, qi, hasHeadSink) }}{% else %}{{ output_state(c, qi) }} * inv{% endif %}, vec4<f32>(), zeroSupport){% if hasHeadSink %}, vec4<f32>(bitcast<f32>(sinkBits | 0x00400000u)), !sinkAllowsZero){% endif %}{% endmacro %}{% for qi in range(QPL) %}if ({{ qn("qValid", qi) }}) {{% if QL == "bhsd" %}let outBase4 = ((b * Q_HEADS + h) * {{ QSEQ }} + {{ qn("qIdx", qi) }}) * {{ VALUE_DIM_V4_NAME }} + lane8 * {{ VALUE_SLICE_NAME }};{% else %}let outBase4 = (b * {{ QSEQ }} + {{ qn("qIdx", qi) }}) * Q_HIDDEN_V4 + h * {{ VALUE_DIM_V4_NAME }} + lane8 * {{ VALUE_SLICE_NAME }};{% endif %}{% if hasHeadSink %}// The head sink is a learned logit that competes with the keys but carries3 unmodified lineslet sink = f32(head_sink[h]);let finalM = max({{ qn("m", qi) }}, sink);let accScale = exp({{ qn("m", qi) }} - finalM);let finalDenom = exp(sink - finalM) + {{ qn("l", qi) }} * accScale;{% if not NORMALIZED_VALUES %}let inv = accScale / finalDenom;{% endif %}let denomIsNaN = (bitcast<u32>(finalDenom) & 0x7fffffffu) > 0x7f800000u;let sinkBits = bitcast<u32>(sink);let sinkAllowsZero = (sinkBits & 0x7fffffffu) < 0x7f800000u || sinkBits == 0xff800000u;let zeroSupport = {{ qn("l", qi) }} == 0.0 && !denomIsNaN && sinkAllowsZero;{% else %}// {{ qn("l", qi) }} == 0 means this query had no probability-bearing key: either its// causal/window range is empty or its logical bool mask rejects every key.// Emit 0 rather than 0/0. Other attention paths enforce the same empty-row// contract by selecting on positive global mass.{% if not NORMALIZED_VALUES %}let inv = select(0.0, 1.0 / {{ qn("l", qi) }}, {{ qn("l", qi) }} > 0.0);{% endif %}let zeroSupport = {{ qn("l", qi) }} == 0.0;{% endif %}{% for c in range(VALUE_SLICE_COUNT) %}{{ OUTPUT }}[outBase4 + {{ c }}u] = vec4<{{ scalar }}>({{ attention_value(c, qi) }});{{ "\n" }}{% endfor %}}{% endfor %}{% if OFFSET_FOLDS %}// A lane whose folds left their range marks its own first output for step 1.// u32(foldExact) is zero here; as a non-constant operand it keeps the NaN out// of constant evaluation.if (!foldExact && qValid) {{{ FOLD_MARK_BUFFER }}[{{ fold_mark_index("qIdx", "lane8") }}] = vec4<f32>(bitcast<f32>(0x7fc00000u | u32(foldExact)));}{% endif %}}
123451 unmodified line78910111213141516171819202122232425264 unmodified lines31323334353610 unmodified lines4748495051525354552 unmodified lines585960616263649 unmodified lines747576777879808182838485868788899091921 unmodified line9495969798991001011021031041051061077 unmodified lines11511611711811912012114 unmodified lines13613713813914014114214314414514614714814915015115215315415515615715815916016120 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472484 unmodified lines253254255256257258259// Register-resident flash prefill uses one 32-lane subgroup per workgroup (fixed// by the adapter, or pinned where the adapter can compile exactly 32 lanes). Each// lane owns a query row and keeps its Q slice and f32 output in registers. Lanes// cooperatively load K/V and broadcast them with subgroupShuffle, so each query// computes q·k and p·v without cross-lane reductions or workgroup storage.1 unmodified line// Batch, BHSD layout, grouped heads, and causal key ceilings share one uniform// key-loop bound so subgroup operations stay reconverged. Packed Q/K/V bias// applies Q before attention and V after normalization; key-independent K bias// cancels in softmax. Arbitrary attention masks use the fallback routes.{% set ST = "f16" if usesF16 else "f32" %}{% set components = ["x", "y", "z", "w"] %}{% set USE_SUBGROUPS = useSubgroups if useSubgroups is defined else true %}{% set PIN_SUBGROUP_32 = USE_SUBGROUPS and pinSubgroupSize32 is defined and pinSubgroupSize32 %}{% set Q_STEP = qStep if qStep is defined else 32 %}{% set CAUSAL = false if (hasCausal is defined and not hasCausal) else true %}{% if USE_SUBGROUPS %}enable subgroups;{% endif %}{% if PIN_SUBGROUP_32 %}enable subgroup_size_control;{% endif %}{{ env.wgsl.resourceDeclarations }}const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;const Q_HEADS: u32 = {{ qNumHeads }}u;4 unmodified linesconst KV_HIDDEN_V4: u32 = KV_HEADS * HEAD_DIM_V4;const NEG_INF: f32 = -3.4028234663852886e38;{% if not USE_SUBGROUPS %}// No-subgroup backend: the same one-query-per-lane algorithm broadcasts a// 32-key K/V tile through workgroup memory. The portable fallback can assign10 unmodified linesif (params.scale != 0.0) { return params.scale; }return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));}@compute @workgroup_size({{ Q_STEP }}, 1, 1){{ " @subgroup_size(32)" if PIN_SUBGROUP_32 else "" }}fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>{% if USE_SUBGROUPS %},2 unmodified lines{% endif %}) {{% if USE_SUBGROUPS %}if (sg_size != 32u) { return; }{% else %}let lane = lid.x;{% endif %}9 unmodified lineslet qClamped = min(qi, params.qSeq - 1u);let qBaseV4 = (b * params.qSeq + qClamped) * Q_HIDDEN_V4 + h * HEAD_DIM_V4;var q_tile: array<vec4<{{ ST }}>, HEAD_DIM_V4>;var o_tile: array<vec4<f32>, HEAD_DIM_V4>;for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {if (valid_q) {q_tile[d4] = query[qBaseV4 + d4];} else {q_tile[d4] = vec4<{{ ST }}>(0.0);}o_tile[d4] = vec4<f32>(0.0);}var previous_max: f32 = NEG_INF;var previous_denom: f32 = 0.0;// Causal key ceiling. The key-loop bound (kvEnd) uses the workgroup's LAST query// so every lane shares a uniform trip count (subgroup ops stay reconverged);// each lane masks its own keys past myMaxKj to NEG_INF.1 unmodified line{% set FIXED_CAUSAL = fixedCausal is defined and fixedCausal %}{% macro key_ceiling(query) %}{% if FIXED_CAUSAL %}min({{ query }} + 1u, params.kvSeq){% else %}select(params.kvSeq, min({{ query }} + 1u, params.kvSeq), params.isCausal != 0u){% endif %}{% endmacro %}let lastQ = min(wg.x * Q_STEP + Q_STEP - 1u, params.qSeq - 1u);let kvEnd = {{ key_ceiling("lastQ") }};let myMaxKj = {{ key_ceiling("qi") }};{% else %}let kvEnd = params.kvSeq;let myMaxKj = params.kvSeq;{% endif %}let kvBase = b * params.kvSeq * KV_HIDDEN_V4 + hKv * HEAD_DIM_V4;let kvKeyStride = KV_HIDDEN_V4;7 unmodified lineslet tileOffset = d4 * K_STEP + ki;var kLocal = vec4<{{ ST }}>(0.0);var vLocal = vec4<{{ ST }}>(0.0);if (k_start + ki < params.kvSeq) {let sourceOffset = kvBase + (k_start + ki) * kvKeyStride + d4;kLocal = key[sourceOffset];vLocal = value[sourceOffset];14 unmodified lines{% if kStep == 64 %}var k_local1: vec4<{{ ST }}> = vec4<{{ ST }}>(0.0);{% endif %}if (k_start + sg_id < params.kvSeq) {k_local0 = key[kvBase + (k_start + sg_id) * kvKeyStride + d4];}{% if kStep == 64 %}if (k_start + sg_id + 32u < params.kvSeq) {k_local1 = key[kvBase + (k_start + sg_id + 32u) * kvKeyStride + d4];}{% endif %}{% endif %}{% for g in range(qkGroups) %}{% for lane in range(4) %}{% if USE_SUBGROUPS %}{% if g < 8 %}qk{{ g }}.{{ components[lane] }} = qk{{ g }}.{{ components[lane] }} + f32(dot(q_own, subgroupShuffle(k_local0, {{ g * 4 + lane }}u)));{% else %}qk{{ g }}.{{ components[lane] }} = qk{{ g }}.{{ components[lane] }} + f32(dot(q_own, subgroupShuffle(k_local1, {{ (g - 8) * 4 + lane }}u)));{% endif %}{% else %}qk{{ g }}.{{ components[lane] }} = qk{{ g }}.{{ components[lane] }} + f32(dot(q_own, keyTile[d4 * K_STEP + {{ g * 4 + lane }}u]));{% endif %}{% endfor %}{% endfor %}}20 unmodified lines{% for g in range(qkGroups) %}tile_sum = tile_sum + qk{{ g }}.x + qk{{ g }}.y + qk{{ g }}.z + qk{{ g }}.w;{% endfor %}let dleft = previous_denom * exp(previous_max - new_max);let denom = max(dleft + tile_sum, 0.0000001);let o_ratio = dleft / denom;{% for g in range(qkGroups) %}qk{{ g }} = qk{{ g }} / vec4<f32>(denom);{% endfor %}previous_max = new_max;previous_denom = denom;{% set PV_HALF = ST == "f16" and not (precisePv | default(false)) %}{% set PV_FLUSH_GROUPS = 4 %}{% if PV_HALF %}{% for g in range(qkGroups) %}let p{{ g }} = vec4<f16>(qk{{ g }});{% endfor %}{% endif %}for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {{% if USE_SUBGROUPS %}var v_local0: vec4<{{ ST }}> = vec4<{{ ST }}>(0.0);{% if kStep == 64 %}var v_local1: vec4<{{ ST }}> = vec4<{{ ST }}>(0.0);{% endif %}if (k_start + sg_id < params.kvSeq) {v_local0 = value[kvBase + (k_start + sg_id) * kvKeyStride + d4];}{% if kStep == 64 %}if (k_start + sg_id + 32u < params.kvSeq) {v_local1 = value[kvBase + (k_start + sg_id + 32u) * kvKeyStride + d4];}{% endif %}{% endif %}{% if PV_HALF %}var acc_f32: vec4<f32> = vec4<f32>(0.0);var acc: vec4<f16> = vec4<f16>(0.0);{% else %}var acc: vec4<f32> = vec4<f32>(0.0);{% endif %}{% for g in range(qkGroups) %}{% for lane in range(4) %}{% if not USE_SUBGROUPS %}{% set pvValue = "valueTile[d4 * K_STEP + " ~ (g * 4 + lane) ~ "u]" %}{% elif g < 8 %}{% set pvValue = "subgroupShuffle(v_local0, " ~ (g * 4 + lane) ~ "u)" %}{% else %}{% set pvValue = "subgroupShuffle(v_local1, " ~ ((g - 8) * 4 + lane) ~ "u)" %}{% endif %}{% if PV_HALF %}acc = fma({{ pvValue }}, vec4<f16>(p{{ g }}.{{ components[lane] }}), acc);{% else %}acc = acc + vec4<f32>({{ pvValue }}) * qk{{ g }}.{{ components[lane] }};{% endif %}{% endfor %}{% if PV_HALF and (g + 1) % PV_FLUSH_GROUPS == 0 %}acc_f32 = acc_f32 + vec4<f32>(acc);acc = vec4<f16>(0.0);{% endif %}{% endfor %}{% if PV_HALF %}o_tile[d4] = o_tile[d4] * vec4<f32>(o_ratio) + acc_f32;{% else %}o_tile[d4] = o_tile[d4] * vec4<f32>(o_ratio) + acc;{% endif %}}{% if not USE_SUBGROUPS %}4 unmodified linesif (valid_q) {let outBaseV4 = (b * params.qSeq + qi) * Q_HIDDEN_V4 + h * HEAD_DIM_V4;for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {output[outBaseV4 + d4] = vec4<{{ scalar }}>(o_tile[d4]);}}}123456781 unmodified line1011121314151617181920212223242526272829303132334 unmodified lines38394041424344454647484950515253545556575859606162636465666710 unmodified lines787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844852 unmodified lines4884894904914924934944954964974989 unmodified lines5085095105115125135145155165175185195205215225235245255265275281 unmodified line5305315325335345355365375385395405415425437 unmodified lines55155255355455555655714 unmodified lines57257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260320 unmodified lines6246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057064 unmodified lines711712713714715716717{% macro qk_dot(q, k, precise) %}{% if precise %}dot(vec4<f32>({{ q }}), vec4<f32>({{ k }})){% else %}f32(dot({{ q }}, {{ k }})){% endif %}{% endmacro %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {% if queryFloor %}max({{ queryFloor }}, {{ attn_seqlens_count(index) }}){% else %}{{ attn_seqlens_count(index) }}{% endif %}){% endmacro %}// Register-resident flash prefill uses one 32-lane subgroup per workgroup (fixed// by the adapter, or requested where the adapter can compile exactly 32 lanes). Each// lane owns a query row and keeps its Q slice and f32 output in registers. Lanes// cooperatively load K/V and broadcast them with subgroupShuffle, so each query// computes q·k and p·v without cross-lane reductions or workgroup storage.1 unmodified line// Batch, BHSD layout, grouped heads, and causal key ceilings share one uniform// key-loop bound so subgroup operations stay reconverged. Packed Q/K/V bias// applies Q before attention and V after normalization; key-independent K bias// cancels in softmax. Arbitrary attention masks use the fallback variants.{% set ST = "f16" if usesF16 else "f32" %}{% set components = ["x", "y", "z", "w"] %}{% macro lane_word(src, lane, st) %}{% if st == "f16" %}bitcast<vec4<f16>>(subgroupShuffle(bitcast<vec2<u32>>({{ src }}), {{ lane }}u)){% else %}subgroupShuffle({{ src }}, {{ lane }}u){% endif %}{% endmacro %}{% set USE_SUBGROUPS = useSubgroups if useSubgroups is defined else true %}{% set PIN_SUBGROUP_32 = USE_SUBGROUPS and pinSubgroupSize32 is defined and pinSubgroupSize32 %}{% set PIN_WIDTH = 32 if PIN_SUBGROUP_32 else ((sharedSubgroupWidth | default(0)) if not USE_SUBGROUPS else 0) %}{% set Q_STEP = qStep if qStep is defined else 32 %}{% set CAUSAL = false if (hasCausal is defined and not hasCausal) else true %}{% if USE_SUBGROUPS or PIN_WIDTH > 0 %}enable subgroups;{% endif %}{% if PIN_WIDTH > 0 %}enable subgroup_size_control;{% endif %}{{ env.wgsl.resourceDeclarations }}{% macro key_word(group, lane) %}{% if USE_SUBGROUPS %}k_broadcast{{ group }}_{{ lane }}{% else %}keyTile[d4 * K_STEP + {{ group * 4 + lane }}u]{% endif %}{% endmacro %}{% macro ordinary_score(group, lane) %} qk{{ group }}.{{ components[lane] }} = qk{{ group }}.{{ components[lane] }} + {{ qk_dot("q_own", key_word(group, lane), preciseQk | default(false)) }};{% endmacro %}const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;const Q_HEADS: u32 = {{ qNumHeads }}u;4 unmodified linesconst KV_HIDDEN_V4: u32 = KV_HEADS * HEAD_DIM_V4;const NEG_INF: f32 = -3.4028234663852886e38;{% if USE_SUBGROUPS %}// One entry-point proof for algorithms that assign data using local-ID lane// blocks. Every subgroup checks all active members; the workgroup accepts only// when every subgroup has a valid complete layout. Call once in uniform flow.// The rejection flag starts zero through WGSL workgroup initialization.// Some Adreno 6xx drivers cannot create a pipeline that calls subgroupAll; a ballot builds wherever subgroups do.// A subgroup is valid when no active member is invalid. That is subgroupAll, expressed as a ballot so the shader// does not depend on subgroupAll.var<workgroup> subgroupLocalLayoutRejected: atomic<u32>;var<workgroup> subgroupLocalLayoutAcceptedState: u32;fn subgroupLocalLayoutAccepted(localIndex: u32, memberValid: bool) -> bool {let valid = all(subgroupBallot(!memberValid) == vec4<u32>(0u));if (subgroupElect() && !valid) {atomicStore(&subgroupLocalLayoutRejected, 1u);}workgroupBarrier();if (localIndex == 0u) {subgroupLocalLayoutAcceptedState = select(0u, 1u, atomicLoad(&subgroupLocalLayoutRejected) == 0u);}return workgroupUniformLoad(&subgroupLocalLayoutAcceptedState) != 0u;}{% endif %}{% if not USE_SUBGROUPS %}// No-subgroup backend: the same one-query-per-lane algorithm broadcasts a// 32-key K/V tile through workgroup memory. The portable fallback can assign10 unmodified linesif (params.scale != 0.0) { return params.scale; }return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));}{% if ST == "f32" %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&{% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &{% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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 }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("vec4<f32>", rescale=true, merge=true) }}{% endif %}@compute @workgroup_size({{ Q_STEP }}, 1, 1){{ " @subgroup_size(" ~ PIN_WIDTH ~ ")" if PIN_WIDTH > 0 else "" }}fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>{% if USE_SUBGROUPS %},2 unmodified lines{% endif %}) {{% if USE_SUBGROUPS %}let populationMask = subgroupBallot(true);let population = countOneBits(populationMask.x) + countOneBits(populationMask.y)+ countOneBits(populationMask.z) + countOneBits(populationMask.w);let nativeBroadcastLayout = subgroupLocalLayoutAccepted(lid.x,sg_size == 32u && population == 32u);{% else %}let lane = lid.x;{% endif %}9 unmodified lineslet qClamped = min(qi, params.qSeq - 1u);let qBaseV4 = (b * params.qSeq + qClamped) * Q_HIDDEN_V4 + h * HEAD_DIM_V4;var q_tile: array<vec4<{{ ST }}>, HEAD_DIM_V4>;var o_tile: array<{{ "ScaledValue" if ST == "f32" else "vec4<f32>" }}, HEAD_DIM_V4>;for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {if (valid_q) {q_tile[d4] = query[qBaseV4 + d4];} else {q_tile[d4] = vec4<{{ ST }}>(0.0);}o_tile[d4] = {% if ST == "f32" %}scaled_value_zero(){% else %}vec4<f32>(0.0){% endif %};}var previous_max: f32 = NEG_INF;var previous_denom: f32 = 0.0;let kvActive = {{ attn_seqlens_bound("params.kvSeq", "b", "params.qSeq" if seqlensQueryFloor | default(false) else "") }};{% set KVA = "kvActive" %}// Causal key ceiling. The key-loop bound (kvEnd) uses the workgroup's LAST query// so every lane shares a uniform trip count (subgroup ops stay reconverged);// each lane masks its own keys past myMaxKj to NEG_INF.1 unmodified line{% set FIXED_CAUSAL = fixedCausal is defined and fixedCausal %}{% macro key_ceiling(query) %}{% if FIXED_CAUSAL %}min({{ query }} + 1u, {{ KVA }}){% else %}select({{ KVA }}, min({{ query }} + 1u, {{ KVA }}), params.isCausal != 0u){% endif %}{% endmacro %}let lastQ = min(wg.x * Q_STEP + Q_STEP - 1u, params.qSeq - 1u);let kvEnd = {{ key_ceiling("lastQ") }};let myMaxKj = {{ key_ceiling("qi") }};{% else %}let kvEnd = {{ KVA }};let myMaxKj = {{ KVA }};{% endif %}let kvBase = b * params.kvSeq * KV_HIDDEN_V4 + hKv * HEAD_DIM_V4;let kvKeyStride = KV_HIDDEN_V4;7 unmodified lineslet tileOffset = d4 * K_STEP + ki;var kLocal = vec4<{{ ST }}>(0.0);var vLocal = vec4<{{ ST }}>(0.0);if (k_start + ki < {{ KVA }}) {let sourceOffset = kvBase + (k_start + ki) * kvKeyStride + d4;kLocal = key[sourceOffset];vLocal = value[sourceOffset];14 unmodified lines{% if kStep == 64 %}var k_local1: vec4<{{ ST }}> = vec4<{{ ST }}>(0.0);{% endif %}k_local0 = select(vec4<{{ ST }}>(0.0),key[kvBase + min(k_start + sg_id, {{ KVA }} - 1u) * kvKeyStride + d4],k_start + sg_id < {{ KVA }});{% if kStep == 64 %}k_local1 = select(vec4<{{ ST }}>(0.0),key[kvBase + min(k_start + sg_id + 32u, {{ KVA }} - 1u) * kvKeyStride + d4],k_start + sg_id + 32u < {{ KVA }});{% endif %}{% endif %}{% for g in range(qkGroups) %}{% for lane in range(4) %}{% if USE_SUBGROUPS %}var k_broadcast{{ g }}_{{ lane }} = vec4<{{ ST }}>(0.0);if (nativeBroadcastLayout) {{% if g < 8 %}k_broadcast{{ g }}_{{ lane }} = {{ lane_word("k_local0", g * 4 + lane, ST) }};{% else %}k_broadcast{{ g }}_{{ lane }} = {{ lane_word("k_local1", (g - 8) * 4 + lane, ST) }};{% endif %}} else {if (k_start + {{ g * 4 + lane }}u < {{ KVA }}) {k_broadcast{{ g }}_{{ lane }} = key[kvBase + (k_start + {{ g * 4 + lane }}u) * kvKeyStride + d4];}}{% endif %}{{ ordinary_score(g, lane) }}{% endfor %}{% endfor %}}20 unmodified lines{% for g in range(qkGroups) %}tile_sum = tile_sum + qk{{ g }}.x + qk{{ g }}.y + qk{{ g }}.z + qk{{ g }}.w;{% endfor %}{% if ST == "f32" %}let previous_scale = exp(previous_max - new_max);let dleft = previous_denom * previous_scale;{% else %} let dleft = previous_denom * exp(previous_max - new_max);{% endif %}let denom = max(dleft + tile_sum, 0.0000001);{% if ST != "f32" %} let o_ratio = dleft / denom;{% for g in range(qkGroups) %}qk{{ g }} = qk{{ g }} / vec4<f32>(denom);{% endfor %}{% endif %}previous_max = new_max;previous_denom = denom;{% if ST == "f32" %}// Keep the qk group/component order without replicating the// complete scaled-value helper at every statically expanded PV call site.var pv_weights: array<vec4<f32>, {{ qkGroups }}>;{% for g in range(qkGroups) %}pv_weights[{{ g }}u] = qk{{ g }};{% endfor %}{% endif %}for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {{% if USE_SUBGROUPS %}var v_local0: vec4<{{ ST }}> = vec4<{{ ST }}>(0.0);{% if kStep == 64 %}var v_local1: vec4<{{ ST }}> = vec4<{{ ST }}>(0.0);{% endif %}v_local0 = select(vec4<{{ ST }}>(0.0),value[kvBase + min(k_start + sg_id, {{ KVA }} - 1u) * kvKeyStride + d4],k_start + sg_id < {{ KVA }});{% if kStep == 64 %}v_local1 = select(vec4<{{ ST }}>(0.0),value[kvBase + min(k_start + sg_id + 32u, {{ KVA }} - 1u) * kvKeyStride + d4],k_start + sg_id + 32u < {{ KVA }});{% endif %}{% endif %}var acc{% if ST != "f32" %}: vec4<f32>{% endif %} = {% if ST == "f32" %}scaled_value_zero(){% else %}vec4<f32>(0.0){% endif %};{% if ST == "f32" %}for (var ki: u32 = 0u; ki < K_STEP; ki = ki + 1u) {var v_broadcast = vec4<f32>(0.0);if (nativeBroadcastLayout) {let v_local = select(v_local0, v_local1, ki >= 32u);v_broadcast = subgroupShuffle(v_local, ki & 31u);} else {if (k_start + ki < {{ KVA }}) {v_broadcast = value[kvBase + (k_start + ki) * kvKeyStride + d4];}}acc = scaled_value_add(acc, pv_weights[ki / 4u][ki % 4u], v_broadcast);}{% else %}{% for g in range(qkGroups) %}{% for lane in range(4) %}{% if not USE_SUBGROUPS %}{% set pvValue = "valueTile[d4 * K_STEP + " ~ (g * 4 + lane) ~ "u]" %}{% else %}var v_broadcast{{ g }}_{{ lane }} = vec4<{{ ST }}>(0.0);if (nativeBroadcastLayout) {{% if g < 8 %}v_broadcast{{ g }}_{{ lane }} = {{ lane_word("v_local0", g * 4 + lane, ST) }};{% else %}v_broadcast{{ g }}_{{ lane }} = {{ lane_word("v_local1", (g - 8) * 4 + lane, ST) }};{% endif %}} else {if (k_start + {{ g * 4 + lane }}u < {{ KVA }}) {v_broadcast{{ g }}_{{ lane }} = value[kvBase + (k_start + {{ g * 4 + lane }}u) * kvKeyStride + d4];}}{% set pvValue = "v_broadcast" ~ g ~ "_" ~ lane %}{% endif %}acc = acc + vec4<f32>({{ pvValue }}) * qk{{ g }}.{{ components[lane] }};{% endfor %}{% endfor %}{% endif %}{% if ST == "f32" %}o_tile[d4] = scaled_value_merge(scaled_value_rescale(o_tile[d4], previous_scale), acc);{% else %} o_tile[d4] = o_tile[d4] * vec4<f32>(o_ratio) + acc;{% endif %}}{% if not USE_SUBGROUPS %}4 unmodified linesif (valid_q) {let outBaseV4 = (b * params.qSeq + qi) * Q_HIDDEN_V4 + h * HEAD_DIM_V4;for (var d4: u32 = 0u; d4 < HEAD_DIM_V4; d4 = d4 + 1u) {output[outBaseV4 + d4] = vec4<{{ scalar }}>({% if ST == "f32" %}scaled_value_mean(o_tile[d4], previous_denom){% else %}o_tile[d4]{% endif %});}}}
11 unmodified lines12131415161718192021222328 unmodified lines5253545556575811 unmodified lines// `maxOnly` means the producer published only a row max per slot because// computing the denominator there would double the exp count. Fold maxima and// leave the denominator to the apply pass, which sees every row element anyway.{% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) { return; }{% endmacro %}{{ env.wgsl.resourceDeclarations }}const SLOTS: u32 = {{ statSlots }}u;28 unmodified linesfn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d("WG", "row", "params.rows", guardInline=true) }}// `row` already runs over (batch, head, query) together, and the partial// layout puts that same product one axis out from the slot, so the stride11 unmodified lines12131415161718192021222324252628 unmodified lines5556575859606111 unmodified lines// `maxOnly` means the producer published only a row max per slot because// computing the denominator there would double the exp count. Fold maxima and// leave the denominator to the apply pass, which sees every row element anyway.{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) {return;}{% endmacro %}{{ env.wgsl.resourceDeclarations }}const SLOTS: u32 = {{ statSlots }}u;28 unmodified linesfn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d("WG", "row", "params.rows") }}// `row` already runs over (batch, head, query) together, and the partial// layout puts that same product one axis out from the slot, so the stride
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295{% set STORAGE_F16 = false %}{% set QUERY_CHUNKED = false %}{{ env.wgsl.resourceDeclarations }}{% set COMP_SCORE = true %}{% set scoreGuardDeferred = COMP_SCORE and (deferNativeScoreGuard | default(false)) %}{%- set LIVE_KEYS = "liveKeys" %}{% macro score_type() %}DotAccumulator{% endmacro %}{% macro score_init() %}DotAccumulator(0.0, 0.0){% endmacro %}{% macro score_step(acc, query, key) %}{{ acc }} = score_dot_accumulate4({{ acc }}, {{ query }}, {{ key }});{% endmacro %}{% macro score_value(acc, key) %}{% if scoreGuardDeferred %}finish_score({{ acc }}, b, h, hKv, qi, {{ key }}){% else %}dot_value({{ acc }}){% endif %}{% endmacro %}{% macro mask_future_key(key) %}{% endmacro %}{% set dotGuardNonfinite = true %}{% set dotType = "f32" %}// Retain product and addition residuals across a dot product. Explicit fma// boundaries preserve the addition error transform under reassociation.struct DotAccumulator { hi: {{ dotType }}, lo: {{ dotType }},}{% if dotRecoverProductResidual | default(false) %}{% set dotBitsType = "u32" %}// Recover an inexact product when a backend returns a zero fma residual.{% set dotExponentType = "i32" %}{% macro dot_parts() -%}let aBits = bitcast<{{ dotBitsType }}>(a);let bBits = bitcast<{{ dotBitsType }}>(b);let pBits = bitcast<{{ dotBitsType }}>(product);let ae = (aBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let be = (bBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let pe = (pBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);{% endmacro %}fn dot_product_error(a: {{ dotType }}, b: {{ dotType }}, product: {{ dotType }}) -> {{ dotType }} { // Twelve-bit significand parts make each split product exactly representable. let nativeError = fma(a, b, -product); if (nativeError == 0.0) {{{ dot_parts() | indent(4, true) }} let lowProduct = (((aBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u)) * ((bBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u))) & {{ dotBitsType }}(0x00ffffffu); let recover = (nativeError == {{ dotType }}(0.0)) && (lowProduct != {{ dotBitsType }}(0u)) && (ae > {{ dotBitsType }}(0u)) && (ae < {{ dotBitsType }}(255u)) && (be > {{ dotBitsType }}(0u)) && (be < {{ dotBitsType }}(255u)) && (pe > {{ dotBitsType }}(0u)) && (pe < {{ dotBitsType }}(255u)); if (recover) { // Normalize before splitting: a normal input can otherwise produce a // subnormal low word that a conformant backend is allowed to flush. let an = bitcast<{{ dotType }}>((aBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u)); let bn = bitcast<{{ dotType }}>((bBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u)); let exponent = select({{ dotExponentType }}(0), {{ dotExponentType }}(ae) + {{ dotExponentType }}(be) - {{ dotExponentType }}(254), recover); let pnExponent = select({{ dotBitsType }}(127u), {{ dotBitsType }}({{ dotExponentType }}(pe) - exponent), recover); let pn = bitcast<{{ dotType }}>((pBits & {{ dotBitsType }}(0x807fffffu)) | (pnExponent << {{ dotBitsType }}(23u))); let ah = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(an) & {{ dotBitsType }}(0xfffff000u)); let bh = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(bn) & {{ dotBitsType }}(0xfffff000u)); let al = fma({{ dotType }}(-1.0), ah, an); let bl = fma({{ dotType }}(-1.0), bh, bn); let e0 = fma(ah, bh, -pn); let e1 = fma(al, bh, e0); let e2 = fma(ah, bl, e1); let recovered = ldexp(fma(al, bl, e2), exponent); return select(nativeError, recovered, recover); } } return nativeError;}{% endif %}{% macro dot_step(name, dotGuardNonfinite) %}fn {{ name }}(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator { let product = fma(a, b, {{ dotType }}(0.0));{% if dotGuardNonfinite | default(false) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product); // Nonfinite sums retain ordinary f32 addition classes; Inf-Inf residuals // must not poison a valid infinite dot accumulator. if (!(abs(acc.hi) <= 3.4028234663852886e38) || !(abs(acc.lo) <= 3.4028234663852886e38) || !(abs(product) <= 3.4028234663852886e38) || !(abs(sum) <= 3.4028234663852886e38)) { return DotAccumulator(sum, {{ dotType }}(0.0)); }{% endif %} let productError = {% if dotRecoverProductResidual | default(false) %}dot_product_error(a, b, product){% else %}fma(a, b, -product){% endif %};{% if not (dotGuardNonfinite | default(false)) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);{% endif %} let bv = fma({{ dotType }}(-1.0), acc.hi, sum); let av = fma({{ dotType }}(-1.0), bv, sum); let ae = fma({{ dotType }}(-1.0), av, acc.hi); let be = fma({{ dotType }}(-1.0), bv, product); let error = fma(fma(fma(ae, {{ dotType }}(1.0), be), {{ dotType }}(1.0), acc.lo), {{ dotType }}(1.0), productError); let hi = fma(sum, {{ dotType }}(1.0), error);{% if dotGuardNonfinite | default(false) %} if (!(abs(hi) <= 3.4028234663852886e38)) { return DotAccumulator(hi, {{ dotType }}(0.0)); }{% endif %} return DotAccumulator(hi, fma({{ dotType }}(-1.0), fma({{ dotType }}(-1.0), sum, hi), error));}{% endmacro %}{{ dot_step("dot_accumulate", dotGuardNonfinite | default(false)) }}{% if scoreGuardDeferred | default(false) %}// Dot2 (Ogita, Rump and Oishi) for the deferred-guard fast path: the running sum and// the accumulated product and addition residuals stay apart, so no step renormalizes// them and Knuth's TwoSum needs no magnitude ordering; dot_value adds them once. Its// error bound matches the renormalizing form, u|dot| + gamma_n^2 sum|a b|. A nonfinite// running sum leaves a nonfinite word, which finish_score replays with guards.fn dot_accumulate_finite(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator { let product = fma(a, b, {{ dotType }}(0.0)); // Deferred guards are only enabled where the native fma residual is trusted. let productError = fma(a, b, -product); let sum = fma(acc.hi, {{ dotType }}(1.0), product); let bv = fma({{ dotType }}(-1.0), acc.hi, sum); let av = fma({{ dotType }}(-1.0), bv, sum); let addError = fma(fma({{ dotType }}(-1.0), av, acc.hi), {{ dotType }}(1.0), fma({{ dotType }}(-1.0), bv, product)); return DotAccumulator(sum, fma(addError, {{ dotType }}(1.0), fma(acc.lo, {{ dotType }}(1.0), productError)));}{% endif %}fn dot_value(acc: DotAccumulator) -> {{ dotType }} { return fma(acc.hi, {{ dotType }}(1.0), acc.lo);}fn score_dot_accumulate4(acc: DotAccumulator, q: vec4<f32>, k: vec4<f32>) -> DotAccumulator { var next = acc;{% for component in ["x", "y", "z", "w"] %} next = {{ "dot_accumulate_finite" if scoreGuardDeferred | default(false) else "dot_accumulate" }}(next, q.{{ component }}, k.{{ component }});{% endfor %} return next;}
// f32 prefill score GEMM with BHSD and packed BSH specializations. It computes// the score matrix as a 64x64 register-blocked product. Q and K are both stored row-major in the head// dimension — the axis this GEMM reduces over — so both tiles group four of// its values per vector word, every staging read is contiguous, and the// micro-tile reuses TM + TN vector words for TM * TN component dots.// Callers can retain product and addition residuals. K keeps a one-word shared stride// padding, which changes the transposed workgroup-memory stride and reduces// bank-conflict risk on banked implementations.{% if scalarAccumulators is not defined %}{% set scalarAccumulators = false %}{% endif %}{% if scalarAccumulators %}{% set TM_JINJA = (materializedQueryTile / materializedWorkgroupDim)|int %}{% set TN_JINJA = (materializedKeyTile / materializedWorkgroupDim)|int %}{% endif %}
const Q_HEADS: u32 = {{ qNumHeads }}u;const KV_HEADS: u32 = {{ kvNumHeads }}u;const HEAD_DIM: u32 = {{ headDim }}u;const Q_HIDDEN: u32 = Q_HEADS * HEAD_DIM;const KV_HIDDEN: u32 = KV_HEADS * HEAD_DIM;
const BK: u32 = {{ materializedInnerTile }}u;const BM: u32 = {{ materializedQueryTile }}u;const BN: u32 = {{ materializedKeyTile }}u;const WG_DIM: u32 = {{ materializedWorkgroupDim }}u;const WG_THREADS: u32 = WG_DIM * WG_DIM;const TM: u32 = BM / WG_DIM;const TN: u32 = BN / WG_DIM;const D_VECS: u32 = BK / 4u;
var<workgroup> tileQ: array<array<vec4<f32>, D_VECS>, BM>;var<workgroup> tileK: array<array<vec4<f32>, D_VECS + 1u>, BN>;
{% set ATTN_SCALE_DIM = "HEAD_DIM" %}fn scale_value() -> f32 { if (params.scale != 0.0) { return params.scale; } return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));}
fn q_at(b: u32, h: u32, q: u32, d: u32) -> f32 { var value = {{ "f32(" if STORAGE_F16 else "" }}query[(b * {{ "params.fullQSeq" if QUERY_CHUNKED else "params.qSeq" }} + {{ "params.qOffset + q" if QUERY_CHUNKED else "q" }}) * Q_HIDDEN + h * HEAD_DIM + d]{{ ")" if STORAGE_F16 else "" }}; return value;}
fn k_at(b: u32, h: u32, k: u32, d: u32) -> f32 { return {{ "f32(" if STORAGE_F16 else "" }}key[(b * params.kvSeq + k) * KV_HIDDEN + h * HEAD_DIM + d]{{ ")" if STORAGE_F16 else "" }};}
{% if scoreGuardDeferred %}// A nonfinite product or sum poisons the compensation residual. Repeat just// that score with per-component guards to preserve ordinary f32 infinities.fn finish_score(acc: DotAccumulator, batch: u32, head: u32, kvHead: u32, q: u32, k: u32) -> f32 { let exponent = 0x7f800000u; if ((bitcast<u32>(acc.hi) & exponent) != exponent && (bitcast<u32>(acc.lo) & exponent) != exponent) { return dot_value(acc); } var replay = DotAccumulator(0.0, 0.0); for (var d = 0u; d < HEAD_DIM; d++) { replay = dot_accumulate(replay, q_at(batch, head, q, d), k_at(batch, kvHead, k, d)); } return dot_value(replay);}
{% endif %}@compute @workgroup_size(WG_DIM, WG_DIM, 1)fn main( @builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) { let h = wg.z % Q_HEADS; let b = wg.z / Q_HEADS; let hKv = h / (Q_HEADS / KV_HEADS); let qBase = wg.y * BM; let kBase = wg.x * BN;{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {{ attn_seqlens_count(index) }}){% endmacro %} let liveKeys = {{ attn_seqlens_bound("params.kvSeq", "b") }}; // Softmax and the value product also skip this padding, so these tiles need no score writes. if (kBase >= liveKeys) { return; }{% if repairScoreTiles | default(false) %} let tileIndex = (wg.z * ((params.qSeq + BM - 1u) / BM) + wg.y) * ((params.kvSeq + BN - 1u) / BN) + wg.x; if (repair[tileIndex] == 0u) { return; }{% endif %} let li = lid.y * WG_DIM + lid.x;
{% if scalarAccumulators %} // Keep every register-tile cell statically addressable.{% for i in range(TM_JINJA) %}{% for j in range(TN_JINJA) %} var acc{{ i }}_{{ j }}: {{ score_type() }} = {{ score_init() }};{% endfor %}{% endfor %}{% else %} var acc: array<{{ score_type() }}, TM * TN>; for (var i = 0u; i < TM * TN; i = i + 1u) { acc[i] = {{ score_init() }}; }{% endif %}
for (var dBase = 0u; dBase < HEAD_DIM; dBase = dBase + BK) { // Both source tiles are loaded in their physical row-major direction. // Each lane stages whole vector words: four adjacent head dimensions of one // query row and of one key row, both contiguous in their source tensor. for (var linear = li; linear < BM * D_VECS; linear += WG_THREADS) { let qr = linear / D_VECS; let qv4 = linear % D_VECS; let qi = qBase + qr; let d = dBase + qv4 * 4u; let qLive = qi < params.qSeq; tileQ[qr][qv4] = vec4<f32>({% for component in range(4) %} select(0.0, q_at(b, h, qi, d + {{ component }}u), qLive && d + {{ component }}u < HEAD_DIM){% if not loop.last %},{% endif %}{% endfor %} ); } for (var linear = li; linear < BN * D_VECS; linear += WG_THREADS) { let kr = linear / D_VECS; let kv4 = linear % D_VECS; let ki = kBase + kr; let kdim = dBase + kv4 * 4u; let kLive = ki < {{ LIVE_KEYS }}; tileK[kr][kv4] = vec4<f32>({% for component in range(4) %} select(0.0, k_at(b, hKv, ki, kdim + {{ component }}u), kLive && kdim + {{ component }}u < HEAD_DIM){% if not loop.last %},{% endif %}{% endfor %} ); } workgroupBarrier();
let qr0 = lid.y * TM; let kc0 = lid.x * TN; for (var dv = 0u; dv < D_VECS; dv = dv + 1u) {{% if scalarAccumulators %}{% for i in range(TM_JINJA) %} let qv{{ i }} = tileQ[qr0 + {{ i }}u][dv];{% endfor %}{% for j in range(TN_JINJA) %} let kv{{ j }} = tileK[kc0 + {{ j }}u][dv];{% endfor %}{% for i in range(TM_JINJA) %}{% for j in range(TN_JINJA) %} {{ score_step("acc" ~ i ~ "_" ~ j, "qv" ~ i, "kv" ~ j) }}{% endfor %}{% endfor %}{% else %} var qv: array<vec4<f32>, TM>; var kv: array<vec4<f32>, TN>; for (var i = 0u; i < TM; i = i + 1u) { qv[i] = tileQ[qr0 + i][dv]; } for (var j = 0u; j < TN; j = j + 1u) { kv[j] = tileK[kc0 + j][dv]; } for (var i = 0u; i < TM; i = i + 1u) { for (var j = 0u; j < TN; j = j + 1u) { {{ score_step("acc[i * TN + j]", "qv[i]", "kv[j]") }} } }{% endif %} } workgroupBarrier(); }
let qi0 = qBase + lid.y * TM; let ki0 = kBase + lid.x * TN; let scoreBase = wg.z * params.qSeq * params.kvSeq; let scale = scale_value();{% if scalarAccumulators %}{% for i in range(TM_JINJA) %} { let qi = qi0 + {{ i }}u; if (qi < params.qSeq) {{% for j in range(TN_JINJA) %} let ki{{ j }} = ki0 + {{ j }}u; if (ki{{ j }} < {{ LIVE_KEYS }}) { var score = {{ score_value("acc" ~ i ~ "_" ~ j, "ki" ~ j) }} * scale;{{ mask_future_key("ki" ~ j) }} scores[scoreBase + qi * params.kvSeq + ki{{ j }}] = score; }{% endfor %} } }{% endfor %}{% else %} for (var i = 0u; i < TM; i = i + 1u) { let qi = qi0 + i; if (qi >= params.qSeq) { continue; } for (var j = 0u; j < TN; j = j + 1u) { let ki = ki0 + j; if (ki < {{ LIVE_KEYS }}) { var score = {{ score_value("acc[i * TN + j]", "ki") }} * scale;{{ mask_future_key("ki") }} scores[scoreBase + qi * params.kvSeq + ki] = score; } } }{% endif %}
}123459 unmodified lines1516171819202122232425262728293031325 unmodified lines383940414243444546474849505152535455565758596061626364656667688 unmodified lines777879808182838411 unmodified lines9697989910010110217 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471486 unmodified lines1551561571581591601619 unmodified lines1711721731741751761771781791801811821831841851861871881891901911921931941951961971981994 unmodified lines2042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452466 unmodified lines2532542552562572582592602612622632642 unmodified lines2672682692702712722735 unmodified lines2792802812822832842852862872882892902912922932942952962972982993003015 unmodified lines3073083093103113123133143153163173183193203213223233243253264 unmodified lines3313323333343353363373383393403413423433443453463472 unmodified lines35035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240312 unmodified lines41641741841942042142242342442542642710 unmodified lines4384394404414424434444454468 unmodified lines4554564574584594604614624634644654664674684694704714724734744754764774784794804816 unmodified lines48848949049149249349449515 unmodified lines511512513514{% set MT = "f16" if (operandF16 is defined and operandF16) else "f32" %}{% set ST = "f16" if (storageF16 is defined and storageF16) else MT %}enable subgroups;{% if pinSubgroupSize32 %}enable subgroup_size_control;9 unmodified lines{% macro q_index(row, d) %}(b * params.qSeq + {{ row }}) * HIDDEN + h * HEAD_DIM + {{ d }}{% endmacro %}{% macro kv_index(seq, d) %}{% if kvHeadMajor %}((b * KV_HEADS + h_kv) * params.kvSeq + {{ seq }}) * HEAD_DIM + {{ d }}{% else %}(b * params.kvSeq + {{ seq }}) * KV_HIDDEN + h_kv * HEAD_DIM + {{ d }}{% endif %}{% endmacro %}{% set OUT_ROW_STRIDE = "HIDDEN" %}{% set KV_ROW_STRIDE = "HEAD_DIM" if kvHeadMajor else "KV_HIDDEN" %}{% set SCRATCH_HEAD = "(b * HEADS + h)" %}{% set scorePhase = phase == "score" %}{% set SCORE_BIAS = scorePhase and scoreBias is defined and scoreBias %}{% set SCORE_WINDOW = CAUSAL and scoreWindow is defined and scoreWindow %}{% set USE_SEQLENS = useSeqlens is defined and useSeqlens %}{% set FUSED_SOFTMAX = fusedSoftmax is defined and fusedSoftmax %}{% set PRIVATE_ROW_STATS = FUSED_SOFTMAX and (materializedSgmatPrivateRowStats is defined and materializedSgmatPrivateRowStats) %}{% macro score_value(index, guard) %}{% set rowMax = "private_softmax_m" if PRIVATE_ROW_STATS else "softmax_m[" ~ guard[0] ~ "]" %}{% set rowDenom = "private_softmax_d" if PRIVATE_ROW_STATS else "softmax_d[" ~ guard[0] ~ "]" %}select(0.0, {{ "exp_shift(scores[" ~ index ~ "], " ~ rowMax ~ ") / " ~ rowDenom if FUSED_SOFTMAX else "scores[" ~ index ~ "]" }}, {{ guard[1] }}){% endmacro %}{% set TILE_M_VALUE = materializedSgmatQueryTile %}{% set TILE_N_VALUE = materializedSgmatKeyTile %}{% set TILE_K_VALUE = materializedSgmatInnerTile %}5 unmodified lines{% set SUBGROUP_COLS = (TILE_N_VALUE / SUB_COLS_VALUE)|int %}{% set SUBGROUP_COUNT = SUBGROUP_ROWS * SUBGROUP_COLS %}{% set WORKGROUP_THREADS = SUBGROUP_COUNT * 32 %}{% if hasBias is not defined %}{% set hasBias = false %}{% endif %}{% set EMIT_ROW_STATS = emitRowStats is defined and emitRowStats %}{% set DIRECT_SCORE_STORE = false %}{% set DIRECT_APPLY_STORE = false %}{% set DIRECT_OUTPUT_STORE = DIRECT_SCORE_STORE if scorePhase else DIRECT_APPLY_STORE %}{% set RUNTIME_DIRECT_STORE = (not DIRECT_OUTPUT_STORE)and materializedSgmatRuntimeDirectStoreand (scorePhase or (not hasBias and MT == "f32" and ST == "f32"))and not EMIT_ROW_STATS %}{% set ANY_DIRECT_STORE = DIRECT_OUTPUT_STORE or RUNTIME_DIRECT_STORE %}{% set SCALE_IN_Q = DIRECT_SCORE_STORE or (RUNTIME_DIRECT_STORE and scorePhase) %}{% macro operand_load(name, index) %}{% if ST != MT %}{{ MT }}({% endif %}{{ name }}[{{ index }}]{% if ST != MT %}){% endif %}{% endmacro %}{% macro q_tile_value(index) %}{% if hasBias %}({{ operand_load("query", index) }} + bias[h * HEAD_DIM + k]){% else %}{{ operand_load("query", index) }}{% endif %}{% if SCALE_IN_Q %} * score_scale{% endif %}{% endmacro %}const HEADS: u32 = {{ qNumHeads }}u;const KV_HEADS: u32 = {{ kvNumHeads }}u;const HEAD_DIM: u32 = {{ headDim }}u;const HIDDEN: u32 = {{ qHidden }}u;{% if hasBias %}/* Packed [Q; K; V] bias. Q folds into the query tile before the GEMM. K is* omitted: expanding (q + bq).(k + bk) leaves a (q + bq).bk term that is* constant across every key in the row, and softmax is invariant under that* constant. V is token-independent, so sum_k p[k] * bv = bv after* normalization; it is added after the apply GEMM. */{% endif %}{% if not kvHeadMajor %}// Packed K/V rows span KV_HEADS heads, so they are narrower than the query// row whenever queries are grouped. Q and the output keep HIDDEN.8 unmodified linesconst SUB_ROWS: u32 = {{ SUB_ROWS_VALUE }}u;const SUB_COLS: u32 = {{ SUB_COLS_VALUE }}u;const SUBGROUP_ROWS: u32 = {{ SUBGROUP_ROWS }}u;{% if (FUSED_SOFTMAX and not PRIVATE_ROW_STATS)or not (TILE_M_VALUE == 64 and TILE_N_VALUE == 64 and TILE_K_VALUE == 32 and WORKGROUP_THREADS == 256) %}const WORKGROUP_THREADS: u32 = {{ WORKGROUP_THREADS }}u;{% endif %}11 unmodified linesvar<workgroup> softmax_m: array<f32, {{ TILE_M_VALUE }}>;var<workgroup> softmax_d: array<f32, {{ TILE_M_VALUE }}>;{% endif %}{% if FUSED_SOFTMAX or EMIT_ROW_STATS %}// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret17 unmodified linesfn exp_shift(value: f32, maxValue: f32) -> f32 {return exp(shifted_value(value, maxValue));}{% endif %}@compute @workgroup_size({{ WORKGROUP_THREADS }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_index) li: u32{% if not DIRECT_OUTPUT_STORE %},@builtin(subgroup_invocation_id) lane: u32{% endif %}) {let h = wg.z % HEADS;let b = wg.z / HEADS;let h_kv = h / (HEADS / KV_HEADS);let m_base = wg.y * TILE_M;let n_base = wg.x * TILE_N;let subgroup = li / 32u;let subtile_idy = subgroup % SUBGROUP_ROWS;let subtile_idx = subgroup / SUBGROUP_ROWS;let base_A = subtile_idy * SUB_ROWS;let base_B = subtile_idx * SUB_COLS;{% if USE_SEQLENS %}// Resident rows occupy [0, kv_active). Causal and window bounds use this live// length while params.kvSeq remains the allocated stride. Clamp by qSeq so a// right-padded batch still includes the complete appended query chunk.let kv_active = min(params.kvSeq, max(params.qSeq, u32(seqlens_k[b]) + 1u));{% endif %}{% if CAUSAL and scorePhase %}// Workgroup-uniform causal skip: a key tile starting past the last row's6 unmodified lineslet kv_causal_off = i32({% if USE_SEQLENS %}kv_active{% else %}params.kvSeq{% endif %}) - i32(params.qSeq);if (i32(n_base) > kv_causal_off + i32(m_base + TILE_M) - 1{% if USE_SEQLENS %}|| n_base >= kv_active{% endif %}{% if SCORE_WINDOW %}|| i32(n_base + TILE_N) <= kv_causal_off + i32(m_base) + 1 - i32(params.windowSize){% endif %}) {for (var idx = li; idx < TILE_M * {{ SUBGROUP_COLS }}u; idx += {{ WORKGROUP_THREADS }}u) {let stat_row = m_base + idx / {{ SUBGROUP_COLS }}u;if (stat_row < params.qSeq) {9 unmodified lines{% for row_block in range(ROW_BLOCKS) %}{% for col_block in range(COL_BLOCKS) %}var matC{{ row_block }}{{ col_block }}: subgroup_matrix_result<f32, 8, 8>;{% endfor %}{% endfor %}{% if scorePhase %}let inner = HEAD_DIM;{% else %}let inner = {% if USE_SEQLENS %}kv_active{% else %}params.kvSeq{% endif %};{% if CAUSAL %}// Score tiles past this query tile's causal bound were never written; stop// the reduction at the last written key column for the tile's rows.let kv_causal_off = i32({% if USE_SEQLENS %}inner{% else %}params.kvSeq{% endif %}) - i32(params.qSeq);let inner_bound = u32(clamp(kv_causal_off + i32(m_base + TILE_M), 0, i32(inner)));{% if SCORE_WINDOW %}// Score tiles behind every row's window floor were never written either. The// floor of this tile's FIRST row is the leftmost any of its rows can reach,// and rounding it down to a tile boundary only re-reads columns the score// phase did write (its skip test uses whole key tiles).let inner_start = (u32(max(kv_causal_off + i32(m_base) + 1 - i32(params.windowSize), 0)) / TILE_K) * TILE_K;{% endif %}{% endif %}{% endif %}{% if FUSED_SOFTMAX %}// One row-stats pair per query row of the tile. A query tail clamps to the last// real row rather than reading past the buffer; those lanes are discarded by the// staging guard anyway, and the clamp keeps the denominator non-zero.4 unmodified lines}workgroupBarrier();{% endif %}for (var k_base = {% if SCORE_WINDOW and not scorePhase %}inner_start{% else %}0u{% endif %}; k_base < {% if CAUSAL and not scorePhase %}inner_bound{% else %}inner{% endif %}; k_base += TILE_K) {{% if phase == "apply" and not FUSED_SOFTMAX and MT == "f32" and ST == "f32" %}// Full interior PV tiles can be loaded directly from storage. Query,// reduction, and output-dimension tails use the guarded shared path below.if (k_base + TILE_K <= inner &&m_base + TILE_M <= params.qSeq &&n_base + TILE_N <= HEAD_DIM) {for (var step = 0u; step < TILE_K; step += 8u) {{% for row_block in range(ROW_BLOCKS) %}let score_offset{{ row_block }} = {{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq+ (m_base + base_A + {{ row_block * 8 }}u) * params.kvSeq + k_base + step;var matA{{ row_block }}: subgroup_matrix_left<f32, 8, 8> =subgroupMatrixLoad<subgroup_matrix_left<f32, 8, 8>, row_major>(&scores, score_offset{{ row_block }}, params.kvSeq);{% endfor %}{% for col_block in range(COL_BLOCKS) %}let value_offset{{ col_block }} ={{ kv_index("k_base + step", "n_base + base_B + " ~ (col_block * 8) ~ "u") }};var matB{{ col_block }}: subgroup_matrix_right<f32, 8, 8> =subgroupMatrixLoad<subgroup_matrix_right<f32, 8, 8>, row_major>(&value, value_offset{{ col_block }}, {{ KV_ROW_STRIDE }});{% endfor %}{% for row_block in range(ROW_BLOCKS) %}{% for col_block in range(COL_BLOCKS) %}matC{{ row_block }}{{ col_block }} = subgroupMatrixMultiplyAccumulate(matA{{ row_block }}, matB{{ col_block }}, matC{{ row_block }}{{ col_block }});{% endfor %}{% endfor %}}continue;}{% endif %}{% if TILE_M_VALUE == 64 and TILE_N_VALUE == 64 and TILE_K_VALUE == 32 and WORKGROUP_THREADS == 256 %}// In the BM64/BN64/BK32/WG256 geometry, four adjacent threads each own one6 unmodified lines{% if scorePhase %}{% if headDim % 32 == 0 %}tile_A[a_row * TILE_K + a_col + i] = select({{ "0.0h" if MT == "f16" else "0.0" }},{{ q_tile_value(q_index("row", "k")) }},row < params.qSeq);{% else %}var loaded = {{ "0.0h" if MT == "f16" else "0.0" }};if (row < params.qSeq && k < HEAD_DIM) {loaded = {{ q_tile_value(q_index("row", "k")) }};}2 unmodified lines{% else %}let score_base = {{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq;tile_A[a_row * TILE_K + a_col + i] ={{ "f16(" if MT == "f16" else "" }}{{ score_value("score_base + row * params.kvSeq + k", ["a_row", "row < params.qSeq && k < params.kvSeq"]) }}{{ ")" if MT == "f16" else "" }};{% endif %}}5 unmodified lines{% if scorePhase %}{% if headDim % 32 == 0 %}tile_B[b_row * TILE_K + b_col + i] = select({{ "0.0h" if MT == "f16" else "0.0" }},{{ operand_load("key", kv_index("col", "k")) }},col < params.kvSeq);{% else %}var loaded = {{ "0.0h" if MT == "f16" else "0.0" }};if (col < params.kvSeq && k < HEAD_DIM) {loaded = {{ operand_load("key", kv_index("col", "k")) }};}tile_B[b_row * TILE_K + b_col + i] = loaded;{% endif %}{% else %}tile_B[b_row * TILE_K + b_col + i] = select({{ "0.0h" if MT == "f16" else "0.0" }},{{ operand_load("value", kv_index("k", "col")) }},k < params.kvSeq && col < HEAD_DIM);{% endif %}}{% else %}5 unmodified lineslet row = m_base + tile_row;let k = k_base + tile_k;{% if scorePhase %}var loaded = {{ "0.0h" if MT == "f16" else "0.0" }};if (row < params.qSeq && k < HEAD_DIM) {loaded = {{ q_tile_value(q_index("row", "k")) }};}{% elif FUSED_SOFTMAX %}let score_base = {{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq;let loaded ={{ "f16(" if MT == "f16" else "" }}{{ score_value("score_base + row * params.kvSeq + k", ["tile_row", "row < params.qSeq && k < params.kvSeq"]) }}{{ ")" if MT == "f16" else "" }};{% else %}var loaded = 0.0;if (row < params.qSeq && k < params.kvSeq) {let score_base = {{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq;loaded = scores[score_base + row * params.kvSeq + k];}{% endif %}tile_A[idx] = loaded;}4 unmodified lineslet col = n_base + tile_col;let k = k_base + tile_k;{% if scorePhase %}var loaded = {{ "0.0h" if MT == "f16" else "0.0" }};if (col < params.kvSeq && k < HEAD_DIM) {loaded = {{ operand_load("key", kv_index("col", "k")) }};}{% else %}var loaded = {{ "0.0h" if MT == "f16" else "0.0" }};if (k < params.kvSeq && col < HEAD_DIM) {loaded = {{ operand_load("value", kv_index("k", "col")) }};}{% endif %}tile_B[idx] = loaded;}{% endif %}workgroupBarrier();2 unmodified lines{% for row_block in range(ROW_BLOCKS) %}let matrix_a_offset{{ row_block }} =(subtile_idy * SUB_ROWS + {{ row_block * 8 }}u) * TILE_K + step;var matA{{ row_block }}: subgroup_matrix_left<{{ MT }}, 8, 8> =subgroupMatrixLoad<subgroup_matrix_left<{{ MT }}, 8, 8>, row_major>(&tile_A, matrix_a_offset{{ row_block }}, TILE_K);{% endfor %}{% for col_block in range(COL_BLOCKS) %}let matrix_b_offset{{ col_block }} =(subtile_idx * SUB_COLS + {{ col_block * 8 }}u) * TILE_K + step;var matB{{ col_block }}: subgroup_matrix_right<{{ MT }}, 8, 8> =subgroupMatrixLoad<subgroup_matrix_right<{{ MT }}, 8, 8>, col_major>(&tile_B, matrix_b_offset{{ col_block }}, TILE_K);{% endfor %}{% for row_block in range(ROW_BLOCKS) %}{% for col_block in range(COL_BLOCKS) %}matC{{ row_block }}{{ col_block }} = subgroupMatrixMultiplyAccumulate(matA{{ row_block }}, matB{{ col_block }}, matC{{ row_block }}{{ col_block }});{% endfor %}{% endfor %}}workgroupBarrier();}{% if ANY_DIRECT_STORE %}// Every dispatched tile is interior, so the matrices can go straight to// storage without the compact scratch/readback epilogue.{% for row_block in range(ROW_BLOCKS) %}{% for col_block in range(COL_BLOCKS) %}{% if scorePhase %}let output_offset{{ row_block }}{{ col_block }} ={{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq+ (m_base + base_A + {{ row_block * 8 }}u) * params.kvSeq+ n_base + base_B + {{ col_block * 8 }}u;subgroupMatrixStore<row_major>(&scores, output_offset{{ row_block }}{{ col_block }},matC{{ row_block }}{{ col_block }}, params.kvSeq);{% else %}let output_offset{{ row_block }}{{ col_block }} ={{ q_index("m_base + base_A + " ~ (row_block * 8) ~ "u", "n_base + base_B + " ~ (col_block * 8) ~ "u") }};subgroupMatrixStore<row_major>(&output, output_offset{{ row_block }}{{ col_block }},matC{{ row_block }}{{ col_block }}, {{ OUT_ROW_STRIDE }});{% endif %}{% endfor %}{% endfor %}{% endif %}{% if not DIRECT_OUTPUT_STORE %}let row_in_block = lane / 4u;12 unmodified linesvar stat_d{{ row_block }} = 0.0;{% endif %}{% for col_block in range(COL_BLOCKS) %}subgroupMatrixStore<row_major>(&{{ SCRATCH }},(subgroup * {{ COL_BLOCKS }}u + {{ col_block }}u) * 64u,matC{{ row_block }}{{ col_block }},8u);{% endfor %}workgroupBarrier();10 unmodified lines+ row_in_block * 8u + col_in_block + pair];{% if scorePhase %}{% if not SCALE_IN_Q %}let scale = {{ attentionScaleExpression }};{% endif %}{% if CAUSAL %}var scored = result * scale;{% if SCORE_BIAS %}8 unmodified linesif (col >= kv_active) { scored = -FLT_MAX; }{% endif %}{% if SCORE_WINDOW %}if (i32(col) + i32(params.windowSize) <= kv_causal_off + i32(row)) { scored = -FLT_MAX; }{% endif %}{% else %}let scored = result{% if not SCALE_IN_Q %} * scale{% endif %};{% endif %}scores[{{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq + row * params.kvSeq + col] = scored;{% if EMIT_ROW_STATS %}// Softmax sees the STORED value, so the statistics have to be taken on it// and not on the raw accumulator.let stat_prev = stat_m{{ row_block }};stat_m{{ row_block }} = max(stat_m{{ row_block }}, scored);stat_d{{ row_block }} = stat_d{{ row_block }} * exp_shift(stat_prev, stat_m{{ row_block }})+ exp_shift(scored, stat_m{{ row_block }});{% endif %}{% else %}{% if hasBias %}// V bias row base: skip the packed Q and K blocks, then index this head.{% endif %}output[{{ q_index("row", "col") }}] = {{ "f16(" if ST == "f16" else "" }}result{{ ")" if ST == "f16" else "" }}{% if hasBias %} + bias[2u * HIDDEN + h * HEAD_DIM + col]{% endif %};{% endif %}}}6 unmodified lines// quads of the subgroup satisfy would not be uniform.{% for xor in [1, 2] %}{let other_m = subgroupShuffleXor(stat_m{{ row_block }}, {{ xor }}u);let other_d = subgroupShuffleXor(stat_d{{ row_block }}, {{ xor }}u);let merged_m = max(stat_m{{ row_block }}, other_m);stat_d{{ row_block }} = stat_d{{ row_block }} * exp_shift(stat_m{{ row_block }}, merged_m)+ other_d * exp_shift(other_m, merged_m);15 unmodified lines{% endif %}{% endfor %}{% endif %}}123456789 unmodified lines1819202122232425262728293031323334353637383940415 unmodified lines4748495051525354555657585960616263646566678 unmodified lines7677787980818211 unmodified lines94959697989917 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326 unmodified lines6396406416426436446459 unmodified lines6556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946954 unmodified lines7007017027037047057067076 unmodified lines7147157167177187197207217227237247252 unmodified lines7287297307317327337345 unmodified lines7407417427437447457467477487497507517527537547557567577587597607617627637647657667675 unmodified lines7737747757767777787797807817827837847857864 unmodified lines7917927937947957967977987998008018028038048058068078088098108112 unmodified lines81481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989012 unmodified lines90390490590690790890910 unmodified lines9209219229239249259268 unmodified lines9359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679686 unmodified lines97597697797897998098198298398498598698798898999099199299315 unmodified lines10091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {% if queryFloor %}max({{ queryFloor }}, {{ attn_seqlens_count(index) }}){% else %}{{ attn_seqlens_count(index) }}{% endif %}){% endmacro %}{% set MT = "f16" if (operandF16 is defined and operandF16) else "f32" %}{% set OPERAND_ZERO = "0.0h" if MT == "f16" else "0.0" %}{% set ST = MT %}enable subgroups;{% if pinSubgroupSize32 %}enable subgroup_size_control;9 unmodified lines{% macro q_index(row, d) %}(b * params.qSeq + {{ row }}) * HIDDEN + h * HEAD_DIM + {{ d }}{% endmacro %}{% macro kv_index(seq, d) %}{% if kvHeadMajor %}((b * KV_HEADS + h_kv) * params.kvSeq + {{ seq }}) * HEAD_DIM + {{ d }}{% else %}(b * params.kvSeq + {{ seq }}) * KV_HIDDEN + h_kv * HEAD_DIM + {{ d }}{% endif %}{% endmacro %}{% set OUT_ROW_STRIDE = "HIDDEN" %}{% set SCRATCH_HEAD = "(b * HEADS + h)" %}{% set scorePhase = phase == "score" %}{% set SCORE_BIAS = scorePhase and scoreBias is defined and scoreBias %}{% set SCORE_WINDOW = CAUSAL and scoreWindow is defined and scoreWindow %}{% set USE_SEQLENS = useSeqlens is defined and useSeqlens %}{% set LIVE_KV = "kv_active" if USE_SEQLENS else "params.kvSeq" %}{% set FUSED_SOFTMAX = fusedSoftmax is defined and fusedSoftmax %}{% set SAFE_VALUE_REDO = FUSED_SOFTMAX and not scorePhase and MT == "f32" and ST == "f32" %}{% set DEFER_VALUE_NORMALIZATION = SAFE_VALUE_REDO and (deferValueNormalization | default(false)) %}{% set PRIVATE_ROW_STATS = FUSED_SOFTMAX and (materializedSgmatPrivateRowStats is defined and materializedSgmatPrivateRowStats) %}{% set PV_LOAD_GUARD = "k < inner_bound && i32(k) <= kv_causal_off + i32(row)" if CAUSAL else "k < " ~ LIVE_KV %}{% if SCORE_WINDOW %}{% set PV_LOAD_GUARD = PV_LOAD_GUARD ~ " && i32(k) + i32(min(params.windowSize, " ~ LIVE_KV ~ ")) > kv_causal_off + i32(row)" %}{% endif %}{% set PV_VALUE_LOAD_GUARD = "k < inner_bound" if CAUSAL else "k < " ~ LIVE_KV %}{% if SCORE_WINDOW %}{% set PV_VALUE_LOAD_GUARD = PV_VALUE_LOAD_GUARD ~ " && i32(k) >= kv_causal_off + i32(m_base) + 1 - i32(min(params.windowSize, " ~ LIVE_KV ~ "))" %}{% endif %}{% macro score_value(index, rowIndex, valid) %}{% set rowMax = "private_softmax_m" if PRIVATE_ROW_STATS else "softmax_m[" ~ rowIndex ~ "]" %}{% set rowDenom = "private_softmax_d" if PRIVATE_ROW_STATS else "softmax_d[" ~ rowIndex ~ "]" %}{% if SAFE_VALUE_REDO %}materialized_probability(scores[{{ index }}], {{ rowMax }}, {{ rowDenom }}, {{ valid }}, &valueRangeNeedsFallback){% else %}select(0.0, {{ "exp_shift(scores[" ~ index ~ "], " ~ rowMax ~ ") / " ~ rowDenom }}, {{ valid }}{% if FUSED_SOFTMAX and (CAUSAL or USE_SEQLENS) %} && {{ rowDenom }} != 0.0{% endif %}){% endif %}{% endmacro %}{% set TILE_M_VALUE = materializedSgmatQueryTile %}{% set TILE_N_VALUE = materializedSgmatKeyTile %}{% set TILE_K_VALUE = materializedSgmatInnerTile %}5 unmodified lines{% set SUBGROUP_COLS = (TILE_N_VALUE / SUB_COLS_VALUE)|int %}{% set SUBGROUP_COUNT = SUBGROUP_ROWS * SUBGROUP_COLS %}{% set WORKGROUP_THREADS = SUBGROUP_COUNT * 32 %}{% set hasBias = false %}{% set EMIT_ROW_STATS = emitRowStats is defined and emitRowStats %}{% set DIRECT_OUTPUT_STORE = not scorePhase and materializedSgmatDirectApplyStore and not hasBias and MT == "f32" and ST == "f32" and not DEFER_VALUE_NORMALIZATION %}{% set RUNTIME_DIRECT_STORE = not scorePhase and not DIRECT_OUTPUT_STORE and materializedSgmatRuntimeDirectStore and not hasBias and MT == "f32" and ST == "f32" and not DEFER_VALUE_NORMALIZATION %}{% set ANY_DIRECT_STORE = DIRECT_OUTPUT_STORE or RUNTIME_DIRECT_STORE %}{% macro operand_load(name, index) %}{% if ST != MT %}{{ MT }}({% endif %}{{ name }}[{{ index }}]{% if ST != MT %}){% endif %}{% endmacro %}{% macro q_tile_value(index) %}{{ operand_load("query", index) }}{% endmacro %}const HEADS: u32 = {{ qNumHeads }}u;{% if kvNumHeads is defined %}const KV_HEADS: u32 = {{ kvNumHeads }}u;{% else %}const KV_HEADS: u32 = HEADS;{% endif %}const HEAD_DIM: u32 = {{ headDim }}u;const HIDDEN: u32 = {{ qHidden }}u;{% if not kvHeadMajor %}// Packed K/V rows span KV_HEADS heads, so they are narrower than the query// row whenever queries are grouped. Q and the output keep HIDDEN.8 unmodified linesconst SUB_ROWS: u32 = {{ SUB_ROWS_VALUE }}u;const SUB_COLS: u32 = {{ SUB_COLS_VALUE }}u;const SUBGROUP_ROWS: u32 = {{ SUBGROUP_ROWS }}u;{% if SAFE_VALUE_REDO or (FUSED_SOFTMAX and not PRIVATE_ROW_STATS) or not (TILE_M_VALUE == 64 and TILE_N_VALUE == 64 and TILE_K_VALUE == 32 and WORKGROUP_THREADS == 256) %}const WORKGROUP_THREADS: u32 = {{ WORKGROUP_THREADS }}u;{% endif %}11 unmodified linesvar<workgroup> softmax_m: array<f32, {{ TILE_M_VALUE }}>;var<workgroup> softmax_d: array<f32, {{ TILE_M_VALUE }}>;{% endif %}// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret17 unmodified linesfn exp_shift(value: f32, maxValue: f32) -> f32 {return exp(shifted_value(value, maxValue));}{% if SAFE_VALUE_REDO %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&{% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &{% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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 }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("f32") }}fn materialized_probability(score: f32, maximum: f32, denominator: f32,valid: bool, needsFallback: ptr<function, bool>) -> f32 {if (!valid || denominator == 0.0) { return 0.0; }let weight = exp_shift(score, maximum);let probability = weight / denominator;// If both P and |V| are at least sqrt(FLT_MIN), their product is normal.// Smaller nonzero operands use the scaled raw-value path below.if (weight > 0.0 && probability < 1.0842021724855044e-19) {*needsFallback = true;}return probability;}{% endif %}// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {// WGSL initializes workgroup variables to zero before this entry point.let population = subgroupBallot(true);let populationCount = countOneBits(population.x) + countOneBits(population.y)+ countOneBits(population.z) + countOneBits(population.w);var claimed = 0u;if (subgroupElect()) {claimed = atomicAdd(&matrixRoleCount, 1u);if (width != requiredWidth || populationCount != requiredWidth) {atomicStore(&matrixRejected, 1u);}}// Reconverge every invocation before broadcasting the elected claim.workgroupBarrier();return subgroupBroadcastFirst(claimed);}fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {if (localIndex == 0u) {matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u&& atomicLoad(&matrixRoleCount) == bankCount);}// The uniform load both publishes the leader's decision and gives the// compiler a workgroup-uniform condition for the barrier-containing arms.return workgroupUniformLoad(&matrixAccepted) != 0u;}// The portable arm owns two result components per logical 32-invocation group.// Staging casts, 8-wide K steps, barriers and the epilogue match the// subgroup-matrix arm.var<private> matrixSoftwareLane: u32;fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>,acc: vec2<f32>) -> vec2<f32> {var value = acc;for (var k = 0u; k < 8u; k += 1u) {value = fma(vec2<f32>(lhs[k]), rhs[k], value);}return value;}{% macro matrixType(software, kind, scalar) %}{% if software %}{% if kind == "left" %}array<f32, 8>{% elif kind == "right" %}array<vec2<f32>, 8>{% else %}vec2<{{ scalar }}>{% endif %}{% else %}subgroup_matrix_{{ kind }}<{{ scalar }}, 8, 8>{% endif %}{% endmacro %}{% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}{% if kind == "left" %}array<f32, 8>({% for k in range(8) %}f32((*({{ pointer }}))[({{ offset }}) + {% if major == "row_major" %}(matrixSoftwareLane / 4u) * ({{ stride }}) + {{ k }}u{% else %}{{ k }}u * ({{ stride }}) + matrixSoftwareLane / 4u{% endif %}]){{ "," if k < 7 else "" }}{% endfor %}){% else %}array<vec2<f32>, 8>({% for k in range(8) %}vec2<f32>({% for h in range(2) %}f32((*({{ pointer }}))[({{ offset }}) + {% if major == "row_major" %}{{ k }}u * ({{ stride }}) + (matrixSoftwareLane % 4u) * 2u + {{ h }}u{% else %}((matrixSoftwareLane % 4u) * 2u + {{ h }}u) * ({{ stride }}) + {{ k }}u{% endif %}]){{ "," if h == 0 else "" }}{% endfor %}){{ "," if k < 7 else "" }}{% endfor %}){% endif %}{% endif %}{% endmacro %}{% macro matrixMma(software, scalar, lhs, rhs, acc) %}{% if not software %}subgroupMatrixMultiplyAccumulate({{ lhs }}, {{ rhs }}, {{ acc }}){% else %}vec2<{{ scalar }}>(matrixSoftwareMultiplyAccumulate({{ lhs }}, {{ rhs }}, vec2<f32>({{ acc }}))){% endif %}{% endmacro %}{% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{let matrixPointer = {{ pointer }};let matrixValue = {{ value }};{% for h in range(2) %} (*matrixPointer)[({{ offset }}) + {{ {"row_major": "(matrixSoftwareLane / 4u) * (" ~ stride ~ ") + (matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u", "col_major": "((matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u) * (" ~ stride ~ ") + matrixSoftwareLane / 4u"}[major] }}] = matrixValue.{{ "x" if h == 0 else "y" }};{% endfor %}}{% endif %}{% endmacro %}{% if CAUSAL and not scorePhase %}// Native PV must exclude visibility-changing nonfinite values: a masked zero must not become// NaN through 0*Inf. The explicit per-row path below skips excluded keys.var<workgroup> causalValueNonFinite: atomic<u32>;var<workgroup> causalValuesFinite: u32;{% endif %}{% macro matrixKernelBody(matrixSoftware) %}{% if SAFE_VALUE_REDO %}// The topology decision is complete. Reuse its atomic scratch for the rare// probability-range fallback without increasing workgroup storage.if (li == 0u) { atomicStore(&matrixRejected, 0u); }workgroupBarrier();var valueRangeNeedsFallback = false;{% endif %}let h = wg.z % HEADS;let b = wg.z / HEADS;let h_kv = h / (HEADS / KV_HEADS);let m_base = wg.y * TILE_M;let n_base = wg.x * TILE_N;let subgroup = matrixRole;let subtile_idy = subgroup % SUBGROUP_ROWS;let subtile_idx = subgroup / SUBGROUP_ROWS;let base_A = subtile_idy * SUB_ROWS;let base_B = subtile_idx * SUB_COLS;{% if USE_SEQLENS %}// Resident rows occupy [0, kv_active). Causal and window bounds use this live// length while params.kvSeq remains the allocated stride.let kv_active = {{ attn_seqlens_bound("params.kvSeq", "b", "params.qSeq" if seqlensQueryFloor | default(true) else "") }};{% endif %}{% if CAUSAL and scorePhase %}// Workgroup-uniform causal skip: a key tile starting past the last row's6 unmodified lineslet kv_causal_off = i32({% if USE_SEQLENS %}kv_active{% else %}params.kvSeq{% endif %}) - i32(params.qSeq);if (i32(n_base) > kv_causal_off + i32(m_base + TILE_M) - 1{% if USE_SEQLENS %}|| n_base >= kv_active{% endif %}{% if SCORE_WINDOW %}|| i32(n_base + TILE_N) <= kv_causal_off + i32(m_base) + 1 - i32(min(params.windowSize, {{ LIVE_KV }})){% endif %}) {for (var idx = li; idx < TILE_M * {{ SUBGROUP_COLS }}u; idx += {{ WORKGROUP_THREADS }}u) {let stat_row = m_base + idx / {{ SUBGROUP_COLS }}u;if (stat_row < params.qSeq) {9 unmodified lines{% for row_block in range(ROW_BLOCKS) %}{% for col_block in range(COL_BLOCKS) %}var matC{{ row_block }}{{ col_block }}: {{ matrixType(matrixSoftware, "result", "f32") }};{% endfor %}{% endfor %}{% if scorePhase %}let inner = HEAD_DIM;{% else %}let inner = {% if USE_SEQLENS %}kv_active{% else %}params.kvSeq{% endif %};{% if CAUSAL %}// Score tiles past this query tile's causal bound were never written; stop// the reduction at the last written key column for the tile's rows.let kv_causal_off = i32({% if USE_SEQLENS %}inner{% else %}params.kvSeq{% endif %}) - i32(params.qSeq);let inner_bound = u32(clamp(kv_causal_off + i32(min(m_base + TILE_M, params.qSeq)), 0, i32(inner)));{% if SCORE_WINDOW %}// Score tiles behind every row's window floor were never written either. The// floor of this tile's FIRST row is the leftmost any of its rows can reach,// and rounding it down to a tile boundary only re-reads columns the score// phase did write (its skip test uses whole key tiles).let inner_start = (u32(max(kv_causal_off + i32(m_base) + 1 - i32(min(params.windowSize, {{ LIVE_KV }})), 0)) / TILE_K) * TILE_K;{% endif %}{% endif %}{% endif %}{% if FUSED_SOFTMAX %}{% if PRIVATE_ROW_STATS %}// In the supported BM64/BN64/BK32/WG256 loader, four adjacent lanes own the// same query row for every reduction tile. Keep that row's constants private:// this removes both 512 bytes of workgroup storage and the initialization// barrier while preserving the exact exp/divide sequence of the shared-memory// row-stats arm.let private_stat_row ={{ SCRATCH_HEAD }} * params.qSeq + min(m_base + li / 4u, params.qSeq - 1u);let private_softmax_m = rowStats[private_stat_row * 2u];let private_softmax_d = rowStats[private_stat_row * 2u + 1u];{% else %}// One row-stats pair per query row of the tile. A query tail clamps to the last// real row rather than reading past the buffer; those lanes are discarded by the// staging guard anyway, and the clamp keeps the denominator non-zero.4 unmodified lines}workgroupBarrier();{% endif %}{% endif %}for (var k_base = {% if SCORE_WINDOW and not scorePhase %}inner_start{% else %}0u{% endif %}; k_base < {% if CAUSAL and not scorePhase %}inner_bound{% else %}inner{% endif %}; k_base += TILE_K) {{% if TILE_M_VALUE == 64 and TILE_N_VALUE == 64 and TILE_K_VALUE == 32 and WORKGROUP_THREADS == 256 %}// In the BM64/BN64/BK32/WG256 geometry, four adjacent threads each own one6 unmodified lines{% if scorePhase %}{% if headDim % 32 == 0 %}tile_A[a_row * TILE_K + a_col + i] = select({{ OPERAND_ZERO }},{{ q_tile_value(q_index("row", "k")) }},row < params.qSeq);{% else %}var loaded = {{ OPERAND_ZERO }};if (row < params.qSeq && k < HEAD_DIM) {loaded = {{ q_tile_value(q_index("row", "k")) }};}2 unmodified lines{% else %}let score_base = {{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq;tile_A[a_row * TILE_K + a_col + i] ={{ "f16(" if MT == "f16" else "" }}{{ score_value("score_base + row * params.kvSeq + k", "a_row", "row < params.qSeq && " ~ PV_LOAD_GUARD) }}{{ ")" if MT == "f16" else "" }};{% endif %}}5 unmodified lines{% if scorePhase %}{% if headDim % 32 == 0 %}tile_B[b_row * TILE_K + b_col + i] = select({{ OPERAND_ZERO }},{{ operand_load("key", kv_index("col", "k")) }},col < {{ LIVE_KV }});{% else %}var loaded = {{ OPERAND_ZERO }};if (col < {{ LIVE_KV }} && k < HEAD_DIM) {loaded = {{ operand_load("key", kv_index("col", "k")) }};}tile_B[b_row * TILE_K + b_col + i] = loaded;{% endif %}{% else %}tile_B[b_row * TILE_K + b_col + i] = select({{ OPERAND_ZERO }},{{ operand_load("value", kv_index("k", "col")) }},{{ PV_VALUE_LOAD_GUARD }} && col < HEAD_DIM);{% if SAFE_VALUE_REDO %}let staged_value = tile_B[b_row * TILE_K + b_col + i];if (abs(staged_value) > 0.0 && abs(staged_value) < 1.0842021724855044e-19) { valueRangeNeedsFallback = true; }{% if DEFER_VALUE_NORMALIZATION %} if (!(abs(staged_value) <= FLT_MAX / (4.0 * f32(max(inner, 1u))))) { valueRangeNeedsFallback = true; }{% endif %}{% endif %}{% endif %}}{% else %}5 unmodified lineslet row = m_base + tile_row;let k = k_base + tile_k;{% if scorePhase %}var loaded = {{ OPERAND_ZERO }};if (row < params.qSeq && k < HEAD_DIM) {loaded = {{ q_tile_value(q_index("row", "k")) }};}{% else %}let score_base = {{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq;let loaded ={{ "f16(" if MT == "f16" else "" }}{{ score_value("score_base + row * params.kvSeq + k", "tile_row", "row < params.qSeq && " ~ PV_LOAD_GUARD) }}{{ ")" if MT == "f16" else "" }};{% endif %}tile_A[idx] = loaded;}4 unmodified lineslet col = n_base + tile_col;let k = k_base + tile_k;{% if scorePhase %}var loaded = {{ OPERAND_ZERO }};if (col < {{ LIVE_KV }} && k < HEAD_DIM) {loaded = {{ operand_load("key", kv_index("col", "k")) }};}{% else %}var loaded = {{ OPERAND_ZERO }};if ({{ PV_VALUE_LOAD_GUARD }} && col < HEAD_DIM) {loaded = {{ operand_load("value", kv_index("k", "col")) }};}{% endif %}tile_B[idx] = loaded;{% if SAFE_VALUE_REDO %}if (abs(loaded) > 0.0 && abs(loaded) < 1.0842021724855044e-19) { valueRangeNeedsFallback = true; }{% if DEFER_VALUE_NORMALIZATION %} if (!(abs(loaded) <= FLT_MAX / (4.0 * f32(max(inner, 1u))))) { valueRangeNeedsFallback = true; }{% endif %}{% endif %}}{% endif %}workgroupBarrier();2 unmodified lines{% for row_block in range(ROW_BLOCKS) %}let matrix_a_offset{{ row_block }} =(subtile_idy * SUB_ROWS + {{ row_block * 8 }}u) * TILE_K + step;var matA{{ row_block }}: {{ matrixType(matrixSoftware, "left", MT) }} ={{ matrixLoad(matrixSoftware, "left", MT, "row_major", "&tile_A", "matrix_a_offset" ~ (row_block), "TILE_K") }};{% endfor %}{% for col_block in range(COL_BLOCKS) %}let matrix_b_offset{{ col_block }} =(subtile_idx * SUB_COLS + {{ col_block * 8 }}u) * TILE_K + step;var matB{{ col_block }}: {{ matrixType(matrixSoftware, "right", MT) }} ={{ matrixLoad(matrixSoftware, "right", MT, "col_major", "&tile_B", "matrix_b_offset" ~ (col_block), "TILE_K") }};{% endfor %}{% for row_block in range(ROW_BLOCKS) %}{% for col_block in range(COL_BLOCKS) %}matC{{ row_block }}{{ col_block }} = {{ matrixMma(matrixSoftware, "f32", "matA" ~ (row_block), "matB" ~ (col_block), "matC" ~ (row_block) ~ (col_block)) }};{% endfor %}{% endfor %}}workgroupBarrier();}{% if SAFE_VALUE_REDO %}if (valueRangeNeedsFallback) { atomicOr(&matrixRejected, 1u); }workgroupBarrier();if (li == 0u) { matrixAccepted = atomicLoad(&matrixRejected); }if (workgroupUniformLoad(&matrixAccepted) != 0u) {// A small probability can multiply a large V into a normal contribution.// Recompute only affected workgroups before any native output is stored.for (var flat = li; flat < TILE_M * TILE_N; flat += WORKGROUP_THREADS) {let row = m_base + flat / TILE_N;let col = n_base + flat % TILE_N;if (row < params.qSeq && col < HEAD_DIM) {let row_stat = {{ SCRATCH_HEAD }} * params.qSeq + row;let row_m = rowStats[row_stat * 2u];let row_d = rowStats[row_stat * 2u + 1u];let row_end = {% if CAUSAL %}u32(clamp(kv_causal_off + i32(row) + 1, 0, i32(inner))){% else %}inner{% endif %};let row_start = {% if SCORE_WINDOW %}u32(max(kv_causal_off + i32(row) + 1 - i32(min(params.windowSize, {{ LIVE_KV }})), 0)){% else %}0u{% endif %};var sum = scaled_value_zero();for (var key = row_start; key < row_end && row_d != 0.0; key++) {let score = scores[{{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq + row * params.kvSeq + key];sum = {% if DEFER_VALUE_NORMALIZATION %}materialized_raw_add(sum, score, row_m, {{ operand_load("value", kv_index("key", "col")) }}){% else %}scaled_value_add(sum, exp_shift(score, row_m), {{ operand_load("value", kv_index("key", "col")) }}){% endif %};}output[{{ q_index("row", "col") }}] = scaled_value_mean(sum, row_d);}}return;}{% endif %}{% if ANY_DIRECT_STORE %}{% if RUNTIME_DIRECT_STORE %}// Workgroup-uniform (both bases come from workgroup_id alone): an interior tile// publishes through the subgroup-matrix collectives and is done; only an edge// tile falls through to the scratch round trip and its barriers.if (m_base + TILE_M <= params.qSeq &&n_base + TILE_N <= HEAD_DIM) {{% else %}// Every dispatched tile is interior, so the matrices can go straight to// storage without the compact scratch/readback epilogue.{% endif %}{% for row_block in range(ROW_BLOCKS) %}{% for col_block in range(COL_BLOCKS) %}let output_offset{{ row_block }}{{ col_block }} ={{ q_index("m_base + base_A + " ~ (row_block * 8) ~ "u", "n_base + base_B + " ~ (col_block * 8) ~ "u") }};{{ matrixStore(matrixSoftware, "row_major", "&output", "output_offset" ~ (row_block) ~ (col_block), "matC" ~ (row_block) ~ (col_block), OUT_ROW_STRIDE) }}{% endfor %}{% endfor %}{% if RUNTIME_DIRECT_STORE %}return;}{% endif %}{% endif %}{% if not DIRECT_OUTPUT_STORE %}let row_in_block = lane / 4u;12 unmodified linesvar stat_d{{ row_block }} = 0.0;{% endif %}{% for col_block in range(COL_BLOCKS) %}{{ matrixStore(matrixSoftware, "row_major", "&" ~ (SCRATCH), "(subgroup * " ~ (COL_BLOCKS) ~ "u + " ~ (col_block) ~ "u) * 64u", "matC" ~ (row_block) ~ (col_block), "8u") }}{% endfor %}workgroupBarrier();10 unmodified lines+ row_in_block * 8u + col_in_block + pair];{% if scorePhase %}let scale = {{ attentionScaleExpression }};{% if CAUSAL %}var scored = result * scale;{% if SCORE_BIAS %}8 unmodified linesif (col >= kv_active) { scored = -FLT_MAX; }{% endif %}{% if SCORE_WINDOW %}if (i32(col) + i32(min(params.windowSize, {{ LIVE_KV }})) <= kv_causal_off + i32(row)) { scored = -FLT_MAX; }{% endif %}{% else %}let scored = result * scale;{% endif %}scores[{{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq + row * params.kvSeq + col] = scored;// Softmax sees the STORED value, so the statistics have to be taken on it// and not on the raw accumulator.{% if CAUSAL %}if ({% if USE_SEQLENS %}col < kv_active && {% endif %}i32(col) <= kv_causal_off + i32(row){% if SCORE_WINDOW %} && i32(col) + i32(min(params.windowSize, {{ LIVE_KV }})) > kv_causal_off + i32(row){% endif %}) {{% endif %}let stat_prev = stat_m{{ row_block }};stat_m{{ row_block }} = max(stat_m{{ row_block }}, scored);stat_d{{ row_block }} = stat_d{{ row_block }} * exp_shift(stat_prev, stat_m{{ row_block }})+ exp_shift(scored, stat_m{{ row_block }});{% if CAUSAL %} }{% endif %}{% else %}{% if DEFER_VALUE_NORMALIZATION %}let denominator = rowStats[({{ SCRATCH_HEAD }} * params.qSeq + row) * 2u + 1u];// Divide once after summing the raw numerator. Zero-denominator rows produce// zero; NaN denominators propagate as NaN.let normalized = select(result / denominator, 0.0, denominator == 0.0);{% endif %}output[{{ q_index("row", "col") }}] = {{ "f16(" if ST == "f16" else "" }}{% if DEFER_VALUE_NORMALIZATION %}normalized{% elif FUSED_SOFTMAX and (CAUSAL or USE_SEQLENS) %}select(result, 0.0, rowStats[({{ SCRATCH_HEAD }} * params.qSeq + row) * 2u + 1u] == 0.0){% else %}result{% endif %}{{ ")" if ST == "f16" else "" }};{% endif %}}}6 unmodified lines// quads of the subgroup satisfy would not be uniform.{% for xor in [1, 2] %}{{% if matrixSoftware %}// Result readers finish before the dead epilogue bank becomes quad transport.workgroupBarrier();{{ SCRATCH }}[2u * li] = stat_m{{ row_block }};{{ SCRATCH }}[2u * li + 1u] = stat_d{{ row_block }};workgroupBarrier();let other_m = {{ SCRATCH }}[2u * (li ^ {{ xor }}u)];let other_d = {{ SCRATCH }}[2u * (li ^ {{ xor }}u) + 1u];workgroupBarrier();{% else %}let other_m = subgroupShuffleXor(stat_m{{ row_block }}, {{ xor }}u);let other_d = subgroupShuffleXor(stat_d{{ row_block }}, {{ xor }}u);{% endif %}let merged_m = max(stat_m{{ row_block }}, other_m);stat_d{{ row_block }} = stat_d{{ row_block }} * exp_shift(stat_m{{ row_block }}, merged_m)+ other_d * exp_shift(other_m, merged_m);15 unmodified lines{% endif %}{% endfor %}{% endif %}{% endmacro %}@compute @workgroup_size({{ WORKGROUP_THREADS }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_index) li: u32,@builtin(subgroup_size) matrixPhysicalWidth: u32,@builtin(subgroup_invocation_id) matrixPhysicalLane: u32) {let matrixRole = claimMatrixSubgroupRole(matrixPhysicalWidth, 32u);{% if not (CAUSAL and not scorePhase) %} let matrixAcceptedHere = matrixTopologyAccepted(li, {{ WORKGROUP_THREADS }}u / 32u);{% endif %}{% if CAUSAL and not scorePhase %}let h = wg.z % HEADS;let b = wg.z / HEADS;let h_kv = h / (HEADS / KV_HEADS);let causal_row_base = wg.y * TILE_M;let causal_col_base = wg.x * TILE_N;let causal_live = {% if USE_SEQLENS %}{{ attn_seqlens_bound("params.kvSeq", "b", "params.qSeq") }}{% else %}params.kvSeq{% endif %};let causal_offset = i32(causal_live) - i32(params.qSeq);let causal_end = u32(clamp(causal_offset + i32(min(causal_row_base + TILE_M, params.qSeq)), 0, i32(causal_live)));let common_end = u32(clamp(causal_offset + i32(causal_row_base) + 1, 0, i32(causal_live)));let causal_start = {% if SCORE_WINDOW %}u32(max(causal_offset + i32(causal_row_base) + 1 - i32(min(params.windowSize, causal_live)), 0)){% else %}0u{% endif %};let common_start = {% if SCORE_WINDOW %}u32(max(causal_offset + i32(min(causal_row_base + TILE_M, params.qSeq)) - i32(min(params.windowSize, causal_live)), 0)){% else %}0u{% endif %};// Only keys whose visibility changes across real rows can leak a masked// nonfinite into another row. Common visible keys preserve native semantics.let left_end = min(common_start, causal_end);let right_start = max(common_end, left_end);let causal_col = causal_col_base + (li % {{ TILE_N_VALUE // 4 }}u) * 4u;{% for edge in range(2) %}{let edge_start = {% if edge == 0 %}causal_start{% else %}right_start{% endif %};let edge_end = {% if edge == 0 %}left_end{% else %}causal_end{% endif %};for (var key = edge_start + li / {{ TILE_N_VALUE // 4 }}u; key < edge_end; key += {{ WORKGROUP_THREADS * 4 // TILE_N_VALUE }}u) {var exponentBits = 0u;{% for c in range(4) %}if (causal_col + {{ c }}u < HEAD_DIM) {let bits = bitcast<u32>(f32({{ MT }}({{ operand_load("value", kv_index("key", "causal_col + " ~ c ~ "u")) }})));exponentBits |= select(0u, 1u, (bits & 0x7f800000u) == 0x7f800000u);}{% endfor %}if (exponentBits != 0u) { atomicOr(&causalValueNonFinite, 1u); }}}{% endfor %}let matrixAcceptedHere = matrixTopologyAccepted(li, {{ WORKGROUP_THREADS }}u / 32u);if (li == 0u) { causalValuesFinite = select(0u, 1u, atomicLoad(&causalValueNonFinite) == 0u); }if (workgroupUniformLoad(&causalValuesFinite) == 0u) {// Each output belongs to one invocation. Excluded keys are never evaluated,// preserving the operator's causal/window semantics even for nonfinite V.for (var flat = li; flat < TILE_M * TILE_N; flat += {{ WORKGROUP_THREADS }}u) {let row = causal_row_base + flat / TILE_N;let col = causal_col_base + flat % TILE_N;if (row < params.qSeq && col < HEAD_DIM) {let row_end = u32(clamp(causal_offset + i32(row) + 1, 0, i32(causal_live)));let row_start = {% if SCORE_WINDOW %}u32(max(causal_offset + i32(row) + 1 - i32(min(params.windowSize, causal_live)), 0)){% else %}0u{% endif %};var sum = {{ "scaled_value_zero()" if SAFE_VALUE_REDO else "0.0" }};let row_stat = {{ SCRATCH_HEAD }} * params.qSeq + row;let row_m = rowStats[row_stat * 2u];let row_d = rowStats[row_stat * 2u + 1u];for (var key = row_start; key < row_end && row_d != 0.0; key++) {let score = scores[{{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq + row * params.kvSeq + key];{% if SAFE_VALUE_REDO %}sum = scaled_value_add(sum, exp_shift(score, row_m), {{ operand_load("value", kv_index("key", "col")) }});{% else %}let probability = f32({{ MT }}(exp_shift(score, row_m) / row_d));sum = fma(probability, f32({{ operand_load("value", kv_index("key", "col")) }}), sum);{% endif %}}output[{{ q_index("row", "col") }}] = {{ ST }}({% if SAFE_VALUE_REDO %}scaled_value_mean(sum, row_d){% else %}sum{% endif %});}}return;}{% endif %}matrixSoftwareLane = li % 32u;if (matrixAcceptedHere) {let lane = matrixPhysicalLane;{{ matrixKernelBody(false) }}} else {let matrixRole = li / 32u;let lane = li % 32u;{{ matrixKernelBody(true) }}}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768{% set MT = "f16" if operandF16 | default(false) else "f32" %}{% set ST = MT %}{% set scorePhase = phase == "score" %}{% set FUSED_SOFTMAX = fusedSoftmax | default(false) %}{% set SAFE_VALUE_REDO = FUSED_SOFTMAX and not scorePhase and MT == "f32" %}{% set EMIT_ROW_STATS = emitRowStats | default(false) %}{% set SCORE_BIAS = scorePhase and scoreBias | default(false) %}{% set USE_SEQLENS = useSeqlens | default(false) %}{% set CAUSAL = causalRightAlign | default(false) %}{% set SCORE_WINDOW = CAUSAL and scoreWindow | default(false) %}{% set kvLayout = kvLayout | default(layout) %}{% set kvHeadMajor = kvLayout == "bhsd" %}{% set SCRATCH_HEAD = "(b * HEADS + h)" %}{% set WIDTH = matrixSubgroupWidth %}{% set GROUPS = (128 / WIDTH) | int %}{% set OWNED = (4 / GROUPS) | int %}{% set TM = matrixM * 2 %}{% set TN = matrixN * 2 %}{% set TK = matrixK %}{% set A_COUNT = TM * TK %}{% set B_COUNT = TN * TK %}{% set C_COUNT = TM * TN %}{% set OPERAND_BYTES = 2 if MT == "f16" else 4 %}{% set ARENA_BYTES = max((A_COUNT + B_COUNT) * OPERAND_BYTES, C_COUNT * 4) %}{% set USE_VIEW = device.wgslLanguageFeatures.has("buffer_view") %}{% macro q_index(row, d) %}(b * params.qSeq + {{ row }}) * HIDDEN + h * HEAD_DIM + {{ d }}{% endmacro %}{% macro kv_index(seq, d) %}{% if kvHeadMajor %}((b * KV_HEADS + h_kv) * params.kvSeq + {{ seq }}) * HEAD_DIM + {{ d }}{% else %}(b * params.kvSeq + {{ seq }}) * KV_HIDDEN + h_kv * HEAD_DIM + {{ d }}{% endif %}{% endmacro %}{% macro operand(name, index) %}{{ name }}[{{ index }}]{% endmacro %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {% if queryFloor %}max({{ queryFloor }}, {{ attn_seqlens_count(index) }}){% else %}{{ attn_seqlens_count(index) }}{% endif %}){% endmacro %}enable subgroups;enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{% if USE_VIEW %}requires buffer_view;{% endif %}{{ env.wgsl.resourceDeclarations }}const HEADS: u32 = {{ qNumHeads }}u;const KV_HEADS: u32 = {{ kvNumHeads | default(qNumHeads) }}u;const HEAD_DIM: u32 = {{ headDim }}u;const HIDDEN: u32 = {{ qHidden }}u;{% if not kvHeadMajor %}const KV_HIDDEN: u32 = KV_HEADS * HEAD_DIM;{% endif %}{% if EMIT_ROW_STATS %}const STAT_SLOTS: u32 = {{ statSlots }}u;{% endif %}const TILE_M: u32 = {{ TM }}u;const TILE_N: u32 = {{ TN }}u;const TILE_K: u32 = {{ TK }}u;{% if USE_VIEW %}// Operand reads end at the final reduction barrier. Result fragments then// overwrite that dead staging arena; the epilogue reads only its f32 view.var<workgroup> matrixArena: buffer<{{ ARENA_BYTES }}>;{% else %}var<workgroup> tileA: array<{{ MT }}, {{ A_COUNT }}>;var<workgroup> tileB: array<{{ MT }}, {{ B_COUNT }}>;var<workgroup> tileC: array<f32, {{ C_COUNT }}>;{% endif %}{% if FUSED_SOFTMAX %}var<workgroup> softmaxM: array<f32, {{ TM }}>;var<workgroup> softmaxD: array<f32, {{ TM }}>;{% endif %}{% if FUSED_SOFTMAX or EMIT_ROW_STATS %}// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret// a zero final denominator according to their public semantics. Using -inf// here changes +inf-row behavior.const FLT_MAX: f32 = 3.4028234663852886e38;
fn is_finite_f32(value: f32) -> bool { return select(false, value <= FLT_MAX, value >= -FLT_MAX);}
// x - m that is exactly 0 when x equals a finite m, so exp(shifted) == 1// exactly at the row max. `x - x` on an infinite max is a legal fast-math// fold to 0, which would silently turn +inf rows finite — the explicit// equality test keeps the NaN propagation of the serial kernels.fn shifted_value(value: f32, maxValue: f32) -> f32 { let equalFiniteMax = select(false, value == maxValue, is_finite_f32(maxValue)); return select(value - maxValue, 0.0, equalFiniteMax);}
fn exp_shift(value: f32, maxValue: f32) -> f32 { return exp(shifted_value(value, maxValue));}{% endif %}{% if SAFE_VALUE_REDO %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} { let bits = bitcast<{{ bitsType }}>(x); return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} { let swap = abs(a) < abs(b); let larger = select(a, b, swap); let smaller = select(b, a, swap); // Keep the rounded high-part difference observable before subtracting it // from the smaller addend. Reassociation here erases the residual. return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }
{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar { return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool { return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 { if (a.hi == 0.0) { if (a.lo == 0.0) { return -1024; } return a.exponent + frexp(a.lo).exp; } if (!scaled_value_scalar_finite(a.hi)) { return 1024; } return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 { let bits = bitcast<u32>(value); let sign = bits & 0x80000000u; let fraction = bits & 0x007fffffu; let inputExponent = i32((bits >> 23u) & 0xffu); if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; } var significand = fraction | 0x00800000u; var exponent = inputExponent + shift; if (inputExponent == 0) { let normalize = countLeadingZeros(fraction) - 8u; significand = fraction << normalize; exponent = 1 + shift - i32(normalize); } if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); } if (exponent > 0) { return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu)); } let distance = u32(1 - exponent); if (distance > 24u) { return bitcast<f32>(sign); } let high = significand >> distance; let remainder = significand & ((1u << distance) - 1u); let halfway = 1u << (distance - 1u); let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u); return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar { if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); } if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); } return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar { let nextHi = fma(hi, 1.0, lo); let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %}; if (nextHi == 0.0) { return scaled_value_scalar_zero(); } if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); } let parts = frexp(nextHi); let rawExponent = exponent + parts.exp; // Ordinary magnitudes return to the unscaled fast path. The margin keeps // boundary values away from overflow/underflow while scaling the low word. if (rawExponent >= -120 && rawExponent <= 120) { return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0); } return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar { let sum = fma(a.hi, 1.0, product); let bv = fma(-1.0, a.hi, sum); let av = fma(-1.0, bv, sum); let ae = fma(-1.0, av, a.hi); let be = fma(-1.0, bv, product); let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error); let hi = fma(sum, 1.0, residual); return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar { if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) || !scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) || !scaled_value_scalar_finite(weight)) { return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0); } if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; } if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; } if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) { let product = fma(weight, b.hi, 0.0); let lowProduct = fma(weight, b.lo, 0.0); let rawSum = fma(a.hi, 1.0, product); let productNormal = abs(product) >= 1.1754943508222875e-38; if (productNormal && scaled_value_scalar_finite(product) && scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) { let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct); let result = scaled_value_scalar_add_words(a, product, error); if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; } } } // Decompose BEFORE multiplying: a merge coefficient may exceed one, so // its unscaled product with a finite partial mean need not fit in f32. var other = b; if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); } let wp = frexp(weight); let vp = frexp(other.hi); let productExponent = other.exponent + wp.exp + vp.exp; let commonExponent = max(scaled_value_scalar_leading(a), productExponent); let aligned = scaled_value_scalar_align(a, commonExponent); let product = fma(wp.fract, vp.fract, 0.0); let productError = fma(wp.fract, vp.fract, -product); let shift = productExponent - commonExponent; let highWord = scaled_value_scalar_shift(product, shift); let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0, fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %} let sum = aligned.hi + highWord; let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord; return scaled_value_scalar_finish(sum, low, commonExponent);{% else %} let result = scaled_value_scalar_add_words(aligned, highWord, lowWord); return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 { if (denominator == 0.0) { return 0.0; } if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; } if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) { return fma(a.hi, 1.0, a.lo) / denominator; } let valueParts = frexp(a.hi); let denominatorParts = frexp(denominator); let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp)); let quotient = mantissa / denominatorParts.fract; return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue { return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue { let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %} // FastTwoSum recovers the rounding error with the larger magnitude first. let takeProduct = abs(acc.hi) < abs(product); let larger = select(acc.hi, product, takeProduct); let smaller = select(product, acc.hi, takeProduct); let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller); let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %} let bv = fma({{ type }}(-1.0), acc.hi, sum); let av = fma({{ type }}(-1.0), bv, sum); let ae = fma({{ type }}(-1.0), av, acc.hi); let be = fma({{ type }}(-1.0), bv, product); let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %} let hi = fma(sum, {{ type }}(1.0), residual); return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue { let w = {{ type }}(weight); let product = fma(w, value, {{ type }}(0.0)); return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} { return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool { return all(start.exponent == {{ exponentType }}(0)) && all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) & (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) & ({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile { let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37))); let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u)); return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile { let w = {{ type }}(weight); let sum = fma(w, value, tile.sum); let change = fma({{ type }}(-1.0), tile.sum, sum); return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue { let high = fma({{ type }}(-1.0), tile.offset, tile.sum); let sum = fma(high, {{ type }}(1.0), tile.low); let bv = fma({{ type }}(-1.0), high, sum); let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low)); return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool { return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) && {% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) | (bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep { let w = {{ type }}(weight); let product = fma(w, value, {{ type }}(0.0)); let sum = scaled_value_add_words(acc, product, fma(w, value, -product)); let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38)); let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) & {% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38)); return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent), fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %} // Ordinary raw products use one vector compensated sum. Every exceptional // component falls back to the same scalar exponent-aware implementation. if (all(acc.exponent == {{ exponentType }}(0)) && all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) && all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) { let step = scaled_value_add_step(acc, weight, value); if (all(step.exact)) { return step.value; } }{% endif %} var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} 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)); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %} let w = {{ type }}(correction); let product = fma(w, acc.hi, {{ type }}(0.0)); let scaled = scaled_value_add_words(scaled_value_zero(), product, fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0)))); let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0); let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) & (abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) & (zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero), select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue { // From finite words at exponent zero, the scalar path below leaves zero // words for a zero value or correction, the value itself for a unit // correction, and otherwise this compensated product onto zero words when // the product is normal and the low word finite (which bounds the rest, as // in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) { return {{ rescale_vector_value() }}; } var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }})); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue { var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} 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 }})); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} { // Words at exponent zero well inside the normal range, with a normal // quotient: the scalar path below divides this same sum by this same // denominator, each scaled by a power of two, so it rounds to this quotient // wherever division is scale-invariant. Bounding the denominator above also // keeps a division through its reciprocal clear of a subnormal reciprocal. let d = {{ type }}(denominator); let sum = fma(acc.hi, {{ type }}(1.0), acc.lo); let quotient = sum / d; if (all((acc.exponent == {{ exponentType }}(0)) & (abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) & (abs(acc.lo) <= abs(acc.hi)) & (abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) & ((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) { return quotient; } var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %} return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} { var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %} return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue { var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %} let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }}); result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %} return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("f32") }}{% endif %}// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}{% if not scorePhase and CAUSAL %}// Visibility-changing nonfinite values require explicit per-row masks.// Common visible values retain their ordinary native propagation.var<workgroup> matrixNonFinite: atomic<u32>;var<workgroup> matrixFinite: u32;{% endif %}{% macro views() %}{% if USE_VIEW %} let tileA = bufferView<array<{{ MT }}, {{ A_COUNT }}>>(&matrixArena, 0u); let tileB = bufferView<array<{{ MT }}, {{ B_COUNT }}>>(&matrixArena, {{ A_COUNT * OPERAND_BYTES }}u); let tileC = bufferView<array<f32, {{ C_COUNT }}>>(&matrixArena, 0u);{% endif %}{% endmacro %}{% macro element(name, offset) %}{% if USE_VIEW %}(*{{ name }}){% else %}{{ name }}{% endif %}[{{ offset }}]{% endmacro %}{% macro pointer(name) %}{% if USE_VIEW %}{{ name }}{% else %}&{{ name }}{% endif %}{% endmacro %}{% macro loadTiles() %} for (var flat = tid; flat < TILE_M * TILE_K; flat += 128u) { let tileRow = flat / TILE_K; let row = rowBase + tileRow; let k = kk + flat % TILE_K; var loaded = {{ MT }}(0);{% if scorePhase %} if (row < params.qSeq && k < HEAD_DIM) { loaded = {{ operand("query", q_index("row", "k")) }}; }{% else %} if (row < params.qSeq && k < {% if CAUSAL %}inner{% else %}kvActive{% endif %}{% if CAUSAL %} && i32(k) <= causalOffset + i32(row){% endif %}{% if SCORE_WINDOW %} && i32(k) + i32(min(params.windowSize, kvActive)) > causalOffset + i32(row){% endif %}{% if FUSED_SOFTMAX and (CAUSAL or USE_SEQLENS) %} && softmaxD[tileRow] != 0.0{% endif %}) { let score = scores[{{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq + row * params.kvSeq + k];{% if SAFE_VALUE_REDO %} let weight = exp_shift(score, softmaxM[tileRow]); loaded = weight / softmaxD[tileRow]; if (weight > 0.0 && loaded < 1.0842021724855044e-19) { valueRangeNeedsFallback = true; }{% else %} loaded = {{ MT }}(exp_shift(score, softmaxM[tileRow]) / softmaxD[tileRow]);{% endif %} }{% endif %} {{ element("tileA", "flat") }} = loaded; } for (var flat = tid; flat < TILE_N * TILE_K; flat += 128u) { let col = colBase + flat / TILE_K; let k = kk + flat % TILE_K; var loaded = {{ MT }}(0);{% if scorePhase %} if (col < kvActive && k < HEAD_DIM) { loaded = {{ operand("key", kv_index("col", "k")) }}; }{% else %} if (k < {% if CAUSAL %}inner{% else %}kvActive{% endif %}{% if SCORE_WINDOW %} && k >= firstLiveKey{% endif %} && col < HEAD_DIM) { loaded = {{ operand("value", kv_index("k", "col")) }}; }{% if SAFE_VALUE_REDO %} if (abs(loaded) > 0.0 && abs(loaded) < 1.0842021724855044e-19) { valueRangeNeedsFallback = true; }{% endif %}{% endif %} {{ element("tileB", "flat") }} = loaded; }{% endmacro %}{% macro scoreValue(value, row, col) %} var scored = {{ value }} * {{ attentionScaleExpression }};{% if SCORE_BIAS %} let biasB = select(b, 0u, params.biasBatch == 1u); let biasH = select(h, 0u, params.biasHeads == 1u); scored += attention_bias[((biasB * params.biasHeads + biasH) * params.qSeq + {{ row }}) * params.kvSeq + {{ col }}];{% endif %}{% if CAUSAL %} if (i32({{ col }}) > causalOffset + i32({{ row }})) { scored = -FLT_MAX; }{% endif %}{% if USE_SEQLENS %} if ({{ col }} >= kvActive) { scored = -FLT_MAX; }{% endif %}{% if SCORE_WINDOW %} if (i32({{ col }}) + i32(min(params.windowSize, kvActive)) <= causalOffset + i32({{ row }})) { scored = -FLT_MAX; }{% endif %}{% endmacro %}@compute @workgroup_size(128, 1, 1)fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) tid: u32, @builtin(subgroup_size) width: u32) { // Claim every active population before choosing lane-owned matrix banks. // The uniform topology check completes before native ownership below. let role = claimMatrixSubgroupRole(width, {{ WIDTH }}u);{% if scorePhase or not CAUSAL %} let provenTopology = matrixTopologyAccepted(tid, {{ GROUPS }}u);{% endif %} let h = wg.z % HEADS; let b = wg.z / HEADS; let h_kv = h / (HEADS / KV_HEADS); let rowBase = wg.y * TILE_M; let colBase = wg.x * TILE_N; let kvActive = {% if USE_SEQLENS %}{{ attn_seqlens_bound("params.kvSeq", "b", "params.qSeq" if seqlensQueryFloor | default(true) else "") }}{% else %}params.kvSeq{% endif %};{% if CAUSAL %} let causalOffset = i32(kvActive) - i32(params.qSeq);{% endif %}{% if scorePhase and CAUSAL %} // Whole dead key tiles publish the online identity before uniformly leaving. if (i32(colBase) > causalOffset + i32(rowBase + TILE_M) - 1 || colBase >= kvActive{% if SCORE_WINDOW %} || i32(colBase + TILE_N) <= causalOffset + i32(rowBase) + 1 - i32(min(params.windowSize, kvActive)){% endif %}) { for (var tileRow = tid; tileRow < TILE_M; tileRow += 128u) { let row = rowBase + tileRow; if (row < params.qSeq) { let index = (({{ SCRATCH_HEAD }} * STAT_SLOTS + wg.x) * params.qSeq + row) * 2u; scorePartials[index] = -FLT_MAX; scorePartials[index + 1u] = 0.0; } } return; }{% endif %}{{ views() }}{% if FUSED_SOFTMAX %} for (var row = tid; row < TILE_M; row += 128u) { let statRow = {{ SCRATCH_HEAD }} * params.qSeq + min(rowBase + row, params.qSeq - 1u); softmaxM[row] = rowStats[statRow * 2u]; softmaxD[row] = rowStats[statRow * 2u + 1u]; } workgroupBarrier();{% endif %} let inner = {% if scorePhase %}HEAD_DIM{% elif CAUSAL %}u32(clamp(causalOffset + i32(min(rowBase + TILE_M, params.qSeq)), 0, i32(kvActive))){% else %}kvActive{% endif %};{% if not scorePhase and SCORE_WINDOW %} let firstLiveKey = u32(max(causalOffset + i32(rowBase) + 1 - i32(min(params.windowSize, kvActive)), 0)); let innerStart = firstLiveKey / TILE_K * TILE_K;{% endif %}{% if not scorePhase and CAUSAL %} let commonEnd = u32(clamp(causalOffset + i32(rowBase) + 1, 0, i32(kvActive))); let commonStart = {% if SCORE_WINDOW %}u32(max(causalOffset + i32(min(rowBase + TILE_M, params.qSeq)) - i32(min(params.windowSize, kvActive)), 0)){% else %}0u{% endif %}; let leftEnd = min(commonStart, inner); let rightStart = max(commonEnd, leftEnd); // Scan union minus intersection: only visibility-changing keys require // an explicit per-row mask when V is nonfinite after operand conversion.{% for edge in range(2) %} { let edgeStart = {% if edge == 0 %}{% if SCORE_WINDOW %}firstLiveKey{% else %}0u{% endif %}{% else %}rightStart{% endif %}; let edgeEnd = {% if edge == 0 %}leftEnd{% else %}inner{% endif %}; let finiteColumn = colBase + tid % TILE_N; for (var k = edgeStart + tid / TILE_N; k < edgeEnd; k += {{ 128 // TN }}u) { if (finiteColumn < HEAD_DIM) { let bits = bitcast<u32>(f32({{ MT }}({{ operand("value", kv_index("k", "finiteColumn")) }}))); if ((bits & 0x7f800000u) == 0x7f800000u) { atomicOr(&matrixNonFinite, 1u); } } } }{% endfor %} let provenTopology = matrixTopologyAccepted(tid, {{ GROUPS }}u); if (tid == 0u) { matrixFinite = select(0u, 1u, atomicLoad(&matrixNonFinite) == 0u); } let nativeTopology = provenTopology && workgroupUniformLoad(&matrixFinite) != 0u;{% else %} let nativeTopology = provenTopology;{% endif %}{% if SAFE_VALUE_REDO %} // The subgroup-layout check has finished with its scratch. Reuse it for the rare // normalized-product range fallback without increasing workgroup storage. if (tid == 0u) { atomicStore(&matrixRejected, 0u); } workgroupBarrier(); var valueRangeNeedsFallback = false;{% endif %} if (nativeTopology) {{% for slot in range(OWNED) %} let bank{{ slot }} = role + {{ slot * GROUPS }}u; let bankRow{{ slot }} = bank{{ slot }} / 2u * {{ matrixM }}u; let bankCol{{ slot }} = bank{{ slot }} % 2u * {{ matrixN }}u; var acc{{ slot }}: subgroup_matrix_result<f32, {{ matrixN }}, {{ matrixM }}>;{% endfor %} for (var kk = {% if not scorePhase and SCORE_WINDOW %}innerStart{% else %}0u{% endif %}; kk < inner; kk += TILE_K) {{{ loadTiles() }} workgroupBarrier();{% for slot in range(OWNED) %} let left{{ slot }} = subgroupMatrixLoad<subgroup_matrix_left<{{ MT }}, {{ matrixK }}, {{ matrixM }}>, row_major>({{ pointer("tileA") }}, bankRow{{ slot }} * TILE_K, TILE_K); let right{{ slot }} = subgroupMatrixLoad<subgroup_matrix_right<{{ MT }}, {{ matrixN }}, {{ matrixK }}>, col_major>({{ pointer("tileB") }}, bankCol{{ slot }} * TILE_K, TILE_K); acc{{ slot }} = subgroupMatrixMultiplyAccumulate(left{{ slot }}, right{{ slot }}, acc{{ slot }});{% endfor %} workgroupBarrier(); }{% for slot in range(OWNED) %} subgroupMatrixStore<row_major>({{ pointer("tileC") }}, bankRow{{ slot }} * TILE_N + bankCol{{ slot }}, acc{{ slot }}, TILE_N);{% endfor %} } else { // Independent invocation ownership handles any legal subgroup partition. var acc: array<f32, {{ (C_COUNT + 127) // 128 }}>; for (var kk = {% if not scorePhase and SCORE_WINDOW %}innerStart{% else %}0u{% endif %}; kk < inner; kk += TILE_K) {{{ loadTiles() }} workgroupBarrier(); for (var cell = 0u; cell < {{ (C_COUNT + 127) // 128 }}u; cell++) { let flat = tid + cell * 128u; if (flat < TILE_M * TILE_N) { let row = flat / TILE_N; let col = flat % TILE_N; for (var k = 0u; k < TILE_K; k++) {{% if not scorePhase and CAUSAL %} let key = kk + k; let query = rowBase + row; if (key < kvActive && softmaxD[row] != 0.0 && i32(key) <= causalOffset + i32(query){% if SCORE_WINDOW %} && i32(key) + i32(min(params.windowSize, kvActive)) > causalOffset + i32(query){% endif %}) {{% endif %} acc[cell] = fma(f32({{ element("tileA", "row * TILE_K + k") }}), f32({{ element("tileB", "col * TILE_K + k") }}), acc[cell]);{% if not scorePhase and CAUSAL %} }{% endif %} } } } workgroupBarrier(); } for (var cell = 0u; cell < {{ (C_COUNT + 127) // 128 }}u; cell++) { let flat = tid + cell * 128u; if (flat < TILE_M * TILE_N) { {{ element("tileC", "flat") }} = acc[cell]; } } } workgroupBarrier();{% if SAFE_VALUE_REDO %} if (valueRangeNeedsFallback) { atomicOr(&matrixRejected, 1u); } workgroupBarrier(); if (tid == 0u) { matrixAccepted = atomicLoad(&matrixRejected); } if (workgroupUniformLoad(&matrixAccepted) != 0u) { // Retain raw exp weights until the scaled value product. Both a tiny // probability times a large V and many tiny products can have normal means. for (var flat = tid; flat < TILE_M * TILE_N; flat += 128u) { let tileRow = flat / TILE_N; let row = rowBase + tileRow; let col = colBase + flat % TILE_N; if (row < params.qSeq && col < HEAD_DIM) { let denominator = softmaxD[tileRow]; let rowEnd = {% if CAUSAL %}u32(clamp(causalOffset + i32(row) + 1, 0, i32(inner))){% else %}inner{% endif %}; let rowStart = {% if SCORE_WINDOW %}u32(max(causalOffset + i32(row) + 1 - i32(min(params.windowSize, kvActive)), 0)){% else %}0u{% endif %}; var sum = scaled_value_zero(); for (var key = rowStart; key < rowEnd && denominator != 0.0; key++) { let score = scores[{{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq + row * params.kvSeq + key]; sum = scaled_value_add(sum, exp_shift(score, softmaxM[tileRow]), {{ operand("value", kv_index("key", "col")) }}); } output[{{ q_index("row", "col") }}] = scaled_value_mean(sum, denominator); } } return; }{% endif %} for (var flat = tid; flat < TILE_M * TILE_N; flat += 128u) { let row = rowBase + flat / TILE_N; let col = colBase + flat % TILE_N; if (row < params.qSeq && col < {% if scorePhase %}params.kvSeq{% else %}HEAD_DIM{% endif %}) {{% if scorePhase %}{{ scoreValue(element("tileC", "flat"), "row", "col") }} scores[{{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq + row * params.kvSeq + col] = scored;{% else %} output[{{ q_index("row", "col") }}] = {{ ST }}({% if FUSED_SOFTMAX and (CAUSAL or USE_SEQLENS) %}select({{ element("tileC", "flat") }}, 0.0, softmaxD[flat / TILE_N] == 0.0){% else %}{{ element("tileC", "flat") }}{% endif %});{% endif %} } }{% if EMIT_ROW_STATS %} // One invocation owns each complete row, independently of physical lanes. // Each key tile contributes one (m,d) slot; no 8-row quad assumption remains. for (var tileRow = tid; tileRow < TILE_M; tileRow += 128u) { let row = rowBase + tileRow; if (row < params.qSeq) { var m = -FLT_MAX; var d = 0.0; for (var tileCol = 0u; tileCol < TILE_N; tileCol++) { let col = colBase + tileCol; if (col < params.kvSeq{% if USE_SEQLENS %} && col < kvActive{% endif %}{% if CAUSAL %} && i32(col) <= causalOffset + i32(row){% endif %}{% if SCORE_WINDOW %} && i32(col) + i32(min(params.windowSize, kvActive)) > causalOffset + i32(row){% endif %}) {{{ scoreValue(element("tileC", "tileRow * TILE_N + tileCol"), "row", "col") }} let previous = m; m = max(m, scored); d = d * exp_shift(previous, m) + exp_shift(scored, m); } } let index = (({{ SCRATCH_HEAD }} * STAT_SLOTS + wg.x) * params.qSeq + row) * 2u; scorePartials[index] = m; scorePartials[index + 1u] = d; } }{% endif %}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119{% set CAUSAL_ROWS = false %}{%- set LIVE_ROWS_PER_BATCH = seqlensRowsPerBatch | default(0) %}{% set COLS_EXPR = "COLS" %}{% set ROWS_EXPR = "params.rows" %}enable subgroups;{{ env.wgsl.resourceDeclarations }}
// In-place row softmax for materialized f32 attention. The default path reads// each scalar twice; the register-cached vec4 path eliminates the second read.const WG: u32 = {{ materializedSoftmaxWg }}u;{% set SCALED_SCORE = "scores[base + c]" %}const COLS: u32 = {{ materializedSoftmaxCols }}u;// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep// `m - m` finite so an empty lane / all--inf row contributes the exact// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret// a zero final denominator according to their public semantics. Using -inf// here changes +inf-row behavior.const FLT_MAX: f32 = 3.4028234663852886e38;
fn is_finite_f32(value: f32) -> bool { return select(false, value <= FLT_MAX, value >= -FLT_MAX);}
// x - m that is exactly 0 when x equals a finite m, so exp(shifted) == 1// exactly at the row max. `x - x` on an infinite max is a legal fast-math// fold to 0, which would silently turn +inf rows finite — the explicit// equality test keeps the NaN propagation of the serial kernels.fn shifted_value(value: f32, maxValue: f32) -> f32 { let equalFiniteMax = select(false, value == maxValue, is_finite_f32(maxValue)); return select(value - maxValue, 0.0, equalFiniteMax);}
fn exp_shift(value: f32, maxValue: f32) -> f32 { return exp(shifted_value(value, maxValue));}// Workgroup-cooperative merge of per-thread online-softmax (m, d) partials:// mNew = max(m1, m2)// dNew = d1 * exp(m1 - mNew) + d2 * exp(m2 - mNew)// Both the subgroup and portable barrier-tree engines return the same merged// pair to every invocation. Repeated merges require a workgroup barrier between// calls before their shared partial storage is reused.// Cross-subgroup merge that assumes nothing about which invocations share a// subgroup or how many subgroups there are: each subgroup's elected lane// publishes the subgroup pair in the slot at its OWN invocation index and sets// that index's bit in a workgroup bitmask; thread 0 then folds exactly the// published slots, in ascending index order (the online (m, d) merge is not// float-associative, so the order is fixed), and clears the mask for the next// call as it reads it. Workgroup memory starts zeroed, so the mask needs no// setup. Same three collectives as a single-subgroup reduce, two barriers.var<workgroup> partialM: array<f32, WG>;var<workgroup> partialD: array<f32, WG>;var<workgroup> leaderMask: array<atomic<u32>, (WG + 31u) / 32u>;var<workgroup> combinedMD: vec2<f32>;
fn combine_partials(m: f32, d: f32, lidx: u32) -> vec2<f32> { let sgM = subgroupMax(m); // A lane with no elements contributes d == 0 (exact identity). A +inf // element made exp(inf - inf) = NaN stick in that lane's d; a NaN element // landed in d via exp(NaN); both survive the merge and are detected by the // code after the reduction. let sgD = subgroupAdd(d * exp_shift(m, sgM)); if (subgroupElect()) { partialM[lidx] = sgM; partialD[lidx] = sgD; atomicOr(&leaderMask[lidx / 32u], 1u << (lidx % 32u)); } workgroupBarrier(); if (lidx == 0u) { var accM = -FLT_MAX; var accD = 0.0; for (var w = 0u; w < (WG + 31u) / 32u; w = w + 1u) { var bits = atomicExchange(&leaderMask[w], 0u); while (bits != 0u) { let slot = w * 32u + firstTrailingBit(bits); bits = bits & (bits - 1u); let mNew = max(accM, partialM[slot]); accD = accD * exp_shift(accM, mNew) + partialD[slot] * exp_shift(partialM[slot], mNew); accM = mNew; } } combinedMD = vec2<f32>(accM, accD); } workgroupBarrier(); return combinedMD;}
@compute @workgroup_size(WG, 1, 1)fn main( @builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) { let row = wg.x + wg.y * {{ DISPATCH_FOLD_WIDTH }}u; if (row >= {{ ROWS_EXPR }}) { return; } let base = row * {{ COLS_EXPR }};{% if LIVE_ROWS_PER_BATCH %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {{ attn_seqlens_count(index) }}){% endmacro %} // Padded scores can contain NaNs. Only the live prefix contributes to the row statistics. let validKeys = {{ attn_seqlens_bound(COLS_EXPR, "row / " ~ LIVE_ROWS_PER_BATCH ~ "u") }};{% endif %} var m = -FLT_MAX; var d = 0.0; for (var c = lid.x; c < {{ "validKeys" if CAUSAL_ROWS or LIVE_ROWS_PER_BATCH else COLS_EXPR }}; c = c + WG) { let v = {{ SCALED_SCORE }}; let mNew = max(m, v); d = d * exp_shift(m, mNew) + exp_shift(v, mNew); m = mNew; } let md = combine_partials(m, d, lid.x); let rowM = md.x; let rowD = md.y;
// Keep the raw score matrix for the value pass: a tiny probability can carry // a normal weighted value and must not be rounded away in an intermediate. if (lid.x == 0u) { rowStats[row * 2u] = rowM; rowStats[row * 2u + 1u] = rowD; }}123453 unmodified lines91011121314151617181920213 unmodified lines252627282930313233343536373839404142434445464748495051525354555614 unmodified lines7172737475767778798027 unmodified lines1081091101111121131 unmodified line11511611711811912012112212312412512612712816 unmodified lines145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193{{ env.wgsl.resourceDeclarations }}{% set MASK_BATCH = "batch * params.maskBatchStride + " %}// Online-softmax attention fallback with no feature requirements: one// workgroup per (batch, head, query token) walks the keys serially; the3 unmodified lines// Layout: rank-3 token-major [batch, seq, heads * headDim].// An omitted scale uses 1/sqrt(headDim); explicit zero remains zero through// the scaleIsExplicitZero specialization.{% if hasBias %}// Packed [Q; K; V] bias rows are applied during the serial key walk.{% endif %}{% if hasMask %}// Additive per-score attention bias with broadcast strides: a stride of 0// collapses that axis (batch and/or head broadcast).{% endif %}const HEAD_DIM: u32 = {{ headDim }}u;const Q_HIDDEN: u32 = {{ qHidden }}u;const KV_HIDDEN: u32 = {{ kvHidden }}u;3 unmodified lines{% set kvHeads = "KV_HEADS" %}const WG: u32 = {{ workgroupSize }}u;{% set dotType = "f32" %}// Retain product and addition residuals across a dot product. Explicit fma// boundaries preserve the addition error transform under reassociation.struct DotAccumulator {hi: {{ dotType }},lo: {{ dotType }},}fn dot_accumulate(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator {let product = fma(a, b, {{ dotType }}(0.0));let productError = fma(a, b, -product);let sum = fma(acc.hi, {{ dotType }}(1.0), product);let bv = fma({{ dotType }}(-1.0), acc.hi, sum);let av = fma({{ dotType }}(-1.0), bv, sum);let ae = fma({{ dotType }}(-1.0), av, acc.hi);let be = fma({{ dotType }}(-1.0), bv, product);let error = fma(fma(fma(ae, {{ dotType }}(1.0), be), {{ dotType }}(1.0), acc.lo), {{ dotType }}(1.0), productError);let hi = fma(sum, {{ dotType }}(1.0), error);return DotAccumulator(hi, fma({{ dotType }}(-1.0), fma({{ dotType }}(-1.0), sum, hi), error));}fn dot_value(acc: DotAccumulator) -> {{ dotType }} {return fma(acc.hi, {{ dotType }}(1.0), acc.lo);}var<workgroup> partial: array<DotAccumulator, WG>;var<workgroup> running_max: f32;var<workgroup> running_denom: f32;var<workgroup> running_out: array<f32, HEAD_DIM>;var<workgroup> previous_scale: f32;{% macro wgsl_tree_reduce_f32(name, mode, buffer="partial", wg="WG", trailingBarrier=true, valueType="f32") %}fn {{ name }}(value: {{ valueType }}, tid: u32) -> {{ valueType }} {14 unmodified linesbreak;}}// The default trailing barrier makes this helper safe for back-to-back calls: every lane reads// slot 0 here, so the next call's first store must not run until all lanes have read it.// `trailingBarrier=false` is safe only when the buffer is never written again before kernel exit.let reduced = {{ buffer }}[0];workgroupBarrier();return reduced;}27 unmodified lines// Reduces to exactly one query per workgroup (bit-identical) when nwg.x == qSeq.for (var query_token = wg.x; query_token < params.qSeq; query_token = query_token + nwg.x) {// Row bases: Q/output share one row, K/V rows are kvBase + token * stride.let qBase = (batch * params.qSeq + query_token) * Q_HIDDEN + h * HEAD_DIM;let kvBase = batch * params.kvSeq * KV_HIDDEN + kv_head * HEAD_DIM;1 unmodified lineif (tid == 0u) {running_max = -3.4028234663852886e38;running_denom = 0.0;}for (var d: u32 = tid; d < HEAD_DIM; d = d + WG) {running_out[d] = 0.0;}workgroupBarrier();var maxKj = params.kvSeq;var minKj: u32 = 0u;{% if hasCausal %}maxKj = min(maxKj, select(params.kvSeq, query_token + 1u, params.isCausal != 0u));16 unmodified linesfor (var d: u32 = tid; d < HEAD_DIM; d = d + WG) {var q_value = f32(query[qBase + d]);var k_value = f32(key[kRow + d]);{% if hasBias %}let channel = h * HEAD_DIM + d;q_value = q_value + f32(bias[channel]);k_value = k_value + f32(bias[Q_HIDDEN + channel]);{% endif %}partial_dot = dot_accumulate(partial_dot, q_value, k_value);}// reduce_dot returns the same partial[0] to every lane, so `score` is already// workgroup-uniform; tid==0 advances the running max/denom/scale (broadcast// through shared memory by the barrier below).{% if hasMask %}let maskIndex = {{ MASK_BATCH }}h * params.maskHeadStride + query_token * params.maskSeqStride + key_token;let score = dot_value(reduce_dot(partial_dot, tid)) * scale_value() + f32(attn_mask[maskIndex]);{% else %}let score = dot_value(reduce_dot(partial_dot, tid)) * scale_value();{% endif %}if (tid == 0u) {let next_max = max(running_max, score);let old_factor = exp(running_max - next_max);let new_factor = exp(score - next_max);previous_scale = old_factor;running_max = next_max;running_denom = running_denom * old_factor + new_factor;}workgroupBarrier();let probability_numerator = exp(score - running_max);for (var d: u32 = tid; d < HEAD_DIM; d = d + WG) {var v_value = f32(value[kRow + d]);{% if hasBias %}v_value = v_value + f32(bias[2u * Q_HIDDEN + h * HEAD_DIM + d]);{% endif %}running_out[d] = running_out[d] * previous_scale + probability_numerator * v_value;}workgroupBarrier();}// A query whose every key is masked to -inf (or whose key range is empty)// leaves running_denom at zero; emit a zero row rather than 0 * (1/0) = NaN.let inv_denom = select(0.0, 1.0 / running_denom, running_denom > 0.0);for (var d: u32 = tid; d < HEAD_DIM; d = d + WG) {output[qBase + d] = {{ outputScalar }}(running_out[d] * inv_denom);}// Separate this query's reads of the shared running state from the next// iteration's re-initialization (grid-stride; no-op when the loop runs once).1234563 unmodified lines1011121314153 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451514 unmodified lines53053153253353453553653753827 unmodified lines5665675685695705715725735745751 unmodified line57757857958058158258358458558658758858959059159259316 unmodified lines610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {% if queryFloor %}max({{ queryFloor }}, {{ attn_seqlens_count(index) }}){% else %}{{ attn_seqlens_count(index) }}{% endif %}){% endmacro %}{{ env.wgsl.resourceDeclarations }}// Online-softmax attention fallback with no feature requirements: one// workgroup per (batch, head, query token) walks the keys serially; the3 unmodified lines// Layout: rank-3 token-major [batch, seq, heads * headDim].// An omitted scale uses 1/sqrt(headDim); explicit zero remains zero through// the scaleIsExplicitZero specialization.const HEAD_DIM: u32 = {{ headDim }}u;const Q_HIDDEN: u32 = {{ qHidden }}u;const KV_HIDDEN: u32 = {{ kvHidden }}u;3 unmodified lines{% set kvHeads = "KV_HEADS" %}const WG: u32 = {{ workgroupSize }}u;{% set compensatedValues = compensateValues | default(false) %}{% set COMP_DENOM = compensatedValues and (compensatedOnlineDenominator | default(false)) %}{% if compensatedValues %}{% set dotGuardNonfinite = true %}{% endif %}{% set dotType = "f32" %}{% set protectDifference = false %}// Retain product and addition residuals across a dot product. Explicit fma// boundaries preserve the addition error transform under reassociation.struct DotAccumulator {hi: {{ dotType }},lo: {{ dotType }},}{% if dotRecoverProductResidual | default(false) %}{% set dotBitsType = "u32" %}// Recover an inexact product when a backend returns a zero fma residual.{% set dotExponentType = "i32" %}{% macro dot_parts() -%}let aBits = bitcast<{{ dotBitsType }}>(a);let bBits = bitcast<{{ dotBitsType }}>(b);let pBits = bitcast<{{ dotBitsType }}>(product);let ae = (aBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let be = (bBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);let pe = (pBits >> {{ dotBitsType }}(23u)) & {{ dotBitsType }}(255u);{% endmacro %}fn dot_product_error(a: {{ dotType }}, b: {{ dotType }}, product: {{ dotType }}) -> {{ dotType }} {// Twelve-bit significand parts make each split product exactly representable.let nativeError = fma(a, b, -product);if (nativeError == 0.0) {{{ dot_parts() | indent(4, true) }}let lowProduct = (((aBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u)) *((bBits & {{ dotBitsType }}(0x007fffffu)) | {{ dotBitsType }}(0x00800000u))) & {{ dotBitsType }}(0x00ffffffu);let recover = (nativeError == {{ dotType }}(0.0)) && (lowProduct != {{ dotBitsType }}(0u)) && (ae > {{ dotBitsType }}(0u)) && (ae < {{ dotBitsType }}(255u)) && (be > {{ dotBitsType }}(0u)) && (be < {{ dotBitsType }}(255u)) && (pe > {{ dotBitsType }}(0u)) && (pe < {{ dotBitsType }}(255u));if (recover) {// Normalize before splitting: a normal input can otherwise produce a// subnormal low word that a conformant backend is allowed to flush.let an = bitcast<{{ dotType }}>((aBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u));let bn = bitcast<{{ dotType }}>((bBits & {{ dotBitsType }}(0x807fffffu)) | {{ dotBitsType }}(0x3f800000u));let exponent = select({{ dotExponentType }}(0), {{ dotExponentType }}(ae) + {{ dotExponentType }}(be) - {{ dotExponentType }}(254), recover);let pnExponent = select({{ dotBitsType }}(127u), {{ dotBitsType }}({{ dotExponentType }}(pe) - exponent), recover);let pn = bitcast<{{ dotType }}>((pBits & {{ dotBitsType }}(0x807fffffu)) | (pnExponent << {{ dotBitsType }}(23u)));let ah = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(an) & {{ dotBitsType }}(0xfffff000u));let bh = bitcast<{{ dotType }}>(bitcast<{{ dotBitsType }}>(bn) & {{ dotBitsType }}(0xfffff000u));let al = fma({{ dotType }}(-1.0), ah, an);let bl = fma({{ dotType }}(-1.0), bh, bn);let e0 = fma(ah, bh, -pn);let e1 = fma(al, bh, e0);let e2 = fma(ah, bl, e1);let recovered = ldexp(fma(al, bl, e2), exponent);return select(nativeError, recovered, recover);}}return nativeError;}{% endif %}{% macro dot_step(name, dotGuardNonfinite) %}fn {{ name }}(acc: DotAccumulator, a: {{ dotType }}, b: {{ dotType }}) -> DotAccumulator {let product = fma(a, b, {{ dotType }}(0.0));{% if dotGuardNonfinite | default(false) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);// Nonfinite sums retain ordinary f32 addition classes; Inf-Inf residuals// must not poison a valid infinite dot accumulator.if (!(abs(acc.hi) <= 3.4028234663852886e38) ||!(abs(acc.lo) <= 3.4028234663852886e38) ||!(abs(product) <= 3.4028234663852886e38) ||!(abs(sum) <= 3.4028234663852886e38)) {return DotAccumulator(sum, {{ dotType }}(0.0));}{% endif %} let productError = {% if dotRecoverProductResidual | default(false) %}dot_product_error(a, b, product){% else %}fma(a, b, -product){% endif %};{% if not (dotGuardNonfinite | default(false)) %} let sum = fma(acc.hi, {{ dotType }}(1.0), product);{% endif %} let bv = fma({{ dotType }}(-1.0), acc.hi, sum);let av = fma({{ dotType }}(-1.0), bv, sum);let ae = fma({{ dotType }}(-1.0), av, acc.hi);let be = fma({{ dotType }}(-1.0), bv, product);let error = fma(fma(fma(ae, {{ dotType }}(1.0), be), {{ dotType }}(1.0), acc.lo), {{ dotType }}(1.0), productError);let hi = fma(sum, {{ dotType }}(1.0), error);{% if dotGuardNonfinite | default(false) %} if (!(abs(hi) <= 3.4028234663852886e38)) {return DotAccumulator(hi, {{ dotType }}(0.0));}{% endif %} return DotAccumulator(hi, fma({{ dotType }}(-1.0), fma({{ dotType }}(-1.0), sum, hi), error));}{% endmacro %}{{ dot_step("dot_accumulate", dotGuardNonfinite | default(false)) }}fn dot_value(acc: DotAccumulator) -> {{ dotType }} {return fma(acc.hi, {{ dotType }}(1.0), acc.lo);}{% if COMP_DENOM %}fn attention_denom_update(acc: DotAccumulator, correction: f32, weight: f32) -> DotAccumulator {var scaled = acc;if (correction != 1.0) {scaled = dot_accumulate(DotAccumulator(0.0, 0.0), acc.hi, correction);scaled = dot_accumulate(scaled, acc.lo, correction);}return dot_accumulate(scaled, weight, 1.0);}{% endif %}{% if compensatedValues %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&{% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &{% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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 }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("f32", rescale=true) }}{% endif %}var<workgroup> partial: array<DotAccumulator, WG>;var<workgroup> running_max: f32;var<workgroup> running_denom: {% if COMP_DENOM %}DotAccumulator{% else %}f32{% endif %};{% if not compensatedValues %}var<workgroup> running_out: array<f32, HEAD_DIM>;{% endif %}var<workgroup> previous_scale: f32;{% macro wgsl_tree_reduce_f32(name, mode, buffer="partial", wg="WG", trailingBarrier=true, valueType="f32") %}fn {{ name }}(value: {{ valueType }}, tid: u32) -> {{ valueType }} {14 unmodified linesbreak;}}let reduced = {{ buffer }}[0];// Every lane reads slot 0 above, so a following reduction's first store must not run until// all lanes have read it.workgroupBarrier();return reduced;}27 unmodified lines// Reduces to exactly one query per workgroup (bit-identical) when nwg.x == qSeq.for (var query_token = wg.x; query_token < params.qSeq; query_token = query_token + nwg.x) {{% if compensatedValues %}// Output channels stay with the same lane throughout the serial key sweep.var value_acc: array<ScaledValue, {{ ((headDim + workgroupSize - 1) / workgroupSize) | int }}>;{% endif %}// Row bases: Q/output share one row, K/V rows are kvBase + token * stride.let qBase = (batch * params.qSeq + query_token) * Q_HIDDEN + h * HEAD_DIM;let kvBase = batch * params.kvSeq * KV_HIDDEN + kv_head * HEAD_DIM;1 unmodified lineif (tid == 0u) {running_max = -3.4028234663852886e38;running_denom = {% if COMP_DENOM %}DotAccumulator(0.0, 0.0){% else %}0.0{% endif %};}for (var d: u32 = tid; d < HEAD_DIM; d = d + WG) {{% if compensatedValues %}value_acc[d / WG] = scaled_value_zero();{% else %} running_out[d] = 0.0;{% endif %}}workgroupBarrier();var maxKj = {{ attn_seqlens_bound("params.kvSeq", "batch", "params.qSeq" if seqlensQueryFloor | default(false) else "") }};var minKj: u32 = 0u;{% if hasCausal %}maxKj = min(maxKj, select(params.kvSeq, query_token + 1u, params.isCausal != 0u));16 unmodified linesfor (var d: u32 = tid; d < HEAD_DIM; d = d + WG) {var q_value = f32(query[qBase + d]);var k_value = f32(key[kRow + d]);partial_dot = dot_accumulate(partial_dot, q_value, k_value);}// reduce_dot returns the same partial[0] to every lane, so `score` is already// workgroup-uniform; tid==0 advances the running max/denom/scale (broadcast// through shared memory by the barrier below).let score = dot_value(reduce_dot(partial_dot, tid)) * scale_value();if (tid == 0u) {let next_max = max(running_max, score);let old_factor = exp(running_max - next_max);let new_factor = exp(score - next_max);previous_scale = old_factor;running_max = next_max;{% if COMP_DENOM %} running_denom = attention_denom_update(running_denom, old_factor, new_factor);{% else %} running_denom = running_denom * old_factor + new_factor;{% endif %}}workgroupBarrier();let probability_numerator = exp(score - running_max);for (var d: u32 = tid; d < HEAD_DIM; d = d + WG) {var v_value = f32(value[kRow + d]);{% if compensatedValues %}value_acc[d / WG] = scaled_value_add(scaled_value_rescale(value_acc[d / WG], previous_scale), probability_numerator, v_value);{% else %}running_out[d] = running_out[d] * previous_scale + probability_numerator * v_value;{% endif %}}workgroupBarrier();}{% if COMP_DENOM %} let denominator = dot_value(running_denom);{% endif %} // A query whose every key is masked to -inf (or whose key range is empty)// leaves running_denom at zero; emit a zero row rather than 0 * (1/0) = NaN.{% if not compensatedValues %}let inv_denom = select(0.0, 1.0 / running_denom, running_denom > 0.0);{% endif %}for (var d: u32 = tid; d < HEAD_DIM; d = d + WG) {{% if compensatedValues %}output[qBase + d] = {{ outputScalar }}(select(scaled_value_mean(value_acc[d / WG], {% if COMP_DENOM %}denominator{% else %}running_denom{% endif %}), 0.0, {% if COMP_DENOM %}denominator{% else %}running_denom{% endif %} == 0.0));{% else %}output[qBase + d] = {{ outputScalar }}(running_out[d] * inv_denom);{% endif %}}// Separate this query's reads of the shared running state from the next// iteration's re-initialization (grid-stride; no-op when the loop runs once).
1237 unmodified lines111213141516171819202148 unmodified lines707172737475767778798081828311 unmodified lines95969798991001011021031041051061071081091101111 unmodified line11311411511611711811912012112211 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811 unmodified line18318418518618718818919019119219319419519619719819920020120220320420520616 unmodified lines22322422522622722822923023123223323423523623723823915 unmodified lines2552562572582592602612622632642652666 unmodified lines27327427527627727827928028128228328428513 unmodified lines299300301302303304305306307{% set usesF16 = usesF16 | default(false) %}{% set quantized = quantized | default(false) %}{% set bits = bits | default(0) %}7 unmodified lines// f16 inputs widen to f32 on load; computation and shared memory remain f32,// and results narrow only on store. The casts are identities for f32.{% set IO = "f16" if usesF16 else "f32" %}{% if cooperative %}// One workgroup owns each (batch, qHead, qToken). Lanes partition the key range,// run local online softmax states, then merge max/rescale/sum through workgroup// memory. This exposes parallelism when the query count is small.{% else %}// One invocation owns each (batch, qHead, qToken) and walks the key range. The// larger query grid supplies parallelism without a workgroup-level merge.48 unmodified lines{% if cooperative %}// One allocation avoids the per-variable 16-byte padding between arrays.// The manifest budgets the structure's complete size, rounded to 16 bytes.struct CooperativeState {q: array<f32, HEAD_DIM>,acc: array<f32, HEAD_DIM * WG>,m: array<f32, WG>,l: array<f32, WG>,}var<workgroup> state: CooperativeState;@compute @workgroup_size(WG)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {11 unmodified lines{% if useSeqlens %}// Buffer-sharing caches keep capacity in the BNSH dim2 stride; seqlens_k[b]+1// is the per-batch active end and rows beyond it are untouched storage.let activeEnd = min(totalSeq, max(params.qSeq, u32(seqlens_k[b]) + 1u));{% else %}let activeEnd = totalSeq;{% endif %}{% if not bidirectional or hasRotary %} let absPos = activeEnd - params.qSeq + s;{% endif %}{% if needsOrigin %}// Absolute position of cache row 0 (windowed cache): the query end is the// unclamped total while the cache holds only its last `activeEnd` rows.let origin = max(params.qSeq, u32(seqlens_k[b]) + 1u) - activeEnd;{% endif %}// Cooperative query-vector prep (post norm/rotary) into shared memory.let qBase = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;for (var d = lane; d < HEAD_DIM; d = d + WG) { state.q[d] = f32(query[qBase + d]); }1 unmodified line{% if hasQNorm %}var part = 0.0;for (var d = lane; d < HEAD_DIM; d = d + WG) { part = part + state.q[d] * state.q[d]; }state.m[lane] = part;workgroupBarrier();var ms = 0.0;for (var L = 0u; L < WG; L = L + 1u) { ms = ms + state.m[L]; }let invRms = inverseSqrt(ms / f32(HEAD_DIM) + QK_EPS);for (var d = lane; d < HEAD_DIM; d = d + WG) { state.q[d] = state.q[d] * invRms * f32(q_norm_weight[d]); }workgroupBarrier();11 unmodified linesworkgroupBarrier();{% endif %}let scale = scale_value();let maxKj = {% if bidirectional %}activeEnd{% else %}absPos + 1u{% endif %};var minKj = 0u;if (params.windowSize > 0u && maxKj > params.windowSize) { minKj = maxKj - params.windowSize; }let accBase = lane * HEAD_DIM;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { state.acc[accBase + d] = 0.0; }var m = NEG_INF;var l = 0.0;// Each lane sweeps a strided slice of the key range.for (var j = minKj + lane; j < maxKj; j = j + WG) {let base = ((b * KV_HEADS + hk) * totalSeq + j) * PACKED;var dot = 0.0;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { dot = dot + state.q[d] * read_k(base, d{% if quantized %}, hk{% endif %}); }var score = dot * scale;if (params.softcap > 0.0) { score = params.softcap * tanh(clamp(score / params.softcap, -30.0, 30.0)); }{% if hasBias %}let bb = select(b, 0u, params.biasBatch == 1u);let bh = select(h, 0u, params.biasHeads == 1u);score = score + f32(attn_bias[((bb * params.biasHeads + bh) * params.qSeq + s) * {{ biasStride }} + {{ biasCol }}]);{% endif %}let newM = max(m, score);let corr = exp(m - newM);let p = exp(score - newM);l = l * corr + p;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { state.acc[accBase + d] = state.acc[accBase + d] * corr + p * read_v(base, d{% if quantized %}, hk{% endif %}); }m = newM;}// Flash merge across the WG lanes: global max, rescale, summed denom.state.m[lane] = m;workgroupBarrier();var gm = NEG_INF;for (var L = 0u; L < WG; L = L + 1u) { gm = max(gm, state.m[L]); }let fctr = exp(m - gm);l = l * fctr;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { state.acc[accBase + d] = state.acc[accBase + d] * fctr; }state.l[lane] = l;workgroupBarrier();var glsum = 0.0;for (var L = 0u; L < WG; L = L + 1u) { glsum = glsum + state.l[L]; }var sink = 0.0;{% if hasHeadSink %}sink = f32(head_sink[h]);1 unmodified line{% else %}let useSmooth = params.smoothSoftmax != 0u;{% endif %}var finalM = gm;var smoothTerm = 0.0;if (useSmooth) {finalM = max(gm, sink);smoothTerm = exp(sink - finalM);}let accScale = exp(gm - finalM);// A query whose every key is masked out leaves the denominator at zero (no// head sink to carry mass); emit a zero row instead of 0 * (1/0) = NaN.let denom = smoothTerm + glsum * accScale;let invDenom = select(0.0, accScale / denom, denom > 0.0);// Cross-lane sum of the rescaled V accumulators, written cooperatively.let oBase = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;for (var d = lane; d < HEAD_DIM; d = d + WG) {var sumacc = 0.0;for (var L = 0u; L < WG; L = L + 1u) { sumacc = sumacc + state.acc[L * HEAD_DIM + d]; }output[oBase + d] = {{ IO }}(sumacc * invDenom);}}{% else %}16 unmodified lines{% if useSeqlens %}// Buffer-sharing caches keep capacity in the BNSH dim2 stride; seqlens_k[b]+1// is the per-batch active end and rows beyond it are untouched storage.let activeEnd = min(totalSeq, max(params.qSeq, u32(seqlens_k[b]) + 1u));{% else %}let activeEnd = totalSeq;{% endif %}{% if not bidirectional or hasRotary %} let absPos = activeEnd - params.qSeq + s;{% endif %}{% if needsOrigin %}// Absolute position of cache row 0 (windowed cache): the query end is the// unclamped total while the cache holds only its last `activeEnd` rows.let origin = max(params.qSeq, u32(seqlens_k[b]) + 1u) - activeEnd;{% endif %}// Private query-vector prep (post norm/rotary).var q: array<f32, HEAD_DIM>;let qBase = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;15 unmodified lines}{% endif %}let scale = scale_value();let maxKj = {% if bidirectional %}activeEnd{% else %}absPos + 1u{% endif %};var minKj = 0u;if (params.windowSize > 0u && maxKj > params.windowSize) { minKj = maxKj - params.windowSize; }var acc: array<f32, HEAD_DIM>;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { acc[d] = 0.0; }var m = NEG_INF;var l = 0.0;6 unmodified lines{% if hasBias %}let bb = select(b, 0u, params.biasBatch == 1u);let bh = select(h, 0u, params.biasHeads == 1u);score = score + f32(attn_bias[((bb * params.biasHeads + bh) * params.qSeq + s) * {{ biasStride }} + {{ biasCol }}]);{% endif %}let newM = max(m, score);let corr = exp(m - newM);let p = exp(score - newM);l = l * corr + p;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { acc[d] = acc[d] * corr + p * read_v(base, d{% if quantized %}, hk{% endif %}); }m = newM;}13 unmodified lineslet accScale = exp(m - finalM);// Same all-masked guard as the cooperative epilogue above.let denom = smoothTerm + l * accScale;let invDenom = select(0.0, accScale / denom, denom > 0.0);let oBase = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { output[oBase + d] = {{ IO }}(acc[d] * invDenom); }}{% endif %}12347 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342448 unmodified lines47347447547647747847948048148248348448548611 unmodified lines4984995005015025035045055065075085095105115125135145155165175185195205211 unmodified line52352452552652752852953053153211 unmodified lines5445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166171 unmodified line61962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864916 unmodified lines66666766866967067167267367467567667767867968068168268368468568668768868915 unmodified lines7057067077087097107117127137147157166 unmodified lines72372472572672772872973073173273373473573673773873974074174274374474574674713 unmodified lines761762763764765766767768769770771772773774775776{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% set usesF16 = usesF16 | default(false) %}{% set quantized = quantized | default(false) %}{% set bits = bits | default(0) %}7 unmodified lines// f16 inputs widen to f32 on load; computation and shared memory remain f32,// and results narrow only on store. The casts are identities for f32.{% set IO = "f16" if usesF16 else "f32" %}{% set NORMALIZED_VALUES = not usesF16 %}{% if NORMALIZED_VALUES %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}{% set boundNumerator = boundValueNumerator | default(false) %}{% if boundNumerator and (exact or tile) %}// Even a u32 key count times this magnitude leaves a bit of f32 exponent// headroom for a partial sum. Larger terms use the exponent-aware path.const VALUE_FAST_LIMIT: f32 = 0x1p94f;{% endif %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&{% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &{% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}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 }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("f32", rescale=true, recoverSum=boundValueNumerator) }}{% endif %}{% if cooperative %}// One workgroup owns each (batch, qHead, qToken) and walks the key range in// tiles of WG keys: each lane scores one key of the tile, then each lane folds// the tile's keys, in order, into the head dimensions it owns. This exposes// parallelism when the query count is small.{% else %}// One invocation owns each (batch, qHead, qToken) and walks the key range. The// larger query grid supplies parallelism without a workgroup-level merge.48 unmodified lines{% if cooperative %}// One allocation avoids the per-variable 16-byte padding between arrays.struct CooperativeState {q: array<f32, HEAD_DIM>,score: array<f32, WG>,p: array<f32, WG>,}var<workgroup> state: CooperativeState;// Head dimensions lane, lane + WG, ... belong to one lane.const DIM_SLOTS: u32 = {{ ceilDiv(headDim, gqaCooperativeWorkgroupSize) }}u;@compute @workgroup_size(WG)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {11 unmodified lines{% if useSeqlens %}// Buffer-sharing caches keep capacity in the BNSH dim2 stride; seqlens_k[b]+1// is the per-batch active end and rows beyond it are untouched storage.let activeEnd = min(totalSeq, max(params.qSeq, {{ attn_seqlens_count("b") }}));{% else %}let activeEnd = totalSeq;{% endif %}{% if not bidirectional or hasRotary %} let absPos = activeEnd - min(activeEnd, params.qSeq) + s;{% endif %}{% if needsOrigin %}// Absolute position of cache row 0 (windowed cache): the query end is the// unclamped total while the cache holds only its last `activeEnd` rows.let origin = max(params.qSeq, u32(max(seqlens_k[params.batch + b], 0)) + 1u) - activeEnd;{% endif %}{% if hasRotary %}if ({{ ropePos }} >= {{ gqaRotaryCacheRows }}u) {let outBase = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;for (var d = lane; d < HEAD_DIM; d += WG) { output[outBase + d] = {{ IO }}(0.0); }return;}{% endif %}// Cooperative query-vector prep (post norm/rotary) into shared memory.let qBase = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;for (var d = lane; d < HEAD_DIM; d = d + WG) { state.q[d] = f32(query[qBase + d]); }1 unmodified line{% if hasQNorm %}var part = 0.0;for (var d = lane; d < HEAD_DIM; d = d + WG) { part = part + state.q[d] * state.q[d]; }state.score[lane] = part;workgroupBarrier();var ms = 0.0;for (var L = 0u; L < WG; L = L + 1u) { ms = ms + state.score[L]; }let invRms = inverseSqrt(ms / f32(HEAD_DIM) + QK_EPS);for (var d = lane; d < HEAD_DIM; d = d + WG) { state.q[d] = state.q[d] * invRms * f32(q_norm_weight[d]); }workgroupBarrier();11 unmodified linesworkgroupBarrier();{% endif %}let scale = scale_value();let maxKj = {% if bidirectional %}activeEnd{% else %}min(activeEnd, absPos + 1u){% endif %};var minKj = 0u;if (params.windowSize > 0u && maxKj > params.windowSize) { minKj = maxKj - params.windowSize; }var acc: array<{% if NORMALIZED_VALUES %}ScaledValue{% else %}f32{% endif %}, DIM_SLOTS>;for (var i = 0u; i < DIM_SLOTS; i = i + 1u) { acc[i] = {% if NORMALIZED_VALUES %}scaled_value_zero(){% else %}0.0{% endif %}; }var m = NEG_INF;var l = 0.0;for (var tile = minKj; tile < maxKj; tile = tile + WG) {let count = min(WG, maxKj - tile);var score = NEG_INF;if (lane < count) {let j = tile + lane;let base = ((b * KV_HEADS + hk) * totalSeq + j) * PACKED;var dot = 0.0;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { dot = dot + state.q[d] * read_k(base, d{% if quantized %}, hk{% endif %}); }score = dot * scale;if (params.softcap > 0.0) { score = params.softcap * tanh(clamp(score / params.softcap, -30.0, 30.0)); }{% if hasBias %}let bb = select(b, 0u, params.biasBatch == 1u);let bh = select(h, 0u, params.biasHeads == 1u);{% if needsOrigin %}let biasKey = {{ biasCol }};// Absolute positions must be checked before adding them to the row base:// robust buffer bounds alone cannot prevent reading the next query row.if (biasKey < params.biasCols) {score = score + f32(attn_bias[((bb * params.biasHeads + bh) * params.qSeq + s) * params.biasCols + biasKey]);}{% else %}score = score + f32(attn_bias[((bb * params.biasHeads + bh) * params.qSeq + s) * {{ biasStride }} + {{ biasCol }}]);{% endif %}{% endif %}}// Every read of the previous scores precedes the previous tile's second// barrier, and every read of the previous probabilities precedes this one.state.score[lane] = score;workgroupBarrier();var tileMax = NEG_INF;for (var t = 0u; t < count; t = t + 1u) { tileMax = max(tileMax, state.score[t]); }let newM = max(m, tileMax);let corr = exp(m - newM);state.p[lane] = exp(score - newM);workgroupBarrier();// Every lane folds the same probabilities in the same order, so the// denominator agrees across the workgroup without a reduction.l = l * corr;for (var t = 0u; t < count; t = t + 1u) { l = l + state.p[t]; }for (var i = 0u; i < DIM_SLOTS; i = i + 1u) {let d = lane + i * WG;if (d < HEAD_DIM) {{% if NORMALIZED_VALUES %}var value = scaled_value_rescale(acc[i], corr);for (var t = 0u; t < count; t = t + 1u) {value = scaled_value_add(value, state.p[t], read_v(((b * KV_HEADS + hk) * totalSeq + tile + t) * PACKED, d{% if quantized %}, hk{% endif %}));}{% else %}var value = acc[i] * corr;for (var t = 0u; t < count; t = t + 1u) {value = value + state.p[t] * read_v(((b * KV_HEADS + hk) * totalSeq + tile + t) * PACKED, d);}{% endif %}acc[i] = value;}}m = newM;}var sink = 0.0;{% if hasHeadSink %}sink = f32(head_sink[h]);1 unmodified line{% else %}let useSmooth = params.smoothSoftmax != 0u;{% endif %}var finalM = m;var smoothTerm = 0.0;if (useSmooth) {finalM = max(m, sink);smoothTerm = exp(sink - finalM);}let accScale = exp(m - finalM);// A query whose every key is masked out leaves the denominator at zero (no// head sink to carry mass); emit a zero row instead of 0 * (1/0) = NaN.let denom = smoothTerm + l * accScale;{% if not NORMALIZED_VALUES %}let invDenom = select(0.0, accScale / denom, denom > 0.0);{% endif %}// A masked numerator may contain 0 * nonfinite V. Empty support is zero.let denomIsNaN = (bitcast<u32>(denom) & 0x7fffffffu) > 0x7f800000u;let sinkBits = bitcast<u32>(sink);let sinkAllowsZero = !useSmooth || (sinkBits & 0x7fffffffu) < 0x7f800000u || sinkBits == 0xff800000u;let zeroSupport = l == 0.0 && !denomIsNaN && sinkAllowsZero;let oBase = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;for (var i = 0u; i < DIM_SLOTS; i = i + 1u) {let d = lane + i * WG;if (d < HEAD_DIM) {output[oBase + d] = {{ IO }}(select(select({% if NORMALIZED_VALUES %}scaled_value_mean(scaled_value_rescale(acc[i], accScale), denom){% else %}acc[i] * invDenom{% endif %}, 0.0, zeroSupport), bitcast<f32>(sinkBits | 0x00400000u), !sinkAllowsZero));}}}{% else %}16 unmodified lines{% if useSeqlens %}// Buffer-sharing caches keep capacity in the BNSH dim2 stride; seqlens_k[b]+1// is the per-batch active end and rows beyond it are untouched storage.let activeEnd = min(totalSeq, max(params.qSeq, {{ attn_seqlens_count("b") }}));{% else %}let activeEnd = totalSeq;{% endif %}{% if not bidirectional or hasRotary %} let absPos = activeEnd - min(activeEnd, params.qSeq) + s;{% endif %}{% if needsOrigin %}// Absolute position of cache row 0 (windowed cache): the query end is the// unclamped total while the cache holds only its last `activeEnd` rows.let origin = max(params.qSeq, u32(max(seqlens_k[params.batch + b], 0)) + 1u) - activeEnd;{% endif %}{% if hasRotary %}if ({{ ropePos }} >= {{ gqaRotaryCacheRows }}u) {let outBase = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;for (var d = 0u; d < HEAD_DIM; d += 1u) { output[outBase + d] = {{ IO }}(0.0); }return;}{% endif %}// Private query-vector prep (post norm/rotary).var q: array<f32, HEAD_DIM>;let qBase = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;15 unmodified lines}{% endif %}let scale = scale_value();let maxKj = {% if bidirectional %}activeEnd{% else %}min(activeEnd, absPos + 1u){% endif %};var minKj = 0u;if (params.windowSize > 0u && maxKj > params.windowSize) { minKj = maxKj - params.windowSize; }var acc: array<{% if NORMALIZED_VALUES %}ScaledValue{% else %}f32{% endif %}, HEAD_DIM>;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { acc[d] = {% if NORMALIZED_VALUES %}scaled_value_zero(){% else %}0.0{% endif %}; }var m = NEG_INF;var l = 0.0;6 unmodified lines{% if hasBias %}let bb = select(b, 0u, params.biasBatch == 1u);let bh = select(h, 0u, params.biasHeads == 1u);{% if needsOrigin %}let biasKey = {{ biasCol }};if (biasKey < params.biasCols) {score = score + f32(attn_bias[((bb * params.biasHeads + bh) * params.qSeq + s) * params.biasCols + biasKey]);}{% else %}score = score + f32(attn_bias[((bb * params.biasHeads + bh) * params.qSeq + s) * {{ biasStride }} + {{ biasCol }}]);{% endif %}{% endif %}let newM = max(m, score);let corr = exp(m - newM);let p = exp(score - newM);{% if NORMALIZED_VALUES %}l = l * corr + p;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { acc[d] = scaled_value_add(scaled_value_rescale(acc[d], corr), p, read_v(base, d{% if quantized %}, hk{% endif %})); }{% else %}l = l * corr + p;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { acc[d] = acc[d] * corr + p * read_v(base, d); }{% endif %}m = newM;}13 unmodified lineslet accScale = exp(m - finalM);// Same all-masked guard as the cooperative epilogue above.let denom = smoothTerm + l * accScale;{% if not NORMALIZED_VALUES %}let invDenom = select(0.0, accScale / denom, denom > 0.0);{% endif %}// A masked numerator may contain 0 * nonfinite V. Empty support is zero.let denomIsNaN = (bitcast<u32>(denom) & 0x7fffffffu) > 0x7f800000u;let sinkBits = bitcast<u32>(sink);let sinkAllowsZero = !useSmooth || (sinkBits & 0x7fffffffu) < 0x7f800000u || sinkBits == 0xff800000u;let zeroSupport = l == 0.0 && !denomIsNaN && sinkAllowsZero;let oBase = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { output[oBase + d] = {{ IO }}(select(select({% if NORMALIZED_VALUES %}scaled_value_mean(scaled_value_rescale(acc[d], accScale), denom){% else %}acc[d] * invDenom{% endif %}, 0.0, zeroSupport), bitcast<f32>(sinkBits | 0x00400000u), !sinkAllowsZero)); }}{% endif %}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{{ env.wgsl.resourceDeclarations }}
// Per-head RMS normalization and NeoX half-split rotation of new rows for a buffer-sharing// cache, one workgroup per head row: the lanes share the head's sum of squares through// workgroup memory, then each rotates whole (d, d + HALF) pairs at the row's absolute position,// the end of its batch's live range `seqlens_k[b] + 1`. A position past the rotary tables uses// cos = sin = 0, so the row is written as zeros.{% if rowKind == "key" %}// Key rows: each (batch, kvHead, token) row is written, with its raw value row, into the// shared-capacity BNSH caches at the batch's append offset. Rows outside the append window are// copied from the past cache by a separate pass (or are the same buffer).{% else %}// Query rows: each (batch, token, head) row is written to the BSH scratch buffer that attention reads.{% endif %}const HEAD_DIM: u32 = {{ headDim }}u;const HALF: u32 = {{ half }}u;{% if rowKind == "key" %}const HEADS: u32 = {{ kvHeads }}u;{% else %}const HEADS: u32 = {{ qHeads }}u;{% endif %}const WG: u32 = {{ copyWorkgroupSize }}u;const QK_EPS: f32 = {{ qkEps }};
var<workgroup> partial: array<f32, WG>;
@compute @workgroup_size(WG)fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) { let row = wid.x + wid.y * {{ DISPATCH_FOLD_WIDTH }}u;{% if rowKind == "key" %} if (row >= params.count) { return; } let j = row % params.keySeq; let rest = row / params.keySeq; let h = rest % HEADS; let b = rest / HEADS; // Clamping below by keySeq maps a right-padded first prompt // (seqlens_k[b]+1 < keySeq) to append offset 0. let activeEnd = min(params.seq, max(params.keySeq, {{ attn_seqlens_count("b") }})); let t = activeEnd - params.keySeq + j; let src = (b * params.keySeq + j) * HEADS * HEAD_DIM + h * HEAD_DIM; let dst = ((b * HEADS + h) * params.seq + t) * HEAD_DIM;{% else %} if (row >= params.batch * params.qSeq * HEADS) { return; } let h = row % HEADS; let s = (row / HEADS) % params.qSeq; let b = row / (HEADS * params.qSeq); let t = min(params.totalSeq, max(params.qSeq, {{ attn_seqlens_count("b") }})) - params.qSeq + s; let src = (b * params.qSeq + s) * HEADS * HEAD_DIM + h * HEAD_DIM; let dst = src;{% endif %}
var ss = 0.0; for (var d = lid.x; d < HEAD_DIM; d = d + WG) { let x = f32({{ rowSource }}[src + d]); ss = ss + x * x; } partial[lid.x] = ss; workgroupBarrier(); for (var stride = WG / 2u; stride > 0u; stride = stride / 2u) { if (lid.x < stride) { partial[lid.x] = partial[lid.x] + partial[lid.x + stride]; } workgroupBarrier(); } let invRms = inverseSqrt(partial[0] / f32(HEAD_DIM) + QK_EPS);
for (var d = lid.x; d < HALF; d = d + WG) { var cs = 0.0; var sn = 0.0; if (t < {{ gqaRotaryCacheRows }}u) { cs = f32(cos_cache[t * HALF + d]); sn = f32(sin_cache[t * HALF + d]); } let x0 = f32({{ rowSource }}[src + d]) * invRms * f32({{ rowNormWeight }}[d]); let x1 = f32({{ rowSource }}[src + d + HALF]) * invRms * f32({{ rowNormWeight }}[d + HALF]); {{ rowDestination }}[dst + d] = x0 * cs - x1 * sn; {{ rowDestination }}[dst + d + HALF] = x1 * cs + x0 * sn; }{% if rowKind == "key" %} for (var d = lid.x; d < HEAD_DIM; d = d + WG) { present_value[dst + d] = new_v[src + d]; }{% endif %}}1235 unmodified lines91011121314151617181920212245 unmodified lines686970717273747511 unmodified lines878889909192939495965 unmodified lines10210310410510610710829 unmodified lines1381391401411421431441 unmodified line1461471481491501511521536 unmodified lines1601611621631641651661671681691701711721732 unmodified lines17617717817918018118218372 unmodified lines2562572582592602612626 unmodified lines2692702712722732742751 unmodified line27727827928028128228316 unmodified lines3003013023033043053063073083093103113123134 unmodified lines31831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941010 unmodified lines4214224234244254264274288 unmodified lines437438439440441442443{% if modeSpec is defined %}{% set mode = modeSpec %}{% elif mode is not defined %}5 unmodified lines{% set bits = bits | default(0) %}{% set qmax = qmax | default(0) %}{% set qmin = qmin | default(0) %}{% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.{% if bound == "" %}let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% else %}let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};if ({{ name }} >= {{ bound }}) { return; }{% endif %}{% endmacro %}{{ env.wgsl.resourceDeclarations }}{% if mode == "transpose" %}45 unmodified lines{% else %}{% set shareAppend = mode == "merge_share" and shareRegion == "append" %}{% set shiftRegion = shiftRegion | default("all") %}{% set shiftRetainOnly = mode == "window_shift" and shiftRegion == "shift" %}{% set cooperativeCopy = device.adapterInfo.vendor != "apple" %}{% set cooperativeMerge = cooperativeCopy or shareAppend %}{% set cooperativeMode = cooperativeMerge and (mode == "copy" or mode == "merge" or mode == "merge_share") %}11 unmodified lines// The append and retain passes own disjoint ranges, so their order is immaterial.{% elif mode == "build" %}// Build a BNSH cache from new BSH K/V, optionally applying K RMSNorm and rotary.{% elif mode == "window_shift" %}// Windowed cache: compact the surviving past rows down by the eviction count and// append the new BSH K/V, keeping the most recent min(T, capacity) tokens// contiguous at rows [0, L). Reads past, writes present (distinct buffers).{% elif mode == "append_quant" %}// Quantize new BSH K/V into an existing buffer-sharing INT8 BNSH cache. The// active sequence end comes from seqlens_k; the physical cache stride remains5 unmodified lines{% if mode != "copy" %}const KV_HEADS: u32 = {{ kvHeads }}u;{% endif %}const WG: u32 = {{ tunables.COPY_WORKGROUP_SIZE }}u;{% if mode != "copy" and (mode != "merge_share" or shareAppend) and not shiftRetainOnly %}const KV_HIDDEN: u32 = {{ kvHeads }}u * {{ headDim }}u;{% endif %}{% if mode == "build_quant" or mode == "append_quant" %}const PACKED: u32 = {{ packed }}u;{% endif %}29 unmodified lineslet b = etmp / KV_HEADS;// Clamping below by keySeq maps a right-padded first prompt// (seqlens_k[b]+1 < keySeq) to append offset 0.let activeEnd = min(params.seq, max(params.keySeq, u32(seqlens_k[b]) + 1u));let t = activeEnd - params.keySeq + j;let dst = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM + d;let nSrc = (b * params.keySeq + j) * KV_HIDDEN + hk * HEAD_DIM;1 unmodified line// Element-wise NeoX rotation: the pair (dr, dr+HALF) shares one// cos/sin entry, and row t is its own absolute position.let dr = select(d - HALF, d, d < HALF);let cs = cos_cache[t * HALF + dr];let sn = sin_cache[t * HALF + dr];let x0 = new_k[nSrc + dr];let x1 = new_k[nSrc + dr + HALF];present_key[dst] = select(x1 * cs + x0 * sn, x0 * cs - x1 * sn, d < HALF);6 unmodified lines{% endmacro %}{% macro append_per_row_walk() %}// Per-row append walk: one thread streams its row's contiguous bytes.{{ flat_index_2d("WG", guardInline=true) }}let j = i % params.keySeq;let tmp = i / params.keySeq;let hk = tmp % KV_HEADS;let b = tmp / KV_HEADS;// Clamping below by keySeq maps a right-padded first prompt// (seqlens_k[b]+1 < keySeq) to append offset 0.let activeEnd = min(params.seq, max(params.keySeq, u32(seqlens_k[b]) + 1u));let t = activeEnd - params.keySeq + j;let dstBase = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM;let nSrc = (b * params.keySeq + j) * KV_HIDDEN + hk * HEAD_DIM;2 unmodified linesfor (var d = 0u; d < HEAD_DIM; d = d + 1u) { k[d] = f32(new_k[nSrc + d]); }// Row t is its own absolute position in the shared cache.for (var d = 0u; d < HALF; d = d + 1u) {let cs = cos_cache[t * HALF + d];let sn = sin_cache[t * HALF + d];let x0 = k[d];let x1 = k[d + HALF];k[d] = x0 * cs - x1 * sn;72 unmodified lineslet b = et / (params.seq * KV_HEADS);// Clamping below by keySeq maps a right-padded first prompt// (seqlens_k[b]+1 < keySeq) to append offset 0.let activeEnd = min(params.seq, max(params.keySeq, u32(seqlens_k[b]) + 1u));let appendStart = activeEnd - params.keySeq;// Everything outside the append window. The append pass owns the window itself,// and the shared full-capacity stride makes this an identity copy (dst == src).6 unmodified lines{% endif %}{% elif mode == "copy" %}// Thread i streams one contiguous (batch, kvHead, token) row.{{ flat_index_2d("WG", guardInline=true) }}let base = i * HEAD_DIM;for (var d = 0u; d < HEAD_DIM; d = d + 1u) {present_key[base + d] = src_k[base + d];1 unmodified line}{% elif mode == "merge" %}// Per-row merge walk.{{ flat_index_2d("WG", guardInline=true) }}let t = i % params.seq;let tmp = i / params.seq;let hk = tmp % KV_HEADS;16 unmodified lines{% elif mode == "merge_share" %}// Past and present share the full-capacity stride, so outside-window rows// copy at the same index.{{ flat_index_2d("WG", guardInline=true) }}let t = i % params.seq;let tmp = i / params.seq;let hk = tmp % KV_HEADS;let b = tmp / KV_HEADS;// Clamping below by keySeq maps a right-padded first prompt// (seqlens_k[b]+1 < keySeq) to append offset 0.let activeEnd = min(params.seq, max(params.keySeq, u32(seqlens_k[b]) + 1u));let appendStart = activeEnd - params.keySeq;let dstBase = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM;// Everything outside the append window. The append pass owns the window itself,4 unmodified linespresent_value[dstBase + d] = past_v[dstBase + d];}}{% elif mode == "window_shift" %}// Keep the most recent min(total, capacity) tokens in contiguous cache rows.// Read past and write a distinct present buffer so compaction cannot race.// Rotary append uses the absolute token position; retained keys are already rotated.{% if shiftRegion == "append" %}// Append-only pass: the thread range spans just the appended window (batch x// kvHead x keySeq rows), while `params.seq` stays the cache capacity. The shift// pass owns every other row and the two ranges are disjoint, so their order is// immaterial.{{ flat_index_2d("WG", guardInline=true) }}let j = i % params.keySeq;let tmp = i / params.keySeq;let hk = tmp % KV_HEADS;let b = tmp / KV_HEADS;let absTotal = max(params.keySeq, u32(seqlens_k[b]) + 1u);let residentBefore = min(absTotal - params.keySeq, params.seq);// `max(0u, a + b - c)` does not clamp in u32: the subtraction wraps first, so a// step that evicts nothing reads back ~2^32 instead of 0. Compare before// subtracting.let filled = residentBefore + params.keySeq;let evicted = select(0u, filled - params.seq, filled > params.seq);let appendStart = residentBefore - evicted;let t = appendStart + j;let dstBase = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM;let nSrc = (b * params.keySeq + j) * KV_HIDDEN + hk * HEAD_DIM;// Row appendStart + j carries absolute position absTotal - keySeq + j: the cache// holds only the last L positions, so the row index is short of the absolute one// by the window origin. The reference rotates the same rows at// `appendStart + cacheOrigin`, which is the same number.let pos = absTotal - params.keySeq + j;var k: array<f32, HEAD_DIM>;for (var d = 0u; d < HEAD_DIM; d = d + 1u) { k[d] = new_k[nSrc + d]; }for (var d = 0u; d < HALF; d = d + 1u) {let cs = cos_cache[pos * HALF + d];let sn = sin_cache[pos * HALF + d];let x0 = k[d];let x1 = k[d + HALF];k[d] = x0 * cs - x1 * sn;k[d + HALF] = x1 * cs + x0 * sn;}for (var d = 0u; d < HEAD_DIM; d = d + 1u) {present_key[dstBase + d] = k[d];present_value[dstBase + d] = new_v[nSrc + d];}{% else %}{{ flat_index_2d("WG", guardInline=true) }}let t = i % params.seq;let tmp = i / params.seq;let hk = tmp % KV_HEADS;let b = tmp / KV_HEADS;let absTotal = max(params.keySeq, u32(seqlens_k[b]) + 1u);let residentBefore = min(absTotal - params.keySeq, params.seq);// `max(0u, a + b - c)` does not clamp in u32: the subtraction wraps first, so a// step that evicts nothing reads back ~2^32 instead of 0. Compare before// subtracting.let filled = residentBefore + params.keySeq;let evicted = select(0u, filled - params.seq, filled > params.seq);let appendStart = residentBefore - evicted;let dstBase = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM;if (t < appendStart) {// Surviving past rows slide down by the eviction count.let srcBase = ((b * KV_HEADS + hk) * params.seq + (t + evicted)) * HEAD_DIM;for (var d = 0u; d < HEAD_DIM; d = d + 1u) {present_key[dstBase + d] = past_k[srcBase + d];present_value[dstBase + d] = past_v[srcBase + d];}{% if shiftRegion == "shift" %}} else if (t >= appendStart + params.keySeq) {{% else %}} else if (t < appendStart + params.keySeq) {let nSrc = (b * params.keySeq + (t - appendStart)) * KV_HIDDEN + hk * HEAD_DIM;for (var d = 0u; d < HEAD_DIM; d = d + 1u) {present_key[dstBase + d] = new_k[nSrc + d];present_value[dstBase + d] = new_v[nSrc + d];}} else {{% endif %}// Outside the resident window. Cleared rather than left stale so the present// buffer does not expose stale contents from its distinct allocation.for (var d = 0u; d < HEAD_DIM; d = d + 1u) {present_key[dstBase + d] = {{ zeroScalar }}(0.0);present_value[dstBase + d] = {{ zeroScalar }}(0.0);}}{% endif %}{% else %}{{ flat_index_2d("WG", guardInline=true) }}let t = i % params.seq;let tmp = i / params.seq;let hk = tmp % KV_HEADS;10 unmodified lines{% if hasRotary %}let pos = params.pastSeq + t;for (var d = 0u; d < HALF; d = d + 1u) {let cs = cos_cache[pos * HALF + d];let sn = sin_cache[pos * HALF + d];let x0 = k[d];let x1 = k[d + HALF];k[d] = x0 * cs - x1 * sn;8 unmodified lines}{% else %}{% if mode == "append_quant" %}let activeEnd = u32(seqlens_k[b]) + 1u;let appendStart = activeEnd - params.seq;let dstBase = ((b * KV_HEADS + hk) * params.totalSeq + appendStart + t) * PACKED;{% else %}12345 unmodified lines101112131415161718192021222324252645 unmodified lines72737475767711 unmodified lines8990919293945 unmodified lines10010110210310410510629 unmodified lines1361371381391401411421 unmodified line1441451461471481491501511521531541556 unmodified lines1621631641651661671681691701711721731741752 unmodified lines17817918018118218318418518618718818972 unmodified lines2622632642652662672686 unmodified lines2752762772782792802811 unmodified line28328428528628728828916 unmodified lines3063073083093103113123133143153163173183194 unmodified lines32432532632732832933033110 unmodified lines3423433443453463473483493503513523538 unmodified lines362363364365366367368369{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% if modeSpec is defined %}{% set mode = modeSpec %}{% elif mode is not defined %}5 unmodified lines{% set bits = bits | default(0) %}{% set qmax = qmax | default(0) %}{% set qmin = qmin | default(0) %}{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% if bound != "" %}if ({{ name }} >= {{ bound }}) {return;}{% endif %}{% endmacro %}{{ env.wgsl.resourceDeclarations }}{% if mode == "transpose" %}45 unmodified lines{% else %}{% set shareAppend = mode == "merge_share" and shareRegion == "append" %}{% set cooperativeCopy = device.adapterInfo.vendor != "apple" %}{% set cooperativeMerge = cooperativeCopy or shareAppend %}{% set cooperativeMode = cooperativeMerge and (mode == "copy" or mode == "merge" or mode == "merge_share") %}11 unmodified lines// The append and retain passes own disjoint ranges, so their order is immaterial.{% elif mode == "build" %}// Build a BNSH cache from new BSH K/V, optionally applying K RMSNorm and rotary.{% elif mode == "append_quant" %}// Quantize new BSH K/V into an existing buffer-sharing INT8 BNSH cache. The// active sequence end comes from seqlens_k; the physical cache stride remains5 unmodified lines{% if mode != "copy" %}const KV_HEADS: u32 = {{ kvHeads }}u;{% endif %}const WG: u32 = {{ tunables.COPY_WORKGROUP_SIZE }}u;{% if mode != "copy" and (mode != "merge_share" or shareAppend) %}const KV_HIDDEN: u32 = {{ kvHeads }}u * {{ headDim }}u;{% endif %}{% if mode == "build_quant" or mode == "append_quant" %}const PACKED: u32 = {{ packed }}u;{% endif %}29 unmodified lineslet b = etmp / KV_HEADS;// Clamping below by keySeq maps a right-padded first prompt// (seqlens_k[b]+1 < keySeq) to append offset 0.let activeEnd = min(params.seq, max(params.keySeq, {{ attn_seqlens_count("b") }}));let t = activeEnd - params.keySeq + j;let dst = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM + d;let nSrc = (b * params.keySeq + j) * KV_HIDDEN + hk * HEAD_DIM;1 unmodified line// Element-wise NeoX rotation: the pair (dr, dr+HALF) shares one// cos/sin entry, and row t is its own absolute position.let dr = select(d - HALF, d, d < HALF);var cs = 0.0;var sn = 0.0;if (t < {{ gqaRotaryCacheRows }}u) {cs = f32(cos_cache[t * HALF + dr]);sn = f32(sin_cache[t * HALF + dr]);}let x0 = new_k[nSrc + dr];let x1 = new_k[nSrc + dr + HALF];present_key[dst] = select(x1 * cs + x0 * sn, x0 * cs - x1 * sn, d < HALF);6 unmodified lines{% endmacro %}{% macro append_per_row_walk() %}// Per-row append walk: one thread streams its row's contiguous bytes.{{ flat_index_2d("WG") }}let j = i % params.keySeq;let tmp = i / params.keySeq;let hk = tmp % KV_HEADS;let b = tmp / KV_HEADS;// Clamping below by keySeq maps a right-padded first prompt// (seqlens_k[b]+1 < keySeq) to append offset 0.let activeEnd = min(params.seq, max(params.keySeq, {{ attn_seqlens_count("b") }}));let t = activeEnd - params.keySeq + j;let dstBase = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM;let nSrc = (b * params.keySeq + j) * KV_HIDDEN + hk * HEAD_DIM;2 unmodified linesfor (var d = 0u; d < HEAD_DIM; d = d + 1u) { k[d] = f32(new_k[nSrc + d]); }// Row t is its own absolute position in the shared cache.for (var d = 0u; d < HALF; d = d + 1u) {var cs = 0.0;var sn = 0.0;if (t < {{ gqaRotaryCacheRows }}u) {cs = f32(cos_cache[t * HALF + d]);sn = f32(sin_cache[t * HALF + d]);}let x0 = k[d];let x1 = k[d + HALF];k[d] = x0 * cs - x1 * sn;72 unmodified lineslet b = et / (params.seq * KV_HEADS);// Clamping below by keySeq maps a right-padded first prompt// (seqlens_k[b]+1 < keySeq) to append offset 0.let activeEnd = min(params.seq, max(params.keySeq, {{ attn_seqlens_count("b") }}));let appendStart = activeEnd - params.keySeq;// Everything outside the append window. The append pass owns the window itself,// and the shared full-capacity stride makes this an identity copy (dst == src).6 unmodified lines{% endif %}{% elif mode == "copy" %}// Thread i streams one contiguous (batch, kvHead, token) row.{{ flat_index_2d("WG") }}let base = i * HEAD_DIM;for (var d = 0u; d < HEAD_DIM; d = d + 1u) {present_key[base + d] = src_k[base + d];1 unmodified line}{% elif mode == "merge" %}// Per-row merge walk.{{ flat_index_2d("WG") }}let t = i % params.seq;let tmp = i / params.seq;let hk = tmp % KV_HEADS;16 unmodified lines{% elif mode == "merge_share" %}// Past and present share the full-capacity stride, so outside-window rows// copy at the same index.{{ flat_index_2d("WG") }}let t = i % params.seq;let tmp = i / params.seq;let hk = tmp % KV_HEADS;let b = tmp / KV_HEADS;// Clamping below by keySeq maps a right-padded first prompt// (seqlens_k[b]+1 < keySeq) to append offset 0.let activeEnd = min(params.seq, max(params.keySeq, {{ attn_seqlens_count("b") }}));let appendStart = activeEnd - params.keySeq;let dstBase = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM;// Everything outside the append window. The append pass owns the window itself,4 unmodified linespresent_value[dstBase + d] = past_v[dstBase + d];}}{% else %}{{ flat_index_2d("WG") }}let t = i % params.seq;let tmp = i / params.seq;let hk = tmp % KV_HEADS;10 unmodified lines{% if hasRotary %}let pos = params.pastSeq + t;for (var d = 0u; d < HALF; d = d + 1u) {var cs = 0.0;var sn = 0.0;if (pos < {{ gqaRotaryCacheRows }}u) {cs = f32(cos_cache[pos * HALF + d]);sn = f32(sin_cache[pos * HALF + d]);}let x0 = k[d];let x1 = k[d + HALF];k[d] = x0 * cs - x1 * sn;8 unmodified lines}{% else %}{% if mode == "append_quant" %}let activeEnd = min(params.totalSeq, {{ attn_seqlens_count("b") }});if (activeEnd < params.seq) { return; }let appendStart = activeEnd - params.seq;let dstBase = ((b * KV_HEADS + hk) * params.totalSeq + appendStart + t) * PACKED;{% else %}
123456782 unmodified lines111213141516171819202122231 unmodified line2526272829301 unmodified line323334353637385 unmodified lines44454647484950514 unmodified lines56575859{% macro flat_index_2d(workgroupSize, name="i", bound="params.count", guardInline=false) %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %}{{ env.wgsl.resourceDeclarations }}// One invocation per (batch, query head, query token) applies optional per-head2 unmodified lines// writes only Q in BSH layout. f16 queries are widened for normalization,// trigonometry, and rotation. The result narrows only when the following// attention pass consumes f16 operand tiles; other configurations store f32.const HEAD_DIM: u32 = {{ headDim }}u;const HEAD_DIM_V4: u32 = {{ headDim }}u / 4u;const Q_HEADS: u32 = {{ qHeads }}u;const Q_HIDDEN: u32 = {{ qHidden }}u;const Q_HIDDEN_V4: u32 = {{ qHidden }}u / 4u;const WG: u32 = {{ copyWorkgroupSize }}u;{% set HAS_QNORM = hasQNorm is not defined or hasQNorm %}const HALF: u32 = {{ half }}u;{% if HAS_QNORM %}const QK_EPS: f32 = {{ qkEps }};1 unmodified line@compute @workgroup_size(WG)fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{{ flat_index_2d("WG", "qi", "") }}let total = params.batch * Q_HEADS * params.qSeq;if (qi >= total) { return; }1 unmodified linelet tmp = qi / params.qSeq;let h = tmp % Q_HEADS;let b = tmp / Q_HEADS;let absPos = params.totalSeq - params.qSeq + s;let base = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;var q: array<f32, HEAD_DIM>;5 unmodified linesfor (var d = 0u; d < HEAD_DIM; d = d + 1u) { q[d] = q[d] * invRms * f32(q_norm_weight[d]); }{% endif %}for (var d = 0u; d < HALF; d = d + 1u) {let cs = f32(cos_cache[absPos * HALF + d]);let sn = f32(sin_cache[absPos * HALF + d]);let x0 = q[d];let x1 = q[d + HALF];q[d] = x0 * cs - x1 * sn;4 unmodified linesfor (var c = 0u; c < HEAD_DIM_V4; c = c + 1u) {qout[base4 + c] = {{ "vec4<f16>(" if (qPrepF16 is defined and qPrepF16) else "" }}vec4<f32>(q[c * 4u], q[c * 4u + 1u], q[c * 4u + 2u], q[c * 4u + 3u]){{ ")" if (qPrepF16 is defined and qPrepF16) else "" }};}}1234567892 unmodified lines121314151617181920212223242526272829301 unmodified line323334353637383940414243444546474849505152535455565758591 unmodified line616263646566675 unmodified lines7374757677787980818283844 unmodified lines8990919293{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}// 2D-folded flat index: gid.y carries the high bits past the dispatch's// per-axis workgroup fold width.let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% endmacro %}{{ env.wgsl.resourceDeclarations }}// One invocation per (batch, query head, query token) applies optional per-head2 unmodified lines// writes only Q in BSH layout. f16 queries are widened for normalization,// trigonometry, and rotation. The result narrows only when the following// attention pass consumes f16 operand tiles; other configurations store f32.{% set HAS_QNORM = hasQNorm is not defined or hasQNorm %}{% set PAIRS = qPrepPairs is defined and qPrepPairs and not HAS_QNORM %}{% set OUT = "vec4<f16>" if (qPrepF16 is defined and qPrepF16) else "vec4<f32>" %}const HEAD_DIM: u32 = {{ headDim }}u;{% if not PAIRS %}const HEAD_DIM_V4: u32 = {{ headDim }}u / 4u;{% endif %}const Q_HEADS: u32 = {{ qHeads }}u;const Q_HIDDEN: u32 = {{ qHidden }}u;{% if not PAIRS %}const Q_HIDDEN_V4: u32 = {{ qHidden }}u / 4u;{% endif %}const WG: u32 = {{ copyWorkgroupSize }}u;const HALF: u32 = {{ half }}u;{% if HAS_QNORM %}const QK_EPS: f32 = {{ qkEps }};1 unmodified line@compute @workgroup_size(WG)fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{% if PAIRS %}{{ flat_index_2d("WG", "i", "") }}let quads = HALF / 4u;if (i >= params.batch * params.qSeq * Q_HEADS * quads) { return; }let p = (i % quads) * 4u;let rest = i / quads;let h = rest % Q_HEADS;let row = rest / Q_HEADS;let absPos = params.totalSeq - min(params.totalSeq, params.qSeq) + row % params.qSeq;let base = row * Q_HIDDEN + h * HEAD_DIM + p;let x0 = vec4<f32>(f32(query[base]), f32(query[base + 1u]), f32(query[base + 2u]), f32(query[base + 3u]));let x1 = vec4<f32>(f32(query[base + HALF]), f32(query[base + HALF + 1u]), f32(query[base + HALF + 2u]), f32(query[base + HALF + 3u]));var cs = vec4<f32>(0.0);var sn = vec4<f32>(0.0);if (absPos < {{ gqaRotaryCacheRows }}u) {let r = absPos * HALF + p;cs = vec4<f32>(f32(cos_cache[r]), f32(cos_cache[r + 1u]), f32(cos_cache[r + 2u]), f32(cos_cache[r + 3u]));sn = vec4<f32>(f32(sin_cache[r]), f32(sin_cache[r + 1u]), f32(sin_cache[r + 2u]), f32(sin_cache[r + 3u]));}qout[base / 4u] = {{ OUT }}(x0 * cs - x1 * sn);qout[(base + HALF) / 4u] = {{ OUT }}(x1 * cs + x0 * sn);{% else %}{{ flat_index_2d("WG", "qi", "") }}let total = params.batch * Q_HEADS * params.qSeq;if (qi >= total) { return; }1 unmodified linelet tmp = qi / params.qSeq;let h = tmp % Q_HEADS;let b = tmp / Q_HEADS;let absPos = params.totalSeq - min(params.totalSeq, params.qSeq) + s;let base = (b * params.qSeq + s) * Q_HIDDEN + h * HEAD_DIM;var q: array<f32, HEAD_DIM>;5 unmodified linesfor (var d = 0u; d < HEAD_DIM; d = d + 1u) { q[d] = q[d] * invRms * f32(q_norm_weight[d]); }{% endif %}for (var d = 0u; d < HALF; d = d + 1u) {var cs = 0.0;var sn = 0.0;if (absPos < {{ gqaRotaryCacheRows }}u) {cs = f32(cos_cache[absPos * HALF + d]);sn = f32(sin_cache[absPos * HALF + d]);}let x0 = q[d];let x1 = q[d + HALF];q[d] = x0 * cs - x1 * sn;4 unmodified linesfor (var c = 0u; c < HEAD_DIM_V4; c = c + 1u) {qout[base4 + c] = {{ "vec4<f16>(" if (qPrepF16 is defined and qPrepF16) else "" }}vec4<f32>(q[c * 4u], q[c * 4u + 1u], q[c * 4u + 2u], q[c * 4u + 3u]){{ ")" if (qPrepF16 is defined and qPrepF16) else "" }};}{% endif %}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182enable subgroups;{% if pinSubgroupSize32 %}enable subgroup_size_control;{% endif %}enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {{ attn_seqlens_count(index) }}){% endmacro %}{{ env.wgsl.resourceDeclarations }}const HEAD_DIM = {{ headDim }}u;const Q_HEADS = {{ qNumHeads }}u;const KV_HEADS = {{ kvNumHeads }}u;{% set ATTN_SCALE_DIM = "HEAD_DIM" %}fn scale_value() -> f32 { if (params.scale != 0.0) { return params.scale; } return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));}// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}
const DOT_ROUNDOFF = 2.01 * (f32(HEAD_DIM) + 4.0) * 0x1p-24;var<workgroup> kFullTile: array<f32, 512>;var<workgroup> qHi: array<f32, 512>;var<workgroup> qLow: array<f32, 512>;var<workgroup> kHi: array<f32, 512>;var<workgroup> kLow: array<f32, 512>;var<workgroup> sums: array<f32, 768>;
@compute @workgroup_size(128){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) grid: vec3u, @builtin(local_invocation_index) li: u32, @builtin(subgroup_size) width: u32, @builtin(subgroup_invocation_id) lane: u32) { let h = wg.z % Q_HEADS; let b = wg.z / Q_HEADS; let kvHead = h / (Q_HEADS / KV_HEADS); let live = {{ attn_seqlens_bound("params.kvSeq", "b") }}; let q0 = wg.y * 32u; let k0 = wg.x * 32u;
let headBase = b * (Q_HEADS * grid.y + KV_HEADS * grid.x); let keyBase = headBase + Q_HEADS * grid.y + kvHead * grid.x; let qRange = ranges[headBase + h * grid.y + wg.y]; let kRange = ranges[keyBase + wg.x]; let tileIndex = (wg.z * grid.y + wg.y) * grid.x + wg.x; if (k0 >= live) { if (li == 0u) { repair[tileIndex] = 0u; } return; } // Ranges contain the grid step, row L2 bound, live |V| maximum and signed L1 bound. let exactGrid = (qRange.w <= 0.0 && kRange.w <= 0.0) || qRange.y == 0.0 || kRange.y == 0.0; if (li == 0u && (qRange.x < 0.0 || kRange.x < 0.0)) { atomicStore(&matrixRejected, 1u); } // A score changes the normalization of every live value in this head. // Require an exact dot or replay when any value can amplify weight rounding. if (!exactGrid) { for (var tile = li; tile < (live + 31u) / 32u; tile += 128u) { if (ranges[keyBase + tile].z > 1.0) { atomicStore(&matrixRejected, 1u); } } } let role = claimMatrixSubgroupRole(width, 32u); if (!matrixTopologyAccepted(li, 4u)) { if (li == 0u) { repair[tileIndex] = 1u; } return; } let scoreBase = wg.z * params.qSeq * params.kvSeq; let scale = scale_value(); // Cauchy-Schwarz bounds sum(abs(q*k)). Allow one product and one addition // rounding per component, plus scaling and the final score rounding. let plainError = DOT_ROUNDOFF * qRange.y * kRange.y * abs(scale); let plain = exactGrid || plainError <= 0x1p-25; let qFragment = role / 2u * 16u; let kFragment = role % 2u * 16u;{% for r in range(2) %}{% for c in range(2) %}{% for a in ['hi','left','right'] %} var {{a}}{{r}}{{c}}: subgroup_matrix_result<f32, 8, 8>;{% endfor %}{% endfor %}{% endfor %} for (var depth = 0u; depth < HEAD_DIM; depth += 16u) { for (var off = li; off < 512u; off += 128u) { let row = off / 16u; let d = depth + off % 16u;{% for t,x,idx in [['q', 'qRange', '((b * params.qSeq + q0 + row) * Q_HEADS + h)'],['k', 'kRange', '((b * params.kvSeq + k0 + row) * KV_HEADS + kvHead)']] %} var {{t}} = 0.0; if ({{'q0 + row < params.qSeq' if t=='q' else 'k0 + row < live'}}) { {{t}} = {{'query' if t=='q' else 'key'}}[{{idx}} * HEAD_DIM + d]; } let {{t}}High = select(round({{t}} / {{x}}.x) * {{x}}.x, {{t}}, plain); {{t}}Hi[off] = {{t}}High; if (!plain) { {{t}}Low[off] = fma(-1.0, {{t}}High, {{t}}); }{% if t == 'k' %} kFullTile[off] = k;{% endif %}{% endfor %} } workgroupBarrier(); for (var d = 0u; d < 16u; d += 8u) {{% for r in range(2) %} let qHi{{r}} = subgroupMatrixLoad<subgroup_matrix_left<f32, 8, 8>, row_major>(&qHi, (qFragment + {{ r * 8 }}u) * 16u + d, 16u); let kHi{{r}} = subgroupMatrixLoad<subgroup_matrix_right<f32, 8, 8>, col_major>(&kHi, (kFragment + {{ r * 8 }}u) * 16u + d, 16u);{% endfor %}{% for r in range(2) %}{% for c in range(2) %} hi{{r}}{{c}} = subgroupMatrixMultiplyAccumulate(qHi{{r}}, kHi{{c}}, hi{{r}}{{c}});{% endfor %}{% endfor %} if (!plain) {{% for r in range(2) %} let qLow{{r}} = subgroupMatrixLoad<subgroup_matrix_left<f32, 8, 8>, row_major>(&qLow, (qFragment + {{ r * 8 }}u) * 16u + d, 16u); let kLow{{r}} = subgroupMatrixLoad<subgroup_matrix_right<f32, 8, 8>, col_major>(&kLow, (kFragment + {{ r * 8 }}u) * 16u + d, 16u); let kFull{{r}} = subgroupMatrixLoad<subgroup_matrix_right<f32, 8, 8>, col_major>(&kFullTile, (kFragment + {{ r * 8 }}u) * 16u + d, 16u);{% endfor %}{% for r in range(2) %}{% for c in range(2) %} left{{r}}{{c}} = subgroupMatrixMultiplyAccumulate(qHi{{r}}, kLow{{c}}, left{{r}}{{c}}); right{{r}}{{c}} = subgroupMatrixMultiplyAccumulate(qLow{{r}}, kFull{{c}}, right{{r}}{{c}});{% endfor %}{% endfor %} } } workgroupBarrier(); } // The leading product is exact. Only the two residual matrix products can // accumulate error. Each low component is at most half its row grid step. let qLowBound = select(0.5 * qRange.x, 0.0, qRange.w <= 0.0); let kLowBound = select(0.5 * kRange.x, 0.0, kRange.w <= 0.0); let sumAbs = kLowBound * (abs(qRange.w) + f32(HEAD_DIM) * qLowBound) + qLowBound * abs(kRange.w); // Two roundings per component also cover non-fused or truncating matrix MACs. // Four additional roundings enclose the sum and both interval endpoints. let radius = sumAbs * DOT_ROUNDOFF;{% for r in range(2) %}{% for c in range(2) %} {{% for a in ['hi','left','right'] %} subgroupMatrixStore<row_major>(&sums, role * 192u + {{ loop.index0 * 64 }}u, {{a}}{{r}}{{c}}, 8u);{% endfor %} workgroupBarrier(); for (var cell = lane; cell < 64u; cell += 32u) { let q = q0 + qFragment + {{ r * 8 }}u + cell / 8u; let k = k0 + kFragment + {{ c * 8 }}u + cell % 8u; let idx = role * 192u + cell; if (q < params.qSeq && k < live) { let leading = sums[idx]; var result = leading * scale; if (!plain) { // q*k = qHi*kHi + qHi*kLow + qLow*k. Round both endpoints in // the same order as the score, including negative attention scales. let correction = sums[idx + 64u] + sums[idx + 128u]; let lo = fma(1.0, leading, correction - radius) * scale; let hi = fma(1.0, leading, correction + radius) * scale; result = fma(1.0, leading, correction) * scale; // For |V| <= 1, softmax's Jacobian bounds absolute output sensitivity // by the largest absolute logit perturbation, including near cancellation. if (!(lo == hi || max(abs(result - lo), abs(hi - result)) <= 0x1p-24)) { atomicStore(&matrixRejected, 1u); } } scores[scoreBase + q * params.kvSeq + k] = result; } } workgroupBarrier(); }{% endfor %}{% endfor %} if (li == 0u) { repair[tileIndex] = atomicLoad(&matrixRejected); }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {{ attn_seqlens_count(index) }}){% endmacro %}{{ env.wgsl.resourceDeclarations }}const HEAD_DIM = {{ headDim }}u;const Q_HEADS = {{ qNumHeads }}u;const KV_HEADS = {{ kvNumHeads }}u;const INVALID_GRID = 0xffffffffu;var<workgroup> normParts: array<vec2f, 128>;var<workgroup> normSquaredMax: atomic<u32>;var<workgroup> valueMax: atomic<u32>;var<workgroup> normOneMax: atomic<u32>;var<workgroup> finestGrid: atomic<u32>;
@compute @workgroup_size(128)fn main(@builtin(workgroup_id) wg: vec3u, @builtin(local_invocation_index) lane: u32) { let b = wg.z / Q_HEADS; let head = wg.z % Q_HEADS; let isQuery = wg.y == 0u; if (!isQuery && head >= KV_HEADS) { return; } let seq = select(params.kvSeq, params.qSeq, isQuery); let live = select({{ attn_seqlens_bound("params.kvSeq", "b") }}, params.qSeq, isQuery); let first = wg.x * 32u; if (first >= seq) { return; } let row = first + lane / 4u; let heads = select(KV_HEADS, Q_HEADS, isQuery); let base = ((b * seq + row) * heads + head) * HEAD_DIM; var norm = vec2f(0.0); var valueBits = 0u; var gridBits = 0u; if (row < live) { for (var d = lane % 4u; d < HEAD_DIM; d += 4u) { var x: f32; if (isQuery) { x = query[base + d]; } else { x = key[base + d]; valueBits = max(valueBits, bitcast<u32>(value[base + d]) & 0x7fffffffu); } let bits = bitcast<u32>(x) & 0x7fffffffu; if (bits == 0u) { continue; } // Magnitudes outside [2^-32, 2^32) can underflow or overflow the split. if (bits < 0x2f800000u || bits >= 0x4f800000u) { gridBits = INVALID_GRID; continue; } // The last set significand bit gives the finest grid this entry needs. let significand = (bits & 0x7fffffu) | 0x800000u; gridBits = max(gridBits, 278u - (bits >> 23u) - countTrailingZeros(significand)); norm += vec2f(x * x, abs(x)); } } normParts[lane] = norm; atomicMax(&valueMax, valueBits); atomicMax(&finestGrid, gridBits); workgroupBarrier(); if (lane % 4u == 0u) { let rowSums = (norm + normParts[lane + 1u]) + (normParts[lane + 2u] + normParts[lane + 3u]); atomicMax(&normSquaredMax, bitcast<u32>(rowSums.x)); atomicMax(&normOneMax, bitcast<u32>(rowSums.y)); } workgroupBarrier(); if (lane == 0u) { let qChunks = (params.qSeq + 31u) / 32u; let kChunks = (params.kvSeq + 31u) / 32u; let headBase = select(Q_HEADS * qChunks + head * kChunks, head * qChunks, isQuery); let index = b * (Q_HEADS * qChunks + KV_HEADS * kChunks) + headBase + wg.x; let maxValue = bitcast<f32>(min(atomicLoad(&valueMax), 0x7f7fffffu)); let grid = atomicLoad(&finestGrid); if (grid == INVALID_GRID) { ranges[index] = vec4f(-1.0, 0.0, maxValue, 0.0); return; } // Inflate the reductions before rounding the grid spacing up to a power of two. // Rounding at most 256 components adds at most 8 to the integer L2 norm, // so every leading dot and partial sum fits in the 24-bit significand. let norm2 = sqrt(bitcast<f32>(atomicLoad(&normSquaredMax))) * 1.0001; let stepBits = (bitcast<u32>(max(norm2 / 4080.0, 0x1p-48)) + 0x7fffffu) & 0x7f800000u; let norm1 = bitcast<f32>(atomicLoad(&normOneMax)) * 1.0001; let onGrid = grid <= 255u - (stepBits >> 23u); // The sign of the L1 bound records whether the row block has a zero residual. ranges[index] = vec4f(bitcast<f32>(stepBits), norm2, maxValue, select(norm1, -norm1, onGrid)); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206{% set R = streamRows %}{% set K = streamKeys %}{% set W = 8 %}{% set VC = streamValueKeys %}{% set D = attnHeadDim %}{% set WG = 256 %}{% set DV = D // 4 %}{% macro scalar_dot() -%}var dot = 0.0; for (var d = 0u; d < {{ D }}u; d++) { dot = fma(f32(query[qStart + r * QS + d]), f32(key[kvStart + k * KS + d]), dot); }{%- endmacro %}{% macro nonfinite_mask(v) -%}(bitcast<vec4<u32>>({{ v }}) & vec4<u32>(0x7f800000u)) == vec4<u32>(0x7f800000u){%- endmacro %}enable subgroups;{% if pinSubgroupSize32 %}enable subgroup_size_control;{% endif %}enable chromium_experimental_subgroup_matrix;diagnostic(off, chromium.subgroup_matrix_uniformity);{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {{ attn_seqlens_count(index) }}){% endmacro %}{{ env.wgsl.resourceDeclarations }}// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 { // WGSL initializes workgroup variables to zero before this entry point. let population = subgroupBallot(true); let populationCount = countOneBits(population.x) + countOneBits(population.y) + countOneBits(population.z) + countOneBits(population.w); var claimed = 0u; if (subgroupElect()) { claimed = atomicAdd(&matrixRoleCount, 1u); if (width != requiredWidth || populationCount != requiredWidth) { atomicStore(&matrixRejected, 1u); } } // Reconverge every invocation before broadcasting the elected claim. workgroupBarrier(); return subgroupBroadcastFirst(claimed);}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool { if (localIndex == 0u) { matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u && atomicLoad(&matrixRoleCount) == bankCount); } // The uniform load both publishes the leader's decision and gives the // compiler a workgroup-uniform condition for the barrier-containing arms. return workgroupUniformLoad(&matrixAccepted) != 0u;}const QS = {{ D * attnQHeads }}u;const KS = {{ D * attnKvHeads }}u;var<workgroup> scores: array<f32, {{ R * K }}>;var<workgroup> values: array<f32, {{ VC * D }}>;
var<workgroup> zeros: array<f32, 64>;var<workgroup> maxScore: array<f32, {{ R }}>;var<workgroup> denom: array<f32, {{ R }}>;var<workgroup> alpha: array<f32, {{ R }}>;var<workgroup> nonfinite: atomic<u32>;@compute @workgroup_size({{ WG }}){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) tid: u32, @builtin(subgroup_size) width: u32, @builtin(subgroup_invocation_id) lane: u32) { let role = claimMatrixSubgroupRole(width, 32u); let qStart = (wg.z * params.qSeq + wg.x * {{ R }}u) * QS + wg.y * {{ D }}u; let kvStart = wg.z * params.kvSeq * KS + (wg.y / {{ attnQHeads // attnKvHeads }}u) * {{ D }}u; let scale = select(params.scale, inverseSqrt(f32({{ D }}u)), params.scale == 0.0); let live = {{ attn_seqlens_bound("params.kvSeq", "wg.z") }}; if (matrixTopologyAccepted(tid, {{ W }}u)) { if (tid < {{ R }}u) { maxScore[tid] = -3.4028234663852886e38; } workgroupBarrier(); var sums: array<vec4<f32>, {{ (R * DV + WG - 1) // WG }}>; for (var kb = 0u; kb < params.kvSeq; kb += {{ K }}u) {{% set SR = 2 %}{% set SC = 4 %} for (var tile = role; tile < {{ (R // (SR * 8)) * (K // (SC * 8)) }}u; tile += {{ W }}u) { let q0 = tile / {{ K // (SC * 8) }}u * {{ SR * 8 }}u; let k0 = tile % {{ K // (SC * 8) }}u * {{ SC * 8 }}u;{% for i in range(SR) %}{% for j in range(SC) %} var dot{{i}}_{{j}} = subgroupMatrixLoad<subgroup_matrix_result<f32, 8, 8>, row_major>(&zeros, 0u, 8u);{% endfor %}{% endfor %} for (var d = 0u; d < {{ D }}u; d += 8u) {{% for i in range(SR) %} let qf{{i}} = subgroupMatrixLoad<subgroup_matrix_left<f16, 8, 8>, row_major>(&query, qStart + (q0 + {{ i * 8 }}u) * QS + d, QS);{% endfor %}{% for j in range(SC) %} let kf{{j}} = subgroupMatrixLoad<subgroup_matrix_right<f16, 8, 8>, col_major>(&key, kvStart + (kb + k0 + {{ j * 8 }}u) * KS + d, KS);{% endfor %}{% for i in range(SR) %}{% for j in range(SC) %} dot{{i}}_{{j}} = subgroupMatrixMultiplyAccumulate(qf{{i}}, kf{{j}}, dot{{i}}_{{j}});{% endfor %}{% endfor %} }{% for i in range(SR) %}{% for j in range(SC) %} subgroupMatrixStore<row_major>(&scores, (q0 + {{ i * 8 }}u) * {{ K }}u + k0 + {{ j * 8 }}u, dot{{i}}_{{j}}, {{ K }}u);{% endfor %}{% endfor %} } workgroupBarrier(); for (var r0 = 0u; r0 < {{ R }}u; r0 += {{ W }}u) { let r = r0 + role; var m = -3.4028234663852886e38; for (var k = lane; k < {{ K }}u; k += 32u) { if (kb + k < live) { m = max(m, scores[r * {{ K }}u + k] * scale); } } let old = maxScore[r]; let now = max(old, subgroupMax(m)); let a = exp(old - now); var s = 0.0; for (var k = lane; k < {{ K }}u; k += 32u) { let p = select(0.0, exp(scores[r * {{ K }}u + k] * scale - now), kb + k < live); scores[r * {{ K }}u + k] = p; s += p; } let total = subgroupAdd(s); if (lane == 0u) { maxScore[r] = now; alpha[r] = a; denom[r] = denom[r] * a + total; } } workgroupBarrier();{% set WX = W if D % (8 * W) == 0 else W // 2 %}{% set WY = W // WX %}{% set H = (R // 8) // WY %}{% set B = (D // 8) // WX %} let pvr = role / {{ WX }}u * {{ H * 8 }}u; let pvd = role % {{ WX }}u * {{ B * 8 }}u;{% for i in range(H) %}{% for j in range(B) %} var pv{{i}}_{{j}} = subgroupMatrixLoad<subgroup_matrix_result<f32, 8, 8>, row_major>(&zeros, 0u, 8u);{% endfor %}{% endfor %} for (var vc = 0u; vc < {{ K }}u; vc += {{ VC }}u) { for (var i = tid; i < {{ VC * DV }}u; i += {{ WG }}u) { let raw = vec4<f32>(value[(kvStart + (kb + vc + i / {{ DV }}u) * KS) / 4u + i % {{ DV }}u]); let exceptional = {{ nonfinite_mask("raw") }}; if (any(exceptional)) { atomicOr(&nonfinite, 1u); } let v = select(raw, vec4<f32>(0.0), exceptional); values[i * 4u] = v.x; values[i * 4u + 1u] = v.y; values[i * 4u + 2u] = v.z; values[i * 4u + 3u] = v.w; } workgroupBarrier();{% for kk in range(VC // 8) %} {{% for i in range(H) %} let p{{i}} = subgroupMatrixLoad<subgroup_matrix_left<f32, 8, 8>, row_major>(&scores, (pvr + {{ i * 8 }}u) * {{ K }}u + vc + {{ kk * 8 }}u, {{ K }}u);{% endfor %}{% for j in range(B) %} let v{{j}} = subgroupMatrixLoad<subgroup_matrix_right<f32, 8, 8>, row_major>(&values, {{ kk * 8 * D }}u + pvd + {{ j * 8 }}u, {{ D }}u);{% endfor %}{% for i in range(H) %}{% for j in range(B) %} pv{{i}}_{{j}} = subgroupMatrixMultiplyAccumulate(p{{i}}, v{{j}}, pv{{i}}_{{j}});{% endfor %}{% endfor %} }{% endfor %} workgroupBarrier(); }{% for slab in range(R // VC) %} {{% for i in range(H) %} let row{{i}} = pvr + {{ i * 8 }}u; if (row{{i}} >= {{ slab * VC }}u && row{{i}} < {{ (slab + 1) * VC }}u) {{% for j in range(B) %} subgroupMatrixStore<row_major>(&values, (row{{i}} - {{ slab * VC }}u) * {{ D }}u + pvd + {{ j * 8 }}u, pv{{i}}_{{j}}, {{ D }}u);{% endfor %} }{% endfor %} workgroupBarrier();{% set offset = (slab * VC * DV) % WG %} for (var i = {% if offset %}((tid + {{ WG - offset }}u) % {{ WG }}u){% else %}tid{% endif %} + {{ slab * VC * DV }}u; i < {{ (slab + 1) * VC * DV }}u; i += {{ WG }}u) { let row = i / {{ DV }}u; let v = vec4<f32>(values[(i - {{ slab * VC * DV }}u) * 4u], values[(i - {{ slab * VC * DV }}u) * 4u + 1u], values[(i - {{ slab * VC * DV }}u) * 4u + 2u], values[(i - {{ slab * VC * DV }}u) * 4u + 3u]); sums[i / {{ WG }}u] = sums[i / {{ WG }}u] * alpha[row] + v; } workgroupBarrier(); }{% endfor %} } for (var i = tid; i < {{ R * DV }}u; i += {{ WG }}u) { let r = i / {{ DV }}u; let l = denom[r]; let dc = i % {{ DV }}u; var mean = select(sums[i / {{ WG }}u] / l, vec4<f32>(0.0), l == 0.0); if (atomicLoad(&nonfinite) != 0u && l > 0.0) { for (var k = 0u; k < live; k++) { let v = vec4<f32>(value[(kvStart + k * KS) / 4u + dc]); let nf = {{ nonfinite_mask("v") }}; if (any(nf)) { {{ scalar_dot() }} let p = exp(dot * scale - maxScore[r]) / l; mean += select(vec4<f32>(0.0), v * p, nf); } } } output[(qStart + r * QS) / 4u + dc] = vec4<f16>(mean); } } else { for (var i = tid; i < {{ R * DV }}u; i += {{ WG }}u) { let r = i / {{ DV }}u; let dc = i % {{ DV }}u; var m = -3.4028234663852886e38; for (var k = 0u; k < live; k++) { {{ scalar_dot() }} m = max(m, dot * scale); } var sum = vec4<f32>(0.0); var l = 0.0; for (var k = 0u; k < live; k++) { {{ scalar_dot() }} let w = exp(dot * scale - m); sum += w * vec4<f32>(value[(kvStart + k * KS) / 4u + dc]); l += w; } output[(qStart + r * QS) / 4u + dc] = vec4<f16>(select(sum / l, vec4<f32>(0.0), l == 0.0)); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156{% set stageRegion = stageRegion | default("all") %}{% set hasRotary = hasRotary | default(false) %}{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %} // 2D-folded flat index: gid.y carries the high bits past the dispatch's // per-axis workgroup fold width. let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};{% if bound != "" %} if ({{ name }} >= {{ bound }}) { return; }{% endif %}{% endmacro %}{{ env.wgsl.resourceDeclarations }}const HEAD_DIM: u32 = {{ headDim }}u;const KV_HEADS: u32 = {{ kvHeads }}u;const WG: u32 = {{ copyWorkgroupSize }}u;{% if windowPhase == "stage" %}{% if stageRegion != "append" %}const BATCH: u32 = {{ windowBatchCount }}u;{% endif %}{% if stageRegion != "shift" %}const KV_HIDDEN: u32 = KV_HEADS * HEAD_DIM;{% if hasRotary %}const HALF: u32 = {{ half }}u;{% endif %}{% endif %}{% endif %}
// Equivalent to T-gap*ceil((T-C)/gap), without a product or rounded-up sum// that can overflow. T is allowed to reach INT32_MAX+1; C>=W>0 is host-checked.fn window_end(total: u32) -> u32 { if (total <= params.capacity) { return total; } let gap = params.capacity - params.windowSize + 1u; return params.windowSize + (total - params.capacity - 1u) % gap;}
struct WindowStep { total: u32, pastRows: u32, stageEnd: u32 }fn window_step(last: i32) -> WindowStep { var step = WindowStep(0u, 0u, 0u); // Validate the signed value before conversion and subtraction. An invalid // `seqlens_k` value clears this batch rather than reading another slice. if (last < 0) { return step; } let total = u32(last) + 1u; if (total < params.keySeq) { return step; } step.total = total; step.pastRows = window_end(total - params.keySeq); step.stageEnd = step.pastRows + params.keySeq; return step;}
{% set cooperativeWindow = windowCooperativeCopy and not (windowPhase == "stage" and stageRegion == "append") %}{% set copyWidth = 2 if inputScalar == "f16" else 1 %}{% macro channel_loop(bound, stores) %}{% if cooperativeWindow %} for (var dBase = lane * {{ copyWidth }}u; dBase < {{ bound }}; dBase += WG * {{ copyWidth }}u) {{% for dc in range(copyWidth) %} { let d = dBase + {{ dc }}u;{% for store in stores %} {{ store }}{% endfor %} }{% endfor %} }{% else %} for (var d = 0u; d < {{ bound }}; d += 1u) {{% for store in stores %} {{ store }}{% endfor %} }{% endif %}{% endmacro %}@compute @workgroup_size(WG)fn main(@builtin(global_invocation_id) gid: vec3<u32>) {{% if cooperativeWindow %}{{ flat_index_2d("WG", "linear", "") }} let lane = linear % WG; let rowBase = linear - lane; let rowEnd = min(params.count, rowBase + WG); for (var i = rowBase; i < rowEnd; i++) {{% else %}{{ flat_index_2d("WG") }}{% endif %}{% if windowPhase == "compact" %} let t = i % params.capacity; let slice = i / params.capacity; let hk = slice % KV_HEADS; let b = slice / KV_HEADS; let step = window_step(seqlens_k[params.batch + b]); if (step.total == 0u && hk == 0u) { // A rejected sample must be zero even if its query contained NaN/Inf. // Attention has finished; cache rows partition all its query rows safely, // including chunks longer than the cache capacity. for (var s = t; s < params.keySeq; s += params.capacity) { let outBase = (b * params.keySeq + s) * {{ windowQueryHeads }}u * HEAD_DIM; {{ channel_loop(windowQueryHeads|string + "u * HEAD_DIM", ["output[outBase + d] = " + inputScalar + "(0.0);"]) }} } } let end = window_end(step.total); let dst = ((b * KV_HEADS + hk) * params.capacity + t) * HEAD_DIM; if (t < end) { // All attention passes have finished. Writing the real cache now is safe // even when its allocation aliases past, and preserves early-query history. let src = ((b * KV_HEADS + hk) * params.seq + step.stageEnd - end + t) * HEAD_DIM; {{ channel_loop("HEAD_DIM", ["present_key[dst + d] = stage_k[src + d];", "present_value[dst + d] = stage_v[src + d];"]) }} } else { // Zero every cache slot outside the resident prefix [0, end). {{ channel_loop("HEAD_DIM", ["present_key[dst + d] = " + inputScalar + "(0.0);", "present_value[dst + d] = " + inputScalar + "(0.0);"]) }} }{% else %}{% if stageRegion == "append" %} let j = i % params.keySeq; let slice = i / params.keySeq;{% else %} let t = i % params.seq; let slice = i / params.seq;{% endif %} let hk = slice % KV_HEADS; let b = slice / KV_HEADS; let step = window_step(seqlens_k[b]);{% if stageRegion != "append" %} if (hk == 0u && t == 0u{% if cooperativeWindow %} && lane == 0u{% endif %}) { // Attention kernels consume resident lengths, while rotary/bias still need // absolute positions. Both fit in one metadata binding. stage_seqlens[b] = i32(step.stageEnd) - 1; stage_seqlens[BATCH + b] = select(-1, seqlens_k[b], step.total != 0u); }{% endif %}{% if stageRegion == "append" %} let t = step.pastRows + j; let dst = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM; if (step.total == 0u || step.total - params.keySeq + j >= {{ windowRotaryRows }}u) { {{ channel_loop("HEAD_DIM", ["present_key[dst + d] = " + inputScalar + "(0.0);", "present_value[dst + d] = " + inputScalar + "(0.0);"]) }} return; } let src = (b * params.keySeq + j) * KV_HIDDEN + hk * HEAD_DIM; let pos = step.total - params.keySeq + j; for (var d = 0u; d < HALF; d += 1u) { let cs = cos_cache[pos * HALF + d]; let sn = sin_cache[pos * HALF + d]; let x0 = new_k[src + d]; let x1 = new_k[src + d + HALF]; present_key[dst + d] = x0 * cs - x1 * sn; present_key[dst + d + HALF] = x1 * cs + x0 * sn; present_value[dst + d] = new_v[src + d]; present_value[dst + d + HALF] = new_v[src + d + HALF]; }{% else %} let dst = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM; if (t < step.pastRows) { let src = ((b * KV_HEADS + hk) * params.capacity + t) * HEAD_DIM; {{ channel_loop("HEAD_DIM", ["present_key[dst + d] = past_k[src + d];", "present_value[dst + d] = past_v[src + d];"]) }}{% if stageRegion != "shift" %} } else if (t < step.stageEnd) { let src = (b * params.keySeq + t - step.pastRows) * KV_HIDDEN + hk * HEAD_DIM; {{ channel_loop("HEAD_DIM", ["present_key[dst + d] = new_k[src + d];", "present_value[dst + d] = new_v[src + d];"]) }}{% endif %} } else if (t >= step.stageEnd) { {{ channel_loop("HEAD_DIM", ["present_key[dst + d] = " + inputScalar + "(0.0);", "present_value[dst + d] = " + inputScalar + "(0.0);"]) }} }{% endif %}{% endif %}{% if cooperativeWindow %} }{% endif %}}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889{"name": "com.microsoft.GroupQueryAttention","id": "_com_microsoft_groupqueryattention_webgpu_0c84e3e","version": 1,"license": "Apache-2.0","backend": { "type": "webgpu" },"digest": {"algorithm": "sha256","files": {"attention-rank4-tiled.wgsl.jinja": "084x5bbpxeFR95/Q4nGzLrLnk9JJrd9XA1KJHxwU9CY=","attn-flash-decode-splitk-merge.wgsl.jinja": "nKMUcaMP7mcKykLHoGsn/KnsIaJiJRHDsceE7dKVcwo=","attn-flash-decode-splitk.wgsl.jinja": "ZD6C2fn5I7xZvvpTlsHdLtai8JBK2Ar+xc0SrLn3SAE=","attn-flash-online.wgsl.jinja": "QGaUiZyIJuQ9xS00I8cuZWYQI8bGldV+UJ0Mp/5kj6w=","attn-flash-prefill-cluster.wgsl.jinja": "Q7DUmulv66HOVBMkAannNVhEtOWkD+uhDn5muWo4p+E=","attn-flash-q32-broadcast.wgsl.jinja": "vogUJggIxK8tRg2tDORhIXZLheesY3Y221iVFFyHVY4=","attn-materialized-rowstats-combine-f32.wgsl.jinja": "SG+V1o5KhJ1LvkUQL0jcq62C+ETRGpy0XV9tvvOQivk=","attn-materialized-sgmat-f32.wgsl.jinja": "R0+zNbbnfRKpA+R7lcgY5FPlkmLNzNBJwJe1PmaSOvE=","attn-online-scalar.wgsl.jinja": "ysj3CuuKeu+MPlnaTwnNvCu3sSf8egjHE/uhE/Essmo=","bench.json": "v06hV3rz9UPzelx7YbIHmyOWgbj/0Y9ci7iz9mQS6m0=","gqa-attention.wgsl.jinja": "Wy1oR/7g/EzxQZizt/zGtOh4qiD60SVN4pfLSjmfsDo=","gqa-present.wgsl.jinja": "r0ELXXscqaVYqTYzA9IYr/xl9jWAe20ZFPScyiw34UQ=","gqa-qprep.wgsl.jinja": "VI/IHqwEMTpvrhFza3kKRDuLO3Eau91C4aMZRW0nAjg=","manifest.json": "8m8RL1h3mBW9P8voV+gr/KpJiMheynqdWWhmcrOoi8E=","test.json": "I771sUbwb/9MXIc27bUlvNl3UsiiFxP3H0/wRMt/B9M="}},"provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },"webgpu": {"manifestSpec": "2.1","variants": {"qkv_present_materialized_sgmat_f32": ["attn-materialized-rowstats-combine-f32.wgsl.jinja", "attn-materialized-sgmat-f32.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_materialized_sgmat_f32": ["attn-materialized-rowstats-combine-f32.wgsl.jinja", "attn-materialized-sgmat-f32.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_bias_materialized_sgmat_f32": ["attn-materialized-rowstats-combine-f32.wgsl.jinja", "attn-materialized-sgmat-f32.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_materialized_sgmat_f16": ["attn-materialized-rowstats-combine-f32.wgsl.jinja", "attn-materialized-sgmat-f32.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_rotary_materialized_sgmat_f32": ["attn-materialized-rowstats-combine-f32.wgsl.jinja", "attn-materialized-sgmat-f32.wgsl.jinja", "gqa-present.wgsl.jinja", "gqa-qprep.wgsl.jinja"],"past_kv_rotary_materialized_sgmat_f16": ["attn-materialized-rowstats-combine-f32.wgsl.jinja", "attn-materialized-sgmat-f32.wgsl.jinja", "gqa-present.wgsl.jinja", "gqa-qprep.wgsl.jinja"],"new_kv_past_materialized_sgmat_f32": ["attn-materialized-rowstats-combine-f32.wgsl.jinja", "attn-materialized-sgmat-f32.wgsl.jinja", "gqa-present.wgsl.jinja"],"window_shift_materialized_sgmat_f32": ["attn-materialized-rowstats-combine-f32.wgsl.jinja", "attn-materialized-sgmat-f32.wgsl.jinja", "gqa-present.wgsl.jinja"],"share_append_materialized_sgmat_f32": ["attn-materialized-rowstats-combine-f32.wgsl.jinja", "attn-materialized-sgmat-f32.wgsl.jinja", "gqa-present.wgsl.jinja"],"new_kv_share_append_split": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"new_kv_share_append_headsink_split": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"new_kv_share_append_rotary_split": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"new_kv_share_append_bidirectional_split": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"qkv_present_tiled_nosg": ["attention-rank4-tiled.wgsl.jinja", "gqa-present.wgsl.jinja"],"qkv_present_flash": ["attn-flash-online.wgsl.jinja", "gqa-present.wgsl.jinja"],"qkv_present_flash_causal": ["attn-flash-online.wgsl.jinja", "gqa-present.wgsl.jinja"],"qkv_present": ["attn-online-scalar.wgsl.jinja", "gqa-present.wgsl.jinja"],"qkv_present_causal": ["attn-online-scalar.wgsl.jinja", "gqa-present.wgsl.jinja"],"quant_int8": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"quant_int4": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"quant_int8_decode_splitk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "gqa-present.wgsl.jinja"],"qkv_present_flash_splitk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "gqa-present.wgsl.jinja"],"qkv_present_flash_cluster": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_bias_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_qnorm_rotary_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja", "gqa-qprep.wgsl.jinja"],"past_kv_decode_splitk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "gqa-present.wgsl.jinja"],"new_kv_past_decode_splitk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "gqa-present.wgsl.jinja"],"window_shift_decode_splitk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"new_kv_past_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_rotary_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_softcap_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_headsink_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_bias_headsink_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"window_shift_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"qkv_present_flash_q32_broadcast": ["attn-flash-q32-broadcast.wgsl.jinja", "gqa-present.wgsl.jinja"],"qkv_present_flash_q32_shared": ["attn-flash-q32-broadcast.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_rotary": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_qnorm_rotary": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"window_shift_rotary_append": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"window_shift_rotary_headsink_append": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"window_shift_rotary_bias_append": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"new_kv_past": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"window_shift_append": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"window_shift_headsink_append": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"window_shift_bias_append": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"new_kv_qnorm_rotary": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_bias": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_headsink": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"past_kv_bias_headsink": ["gqa-attention.wgsl.jinja", "gqa-present.wgsl.jinja"],"quant_int8_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"quant_int4_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"share_append_split_decode_splitk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "attn-flash-decode-splitk.wgsl.jinja", "gqa-present.wgsl.jinja"],"share_append_split_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"],"share_append_bidirectional_flash_prefill": ["attn-flash-prefill-cluster.wgsl.jinja", "gqa-present.wgsl.jinja"]}}}1{"name":"com.microsoft.GroupQueryAttention","id":"_com_microsoft_groupqueryattention_webgpu_2402ac0","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"attention-flash-sgmat16.wgsl.jinja":"UzAXZlMUtrVnplvxOf4cfCmMEsRzNYvJhUpKxUTDmHM=","attention-prepare-f32.wgsl.jinja":"EloABipalbUFQwpD6v463xHUsr85T9l+Xpv5wjecZSQ=","attention-rank4-tiled.wgsl.jinja":"R6/jTmX1a8MbNsGb/JXdXkW7T5otBVNhiUJdjY+XfP4=","attn-decode-gqa-splitk-merge.wgsl.jinja":"z9cfJRLVs572rZlrRvUKszC2UeMxxuRUOI22xW8Whd0=","attn-decode-gqa-splitk.wgsl.jinja":"NFZvjKLJr1YN5JqOEqdrsRCoVZWzRZn7pR5JKkztVzA=","attn-flash-decode-splitk-merge.wgsl.jinja":"y/9U0Xh0klSF4O9HW9Fug0EUvHEEsVnn7xEDzp/U23I=","attn-flash-decode-splitk.wgsl.jinja":"hUxYqvauQQHsLoVkNLjxrXMjKMXSf8FLdfogXN/ju9Y=","attn-flash-online.wgsl.jinja":"rrsiIKWxZ/CstabiQtigJS7NO7hNKxXhCxb6QXklc18=","attn-flash-prefill-cluster.wgsl.jinja":"w37j8yp9fFcv+a1hBRkaKMrM/KgDgd3TJdAR4iRjVz4=","attn-flash-q32-broadcast.wgsl.jinja":"Wl39Xb9AHY3o0sSHqyA/VQBKPus3SAyA9IVjpBLxgOI=","attn-materialized-rowstats-combine-f32.wgsl.jinja":"qkKK5gC1J+jmplB5S8Lrzf7lxUHivZAAZZq+11UHJh0=","attn-materialized-score-f32.wgsl.jinja":"ERy/IQJ0VD9B9xlORVG7PGq/aSTKsYkf3LzqxPmyVRk=","attn-materialized-sgmat-f32.wgsl.jinja":"CNTAoDU3CVK9PwG60ISp0C9lIs+BKrzty3H+ziDbPCw=","attn-materialized-shaped.wgsl.jinja":"Xr1nrb9xgM8JqGDl1Zqx/jzVpj6nYAGg+QH41gC4bhw=","attn-materialized-softmax-f32.wgsl.jinja":"Zfy2YAJrD1Aq0/jWTilwp86W9tXjFnN7fD749uZx8Zc=","attn-online-scalar.wgsl.jinja":"Zb9PyRnIZw+6B7mmB7LEvJ/LsaoCy5KbseB7l8W6an8=","bench.json":"ePHlnumCsOgjN11R2O074B5IGnOXyeC24yLrtDqzEwc=","gqa-attention.wgsl.jinja":"HdBShu4NSG7P2/vqPU/eV2yvWkWTdez27uRD3m7NK0g=","gqa-norm-rotate-rows.wgsl.jinja":"9d3WsJ+tnkkaVAypD9K5h261TB4CaVQbmdJAKgYiInU=","gqa-present.wgsl.jinja":"aMP8z5Tq1gbN28nlsszke8PoPotjsFbS3V807cemjKU=","gqa-qprep.wgsl.jinja":"hyDDjkivTEIGxVaUu2uBnzhVNgBlfFizSJra9myttVo=","gqa-score-matrix.wgsl.jinja":"kOSIr9j7KOGSqwn8YDoY5kwE5mP4sS8+mil3qpqEV5o=","gqa-score-range.wgsl.jinja":"DWwsSvuC7onB2m/TnlTaz6rPNJKVKl3TNKonzq3f0bI=","gqa-stream-matrix8.wgsl.jinja":"oNSL/1XFndbtiQ9F/9UXGirCGpbGasDgntPYdu2dv4k=","gqa-window-cache.wgsl.jinja":"mULLtk/RHaZFEUduNpTQsowS0vViQu5iP/RL/BHdSqo=","manifest.json":"8fIjKrPxItKC9brJ7QtZTmZFGRBOj5ueJmhekLmyReE=","test.json":"7ECV5N8bSb0DOc9MtGZ3D7T+7MCpSLjkhqkXdJTkSv8="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}
README.md+107-55
build/webgpu/attention-flash-sgmat16.wgsl.jinjaAdded+1095
build/webgpu/attention-prepare-f32.wgsl.jinjaAdded+18
build/webgpu/attention-rank4-tiled.wgsl.jinja+551-17
build/webgpu/attn-decode-gqa-splitk-merge.wgsl.jinjaAdded+477
build/webgpu/attn-decode-gqa-splitk.wgsl.jinjaAdded+640
build/webgpu/attn-flash-decode-splitk-merge.wgsl.jinja+568-27
build/webgpu/attn-flash-decode-splitk.wgsl.jinja+718-64
build/webgpu/attn-flash-online.wgsl.jinja+547-48
build/webgpu/attn-flash-prefill-cluster.wgsl.jinja+897-140
build/webgpu/attn-flash-q32-broadcast.wgsl.jinja+517-59
build/webgpu/attn-materialized-rowstats-combine-f32.wgsl.jinja+6-3
build/webgpu/attn-materialized-score-f32.wgsl.jinjaAdded+295
build/webgpu/attn-materialized-sgmat-f32.wgsl.jinja+720-140
build/webgpu/attn-materialized-shaped.wgsl.jinjaAdded+768
build/webgpu/attn-materialized-softmax-f32.wgsl.jinjaAdded+119
build/webgpu/attn-online-scalar.wgsl.jinja+503-39
build/webgpu/bench.json
build/webgpu/gqa-attention.wgsl.jinja+528-59
build/webgpu/gqa-norm-rotate-rows.wgsl.jinjaAdded+89
build/webgpu/gqa-present.wgsl.jinja+38-112
build/webgpu/gqa-qprep.wgsl.jinja+40-6
build/webgpu/gqa-score-matrix.wgsl.jinjaAdded+182
build/webgpu/gqa-score-range.wgsl.jinjaAdded+79
build/webgpu/gqa-stream-matrix8.wgsl.jinjaAdded+206
build/webgpu/gqa-window-cache.wgsl.jinjaAdded+156
build/webgpu/manifest.json
build/webgpu/metadata.json+1-89
build/webgpu/test.json