sync 4385228f788d
Browse files- README.md +73 -16
- build/webgpu/attn-flash-decode-splitk-merge.wgsl.jinja +38 -12
- build/webgpu/bench.json +0 -0
- build/webgpu/manifest.json +1 -526
- build/webgpu/metadata.json +1 -32
- build/webgpu/paged-attention.wgsl.jinja +517 -34
- build/webgpu/paged-qknorm.wgsl.jinja +274 -0
- build/webgpu/paged-rotary-qk.wgsl.jinja +176 -0
- build/webgpu/paged-scatter-kv.wgsl.jinja +92 -11
- build/webgpu/test.json +0 -0
README.md
CHANGED
|
@@ -12,10 +12,24 @@ tags:
|
|
| 12 |
|
| 13 |
## Description
|
| 14 |
|
| 15 |
-
Attention over
|
| 16 |
|
| 17 |
See the [ONNX Runtime `PagedAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.PagedAttention) for the reference semantics.
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
## Inputs
|
| 20 |
|
| 21 |
| Name | Upstream name | Logical dtype | WebGPU storage | Rank | Shape | Description | Presence |
|
|
@@ -28,7 +42,12 @@ See the [ONNX Runtime `PagedAttention` contrib-operator spec](https://github.com
|
|
| 28 |
| `cumulativeSequenceLengthT` | `cumulative_sequence_length` | `S` | `int32` | `1` | — | Exclusive prefix sums of the per-sequence token counts, shape `(batch_size + 1)`; sequence `b` owns packed tokens `[cum[b], cum[b+1])`. | required |
|
| 29 |
| `pastSeqlensT` | `past_seqlens` | `S` | `int32` | `1` | — | Cached history length per sequence, shape `(batch_size)`. | required |
|
| 30 |
| `blockTableT` | `block_table` | `S` | `int32` | `2` | — | Physical block index per sequence and logical block, shape `(batch_size, max_blocks_per_sequence)`. | required |
|
|
|
|
|
|
|
| 31 |
| `slotMappingT` | `slot_mapping` | `S` | `int32` | `1` | — | Flat destination slot, `block_id * block_size + offset`, for each token; `-1` suppresses that token's cache write. When omitted, the slot is derived from `past_seqlens`. `block_table` remains required because it defines the read path. | optional |
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
## Outputs
|
| 34 |
|
|
@@ -44,9 +63,13 @@ Attributes and default values (overridable per request):
|
|
| 44 |
|
| 45 |
| Attribute | Default | Description |
|
| 46 |
| --- | --- | --- |
|
| 47 |
-
| `
|
|
|
|
| 48 |
| `kv_num_heads` | — | Number of key/value heads. |
|
|
|
|
| 49 |
| `num_heads` | — | Number of query heads. |
|
|
|
|
|
|
|
| 50 |
| `scale` | — | Scale applied to query-key products; zero or omission selects `1 / sqrt(head_size)`. |
|
| 51 |
|
| 52 |
## Type constraints
|
|
@@ -60,42 +83,75 @@ Attributes and default values (overridable per request):
|
|
| 60 |
|
| 61 |
One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
|
| 62 |
|
| 63 |
-
- `
|
| 64 |
-
- `
|
| 65 |
-
- `
|
| 66 |
-
- `
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
## Device requirements
|
| 69 |
|
| 70 |
-
Every implementation variant requires `shader-f16`
|
|
|
|
|
|
|
| 71 |
|
| 72 |
## Files
|
| 73 |
|
| 74 |
-
- [`metadata.json`](build/webgpu/metadata.json) — kernel metadata (id, digests,
|
| 75 |
-
- [`manifest.json`](build/webgpu/manifest.json) — the op contract (source of truth)
|
| 76 |
-
- [`test.json`](build/webgpu/test.json) — correctness cases
|
| 77 |
-
- [`bench.json`](build/webgpu/bench.json) — benchmark cases
|
| 78 |
-
- [`attn-flash-decode-splitk-merge.wgsl.jinja`](build/webgpu/attn-flash-decode-splitk-merge.wgsl.jinja)
|
| 79 |
-
- [`paged-attention.wgsl.jinja`](build/webgpu/paged-attention.wgsl.jinja)
|
| 80 |
-
- [`paged-
|
|
|
|
|
|
|
| 81 |
|
| 82 |
## Use with `@huggingface/kernels`
|
| 83 |
|
| 84 |
```sh
|
| 85 |
-
npm install --save-exact @huggingface/kernels@0.0.1-preview.
|
| 86 |
```
|
| 87 |
|
|
|
|
|
|
|
|
|
|
| 88 |
Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
|
| 89 |
|
| 90 |
The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
|
| 91 |
It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
|
| 92 |
|
| 93 |
-
|
| 94 |
|
| 95 |
```js
|
| 96 |
import { getKernel } from "@huggingface/kernels";
|
| 97 |
|
| 98 |
const kernel = await getKernel("webgpu-kernels/com.microsoft.PagedAttention", { version: 1 });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
const { keyCacheT, valueCacheT, outputT } = await kernel({
|
| 100 |
queryT: { data: queryTData, shape: [2, 4] },
|
| 101 |
keyT: { data: keyTData, shape: [2, 2] },
|
|
@@ -108,4 +164,5 @@ const { keyCacheT, valueCacheT, outputT } = await kernel({
|
|
| 108 |
}, {
|
| 109 |
attrs: { num_heads: 2, kv_num_heads: 1 },
|
| 110 |
});
|
|
|
|
| 111 |
```
|
|
|
|
| 12 |
|
| 13 |
## Description
|
| 14 |
|
| 15 |
+
Attention over an in-place paged KV cache. Supports grouped heads, packed QKV, scaling, explicit slots, float16 storage, causal/full masks, left windows, RoPE, paired per-head Q/K RMS normalization and head sinks. Sequence lengths, block tables and rotary positions are checked on the GPU before indexing: invalid requests yield zero attention and skip the writes derived from them; invalid blocks or slots are skipped. Without RoPE, explicit slot writes do not depend on the sequence lengths. Softcap, LATENT layout, narrower value heads, quantized KV and attention metadata are unsupported.
|
| 16 |
|
| 17 |
See the [ONNX Runtime `PagedAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.PagedAttention) for the reference semantics.
|
| 18 |
|
| 19 |
+
## Differences from the ONNX Runtime spec
|
| 20 |
+
|
| 21 |
+
- Input `k_scale`, attribute `k_cache_dtype`, attribute `k_quant_type`: Quantized key-cache storage is not implemented by this inference package.
|
| 22 |
+
- Input `v_scale`, attribute `v_cache_dtype`, attribute `v_quant_type`: Quantized value-cache storage is not implemented by this inference package.
|
| 23 |
+
- Input `attention_metadata`: The optional attention-metadata fast path is not implemented by this inference package.
|
| 24 |
+
- Attribute `kv_cache_layout`: Only the standard paged cache layout represented by the rank-4 cache inputs is implemented.
|
| 25 |
+
- Attribute `rotary_offset`: Only zero-offset prefix rotary embedding is supported by this inference package.
|
| 26 |
+
- Attribute `softcap`: Attention softcap is not implemented by this inference package.
|
| 27 |
+
- Attribute `v_head_size`: A value-head width distinct from the query/key head width is not implemented.
|
| 28 |
+
- Input `valueCacheT` (ONNX `value_cache`): This package requires a distinct value cache; the schema's key-only cache mode is unsupported.
|
| 29 |
+
- Output `key_cache_out`: Returned as output `keyCacheT`.
|
| 30 |
+
- Output `value_cache_out`: Returned as output `valueCacheT`.
|
| 31 |
+
- Type `T`: Query, key, value, and cache tensors must use one common float16 data type.
|
| 32 |
+
|
| 33 |
## Inputs
|
| 34 |
|
| 35 |
| Name | Upstream name | Logical dtype | WebGPU storage | Rank | Shape | Description | Presence |
|
|
|
|
| 42 |
| `cumulativeSequenceLengthT` | `cumulative_sequence_length` | `S` | `int32` | `1` | — | Exclusive prefix sums of the per-sequence token counts, shape `(batch_size + 1)`; sequence `b` owns packed tokens `[cum[b], cum[b+1])`. | required |
|
| 43 |
| `pastSeqlensT` | `past_seqlens` | `S` | `int32` | `1` | — | Cached history length per sequence, shape `(batch_size)`. | required |
|
| 44 |
| `blockTableT` | `block_table` | `S` | `int32` | `2` | — | Physical block index per sequence and logical block, shape `(batch_size, max_blocks_per_sequence)`. | required |
|
| 45 |
+
| `cosCacheT` | `cos_cache` | `T` | same as logical dtype | `2` | — | Optional RoPE cosine cache, `(positions, rotary_dim / 2)`, paired with `sin_cache` when `do_rotary` is 1. The positive even rotary span may be a prefix of a head. Inactive caches are ignored. | optional |
|
| 46 |
+
| `sinCacheT` | `sin_cache` | `T` | same as logical dtype | `2` | — | Optional sine cache with the same shape and dtype as `cos_cache`. RoPE uses absolute positions `past[b] + local_token`, before new keys enter the cache. | optional |
|
| 47 |
| `slotMappingT` | `slot_mapping` | `S` | `int32` | `1` | — | Flat destination slot, `block_id * block_size + offset`, for each token; `-1` suppresses that token's cache write. When omitted, the slot is derived from `past_seqlens`. `block_table` remains required because it defines the read path. | optional |
|
| 48 |
+
| `headSinkT` | `head_sink` | `T` | same as logical dtype | `1` | — | Optional (`num_heads`) already-scaled logits. Each query head adds exp(sink) to its softmax denominator once, including across Split-K. Negative infinity contributes no mass; NaN or positive infinity produces NaN on a valid row. Invalid sequence lengths ignore sinks and output zero. | optional |
|
| 49 |
+
| `qNormT` | `q_norm_weight` | `T` | same as logical dtype | `1` | — | Optional per-channel RMS multiplier shared across query heads. Query and key weights must be supplied together; absent weights leave both inputs unchanged. | optional |
|
| 50 |
+
| `kNormT` | `k_norm_weight` | `T` | same as logical dtype | `1` | — | Optional per-channel RMS multiplier shared across key heads. Query and key weights must be supplied together; absent weights leave both inputs unchanged. | optional |
|
| 51 |
|
| 52 |
## Outputs
|
| 53 |
|
|
|
|
| 63 |
|
| 64 |
| Attribute | Default | Description |
|
| 65 |
| --- | --- | --- |
|
| 66 |
+
| `do_rotary` | `0` | Value 1 rotates the Q/K prefix in FP32 and rounds it to float16 before attention/cache storage; other integer values disable rotation. Requires positive-width matching cosine/sine caches. Rotary offset remains zero. |
|
| 67 |
+
| `is_causal` | `1` | Whether to apply causal masking: 1 attends through the current token; 0 attends to the full live context, including later tokens in this request. |
|
| 68 |
| `kv_num_heads` | — | Number of key/value heads. |
|
| 69 |
+
| `local_window_size` | `-1` | Query-relative left window. A positive W includes the current token and at most W-1 earlier tokens; non-causal mode retains every later live token. Non-positive values disable the window. Must be a safe integer; windows larger than the logical cache capacity are equivalent to an unbounded left mask. |
|
| 70 |
| `num_heads` | — | Number of query heads. |
|
| 71 |
+
| `qk_norm_epsilon` | `0.000001` | Positive representable finite float32 epsilon added to each incoming head's float32 mean square before normalization. Used only when both normalization weights are present. Normalized values round to float16 before optional rotary embedding. |
|
| 72 |
+
| `rotary_interleaved` | `0` | Value 1 pairs adjacent channels; other integer values pair the two halves of the rotary prefix. |
|
| 73 |
| `scale` | — | Scale applied to query-key products; zero or omission selects `1 / sqrt(head_size)`. |
|
| 74 |
|
| 75 |
## Type constraints
|
|
|
|
| 83 |
|
| 84 |
One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
|
| 85 |
|
| 86 |
+
- `paged_splitk_subgroups` — Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation.
|
| 87 |
+
- `paged_subgroups` — Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation.
|
| 88 |
+
- `paged_splitk` — Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation.
|
| 89 |
+
- `paged` — Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation.
|
| 90 |
+
- `paged_qknorm_fused_splitk_subgroups` — Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. A first pass applies per-head RMS normalization to Q and K, with RoPE in the same pass when enabled.
|
| 91 |
+
- `paged_qknorm_fused_subgroups` — Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. A first pass applies per-head RMS normalization to Q and K, with RoPE in the same pass when enabled.
|
| 92 |
+
- `paged_qknorm_fused_splitk` — Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. A first pass applies per-head RMS normalization to Q and K, with RoPE in the same pass when enabled.
|
| 93 |
+
- `paged_qknorm_fused` — Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. A first pass applies per-head RMS normalization to Q and K, with RoPE in the same pass when enabled.
|
| 94 |
+
- `paged_rotary_splitk_subgroups` — Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. A first pass applies RoPE to Q and K.
|
| 95 |
+
- `paged_rotary_subgroups` — Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. A first pass applies RoPE to Q and K.
|
| 96 |
+
- `paged_rotary_splitk` — Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. A first pass applies RoPE to Q and K.
|
| 97 |
+
- `paged_rotary` — Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. A first pass applies RoPE to Q and K.
|
| 98 |
+
- `paged_rotary_qknorm_splitk_subgroups` — Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. Separate first passes normalize Q, normalize K, then apply RoPE.
|
| 99 |
+
- `paged_rotary_qknorm_subgroups` — Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. Separate first passes normalize Q, normalize K, then apply RoPE.
|
| 100 |
+
- `paged_rotary_qknorm_splitk` — Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. Separate first passes normalize Q, normalize K, then apply RoPE.
|
| 101 |
+
- `paged_rotary_qknorm` — Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. Separate first passes normalize Q, normalize K, then apply RoPE.
|
| 102 |
|
| 103 |
## Device requirements
|
| 104 |
|
| 105 |
+
Every implementation variant requires `shader-f16`, so the package does not run without it.
|
| 106 |
+
|
| 107 |
+
Some implementation variants require `subgroups`. Other variants run without it; which variant runs also depends on the request's shapes and dtypes.
|
| 108 |
|
| 109 |
## Files
|
| 110 |
|
| 111 |
+
- [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PagedAttention/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)
|
| 112 |
+
- [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PagedAttention/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)
|
| 113 |
+
- [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PagedAttention/blob/v1/build/webgpu/test.json) — correctness cases
|
| 114 |
+
- [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PagedAttention/blob/v1/build/webgpu/bench.json) — benchmark cases
|
| 115 |
+
- [`attn-flash-decode-splitk-merge.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PagedAttention/blob/v1/build/webgpu/attn-flash-decode-splitk-merge.wgsl.jinja)
|
| 116 |
+
- [`paged-attention.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PagedAttention/blob/v1/build/webgpu/paged-attention.wgsl.jinja)
|
| 117 |
+
- [`paged-qknorm.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PagedAttention/blob/v1/build/webgpu/paged-qknorm.wgsl.jinja)
|
| 118 |
+
- [`paged-rotary-qk.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PagedAttention/blob/v1/build/webgpu/paged-rotary-qk.wgsl.jinja)
|
| 119 |
+
- [`paged-scatter-kv.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PagedAttention/blob/v1/build/webgpu/paged-scatter-kv.wgsl.jinja)
|
| 120 |
|
| 121 |
## Use with `@huggingface/kernels`
|
| 122 |
|
| 123 |
```sh
|
| 124 |
+
npm install --save-exact @huggingface/kernels@0.0.1-preview.4
|
| 125 |
```
|
| 126 |
|
| 127 |
+
Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.
|
| 128 |
+
This example also needs a device that supports the kernel's required WebGPU features.
|
| 129 |
+
|
| 130 |
Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
|
| 131 |
|
| 132 |
The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.
|
| 133 |
It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.
|
| 134 |
|
| 135 |
+
The `Uint16Array` inputs hold raw float16 bits and work on browsers without a `Float16Array` constructor.
|
| 136 |
|
| 137 |
```js
|
| 138 |
import { getKernel } from "@huggingface/kernels";
|
| 139 |
|
| 140 |
const kernel = await getKernel("webgpu-kernels/com.microsoft.PagedAttention", { version: 1 });
|
| 141 |
+
|
| 142 |
+
const queryTData = Uint16Array.of(14920, 15384, 15400, 14976, 13869, 45218, 47424, 48157);
|
| 143 |
+
const keyTData = Uint16Array.of(46304, 44288, 12572, 13876);
|
| 144 |
+
const valueTData = Uint16Array.of(14469, 14860, 15030, 14942);
|
| 145 |
+
const keyCacheTData = Uint16Array.of(
|
| 146 |
+
13415, 13638, 13778, 13842, 13844, 13799, 13727, 13644, 13565, 13500, 13455, 13429,
|
| 147 |
+
);
|
| 148 |
+
const valueCacheTData = Uint16Array.of(
|
| 149 |
+
44245, 12392, 13113, 12712, 10327, 45027, 45747, 45404, 8203, 13384, 14385, 14705,
|
| 150 |
+
);
|
| 151 |
+
const cumulativeSequenceLengthTData = Int32Array.of(0, 2);
|
| 152 |
+
const pastSeqlensTData = Int32Array.of(2);
|
| 153 |
+
const blockTableTData = Int32Array.of(2, 0, 1);
|
| 154 |
+
|
| 155 |
const { keyCacheT, valueCacheT, outputT } = await kernel({
|
| 156 |
queryT: { data: queryTData, shape: [2, 4] },
|
| 157 |
keyT: { data: keyTData, shape: [2, 2] },
|
|
|
|
| 164 |
}, {
|
| 165 |
attrs: { num_heads: 2, kv_num_heads: 1 },
|
| 166 |
});
|
| 167 |
+
console.log({ keyCacheT, valueCacheT, outputT });
|
| 168 |
```
|
build/webgpu/attn-flash-decode-splitk-merge.wgsl.jinja
CHANGED
|
@@ -6,9 +6,11 @@
|
|
| 6 |
// globalMax = max_s partialMax[s]
|
| 7 |
// globalDen = sum_s partialDenom[s] * exp(partialMax[s] - globalMax)
|
| 8 |
// out[d] = (sum_s partialOut[s, d] * exp(partialMax[s] - globalMax)) / globalDen
|
| 9 |
-
// One workgroup per (batch, head)
|
| 10 |
-
//
|
| 11 |
-
//
|
|
|
|
|
|
|
| 12 |
// Output layout: token-major [batch, seq, heads * headDim], matching the split pass.
|
| 13 |
const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;
|
| 14 |
const Q_HEADS: u32 = {{ qNumHeads }}u;
|
|
@@ -37,7 +39,16 @@ fn shifted_value(value: f32, maxValue: f32) -> f32 {
|
|
| 37 |
fn exp_shift(value: f32, maxValue: f32) -> f32 {
|
| 38 |
return exp(shifted_value(value, maxValue));
|
| 39 |
}
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
fn main(
|
| 42 |
@builtin(workgroup_id) wg: vec3<u32>,
|
| 43 |
@builtin(local_invocation_id) lid: vec3<u32>
|
|
@@ -45,28 +56,43 @@ fn main(
|
|
| 45 |
let h = wg.y;
|
| 46 |
let b = wg.z;
|
| 47 |
let d4 = lid.x;
|
| 48 |
-
|
|
|
|
|
|
|
| 49 |
return;
|
| 50 |
}
|
| 51 |
|
| 52 |
let mdBase = (b * Q_HEADS + h) * NUM_SPLITS;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
var globalMax = -FLT_MAX;
|
| 54 |
for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {
|
| 55 |
-
globalMax = max(globalMax,
|
|
|
|
|
|
|
|
|
|
| 56 |
}
|
|
|
|
| 57 |
var globalDenom = 0.0;
|
| 58 |
var outV = vec4<f32>(0.0);
|
| 59 |
for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {
|
| 60 |
-
let
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
let pBase = ((b * Q_HEADS + h) * NUM_SPLITS + s) * HEAD_DIM_V4;
|
| 64 |
-
outV = outV + partial_out[pBase + d4] * w;
|
| 65 |
}
|
| 66 |
|
| 67 |
let qBaseV4 = b * Q_HIDDEN_V4 + h * HEAD_DIM_V4;
|
| 68 |
// A split that covers no keys writes vec2(-FLT_MAX, 0), so when every split is empty —
|
| 69 |
-
// a query whose window
|
| 70 |
// and globalDenom lands on exactly 0. Emit 0 rather than dividing so an all-empty
|
| 71 |
// row has a defined zero result.
|
| 72 |
var outValue = select(vec4<f32>(0.0), outV / globalDenom, globalDenom > 0.0);
|
|
|
|
| 6 |
// globalMax = max_s partialMax[s]
|
| 7 |
// globalDen = sum_s partialDenom[s] * exp(partialMax[s] - globalMax)
|
| 8 |
// out[d] = (sum_s partialOut[s, d] * exp(partialMax[s] - globalMax)) / globalDen
|
| 9 |
+
// One workgroup per (batch, head), or per (batch, query token, head) when queries are split; one thread per
|
| 10 |
+
// output vec4 channel (per channel and split group when the splits are divided into groups). Each
|
| 11 |
+
// split's (max, denom) is read into workgroup memory once and its scale onto
|
| 12 |
+
// the global max computed once; every thread then sums the denominator in
|
| 13 |
+
// split order and keeps the merge state in registers.
|
| 14 |
// Output layout: token-major [batch, seq, heads * headDim], matching the split pass.
|
| 15 |
const HEAD_DIM_V4: u32 = {{ headDimV4 }}u;
|
| 16 |
const Q_HEADS: u32 = {{ qNumHeads }}u;
|
|
|
|
| 39 |
fn exp_shift(value: f32, maxValue: f32) -> f32 {
|
| 40 |
return exp(shifted_value(value, maxValue));
|
| 41 |
}
|
| 42 |
+
// Every split's statistics, read once for the workgroup, and its scale onto
|
| 43 |
+
// the global max, computed once.
|
| 44 |
+
var<workgroup> split_max: array<f32, NUM_SPLITS>;
|
| 45 |
+
var<workgroup> split_denom: array<f32, NUM_SPLITS>;
|
| 46 |
+
var<workgroup> split_scale: array<f32, NUM_SPLITS>;
|
| 47 |
+
const MERGE_THREADS: u32 = HEAD_DIM_V4;
|
| 48 |
+
// A split's partial row: its output vec4s, then its statistics when inline.
|
| 49 |
+
const PARTIAL_STRIDE: u32 = HEAD_DIM_V4{% if inlinePartialStats is defined and inlinePartialStats %} + 1u{% endif %};
|
| 50 |
+
|
| 51 |
+
@compute @workgroup_size(MERGE_THREADS, 1, 1)
|
| 52 |
fn main(
|
| 53 |
@builtin(workgroup_id) wg: vec3<u32>,
|
| 54 |
@builtin(local_invocation_id) lid: vec3<u32>
|
|
|
|
| 56 |
let h = wg.y;
|
| 57 |
let b = wg.z;
|
| 58 |
let d4 = lid.x;
|
| 59 |
+
// The workgroup is HEAD_DIM_V4 lanes per group exactly, so the exit stays
|
| 60 |
+
// uniform ahead of the barriers below.
|
| 61 |
+
if (h >= Q_HEADS) {
|
| 62 |
return;
|
| 63 |
}
|
| 64 |
|
| 65 |
let mdBase = (b * Q_HEADS + h) * NUM_SPLITS;
|
| 66 |
+
|
| 67 |
+
for (var s = lid.x; s < NUM_SPLITS; s = s + MERGE_THREADS) {
|
| 68 |
+
{% if inlinePartialStats is defined and inlinePartialStats %}
|
| 69 |
+
let stats = partial_out[(mdBase + s) * PARTIAL_STRIDE + HEAD_DIM_V4].xy;
|
| 70 |
+
{% else %}
|
| 71 |
+
let stats = partial_stats[mdBase + s];
|
| 72 |
+
{% endif %}
|
| 73 |
+
split_max[s] = stats.x;
|
| 74 |
+
split_denom[s] = stats.y;
|
| 75 |
+
}
|
| 76 |
+
workgroupBarrier();
|
| 77 |
var globalMax = -FLT_MAX;
|
| 78 |
for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {
|
| 79 |
+
globalMax = max(globalMax, split_max[s]);
|
| 80 |
+
}
|
| 81 |
+
for (var s = lid.x; s < NUM_SPLITS; s = s + MERGE_THREADS) {
|
| 82 |
+
split_scale[s] = exp_shift(split_max[s], globalMax);
|
| 83 |
}
|
| 84 |
+
workgroupBarrier();
|
| 85 |
var globalDenom = 0.0;
|
| 86 |
var outV = vec4<f32>(0.0);
|
| 87 |
for (var s: u32 = 0u; s < NUM_SPLITS; s = s + 1u) {
|
| 88 |
+
let w = split_scale[s];
|
| 89 |
+
globalDenom = globalDenom + split_denom[s] * w;
|
| 90 |
+
outV = outV + partial_out[(mdBase + s) * PARTIAL_STRIDE + d4] * w;
|
|
|
|
|
|
|
| 91 |
}
|
| 92 |
|
| 93 |
let qBaseV4 = b * Q_HIDDEN_V4 + h * HEAD_DIM_V4;
|
| 94 |
// A split that covers no keys writes vec2(-FLT_MAX, 0), so when every split is empty —
|
| 95 |
+
// a query whose window contains no keys — globalMax stays -FLT_MAX, exp_shift(x, x) is 1,
|
| 96 |
// and globalDenom lands on exactly 0. Emit 0 rather than dividing so an all-empty
|
| 97 |
// row has a defined zero result.
|
| 98 |
var outValue = select(vec4<f32>(0.0), outV / globalDenom, globalDenom > 0.0);
|
build/webgpu/bench.json
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
build/webgpu/manifest.json
CHANGED
|
@@ -1,526 +1 @@
|
|
| 1 |
-
{
|
| 2 |
-
"domain": "com.microsoft",
|
| 3 |
-
"name": "PagedAttention",
|
| 4 |
-
"sinceVersion": 1,
|
| 5 |
-
"inputs": {
|
| 6 |
-
"queryT": { "onnx": "query", "dtype": "T", "rank": 2 },
|
| 7 |
-
"keyT": { "onnx": "key", "dtype": "T", "rank": 2, "optional": true },
|
| 8 |
-
"valueT": { "onnx": "value", "dtype": "T", "rank": 2, "optional": true },
|
| 9 |
-
"keyCacheT": { "onnx": "key_cache", "dtype": "T", "rank": 4 },
|
| 10 |
-
"valueCacheT": { "onnx": "value_cache", "dtype": "T", "rank": 4 },
|
| 11 |
-
"cumulativeSequenceLengthT": { "onnx": "cumulative_sequence_length", "dtype": "S", "rank": 1, "storage": "int32" },
|
| 12 |
-
"pastSeqlensT": { "onnx": "past_seqlens", "dtype": "S", "rank": 1, "storage": "int32" },
|
| 13 |
-
"blockTableT": { "onnx": "block_table", "dtype": "S", "rank": 2, "storage": "int32" },
|
| 14 |
-
"slotMappingT": { "onnx": "slot_mapping", "dtype": "S", "rank": 1, "optional": true, "storage": "int32" }
|
| 15 |
-
},
|
| 16 |
-
"outputs": {
|
| 17 |
-
"outputT": {
|
| 18 |
-
"onnx": "output",
|
| 19 |
-
"dtype": "T",
|
| 20 |
-
"rank": 2,
|
| 21 |
-
"shape": "[dim(shapes.queryT, 0), attrs.num_heads * headSize]"
|
| 22 |
-
},
|
| 23 |
-
"keyCacheT": { "onnx": "key_cache", "dtype": "T", "rank": 4, "optional": true, "shape": "shapes.keyCacheT" },
|
| 24 |
-
"valueCacheT": { "onnx": "value_cache", "dtype": "T", "rank": 4, "optional": true, "shape": "shapes.valueCacheT" }
|
| 25 |
-
},
|
| 26 |
-
"attributes": { "is_causal": { "default": 1 }, "kv_num_heads": {}, "num_heads": {}, "scale": {} },
|
| 27 |
-
"attributeConstraints": {
|
| 28 |
-
"is_causal": { "values": [1] },
|
| 29 |
-
"kv_num_heads": { "required": true },
|
| 30 |
-
"num_heads": { "required": true }
|
| 31 |
-
},
|
| 32 |
-
"typeConstraints": { "T": ["float16"], "S": ["int32"] },
|
| 33 |
-
"tunables": {
|
| 34 |
-
"WORKGROUP_SIZE": { "default": 64 },
|
| 35 |
-
"SCATTER_WORKGROUP_SIZE": { "default": 64 },
|
| 36 |
-
"MAX_SPLITS": { "default": 16 },
|
| 37 |
-
"SPLIT_MIN_KEYS": { "default": 128 },
|
| 38 |
-
"SPLIT_TARGET_WORKGROUPS": { "default": 1024 }
|
| 39 |
-
},
|
| 40 |
-
"derive": {
|
| 41 |
-
"tokenCount": "dim(shapes.queryT, 0)",
|
| 42 |
-
"blockSize": "dim(shapes.keyCacheT, 1)",
|
| 43 |
-
"headSize": "dim(shapes.keyCacheT, 3)",
|
| 44 |
-
"maxBlocks": "dim(shapes.blockTableT, 1)",
|
| 45 |
-
"batchSize": "dim(shapes.cumulativeSequenceLengthT, 0) - 1",
|
| 46 |
-
"qHidden": "attrs.num_heads * headSize",
|
| 47 |
-
"kvHidden": "attrs.kv_num_heads * headSize",
|
| 48 |
-
"qPerKv": "attrs.num_heads / max(1, attrs.kv_num_heads)",
|
| 49 |
-
"headVec": "headSize / 4",
|
| 50 |
-
"cacheVec4Ok": "headSize % 4 == 0",
|
| 51 |
-
"packedStride": "qHidden + 2 * kvHidden",
|
| 52 |
-
"cacheShapeOk": "ranks.keyCacheT == 4 and ranks.valueCacheT == 4 and sameShape(shapes.valueCacheT, shapes.keyCacheT) and dim(shapes.keyCacheT, 2) == attrs.kv_num_heads and blockSize > 0 and headSize > 0 and tensorDtypes.keyCacheT == tensorDtypes.queryT and tensorDtypes.valueCacheT == tensorDtypes.queryT",
|
| 53 |
-
"headLayoutOk": "attrs.num_heads > 0 and attrs.kv_num_heads > 0 and attrs.num_heads % attrs.kv_num_heads == 0",
|
| 54 |
-
"scheduleShapeOk": "ranks.cumulativeSequenceLengthT == 1 and ranks.pastSeqlensT == 1 and ranks.blockTableT == 2 and batchSize >= 1 and dim(shapes.pastSeqlensT, 0) == batchSize and dim(shapes.blockTableT, 0) == batchSize and maxBlocks >= 1",
|
| 55 |
-
"ioShapeOk": "ranks.queryT == 2 and ranks.outputT == 2 and dim(shapes.outputT, 0) == tokenCount and dim(shapes.outputT, 1) == qHidden and tensorDtypes.outputT == tensorDtypes.queryT and f16Ok(tensorDtypes.queryT)",
|
| 56 |
-
"separateKv": "present.keyT and present.valueT and ranks.keyT == 2 and ranks.valueT == 2 and dim(shapes.keyT, 0) == tokenCount and dim(shapes.valueT, 0) == tokenCount and dim(shapes.keyT, 1) == kvHidden and dim(shapes.valueT, 1) == kvHidden and tensorDtypes.keyT == tensorDtypes.queryT and tensorDtypes.valueT == tensorDtypes.queryT and dim(shapes.queryT, 1) == qHidden",
|
| 57 |
-
"packedKv": "not present.keyT and not present.valueT and dim(shapes.queryT, 1) == packedStride",
|
| 58 |
-
"slotShapeOk": "dim(shapes.slotMappingT, 0) == tokenCount and ranks.slotMappingT == 1 if present.slotMappingT else true",
|
| 59 |
-
"pagedContractOk": "cacheShapeOk and headLayoutOk and scheduleShapeOk and ioShapeOk and slotShapeOk",
|
| 60 |
-
"dispatchFits": "tokenCount <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and attrs.num_heads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and tunables.WORKGROUP_SIZE <= device.limits.maxComputeInvocationsPerWorkgroup and tunables.SCATTER_WORKGROUP_SIZE <= device.limits.maxComputeInvocationsPerWorkgroup",
|
| 61 |
-
"pagedBaseWorkgroups": "tokenCount * attrs.kv_num_heads",
|
| 62 |
-
"pagedAttnQueryFloats": "2 * headSize * qPerKv",
|
| 63 |
-
"pagedAttnLaneFloats": "3 * qPerKv + 1",
|
| 64 |
-
"pagedAttnWgBudget": "floor(device.limits.maxComputeWorkgroupStorageSize / 4 - pagedAttnQueryFloats) / pagedAttnLaneFloats",
|
| 65 |
-
"pagedAttnWg": "max(32, min(tunables.WORKGROUP_SIZE, pow2ceil(max(1, floor(pagedAttnWgBudget)) + 1) / 2))",
|
| 66 |
-
"pagedAttnStorageBytes": "(pagedAttnQueryFloats + pagedAttnLaneFloats * pagedAttnWg) * 4",
|
| 67 |
-
"pagedAttnStorageFits": "pagedAttnStorageBytes <= device.limits.maxComputeWorkgroupStorageSize and pagedAttnWg <= device.limits.maxComputeInvocationsPerWorkgroup and pagedAttnWg <= device.limits.maxComputeWorkgroupSizeX",
|
| 68 |
-
"pagedKeyCeiling": "maxBlocks * blockSize",
|
| 69 |
-
"pagedSplitWg": "min(256, max(32, pow2ceil(headVec)))",
|
| 70 |
-
"pagedSplitStorageBytes": "(2 * headSize * qPerKv + (3 * qPerKv + 1) * pagedSplitWg) * 4",
|
| 71 |
-
"pagedSplitStorageFits": "pagedSplitStorageBytes <= device.limits.maxComputeWorkgroupStorageSize",
|
| 72 |
-
"pagedSplitCap": "max(1, min(tunables.MAX_SPLITS, pagedKeyCeiling / tunables.SPLIT_MIN_KEYS))",
|
| 73 |
-
"numSplits": "max(1, min(pagedSplitCap, ceilDiv(tunables.SPLIT_TARGET_WORKGROUPS, max(1, pagedBaseWorkgroups))))",
|
| 74 |
-
"pagedSplitScratchBytes": "tokenCount * attrs.num_heads * numSplits * headSize * 4",
|
| 75 |
-
"pagedSplitStatsBytes": "2 * tokenCount * attrs.num_heads * numSplits * 4",
|
| 76 |
-
"pagedSplitFits": "numSplits >= 2 and cacheVec4Ok and headVec >= 1 and pagedSplitScratchBytes <= device.limits.maxStorageBufferBindingSize and pagedSplitScratchBytes <= device.limits.maxBufferSize and pagedSplitStatsBytes <= device.limits.maxStorageBufferBindingSize and pagedSplitStatsBytes <= device.limits.maxBufferSize and numSplits <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and headVec <= device.limits.maxComputeInvocationsPerWorkgroup and headVec <= device.limits.maxComputeWorkgroupSizeX and pagedSplitWg <= device.limits.maxComputeInvocationsPerWorkgroup and pagedSplitWg <= device.limits.maxComputeWorkgroupSizeX",
|
| 77 |
-
"aScalar": "dtypes.T",
|
| 78 |
-
"scalar": "dtypes.T",
|
| 79 |
-
"numHeads": "attrs.num_heads",
|
| 80 |
-
"kvNumHeads": "attrs.kv_num_heads",
|
| 81 |
-
"packedQkv": "not present.keyT",
|
| 82 |
-
"hasSlotMapping": "present.slotMappingT",
|
| 83 |
-
"attnWorkgroup": "pagedAttnWg",
|
| 84 |
-
"cacheVec": "(\"vec4<f16>\" if dtypes.T == \"f16\" else \"vec4<f32>\") if cacheVec4Ok else dtypes.T",
|
| 85 |
-
"headDimV4": "headVec",
|
| 86 |
-
"headDim": "headSize",
|
| 87 |
-
"qNumHeads": "attrs.num_heads",
|
| 88 |
-
"qHiddenV4": "qHidden / 4",
|
| 89 |
-
"outVec": "\"vec4<f16>\" if dtypes.T == \"f16\" else \"vec4<f32>\""
|
| 90 |
-
},
|
| 91 |
-
"when": ["pagedContractOk", "dispatchFits"],
|
| 92 |
-
"bindings": {
|
| 93 |
-
"key": { "arg": "keyT", "elementType": "$aScalar" },
|
| 94 |
-
"value": { "arg": "valueT", "elementType": "$aScalar" },
|
| 95 |
-
"key_cache": { "arg": "keyCacheT", "elementType": "$aScalar" },
|
| 96 |
-
"value_cache": { "arg": "valueCacheT", "elementType": "$aScalar" },
|
| 97 |
-
"cumulative_sequence_length": { "arg": "cumulativeSequenceLengthT", "elementType": "i32" },
|
| 98 |
-
"past_seqlens": { "arg": "pastSeqlensT", "elementType": "i32" },
|
| 99 |
-
"block_table": { "arg": "blockTableT", "elementType": "i32" },
|
| 100 |
-
"params": {
|
| 101 |
-
"struct": [
|
| 102 |
-
{ "name": "batchSize", "type": "u32", "value": "batchSize" },
|
| 103 |
-
{ "name": "scatterCount", "type": "u32", "value": "tokenCount * attrs.kv_num_heads * headSize" }
|
| 104 |
-
]
|
| 105 |
-
},
|
| 106 |
-
"slot_mapping": { "arg": "slotMappingT", "elementType": "i32" },
|
| 107 |
-
"params_scatter": {
|
| 108 |
-
"name": "params",
|
| 109 |
-
"struct": [{ "name": "scatterCount", "type": "u32", "value": "tokenCount * attrs.kv_num_heads * headSize" }]
|
| 110 |
-
},
|
| 111 |
-
"query": { "arg": "queryT", "elementType": "$aScalar" },
|
| 112 |
-
"key_cache_main": {
|
| 113 |
-
"arg": "keyCacheT",
|
| 114 |
-
"name": "key_cache",
|
| 115 |
-
"buffer": "read-only-storage",
|
| 116 |
-
"elementType": "$cacheVec"
|
| 117 |
-
},
|
| 118 |
-
"value_cache_main": {
|
| 119 |
-
"arg": "valueCacheT",
|
| 120 |
-
"name": "value_cache",
|
| 121 |
-
"buffer": "read-only-storage",
|
| 122 |
-
"elementType": "$cacheVec"
|
| 123 |
-
},
|
| 124 |
-
"params_main": {
|
| 125 |
-
"name": "params",
|
| 126 |
-
"struct": [
|
| 127 |
-
{ "name": "batchSize", "type": "u32", "value": "batchSize" },
|
| 128 |
-
{ "name": "scale", "type": "f32", "value": "attrs.scale if has(attrs, \"scale\") else 0" }
|
| 129 |
-
]
|
| 130 |
-
}
|
| 131 |
-
},
|
| 132 |
-
"variants": [
|
| 133 |
-
{
|
| 134 |
-
"id": "separate_derived_splitk",
|
| 135 |
-
"priority": 10,
|
| 136 |
-
"when": ["pagedSplitFits", "pagedSplitStorageFits", "separateKv", "not present.slotMappingT"],
|
| 137 |
-
"requires": { "features": ["shader-f16"] },
|
| 138 |
-
"derive": { "attnWorkgroup": "pagedSplitWg" },
|
| 139 |
-
"intermediates": [
|
| 140 |
-
{ "id": "partialOut", "dtype": "float32", "shape": "[tokenCount * attrs.num_heads * numSplits * headSize]" },
|
| 141 |
-
{ "id": "partialStats", "dtype": "float32", "shape": "[2 * tokenCount * attrs.num_heads * numSplits]" }
|
| 142 |
-
],
|
| 143 |
-
"passes": [
|
| 144 |
-
{
|
| 145 |
-
"id": "scatter",
|
| 146 |
-
"name": "PagedAttention.ScatterKV",
|
| 147 |
-
"shader": "paged-scatter-kv.wgsl.jinja",
|
| 148 |
-
"bindings": ["key", "value", "key_cache", "value_cache", "cumulative_sequence_length", "past_seqlens", "block_table", "params"],
|
| 149 |
-
"dispatch": {
|
| 150 |
-
"x": "min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 151 |
-
"y": "ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 152 |
-
"z": 1
|
| 153 |
-
}
|
| 154 |
-
},
|
| 155 |
-
{
|
| 156 |
-
"id": "split_attention",
|
| 157 |
-
"name": "PagedAttention.AttendSplitK",
|
| 158 |
-
"shader": "paged-attention.wgsl.jinja",
|
| 159 |
-
"derive": { "splitK": true },
|
| 160 |
-
"bindings": [
|
| 161 |
-
"query",
|
| 162 |
-
"key_cache_main",
|
| 163 |
-
"value_cache_main",
|
| 164 |
-
"cumulative_sequence_length",
|
| 165 |
-
"past_seqlens",
|
| 166 |
-
"block_table",
|
| 167 |
-
{ "scratch": "partialOut", "name": "partial_out", "elementType": "vec4<f32>" },
|
| 168 |
-
{ "scratch": "partialStats", "name": "partial_stats", "elementType": "vec2<f32>" },
|
| 169 |
-
"params_main"
|
| 170 |
-
],
|
| 171 |
-
"dispatch": { "x": "tokenCount", "y": "attrs.kv_num_heads", "z": "numSplits" }
|
| 172 |
-
},
|
| 173 |
-
{
|
| 174 |
-
"id": "merge",
|
| 175 |
-
"name": "PagedAttention.AttendSplitKMerge",
|
| 176 |
-
"shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
|
| 177 |
-
"derive": { "layout": "\"bsh\"" },
|
| 178 |
-
"bindings": [
|
| 179 |
-
{
|
| 180 |
-
"scratch": "partialOut",
|
| 181 |
-
"name": "partial_out",
|
| 182 |
-
"buffer": "read-only-storage",
|
| 183 |
-
"elementType": "vec4<f32>"
|
| 184 |
-
},
|
| 185 |
-
{
|
| 186 |
-
"scratch": "partialStats",
|
| 187 |
-
"name": "partial_stats",
|
| 188 |
-
"buffer": "read-only-storage",
|
| 189 |
-
"elementType": "vec2<f32>"
|
| 190 |
-
},
|
| 191 |
-
{ "arg": "outputT", "name": "output", "elementType": "$outVec" }
|
| 192 |
-
],
|
| 193 |
-
"dispatch": { "x": 1, "y": "attrs.num_heads", "z": "tokenCount" }
|
| 194 |
-
}
|
| 195 |
-
]
|
| 196 |
-
},
|
| 197 |
-
{
|
| 198 |
-
"id": "separate_derived",
|
| 199 |
-
"when": ["pagedAttnStorageFits", "separateKv", "not present.slotMappingT"],
|
| 200 |
-
"requires": { "features": ["shader-f16"] },
|
| 201 |
-
"passes": [
|
| 202 |
-
{
|
| 203 |
-
"id": "scatter",
|
| 204 |
-
"name": "PagedAttention.ScatterKV",
|
| 205 |
-
"shader": "paged-scatter-kv.wgsl.jinja",
|
| 206 |
-
"bindings": ["key", "value", "key_cache", "value_cache", "cumulative_sequence_length", "past_seqlens", "block_table", "params"],
|
| 207 |
-
"dispatch": {
|
| 208 |
-
"x": "min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 209 |
-
"y": "ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 210 |
-
"z": 1
|
| 211 |
-
}
|
| 212 |
-
},
|
| 213 |
-
{
|
| 214 |
-
"id": "main",
|
| 215 |
-
"name": "PagedAttention.Attend",
|
| 216 |
-
"shader": "paged-attention.wgsl.jinja",
|
| 217 |
-
"bindings": [
|
| 218 |
-
"query",
|
| 219 |
-
"key_cache_main",
|
| 220 |
-
"value_cache_main",
|
| 221 |
-
"cumulative_sequence_length",
|
| 222 |
-
"past_seqlens",
|
| 223 |
-
"block_table",
|
| 224 |
-
{ "arg": "outputT", "name": "output", "elementType": "$aScalar" },
|
| 225 |
-
"params_main"
|
| 226 |
-
],
|
| 227 |
-
"dispatch": { "x": "tokenCount", "y": "attrs.kv_num_heads" }
|
| 228 |
-
}
|
| 229 |
-
]
|
| 230 |
-
},
|
| 231 |
-
{
|
| 232 |
-
"id": "separate_slot_splitk",
|
| 233 |
-
"priority": 10,
|
| 234 |
-
"when": ["pagedSplitFits", "pagedSplitStorageFits", "separateKv", "present.slotMappingT"],
|
| 235 |
-
"requires": { "features": ["shader-f16"] },
|
| 236 |
-
"derive": { "attnWorkgroup": "pagedSplitWg" },
|
| 237 |
-
"intermediates": [
|
| 238 |
-
{ "id": "partialOut", "dtype": "float32", "shape": "[tokenCount * attrs.num_heads * numSplits * headSize]" },
|
| 239 |
-
{ "id": "partialStats", "dtype": "float32", "shape": "[2 * tokenCount * attrs.num_heads * numSplits]" }
|
| 240 |
-
],
|
| 241 |
-
"passes": [
|
| 242 |
-
{
|
| 243 |
-
"id": "scatter",
|
| 244 |
-
"name": "PagedAttention.ScatterKV",
|
| 245 |
-
"shader": "paged-scatter-kv.wgsl.jinja",
|
| 246 |
-
"bindings": ["key", "value", "key_cache", "value_cache", "slot_mapping", "params_scatter"],
|
| 247 |
-
"dispatch": {
|
| 248 |
-
"x": "min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 249 |
-
"y": "ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 250 |
-
"z": 1
|
| 251 |
-
}
|
| 252 |
-
},
|
| 253 |
-
{
|
| 254 |
-
"id": "split_attention",
|
| 255 |
-
"name": "PagedAttention.AttendSplitK",
|
| 256 |
-
"shader": "paged-attention.wgsl.jinja",
|
| 257 |
-
"derive": { "splitK": true },
|
| 258 |
-
"bindings": [
|
| 259 |
-
"query",
|
| 260 |
-
"key_cache_main",
|
| 261 |
-
"value_cache_main",
|
| 262 |
-
"cumulative_sequence_length",
|
| 263 |
-
"past_seqlens",
|
| 264 |
-
"block_table",
|
| 265 |
-
{ "scratch": "partialOut", "name": "partial_out", "elementType": "vec4<f32>" },
|
| 266 |
-
{ "scratch": "partialStats", "name": "partial_stats", "elementType": "vec2<f32>" },
|
| 267 |
-
"params_main"
|
| 268 |
-
],
|
| 269 |
-
"dispatch": { "x": "tokenCount", "y": "attrs.kv_num_heads", "z": "numSplits" }
|
| 270 |
-
},
|
| 271 |
-
{
|
| 272 |
-
"id": "merge",
|
| 273 |
-
"name": "PagedAttention.AttendSplitKMerge",
|
| 274 |
-
"shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
|
| 275 |
-
"derive": { "layout": "\"bsh\"" },
|
| 276 |
-
"bindings": [
|
| 277 |
-
{
|
| 278 |
-
"scratch": "partialOut",
|
| 279 |
-
"name": "partial_out",
|
| 280 |
-
"buffer": "read-only-storage",
|
| 281 |
-
"elementType": "vec4<f32>"
|
| 282 |
-
},
|
| 283 |
-
{
|
| 284 |
-
"scratch": "partialStats",
|
| 285 |
-
"name": "partial_stats",
|
| 286 |
-
"buffer": "read-only-storage",
|
| 287 |
-
"elementType": "vec2<f32>"
|
| 288 |
-
},
|
| 289 |
-
{ "arg": "outputT", "name": "output", "elementType": "$outVec" }
|
| 290 |
-
],
|
| 291 |
-
"dispatch": { "x": 1, "y": "attrs.num_heads", "z": "tokenCount" }
|
| 292 |
-
}
|
| 293 |
-
]
|
| 294 |
-
},
|
| 295 |
-
{
|
| 296 |
-
"id": "separate_slot",
|
| 297 |
-
"when": ["pagedAttnStorageFits", "separateKv", "present.slotMappingT"],
|
| 298 |
-
"requires": { "features": ["shader-f16"] },
|
| 299 |
-
"passes": [
|
| 300 |
-
{
|
| 301 |
-
"id": "scatter",
|
| 302 |
-
"name": "PagedAttention.ScatterKV",
|
| 303 |
-
"shader": "paged-scatter-kv.wgsl.jinja",
|
| 304 |
-
"bindings": ["key", "value", "key_cache", "value_cache", "slot_mapping", "params_scatter"],
|
| 305 |
-
"dispatch": {
|
| 306 |
-
"x": "min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 307 |
-
"y": "ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 308 |
-
"z": 1
|
| 309 |
-
}
|
| 310 |
-
},
|
| 311 |
-
{
|
| 312 |
-
"id": "main",
|
| 313 |
-
"name": "PagedAttention.Attend",
|
| 314 |
-
"shader": "paged-attention.wgsl.jinja",
|
| 315 |
-
"bindings": [
|
| 316 |
-
"query",
|
| 317 |
-
"key_cache_main",
|
| 318 |
-
"value_cache_main",
|
| 319 |
-
"cumulative_sequence_length",
|
| 320 |
-
"past_seqlens",
|
| 321 |
-
"block_table",
|
| 322 |
-
{ "arg": "outputT", "name": "output", "elementType": "$aScalar" },
|
| 323 |
-
"params_main"
|
| 324 |
-
],
|
| 325 |
-
"dispatch": { "x": "tokenCount", "y": "attrs.kv_num_heads" }
|
| 326 |
-
}
|
| 327 |
-
]
|
| 328 |
-
},
|
| 329 |
-
{
|
| 330 |
-
"id": "packed_derived_splitk",
|
| 331 |
-
"priority": 10,
|
| 332 |
-
"when": ["pagedSplitFits", "pagedSplitStorageFits", "packedKv", "not present.slotMappingT"],
|
| 333 |
-
"requires": { "features": ["shader-f16"] },
|
| 334 |
-
"derive": { "attnWorkgroup": "pagedSplitWg" },
|
| 335 |
-
"intermediates": [
|
| 336 |
-
{ "id": "partialOut", "dtype": "float32", "shape": "[tokenCount * attrs.num_heads * numSplits * headSize]" },
|
| 337 |
-
{ "id": "partialStats", "dtype": "float32", "shape": "[2 * tokenCount * attrs.num_heads * numSplits]" }
|
| 338 |
-
],
|
| 339 |
-
"passes": [
|
| 340 |
-
{
|
| 341 |
-
"id": "scatter",
|
| 342 |
-
"name": "PagedAttention.ScatterKV",
|
| 343 |
-
"shader": "paged-scatter-kv.wgsl.jinja",
|
| 344 |
-
"bindings": ["query", "key_cache", "value_cache", "cumulative_sequence_length", "past_seqlens", "block_table", "params"],
|
| 345 |
-
"dispatch": {
|
| 346 |
-
"x": "min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 347 |
-
"y": "ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 348 |
-
"z": 1
|
| 349 |
-
}
|
| 350 |
-
},
|
| 351 |
-
{
|
| 352 |
-
"id": "split_attention",
|
| 353 |
-
"name": "PagedAttention.AttendSplitK",
|
| 354 |
-
"shader": "paged-attention.wgsl.jinja",
|
| 355 |
-
"derive": { "splitK": true },
|
| 356 |
-
"bindings": [
|
| 357 |
-
"query",
|
| 358 |
-
"key_cache_main",
|
| 359 |
-
"value_cache_main",
|
| 360 |
-
"cumulative_sequence_length",
|
| 361 |
-
"past_seqlens",
|
| 362 |
-
"block_table",
|
| 363 |
-
{ "scratch": "partialOut", "name": "partial_out", "elementType": "vec4<f32>" },
|
| 364 |
-
{ "scratch": "partialStats", "name": "partial_stats", "elementType": "vec2<f32>" },
|
| 365 |
-
"params_main"
|
| 366 |
-
],
|
| 367 |
-
"dispatch": { "x": "tokenCount", "y": "attrs.kv_num_heads", "z": "numSplits" }
|
| 368 |
-
},
|
| 369 |
-
{
|
| 370 |
-
"id": "merge",
|
| 371 |
-
"name": "PagedAttention.AttendSplitKMerge",
|
| 372 |
-
"shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
|
| 373 |
-
"derive": { "layout": "\"bsh\"" },
|
| 374 |
-
"bindings": [
|
| 375 |
-
{
|
| 376 |
-
"scratch": "partialOut",
|
| 377 |
-
"name": "partial_out",
|
| 378 |
-
"buffer": "read-only-storage",
|
| 379 |
-
"elementType": "vec4<f32>"
|
| 380 |
-
},
|
| 381 |
-
{
|
| 382 |
-
"scratch": "partialStats",
|
| 383 |
-
"name": "partial_stats",
|
| 384 |
-
"buffer": "read-only-storage",
|
| 385 |
-
"elementType": "vec2<f32>"
|
| 386 |
-
},
|
| 387 |
-
{ "arg": "outputT", "name": "output", "elementType": "$outVec" }
|
| 388 |
-
],
|
| 389 |
-
"dispatch": { "x": 1, "y": "attrs.num_heads", "z": "tokenCount" }
|
| 390 |
-
}
|
| 391 |
-
]
|
| 392 |
-
},
|
| 393 |
-
{
|
| 394 |
-
"id": "packed_derived",
|
| 395 |
-
"when": ["pagedAttnStorageFits", "packedKv", "not present.slotMappingT"],
|
| 396 |
-
"requires": { "features": ["shader-f16"] },
|
| 397 |
-
"passes": [
|
| 398 |
-
{
|
| 399 |
-
"id": "scatter",
|
| 400 |
-
"name": "PagedAttention.ScatterKV",
|
| 401 |
-
"shader": "paged-scatter-kv.wgsl.jinja",
|
| 402 |
-
"bindings": ["query", "key_cache", "value_cache", "cumulative_sequence_length", "past_seqlens", "block_table", "params"],
|
| 403 |
-
"dispatch": {
|
| 404 |
-
"x": "min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 405 |
-
"y": "ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 406 |
-
"z": 1
|
| 407 |
-
}
|
| 408 |
-
},
|
| 409 |
-
{
|
| 410 |
-
"id": "main",
|
| 411 |
-
"name": "PagedAttention.Attend",
|
| 412 |
-
"shader": "paged-attention.wgsl.jinja",
|
| 413 |
-
"bindings": [
|
| 414 |
-
"query",
|
| 415 |
-
"key_cache_main",
|
| 416 |
-
"value_cache_main",
|
| 417 |
-
"cumulative_sequence_length",
|
| 418 |
-
"past_seqlens",
|
| 419 |
-
"block_table",
|
| 420 |
-
{ "arg": "outputT", "name": "output", "elementType": "$aScalar" },
|
| 421 |
-
"params_main"
|
| 422 |
-
],
|
| 423 |
-
"dispatch": { "x": "tokenCount", "y": "attrs.kv_num_heads" }
|
| 424 |
-
}
|
| 425 |
-
]
|
| 426 |
-
},
|
| 427 |
-
{
|
| 428 |
-
"id": "packed_slot_splitk",
|
| 429 |
-
"priority": 10,
|
| 430 |
-
"when": ["pagedSplitFits", "pagedSplitStorageFits", "packedKv", "present.slotMappingT"],
|
| 431 |
-
"requires": { "features": ["shader-f16"] },
|
| 432 |
-
"derive": { "attnWorkgroup": "pagedSplitWg" },
|
| 433 |
-
"intermediates": [
|
| 434 |
-
{ "id": "partialOut", "dtype": "float32", "shape": "[tokenCount * attrs.num_heads * numSplits * headSize]" },
|
| 435 |
-
{ "id": "partialStats", "dtype": "float32", "shape": "[2 * tokenCount * attrs.num_heads * numSplits]" }
|
| 436 |
-
],
|
| 437 |
-
"passes": [
|
| 438 |
-
{
|
| 439 |
-
"id": "scatter",
|
| 440 |
-
"name": "PagedAttention.ScatterKV",
|
| 441 |
-
"shader": "paged-scatter-kv.wgsl.jinja",
|
| 442 |
-
"bindings": ["query", "key_cache", "value_cache", "slot_mapping", "params_scatter"],
|
| 443 |
-
"dispatch": {
|
| 444 |
-
"x": "min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 445 |
-
"y": "ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 446 |
-
"z": 1
|
| 447 |
-
}
|
| 448 |
-
},
|
| 449 |
-
{
|
| 450 |
-
"id": "split_attention",
|
| 451 |
-
"name": "PagedAttention.AttendSplitK",
|
| 452 |
-
"shader": "paged-attention.wgsl.jinja",
|
| 453 |
-
"derive": { "splitK": true },
|
| 454 |
-
"bindings": [
|
| 455 |
-
"query",
|
| 456 |
-
"key_cache_main",
|
| 457 |
-
"value_cache_main",
|
| 458 |
-
"cumulative_sequence_length",
|
| 459 |
-
"past_seqlens",
|
| 460 |
-
"block_table",
|
| 461 |
-
{ "scratch": "partialOut", "name": "partial_out", "elementType": "vec4<f32>" },
|
| 462 |
-
{ "scratch": "partialStats", "name": "partial_stats", "elementType": "vec2<f32>" },
|
| 463 |
-
"params_main"
|
| 464 |
-
],
|
| 465 |
-
"dispatch": { "x": "tokenCount", "y": "attrs.kv_num_heads", "z": "numSplits" }
|
| 466 |
-
},
|
| 467 |
-
{
|
| 468 |
-
"id": "merge",
|
| 469 |
-
"name": "PagedAttention.AttendSplitKMerge",
|
| 470 |
-
"shader": "attn-flash-decode-splitk-merge.wgsl.jinja",
|
| 471 |
-
"derive": { "layout": "\"bsh\"" },
|
| 472 |
-
"bindings": [
|
| 473 |
-
{
|
| 474 |
-
"scratch": "partialOut",
|
| 475 |
-
"name": "partial_out",
|
| 476 |
-
"buffer": "read-only-storage",
|
| 477 |
-
"elementType": "vec4<f32>"
|
| 478 |
-
},
|
| 479 |
-
{
|
| 480 |
-
"scratch": "partialStats",
|
| 481 |
-
"name": "partial_stats",
|
| 482 |
-
"buffer": "read-only-storage",
|
| 483 |
-
"elementType": "vec2<f32>"
|
| 484 |
-
},
|
| 485 |
-
{ "arg": "outputT", "name": "output", "elementType": "$outVec" }
|
| 486 |
-
],
|
| 487 |
-
"dispatch": { "x": 1, "y": "attrs.num_heads", "z": "tokenCount" }
|
| 488 |
-
}
|
| 489 |
-
]
|
| 490 |
-
},
|
| 491 |
-
{
|
| 492 |
-
"id": "packed_slot",
|
| 493 |
-
"when": ["pagedAttnStorageFits", "packedKv", "present.slotMappingT"],
|
| 494 |
-
"requires": { "features": ["shader-f16"] },
|
| 495 |
-
"passes": [
|
| 496 |
-
{
|
| 497 |
-
"id": "scatter",
|
| 498 |
-
"name": "PagedAttention.ScatterKV",
|
| 499 |
-
"shader": "paged-scatter-kv.wgsl.jinja",
|
| 500 |
-
"bindings": ["query", "key_cache", "value_cache", "slot_mapping", "params_scatter"],
|
| 501 |
-
"dispatch": {
|
| 502 |
-
"x": "min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 503 |
-
"y": "ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)",
|
| 504 |
-
"z": 1
|
| 505 |
-
}
|
| 506 |
-
},
|
| 507 |
-
{
|
| 508 |
-
"id": "main",
|
| 509 |
-
"name": "PagedAttention.Attend",
|
| 510 |
-
"shader": "paged-attention.wgsl.jinja",
|
| 511 |
-
"bindings": [
|
| 512 |
-
"query",
|
| 513 |
-
"key_cache_main",
|
| 514 |
-
"value_cache_main",
|
| 515 |
-
"cumulative_sequence_length",
|
| 516 |
-
"past_seqlens",
|
| 517 |
-
"block_table",
|
| 518 |
-
{ "arg": "outputT", "name": "output", "elementType": "$aScalar" },
|
| 519 |
-
"params_main"
|
| 520 |
-
],
|
| 521 |
-
"dispatch": { "x": "tokenCount", "y": "attrs.kv_num_heads" }
|
| 522 |
-
}
|
| 523 |
-
]
|
| 524 |
-
}
|
| 525 |
-
]
|
| 526 |
-
}
|
|
|
|
| 1 |
+
{"domain":"com.microsoft","name":"PagedAttention","sinceVersion":1,"inputs":{"queryT":{"onnx":"query","dtype":"T","rank":2},"keyT":{"onnx":"key","dtype":"T","rank":2,"optional":true},"valueT":{"onnx":"value","dtype":"T","rank":2,"optional":true},"keyCacheT":{"onnx":"key_cache","dtype":"T","rank":4},"valueCacheT":{"onnx":"value_cache","dtype":"T","rank":4},"cumulativeSequenceLengthT":{"onnx":"cumulative_sequence_length","dtype":"S","rank":1,"storage":"int32"},"pastSeqlensT":{"onnx":"past_seqlens","dtype":"S","rank":1,"storage":"int32"},"blockTableT":{"onnx":"block_table","dtype":"S","rank":2,"storage":"int32"},"cosCacheT":{"onnx":"cos_cache","dtype":"T","rank":2,"optional":true},"sinCacheT":{"onnx":"sin_cache","dtype":"T","rank":2,"optional":true},"slotMappingT":{"onnx":"slot_mapping","dtype":"S","rank":1,"optional":true,"storage":"int32"},"headSinkT":{"onnx":"head_sink","dtype":"T","rank":1,"optional":true},"qNormT":{"dtype":"T","rank":1,"optional":true,"onnx":"q_norm_weight"},"kNormT":{"dtype":"T","rank":1,"optional":true,"onnx":"k_norm_weight"}},"outputs":{"outputT":{"onnx":"output","dtype":"T","rank":2,"shape":"[dim(shapes.queryT, 0), attrs.num_heads * headSize]"},"keyCacheT":{"onnx":"key_cache","dtype":"T","rank":4,"optional":true,"shape":"shapes.keyCacheT"},"valueCacheT":{"onnx":"value_cache","dtype":"T","rank":4,"optional":true,"shape":"shapes.valueCacheT"}},"attributes":{"is_causal":{"default":1},"kv_num_heads":{},"num_heads":{},"scale":{},"local_window_size":{"default":-1},"do_rotary":{"default":0},"rotary_interleaved":{"default":0},"qk_norm_epsilon":{"default":0.000001}},"attributeConstraints":{"is_causal":{"values":[0,1]},"kv_num_heads":{"required":true},"num_heads":{"required":true}},"typeConstraints":{"T":["float16"],"S":["int32"]},"tunables":{"WORKGROUP_SIZE":{"default":64},"SCATTER_WORKGROUP_SIZE":{"default":64},"MAX_SPLITS":{"default":16},"SPLIT_MIN_KEYS":{"default":128},"SPLIT_TARGET_WORKGROUPS":{"default":1024},"NORM_WORKGROUP_SIZE":{"default":128}},"derive":{"tokenCount":"dim(shapes.queryT, 0)","blockSize":"dim(shapes.keyCacheT, 1)","headSize":"dim(shapes.keyCacheT, 3)","maxBlocks":"dim(shapes.blockTableT, 1)","batchSize":"dim(shapes.cumulativeSequenceLengthT, 0) - 1","qHidden":"attrs.num_heads * headSize","kvHidden":"attrs.kv_num_heads * headSize","qPerKv":"attrs.num_heads / max(1, attrs.kv_num_heads)","headVec":"headSize / 4","cacheVec4Ok":"headSize % 4 == 0","packedStride":"qHidden + 2 * kvHidden","cacheShapeOk":"ranks.keyCacheT == 4 and ranks.valueCacheT == 4 and sameShape(shapes.valueCacheT, shapes.keyCacheT) and dim(shapes.keyCacheT, 2) == attrs.kv_num_heads and blockSize > 0 and headSize > 0 and tensorDtypes.keyCacheT == tensorDtypes.queryT and tensorDtypes.valueCacheT == tensorDtypes.queryT","headLayoutOk":"attrs.num_heads > 0 and attrs.kv_num_heads > 0 and attrs.num_heads % attrs.kv_num_heads == 0","scheduleShapeOk":"ranks.cumulativeSequenceLengthT == 1 and ranks.pastSeqlensT == 1 and ranks.blockTableT == 2 and batchSize >= 1 and dim(shapes.pastSeqlensT, 0) == batchSize and dim(shapes.blockTableT, 0) == batchSize and maxBlocks >= 1","ioShapeOk":"ranks.queryT == 2 and ranks.outputT == 2 and dim(shapes.outputT, 0) == tokenCount and dim(shapes.outputT, 1) == qHidden and tensorDtypes.outputT == tensorDtypes.queryT and f16Ok(tensorDtypes.queryT)","separateKv":"present.keyT and present.valueT and ranks.keyT == 2 and ranks.valueT == 2 and dim(shapes.keyT, 0) == tokenCount and dim(shapes.valueT, 0) == tokenCount and dim(shapes.keyT, 1) == kvHidden and dim(shapes.valueT, 1) == kvHidden and tensorDtypes.keyT == tensorDtypes.queryT and tensorDtypes.valueT == tensorDtypes.queryT and dim(shapes.queryT, 1) == qHidden","packedKv":"not present.keyT and not present.valueT and dim(shapes.queryT, 1) == packedStride","slotShapeOk":"dim(shapes.slotMappingT, 0) == tokenCount and ranks.slotMappingT == 1 if present.slotMappingT else true","pagedContractOk":"cacheShapeOk and headLayoutOk and scheduleShapeOk and ioShapeOk and slotShapeOk","dispatchFits":"tokenCount <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and attrs.num_heads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and tunables.WORKGROUP_SIZE <= device.limits.maxComputeInvocationsPerWorkgroup and tunables.SCATTER_WORKGROUP_SIZE <= device.limits.maxComputeInvocationsPerWorkgroup","pagedBaseWorkgroups":"tokenCount * attrs.kv_num_heads","pagedAttnQueryFloats":"2 * headSize * qPerKv","pagedAttnLaneFloats":"3 * qPerKv + 1","pagedAttnWgBudget":"floor(device.limits.maxComputeWorkgroupStorageSize / 4 - pagedAttnQueryFloats) / pagedAttnLaneFloats","pagedAttnWg":"max(32, min(tunables.WORKGROUP_SIZE, pow2ceil(max(1, floor(pagedAttnWgBudget)) + 1) / 2))","pagedAttnStorageBytes":"(pagedAttnQueryFloats + pagedAttnLaneFloats * pagedAttnWg) * 4","pagedAttnStorageFits":"pagedAttnStorageBytes <= device.limits.maxComputeWorkgroupStorageSize and pagedAttnWg <= device.limits.maxComputeInvocationsPerWorkgroup and pagedAttnWg <= device.limits.maxComputeWorkgroupSizeX","pagedKeyCeiling":"maxBlocks * blockSize","pagedSplitWg":"min(256, max(32, pow2ceil(headVec)))","pagedSplitStorageBytes":"(2 * headSize * qPerKv + (3 * qPerKv + 1) * pagedSplitWg) * 4","pagedSplitStorageFits":"pagedSplitStorageBytes <= device.limits.maxComputeWorkgroupStorageSize","pagedSplitCap":"max(1, min(tunables.MAX_SPLITS, floor(pagedKeyCeiling / max(1, 2 * pagedSplitWg)))) if 2 * pagedSplitWg < tunables.SPLIT_MIN_KEYS and pagedKeyCeiling >= 2 * tunables.SPLIT_MIN_KEYS and device.features.has(\"subgroups\") and device.adapterInfo.subgroupMinSize == 16 and device.adapterInfo.subgroupMaxSize == 32 else max(1, min(tunables.MAX_SPLITS, floor(pagedKeyCeiling / tunables.SPLIT_MIN_KEYS)))","numSplits":"max(1, min(pagedSplitCap, ceilDiv(tunables.SPLIT_TARGET_WORKGROUPS, max(1, pagedBaseWorkgroups))))","pagedHasSink":"present.headSinkT","pagedSplitScratchBytes":"tokenCount * attrs.num_heads * numSplits * (headSize + (4 if pagedHasSink else 0)) * 4","pagedSplitStatsBytes":"2 * tokenCount * attrs.num_heads * numSplits * 4","pagedSplitFits":"numSplits >= 2 and cacheVec4Ok and headVec >= 1 and pagedSplitScratchBytes <= device.limits.maxStorageBufferBindingSize and pagedSplitScratchBytes <= device.limits.maxBufferSize and pagedSplitStatsBytes <= device.limits.maxStorageBufferBindingSize and pagedSplitStatsBytes <= device.limits.maxBufferSize and numSplits <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and headVec <= device.limits.maxComputeInvocationsPerWorkgroup and headVec <= device.limits.maxComputeWorkgroupSizeX and pagedSplitWg <= device.limits.maxComputeInvocationsPerWorkgroup and pagedSplitWg <= device.limits.maxComputeWorkgroupSizeX","aScalar":"dtypes.T","scalar":"dtypes.T","numHeads":"attrs.num_heads","kvNumHeads":"attrs.kv_num_heads","packedQkv":"not present.keyT","hasSlotMapping":"present.slotMappingT","attnWorkgroup":"pagedAttnWg","cacheVec":"(\"vec4<f16>\" if dtypes.T == \"f16\" else \"vec4<f32>\") if cacheVec4Ok else dtypes.T","headDimV4":"headVec","headDim":"headSize","qNumHeads":"attrs.num_heads","qHiddenV4":"qHidden / 4","outVec":"\"vec4<f16>\" if dtypes.T == \"f16\" else \"vec4<f32>\"","pagedBinarySequenceLookup":"batchSize >= 2 and batchSize >= 4 * log2ceil(batchSize)","addressShapeOk":"tokenCount <= 2147483647 and pagedKeyCeiling <= 2147483647 and dim(shapes.keyCacheT, 0) > 0 and numel(shapes.keyCacheT) <= 4294967295 and numel(shapes.queryT) <= 4294967295 and numel(shapes.outputT) <= 4294967295 and numel(shapes.blockTableT) <= 4294967295","pagedIsCausal":"attrs.is_causal == 1","pagedWindowOk":"attrs.local_window_size >= -9007199254740991 and attrs.local_window_size <= 9007199254740991 and attrs.local_window_size == floor(attrs.local_window_size)","pagedLocalWindow":"min(pagedKeyCeiling, max(0, attrs.local_window_size))","prefillTokens":"max(1, floor(4 / max(1, qPerKv)))","prefillWorkgroupBytes":"16 * (headSize + pagedKeyCeiling + ceilDiv(pagedKeyCeiling, 4) + pagedAttnWg)","pagedResidentPrefill":"not device.features.has(\"subgroups\") and cacheVec4Ok and headVec >= 8 and qPerKv * prefillTokens == 4 and (prefillTokens == 1 or batchSize == 1) and tokenCount >= batchSize * pagedAttnWg and pagedKeyCeiling >= pagedAttnWg and pagedKeyCeiling <= 4 * pagedAttnWg and not pagedHasSink and pagedLocalWindow == 0 and prefillWorkgroupBytes <= device.limits.maxComputeWorkgroupStorageSize","pagedDoRotary":"attrs.do_rotary == 1","pagedRotaryInterleaved":"attrs.rotary_interleaved == 1","pagedRotaryHalf":"dim(shapes.cosCacheT, 1) if pagedDoRotary and present.cosCacheT else 0","pagedRotaryRows":"dim(shapes.cosCacheT, 0) if pagedDoRotary and present.cosCacheT else 0","pagedRotaryFlagsOk":"attrs.do_rotary == floor(attrs.do_rotary) and attrs.do_rotary >= -9007199254740991 and attrs.do_rotary <= 9007199254740991 and attrs.rotary_interleaved == floor(attrs.rotary_interleaved) and attrs.rotary_interleaved >= -9007199254740991 and attrs.rotary_interleaved <= 9007199254740991","pagedRotaryShapeOk":"present.cosCacheT and present.sinCacheT and ranks.cosCacheT == 2 and ranks.sinCacheT == 2 and sameShape(shapes.cosCacheT, shapes.sinCacheT) and tensorDtypes.cosCacheT == tensorDtypes.queryT and tensorDtypes.sinCacheT == tensorDtypes.queryT and pagedRotaryRows > 0 and pagedRotaryHalf > 0 and 2 * pagedRotaryHalf <= headSize and numel(shapes.cosCacheT) <= 4294967295 if pagedDoRotary else true","pagedRotaryQBytes":"2 * tokenCount * qHidden","pagedRotaryKBytes":"2 * tokenCount * kvHidden","pagedRotaryFits":"pagedRotaryQBytes <= min(device.limits.maxBufferSize, device.limits.maxStorageBufferBindingSize) and pagedRotaryKBytes <= min(device.limits.maxBufferSize, device.limits.maxStorageBufferBindingSize) and tokenCount * (qHidden + kvHidden) <= 4294967295 if pagedDoRotary else true","pagedSinkShapeOk":"ranks.headSinkT == 1 and dim(shapes.headSinkT, 0) == numHeads and tensorDtypes.headSinkT == tensorDtypes.queryT if pagedHasSink else true","numCacheBlocks":"dim(shapes.keyCacheT, 0)","pagedPrivateOutput":"device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize == 32 and device.adapterInfo.subgroupMaxSize == 32","pagedDoNorm":"present.qNormT and present.kNormT","attentionQueryStride":"packedStride if packedQkv and not pagedDoRotary and not pagedDoNorm else qHidden","normWg":"max(1, min(128, pow2ceil(headSize), pow2ceil(max(1, min(tunables.NORM_WORKGROUP_SIZE, device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX, floor(device.limits.maxComputeWorkgroupStorageSize / 4))) + 1) / 2))","normShapeOk":"present.qNormT == present.kNormT and (not pagedDoNorm or (ranks.qNormT == 1 and ranks.kNormT == 1 and dim(shapes.qNormT, 0) == headSize and dim(shapes.kNormT, 0) == headSize and tensorDtypes.qNormT == tensorDtypes.queryT and tensorDtypes.kNormT == tensorDtypes.queryT))","normEpsilonOk":"not pagedDoNorm or (attrs.qk_norm_epsilon >= 0.000000000000000000000000000000000000000000001401298464324817 and attrs.qk_norm_epsilon <= 340282346638528860000000000000000000000)","normScratchFits":"not pagedDoNorm or (2 * tokenCount * max(qHidden, kvHidden) <= min(device.limits.maxBufferSize, device.limits.maxStorageBufferBindingSize) and tokenCount * (numHeads + kvNumHeads) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) * min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(normWg * 4, 16) * 16 <= device.limits.maxComputeWorkgroupStorageSize)","normFused":false},"when":["pagedContractOk","separateKv or packedKv","dispatchFits","addressShapeOk","pagedWindowOk","pagedRotaryFlagsOk","pagedRotaryShapeOk","pagedRotaryFits","pagedSinkShapeOk","normShapeOk","normEpsilonOk","normScratchFits"],"bindings":{"key":{"arg":"keyT","elementType":"$aScalar","when":"not packedQkv"},"value":{"arg":"valueT","elementType":"$aScalar","when":"not packedQkv"},"key_cache":{"arg":"keyCacheT","elementType":"$aScalar"},"value_cache":{"arg":"valueCacheT","elementType":"$aScalar"},"cumulative_sequence_length":{"arg":"cumulativeSequenceLengthT","elementType":"i32"},"past_seqlens":{"arg":"pastSeqlensT","elementType":"i32"},"block_table":{"arg":"blockTableT","elementType":"i32"},"scatter_key":{"arg":"keyT","name":"key","elementType":"$aScalar","when":"not packedQkv and not pagedDoRotary and not pagedDoNorm"},"scatter_key_norm":{"scratch":"normK","name":"key","buffer":"read-only-storage","elementType":"$aScalar","when":"pagedDoNorm and not pagedDoRotary"},"scatter_query":{"arg":"queryT","name":"query","elementType":"$aScalar","when":"packedQkv"},"scatter_cumulative_sequence_length":{"arg":"cumulativeSequenceLengthT","name":"cumulative_sequence_length","elementType":"i32","when":"not hasSlotMapping or pagedDoRotary"},"scatter_past_seqlens":{"arg":"pastSeqlensT","name":"past_seqlens","elementType":"i32","when":"not hasSlotMapping or pagedDoRotary"},"scatter_block_table":{"arg":"blockTableT","name":"block_table","elementType":"i32","when":"not hasSlotMapping"},"params":{"struct":[{"name":"batchSize","type":"u32","value":"batchSize"},{"name":"scatterCount","type":"u32","value":"tokenCount * attrs.kv_num_heads * headSize"}],"when":"not hasSlotMapping or pagedDoRotary"},"slot_mapping":{"arg":"slotMappingT","elementType":"i32","when":"hasSlotMapping"},"params_scatter":{"name":"params","struct":[{"name":"scatterCount","type":"u32","value":"tokenCount * attrs.kv_num_heads * headSize"}],"when":"hasSlotMapping and not pagedDoRotary"},"query":{"arg":"queryT","elementType":"$aScalar"},"attention_query":{"arg":"queryT","name":"query","elementType":"$aScalar","when":"not pagedDoRotary and not pagedDoNorm"},"attention_query_norm":{"scratch":"normQ","name":"query","buffer":"read-only-storage","elementType":"$aScalar","when":"pagedDoNorm and not pagedDoRotary"},"key_cache_main":{"arg":"keyCacheT","name":"key_cache","buffer":"read-only-storage","elementType":"$cacheVec"},"value_cache_main":{"arg":"valueCacheT","name":"value_cache","buffer":"read-only-storage","elementType":"$cacheVec"},"params_main":{"name":"params","struct":[{"name":"batchSize","type":"u32","value":"batchSize"},{"name":"scale","type":"f32","value":"attrs.scale if has(attrs, \"scale\") else 0"}]},"cos_cache":{"arg":"cosCacheT","elementType":"$aScalar","when":"pagedDoRotary"},"sin_cache":{"arg":"sinCacheT","elementType":"$aScalar","when":"pagedDoRotary"},"head_sink":{"arg":"headSinkT","elementType":"$aScalar","when":"pagedHasSink"},"query_rotary":{"scratch":"rotaryQ","name":"query","buffer":"read-only-storage","elementType":"$aScalar","when":"pagedDoRotary"},"key_rotary":{"scratch":"rotaryK","name":"key","buffer":"read-only-storage","elementType":"$aScalar","when":"pagedDoRotary"},"params_rotary":{"name":"params","struct":[{"name":"batchSize","type":"u32","value":"batchSize"},{"name":"rotaryCount","type":"u32","value":"tokenCount * (qHidden + kvHidden)"}]},"query_norm":{"scratch":"normQ","name":"query","buffer":"read-only-storage","elementType":"$aScalar"},"key_norm":{"scratch":"normK","name":"key","buffer":"read-only-storage","elementType":"$aScalar"},"q_norm_weight":{"arg":"qNormT","elementType":"$aScalar"},"k_norm_weight":{"arg":"kNormT","elementType":"$aScalar"},"params_norm":{"name":"norm_params","struct":[{"name":"epsilon","type":"f32","value":"attrs.qk_norm_epsilon"}]},"q_norm_output":{"scratch":"normQ","name":"q_normalized","elementType":"$aScalar","when":"not pagedDoRotary"},"k_norm_output":{"scratch":"normK","name":"k_normalized","elementType":"$aScalar","when":"not pagedDoRotary"},"q_rotary_output":{"scratch":"rotaryQ","name":"q_rotary","elementType":"$aScalar"},"k_rotary_output":{"scratch":"rotaryK","name":"k_rotary","elementType":"$aScalar"},"q_norm_input":{"arg":"queryT","name":"x","elementType":"$aScalar"},"q_norm_weight_input":{"arg":"qNormT","name":"gamma","elementType":"$aScalar"},"q_norm_result":{"scratch":"normQ","name":"normalized","elementType":"$aScalar"},"k_norm_input":{"arg":"keyT","name":"x","elementType":"$aScalar","when":"not packedQkv"},"k_norm_packed_input":{"arg":"queryT","name":"x","elementType":"$aScalar","when":"packedQkv"},"k_norm_weight_input":{"arg":"kNormT","name":"gamma","elementType":"$aScalar"},"k_norm_result":{"scratch":"normK","name":"normalized","elementType":"$aScalar"},"q_norm_rotary_output":{"scratch":"rotaryQ","name":"q_normalized","elementType":"$aScalar","when":"pagedDoRotary"},"k_norm_rotary_output":{"scratch":"rotaryK","name":"k_normalized","elementType":"$aScalar","when":"pagedDoRotary"}},"variants":[{"id":"paged_splitk_subgroups","priority":11,"when":["pagedSplitFits","pagedSplitStorageFits","device.wgslLanguageFeatures.has(\"subgroup_id\")","not pagedDoRotary and not pagedDoNorm"],"requires":{"features":["shader-f16","subgroups"]},"derive":{"attnWorkgroup":"pagedSplitWg","pagedSubgroupFold":true},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"partialOut","dtype":"float32","shape":"[tokenCount * attrs.num_heads * numSplits * (headSize + (4 if pagedHasSink else 0))]"},{"id":"partialStats","dtype":"float32","shape":"[2 * tokenCount * attrs.num_heads * numSplits]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}],"passes":[{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"split_attention","name":"PagedAttention.AttendSplitK","shader":"paged-attention.wgsl.jinja","derive":{"splitK":true},"bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"scratch":"partialOut","name":"partial_out","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","elementType":"vec2<f32>","when":"not pagedHasSink"},"params_main"],"dispatch":{"x":"tokenCount","y":"attrs.kv_num_heads","z":"numSplits"}},{"id":"merge","name":"PagedAttention.AttendSplitKMerge","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bsh\"","inlinePartialStats":"pagedHasSink"},"bindings":[{"scratch":"partialOut","name":"partial_out","buffer":"read-only-storage","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","buffer":"read-only-storage","elementType":"vec2<f32>","when":"not pagedHasSink"},{"arg":"outputT","name":"output","elementType":"$outVec"}],"dispatch":{"x":1,"y":"attrs.num_heads","z":"tokenCount"}}]},{"id":"paged_subgroups","when":["pagedAttnStorageFits","device.wgslLanguageFeatures.has(\"subgroup_id\")","not pagedDoRotary and not pagedDoNorm"],"requires":{"features":["shader-f16","subgroups"]},"passes":[{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"main","name":"PagedAttention.Attend","shader":"paged-attention.wgsl.jinja","bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"arg":"outputT","name":"output","elementType":"$aScalar"},"params_main"],"dispatch":{"x":"ceilDiv(tokenCount, prefillTokens) if pagedResidentPrefill else tokenCount","y":"attrs.kv_num_heads"}}],"priority":1,"derive":{"pagedSubgroupFold":true},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}]},{"id":"paged_splitk","priority":10,"when":["pagedSplitFits","pagedSplitStorageFits","true","not pagedDoRotary and not pagedDoNorm"],"requires":{"features":["shader-f16"]},"derive":{"attnWorkgroup":"pagedSplitWg","pagedSubgroupFold":false},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"partialOut","dtype":"float32","shape":"[tokenCount * attrs.num_heads * numSplits * (headSize + (4 if pagedHasSink else 0))]"},{"id":"partialStats","dtype":"float32","shape":"[2 * tokenCount * attrs.num_heads * numSplits]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}],"passes":[{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"split_attention","name":"PagedAttention.AttendSplitK","shader":"paged-attention.wgsl.jinja","derive":{"splitK":true},"bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"scratch":"partialOut","name":"partial_out","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","elementType":"vec2<f32>","when":"not pagedHasSink"},"params_main"],"dispatch":{"x":"tokenCount","y":"attrs.kv_num_heads","z":"numSplits"}},{"id":"merge","name":"PagedAttention.AttendSplitKMerge","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bsh\"","inlinePartialStats":"pagedHasSink"},"bindings":[{"scratch":"partialOut","name":"partial_out","buffer":"read-only-storage","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","buffer":"read-only-storage","elementType":"vec2<f32>","when":"not pagedHasSink"},{"arg":"outputT","name":"output","elementType":"$outVec"}],"dispatch":{"x":1,"y":"attrs.num_heads","z":"tokenCount"}}]},{"id":"paged","when":["pagedAttnStorageFits","true","not pagedDoRotary and not pagedDoNorm"],"requires":{"features":["shader-f16"]},"passes":[{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"main","name":"PagedAttention.Attend","shader":"paged-attention.wgsl.jinja","bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"arg":"outputT","name":"output","elementType":"$aScalar"},"params_main"],"dispatch":{"x":"ceilDiv(tokenCount, prefillTokens) if pagedResidentPrefill else tokenCount","y":"attrs.kv_num_heads"}}],"priority":0,"derive":{"pagedSubgroupFold":false},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}]},{"id":"paged_qknorm_fused_splitk_subgroups","priority":11,"when":["pagedSplitFits","pagedSplitStorageFits","device.wgslLanguageFeatures.has(\"subgroup_id\")","pagedDoNorm and (not pagedDoRotary or device.limits.maxStorageBuffersPerShaderStage >= (9 if packedQkv else 10))"],"requires":{"features":["shader-f16","subgroups"]},"derive":{"attnWorkgroup":"pagedSplitWg","pagedSubgroupFold":true},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"partialOut","dtype":"float32","shape":"[tokenCount * attrs.num_heads * numSplits * (headSize + (4 if pagedHasSink else 0))]"},{"id":"partialStats","dtype":"float32","shape":"[2 * tokenCount * attrs.num_heads * numSplits]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}],"passes":[{"id":"norm_qk","name":"PagedAttention.NormalizeQK","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":true},"bindings":["query","key","q_norm_weight","k_norm_weight","cos_cache","sin_cache",{"arg":"cumulativeSequenceLengthT","name":"cumulative_sequence_length","elementType":"i32","when":"pagedDoRotary"},{"arg":"pastSeqlensT","name":"past_seqlens","elementType":"i32","when":"pagedDoRotary"},"q_norm_output","q_norm_rotary_output","k_norm_output","k_norm_rotary_output","params_norm"],"dispatch":{"x":"min(tokenCount * (numHeads + kvNumHeads), 65535)","y":"ceilDiv(tokenCount * (numHeads + kvNumHeads), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"split_attention","name":"PagedAttention.AttendSplitK","shader":"paged-attention.wgsl.jinja","derive":{"splitK":true},"bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"scratch":"partialOut","name":"partial_out","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","elementType":"vec2<f32>","when":"not pagedHasSink"},"params_main"],"dispatch":{"x":"tokenCount","y":"attrs.kv_num_heads","z":"numSplits"}},{"id":"merge","name":"PagedAttention.AttendSplitKMerge","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bsh\"","inlinePartialStats":"pagedHasSink"},"bindings":[{"scratch":"partialOut","name":"partial_out","buffer":"read-only-storage","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","buffer":"read-only-storage","elementType":"vec2<f32>","when":"not pagedHasSink"},{"arg":"outputT","name":"output","elementType":"$outVec"}],"dispatch":{"x":1,"y":"attrs.num_heads","z":"tokenCount"}}]},{"id":"paged_qknorm_fused_subgroups","when":["pagedAttnStorageFits","device.wgslLanguageFeatures.has(\"subgroup_id\")","pagedDoNorm and (not pagedDoRotary or device.limits.maxStorageBuffersPerShaderStage >= (9 if packedQkv else 10))"],"requires":{"features":["shader-f16","subgroups"]},"passes":[{"id":"norm_qk","name":"PagedAttention.NormalizeQK","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":true},"bindings":["query","key","q_norm_weight","k_norm_weight","cos_cache","sin_cache",{"arg":"cumulativeSequenceLengthT","name":"cumulative_sequence_length","elementType":"i32","when":"pagedDoRotary"},{"arg":"pastSeqlensT","name":"past_seqlens","elementType":"i32","when":"pagedDoRotary"},"q_norm_output","q_norm_rotary_output","k_norm_output","k_norm_rotary_output","params_norm"],"dispatch":{"x":"min(tokenCount * (numHeads + kvNumHeads), 65535)","y":"ceilDiv(tokenCount * (numHeads + kvNumHeads), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"main","name":"PagedAttention.Attend","shader":"paged-attention.wgsl.jinja","bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"arg":"outputT","name":"output","elementType":"$aScalar"},"params_main"],"dispatch":{"x":"ceilDiv(tokenCount, prefillTokens) if pagedResidentPrefill else tokenCount","y":"attrs.kv_num_heads"}}],"priority":1,"derive":{"pagedSubgroupFold":true},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}]},{"id":"paged_qknorm_fused_splitk","priority":10,"when":["pagedSplitFits","pagedSplitStorageFits","true","pagedDoNorm and (not pagedDoRotary or device.limits.maxStorageBuffersPerShaderStage >= (9 if packedQkv else 10))"],"requires":{"features":["shader-f16"]},"derive":{"attnWorkgroup":"pagedSplitWg","pagedSubgroupFold":false},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"partialOut","dtype":"float32","shape":"[tokenCount * attrs.num_heads * numSplits * (headSize + (4 if pagedHasSink else 0))]"},{"id":"partialStats","dtype":"float32","shape":"[2 * tokenCount * attrs.num_heads * numSplits]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}],"passes":[{"id":"norm_qk","name":"PagedAttention.NormalizeQK","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":true},"bindings":["query","key","q_norm_weight","k_norm_weight","cos_cache","sin_cache",{"arg":"cumulativeSequenceLengthT","name":"cumulative_sequence_length","elementType":"i32","when":"pagedDoRotary"},{"arg":"pastSeqlensT","name":"past_seqlens","elementType":"i32","when":"pagedDoRotary"},"q_norm_output","q_norm_rotary_output","k_norm_output","k_norm_rotary_output","params_norm"],"dispatch":{"x":"min(tokenCount * (numHeads + kvNumHeads), 65535)","y":"ceilDiv(tokenCount * (numHeads + kvNumHeads), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"split_attention","name":"PagedAttention.AttendSplitK","shader":"paged-attention.wgsl.jinja","derive":{"splitK":true},"bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"scratch":"partialOut","name":"partial_out","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","elementType":"vec2<f32>","when":"not pagedHasSink"},"params_main"],"dispatch":{"x":"tokenCount","y":"attrs.kv_num_heads","z":"numSplits"}},{"id":"merge","name":"PagedAttention.AttendSplitKMerge","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bsh\"","inlinePartialStats":"pagedHasSink"},"bindings":[{"scratch":"partialOut","name":"partial_out","buffer":"read-only-storage","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","buffer":"read-only-storage","elementType":"vec2<f32>","when":"not pagedHasSink"},{"arg":"outputT","name":"output","elementType":"$outVec"}],"dispatch":{"x":1,"y":"attrs.num_heads","z":"tokenCount"}}]},{"id":"paged_qknorm_fused","when":["pagedAttnStorageFits","true","pagedDoNorm and (not pagedDoRotary or device.limits.maxStorageBuffersPerShaderStage >= (9 if packedQkv else 10))"],"requires":{"features":["shader-f16"]},"passes":[{"id":"norm_qk","name":"PagedAttention.NormalizeQK","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":true},"bindings":["query","key","q_norm_weight","k_norm_weight","cos_cache","sin_cache",{"arg":"cumulativeSequenceLengthT","name":"cumulative_sequence_length","elementType":"i32","when":"pagedDoRotary"},{"arg":"pastSeqlensT","name":"past_seqlens","elementType":"i32","when":"pagedDoRotary"},"q_norm_output","q_norm_rotary_output","k_norm_output","k_norm_rotary_output","params_norm"],"dispatch":{"x":"min(tokenCount * (numHeads + kvNumHeads), 65535)","y":"ceilDiv(tokenCount * (numHeads + kvNumHeads), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"main","name":"PagedAttention.Attend","shader":"paged-attention.wgsl.jinja","bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"arg":"outputT","name":"output","elementType":"$aScalar"},"params_main"],"dispatch":{"x":"ceilDiv(tokenCount, prefillTokens) if pagedResidentPrefill else tokenCount","y":"attrs.kv_num_heads"}}],"priority":0,"derive":{"pagedSubgroupFold":false},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}]},{"id":"paged_rotary_splitk_subgroups","priority":11,"when":["pagedSplitFits","pagedSplitStorageFits","device.wgslLanguageFeatures.has(\"subgroup_id\")","pagedDoRotary and not pagedDoNorm"],"requires":{"features":["shader-f16","subgroups"]},"derive":{"attnWorkgroup":"pagedSplitWg","pagedSubgroupFold":true},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"partialOut","dtype":"float32","shape":"[tokenCount * attrs.num_heads * numSplits * (headSize + (4 if pagedHasSink else 0))]"},{"id":"partialStats","dtype":"float32","shape":"[2 * tokenCount * attrs.num_heads * numSplits]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}],"passes":[{"id":"rotary","name":"PagedAttention.RotaryQK","shader":"paged-rotary-qk.wgsl.jinja","bindings":["query","key","cos_cache","sin_cache","cumulative_sequence_length","past_seqlens","q_rotary_output","k_rotary_output","params_rotary"],"dispatch":{"x":"min(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"split_attention","name":"PagedAttention.AttendSplitK","shader":"paged-attention.wgsl.jinja","derive":{"splitK":true},"bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"scratch":"partialOut","name":"partial_out","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","elementType":"vec2<f32>","when":"not pagedHasSink"},"params_main"],"dispatch":{"x":"tokenCount","y":"attrs.kv_num_heads","z":"numSplits"}},{"id":"merge","name":"PagedAttention.AttendSplitKMerge","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bsh\"","inlinePartialStats":"pagedHasSink"},"bindings":[{"scratch":"partialOut","name":"partial_out","buffer":"read-only-storage","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","buffer":"read-only-storage","elementType":"vec2<f32>","when":"not pagedHasSink"},{"arg":"outputT","name":"output","elementType":"$outVec"}],"dispatch":{"x":1,"y":"attrs.num_heads","z":"tokenCount"}}]},{"id":"paged_rotary_subgroups","when":["pagedAttnStorageFits","device.wgslLanguageFeatures.has(\"subgroup_id\")","pagedDoRotary and not pagedDoNorm"],"requires":{"features":["shader-f16","subgroups"]},"passes":[{"id":"rotary","name":"PagedAttention.RotaryQK","shader":"paged-rotary-qk.wgsl.jinja","bindings":["query","key","cos_cache","sin_cache","cumulative_sequence_length","past_seqlens","q_rotary_output","k_rotary_output","params_rotary"],"dispatch":{"x":"min(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"main","name":"PagedAttention.Attend","shader":"paged-attention.wgsl.jinja","bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"arg":"outputT","name":"output","elementType":"$aScalar"},"params_main"],"dispatch":{"x":"ceilDiv(tokenCount, prefillTokens) if pagedResidentPrefill else tokenCount","y":"attrs.kv_num_heads"}}],"priority":1,"derive":{"pagedSubgroupFold":true},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}]},{"id":"paged_rotary_splitk","priority":10,"when":["pagedSplitFits","pagedSplitStorageFits","true","pagedDoRotary and not pagedDoNorm"],"requires":{"features":["shader-f16"]},"derive":{"attnWorkgroup":"pagedSplitWg","pagedSubgroupFold":false},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"partialOut","dtype":"float32","shape":"[tokenCount * attrs.num_heads * numSplits * (headSize + (4 if pagedHasSink else 0))]"},{"id":"partialStats","dtype":"float32","shape":"[2 * tokenCount * attrs.num_heads * numSplits]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}],"passes":[{"id":"rotary","name":"PagedAttention.RotaryQK","shader":"paged-rotary-qk.wgsl.jinja","bindings":["query","key","cos_cache","sin_cache","cumulative_sequence_length","past_seqlens","q_rotary_output","k_rotary_output","params_rotary"],"dispatch":{"x":"min(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"split_attention","name":"PagedAttention.AttendSplitK","shader":"paged-attention.wgsl.jinja","derive":{"splitK":true},"bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"scratch":"partialOut","name":"partial_out","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","elementType":"vec2<f32>","when":"not pagedHasSink"},"params_main"],"dispatch":{"x":"tokenCount","y":"attrs.kv_num_heads","z":"numSplits"}},{"id":"merge","name":"PagedAttention.AttendSplitKMerge","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bsh\"","inlinePartialStats":"pagedHasSink"},"bindings":[{"scratch":"partialOut","name":"partial_out","buffer":"read-only-storage","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","buffer":"read-only-storage","elementType":"vec2<f32>","when":"not pagedHasSink"},{"arg":"outputT","name":"output","elementType":"$outVec"}],"dispatch":{"x":1,"y":"attrs.num_heads","z":"tokenCount"}}]},{"id":"paged_rotary","when":["pagedAttnStorageFits","true","pagedDoRotary and not pagedDoNorm"],"requires":{"features":["shader-f16"]},"passes":[{"id":"rotary","name":"PagedAttention.RotaryQK","shader":"paged-rotary-qk.wgsl.jinja","bindings":["query","key","cos_cache","sin_cache","cumulative_sequence_length","past_seqlens","q_rotary_output","k_rotary_output","params_rotary"],"dispatch":{"x":"min(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"main","name":"PagedAttention.Attend","shader":"paged-attention.wgsl.jinja","bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"arg":"outputT","name":"output","elementType":"$aScalar"},"params_main"],"dispatch":{"x":"ceilDiv(tokenCount, prefillTokens) if pagedResidentPrefill else tokenCount","y":"attrs.kv_num_heads"}}],"priority":0,"derive":{"pagedSubgroupFold":false},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}]},{"id":"paged_rotary_qknorm_splitk_subgroups","priority":11,"when":["pagedSplitFits","pagedSplitStorageFits","device.wgslLanguageFeatures.has(\"subgroup_id\")","pagedDoRotary and pagedDoNorm and device.limits.maxStorageBuffersPerShaderStage < (9 if packedQkv else 10)"],"requires":{"features":["shader-f16","subgroups"]},"derive":{"attnWorkgroup":"pagedSplitWg","pagedSubgroupFold":true},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"partialOut","dtype":"float32","shape":"[tokenCount * attrs.num_heads * numSplits * (headSize + (4 if pagedHasSink else 0))]"},{"id":"partialStats","dtype":"float32","shape":"[2 * tokenCount * attrs.num_heads * numSplits]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}],"passes":[{"id":"norm_q","name":"PagedAttention.NormalizeQuery","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":false,"normIsQuery":true},"bindings":["q_norm_input","q_norm_weight_input","q_norm_result","params_norm"],"dispatch":{"x":"min(tokenCount * numHeads, 65535)","y":"ceilDiv(tokenCount * numHeads, 65535)","z":1}},{"id":"norm_k","name":"PagedAttention.NormalizeKey","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":false,"normIsQuery":false},"bindings":["k_norm_packed_input","k_norm_input","k_norm_weight_input","k_norm_result","params_norm"],"dispatch":{"x":"min(tokenCount * kvNumHeads, 65535)","y":"ceilDiv(tokenCount * kvNumHeads, 65535)","z":1}},{"id":"rotary","name":"PagedAttention.RotaryQK","shader":"paged-rotary-qk.wgsl.jinja","bindings":["query_norm","key_norm","cos_cache","sin_cache","cumulative_sequence_length","past_seqlens","q_rotary_output","k_rotary_output","params_rotary"],"dispatch":{"x":"min(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"split_attention","name":"PagedAttention.AttendSplitK","shader":"paged-attention.wgsl.jinja","derive":{"splitK":true},"bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"scratch":"partialOut","name":"partial_out","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","elementType":"vec2<f32>","when":"not pagedHasSink"},"params_main"],"dispatch":{"x":"tokenCount","y":"attrs.kv_num_heads","z":"numSplits"}},{"id":"merge","name":"PagedAttention.AttendSplitKMerge","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bsh\"","inlinePartialStats":"pagedHasSink"},"bindings":[{"scratch":"partialOut","name":"partial_out","buffer":"read-only-storage","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","buffer":"read-only-storage","elementType":"vec2<f32>","when":"not pagedHasSink"},{"arg":"outputT","name":"output","elementType":"$outVec"}],"dispatch":{"x":1,"y":"attrs.num_heads","z":"tokenCount"}}]},{"id":"paged_rotary_qknorm_subgroups","when":["pagedAttnStorageFits","device.wgslLanguageFeatures.has(\"subgroup_id\")","pagedDoRotary and pagedDoNorm and device.limits.maxStorageBuffersPerShaderStage < (9 if packedQkv else 10)"],"requires":{"features":["shader-f16","subgroups"]},"passes":[{"id":"norm_q","name":"PagedAttention.NormalizeQuery","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":false,"normIsQuery":true},"bindings":["q_norm_input","q_norm_weight_input","q_norm_result","params_norm"],"dispatch":{"x":"min(tokenCount * numHeads, 65535)","y":"ceilDiv(tokenCount * numHeads, 65535)","z":1}},{"id":"norm_k","name":"PagedAttention.NormalizeKey","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":false,"normIsQuery":false},"bindings":["k_norm_packed_input","k_norm_input","k_norm_weight_input","k_norm_result","params_norm"],"dispatch":{"x":"min(tokenCount * kvNumHeads, 65535)","y":"ceilDiv(tokenCount * kvNumHeads, 65535)","z":1}},{"id":"rotary","name":"PagedAttention.RotaryQK","shader":"paged-rotary-qk.wgsl.jinja","bindings":["query_norm","key_norm","cos_cache","sin_cache","cumulative_sequence_length","past_seqlens","q_rotary_output","k_rotary_output","params_rotary"],"dispatch":{"x":"min(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"main","name":"PagedAttention.Attend","shader":"paged-attention.wgsl.jinja","bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"arg":"outputT","name":"output","elementType":"$aScalar"},"params_main"],"dispatch":{"x":"ceilDiv(tokenCount, prefillTokens) if pagedResidentPrefill else tokenCount","y":"attrs.kv_num_heads"}}],"priority":1,"derive":{"pagedSubgroupFold":true},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}]},{"id":"paged_rotary_qknorm_splitk","priority":10,"when":["pagedSplitFits","pagedSplitStorageFits","true","pagedDoRotary and pagedDoNorm and device.limits.maxStorageBuffersPerShaderStage < (9 if packedQkv else 10)"],"requires":{"features":["shader-f16"]},"derive":{"attnWorkgroup":"pagedSplitWg","pagedSubgroupFold":false},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"partialOut","dtype":"float32","shape":"[tokenCount * attrs.num_heads * numSplits * (headSize + (4 if pagedHasSink else 0))]"},{"id":"partialStats","dtype":"float32","shape":"[2 * tokenCount * attrs.num_heads * numSplits]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}],"passes":[{"id":"norm_q","name":"PagedAttention.NormalizeQuery","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":false,"normIsQuery":true},"bindings":["q_norm_input","q_norm_weight_input","q_norm_result","params_norm"],"dispatch":{"x":"min(tokenCount * numHeads, 65535)","y":"ceilDiv(tokenCount * numHeads, 65535)","z":1}},{"id":"norm_k","name":"PagedAttention.NormalizeKey","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":false,"normIsQuery":false},"bindings":["k_norm_packed_input","k_norm_input","k_norm_weight_input","k_norm_result","params_norm"],"dispatch":{"x":"min(tokenCount * kvNumHeads, 65535)","y":"ceilDiv(tokenCount * kvNumHeads, 65535)","z":1}},{"id":"rotary","name":"PagedAttention.RotaryQK","shader":"paged-rotary-qk.wgsl.jinja","bindings":["query_norm","key_norm","cos_cache","sin_cache","cumulative_sequence_length","past_seqlens","q_rotary_output","k_rotary_output","params_rotary"],"dispatch":{"x":"min(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"split_attention","name":"PagedAttention.AttendSplitK","shader":"paged-attention.wgsl.jinja","derive":{"splitK":true},"bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"scratch":"partialOut","name":"partial_out","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","elementType":"vec2<f32>","when":"not pagedHasSink"},"params_main"],"dispatch":{"x":"tokenCount","y":"attrs.kv_num_heads","z":"numSplits"}},{"id":"merge","name":"PagedAttention.AttendSplitKMerge","shader":"attn-flash-decode-splitk-merge.wgsl.jinja","derive":{"layout":"\"bsh\"","inlinePartialStats":"pagedHasSink"},"bindings":[{"scratch":"partialOut","name":"partial_out","buffer":"read-only-storage","elementType":"vec4<f32>"},{"scratch":"partialStats","name":"partial_stats","buffer":"read-only-storage","elementType":"vec2<f32>","when":"not pagedHasSink"},{"arg":"outputT","name":"output","elementType":"$outVec"}],"dispatch":{"x":1,"y":"attrs.num_heads","z":"tokenCount"}}]},{"id":"paged_rotary_qknorm","when":["pagedAttnStorageFits","true","pagedDoRotary and pagedDoNorm and device.limits.maxStorageBuffersPerShaderStage < (9 if packedQkv else 10)"],"requires":{"features":["shader-f16"]},"passes":[{"id":"norm_q","name":"PagedAttention.NormalizeQuery","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":false,"normIsQuery":true},"bindings":["q_norm_input","q_norm_weight_input","q_norm_result","params_norm"],"dispatch":{"x":"min(tokenCount * numHeads, 65535)","y":"ceilDiv(tokenCount * numHeads, 65535)","z":1}},{"id":"norm_k","name":"PagedAttention.NormalizeKey","shader":"paged-qknorm.wgsl.jinja","derive":{"normFused":false,"normIsQuery":false},"bindings":["k_norm_packed_input","k_norm_input","k_norm_weight_input","k_norm_result","params_norm"],"dispatch":{"x":"min(tokenCount * kvNumHeads, 65535)","y":"ceilDiv(tokenCount * kvNumHeads, 65535)","z":1}},{"id":"rotary","name":"PagedAttention.RotaryQK","shader":"paged-rotary-qk.wgsl.jinja","bindings":["query_norm","key_norm","cos_cache","sin_cache","cumulative_sequence_length","past_seqlens","q_rotary_output","k_rotary_output","params_rotary"],"dispatch":{"x":"min(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * (qHidden + kvHidden)), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"scatter","name":"PagedAttention.ScatterKV","shader":"paged-scatter-kv.wgsl.jinja","bindings":["scatter_key","scatter_key_norm","key_rotary","value","scatter_query","key_cache","value_cache","scatter_cumulative_sequence_length","scatter_past_seqlens","scatter_block_table","slot_mapping","params","params_scatter"],"dispatch":{"x":"min(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","y":"ceilDiv(ceilDiv((tokenCount * attrs.kv_num_heads * headSize), (tunables.SCATTER_WORKGROUP_SIZE)), 65535)","z":1}},{"id":"main","name":"PagedAttention.Attend","shader":"paged-attention.wgsl.jinja","bindings":["attention_query","attention_query_norm","query_rotary","head_sink","key_cache_main","value_cache_main","cumulative_sequence_length","past_seqlens","block_table",{"arg":"outputT","name":"output","elementType":"$aScalar"},"params_main"],"dispatch":{"x":"ceilDiv(tokenCount, prefillTokens) if pagedResidentPrefill else tokenCount","y":"attrs.kv_num_heads"}}],"priority":0,"derive":{"pagedSubgroupFold":false},"intermediates":[{"id":"rotaryQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"rotaryK","dtype":"float16","shape":"[tokenCount, kvHidden]"},{"id":"normQ","dtype":"float16","shape":"[tokenCount, qHidden]"},{"id":"normK","dtype":"float16","shape":"[tokenCount, kvHidden]"}]}]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
build/webgpu/metadata.json
CHANGED
|
@@ -1,32 +1 @@
|
|
| 1 |
-
{
|
| 2 |
-
"name": "com.microsoft.PagedAttention",
|
| 3 |
-
"id": "_com_microsoft_pagedattention_webgpu_bcb1627",
|
| 4 |
-
"version": 1,
|
| 5 |
-
"license": "Apache-2.0",
|
| 6 |
-
"backend": { "type": "webgpu" },
|
| 7 |
-
"digest": {
|
| 8 |
-
"algorithm": "sha256",
|
| 9 |
-
"files": {
|
| 10 |
-
"attn-flash-decode-splitk-merge.wgsl.jinja": "P0yN9VRWOBKM6lMTWKDX7eKuxcmVjj3YX+eRlYgyG0w=",
|
| 11 |
-
"bench.json": "wiVFqyO9vEyYhD/i3BuWEwEMtorPGtDpjrJQSTX+VEU=",
|
| 12 |
-
"manifest.json": "RVVRT3P/Ix1RKhWszk/4atE5P78+OEHtHAkSyDYe1v0=",
|
| 13 |
-
"paged-attention.wgsl.jinja": "Tkqnp3/PxodwRygVuawTRrPNrS2WDP+n/IYU6693Hog=",
|
| 14 |
-
"paged-scatter-kv.wgsl.jinja": "Xq8l6iRmNLXlx510ylhkcIj4AQSbb5jM5M0/A1IOp7Q=",
|
| 15 |
-
"test.json": "zGwuobgxFob47dayYp0kP1EbTZE9CSCKd0pFZjptm40="
|
| 16 |
-
}
|
| 17 |
-
},
|
| 18 |
-
"provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },
|
| 19 |
-
"webgpu": {
|
| 20 |
-
"manifestSpec": "2.1",
|
| 21 |
-
"variants": {
|
| 22 |
-
"separate_derived_splitk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "paged-attention.wgsl.jinja", "paged-scatter-kv.wgsl.jinja"],
|
| 23 |
-
"separate_derived": ["paged-attention.wgsl.jinja", "paged-scatter-kv.wgsl.jinja"],
|
| 24 |
-
"separate_slot_splitk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "paged-attention.wgsl.jinja", "paged-scatter-kv.wgsl.jinja"],
|
| 25 |
-
"separate_slot": ["paged-attention.wgsl.jinja", "paged-scatter-kv.wgsl.jinja"],
|
| 26 |
-
"packed_derived_splitk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "paged-attention.wgsl.jinja", "paged-scatter-kv.wgsl.jinja"],
|
| 27 |
-
"packed_derived": ["paged-attention.wgsl.jinja", "paged-scatter-kv.wgsl.jinja"],
|
| 28 |
-
"packed_slot_splitk": ["attn-flash-decode-splitk-merge.wgsl.jinja", "paged-attention.wgsl.jinja", "paged-scatter-kv.wgsl.jinja"],
|
| 29 |
-
"packed_slot": ["paged-attention.wgsl.jinja", "paged-scatter-kv.wgsl.jinja"]
|
| 30 |
-
}
|
| 31 |
-
}
|
| 32 |
-
}
|
|
|
|
| 1 |
+
{"name":"com.microsoft.PagedAttention","id":"_com_microsoft_pagedattention_webgpu_7e16880","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"attn-flash-decode-splitk-merge.wgsl.jinja":"ZKgon+6zjNKZLuT9yiJhMYT30yMqaXNiJSoZ4C8H/ac=","bench.json":"MCO1ko1VPHrIHjekm7Mt64qZyUuobOfgMUXI7WiDWTI=","manifest.json":"nRQdsDGONxyOixyv+dET23DGa9NtycrZJl+AoRppCHY=","paged-attention.wgsl.jinja":"BMBCwHrgywSctsIczdpSuGi1u4SYbnBoGHkSwcvgoJ8=","paged-qknorm.wgsl.jinja":"tPmo+aQcAHYq9dJuvWyjr0lV/e6TlOUAnBrfbGMg+Ns=","paged-rotary-qk.wgsl.jinja":"q69gkYAy0cFtbrYf8uDc0ncAhoTIoxAUPZ1SySXrnNY=","paged-scatter-kv.wgsl.jinja":"V+VJsWh+fMgF1BKBUeGLuiFaiOqrybckG7QBCaPhm8A=","test.json":"0KADQKYLpT1Bt2ge6cFTNqbDCLuqz2+2RhNT/PfkXC4="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
build/webgpu/paged-attention.wgsl.jinja
CHANGED
|
@@ -1,5 +1,270 @@
|
|
| 1 |
-
{%
|
| 2 |
-
{% set
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
{% set keyHi = "splitEnd" if splitK else "key_bound" %}
|
| 4 |
{{ env.wgsl.resourceDeclarations }}
|
| 5 |
|
|
@@ -10,12 +275,13 @@
|
|
| 10 |
// Key j of sequence b resides in block_table[b, j / BLOCK_SIZE] at offset
|
| 11 |
// j % BLOCK_SIZE; each tile resolves this mapping once per key and stores the
|
| 12 |
// row bases in workgroup memory. The exclusive key bound is the token's absolute
|
| 13 |
-
// position plus one,
|
|
|
|
| 14 |
{% if splitK %}
|
| 15 |
// Split-K partitions the key axis into NUM_SPLITS contiguous ranges. Each range
|
| 16 |
// writes its unnormalized online state (max, denominator, and weighted V sum),
|
| 17 |
-
// and the merge pass combines those states before the final division.
|
| 18 |
-
//
|
| 19 |
{% endif %}
|
| 20 |
const KV_HEADS: u32 = {{ kvNumHeads }}u;
|
| 21 |
const HEAD_DIM: u32 = {{ headSize }}u;
|
|
@@ -27,7 +293,8 @@ const HEAD_VEC: u32 = {{ headVec }}u;
|
|
| 27 |
{% endif %}
|
| 28 |
const BLOCK_SIZE: u32 = {{ blockSize }}u;
|
| 29 |
const MAX_BLOCKS: u32 = {{ maxBlocks }}u;
|
| 30 |
-
const
|
|
|
|
| 31 |
const Q_PER_KV: u32 = {{ qPerKv }}u;
|
| 32 |
// WG is both the key-tile width and the thread count that walks the head axis.
|
| 33 |
const WG: u32 = {{ attnWorkgroup }}u;
|
|
@@ -62,24 +329,112 @@ fn exp_shift(value: f32, maxValue: f32) -> f32 {
|
|
| 62 |
|
| 63 |
{% if cacheVec4Ok %}
|
| 64 |
var<workgroup> q_shared: array<vec4<f32>, HEAD_VEC * Q_PER_KV>;
|
| 65 |
-
var<workgroup> running_out: array<vec4<f32>, HEAD_VEC * Q_PER_KV>;
|
| 66 |
-
{% else %}
|
| 67 |
var<workgroup> q_shared: array<f32, HEAD_DIM * Q_PER_KV>;
|
| 68 |
-
var<workgroup> running_out: array<f32, HEAD_DIM * Q_PER_KV>;
|
| 69 |
-
{% endif %}
|
| 70 |
var<workgroup> probs: array<f32, WG * Q_PER_KV>;
|
| 71 |
// One resolved cache row base per key of the current tile.
|
| 72 |
var<workgroup> key_rows: array<u32, WG>;
|
| 73 |
|
| 74 |
{% set mdStreams = qPerKv %}
|
|
|
|
| 75 |
// Workgroup-cooperative merge of per-thread online-softmax (m, d) partials:
|
| 76 |
// mNew = max(m1, m2)
|
| 77 |
// dNew = d1 * exp(m1 - mNew) + d2 * exp(m2 - mNew)
|
| 78 |
// Both the subgroup and portable barrier-tree engines return the same merged
|
| 79 |
// pair to every invocation. Repeated merges require a workgroup barrier between
|
| 80 |
// calls before their shared partial storage is reused.
|
|
|
|
| 81 |
{% set mdStreamed = mdStreams is defined %}
|
| 82 |
{% set mdStreams = mdStreams if mdStreams is defined else 1 %}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
{% set mdExtent = "WG" if mdStreams == 1 else "WG * " ~ mdStreams ~ "u" %}
|
| 84 |
var<workgroup> partialM: array<f32, {{ mdExtent }}>;
|
| 85 |
var<workgroup> partialD: array<f32, {{ mdExtent }}>;
|
|
@@ -142,50 +497,138 @@ fn combine_partials(m: f32, d: f32, lidx: u32) -> vec2<f32> {
|
|
| 142 |
return merged;
|
| 143 |
}
|
| 144 |
{% endif %}
|
|
|
|
| 145 |
|
| 146 |
-
{% set ATTN_SCALE_DIM = "HEAD_DIM" %}
|
|
|
|
| 147 |
if (params.scale != 0.0) { return params.scale; }
|
| 148 |
return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));
|
| 149 |
}
|
| 150 |
|
| 151 |
-
{% macro varlen_sequence_of_token(buffer="cumulative_sequence_length") %}
|
| 152 |
fn sequence_of_token(token: u32, batch_size: u32) -> u32 {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
for (var b: u32 = 0u; b < batch_size; b = b + 1u) {
|
| 154 |
if (token < u32({{ buffer }}[b + 1u])) {
|
| 155 |
return b;
|
| 156 |
}
|
| 157 |
}
|
| 158 |
return batch_size - 1u;
|
|
|
|
| 159 |
}{% endmacro %}
|
| 160 |
-
{% macro paged_sequence_index(withLookup=true) %}
|
| 161 |
-
{
|
|
|
|
| 162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
// Physical element base of one (slot, kv head) row of the paged cache, whose
|
| 164 |
// layout is (num_blocks, block_size, kv_num_heads, head_size).
|
| 165 |
fn paged_row_base(block_id: u32, slot_in_block: u32, kv_head: u32) -> u32 {
|
| 166 |
return ((block_id * BLOCK_SIZE + slot_in_block) * KV_HEADS + kv_head) * HEAD_DIM;
|
| 167 |
}
|
|
|
|
| 168 |
{% endmacro %}
|
| 169 |
-
{{ paged_sequence_index() }}
|
| 170 |
@compute @workgroup_size(WG, 1, 1)
|
| 171 |
-
fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
let token = wg.x;
|
| 173 |
let kv_head = wg.y;
|
| 174 |
let head0 = kv_head * Q_PER_KV;
|
| 175 |
let tid = lid.x;
|
| 176 |
|
| 177 |
-
let
|
| 178 |
-
let
|
| 179 |
-
//
|
| 180 |
-
//
|
| 181 |
-
|
|
|
|
|
|
|
| 182 |
let scale = scale_value();
|
|
|
|
|
|
|
| 183 |
{% if splitK %}
|
| 184 |
// Contiguous, equal-length key ranges. The last range is short and a range past
|
| 185 |
// this token's history is empty; both fall out of the tile loop below.
|
| 186 |
let split = wg.z;
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
let splitStart = split * splitLen;
|
|
|
|
| 189 |
let splitEnd = min(key_bound, splitStart + splitLen);
|
| 190 |
{% endif %}
|
| 191 |
|
|
@@ -195,21 +638,34 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
|
|
| 195 |
let lane = dv - g * HEAD_VEC;
|
| 196 |
let qb = token * Q_STRIDE + (head0 + g) * HEAD_DIM + lane * 4u;
|
| 197 |
q_shared[dv] = vec4<f32>(f32(query[qb]), f32(query[qb + 1u]), f32(query[qb + 2u]), f32(query[qb + 3u]));
|
| 198 |
-
running_out[dv] = vec4<f32>(0.0);
|
| 199 |
-
}
|
| 200 |
{% else %}
|
| 201 |
for (var d: u32 = tid; d < HEAD_DIM * Q_PER_KV; d = d + WG) {
|
| 202 |
let g = d / HEAD_DIM;
|
| 203 |
let dim = d - g * HEAD_DIM;
|
| 204 |
q_shared[d] = f32(query[token * Q_STRIDE + (head0 + g) * HEAD_DIM + dim]);
|
| 205 |
-
running_out[d] = 0.0;
|
| 206 |
-
}
|
| 207 |
{% endif %}
|
| 208 |
workgroupBarrier();
|
| 209 |
|
| 210 |
{% for g in range(qPerKv) %}
|
| 211 |
var runningMax_{{ g }} = -FLT_MAX;
|
| 212 |
var runningDenom_{{ g }} = 0.0;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
{% endfor %}
|
| 214 |
|
| 215 |
var tileBase: u32 = {{ keyLo }};
|
|
@@ -218,13 +674,19 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
|
|
| 218 |
break;
|
| 219 |
}
|
| 220 |
let kj = tileBase + tid;
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
{% for g in range(qPerKv) %}
|
| 224 |
var score_{{ g }} = -FLT_MAX;
|
| 225 |
{% endfor %}
|
| 226 |
if (keyAllowed) {
|
| 227 |
-
let block_id = u32(
|
| 228 |
let row = paged_row_base(block_id, kj % BLOCK_SIZE, kv_head);
|
| 229 |
key_rows[tid] = row;
|
| 230 |
{% for g in range(qPerKv) %}
|
|
@@ -251,12 +713,20 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
|
|
| 251 |
score_{{ g }} = acc_{{ g }} * scale;
|
| 252 |
{% endfor %}
|
| 253 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
// All Q_PER_KV reductions ride one barrier tree.
|
| 255 |
{% for g in range(qPerKv) %}
|
| 256 |
partialM[{{ g }}u * WG + tid] = score_{{ g }};
|
| 257 |
partialD[{{ g }}u * WG + tid] = select(0.0, 1.0, keyAllowed);
|
| 258 |
{% endfor %}
|
| 259 |
combine_partials_streams(tid);
|
|
|
|
| 260 |
{% for g in range(qPerKv) %}
|
| 261 |
let tile_{{ g }} = vec2<f32>(partialM[{{ g }}u * WG], partialD[{{ g }}u * WG]);
|
| 262 |
{% endfor %}
|
|
@@ -281,6 +751,9 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
|
|
| 281 |
{% endfor %}
|
| 282 |
// One cache read, every query head in the group, exactly as the scores.
|
| 283 |
for (var i: u32 = 0u; i < tileCount; i = i + 1u) {
|
|
|
|
|
|
|
|
|
|
| 284 |
{% if cacheVec4Ok %}
|
| 285 |
let vv = vec4<f32>(value_cache[key_rows[i] / 4u + dv]);
|
| 286 |
{% else %}
|
|
@@ -291,7 +764,7 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
|
|
| 291 |
{% endfor %}
|
| 292 |
}
|
| 293 |
{% for g in range(qPerKv) %}
|
| 294 |
-
running_out[{{ g }}u * {{ W }} + dv] = running_out[{{ g }}u * {{ W }} + dv] * correction_{{ g }} + vSum_{{ g }};
|
| 295 |
{% endfor %}
|
| 296 |
}
|
| 297 |
// Orders this tile's probs and key_rows reads before the next tile writes them.
|
|
@@ -307,26 +780,35 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
|
|
| 307 |
{% for g in range(qPerKv) %}
|
| 308 |
{
|
| 309 |
let slot_{{ g }} = (token * Q_HEADS + head0 + {{ g }}u) * NUM_SPLITS + split;
|
| 310 |
-
let pBase_{{ g }} = slot_{{ g }} * HEAD_VEC;
|
| 311 |
for (var dv: u32 = tid; dv < HEAD_VEC; dv = dv + WG) {
|
| 312 |
-
partial_out[pBase_{{ g }} + dv] = running_out[{{ g }}u * HEAD_VEC + dv];
|
| 313 |
}
|
| 314 |
if (tid == 0u) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
partial_stats[slot_{{ g }}] = vec2<f32>(runningMax_{{ g }}, runningDenom_{{ g }});
|
|
|
|
| 316 |
}
|
| 317 |
}
|
| 318 |
{% endfor %}
|
| 319 |
}
|
| 320 |
{% else %}
|
| 321 |
-
//
|
| 322 |
-
//
|
| 323 |
{% for g in range(qPerKv) %}
|
| 324 |
let invDenom_{{ g }} = select(0.0, 1.0 / runningDenom_{{ g }}, runningDenom_{{ g }} > 0.0);
|
| 325 |
{% endfor %}
|
| 326 |
for (var dv: u32 = tid; dv < {{ W }}; dv = dv + WG) {
|
| 327 |
{% for g in range(qPerKv) %}
|
| 328 |
{
|
| 329 |
-
let out_v = running_out[{{ g }}u * {{ W }} + dv] * invDenom_{{ g }};
|
| 330 |
{% if cacheVec4Ok %}
|
| 331 |
let ob = token * {{ qHidden }}u + (head0 + {{ g }}u) * HEAD_DIM + dv * 4u;
|
| 332 |
output[ob] = {{ scalar }}(out_v.x);
|
|
@@ -341,3 +823,4 @@ fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid:
|
|
| 341 |
}
|
| 342 |
}
|
| 343 |
{% endif %}
|
|
|
|
|
|
| 1 |
+
{% if pagedResidentPrefill and not (splitK | default(false)) %}
|
| 2 |
+
{% set causalTile = prefillTokens > 1 and pagedIsCausal %}
|
| 3 |
+
{{ env.wgsl.resourceDeclarations }}
|
| 4 |
+
const HEAD_DIM = {{ headSize }}u;
|
| 5 |
+
const HEAD_VEC = {{ headVec }}u;
|
| 6 |
+
const KV_HEADS = {{ kvNumHeads }}u;
|
| 7 |
+
const BLOCK_SIZE = {{ blockSize }}u;
|
| 8 |
+
const MAX_BLOCKS = {{ maxBlocks }}u;
|
| 9 |
+
const Q_STRIDE = {{ attentionQueryStride }}u;
|
| 10 |
+
const WG = {{ attnWorkgroup }}u;
|
| 11 |
+
const KEYS = {{ pagedKeyCeiling }}u;
|
| 12 |
+
|
| 13 |
+
var<workgroup> queries: array<vec4<f32>, 4u * HEAD_VEC>;
|
| 14 |
+
var<workgroup> row_base: array<u32, KEYS>;
|
| 15 |
+
var<workgroup> scores: array<vec4<f32>, KEYS>;
|
| 16 |
+
var<workgroup> partial: array<vec4<f32>, WG>;
|
| 17 |
+
|
| 18 |
+
// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep
|
| 19 |
+
// `m - m` finite so an empty lane / all--inf row contributes the exact
|
| 20 |
+
// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret
|
| 21 |
+
// a zero final denominator according to their public semantics. Using -inf
|
| 22 |
+
// here changes +inf-row behavior.
|
| 23 |
+
const FLT_MAX: f32 = 3.4028234663852886e38;
|
| 24 |
+
|
| 25 |
+
fn is_finite_f32(value: f32) -> bool {
|
| 26 |
+
return select(false, value <= FLT_MAX, value >= -FLT_MAX);
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
// x - m that is exactly 0 when x equals a finite m, so exp(shifted) == 1
|
| 30 |
+
// exactly at the row max. `x - x` on an infinite max is a legal fast-math
|
| 31 |
+
// fold to 0, which would silently turn +inf rows finite — the explicit
|
| 32 |
+
// equality test keeps the NaN propagation of the serial kernels.
|
| 33 |
+
fn shifted_value(value: f32, maxValue: f32) -> f32 {
|
| 34 |
+
let equalFiniteMax = select(false, value == maxValue, is_finite_f32(maxValue));
|
| 35 |
+
return select(value - maxValue, 0.0, equalFiniteMax);
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
fn exp_shift(value: f32, maxValue: f32) -> f32 {
|
| 39 |
+
return exp(shifted_value(value, maxValue));
|
| 40 |
+
}
|
| 41 |
+
{% set ATTN_SCALE_DIM = "HEAD_DIM" %}fn scale_value() -> f32 {
|
| 42 |
+
if (params.scale != 0.0) { return params.scale; }
|
| 43 |
+
return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));
|
| 44 |
+
}
|
| 45 |
+
{% macro varlen_sequence_of_token(buffer="cumulative_sequence_length", binarySearch=false) %}
|
| 46 |
+
fn sequence_of_token(token: u32, batch_size: u32) -> u32 {
|
| 47 |
+
{% if binarySearch %}
|
| 48 |
+
var lo = 0u;
|
| 49 |
+
var hi = batch_size;
|
| 50 |
+
while (lo < hi) {
|
| 51 |
+
let mid = lo + (hi - lo) / 2u;
|
| 52 |
+
if (token < u32({{ buffer }}[mid + 1u])) {
|
| 53 |
+
hi = mid;
|
| 54 |
+
} else {
|
| 55 |
+
lo = mid + 1u;
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
return min(lo, batch_size - 1u);
|
| 59 |
+
{% else %}
|
| 60 |
+
for (var b: u32 = 0u; b < batch_size; b = b + 1u) {
|
| 61 |
+
if (token < u32({{ buffer }}[b + 1u])) {
|
| 62 |
+
return b;
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
return batch_size - 1u;
|
| 66 |
+
{% endif %}
|
| 67 |
+
}{% endmacro %}
|
| 68 |
+
{% macro paged_sequence_index(withLookup=true, attentionMask=false, withRowBase=true) %}
|
| 69 |
+
{% if withLookup %}
|
| 70 |
+
{{ varlen_sequence_of_token(binarySearch=pagedBinarySequenceLookup) }}
|
| 71 |
+
|
| 72 |
+
struct PagedToken {
|
| 73 |
+
sequence: u32,
|
| 74 |
+
keyBound: u32,
|
| 75 |
+
{% if attentionMask and pagedLocalWindow > 0 %}
|
| 76 |
+
keyStart: u32,
|
| 77 |
+
{% endif %}
|
| 78 |
+
valid: bool,
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
// Validate the signed prefix before the lookup casts any endpoint. A malformed
|
| 82 |
+
// prefix disables derived appends and attention for the whole call. Empty
|
| 83 |
+
// requests are legal. No device metadata is copied back to the host.
|
| 84 |
+
fn paged_token_of(token: u32, batchSize: u32) -> PagedToken {
|
| 85 |
+
var info: PagedToken;
|
| 86 |
+
if (cumulative_sequence_length[0] != 0
|
| 87 |
+
|| cumulative_sequence_length[batchSize] != {{ tokenCount }}i) { return info; }
|
| 88 |
+
var previous = 0i;
|
| 89 |
+
for (var b = 1u; b <= batchSize; b++) {
|
| 90 |
+
let end = cumulative_sequence_length[b];
|
| 91 |
+
if (end < previous || end > {{ tokenCount }}i) { return info; }
|
| 92 |
+
previous = end;
|
| 93 |
+
}
|
| 94 |
+
let sequence = sequence_of_token(token, batchSize);
|
| 95 |
+
let start = u32(cumulative_sequence_length[sequence]);
|
| 96 |
+
let end = u32(cumulative_sequence_length[sequence + 1u]);
|
| 97 |
+
let past = past_seqlens[sequence];
|
| 98 |
+
if (token < start || token >= end || past < 0 || u32(past) > {{ pagedKeyCeiling }}u) { return info; }
|
| 99 |
+
// Bound the complete append interval before subtracting or adding. A request
|
| 100 |
+
// that cannot fit this call's tokens is left intact, rather than half updated.
|
| 101 |
+
if (end - start > {{ pagedKeyCeiling }}u - u32(past)) { return info; }
|
| 102 |
+
{% if pagedDoRotary %}
|
| 103 |
+
// Reject the entire append before any rotary cache lookup or cache write.
|
| 104 |
+
if (u32(past) > {{ pagedRotaryRows }}u
|
| 105 |
+
|| end - start > {{ pagedRotaryRows }}u - u32(past)) { return info; }
|
| 106 |
+
{% endif %}
|
| 107 |
+
info.sequence = sequence;
|
| 108 |
+
{% if attentionMask and not pagedIsCausal %}
|
| 109 |
+
// Non-causal attention sees all live keys. Scatter keeps the token's own
|
| 110 |
+
// absolute slot by using this helper without attentionMask.
|
| 111 |
+
info.keyBound = u32(past) + (end - start);
|
| 112 |
+
{% else %}
|
| 113 |
+
info.keyBound = u32(past) + (token - start) + 1u;
|
| 114 |
+
{% endif %}
|
| 115 |
+
{% if attentionMask and pagedLocalWindow > 0 %}
|
| 116 |
+
// The left bound stays relative to this query when future keys are visible.
|
| 117 |
+
// The window constant is clamped before conversion to u32 to prevent wraparound.
|
| 118 |
+
let query_end = u32(past) + (token - start) + 1u;
|
| 119 |
+
info.keyStart = query_end - min(query_end, {{ pagedLocalWindow }}u);
|
| 120 |
+
{% endif %}
|
| 121 |
+
info.valid = true;
|
| 122 |
+
return info;
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
{% endif %}
|
| 126 |
+
{% if withRowBase %}
|
| 127 |
+
// Physical element base of one (slot, kv head) row of the paged cache, whose
|
| 128 |
+
// layout is (num_blocks, block_size, kv_num_heads, head_size).
|
| 129 |
+
fn paged_row_base(block_id: u32, slot_in_block: u32, kv_head: u32) -> u32 {
|
| 130 |
+
return ((block_id * BLOCK_SIZE + slot_in_block) * KV_HEADS + kv_head) * HEAD_DIM;
|
| 131 |
+
}
|
| 132 |
+
{% endif %}
|
| 133 |
+
{% endmacro %}
|
| 134 |
+
{{ paged_sequence_index(attentionMask=true) }}
|
| 135 |
+
{% macro wgsl_tree_reduce_f32(name, mode, buffer="partial", wg="WG", trailingBarrier=true, valueType="f32") %}
|
| 136 |
+
fn {{ name }}(value: {{ valueType }}, tid: u32) -> {{ valueType }} {
|
| 137 |
+
{{ buffer }}[tid] = value;
|
| 138 |
+
workgroupBarrier();
|
| 139 |
+
// Ceil-halving keeps every lane when the workgroup size is not a power of
|
| 140 |
+
// two. For even n this matches the power-of-two tree order; for odd n, lanes
|
| 141 |
+
// [0, n-half) fold the upper tail while the middle lane carries forward.
|
| 142 |
+
var n: u32 = {{ wg }};
|
| 143 |
+
loop {
|
| 144 |
+
let half = (n + 1u) / 2u;
|
| 145 |
+
if (tid < n - half) {
|
| 146 |
+
{% if mode == "max" %}
|
| 147 |
+
{{ buffer }}[tid] = max({{ buffer }}[tid], {{ buffer }}[tid + half]);
|
| 148 |
+
{% else %}
|
| 149 |
+
{{ buffer }}[tid] = {{ buffer }}[tid] + {{ buffer }}[tid + half];
|
| 150 |
+
{% endif %}
|
| 151 |
+
}
|
| 152 |
+
workgroupBarrier();
|
| 153 |
+
n = half;
|
| 154 |
+
if (n == 1u) {
|
| 155 |
+
break;
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
let reduced = {{ buffer }}[0];
|
| 159 |
+
{% if trailingBarrier %}
|
| 160 |
+
// Every lane reads slot 0 above, so a following reduction's first store must not run until
|
| 161 |
+
// all lanes have read it.
|
| 162 |
+
workgroupBarrier();
|
| 163 |
+
{% endif %}
|
| 164 |
+
return reduced;
|
| 165 |
+
}
|
| 166 |
+
{% endmacro %}
|
| 167 |
+
{{ wgsl_tree_reduce_f32("row_max", "max", valueType="vec4<f32>") }}
|
| 168 |
+
{{ wgsl_tree_reduce_f32("row_sum", "sum", trailingBarrier=false, valueType="vec4<f32>") }}
|
| 169 |
+
|
| 170 |
+
@compute @workgroup_size(WG)
|
| 171 |
+
fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) tid: u32) {
|
| 172 |
+
let first = wg.x * {{ prefillTokens }}u;
|
| 173 |
+
let head = wg.y;
|
| 174 |
+
let info = paged_token_of(first, params.batchSize);
|
| 175 |
+
{% if prefillTokens > 1 %}
|
| 176 |
+
let last = min(first + {{ prefillTokens - 1 }}u, {{ tokenCount - 1 }}u);
|
| 177 |
+
let limit = paged_token_of(last, params.batchSize).keyBound;
|
| 178 |
+
{% else %}
|
| 179 |
+
let limit = info.keyBound;
|
| 180 |
+
{% endif %}
|
| 181 |
+
for (var dv = tid; dv < 4u * HEAD_VEC; dv += WG) {
|
| 182 |
+
let row = dv / HEAD_VEC;
|
| 183 |
+
let token = min(first + row / {{ qPerKv }}u, {{ tokenCount - 1 }}u);
|
| 184 |
+
let src = token * Q_STRIDE + (head * {{ qPerKv }}u + row % {{ qPerKv }}u) * HEAD_DIM + (dv % HEAD_VEC) * 4u;
|
| 185 |
+
queries[dv] = vec4<f32>(vec4<f16>(query[src], query[src + 1u], query[src + 2u], query[src + 3u]));
|
| 186 |
+
}
|
| 187 |
+
workgroupBarrier();
|
| 188 |
+
|
| 189 |
+
let scale = scale_value();
|
| 190 |
+
var maximum = vec4<f32>(-FLT_MAX);
|
| 191 |
+
for (var key = tid; key < limit; key += WG) {
|
| 192 |
+
let block = block_table[info.sequence * MAX_BLOCKS + key / BLOCK_SIZE];
|
| 193 |
+
row_base[key] = 0xffffffffu;
|
| 194 |
+
if (block < 0 || u32(block) >= {{ numCacheBlocks }}u) { continue; }
|
| 195 |
+
let base = paged_row_base(u32(block), key % BLOCK_SIZE, head) / 4u;
|
| 196 |
+
row_base[key] = base;
|
| 197 |
+
var score = vec4<f32>(0.0);
|
| 198 |
+
for (var dv = 0u; dv < HEAD_VEC; dv++) {
|
| 199 |
+
let k = vec4<f32>(key_cache[base + dv]);
|
| 200 |
+
{% for r in range(4) %}
|
| 201 |
+
score[{{ r }}] += dot(queries[{{ r }}u * HEAD_VEC + dv], k);
|
| 202 |
+
{% endfor %}
|
| 203 |
+
}
|
| 204 |
+
score *= scale;
|
| 205 |
+
scores[key] = score;
|
| 206 |
+
{% if causalTile %}
|
| 207 |
+
{% for r in range(4) %}
|
| 208 |
+
if (key < info.keyBound + {{ r // qPerKv }}u) { maximum[{{ r }}] = max(maximum[{{ r }}], score[{{ r }}]); }
|
| 209 |
+
{% endfor %}
|
| 210 |
+
{% else %}
|
| 211 |
+
maximum = max(maximum, score);
|
| 212 |
+
{% endif %}
|
| 213 |
+
}
|
| 214 |
+
maximum = row_max(maximum, tid);
|
| 215 |
+
var denom = vec4<f32>(0.0);
|
| 216 |
+
for (var key = tid; key < limit; key += WG) {
|
| 217 |
+
if (row_base[key] == 0xffffffffu) { continue; }
|
| 218 |
+
let score = scores[key];
|
| 219 |
+
var weight = vec4<f32>(0.0);
|
| 220 |
+
{% for r in range(4) %}
|
| 221 |
+
{% if causalTile %}
|
| 222 |
+
if (key < info.keyBound + {{ r // qPerKv }}u) {
|
| 223 |
+
weight[{{ r }}] = exp_shift(score[{{ r }}], maximum[{{ r }}]);
|
| 224 |
+
}
|
| 225 |
+
{% else %}
|
| 226 |
+
weight[{{ r }}] = exp_shift(score[{{ r }}], maximum[{{ r }}]);
|
| 227 |
+
{% endif %}
|
| 228 |
+
{% endfor %}
|
| 229 |
+
scores[key] = weight;
|
| 230 |
+
denom += weight;
|
| 231 |
+
}
|
| 232 |
+
denom = row_sum(denom, tid);
|
| 233 |
+
for (var dv = tid; dv < HEAD_VEC; dv += WG) {
|
| 234 |
+
{% for r in range(4) %}
|
| 235 |
+
var out{{ r }} = vec4<f32>(0.0);
|
| 236 |
+
{% endfor %}
|
| 237 |
+
for (var key = 0u; key < limit; key++) {
|
| 238 |
+
let base = row_base[key];
|
| 239 |
+
if (base == 0xffffffffu) { continue; }
|
| 240 |
+
let v = vec4<f32>(value_cache[base + dv]);
|
| 241 |
+
let weight = scores[key];
|
| 242 |
+
{% if causalTile %} // A future value may be non-finite even when its weight is zero.
|
| 243 |
+
{% endif %}{% for r in range(4) %}
|
| 244 |
+
{% if causalTile %}
|
| 245 |
+
if (key < info.keyBound + {{ r // qPerKv }}u) { out{{ r }} += weight[{{ r }}] * v; }
|
| 246 |
+
{% else %}
|
| 247 |
+
out{{ r }} += weight[{{ r }}] * v;
|
| 248 |
+
{% endif %}
|
| 249 |
+
{% endfor %}
|
| 250 |
+
}
|
| 251 |
+
{% for r in range(4) %}
|
| 252 |
+
{% if prefillTokens > 1 and tokenCount % prefillTokens != 0 and r // qPerKv > 0 %}if (first + {{ r // qPerKv }}u < {{ tokenCount }}u) {% endif %}{
|
| 253 |
+
let offset = (first + {{ r // qPerKv }}u) * {{ qHidden }}u + (head * {{ qPerKv }}u + {{ r % qPerKv }}u) * HEAD_DIM + dv * 4u;
|
| 254 |
+
let value = vec4<f16>(out{{ r }} * select(0.0, 1.0 / denom[{{ r }}], denom[{{ r }}] > 0.0));
|
| 255 |
+
{% for lane in range(4) %}
|
| 256 |
+
output[offset + {{ lane }}u] = value[{{ lane }}];
|
| 257 |
+
{% endfor %}
|
| 258 |
+
}
|
| 259 |
+
{% endfor %}
|
| 260 |
+
}
|
| 261 |
+
}
|
| 262 |
+
{% else %}
|
| 263 |
+
{% if pagedSubgroupFold %}
|
| 264 |
+
enable subgroups;
|
| 265 |
+
{% endif %}
|
| 266 |
+
{% set splitK = splitK is defined and splitK %}{% set privateOutput = pagedPrivateOutput and not splitK %}{% set outputWidth = headVec if cacheVec4Ok else headSize %}{% set outputParts = (outputWidth + attnWorkgroup - 1) // attnWorkgroup %}
|
| 267 |
+
{% set keyLo = "splitStart" if splitK else "info.keyStart" if pagedLocalWindow > 0 else "0u" %}
|
| 268 |
{% set keyHi = "splitEnd" if splitK else "key_bound" %}
|
| 269 |
{{ env.wgsl.resourceDeclarations }}
|
| 270 |
|
|
|
|
| 275 |
// Key j of sequence b resides in block_table[b, j / BLOCK_SIZE] at offset
|
| 276 |
// j % BLOCK_SIZE; each tile resolves this mapping once per key and stores the
|
| 277 |
// row bases in workgroup memory. The exclusive key bound is the token's absolute
|
| 278 |
+
// position plus one in causal mode, or the full live context otherwise.
|
| 279 |
+
// A local window also skips earlier keys before any K/V load.
|
| 280 |
{% if splitK %}
|
| 281 |
// Split-K partitions the key axis into NUM_SPLITS contiguous ranges. Each range
|
| 282 |
// writes its unnormalized online state (max, denominator, and weighted V sum),
|
| 283 |
+
// and the merge pass combines those states before the final division. Empty
|
| 284 |
+
// ranges write the (-FLT_MAX, 0) identity, except split zero owns any valid sink.
|
| 285 |
{% endif %}
|
| 286 |
const KV_HEADS: u32 = {{ kvNumHeads }}u;
|
| 287 |
const HEAD_DIM: u32 = {{ headSize }}u;
|
|
|
|
| 293 |
{% endif %}
|
| 294 |
const BLOCK_SIZE: u32 = {{ blockSize }}u;
|
| 295 |
const MAX_BLOCKS: u32 = {{ maxBlocks }}u;
|
| 296 |
+
const NUM_BLOCKS: u32 = {{ numCacheBlocks }}u;
|
| 297 |
+
const Q_STRIDE: u32 = {{ attentionQueryStride }}u;
|
| 298 |
const Q_PER_KV: u32 = {{ qPerKv }}u;
|
| 299 |
// WG is both the key-tile width and the thread count that walks the head axis.
|
| 300 |
const WG: u32 = {{ attnWorkgroup }}u;
|
|
|
|
| 329 |
|
| 330 |
{% if cacheVec4Ok %}
|
| 331 |
var<workgroup> q_shared: array<vec4<f32>, HEAD_VEC * Q_PER_KV>;
|
| 332 |
+
{% if not privateOutput %}var<workgroup> running_out: array<vec4<f32>, HEAD_VEC * Q_PER_KV>;
|
| 333 |
+
{% endif %}{% else %}
|
| 334 |
var<workgroup> q_shared: array<f32, HEAD_DIM * Q_PER_KV>;
|
| 335 |
+
{% if not privateOutput %}var<workgroup> running_out: array<f32, HEAD_DIM * Q_PER_KV>;
|
| 336 |
+
{% endif %}{% endif %}
|
| 337 |
var<workgroup> probs: array<f32, WG * Q_PER_KV>;
|
| 338 |
// One resolved cache row base per key of the current tile.
|
| 339 |
var<workgroup> key_rows: array<u32, WG>;
|
| 340 |
|
| 341 |
{% set mdStreams = qPerKv %}
|
| 342 |
+
{% set combineSubgroups = pagedSubgroupFold %}
|
| 343 |
// Workgroup-cooperative merge of per-thread online-softmax (m, d) partials:
|
| 344 |
// mNew = max(m1, m2)
|
| 345 |
// dNew = d1 * exp(m1 - mNew) + d2 * exp(m2 - mNew)
|
| 346 |
// Both the subgroup and portable barrier-tree engines return the same merged
|
| 347 |
// pair to every invocation. Repeated merges require a workgroup barrier between
|
| 348 |
// calls before their shared partial storage is reused.
|
| 349 |
+
{% set combineSubgroups = combineSubgroups is defined and combineSubgroups %}
|
| 350 |
{% set mdStreamed = mdStreams is defined %}
|
| 351 |
{% set mdStreams = mdStreams if mdStreams is defined else 1 %}
|
| 352 |
+
{% if combineSubgroups and mdStreamed %}
|
| 353 |
+
var<workgroup> partialM: array<f32, WG * {{ mdStreams }}u>;
|
| 354 |
+
var<workgroup> partialD: array<f32, WG * {{ mdStreams }}u>;
|
| 355 |
+
|
| 356 |
+
fn combine_partials_streams(tid: u32, sgId: u32, foldCount: u32, valid: f32
|
| 357 |
+
{% for g in range(mdStreams) %}
|
| 358 |
+
, score_{{ g }}: f32
|
| 359 |
+
{% endfor %}
|
| 360 |
+
) {
|
| 361 |
+
{% for g in range(mdStreams) %}
|
| 362 |
+
let subgroupMax_{{ g }} = subgroupMax(score_{{ g }});
|
| 363 |
+
let subgroupDenom_{{ g }} = subgroupAdd(valid * exp_shift(score_{{ g }}, subgroupMax_{{ g }}));
|
| 364 |
+
{% endfor %}
|
| 365 |
+
if (subgroupElect()) {
|
| 366 |
+
{% for g in range(mdStreams) %}
|
| 367 |
+
partialM[{{ g }}u * WG + sgId] = subgroupMax_{{ g }};
|
| 368 |
+
partialD[{{ g }}u * WG + sgId] = subgroupDenom_{{ g }};
|
| 369 |
+
{% endfor %}
|
| 370 |
+
}
|
| 371 |
+
workgroupBarrier();
|
| 372 |
+
if (tid == 0u) {
|
| 373 |
+
{% for g in range(mdStreams) %}
|
| 374 |
+
var m_{{ g }} = -FLT_MAX;
|
| 375 |
+
var d_{{ g }} = 0.0;
|
| 376 |
+
{% endfor %}
|
| 377 |
+
for (var s = 0u; s < foldCount; s = s + 1u) {
|
| 378 |
+
{% for g in range(mdStreams) %}
|
| 379 |
+
let sm_{{ g }} = partialM[{{ g }}u * WG + s];
|
| 380 |
+
let newM_{{ g }} = max(m_{{ g }}, sm_{{ g }});
|
| 381 |
+
d_{{ g }} = d_{{ g }} * exp_shift(m_{{ g }}, newM_{{ g }}) + partialD[{{ g }}u * WG + s] * exp_shift(sm_{{ g }}, newM_{{ g }});
|
| 382 |
+
m_{{ g }} = newM_{{ g }};
|
| 383 |
+
{% endfor %}
|
| 384 |
+
}
|
| 385 |
+
{% for g in range(mdStreams) %}
|
| 386 |
+
partialM[{{ g }}u * WG] = m_{{ g }};
|
| 387 |
+
partialD[{{ g }}u * WG] = d_{{ g }};
|
| 388 |
+
{% endfor %}
|
| 389 |
+
}
|
| 390 |
+
workgroupBarrier();
|
| 391 |
+
}
|
| 392 |
+
{% elif combineSubgroups %}
|
| 393 |
+
// Cross-subgroup merge that assumes nothing about which invocations share a
|
| 394 |
+
// subgroup or how many subgroups there are: each subgroup's elected lane
|
| 395 |
+
// publishes the subgroup pair in the slot at its OWN invocation index and sets
|
| 396 |
+
// that index's bit in a workgroup bitmask; thread 0 then folds exactly the
|
| 397 |
+
// published slots, in ascending index order (the online (m, d) merge is not
|
| 398 |
+
// float-associative, so the order is fixed), and clears the mask for the next
|
| 399 |
+
// call as it reads it. Workgroup memory starts zeroed, so the mask needs no
|
| 400 |
+
// setup. Same three collectives as a single-subgroup reduce, two barriers.
|
| 401 |
+
var<workgroup> partialM: array<f32, WG>;
|
| 402 |
+
var<workgroup> partialD: array<f32, WG>;
|
| 403 |
+
var<workgroup> leaderMask: array<atomic<u32>, (WG + 31u) / 32u>;
|
| 404 |
+
var<workgroup> combinedMD: vec2<f32>;
|
| 405 |
+
|
| 406 |
+
fn combine_partials(m: f32, d: f32, lidx: u32) -> vec2<f32> {
|
| 407 |
+
let sgM = subgroupMax(m);
|
| 408 |
+
// A lane with no elements contributes d == 0 (exact identity). A +inf
|
| 409 |
+
// element made exp(inf - inf) = NaN stick in that lane's d; a NaN element
|
| 410 |
+
// landed in d via exp(NaN); both survive the merge and are detected by the
|
| 411 |
+
// code after the reduction.
|
| 412 |
+
let sgD = subgroupAdd(d * exp_shift(m, sgM));
|
| 413 |
+
if (subgroupElect()) {
|
| 414 |
+
partialM[lidx] = sgM;
|
| 415 |
+
partialD[lidx] = sgD;
|
| 416 |
+
atomicOr(&leaderMask[lidx / 32u], 1u << (lidx % 32u));
|
| 417 |
+
}
|
| 418 |
+
workgroupBarrier();
|
| 419 |
+
if (lidx == 0u) {
|
| 420 |
+
var accM = -FLT_MAX;
|
| 421 |
+
var accD = 0.0;
|
| 422 |
+
for (var w = 0u; w < (WG + 31u) / 32u; w = w + 1u) {
|
| 423 |
+
var bits = atomicExchange(&leaderMask[w], 0u);
|
| 424 |
+
while (bits != 0u) {
|
| 425 |
+
let slot = w * 32u + firstTrailingBit(bits);
|
| 426 |
+
bits = bits & (bits - 1u);
|
| 427 |
+
let mNew = max(accM, partialM[slot]);
|
| 428 |
+
accD = accD * exp_shift(accM, mNew) + partialD[slot] * exp_shift(partialM[slot], mNew);
|
| 429 |
+
accM = mNew;
|
| 430 |
+
}
|
| 431 |
+
}
|
| 432 |
+
combinedMD = vec2<f32>(accM, accD);
|
| 433 |
+
}
|
| 434 |
+
workgroupBarrier();
|
| 435 |
+
return combinedMD;
|
| 436 |
+
}
|
| 437 |
+
{% else %}
|
| 438 |
{% set mdExtent = "WG" if mdStreams == 1 else "WG * " ~ mdStreams ~ "u" %}
|
| 439 |
var<workgroup> partialM: array<f32, {{ mdExtent }}>;
|
| 440 |
var<workgroup> partialD: array<f32, {{ mdExtent }}>;
|
|
|
|
| 497 |
return merged;
|
| 498 |
}
|
| 499 |
{% endif %}
|
| 500 |
+
{% endif %}
|
| 501 |
|
| 502 |
+
{% if ATTN_SCALE_DIM is not defined %}{% set ATTN_SCALE_DIM = "HEAD_DIM" %}{% endif %}
|
| 503 |
+
fn scale_value() -> f32 {
|
| 504 |
if (params.scale != 0.0) { return params.scale; }
|
| 505 |
return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));
|
| 506 |
}
|
| 507 |
|
| 508 |
+
{% macro varlen_sequence_of_token(buffer="cumulative_sequence_length", binarySearch=false) %}
|
| 509 |
fn sequence_of_token(token: u32, batch_size: u32) -> u32 {
|
| 510 |
+
{% if binarySearch %}
|
| 511 |
+
var lo = 0u;
|
| 512 |
+
var hi = batch_size;
|
| 513 |
+
while (lo < hi) {
|
| 514 |
+
let mid = lo + (hi - lo) / 2u;
|
| 515 |
+
if (token < u32({{ buffer }}[mid + 1u])) {
|
| 516 |
+
hi = mid;
|
| 517 |
+
} else {
|
| 518 |
+
lo = mid + 1u;
|
| 519 |
+
}
|
| 520 |
+
}
|
| 521 |
+
return min(lo, batch_size - 1u);
|
| 522 |
+
{% else %}
|
| 523 |
for (var b: u32 = 0u; b < batch_size; b = b + 1u) {
|
| 524 |
if (token < u32({{ buffer }}[b + 1u])) {
|
| 525 |
return b;
|
| 526 |
}
|
| 527 |
}
|
| 528 |
return batch_size - 1u;
|
| 529 |
+
{% endif %}
|
| 530 |
}{% endmacro %}
|
| 531 |
+
{% macro paged_sequence_index(withLookup=true, attentionMask=false, withRowBase=true) %}
|
| 532 |
+
{% if withLookup %}
|
| 533 |
+
{{ varlen_sequence_of_token(binarySearch=pagedBinarySequenceLookup) }}
|
| 534 |
|
| 535 |
+
struct PagedToken {
|
| 536 |
+
sequence: u32,
|
| 537 |
+
keyBound: u32,
|
| 538 |
+
{% if attentionMask and pagedLocalWindow > 0 %}
|
| 539 |
+
keyStart: u32,
|
| 540 |
+
{% endif %}
|
| 541 |
+
valid: bool,
|
| 542 |
+
}
|
| 543 |
+
|
| 544 |
+
// Validate the signed prefix before the lookup casts any endpoint. A malformed
|
| 545 |
+
// prefix disables derived appends and attention for the whole call. Empty
|
| 546 |
+
// requests are legal. No device metadata is copied back to the host.
|
| 547 |
+
fn paged_token_of(token: u32, batchSize: u32) -> PagedToken {
|
| 548 |
+
var info: PagedToken;
|
| 549 |
+
if (cumulative_sequence_length[0] != 0
|
| 550 |
+
|| cumulative_sequence_length[batchSize] != {{ tokenCount }}i) { return info; }
|
| 551 |
+
var previous = 0i;
|
| 552 |
+
for (var b = 1u; b <= batchSize; b++) {
|
| 553 |
+
let end = cumulative_sequence_length[b];
|
| 554 |
+
if (end < previous || end > {{ tokenCount }}i) { return info; }
|
| 555 |
+
previous = end;
|
| 556 |
+
}
|
| 557 |
+
let sequence = sequence_of_token(token, batchSize);
|
| 558 |
+
let start = u32(cumulative_sequence_length[sequence]);
|
| 559 |
+
let end = u32(cumulative_sequence_length[sequence + 1u]);
|
| 560 |
+
let past = past_seqlens[sequence];
|
| 561 |
+
if (token < start || token >= end || past < 0 || u32(past) > {{ pagedKeyCeiling }}u) { return info; }
|
| 562 |
+
// Bound the complete append interval before subtracting or adding. A request
|
| 563 |
+
// that cannot fit this call's tokens is left intact, rather than half updated.
|
| 564 |
+
if (end - start > {{ pagedKeyCeiling }}u - u32(past)) { return info; }
|
| 565 |
+
{% if pagedDoRotary %}
|
| 566 |
+
// Reject the entire append before any rotary cache lookup or cache write.
|
| 567 |
+
if (u32(past) > {{ pagedRotaryRows }}u
|
| 568 |
+
|| end - start > {{ pagedRotaryRows }}u - u32(past)) { return info; }
|
| 569 |
+
{% endif %}
|
| 570 |
+
info.sequence = sequence;
|
| 571 |
+
{% if attentionMask and not pagedIsCausal %}
|
| 572 |
+
// Non-causal attention sees all live keys. Scatter keeps the token's own
|
| 573 |
+
// absolute slot by using this helper without attentionMask.
|
| 574 |
+
info.keyBound = u32(past) + (end - start);
|
| 575 |
+
{% else %}
|
| 576 |
+
info.keyBound = u32(past) + (token - start) + 1u;
|
| 577 |
+
{% endif %}
|
| 578 |
+
{% if attentionMask and pagedLocalWindow > 0 %}
|
| 579 |
+
// The left bound stays relative to this query when future keys are visible.
|
| 580 |
+
// The window constant is clamped before conversion to u32 to prevent wraparound.
|
| 581 |
+
let query_end = u32(past) + (token - start) + 1u;
|
| 582 |
+
info.keyStart = query_end - min(query_end, {{ pagedLocalWindow }}u);
|
| 583 |
+
{% endif %}
|
| 584 |
+
info.valid = true;
|
| 585 |
+
return info;
|
| 586 |
+
}
|
| 587 |
+
|
| 588 |
+
{% endif %}
|
| 589 |
+
{% if withRowBase %}
|
| 590 |
// Physical element base of one (slot, kv head) row of the paged cache, whose
|
| 591 |
// layout is (num_blocks, block_size, kv_num_heads, head_size).
|
| 592 |
fn paged_row_base(block_id: u32, slot_in_block: u32, kv_head: u32) -> u32 {
|
| 593 |
return ((block_id * BLOCK_SIZE + slot_in_block) * KV_HEADS + kv_head) * HEAD_DIM;
|
| 594 |
}
|
| 595 |
+
{% endif %}
|
| 596 |
{% endmacro %}
|
| 597 |
+
{{ paged_sequence_index(attentionMask=true) }}
|
| 598 |
@compute @workgroup_size(WG, 1, 1)
|
| 599 |
+
fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>
|
| 600 |
+
{% if pagedSubgroupFold %}
|
| 601 |
+
, @builtin(subgroup_id) sgId: u32
|
| 602 |
+
, @builtin(num_subgroups) foldCount: u32
|
| 603 |
+
{% endif %}
|
| 604 |
+
) {
|
| 605 |
let token = wg.x;
|
| 606 |
let kv_head = wg.y;
|
| 607 |
let head0 = kv_head * Q_PER_KV;
|
| 608 |
let tid = lid.x;
|
| 609 |
|
| 610 |
+
let info = paged_token_of(token, params.batchSize);
|
| 611 |
+
let sequence = info.sequence;
|
| 612 |
+
// The helper validates the schedule and computes this query's visible
|
| 613 |
+
// interval. Scatter always uses its own absolute append slot.
|
| 614 |
+
// Invalid schedules carry a zero key bound, producing zero output and the
|
| 615 |
+
// split merge identity through the ordinary initialization/store path.
|
| 616 |
+
let key_bound = info.keyBound;
|
| 617 |
let scale = scale_value();
|
| 618 |
+
{% if privateOutput %} var running_out: array<{{ "vec4<f32>" if cacheVec4Ok else "f32" }}, {{ outputParts * qPerKv }}>;
|
| 619 |
+
{% endif %}
|
| 620 |
{% if splitK %}
|
| 621 |
// Contiguous, equal-length key ranges. The last range is short and a range past
|
| 622 |
// this token's history is empty; both fall out of the tile loop below.
|
| 623 |
let split = wg.z;
|
| 624 |
+
{% if pagedLocalWindow > 0 %}
|
| 625 |
+
let key_count = key_bound - info.keyStart;
|
| 626 |
+
let splitLen = key_count / NUM_SPLITS + select(0u, 1u, key_count % NUM_SPLITS != 0u);
|
| 627 |
+
let splitStart = info.keyStart + split * splitLen;
|
| 628 |
+
{% else %}
|
| 629 |
+
let splitLen = key_bound / NUM_SPLITS + select(0u, 1u, key_bound % NUM_SPLITS != 0u);
|
| 630 |
let splitStart = split * splitLen;
|
| 631 |
+
{% endif %}
|
| 632 |
let splitEnd = min(key_bound, splitStart + splitLen);
|
| 633 |
{% endif %}
|
| 634 |
|
|
|
|
| 638 |
let lane = dv - g * HEAD_VEC;
|
| 639 |
let qb = token * Q_STRIDE + (head0 + g) * HEAD_DIM + lane * 4u;
|
| 640 |
q_shared[dv] = vec4<f32>(f32(query[qb]), f32(query[qb + 1u]), f32(query[qb + 2u]), f32(query[qb + 3u]));
|
| 641 |
+
{% if not privateOutput %} running_out[dv] = vec4<f32>(0.0);
|
| 642 |
+
{% endif %} }
|
| 643 |
{% else %}
|
| 644 |
for (var d: u32 = tid; d < HEAD_DIM * Q_PER_KV; d = d + WG) {
|
| 645 |
let g = d / HEAD_DIM;
|
| 646 |
let dim = d - g * HEAD_DIM;
|
| 647 |
q_shared[d] = f32(query[token * Q_STRIDE + (head0 + g) * HEAD_DIM + dim]);
|
| 648 |
+
{% if not privateOutput %} running_out[d] = 0.0;
|
| 649 |
+
{% endif %} }
|
| 650 |
{% endif %}
|
| 651 |
workgroupBarrier();
|
| 652 |
|
| 653 |
{% for g in range(qPerKv) %}
|
| 654 |
var runningMax_{{ g }} = -FLT_MAX;
|
| 655 |
var runningDenom_{{ g }} = 0.0;
|
| 656 |
+
{% if pagedHasSink %}
|
| 657 |
+
// A sink is already a scaled logit and enters the global softmax once.
|
| 658 |
+
var sinkBits_{{ g }} = 0xff800000u;
|
| 659 |
+
if (info.valid) { sinkBits_{{ g }} = bitcast<u32>(f32(head_sink[head0 + {{ g }}u])); }
|
| 660 |
+
let sink_{{ g }} = bitcast<f32>(sinkBits_{{ g }});
|
| 661 |
+
let badSink_{{ g }} = (sinkBits_{{ g }} & 0x7fffffffu) > 0x7f800000u || sinkBits_{{ g }} == 0x7f800000u;
|
| 662 |
+
if (info.valid{% if splitK %} && split == 0u{% endif %} && sinkBits_{{ g }} != 0xff800000u) {
|
| 663 |
+
// Poisoned sinks are propagated explicitly below, avoiding Inf-Inf and
|
| 664 |
+
// differing empty-denominator epilogues between split and unsplit paths.
|
| 665 |
+
runningMax_{{ g }} = select(sink_{{ g }}, 0.0, badSink_{{ g }});
|
| 666 |
+
runningDenom_{{ g }} = 1.0;
|
| 667 |
+
}
|
| 668 |
+
{% endif %}
|
| 669 |
{% endfor %}
|
| 670 |
|
| 671 |
var tileBase: u32 = {{ keyLo }};
|
|
|
|
| 674 |
break;
|
| 675 |
}
|
| 676 |
let kj = tileBase + tid;
|
| 677 |
+
var keyAllowed = kj < {{ keyHi }};
|
| 678 |
+
var physical_block = -1i;
|
| 679 |
+
if (keyAllowed) {
|
| 680 |
+
physical_block = block_table[sequence * MAX_BLOCKS + kj / BLOCK_SIZE];
|
| 681 |
+
keyAllowed = physical_block >= 0 && u32(physical_block) < NUM_BLOCKS;
|
| 682 |
+
}
|
| 683 |
+
key_rows[tid] = 0xffffffffu;
|
| 684 |
|
| 685 |
{% for g in range(qPerKv) %}
|
| 686 |
var score_{{ g }} = -FLT_MAX;
|
| 687 |
{% endfor %}
|
| 688 |
if (keyAllowed) {
|
| 689 |
+
let block_id = u32(physical_block);
|
| 690 |
let row = paged_row_base(block_id, kj % BLOCK_SIZE, kv_head);
|
| 691 |
key_rows[tid] = row;
|
| 692 |
{% for g in range(qPerKv) %}
|
|
|
|
| 713 |
score_{{ g }} = acc_{{ g }} * scale;
|
| 714 |
{% endfor %}
|
| 715 |
}
|
| 716 |
+
{% if pagedSubgroupFold %}
|
| 717 |
+
combine_partials_streams(tid, sgId, foldCount, select(0.0, 1.0, keyAllowed)
|
| 718 |
+
{% for g in range(qPerKv) %}
|
| 719 |
+
, score_{{ g }}
|
| 720 |
+
{% endfor %}
|
| 721 |
+
);
|
| 722 |
+
{% else %}
|
| 723 |
// All Q_PER_KV reductions ride one barrier tree.
|
| 724 |
{% for g in range(qPerKv) %}
|
| 725 |
partialM[{{ g }}u * WG + tid] = score_{{ g }};
|
| 726 |
partialD[{{ g }}u * WG + tid] = select(0.0, 1.0, keyAllowed);
|
| 727 |
{% endfor %}
|
| 728 |
combine_partials_streams(tid);
|
| 729 |
+
{% endif %}
|
| 730 |
{% for g in range(qPerKv) %}
|
| 731 |
let tile_{{ g }} = vec2<f32>(partialM[{{ g }}u * WG], partialD[{{ g }}u * WG]);
|
| 732 |
{% endfor %}
|
|
|
|
| 751 |
{% endfor %}
|
| 752 |
// One cache read, every query head in the group, exactly as the scores.
|
| 753 |
for (var i: u32 = 0u; i < tileCount; i = i + 1u) {
|
| 754 |
+
// Excluded blocks have no value load: multiplying zero by an unrelated
|
| 755 |
+
// non-finite cache value would still contaminate the result.
|
| 756 |
+
if (key_rows[i] == 0xffffffffu) { continue; }
|
| 757 |
{% if cacheVec4Ok %}
|
| 758 |
let vv = vec4<f32>(value_cache[key_rows[i] / 4u + dv]);
|
| 759 |
{% else %}
|
|
|
|
| 764 |
{% endfor %}
|
| 765 |
}
|
| 766 |
{% for g in range(qPerKv) %}
|
| 767 |
+
running_out[{% if privateOutput %}{{ g * outputParts }}u + dv / WG{% else %}{{ g }}u * {{ W }} + dv{% endif %}] = running_out[{% if privateOutput %}{{ g * outputParts }}u + dv / WG{% else %}{{ g }}u * {{ W }} + dv{% endif %}] * correction_{{ g }} + vSum_{{ g }};
|
| 768 |
{% endfor %}
|
| 769 |
}
|
| 770 |
// Orders this tile's probs and key_rows reads before the next tile writes them.
|
|
|
|
| 780 |
{% for g in range(qPerKv) %}
|
| 781 |
{
|
| 782 |
let slot_{{ g }} = (token * Q_HEADS + head0 + {{ g }}u) * NUM_SPLITS + split;
|
| 783 |
+
let pBase_{{ g }} = slot_{{ g }} * {% if pagedHasSink %}(HEAD_VEC + 1u){% else %}HEAD_VEC{% endif %};
|
| 784 |
for (var dv: u32 = tid; dv < HEAD_VEC; dv = dv + WG) {
|
| 785 |
+
partial_out[pBase_{{ g }} + dv] = {% if pagedHasSink %}select(running_out[{{ g }}u * HEAD_VEC + dv], vec4<f32>(bitcast<f32>(sinkBits_{{ g }} | 0x7fc00000u)), badSink_{{ g }}){% else %}running_out[{{ g }}u * HEAD_VEC + dv]{% endif %};
|
| 786 |
}
|
| 787 |
if (tid == 0u) {
|
| 788 |
+
{% if pagedHasSink %}
|
| 789 |
+
// Inline statistics keep the sink-bearing pass within eight storage bindings.
|
| 790 |
+
// A poisoned sink takes precedence even over nonfinite QK scores. Keep
|
| 791 |
+
// the merge denominator finite so its empty-row guard cannot hide NaN.
|
| 792 |
+
let storedStats_{{ g }} = select(vec2<f32>(runningMax_{{ g }}, runningDenom_{{ g }}),
|
| 793 |
+
vec2<f32>(0.0, select(0.0, 1.0, split == 0u)), badSink_{{ g }});
|
| 794 |
+
partial_out[pBase_{{ g }} + HEAD_VEC] = vec4<f32>(storedStats_{{ g }}, 0.0, 0.0);
|
| 795 |
+
{% else %}
|
| 796 |
partial_stats[slot_{{ g }}] = vec2<f32>(runningMax_{{ g }}, runningDenom_{{ g }});
|
| 797 |
+
{% endif %}
|
| 798 |
}
|
| 799 |
}
|
| 800 |
{% endfor %}
|
| 801 |
}
|
| 802 |
{% else %}
|
| 803 |
+
// Guard empty ranges, excluded physical blocks and non-finite score rows
|
| 804 |
+
// so a zero denominator produces zero output.
|
| 805 |
{% for g in range(qPerKv) %}
|
| 806 |
let invDenom_{{ g }} = select(0.0, 1.0 / runningDenom_{{ g }}, runningDenom_{{ g }} > 0.0);
|
| 807 |
{% endfor %}
|
| 808 |
for (var dv: u32 = tid; dv < {{ W }}; dv = dv + WG) {
|
| 809 |
{% for g in range(qPerKv) %}
|
| 810 |
{
|
| 811 |
+
let out_v = {% if pagedHasSink %}select(running_out[{% if privateOutput %}{{ g * outputParts }}u + dv / WG{% else %}{{ g }}u * {{ W }} + dv{% endif %}] * invDenom_{{ g }}, {{ "vec4<f32>" if cacheVec4Ok else "f32" }}(bitcast<f32>(sinkBits_{{ g }} | 0x7fc00000u)), badSink_{{ g }}){% else %}running_out[{% if privateOutput %}{{ g * outputParts }}u + dv / WG{% else %}{{ g }}u * {{ W }} + dv{% endif %}] * invDenom_{{ g }}{% endif %};
|
| 812 |
{% if cacheVec4Ok %}
|
| 813 |
let ob = token * {{ qHidden }}u + (head0 + {{ g }}u) * HEAD_DIM + dv * 4u;
|
| 814 |
output[ob] = {{ scalar }}(out_v.x);
|
|
|
|
| 823 |
}
|
| 824 |
}
|
| 825 |
{% endif %}
|
| 826 |
+
{% endif %}
|
build/webgpu/paged-qknorm.wgsl.jinja
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
|
| 2 |
+
{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
|
| 3 |
+
// 2D-folded flat index: gid.y carries the high bits past the dispatch's
|
| 4 |
+
// per-axis workgroup fold width.
|
| 5 |
+
let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
|
| 6 |
+
{% endmacro %}
|
| 7 |
+
{% if normFused and pagedDoRotary %}
|
| 8 |
+
{% macro rotary_pair(interleaved) %}
|
| 9 |
+
// Which cos/sin entry a component uses, and which member of its rotation pair it is.
|
| 10 |
+
// The two layouts differ only here: the NeoX split pairs d with d + ROTARY_HALF, and the
|
| 11 |
+
// interleaved layout pairs the even lane with the odd one beside it.
|
| 12 |
+
fn rotary_slot(d: u32) -> u32 {
|
| 13 |
+
{% if interleaved %}
|
| 14 |
+
return d / 2u;
|
| 15 |
+
{% else %}
|
| 16 |
+
return select(d - ROTARY_HALF, d, d < ROTARY_HALF);
|
| 17 |
+
{% endif %}
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
fn rotary_partner(d: u32) -> u32 {
|
| 21 |
+
{% if interleaved %}
|
| 22 |
+
return select(d - 1u, d + 1u, (d % 2u) == 0u);
|
| 23 |
+
{% else %}
|
| 24 |
+
return select(d - ROTARY_HALF, d + ROTARY_HALF, d < ROTARY_HALF);
|
| 25 |
+
{% endif %}
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
fn rotary_is_first(d: u32) -> bool {
|
| 29 |
+
{% if interleaved %}
|
| 30 |
+
return (d % 2u) == 0u;
|
| 31 |
+
{% else %}
|
| 32 |
+
return d < ROTARY_HALF;
|
| 33 |
+
{% endif %}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
// One component of the rotation, written from the component's own point of view so a
|
| 37 |
+
// single expression covers both members of the pair: the leading one subtracts its
|
| 38 |
+
// partner's sine term, the trailing one adds it.
|
| 39 |
+
fn rotary_value(own: f32, partner: f32, cs: f32, sn: f32, first: bool) -> f32 {
|
| 40 |
+
return select(own * cs + partner * sn, own * cs - partner * sn, first);
|
| 41 |
+
}
|
| 42 |
+
{% endmacro %}
|
| 43 |
+
{% endif %}
|
| 44 |
+
{{ env.wgsl.resourceDeclarations }}
|
| 45 |
+
{% if normFused and pagedDoRotary %}fn round_f16_bits_rte(value: f32) -> u32 {
|
| 46 |
+
let bits = bitcast<u32>(value);
|
| 47 |
+
let sign = (bits >> 16u) & 0x8000u;
|
| 48 |
+
let exponent_f32 = (bits >> 23u) & 0xffu;
|
| 49 |
+
let mantissa_f32 = bits & 0x7fffffu;
|
| 50 |
+
|
| 51 |
+
if (exponent_f32 == 0xffu) {
|
| 52 |
+
if (mantissa_f32 != 0u) {
|
| 53 |
+
return 0x7e00u;
|
| 54 |
+
}
|
| 55 |
+
return sign | 0x7c00u;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
var exponent_f16 = i32(exponent_f32) - 127 + 15;
|
| 59 |
+
if (exponent_f16 >= 0x1f) {
|
| 60 |
+
return sign | 0x7c00u;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
if (exponent_f16 <= 0) {
|
| 64 |
+
if (exponent_f16 < -10) {
|
| 65 |
+
return sign;
|
| 66 |
+
}
|
| 67 |
+
let significand = mantissa_f32 | 0x800000u;
|
| 68 |
+
let shift = u32(14 - exponent_f16);
|
| 69 |
+
let halfway = 1u << (shift - 1u);
|
| 70 |
+
let discarded = significand & ((1u << shift) - 1u);
|
| 71 |
+
var fraction = significand >> shift;
|
| 72 |
+
if (discarded > halfway || (discarded == halfway && (fraction & 1u) == 1u)) {
|
| 73 |
+
fraction = fraction + 1u;
|
| 74 |
+
}
|
| 75 |
+
return sign | fraction;
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
let halfway = 1u << 12u;
|
| 79 |
+
let discarded = mantissa_f32 & 0x1fffu;
|
| 80 |
+
var mantissa_f16 = mantissa_f32 >> 13u;
|
| 81 |
+
if (discarded > halfway || (discarded == halfway && (mantissa_f16 & 1u) == 1u)) {
|
| 82 |
+
mantissa_f16 = mantissa_f16 + 1u;
|
| 83 |
+
if (mantissa_f16 == 0x400u) {
|
| 84 |
+
mantissa_f16 = 0u;
|
| 85 |
+
exponent_f16 = exponent_f16 + 1;
|
| 86 |
+
}
|
| 87 |
+
}
|
| 88 |
+
if (exponent_f16 >= 0x1f) {
|
| 89 |
+
return sign | 0x7c00u;
|
| 90 |
+
}
|
| 91 |
+
return sign | (u32(exponent_f16) << 10u) | mantissa_f16;
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
fn widen_f16_bits(value: u32) -> f32 {
|
| 95 |
+
return unpack2x16float(value & 0xffffu).x;
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
// Typed ONNX edges must survive arithmetic fusion and narrow/wide casts.
|
| 99 |
+
// Integer rounding also fixes the ties-to-even rule independently of the
|
| 100 |
+
// implementation's floating-point conversion rounding mode.
|
| 101 |
+
fn half_stage(value: f32) -> f32 {
|
| 102 |
+
return widen_f16_bits(round_f16_bits_rte(value));
|
| 103 |
+
}
|
| 104 |
+
{% endif %}
|
| 105 |
+
{% if normFused and pagedDoRotary %}
|
| 106 |
+
const ROTARY_HALF: u32 = {{ pagedRotaryHalf }}u;
|
| 107 |
+
const ROTARY_DIM: u32 = {{ 2 * pagedRotaryHalf }}u;
|
| 108 |
+
{% macro varlen_sequence_of_token(buffer="cumulative_sequence_length", binarySearch=false) %}
|
| 109 |
+
fn sequence_of_token(token: u32, batch_size: u32) -> u32 {
|
| 110 |
+
{% if binarySearch %}
|
| 111 |
+
var lo = 0u;
|
| 112 |
+
var hi = batch_size;
|
| 113 |
+
while (lo < hi) {
|
| 114 |
+
let mid = lo + (hi - lo) / 2u;
|
| 115 |
+
if (token < u32({{ buffer }}[mid + 1u])) {
|
| 116 |
+
hi = mid;
|
| 117 |
+
} else {
|
| 118 |
+
lo = mid + 1u;
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
return min(lo, batch_size - 1u);
|
| 122 |
+
{% else %}
|
| 123 |
+
for (var b: u32 = 0u; b < batch_size; b = b + 1u) {
|
| 124 |
+
if (token < u32({{ buffer }}[b + 1u])) {
|
| 125 |
+
return b;
|
| 126 |
+
}
|
| 127 |
+
}
|
| 128 |
+
return batch_size - 1u;
|
| 129 |
+
{% endif %}
|
| 130 |
+
}{% endmacro %}
|
| 131 |
+
{% macro paged_sequence_index(withLookup=true, attentionMask=false, withRowBase=true) %}
|
| 132 |
+
{{ varlen_sequence_of_token(binarySearch=pagedBinarySequenceLookup) }}
|
| 133 |
+
|
| 134 |
+
struct PagedToken {
|
| 135 |
+
sequence: u32,
|
| 136 |
+
keyBound: u32,
|
| 137 |
+
{% if attentionMask and pagedLocalWindow > 0 %}
|
| 138 |
+
keyStart: u32,
|
| 139 |
+
{% endif %}
|
| 140 |
+
valid: bool,
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
// Validate the signed prefix before the lookup casts any endpoint. A malformed
|
| 144 |
+
// prefix disables derived appends and attention for the whole call. Empty
|
| 145 |
+
// requests are legal. No device metadata is copied back to the host.
|
| 146 |
+
fn paged_token_of(token: u32, batchSize: u32) -> PagedToken {
|
| 147 |
+
var info: PagedToken;
|
| 148 |
+
if (cumulative_sequence_length[0] != 0
|
| 149 |
+
|| cumulative_sequence_length[batchSize] != {{ tokenCount }}i) { return info; }
|
| 150 |
+
var previous = 0i;
|
| 151 |
+
for (var b = 1u; b <= batchSize; b++) {
|
| 152 |
+
let end = cumulative_sequence_length[b];
|
| 153 |
+
if (end < previous || end > {{ tokenCount }}i) { return info; }
|
| 154 |
+
previous = end;
|
| 155 |
+
}
|
| 156 |
+
let sequence = sequence_of_token(token, batchSize);
|
| 157 |
+
let start = u32(cumulative_sequence_length[sequence]);
|
| 158 |
+
let end = u32(cumulative_sequence_length[sequence + 1u]);
|
| 159 |
+
let past = past_seqlens[sequence];
|
| 160 |
+
if (token < start || token >= end || past < 0 || u32(past) > {{ pagedKeyCeiling }}u) { return info; }
|
| 161 |
+
// Bound the complete append interval before subtracting or adding. A request
|
| 162 |
+
// that cannot fit this call's tokens is left intact, rather than half updated.
|
| 163 |
+
if (end - start > {{ pagedKeyCeiling }}u - u32(past)) { return info; }
|
| 164 |
+
{% if pagedDoRotary %}
|
| 165 |
+
// Reject the entire append before any rotary cache lookup or cache write.
|
| 166 |
+
if (u32(past) > {{ pagedRotaryRows }}u
|
| 167 |
+
|| end - start > {{ pagedRotaryRows }}u - u32(past)) { return info; }
|
| 168 |
+
{% endif %}
|
| 169 |
+
info.sequence = sequence;
|
| 170 |
+
{% if attentionMask and not pagedIsCausal %}
|
| 171 |
+
// Non-causal attention sees all live keys. Scatter keeps the token's own
|
| 172 |
+
// absolute slot by using this helper without attentionMask.
|
| 173 |
+
info.keyBound = u32(past) + (end - start);
|
| 174 |
+
{% else %}
|
| 175 |
+
info.keyBound = u32(past) + (token - start) + 1u;
|
| 176 |
+
{% endif %}
|
| 177 |
+
{% if attentionMask and pagedLocalWindow > 0 %}
|
| 178 |
+
// The left bound stays relative to this query when future keys are visible.
|
| 179 |
+
// The window constant is clamped before conversion to u32 to prevent wraparound.
|
| 180 |
+
let query_end = u32(past) + (token - start) + 1u;
|
| 181 |
+
info.keyStart = query_end - min(query_end, {{ pagedLocalWindow }}u);
|
| 182 |
+
{% endif %}
|
| 183 |
+
info.valid = true;
|
| 184 |
+
return info;
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
{% endmacro %}
|
| 188 |
+
{{ paged_sequence_index(withRowBase=false) }}
|
| 189 |
+
{{ rotary_pair(pagedRotaryInterleaved) }}
|
| 190 |
+
{% endif %}
|
| 191 |
+
var<workgroup> sums: array<f32, {{ normWg }}>;
|
| 192 |
+
@compute @workgroup_size({{ normWg }})
|
| 193 |
+
fn main(@builtin(workgroup_id) gid: vec3<u32>, @builtin(local_invocation_index) lane: u32) {
|
| 194 |
+
{{ flat_index_2d(1, name="row", bound="") }}
|
| 195 |
+
{% if normFused %}
|
| 196 |
+
if (row >= {{ tokenCount * (numHeads + kvNumHeads) }}u) { return; }
|
| 197 |
+
let token = row / {{ numHeads + kvNumHeads }}u;
|
| 198 |
+
let head = row % {{ numHeads + kvNumHeads }}u;
|
| 199 |
+
let is_query = head < {{ numHeads }}u;
|
| 200 |
+
let base = select(token * {{ kvHidden }}u + (head - {{ numHeads }}u) * {{ headSize }}u,
|
| 201 |
+
token * {{ qHidden }}u + head * {{ headSize }}u, is_query);
|
| 202 |
+
{% if packedQkv %}
|
| 203 |
+
let raw_base = token * {{ packedStride }}u + head * {{ headSize }}u;
|
| 204 |
+
{% endif %}
|
| 205 |
+
{% else %}
|
| 206 |
+
if (row >= {{ tokenCount * (numHeads if normIsQuery else kvNumHeads) }}u) { return; }
|
| 207 |
+
let base = row * {{ headSize }}u;
|
| 208 |
+
{% if packedQkv %}
|
| 209 |
+
let raw_base = (row / {{ numHeads if normIsQuery else kvNumHeads }}u) * {{ packedStride }}u + (row % {{ numHeads if normIsQuery else kvNumHeads }}u) * {{ headSize }}u + {{ 0 if normIsQuery else qHidden }}u;
|
| 210 |
+
{% endif %}
|
| 211 |
+
{% endif %}
|
| 212 |
+
var sum = 0.0;
|
| 213 |
+
for (var d = lane; d < {{ headSize }}u; d += {{ normWg }}u) {
|
| 214 |
+
{% if normFused %}
|
| 215 |
+
{% if packedQkv %}
|
| 216 |
+
let value = f32(query[raw_base + d]);
|
| 217 |
+
{% else %}
|
| 218 |
+
var value: f32;
|
| 219 |
+
if (is_query) { value = f32(query[base + d]); }
|
| 220 |
+
else { value = f32(key[base + d]); }
|
| 221 |
+
{% endif %}
|
| 222 |
+
{% else %}
|
| 223 |
+
let value = f32(x[{{ "raw_base" if packedQkv else "base" }} + d]);
|
| 224 |
+
{% endif %}
|
| 225 |
+
sum += value * value;
|
| 226 |
+
}
|
| 227 |
+
sums[lane] = sum;
|
| 228 |
+
workgroupBarrier();
|
| 229 |
+
{% for stride in [64, 32, 16, 8, 4, 2, 1] %}
|
| 230 |
+
{% if stride < normWg %}
|
| 231 |
+
if (lane < {{ stride }}u) { sums[lane] += sums[lane + {{ stride }}u]; }
|
| 232 |
+
workgroupBarrier();
|
| 233 |
+
{% endif %}
|
| 234 |
+
{% endfor %}
|
| 235 |
+
let mean_square = sums[0] / {{ headSize }}.0;
|
| 236 |
+
// A zero head remains zero even when the device flushes a subnormal epsilon.
|
| 237 |
+
let inv = select(inverseSqrt(mean_square + norm_params.epsilon), 0.0, mean_square == 0.0);
|
| 238 |
+
{% if normFused and pagedDoRotary %}
|
| 239 |
+
let info = paged_token_of(token, {{ batchSize }}u);
|
| 240 |
+
{% endif %}
|
| 241 |
+
for (var d = lane; d < {{ headSize }}u; d += {{ normWg }}u) {
|
| 242 |
+
{% if normFused %}
|
| 243 |
+
var rounded: {{ "f32" if pagedDoRotary else "f16" }};
|
| 244 |
+
{% if packedQkv %}
|
| 245 |
+
if (is_query) { rounded = {{ "half_stage" if pagedDoRotary else "f16" }}((f32(query[raw_base + d]) * inv) * f32(q_norm_weight[d])); }
|
| 246 |
+
else { rounded = {{ "half_stage" if pagedDoRotary else "f16" }}((f32(query[raw_base + d]) * inv) * f32(k_norm_weight[d])); }
|
| 247 |
+
{% else %}
|
| 248 |
+
if (is_query) { rounded = {{ "half_stage" if pagedDoRotary else "f16" }}((f32(query[base + d]) * inv) * f32(q_norm_weight[d])); }
|
| 249 |
+
else { rounded = {{ "half_stage" if pagedDoRotary else "f16" }}((f32(key[base + d]) * inv) * f32(k_norm_weight[d])); }
|
| 250 |
+
{% endif %}
|
| 251 |
+
var result = f32(rounded);
|
| 252 |
+
{% if pagedDoRotary %}
|
| 253 |
+
if (!info.valid) { result = 0.0; }
|
| 254 |
+
else if (d < ROTARY_DIM) {
|
| 255 |
+
let partner_d = rotary_partner(d);
|
| 256 |
+
var partner: f32;
|
| 257 |
+
{% if packedQkv %}
|
| 258 |
+
if (is_query) { partner = half_stage((f32(query[raw_base + partner_d]) * inv) * f32(q_norm_weight[partner_d])); }
|
| 259 |
+
else { partner = half_stage((f32(query[raw_base + partner_d]) * inv) * f32(k_norm_weight[partner_d])); }
|
| 260 |
+
{% else %}
|
| 261 |
+
if (is_query) { partner = half_stage((f32(query[base + partner_d]) * inv) * f32(q_norm_weight[partner_d])); }
|
| 262 |
+
else { partner = half_stage((f32(key[base + partner_d]) * inv) * f32(k_norm_weight[partner_d])); }
|
| 263 |
+
{% endif %}
|
| 264 |
+
let cache = (info.keyBound - 1u) * ROTARY_HALF + rotary_slot(d);
|
| 265 |
+
result = rotary_value(result, f32(partner), f32(cos_cache[cache]), f32(sin_cache[cache]), rotary_is_first(d));
|
| 266 |
+
}
|
| 267 |
+
{% endif %}
|
| 268 |
+
if (is_query) { q_normalized[base + d] = f16(result); }
|
| 269 |
+
else { k_normalized[base + d] = f16(result); }
|
| 270 |
+
{% else %}
|
| 271 |
+
normalized[base + d] = f16((f32(x[{{ "raw_base" if packedQkv else "base" }} + d]) * inv) * f32(gamma[d]));
|
| 272 |
+
{% endif %}
|
| 273 |
+
}
|
| 274 |
+
}
|
build/webgpu/paged-rotary-qk.wgsl.jinja
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
|
| 2 |
+
{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
|
| 3 |
+
// 2D-folded flat index: gid.y carries the high bits past the dispatch's
|
| 4 |
+
// per-axis workgroup fold width.
|
| 5 |
+
let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
|
| 6 |
+
if ({{ name }} >= {{ bound }}) {
|
| 7 |
+
return;
|
| 8 |
+
}
|
| 9 |
+
{% endmacro %}
|
| 10 |
+
{% macro rotary_pair(interleaved) %}
|
| 11 |
+
// Which cos/sin entry a component uses, and which member of its rotation pair it is.
|
| 12 |
+
// The two layouts differ only here: the NeoX split pairs d with d + ROTARY_HALF, and the
|
| 13 |
+
// interleaved layout pairs the even lane with the odd one beside it.
|
| 14 |
+
fn rotary_slot(d: u32) -> u32 {
|
| 15 |
+
{% if interleaved %}
|
| 16 |
+
return d / 2u;
|
| 17 |
+
{% else %}
|
| 18 |
+
return select(d - ROTARY_HALF, d, d < ROTARY_HALF);
|
| 19 |
+
{% endif %}
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
fn rotary_partner(d: u32) -> u32 {
|
| 23 |
+
{% if interleaved %}
|
| 24 |
+
return select(d - 1u, d + 1u, (d % 2u) == 0u);
|
| 25 |
+
{% else %}
|
| 26 |
+
return select(d - ROTARY_HALF, d + ROTARY_HALF, d < ROTARY_HALF);
|
| 27 |
+
{% endif %}
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
fn rotary_is_first(d: u32) -> bool {
|
| 31 |
+
{% if interleaved %}
|
| 32 |
+
return (d % 2u) == 0u;
|
| 33 |
+
{% else %}
|
| 34 |
+
return d < ROTARY_HALF;
|
| 35 |
+
{% endif %}
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
// One component of the rotation, written from the component's own point of view so a
|
| 39 |
+
// single expression covers both members of the pair: the leading one subtracts its
|
| 40 |
+
// partner's sine term, the trailing one adds it.
|
| 41 |
+
fn rotary_value(own: f32, partner: f32, cs: f32, sn: f32, first: bool) -> f32 {
|
| 42 |
+
return select(own * cs + partner * sn, own * cs - partner * sn, first);
|
| 43 |
+
}
|
| 44 |
+
{% endmacro %}
|
| 45 |
+
{{ env.wgsl.resourceDeclarations }}
|
| 46 |
+
|
| 47 |
+
// Rotate only this call's Q/K. Materialize f16 before FP32 attention; V and
|
| 48 |
+
// already-rotated cache history are untouched. Separate Q/K uses eight storage
|
| 49 |
+
// bindings; packed QKV uses seven, without an intermediate V copy.
|
| 50 |
+
const HEAD_DIM: u32 = {{ headSize }}u;
|
| 51 |
+
const ROTARY_HALF: u32 = {{ pagedRotaryHalf }}u;
|
| 52 |
+
const ROTARY_DIM: u32 = {{ 2 * pagedRotaryHalf }}u;
|
| 53 |
+
const Q_STRIDE: u32 = {{ packedStride if packedQkv and not pagedDoNorm else qHidden }}u;
|
| 54 |
+
const ROW_WIDTH: u32 = {{ qHidden + kvHidden }}u;
|
| 55 |
+
|
| 56 |
+
{% macro varlen_sequence_of_token(buffer="cumulative_sequence_length", binarySearch=false) %}
|
| 57 |
+
fn sequence_of_token(token: u32, batch_size: u32) -> u32 {
|
| 58 |
+
{% if binarySearch %}
|
| 59 |
+
var lo = 0u;
|
| 60 |
+
var hi = batch_size;
|
| 61 |
+
while (lo < hi) {
|
| 62 |
+
let mid = lo + (hi - lo) / 2u;
|
| 63 |
+
if (token < u32({{ buffer }}[mid + 1u])) {
|
| 64 |
+
hi = mid;
|
| 65 |
+
} else {
|
| 66 |
+
lo = mid + 1u;
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
return min(lo, batch_size - 1u);
|
| 70 |
+
{% else %}
|
| 71 |
+
for (var b: u32 = 0u; b < batch_size; b = b + 1u) {
|
| 72 |
+
if (token < u32({{ buffer }}[b + 1u])) {
|
| 73 |
+
return b;
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
return batch_size - 1u;
|
| 77 |
+
{% endif %}
|
| 78 |
+
}{% endmacro %}
|
| 79 |
+
{% macro paged_sequence_index(withLookup=true, attentionMask=false, withRowBase=true) %}
|
| 80 |
+
{{ varlen_sequence_of_token(binarySearch=pagedBinarySequenceLookup) }}
|
| 81 |
+
|
| 82 |
+
struct PagedToken {
|
| 83 |
+
sequence: u32,
|
| 84 |
+
keyBound: u32,
|
| 85 |
+
{% if attentionMask and pagedLocalWindow > 0 %}
|
| 86 |
+
keyStart: u32,
|
| 87 |
+
{% endif %}
|
| 88 |
+
valid: bool,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
// Validate the signed prefix before the lookup casts any endpoint. A malformed
|
| 92 |
+
// prefix disables derived appends and attention for the whole call. Empty
|
| 93 |
+
// requests are legal. No device metadata is copied back to the host.
|
| 94 |
+
fn paged_token_of(token: u32, batchSize: u32) -> PagedToken {
|
| 95 |
+
var info: PagedToken;
|
| 96 |
+
if (cumulative_sequence_length[0] != 0
|
| 97 |
+
|| cumulative_sequence_length[batchSize] != {{ tokenCount }}i) { return info; }
|
| 98 |
+
var previous = 0i;
|
| 99 |
+
for (var b = 1u; b <= batchSize; b++) {
|
| 100 |
+
let end = cumulative_sequence_length[b];
|
| 101 |
+
if (end < previous || end > {{ tokenCount }}i) { return info; }
|
| 102 |
+
previous = end;
|
| 103 |
+
}
|
| 104 |
+
let sequence = sequence_of_token(token, batchSize);
|
| 105 |
+
let start = u32(cumulative_sequence_length[sequence]);
|
| 106 |
+
let end = u32(cumulative_sequence_length[sequence + 1u]);
|
| 107 |
+
let past = past_seqlens[sequence];
|
| 108 |
+
if (token < start || token >= end || past < 0 || u32(past) > {{ pagedKeyCeiling }}u) { return info; }
|
| 109 |
+
// Bound the complete append interval before subtracting or adding. A request
|
| 110 |
+
// that cannot fit this call's tokens is left intact, rather than half updated.
|
| 111 |
+
if (end - start > {{ pagedKeyCeiling }}u - u32(past)) { return info; }
|
| 112 |
+
{% if pagedDoRotary %}
|
| 113 |
+
// Reject the entire append before any rotary cache lookup or cache write.
|
| 114 |
+
if (u32(past) > {{ pagedRotaryRows }}u
|
| 115 |
+
|| end - start > {{ pagedRotaryRows }}u - u32(past)) { return info; }
|
| 116 |
+
{% endif %}
|
| 117 |
+
info.sequence = sequence;
|
| 118 |
+
{% if attentionMask and not pagedIsCausal %}
|
| 119 |
+
// Non-causal attention sees all live keys. Scatter keeps the token's own
|
| 120 |
+
// absolute slot by using this helper without attentionMask.
|
| 121 |
+
info.keyBound = u32(past) + (end - start);
|
| 122 |
+
{% else %}
|
| 123 |
+
info.keyBound = u32(past) + (token - start) + 1u;
|
| 124 |
+
{% endif %}
|
| 125 |
+
{% if attentionMask and pagedLocalWindow > 0 %}
|
| 126 |
+
// The left bound stays relative to this query when future keys are visible.
|
| 127 |
+
// The window constant is clamped before conversion to u32 to prevent wraparound.
|
| 128 |
+
let query_end = u32(past) + (token - start) + 1u;
|
| 129 |
+
info.keyStart = query_end - min(query_end, {{ pagedLocalWindow }}u);
|
| 130 |
+
{% endif %}
|
| 131 |
+
info.valid = true;
|
| 132 |
+
return info;
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
{% endmacro %}
|
| 136 |
+
{{ paged_sequence_index(withRowBase=false) }}
|
| 137 |
+
{{ rotary_pair(pagedRotaryInterleaved) }}
|
| 138 |
+
@compute @workgroup_size({{ tunables.SCATTER_WORKGROUP_SIZE }})
|
| 139 |
+
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
| 140 |
+
{{ flat_index_2d(tunables.SCATTER_WORKGROUP_SIZE, bound="params.rotaryCount") }}
|
| 141 |
+
let token = i / ROW_WIDTH;
|
| 142 |
+
let col = i % ROW_WIDTH;
|
| 143 |
+
let isQuery = col < {{ qHidden }}u;
|
| 144 |
+
let info = paged_token_of(token, params.batchSize);
|
| 145 |
+
if (!info.valid) {
|
| 146 |
+
if (isQuery) { q_rotary[token * {{ qHidden }}u + col] = 0.0; }
|
| 147 |
+
else { k_rotary[token * {{ kvHidden }}u + col - {{ qHidden }}u] = 0.0; }
|
| 148 |
+
return;
|
| 149 |
+
}
|
| 150 |
+
let d = col % HEAD_DIM;
|
| 151 |
+
let position = info.keyBound - 1u;
|
| 152 |
+
var own: f32;
|
| 153 |
+
var partner: f32;
|
| 154 |
+
if (isQuery) {
|
| 155 |
+
let base = token * Q_STRIDE + col - d;
|
| 156 |
+
own = f32(query[base + d]);
|
| 157 |
+
if (d < ROTARY_DIM) { partner = f32(query[base + rotary_partner(d)]); }
|
| 158 |
+
} else {
|
| 159 |
+
{% if packedQkv and not pagedDoNorm %}
|
| 160 |
+
let base = token * Q_STRIDE + col - d;
|
| 161 |
+
own = f32(query[base + d]);
|
| 162 |
+
if (d < ROTARY_DIM) { partner = f32(query[base + rotary_partner(d)]); }
|
| 163 |
+
{% else %}
|
| 164 |
+
let base = token * {{ kvHidden }}u + col - {{ qHidden }}u - d;
|
| 165 |
+
own = f32(key[base + d]);
|
| 166 |
+
if (d < ROTARY_DIM) { partner = f32(key[base + rotary_partner(d)]); }
|
| 167 |
+
{% endif %}
|
| 168 |
+
}
|
| 169 |
+
var result = own;
|
| 170 |
+
if (d < ROTARY_DIM) {
|
| 171 |
+
let cache = position * ROTARY_HALF + rotary_slot(d);
|
| 172 |
+
result = rotary_value(own, partner, f32(cos_cache[cache]), f32(sin_cache[cache]), rotary_is_first(d));
|
| 173 |
+
}
|
| 174 |
+
if (isQuery) { q_rotary[token * {{ qHidden }}u + col] = {{ scalar }}(result); }
|
| 175 |
+
else { k_rotary[token * {{ kvHidden }}u + col - {{ qHidden }}u] = {{ scalar }}(result); }
|
| 176 |
+
}
|
build/webgpu/paged-scatter-kv.wgsl.jinja
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
-
{% macro flat_index_2d(workgroupSize, name="i", bound="params.count"
|
| 2 |
{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
|
| 3 |
// 2D-folded flat index: gid.y carries the high bits past the dispatch's
|
| 4 |
// per-axis workgroup fold width.
|
| 5 |
let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
|
| 6 |
if ({{ name }} >= {{ bound }}) {
|
| 7 |
return;
|
| 8 |
-
}
|
|
|
|
| 9 |
{{ env.wgsl.resourceDeclarations }}
|
| 10 |
|
| 11 |
// com.microsoft.PagedAttention, KV scatter pass.
|
|
@@ -15,6 +16,7 @@
|
|
| 15 |
const KV_HEADS: u32 = {{ kvNumHeads }}u;
|
| 16 |
const HEAD_DIM: u32 = {{ headSize }}u;
|
| 17 |
const BLOCK_SIZE: u32 = {{ blockSize }}u;
|
|
|
|
| 18 |
{% if not hasSlotMapping %}
|
| 19 |
const MAX_BLOCKS: u32 = {{ maxBlocks }}u;
|
| 20 |
{% endif %}
|
|
@@ -22,24 +24,93 @@ const MAX_BLOCKS: u32 = {{ maxBlocks }}u;
|
|
| 22 |
// Packed layout: query carries [Q | K | V] on one row, so K starts after the
|
| 23 |
// query heads and V after the key heads.
|
| 24 |
const PACKED_STRIDE: u32 = {{ packedStride }}u;
|
|
|
|
| 25 |
const PACKED_K_OFFSET: u32 = {{ qHidden }}u;
|
|
|
|
| 26 |
const PACKED_V_OFFSET: u32 = {{ qHidden }}u + {{ kvHidden }}u;
|
| 27 |
{% else %}
|
| 28 |
const KV_STRIDE: u32 = {{ kvHidden }}u;
|
| 29 |
{% endif %}
|
| 30 |
|
| 31 |
-
{% macro varlen_sequence_of_token(buffer="cumulative_sequence_length") %}
|
| 32 |
fn sequence_of_token(token: u32, batch_size: u32) -> u32 {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
for (var b: u32 = 0u; b < batch_size; b = b + 1u) {
|
| 34 |
if (token < u32({{ buffer }}[b + 1u])) {
|
| 35 |
return b;
|
| 36 |
}
|
| 37 |
}
|
| 38 |
return batch_size - 1u;
|
|
|
|
| 39 |
}{% endmacro %}
|
| 40 |
-
{% macro paged_sequence_index(withLookup=true) %}
|
| 41 |
{% if withLookup %}
|
| 42 |
-
{{ varlen_sequence_of_token() }}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
{% endif %}
|
| 45 |
// Physical element base of one (slot, kv head) row of the paged cache, whose
|
|
@@ -48,7 +119,7 @@ fn paged_row_base(block_id: u32, slot_in_block: u32, kv_head: u32) -> u32 {
|
|
| 48 |
return ((block_id * BLOCK_SIZE + slot_in_block) * KV_HEADS + kv_head) * HEAD_DIM;
|
| 49 |
}
|
| 50 |
{% endmacro %}
|
| 51 |
-
{{ paged_sequence_index(withLookup=not hasSlotMapping) }}
|
| 52 |
@compute @workgroup_size({{ tunables.SCATTER_WORKGROUP_SIZE }})
|
| 53 |
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
| 54 |
{{ flat_index_2d(tunables.SCATTER_WORKGROUP_SIZE, bound="params.scatterCount") }}
|
|
@@ -57,10 +128,14 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
| 57 |
let token = i / (KV_HEADS * HEAD_DIM);
|
| 58 |
|
| 59 |
{% if hasSlotMapping %}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
// `slot_mapping` gives the flat cache slot directly. A negative slot suppresses
|
| 61 |
// this token's cache write; `block_table` still defines the read path.
|
| 62 |
let slot = slot_mapping[token];
|
| 63 |
-
if (slot < 0) {
|
| 64 |
return;
|
| 65 |
}
|
| 66 |
let block_id = u32(slot) / BLOCK_SIZE;
|
|
@@ -68,16 +143,22 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
| 68 |
{% else %}
|
| 69 |
// Derived slot: the token's absolute position in its sequence's cache is the
|
| 70 |
// past length plus its offset among this step's tokens.
|
| 71 |
-
let
|
| 72 |
-
|
| 73 |
-
let absolute_slot =
|
| 74 |
-
let
|
|
|
|
|
|
|
| 75 |
let slot_in_block = absolute_slot % BLOCK_SIZE;
|
| 76 |
{% endif %}
|
| 77 |
|
| 78 |
{% if packedQkv %}
|
| 79 |
let source = token * PACKED_STRIDE + kv_head * HEAD_DIM + dim;
|
|
|
|
|
|
|
|
|
|
| 80 |
let key_value = query[source + PACKED_K_OFFSET];
|
|
|
|
| 81 |
let value_value = query[source + PACKED_V_OFFSET];
|
| 82 |
{% else %}
|
| 83 |
let source = token * KV_STRIDE + kv_head * HEAD_DIM + dim;
|
|
|
|
| 1 |
+
{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
|
| 2 |
{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
|
| 3 |
// 2D-folded flat index: gid.y carries the high bits past the dispatch's
|
| 4 |
// per-axis workgroup fold width.
|
| 5 |
let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
|
| 6 |
if ({{ name }} >= {{ bound }}) {
|
| 7 |
return;
|
| 8 |
+
}
|
| 9 |
+
{% endmacro %}
|
| 10 |
{{ env.wgsl.resourceDeclarations }}
|
| 11 |
|
| 12 |
// com.microsoft.PagedAttention, KV scatter pass.
|
|
|
|
| 16 |
const KV_HEADS: u32 = {{ kvNumHeads }}u;
|
| 17 |
const HEAD_DIM: u32 = {{ headSize }}u;
|
| 18 |
const BLOCK_SIZE: u32 = {{ blockSize }}u;
|
| 19 |
+
const NUM_BLOCKS: u32 = {{ numCacheBlocks }}u;
|
| 20 |
{% if not hasSlotMapping %}
|
| 21 |
const MAX_BLOCKS: u32 = {{ maxBlocks }}u;
|
| 22 |
{% endif %}
|
|
|
|
| 24 |
// Packed layout: query carries [Q | K | V] on one row, so K starts after the
|
| 25 |
// query heads and V after the key heads.
|
| 26 |
const PACKED_STRIDE: u32 = {{ packedStride }}u;
|
| 27 |
+
{% if not pagedDoRotary and not pagedDoNorm %}
|
| 28 |
const PACKED_K_OFFSET: u32 = {{ qHidden }}u;
|
| 29 |
+
{% endif %}
|
| 30 |
const PACKED_V_OFFSET: u32 = {{ qHidden }}u + {{ kvHidden }}u;
|
| 31 |
{% else %}
|
| 32 |
const KV_STRIDE: u32 = {{ kvHidden }}u;
|
| 33 |
{% endif %}
|
| 34 |
|
| 35 |
+
{% macro varlen_sequence_of_token(buffer="cumulative_sequence_length", binarySearch=false) %}
|
| 36 |
fn sequence_of_token(token: u32, batch_size: u32) -> u32 {
|
| 37 |
+
{% if binarySearch %}
|
| 38 |
+
var lo = 0u;
|
| 39 |
+
var hi = batch_size;
|
| 40 |
+
while (lo < hi) {
|
| 41 |
+
let mid = lo + (hi - lo) / 2u;
|
| 42 |
+
if (token < u32({{ buffer }}[mid + 1u])) {
|
| 43 |
+
hi = mid;
|
| 44 |
+
} else {
|
| 45 |
+
lo = mid + 1u;
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
return min(lo, batch_size - 1u);
|
| 49 |
+
{% else %}
|
| 50 |
for (var b: u32 = 0u; b < batch_size; b = b + 1u) {
|
| 51 |
if (token < u32({{ buffer }}[b + 1u])) {
|
| 52 |
return b;
|
| 53 |
}
|
| 54 |
}
|
| 55 |
return batch_size - 1u;
|
| 56 |
+
{% endif %}
|
| 57 |
}{% endmacro %}
|
| 58 |
+
{% macro paged_sequence_index(withLookup=true, attentionMask=false, withRowBase=true) %}
|
| 59 |
{% if withLookup %}
|
| 60 |
+
{{ varlen_sequence_of_token(binarySearch=pagedBinarySequenceLookup) }}
|
| 61 |
+
|
| 62 |
+
struct PagedToken {
|
| 63 |
+
sequence: u32,
|
| 64 |
+
keyBound: u32,
|
| 65 |
+
{% if attentionMask and pagedLocalWindow > 0 %}
|
| 66 |
+
keyStart: u32,
|
| 67 |
+
{% endif %}
|
| 68 |
+
valid: bool,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
// Validate the signed prefix before the lookup casts any endpoint. A malformed
|
| 72 |
+
// prefix disables derived appends and attention for the whole call. Empty
|
| 73 |
+
// requests are legal. No device metadata is copied back to the host.
|
| 74 |
+
fn paged_token_of(token: u32, batchSize: u32) -> PagedToken {
|
| 75 |
+
var info: PagedToken;
|
| 76 |
+
if (cumulative_sequence_length[0] != 0
|
| 77 |
+
|| cumulative_sequence_length[batchSize] != {{ tokenCount }}i) { return info; }
|
| 78 |
+
var previous = 0i;
|
| 79 |
+
for (var b = 1u; b <= batchSize; b++) {
|
| 80 |
+
let end = cumulative_sequence_length[b];
|
| 81 |
+
if (end < previous || end > {{ tokenCount }}i) { return info; }
|
| 82 |
+
previous = end;
|
| 83 |
+
}
|
| 84 |
+
let sequence = sequence_of_token(token, batchSize);
|
| 85 |
+
let start = u32(cumulative_sequence_length[sequence]);
|
| 86 |
+
let end = u32(cumulative_sequence_length[sequence + 1u]);
|
| 87 |
+
let past = past_seqlens[sequence];
|
| 88 |
+
if (token < start || token >= end || past < 0 || u32(past) > {{ pagedKeyCeiling }}u) { return info; }
|
| 89 |
+
// Bound the complete append interval before subtracting or adding. A request
|
| 90 |
+
// that cannot fit this call's tokens is left intact, rather than half updated.
|
| 91 |
+
if (end - start > {{ pagedKeyCeiling }}u - u32(past)) { return info; }
|
| 92 |
+
{% if pagedDoRotary %}
|
| 93 |
+
// Reject the entire append before any rotary cache lookup or cache write.
|
| 94 |
+
if (u32(past) > {{ pagedRotaryRows }}u
|
| 95 |
+
|| end - start > {{ pagedRotaryRows }}u - u32(past)) { return info; }
|
| 96 |
+
{% endif %}
|
| 97 |
+
info.sequence = sequence;
|
| 98 |
+
{% if attentionMask and not pagedIsCausal %}
|
| 99 |
+
// Non-causal attention sees all live keys. Scatter keeps the token's own
|
| 100 |
+
// absolute slot by using this helper without attentionMask.
|
| 101 |
+
info.keyBound = u32(past) + (end - start);
|
| 102 |
+
{% else %}
|
| 103 |
+
info.keyBound = u32(past) + (token - start) + 1u;
|
| 104 |
+
{% endif %}
|
| 105 |
+
{% if attentionMask and pagedLocalWindow > 0 %}
|
| 106 |
+
// The left bound stays relative to this query when future keys are visible.
|
| 107 |
+
// The window constant is clamped before conversion to u32 to prevent wraparound.
|
| 108 |
+
let query_end = u32(past) + (token - start) + 1u;
|
| 109 |
+
info.keyStart = query_end - min(query_end, {{ pagedLocalWindow }}u);
|
| 110 |
+
{% endif %}
|
| 111 |
+
info.valid = true;
|
| 112 |
+
return info;
|
| 113 |
+
}
|
| 114 |
|
| 115 |
{% endif %}
|
| 116 |
// Physical element base of one (slot, kv head) row of the paged cache, whose
|
|
|
|
| 119 |
return ((block_id * BLOCK_SIZE + slot_in_block) * KV_HEADS + kv_head) * HEAD_DIM;
|
| 120 |
}
|
| 121 |
{% endmacro %}
|
| 122 |
+
{{ paged_sequence_index(withLookup=not hasSlotMapping or pagedDoRotary) }}
|
| 123 |
@compute @workgroup_size({{ tunables.SCATTER_WORKGROUP_SIZE }})
|
| 124 |
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
| 125 |
{{ flat_index_2d(tunables.SCATTER_WORKGROUP_SIZE, bound="params.scatterCount") }}
|
|
|
|
| 128 |
let token = i / (KV_HEADS * HEAD_DIM);
|
| 129 |
|
| 130 |
{% if hasSlotMapping %}
|
| 131 |
+
{% if pagedDoRotary %}
|
| 132 |
+
let info = paged_token_of(token, params.batchSize);
|
| 133 |
+
if (!info.valid) { return; }
|
| 134 |
+
{% endif %}
|
| 135 |
// `slot_mapping` gives the flat cache slot directly. A negative slot suppresses
|
| 136 |
// this token's cache write; `block_table` still defines the read path.
|
| 137 |
let slot = slot_mapping[token];
|
| 138 |
+
if (slot < 0 || u32(slot) / BLOCK_SIZE >= NUM_BLOCKS) {
|
| 139 |
return;
|
| 140 |
}
|
| 141 |
let block_id = u32(slot) / BLOCK_SIZE;
|
|
|
|
| 143 |
{% else %}
|
| 144 |
// Derived slot: the token's absolute position in its sequence's cache is the
|
| 145 |
// past length plus its offset among this step's tokens.
|
| 146 |
+
let info = paged_token_of(token, params.batchSize);
|
| 147 |
+
if (!info.valid) { return; }
|
| 148 |
+
let absolute_slot = info.keyBound - 1u;
|
| 149 |
+
let physical_block = block_table[info.sequence * MAX_BLOCKS + absolute_slot / BLOCK_SIZE];
|
| 150 |
+
if (physical_block < 0 || u32(physical_block) >= NUM_BLOCKS) { return; }
|
| 151 |
+
let block_id = u32(physical_block);
|
| 152 |
let slot_in_block = absolute_slot % BLOCK_SIZE;
|
| 153 |
{% endif %}
|
| 154 |
|
| 155 |
{% if packedQkv %}
|
| 156 |
let source = token * PACKED_STRIDE + kv_head * HEAD_DIM + dim;
|
| 157 |
+
{% if pagedDoRotary or pagedDoNorm %}
|
| 158 |
+
let key_value = key[token * {{ kvHidden }}u + kv_head * HEAD_DIM + dim];
|
| 159 |
+
{% else %}
|
| 160 |
let key_value = query[source + PACKED_K_OFFSET];
|
| 161 |
+
{% endif %}
|
| 162 |
let value_value = query[source + PACKED_V_OFFSET];
|
| 163 |
{% else %}
|
| 164 |
let source = token * KV_STRIDE + kv_head * HEAD_DIM + dim;
|
build/webgpu/test.json
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|