sync 4385228f788d
Browse filesFiles changed (9)
- README.md+30-44
- build/webgpu/attn-packed-varlen-cluster.wgsl.jinja+525-34
- build/webgpu/attn-packed-varlen-scalar.wgsl.jinja+432-9
- build/webgpu/gemm-epilogue-tiled-reg.wgsl.jinja+9-4
- build/webgpu/gemm-subgroup-matrix.wgsl.jinja+159-53
- build/webgpu/manifest.json
- build/webgpu/metadata.json+1-61
- build/webgpu/projection-f16.wgsl.jinjaAdded+188
- build/webgpu/test.json+699-16
11 unmodified lines121314151617185 unmodified lines2425262728293025 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271283 unmodified lines13213313413511 unmodified lines## DescriptionSelf-attention with a fused Q/K/V input projection over a padding-removed token stream. The `token_offset` and `cumulative_sequence_length` schedule maps every packed token to its sequence, and a token attends only the keys of that sequence; there is no mask input. The optional attention bias is indexed in PADDED coordinates. The output is 2-D in packed token order. Float32 and float16 only; bfloat16 is not implemented.See the [ONNX Runtime `PackedAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.PackedAttention) for the reference semantics.5 unmodified lines| `weightsT` | `weights` | `T` | same as logical dtype | `2` | — | Merged projection weights with shape `[input_hidden_size, q_hidden + k_hidden + v_hidden]`, column-ordered `[Q all heads \| K all heads \| V all heads]`. | required || `biasT` | `bias` | `T` | same as logical dtype | `1` | — | Required projection bias with shape `[q_hidden + k_hidden + v_hidden]`. | required || `tokenOffsetT` | `token_offset` | `M` | `int32` | `2` | — | Shape `[batch_size, sequence_length]`. The first `token_count` entries hold each packed token's flat index in the padded grid; the rest hold the padding positions. This tensor carries the padded `sequence_length`. | required || `cumulativeSequenceLengthT` | `cumulative_sequence_length` | `M` | `int32` | `1` | — | Exclusive prefix sums with shape `[batch_size + 1]`, starting at 0 and ending at `token_count`. Sequence `i` owns packed tokens `[cum[i], cum[i + 1])`. Outputs are unspecified for a malformed schedule. | required || `attentionBiasT` | `attention_bias` | `T` | same as logical dtype | `4` | — | Optional additive score bias with shape `[batch_size or 1, num_heads or 1, sequence_length, sequence_length]`. Its trailing axes are PADDED positions inside a sequence, not packed indices. | optional |## Outputs25 unmodified lines- `matrix_direct_f32_flash` — Projects with dtype-preserving matrix tiles and direct input reads; a gated staged pass covers partial rows. Attention uses subgroup or portable tiled reductions according to its own resource and lane budget.- `matrix_staged_f32_flash` — Projects with staged 32-row matrix tiles and float32 accumulation, then runs subgroup or portable tiled attention. Small projection grids avoid a separate tail dispatch; both passes retain independent resource guards.- `f32_flash` — Fuses the Q/K/V projection into a register-tiled GEMM, then runs tiled flash attention over the packed token stream: one workgroup covers `CLUSTER_TILE_Q` consecutive tokens for one head and stages `CLUSTER_TILE_K` keys, masking each token to its own sequence. Cluster dot fragments combine through subgroup shuffles.- `matrix_direct_f32_flash_nosg` — Projects with dtype-preserving matrix tiles and direct input reads; a gated staged pass covers partial rows. Attention uses subgroup or portable tiled reductions according to its own resource and lane budget.- `matrix_staged_f32_flash_nosg` — Projects with staged 32-row matrix tiles and float32 accumulation, then runs subgroup or portable tiled attention. Small projection grids avoid a separate tail dispatch; both passes retain independent resource guards.- `f32_flash_nosg` — Projects Q/K/V with the register-tiled GEMM, then performs packed flash attention. Portable clusters distribute dot fragments and softmax work across lanes. Wider heads use more lanes and fewer queries per workgroup; device limits bound geometry and key staging. Four-lane clusters retain the existing reduction.- `matrix_direct_f32_serial` — Projects with dtype-preserving subgroup matrices, direct input reads and double-buffered weights. Float32 uses four accumulation streams. A gated staged pass handles partial rows; sparse grids use smaller staged tiles.- `matrix_staged_f32_serial` — Projects with staged 32-row subgroup-matrix tiles and float32 accumulation before packed attention. Small and partial-row grids avoid an extra projection dispatch; reported matrix configurations, subgroup width and resource limits retain portable fallbacks.- `f32_serial` — Fuses the Q/K/V projection into a register-tiled GEMM, then runs portable serial-key attention: one workgroup owns one (packed token, head) and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.- `matrix_direct_f32_attn_bias_flash` — Projects with dtype-preserving matrix tiles and direct input reads; a gated staged pass covers partial rows. Attention uses subgroup or portable tiled reductions according to its own resource and lane budget.- `matrix_staged_f32_attn_bias_flash` — Projects with staged 32-row matrix tiles and float32 accumulation, then runs subgroup or portable tiled attention. Small projection grids avoid a separate tail dispatch; both passes retain independent resource guards.- `f32_attn_bias_flash` — Fuses the Q/K/V projection into a register-tiled GEMM, then runs tiled flash attention over the packed token stream: one workgroup covers `CLUSTER_TILE_Q` consecutive tokens for one head and stages `CLUSTER_TILE_K` keys, masking each token to its own sequence. Cluster dot fragments combine through subgroup shuffles.- `matrix_direct_f32_attn_bias_flash_nosg` — Projects with dtype-preserving matrix tiles and direct input reads; a gated staged pass covers partial rows. Attention uses subgroup or portable tiled reductions according to its own resource and lane budget.- `matrix_staged_f32_attn_bias_flash_nosg` — Projects with staged 32-row matrix tiles and float32 accumulation, then runs subgroup or portable tiled attention. Small projection grids avoid a separate tail dispatch; both passes retain independent resource guards.- `f32_attn_bias_flash_nosg` — Projects Q/K/V with the register-tiled GEMM, then performs packed flash attention. Portable clusters distribute dot fragments and softmax work across lanes. Wider heads use more lanes and fewer queries per workgroup; device limits bound geometry and key staging. Four-lane clusters retain the existing reduction.- `matrix_direct_f32_attn_bias_serial` — Projects with dtype-preserving subgroup matrices, direct input reads and double-buffered weights. Float32 uses four accumulation streams. A gated staged pass handles partial rows; sparse grids use smaller staged tiles.- `matrix_staged_f32_attn_bias_serial` — Projects with staged 32-row subgroup-matrix tiles and float32 accumulation before packed attention. Small and partial-row grids avoid an extra projection dispatch; reported matrix configurations, subgroup width and resource limits retain portable fallbacks.- `f32_attn_bias_serial` — Fuses the Q/K/V projection into a register-tiled GEMM, then runs portable serial-key attention: one workgroup owns one (packed token, head) and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.- `matrix_direct_f16_flash` — Projects with dtype-preserving matrix tiles and direct input reads; a gated staged pass covers partial rows. Attention uses subgroup or portable tiled reductions according to its own resource and lane budget.- `matrix_staged_f16_flash` — Projects with staged 32-row matrix tiles and float32 accumulation, then runs subgroup or portable tiled attention. Small projection grids avoid a separate tail dispatch; both passes retain independent resource guards.- `f16_flash` — Fuses the Q/K/V projection into a register-tiled GEMM, then runs tiled flash attention over the packed token stream: one workgroup covers `CLUSTER_TILE_Q` consecutive tokens for one head and stages `CLUSTER_TILE_K` keys, masking each token to its own sequence. Cluster dot fragments combine through subgroup shuffles.- `matrix_direct_f16_flash_nosg` — Projects with dtype-preserving matrix tiles and direct input reads; a gated staged pass covers partial rows. Attention uses subgroup or portable tiled reductions according to its own resource and lane budget.- `matrix_staged_f16_flash_nosg` — Projects with staged 32-row matrix tiles and float32 accumulation, then runs subgroup or portable tiled attention. Small projection grids avoid a separate tail dispatch; both passes retain independent resource guards.- `f16_flash_nosg` — Projects Q/K/V with the register-tiled GEMM, then performs packed flash attention. Portable clusters distribute dot fragments and softmax work across lanes. Wider heads use more lanes and fewer queries per workgroup; device limits bound geometry and key staging. Four-lane clusters retain the existing reduction.- `matrix_direct_f16_serial` — Projects with dtype-preserving subgroup matrices, direct input reads and double-buffered weights. Float32 uses four accumulation streams. A gated staged pass handles partial rows; sparse grids use smaller staged tiles.- `matrix_staged_f16_serial` — Projects with staged 32-row subgroup-matrix tiles and float32 accumulation before packed attention. Small and partial-row grids avoid an extra projection dispatch; reported matrix configurations, subgroup width and resource limits retain portable fallbacks.- `f16_serial` — Fuses the Q/K/V projection into a register-tiled GEMM, then runs portable serial-key attention: one workgroup owns one (packed token, head) and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.- `matrix_direct_f16_attn_bias_flash` — Projects with dtype-preserving matrix tiles and direct input reads; a gated staged pass covers partial rows. Attention uses subgroup or portable tiled reductions according to its own resource and lane budget.- `matrix_staged_f16_attn_bias_flash` — Projects with staged 32-row matrix tiles and float32 accumulation, then runs subgroup or portable tiled attention. Small projection grids avoid a separate tail dispatch; both passes retain independent resource guards.- `f16_attn_bias_flash` — Fuses the Q/K/V projection into a register-tiled GEMM, then runs tiled flash attention over the packed token stream: one workgroup covers `CLUSTER_TILE_Q` consecutive tokens for one head and stages `CLUSTER_TILE_K` keys, masking each token to its own sequence. Cluster dot fragments combine through subgroup shuffles.- `matrix_direct_f16_attn_bias_flash_nosg` — Projects with dtype-preserving matrix tiles and direct input reads; a gated staged pass covers partial rows. Attention uses subgroup or portable tiled reductions according to its own resource and lane budget.- `matrix_staged_f16_attn_bias_flash_nosg` — Projects with staged 32-row matrix tiles and float32 accumulation, then runs subgroup or portable tiled attention. Small projection grids avoid a separate tail dispatch; both passes retain independent resource guards.- `f16_attn_bias_flash_nosg` — Projects Q/K/V with the register-tiled GEMM, then performs packed flash attention. Portable clusters distribute dot fragments and softmax work across lanes. Wider heads use more lanes and fewer queries per workgroup; device limits bound geometry and key staging. Four-lane clusters retain the existing reduction.- `matrix_direct_f16_attn_bias_serial` — Projects with dtype-preserving subgroup matrices, direct input reads and double-buffered weights. Float32 uses four accumulation streams. A gated staged pass handles partial rows; sparse grids use smaller staged tiles.- `matrix_staged_f16_attn_bias_serial` — Projects with staged 32-row subgroup-matrix tiles and float32 accumulation before packed attention. Small and partial-row grids avoid an extra projection dispatch; reported matrix configurations, subgroup width and resource limits retain portable fallbacks.- `f16_attn_bias_serial` — Fuses the Q/K/V projection into a register-tiled GEMM, then runs portable serial-key attention: one workgroup owns one (packed token, head) and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.## Device requirementsSome implementation variants require `subgroup-matrix` and `subgroups`. These are route-specific capabilities, not package-wide requirements; availability also depends on the request shape and dtype.## Files- [`metadata.json`](build/webgpu/metadata.json) — kernel metadata (id, digests, per-variant templates, provenance)- [`manifest.json`](build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](build/webgpu/test.json) — correctness cases- [`bench.json`](build/webgpu/bench.json) — benchmark cases- [`attn-packed-varlen-cluster.wgsl.jinja`](build/webgpu/attn-packed-varlen-cluster.wgsl.jinja)- [`attn-packed-varlen-scalar.wgsl.jinja`](build/webgpu/attn-packed-varlen-scalar.wgsl.jinja)- [`gemm-epilogue-tiled-reg.wgsl.jinja`](build/webgpu/gemm-epilogue-tiled-reg.wgsl.jinja)- [`gemm-subgroup-matrix.wgsl.jinja`](build/webgpu/gemm-subgroup-matrix.wgsl.jinja)## Use with `@huggingface/kernels````shnpm install --save-exact @huggingface/kernels@0.0.1-preview.3```Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.Replace each `*Data` placeholder with a typed array containing the corresponding input data.```jsimport { getKernel } from "@huggingface/kernels";const kernel = await getKernel("webgpu-kernels/com.microsoft.PackedAttention", { version: 1 });const { outputT } = await kernel({inputT: { data: inputTData, shape: [2, 4] },weightsT: { data: weightsTData, shape: [4, 12] },3 unmodified lines}, {attrs: { num_heads: 2 },});```11 unmodified lines121314151617185 unmodified lines2425262728293025 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121133 unmodified lines11711811912012111 unmodified lines## DescriptionSelf-attention with fused Q/K/V projection over packed tokens. The `token_offset` and `cumulative_sequence_length` inputs restrict attention to each token's sequence. No mask input; optional attention bias uses padded coordinates. Output is 2-D in packed token order, with float32 or float16 storage. Malformed cumulative prefixes zero the output; an offset inconsistent with the validated prefix zeros its row. These inputs are validated on the GPU before use as unsigned indices, with nothing read back to the CPU.See the [ONNX Runtime `PackedAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.PackedAttention) for the reference semantics.5 unmodified lines| `weightsT` | `weights` | `T` | same as logical dtype | `2` | — | Merged projection weights with shape `[input_hidden_size, q_hidden + k_hidden + v_hidden]`, column-ordered `[Q all heads \| K all heads \| V all heads]`. | required || `biasT` | `bias` | `T` | same as logical dtype | `1` | — | Required projection bias with shape `[q_hidden + k_hidden + v_hidden]`. | required || `tokenOffsetT` | `token_offset` | `M` | `int32` | `2` | — | Shape `[batch_size, sequence_length]`. The first `token_count` entries hold each packed token's flat index in the padded grid; the rest hold the padding positions. This tensor carries the padded `sequence_length`. | required || `cumulativeSequenceLengthT` | `cumulative_sequence_length` | `M` | `int32` | `1` | — | Exclusive prefix sums with shape `[batch_size + 1]`, starting at 0 and ending at `token_count`. Sequence `i` owns packed tokens `[cum[i], cum[i + 1])`. Outputs are unspecified for malformed prefix sums. | required || `attentionBiasT` | `attention_bias` | `T` | same as logical dtype | `4` | — | Optional additive score bias with shape `[batch_size or 1, num_heads or 1, sequence_length, sequence_length]`. Its trailing axes are PADDED positions inside a sequence, not packed indices. | optional |## Outputs25 unmodified lines- `matrix_direct_f32_flash` — Projects with dtype-preserving matrix tiles and direct input reads; a gated staged pass covers partial rows. Attention uses subgroup or portable tiled reductions according to its own resource and lane budget.- `matrix_staged_f32_flash` — Projects with staged 32-row matrix tiles and float32 accumulation, then runs subgroup or portable tiled attention. Small projection grids avoid a separate tail dispatch; both passes retain independent resource guards.- `f32_flash`, `f16_flash` — Fuses the Q/K/V projection into a register-tiled GEMM, then runs tiled flash attention over the packed token stream: one workgroup covers a tile of consecutive tokens for one head and stages keys a tile at a time, masking each token to its own sequence. Cluster dot fragments combine through subgroup shuffles.- `matrix_direct_f32_flash_nosg` — Projects with dtype-preserving matrix tiles and direct input reads; a gated staged pass covers partial rows. Attention uses subgroup or portable tiled reductions according to its own resource and lane budget.- `matrix_staged_f32_flash_nosg` — Projects with staged 32-row matrix tiles and float32 accumulation, then runs subgroup or portable tiled attention. Small projection grids avoid a separate tail dispatch; both passes retain independent resource guards.- `f32_flash_nosg`, `f16_flash_nosg` — Projects Q/K/V with the register-tiled GEMM, then performs packed flash attention. Portable clusters distribute dot fragments and softmax work across lanes. Wider heads use more lanes and fewer queries per workgroup; device limits bound geometry and key staging.- `matrix_direct_f32_serial` — Projects with dtype-preserving subgroup matrices, direct input reads and double-buffered weights. Float32 uses four accumulation streams. A gated staged pass handles partial rows; sparse grids use smaller staged tiles.- `matrix_staged_f32_serial` — Projects with staged 32-row subgroup-matrix tiles and float32 accumulation before packed attention. Small and partial-row grids avoid an extra projection dispatch; reported matrix configurations, subgroup width and resource limits retain portable fallbacks.- `f32_serial`, `f16_serial` — Fuses the Q/K/V projection into a register-tiled GEMM, then runs portable serial-key attention: one workgroup owns one (packed token, head) and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.## Device requirementsSome implementation variants require `subgroup-matrix` and `subgroups`. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.## Files- [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedAttention/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)- [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedAttention/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedAttention/blob/v1/build/webgpu/test.json) — correctness cases- [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedAttention/blob/v1/build/webgpu/bench.json) — benchmark cases- [`attn-packed-varlen-cluster.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedAttention/blob/v1/build/webgpu/attn-packed-varlen-cluster.wgsl.jinja)- [`attn-packed-varlen-scalar.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedAttention/blob/v1/build/webgpu/attn-packed-varlen-scalar.wgsl.jinja)- [`gemm-epilogue-tiled-reg.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedAttention/blob/v1/build/webgpu/gemm-epilogue-tiled-reg.wgsl.jinja)- [`gemm-subgroup-matrix.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedAttention/blob/v1/build/webgpu/gemm-subgroup-matrix.wgsl.jinja)- [`projection-f16.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedAttention/blob/v1/build/webgpu/projection-f16.wgsl.jinja)## Use with `@huggingface/kernels````shnpm install --save-exact @huggingface/kernels@0.0.1-preview.4```Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.The `version: 1` option selects the published kernel contract; it is independent of any operator opset, contrib `since_version`, or model version.It follows the `v1` branch as fixes land. To pin exact artifact bytes, pass a 40-character commit `revision` instead of `version`.```jsimport { getKernel } from "@huggingface/kernels";const kernel = await getKernel("webgpu-kernels/com.microsoft.PackedAttention", { version: 1 });const inputTData = Float32Array.of(0.8, -0.5, 0, 1, 0.5, 0.2, 0.3, -0.6);const weightsTData = Float32Array.of(0.1, -0.2, 0.3, 1, 1.1, 0.3, 0.5, 0.2, 0.3, -0.6, 1.5, 2, 0.5, 0.1, 0.4, 1.6, 1, 2,0.4, 0.8, 0.9, 0.1, -1.3, 0.7, 0.3, 0.2, 4, 2.2, 1.6, 1.1, 0.7, 0.2, 0.4, 1, 1.2, 0.5,0.2, 0.1, 0.4, 1.6, 2.4, 3.3, 2.1, 4.2, 8.4, 0, 2.1, 3.2,);const biasTData = Float32Array.of(-0.5, 0.6, 1.2, 2.1, 0.5, 0.7, 0.2, 1.2, 0.5, 0.4, 0.3, 1.2);const tokenOffsetTData = Int32Array.of(0, 1);const cumulativeSequenceLengthTData = Int32Array.of(0, 2);const { outputT } = await kernel({inputT: { data: inputTData, shape: [2, 4] },weightsT: { data: weightsTData, shape: [4, 12] },3 unmodified lines}, {attrs: { num_heads: 2 },});console.log({ outputT });```
123456782 unmodified lines1112131415161718192042 unmodified lines636465666768692 unmodified lines727374757677787980818212 unmodified lines95969798991001011021031041051061071081091101111121131141151161175 unmodified lines12312412512612712812915 unmodified lines1451461471481491501514 unmodified lines15615715815916016116216316410 unmodified lines1751761771781791801811821831841857 unmodified lines19319419519619719819920020120220320420518 unmodified lines2242252262272282292302312325 unmodified lines23823924024124224324424524624724857 unmodified lines30630730830931031131231331431531631731831926 unmodified lines3463473483493503513523533543553563573583593 unmodified lines3633643653663673683695 unmodified lines375376377378379380381382383384385386387{% set parallelSoftmax = distributedSoftmax is defined and distributedSoftmax and not useSubgroups %}{% if useSubgroups %}enable subgroups;{% endif %}{{ env.wgsl.resourceDeclarations }}{% set QBUF = "query" %}{% set KBUF = "query" %}{% set VBUF = "query" %}2 unmodified lines{% set queryTail = headDimV4 % LPQ != 0 %}{% set VALUE_DIM_V4 = ((vHeadDim / 4) | int) %}{% set VALUE_SLICES = (((VALUE_DIM_V4 + LPQ - 1) / LPQ) | int) %}{% set unequalValue = vHeadDim != headDim %}{% set valueTail = VALUE_DIM_V4 % LPQ != 0 %}{% set valueWidth = "VALUE_HEAD_DIM_V4" if unequalValue else "HEAD_DIM_V4" %}{% set valueLane = "valueLaneSlice" if unequalValue else "laneSlice" %}// Tiled flash attention over a padding-removed packed token stream. One// workgroup covers TILE_Q consecutive packed tokens for one head, with an42 unmodified linesconst O_HEAD_V4: u32 = {{ oHeadStrideV4 }}u;const TILE_Q: u32 = {{ TILE_Q }}u;const TILE_K: u32 = {{ TILE_K }}u;// Lanes per token cluster, sized by the manifest for query and value ownership.const LPQ: u32 = {{ LPQ }}u;const SLICE: u32 = {% if queryTail %}{{ SLICE_COUNT }}u{% else %}HEAD_DIM_V4 / LPQ{% endif %}; // query vec4s per lane sliceconst WG: u32 = TILE_Q * LPQ;2 unmodified linesvar<workgroup> k_tile: array<vec4<{{ ST }}>, TILE_K * HEAD_DIM_V4>;var<workgroup> v_tile: array<vec4<{{ ST }}>, TILE_K * {{ valueWidth }}>;{% if not useSubgroups %}// Reuse scratch for dot fragments, maxima, sums and probabilities when the// manifest admits the full tile; otherwise retain one key's reduction slots.var<workgroup> red: array<f32, {% if parallelSoftmax %}{{ TILE_Q * (LPQ * TILE_K if LPQ * TILE_K > 2 * LPQ + TILE_K else 2 * LPQ + TILE_K) }}{% else %}WG{% endif %}>;{% endif %}{% set ATTN_SCALE_DIM = "HEAD_DIM" %}fn scale_value() -> f32 {if (params.scale != 0.0) { return params.scale; }return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));12 unmodified lines}fn packed_token_of(token: u32, seqPad: u32) -> PackedToken {let flat = u32(token_offset[token]);var info: PackedToken;info.sequence = flat / seqPad;info.position = flat - info.sequence * seqPad;info.keyStart = token - info.position;info.keyEnd = u32(cumulative_sequence_length[info.sequence + 1u]);return info;}{% macro packed_dot_fragment() %}var part: f32 = 0.0;let kb = kk * HEAD_DIM_V4 + laneSlice;{% for c in range(SLICE_COUNT) %}{% if queryTail %}if (laneSlice + {{ c }}u < HEAD_DIM_V4) {{% endif %}part = part + dot(qr{{ c }}, vec4<f32>(k_tile[kb + {{ c }}u]));{% if queryTail %}}{% endif %}5 unmodified lines{% if valueTail %}if ({{ valueLane }} + {{ c }}u < {{ valueWidth }}) {{% endif %}o{{ c }} = o{{ c }} + p * vec4<f32>(v_tile[vRow + {{ c }}u]);{% if valueTail %}}{% endif %}15 unmodified linesfn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>{% if useSubgroups %},@builtin(subgroup_size) sgSize: u32{% endif %}) {let h = wg.y;// The query-tile axis is folded over x and z with a baked stride; z is 14 unmodified linesreturn;}{% if useSubgroups %}// The subgroupShuffleXor butterfly requires every LPQ-lane cluster to fit in,// and align with, one subgroup. Keep a uniform guard for defensive portability.if (sgSize < LPQ || sgSize % LPQ != 0u) { return; }{% endif %}let tid = lid.x;10 unmodified lines// token's sequence start and the last token's sequence end bound every token// in the tile.let lastToken = min(firstToken + TILE_Q - 1u, params.tokenCount - 1u);let wgStart = packed_token_of(firstToken, params.seqPad).keyStart;let wgEnd = packed_token_of(lastToken, params.seqPad).keyEnd;let SCALE = scale_value();let laneSlice = lane * SLICE;{% if unequalValue %}let valueLaneSlice = lane * {{ VALUE_SLICES }}u;{% endif %}7 unmodified lines{% else %}var qr{{ c }} = vec4<f32>({{ QBUF }}[qBase4 + {{ c }}u]);{% endif %}{% if not unequalValue %}var o{{ c }} = vec4<f32>(0.0);{% endif %}{% endfor %}{% if unequalValue %}{% for c in range(VALUE_SLICES) %}var o{{ c }} = vec4<f32>(0.0);{% endfor %}{% endif %}18 unmodified lineslet kj = kStart + slot;if (kj < wgEnd) {var word = vec4<f32>({{ buffer }}[kj * {{ rowStride }} + h * {{ headStride }} + {{ offset }} + d4]);{{ tile }}[i] = vec4<{{ ST }}>(word);} else {{{ tile }}[i] = vec4<{{ ST }}>(0.0);}}{% endfor %}5 unmodified linesif (kj < wgEnd) {var kWord = vec4<f32>({{ KBUF }}[kj * K_ROW_V4 + h * K_HEAD_V4 + K_OFFSET_V4 + d4]);var vWord = vec4<f32>({{ VBUF }}[kj * V_ROW_V4 + h * V_HEAD_V4 + V_OFFSET_V4 + d4]);k_tile[i] = vec4<{{ ST }}>(kWord);v_tile[i] = vec4<{{ ST }}>(vWord);} else {k_tile[i] = vec4<{{ ST }}>(0.0);v_tile[i] = vec4<{{ ST }}>(0.0);}}{% endif %}57 unmodified liness[kk] = NEG_INF;{{ packed_dot_fragment() }}{% if useSubgroups %}// log2(LPQ) butterfly all-reduce inside the cluster: every lane ends with// the full dot.part = part + subgroupShuffleXor(part, 1u);{% for shift in [2, 4, 8, 16, 32] %}{% if LPQ > shift %}part = part + subgroupShuffleXor(part, {{ shift }}u);{% endif %}{% endfor %}{% else %}red[tid] = part;workgroupBarrier();26 unmodified lines{% endif %}// A boundary tile addresses V rows outside this token's sequence. Because// 0 * NaN is NaN, the guarded loop skips the V read entirely for a key with// no probability mass; an interior tile runs the unguarded FMA chain. One// range test covers the whole lane slice, and one probability load feeds// every vec4 of it.let tileInterior = kStart >= minKj && kStart + TILE_K <= maxKj;{% for c in range(VALUE_SLICES) %}o{{ c }} = o{{ c }} * corr;{% endfor %}if (tileInterior) {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {3 unmodified lines} else {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let p = {% if parallelSoftmax %}red[2u * WG + qSub * TILE_K + kk]{% else %}s[kk]{% endif %};if (p != 0.0) {{{ packed_value_accumulate() }}}}5 unmodified linesif (qValid) {// l == 0 means this token had no probability-bearing key. Emit 0 rather// than 0/0.let inv = select(0.0, 1.0 / l, l > 0.0);let outBase4 = qIdx * O_ROW_V4 + h * O_HEAD_V4 + {{ valueLane }};{% for c in range(VALUE_SLICES) %}{% if valueTail %}if ({{ valueLane }} + {{ c }}u < {{ valueWidth }}) {{% endif %}output[outBase4 + {{ c }}u] = vec4<{{ scalar }}>(o{{ c }} * inv);{% if valueTail %}}{% endif %}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004012 unmodified lines40440540640740840941041141241341441541641741841942042142242342442 unmodified lines4674684694704714724732 unmodified lines47647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452512 unmodified lines5385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835 unmodified lines58959059159259359459515 unmodified lines6116126136146156166176184 unmodified lines62362462562662762862963063163263363463510 unmodified lines6466476486496506516526536546556566576586596606616626636646656667 unmodified lines67467567667767867968068168268368468568618 unmodified lines7057067077087097107117127135 unmodified lines71972072172272372472572672772872957 unmodified lines78778878979079179279379479579679779879980080180280380480580680780880981026 unmodified lines8378388398408418428438448458468473 unmodified lines8518528538548558568578585 unmodified lines864865866867868869870871872873874875876877878{% set parallelSoftmax = distributedSoftmax is defined and distributedSoftmax and not useSubgroups %}{% set normalizedValues = scalar == "f32" %}{% if useSubgroups %}enable subgroups;{% endif %}{{ env.wgsl.resourceDeclarations }}{% if normalizedValues %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}) -> bool {return all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = (abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), weight{% if coefficientType != "f32" %}[{{ i }}]{% endif %}, ScaledValueScalar(value{{ c }}, 0.0, 0));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), 1.0, ScaledValueScalar(other.hi{{ c }}, other.lo{{ c }}, other.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("vec4<f32>", "f32", true) }}{% endif %}{% set QBUF = "query" %}{% set KBUF = "query" %}{% set VBUF = "query" %}2 unmodified lines{% set queryTail = headDimV4 % LPQ != 0 %}{% set VALUE_DIM_V4 = ((vHeadDim / 4) | int) %}{% set VALUE_SLICES = (((VALUE_DIM_V4 + LPQ - 1) / LPQ) | int) %}{% set loopValues = false %}{% set unequalValue = vHeadDim != headDim %}{% set valueTail = VALUE_DIM_V4 % LPQ != 0 %}{% set valueWidth = "VALUE_HEAD_DIM_V4" if unequalValue else "HEAD_DIM_V4" %}{% set valueLane = "valueLaneSlice" if unequalValue else "laneSlice" %}{% set BANK_SWIZZLE = (device.adapterInfo.vendor | default("")) == "nvidia" and ST == "f32" %}{% set K_SWZ = 8 if SLICE_COUNT % 8 == 0 else (4 if SLICE_COUNT % 4 == 0 else (2 if SLICE_COUNT % 2 == 0 else 1)) %}{% set V_SWZ = 8 if VALUE_SLICES % 8 == 0 else (4 if VALUE_SLICES % 4 == 0 else (2 if VALUE_SLICES % 2 == 0 else 1)) %}{% set K_SWIZZLE = BANK_SWIZZLE and K_SWZ > 1 and LPQ * K_SWZ > 8 and headDimV4 % K_SWZ == 0 %}{% set V_SWIZZLE = BANK_SWIZZLE and V_SWZ > 1 and LPQ * V_SWZ > 8 and VALUE_DIM_V4 % V_SWZ == 0 %}{% set HOIST_K_COLUMNS = useSubgroups and K_SWIZZLE and LPQ * K_SWZ == 16 and not V_SWIZZLE %}{% macro kswz(d4) %}{% if K_SWIZZLE %} ^ (((({{ d4 }}) / SLICE) % 8u) * {{ K_SWZ }}u / 8u){% endif %}{% endmacro %}{% macro vswz(d4) %}{% if V_SWIZZLE %} ^ (((({{ d4 }}) / {{ VALUE_SLICES }}u) % 8u) * {{ V_SWZ }}u / 8u){% endif %}{% endmacro %}{% macro kc(c) %}{% if K_SWIZZLE %}({{ c }}u ^ kSwz){% else %}{{ c }}u{% endif %}{% endmacro %}{% macro vc(c) %}{% if V_SWIZZLE %}({{ c }}u ^ vSwz){% else %}{{ c }}u{% endif %}{% endmacro %}// Tiled flash attention over a padding-removed packed token stream. One// workgroup covers TILE_Q consecutive packed tokens for one head, with an42 unmodified linesconst O_HEAD_V4: u32 = {{ oHeadStrideV4 }}u;const TILE_Q: u32 = {{ TILE_Q }}u;const TILE_K: u32 = {{ TILE_K }}u;// Lanes per token cluster partition the query and value vectors.const LPQ: u32 = {{ LPQ }}u;const SLICE: u32 = {% if queryTail %}{{ SLICE_COUNT }}u{% else %}HEAD_DIM_V4 / LPQ{% endif %}; // query vec4s per lane sliceconst WG: u32 = TILE_Q * LPQ;2 unmodified linesvar<workgroup> k_tile: array<vec4<{{ ST }}>, TILE_K * HEAD_DIM_V4>;var<workgroup> v_tile: array<vec4<{{ ST }}>, TILE_K * {{ valueWidth }}>;{% if not useSubgroups %}// Reuse scratch for dot fragments, maxima, sums and probabilities when the full// tile fits in workgroup storage; otherwise retain one key's reduction slots.var<workgroup> red: array<f32, {% if parallelSoftmax %}{{ TILE_Q * (LPQ * TILE_K if LPQ * TILE_K > 2 * LPQ + TILE_K else 2 * LPQ + TILE_K) }}{% else %}WG{% endif %}>;{% endif %}{% if useSubgroups %}{% set localFoldWorkgroupSize = TILE_Q * LPQ %}{% set localFoldWidth = LPQ %}// One entry-point proof for algorithms that assign data using local-ID lane// blocks. Every subgroup checks all active members; the workgroup accepts only// when every subgroup has a valid complete layout. Call once in uniform flow.// The rejection flag starts zero through WGSL workgroup initialization.// Some Adreno 6xx drivers cannot create a pipeline that calls subgroupAll; a ballot builds wherever subgroups do.// A subgroup is valid when no active member is invalid. That is subgroupAll, expressed as a ballot so the shader// does not depend on subgroupAll.var<workgroup> subgroupLocalLayoutRejected: atomic<u32>;var<workgroup> subgroupLocalLayoutAcceptedState: u32;fn subgroupLocalLayoutAccepted(localIndex: u32, memberValid: bool) -> bool {let valid = all(subgroupBallot(!memberValid) == vec4<u32>(0u));if (subgroupElect() && !valid) {atomicStore(&subgroupLocalLayoutRejected, 1u);}workgroupBarrier();if (localIndex == 0u) {subgroupLocalLayoutAcceptedState = select(0u, 1u, atomicLoad(&subgroupLocalLayoutRejected) == 0u);}return workgroupUniformLoad(&subgroupLocalLayoutAcceptedState) != 0u;}var<workgroup> localFoldValues: array<f32, {{ localFoldWorkgroupSize }}>;fn sumLocalSubgroup(value: f32, tid: u32, nativeTopology: bool) -> f32 {if (nativeTopology) { return subgroupAdd(value); }localFoldValues[tid] = value;workgroupBarrier();let first = (tid / {{ localFoldWidth }}u) * {{ localFoldWidth }}u;var total = 0.0;for (var i = 0u; i < {{ localFoldWidth }}u; i += 1u) {total += localFoldValues[first + i];}workgroupBarrier();return total;}{% endif %}{% set clusterShuffleLimit = 16 if (device.adapterInfo.subgroupMinSize | default(0)) > 32 else 64 %}{% set ATTN_SCALE_DIM = "HEAD_DIM" %}fn scale_value() -> f32 {if (params.scale != 0.0) { return params.scale; }return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));12 unmodified lines}fn packed_token_of(token: u32, seqPad: u32) -> PackedToken {var info: PackedToken;// An invalid prefix or mapping denotes an empty key range, so every consumer// writes a zero row. Check signed endpoints before unsigned subtraction and// keep all ranges inside this packed stream and its padded bias grid.if (cumulative_sequence_length[0] != 0|| cumulative_sequence_length[{{ batchSize }}u] != {{ tokenCount }}i) { return info; }var previous = 0i;for (var b = 1u; b <= {{ batchSize }}u; b++) {let end = cumulative_sequence_length[b];if (end < previous || end > {{ tokenCount }}i || u32(end - previous) > seqPad) { return info; }previous = end;}let signedFlat = token_offset[token];if (signedFlat < 0) { return info; }let flat = u32(signedFlat);if (flat / seqPad >= {{ batchSize }}u) { return info; }info.sequence = flat / seqPad;info.position = flat - info.sequence * seqPad;let start = u32(cumulative_sequence_length[info.sequence]);let end = u32(cumulative_sequence_length[info.sequence + 1u]);if (info.position > token || token - info.position != start || token >= end) {return PackedToken();}info.keyStart = start;info.keyEnd = end;return info;}{% macro packed_dot_fragment() %}var part: f32 = 0.0;{% if HOIST_K_COLUMNS %}let kb = kk * HEAD_DIM_V4;{% else %}let kb = kk * HEAD_DIM_V4 + laneSlice;{% endif %}{% for c in range(SLICE_COUNT) %}{% if queryTail %}if (laneSlice + {{ c }}u < HEAD_DIM_V4) {{% endif %}part = part + dot(qr{{ c }}, vec4<f32>(k_tile[kb + {{ "kCol" ~ c if HOIST_K_COLUMNS else kc(c) }}]));{% if queryTail %}}{% endif %}5 unmodified lines{% if valueTail %}if ({{ valueLane }} + {{ c }}u < {{ valueWidth }}) {{% endif %}o{{ c }} = {% if normalizedValues %}scaled_value_add(o{{ c }}, p, {% else %}o{{ c }} + p * {% endif %}vec4<f32>(v_tile[vRow + {{ vc(c) }}]){% if normalizedValues %}){% endif %};{% if valueTail %}}{% endif %}15 unmodified linesfn main(@builtin(workgroup_id) wg: vec3<u32>,@builtin(local_invocation_id) lid: vec3<u32>{% if useSubgroups %},@builtin(subgroup_size) sgSize: u32,@builtin(subgroup_invocation_id) sgLane: u32{% endif %}) {let h = wg.y;// The query-tile axis is folded over x and z with a baked stride; z is 14 unmodified linesreturn;}{% if useSubgroups %}let populationMask = subgroupBallot(true);let population = countOneBits(populationMask.x) + countOneBits(populationMask.y)+ countOneBits(populationMask.z) + countOneBits(populationMask.w);let firstLocal = subgroupBroadcastFirst(lid.x);let nativeLayout = subgroupLocalLayoutAccepted(lid.x,population == sgSize && sgSize % LPQ == 0u && sgLane == lid.x % sgSize&& firstLocal == lid.x - sgLane);{% endif %}let tid = lid.x;10 unmodified lines// token's sequence start and the last token's sequence end bound every token// in the tile.let lastToken = min(firstToken + TILE_Q - 1u, params.tokenCount - 1u);let firstInfo = packed_token_of(firstToken, params.seqPad);let lastInfo = packed_token_of(lastToken, params.seqPad);// A bad endpoint token must not truncate valid queries inside the tile.// The fallback union is bounded by the stream, while each query still masks// to its own validated sequence. Valid schedules retain the narrow union.let validEndpoints = firstInfo.keyEnd > firstInfo.keyStart && lastInfo.keyEnd > lastInfo.keyStart;let wgStart = select(0u, firstInfo.keyStart, validEndpoints);let wgEnd = select(params.tokenCount, lastInfo.keyEnd, validEndpoints);let SCALE = scale_value();let laneSlice = lane * SLICE;{% if K_SWIZZLE %} let kSwz = ((lane % 8u) * {{ K_SWZ }}u) / 8u;{% endif %}{% if HOIST_K_COLUMNS %}{% for c in range(SLICE_COUNT) %} let kCol{{ c }} = laneSlice + ({{ c }}u ^ kSwz);{% endfor %}{% endif %}{% if V_SWIZZLE and not loopValues %} let vSwz = ((lane % 8u) * {{ V_SWZ }}u) / 8u;{% endif %}{% if unequalValue %}let valueLaneSlice = lane * {{ VALUE_SLICES }}u;{% endif %}7 unmodified lines{% else %}var qr{{ c }} = vec4<f32>({{ QBUF }}[qBase4 + {{ c }}u]);{% endif %}{% if not unequalValue and not loopValues %}var o{{ c }} = {{ "scaled_value_zero()" if normalizedValues else "vec4<f32>(0.0)" }};{% endif %}{% endfor %}{% if unequalValue %}{% for c in range(VALUE_SLICES) %}var o{{ c }} = {{ "scaled_value_zero()" if normalizedValues else "vec4<f32>(0.0)" }};{% endfor %}{% endif %}18 unmodified lineslet kj = kStart + slot;if (kj < wgEnd) {var word = vec4<f32>({{ buffer }}[kj * {{ rowStride }} + h * {{ headStride }} + {{ offset }} + d4]);{{ tile }}[i{{ vswz("d4") if tile == "v_tile" else kswz("d4") }}] = vec4<{{ ST }}>(word);} else {{{ tile }}[i{{ vswz("d4") if tile == "v_tile" else kswz("d4") }}] = vec4<{{ ST }}>(0.0);}}{% endfor %}5 unmodified linesif (kj < wgEnd) {var kWord = vec4<f32>({{ KBUF }}[kj * K_ROW_V4 + h * K_HEAD_V4 + K_OFFSET_V4 + d4]);var vWord = vec4<f32>({{ VBUF }}[kj * V_ROW_V4 + h * V_HEAD_V4 + V_OFFSET_V4 + d4]);k_tile[i{{ kswz("d4") }}] = vec4<{{ ST }}>(kWord);v_tile[i{{ vswz("d4") }}] = vec4<{{ ST }}>(vWord);} else {k_tile[i{{ kswz("d4") }}] = vec4<{{ ST }}>(0.0);v_tile[i{{ vswz("d4") }}] = vec4<{{ ST }}>(0.0);}}{% endif %}57 unmodified liness[kk] = NEG_INF;{{ packed_dot_fragment() }}{% if useSubgroups %}// Reconverge query tails before the proved native or local-ID fold.workgroupBarrier();if (nativeLayout) {part = part + subgroupShuffleXor(part, 1u);{% for shift in [2, 4, 8, 16, 32] %}{% if LPQ > shift and shift < clusterShuffleLimit %}part = part + subgroupShuffleXor(part, {{ shift }}u);{% endif %}{% endfor %}{% if LPQ > clusterShuffleLimit %}localFoldValues[tid] = part;workgroupBarrier();part = {% for i in range((LPQ / clusterShuffleLimit) | int) %}{{ " + " if not loop.first else "" }}localFoldValues[tid - lane + {{ i * clusterShuffleLimit }}u]{% endfor %};workgroupBarrier();{% endif %}} else {part = sumLocalSubgroup(part, tid, false);}{% else %}red[tid] = part;workgroupBarrier();26 unmodified lines{% endif %}// Exclude V rows outside the query's sequence. Include in-range rows even// when their probability underflows so that NaN and infinity propagate.let tileInterior = kStart >= minKj && kStart + TILE_K <= maxKj;{% for c in range(VALUE_SLICES) %}o{{ c }} = {% if normalizedValues %}scaled_value_rescale(o{{ c }}, corr){% else %}o{{ c }} * corr{% endif %};{% endfor %}if (tileInterior) {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {3 unmodified lines} else {for (var kk: u32 = 0u; kk < TILE_K; kk = kk + 1u) {let p = {% if parallelSoftmax %}red[2u * WG + qSub * TILE_K + kk]{% else %}s[kk]{% endif %};let key_token = kStart + kk;if (key_token >= minKj && key_token < maxKj) {{{ packed_value_accumulate() }}}}5 unmodified linesif (qValid) {// l == 0 means this token had no probability-bearing key. Emit 0 rather// than 0/0.{% if not normalizedValues %}let inv = select(0.0, 1.0 / l, l > 0.0);{% endif %}let outBase4 = qIdx * O_ROW_V4 + h * O_HEAD_V4 + {{ valueLane }};{% for c in range(VALUE_SLICES) %}{% if valueTail %}if ({{ valueLane }} + {{ c }}u < {{ valueWidth }}) {{% endif %}output[outBase4 + {{ c }}u] = vec4<{{ scalar }}>({% if normalizedValues %}scaled_value_mean(o{{ c }}, l){% else %}o{{ c }} * inv{% endif %});{% if valueTail %}}{% endif %}
123429 unmodified lines3435363738394014 unmodified lines5556575859606162636417 unmodified lines82838485868788899091929311 unmodified lines1051061071081091102 unmodified lines11311411511611711811912012129 unmodified lines151152153154155156157158159160161162163164165{{ env.wgsl.resourceDeclarations }}{% set QBUF = "query" %}{% set KBUF = "query" %}{% set VBUF = "query" %}29 unmodified linesvar<workgroup> partial: array<f32, WG>;var<workgroup> running_max: f32;var<workgroup> running_denom: f32;var<workgroup> running_out: array<f32, V_HEAD_DIM>;var<workgroup> previous_scale: f32;{% macro wgsl_tree_reduce_f32(name, mode, buffer="partial", wg="WG", trailingBarrier=true, valueType="f32") %}fn {{ name }}(value: {{ valueType }}, tid: u32) -> {{ valueType }} {14 unmodified linesbreak;}}// The default trailing barrier makes this helper safe for back-to-back calls: every lane reads// slot 0 here, so the next call's first store must not run until all lanes have read it.// `trailingBarrier=false` is safe only when the buffer is never written again before kernel exit.let reduced = {{ buffer }}[0];workgroupBarrier();return reduced;}17 unmodified lines}fn packed_token_of(token: u32, seqPad: u32) -> PackedToken {let flat = u32(token_offset[token]);var info: PackedToken;info.sequence = flat / seqPad;info.position = flat - info.sequence * seqPad;info.keyStart = token - info.position;info.keyEnd = u32(cumulative_sequence_length[info.sequence + 1u]);return info;}11 unmodified lines}let tid = lid.x;let info = packed_token_of(token, params.seqPad);let qBase = token * Q_ROW + h * Q_HEAD;let oBase = token * O_ROW + h * O_HEAD;2 unmodified linesrunning_max = -3.4028234663852886e38;running_denom = 0.0;}for (var d: u32 = tid; d < V_HEAD_DIM; d = d + WG) {running_out[d] = 0.0;}workgroupBarrier();for (var keyToken: u32 = info.keyStart; keyToken < info.keyEnd; keyToken = keyToken + 1u) {29 unmodified lineslet vBase = keyToken * V_ROW + h * V_HEAD + V_OFFSET;for (var d: u32 = tid; d < V_HEAD_DIM; d = d + WG) {var v_value = f32({{ VBUF }}[vBase + d]);running_out[d] = running_out[d] * previous_scale + probability_numerator * v_value;}workgroupBarrier();}// A token whose sequence carries no key leaves running_denom at zero; emit a// zero row rather than 0 * (1/0) = NaN.let inv_denom = select(0.0, 1.0 / running_denom, running_denom > 0.0);for (var d: u32 = tid; d < V_HEAD_DIM; d = d + WG) {output[oBase + d] = {{ outputScalar }}(running_out[d] * inv_denom);}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639729 unmodified lines42742842943043143243343414 unmodified lines44945045145245345445545645717 unmodified lines47547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450511 unmodified lines5175185195205215225235245255262 unmodified lines52953053153253353453553653753829 unmodified lines568569570571572573574575576577578579580581582583584585586587588{{ env.wgsl.resourceDeclarations }}{% set normalizedValues = scalar == "f32" %}{% if normalizedValues %}{% macro sum_error_function(name, type="f32", protectDifference=false) %}{% set bitsType = type | replace("f32", "u32") %}// Observing the rounded sum as bits preserves FastTwoSum on backends// that otherwise reassociate its subtractions. Both signs of zero contribute zero.fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {let bits = bitcast<{{ bitsType }}>(x);return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));}fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {let swap = abs(a) < abs(b);let larger = select(a, b, swap);let smaller = select(b, a, swap);// Keep the rounded high-part difference observable before subtracting it// from the smaller addend. Reassociation here erases the residual.return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);}{% endmacro %}{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}{% set N = 1 if type == "f32" else (type[3] | int) %}{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}{% set exact = add or rescale or merge %}struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }{% if exact %}fn scaled_value_scalar_zero() -> ScaledValueScalar {return ScaledValueScalar(0.0, 0.0, 0);}{% endif %}fn scaled_value_scalar_finite(x: f32) -> bool {return abs(x) <= 3.4028234663852886e38;}{% if exact or align %}fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {if (a.hi == 0.0) {if (a.lo == 0.0) { return -1024; }return a.exponent + frexp(a.lo).exp;}if (!scaled_value_scalar_finite(a.hi)) { return 1024; }return a.exponent + frexp(a.hi).exp;}{% endif %}// Scale the significand bits directly. WGSL ldexp may return zero for a// shift <= -127 even when its input makes the final result normal; shifts// above 128 are indeterminate. Neither limit applies to this exponent sum.fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {let bits = bitcast<u32>(value);let sign = bits & 0x80000000u;let fraction = bits & 0x007fffffu;let inputExponent = i32((bits >> 23u) & 0xffu);if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }var significand = fraction | 0x00800000u;var exponent = inputExponent + shift;if (inputExponent == 0) {let normalize = countLeadingZeros(fraction) - 8u;significand = fraction << normalize;exponent = 1 + shift - i32(normalize);}if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }if (exponent > 0) {return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));}let distance = u32(1 - exponent);if (distance > 24u) { return bitcast<f32>(sign); }let high = significand >> distance;let remainder = significand & ((1u << distance) - 1u);let halfway = 1u << (distance - 1u);let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));}{% if exact or align %}fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);}{% endif %}{% if exact %}{% if recoverSum %}{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}{% endif %}fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {let nextHi = fma(hi, 1.0, lo);let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};if (nextHi == 0.0) { return scaled_value_scalar_zero(); }if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }let parts = frexp(nextHi);let rawExponent = exponent + parts.exp;// Ordinary magnitudes return to the unscaled fast path. The margin keeps// boundary values away from overflow/underflow while scaling the low word.if (rawExponent >= -120 && rawExponent <= 120) {return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);}return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);}fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {let sum = fma(a.hi, 1.0, product);let bv = fma(-1.0, a.hi, sum);let av = fma(-1.0, bv, sum);let ae = fma(-1.0, av, a.hi);let be = fma(-1.0, bv, product);let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);let hi = fma(sum, 1.0, residual);return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);}fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||!scaled_value_scalar_finite(weight)) {return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);}if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }if (a.exponent == 0 && b.exponent == 0) {let product = fma(weight, b.hi, 0.0);let lowProduct = fma(weight, b.lo, 0.0);let rawSum = fma(a.hi, 1.0, product);let productNormal = abs(product) >= 1.1754943508222875e-38;if (productNormal && scaled_value_scalar_finite(product) &&scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);let result = scaled_value_scalar_add_words(a, product, error);if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }}}// Decompose BEFORE multiplying: a merge coefficient may exceed one, so// its unscaled product with a finite partial mean need not fit in f32.var other = b;if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }let wp = frexp(weight);let vp = frexp(other.hi);let productExponent = other.exponent + wp.exp + vp.exp;let commonExponent = max(scaled_value_scalar_leading(a), productExponent);let aligned = scaled_value_scalar_align(a, commonExponent);let product = fma(wp.fract, vp.fract, 0.0);let productError = fma(wp.fract, vp.fract, -product);let shift = productExponent - commonExponent;let highWord = scaled_value_scalar_shift(product, shift);let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));{% if recoverSum %}let sum = aligned.hi + highWord;let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;return scaled_value_scalar_finish(sum, low, commonExponent);{% else %}let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);{% endif %}}{% endif %}fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {if (denominator == 0.0) { return 0.0; }if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {return fma(a.hi, 1.0, a.lo) / denominator;}let valueParts = frexp(a.hi);let denominatorParts = frexp(denominator);let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));let quotient = mantissa / denominatorParts.fract;return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);}fn scaled_value_zero() -> ScaledValue {return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));}{% if N > 1 or rescale or lean %}// Vector form of scaled_value_scalar_add_words: applies it to every component at once.fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {let sum = fma(acc.hi, {{ type }}(1.0), product);{% if magnitudeOrdered %}// FastTwoSum recovers the rounding error with the larger magnitude first.let takeProduct = abs(acc.hi) < abs(product);let larger = select(acc.hi, product, takeProduct);let smaller = select(product, acc.hi, takeProduct);let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% else %}let bv = fma({{ type }}(-1.0), acc.hi, sum);let av = fma({{ type }}(-1.0), bv, sum);let ae = fma({{ type }}(-1.0), av, acc.hi);let be = fma({{ type }}(-1.0), bv, product);let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);{% endif %}let hi = fma(sum, {{ type }}(1.0), residual);return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);}{% endif %}{% if lean %}// Lean folds: the compensated arithmetic of scaled_value_add_step with every// check deferred to the fold's end. A fold that starts from a normalized pair at// exponent zero (the high word is the words' rounded sum), ends with finite words// (a non-finite word stays non-finite through the sum, so this covers the start// too), and whose smallest nonzero weight times smallest nonzero value is normal// took only steps whose result is scaled_value_add's, up to the sign of a zero// word: each nonzero product was normal, every step leaves the pair normalized,// and a zero product leaves a normalized pair unchanged.fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));return scaled_value_add_words(acc, product, fma(w, value, -product));}// The smallest nonzero magnitude among `low` and `value`, per component.fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));}fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {return all(start.exponent == {{ exponentType }}(0)) &&all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));}{% endif %}{% if N > 1 and tile %}{% set uType = "vec" ~ N ~ "<u32>" %}// Offset tile folds. A tile's products, at most `bound` in total magnitude per// component, add onto `offset`, the power of two above 2.25 * bound, so every// partial sum stays within [offset / 2, 2 * offset): each step's change to it is// exact, and the low word gathers each step's remainder, at most half an ulp of// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A// non-finite weight, value or bound leaves a non-finite word, and a bound past// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;// scaled_value_tile_in_range checks what that cannot see.struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));return ScaledValueTile(offset, offset, {{ type }}(0.0));}fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {let w = {{ type }}(weight);let sum = fma(w, value, tile.sum);let change = fma({{ type }}(-1.0), tile.sum, sum);return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));}// The tile's words, normalized, added as scaled_value_add adds a product.fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {let high = fma({{ type }}(-1.0), tile.offset, tile.sum);let sum = fma(high, {{ type }}(1.0), tile.low);let bv = fma({{ type }}(-1.0), high, sum);let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));return scaled_value_add_words(acc, sum, error);}// An offset or start of at least 2^-76, or a zero bound, keeps every word a// flush-to-zero device could drop below 2^-48 of the result.fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}) -> bool {return all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |(bound == {{ type }}(0.0)));}{% endif %}{% if N > 1 and add %}// One compensated fold step without branches, for a caller that folds many// steps before it can afford a branch. From finite words at exponent zero, a// normal product and a finite low word imply every other condition of this// arithmetic in scaled_value_add: the low word is finite only if the high word// is, then the sum is, then the product, the weight and the value. A zero// weight with a finite value is the step whose exact result is the accumulator// itself. `exact` is false in any component whose step only scaled_value_add// computes.struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {let w = {{ type }}(weight);let product = fma(w, value, {{ type }}(0.0));let sum = scaled_value_add_words(acc, product, fma(w, value, -product));let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));let fast = (abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),fast | vec{{ N }}<bool>(keep));}{% endif %}{% if add %}fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {{% if N > 1 %}// Ordinary raw products use one vector compensated sum. Every exceptional// component falls back to the same scalar exponent-aware implementation.if (all(acc.exponent == {{ exponentType }}(0)) &&all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {let step = scaled_value_add_step(acc, weight, value);if (all(step.exact)) { return step.value; }}{% endif %}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), weight{% if coefficientType != "f32" %}[{{ i }}]{% endif %}, ScaledValueScalar(value{{ c }}, 0.0, 0));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if rescale or tile %}{% macro rescale_words() %}let w = {{ type }}(correction);let product = fma(w, acc.hi, {{ type }}(0.0));let scaled = scaled_value_add_words(scaled_value_zero(), product,fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);let unit = correction == 1.0;{% endmacro %}{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}{% endif %}{% if tile %}// scaled_value_rescale's vector path alone; `exact` is false where only its// scalar path applies.struct ScaledValueRescaled { value: ScaledValue, exact: bool }fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});}{% endif %}{% if rescale %}fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {// From finite words at exponent zero, the scalar path below leaves zero// words for a zero value or correction, the value itself for a unit// correction, and otherwise this compensated product onto zero words when// the product is normal and the low word finite (which bounds the rest, as// in scaled_value_add_step).{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {return {{ rescale_vector_value() }};}var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% if merge %}fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), 1.0, ScaledValueScalar(other.hi{{ c }}, other.lo{{ c }}, other.exponent{{ c }}));result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {// Words at exponent zero well inside the normal range, with a normal// quotient: the scalar path below divides this same sum by this same// denominator, each scaled by a power of two, so it rounds to this quotient// wherever division is scale-invariant. Bounding the denominator above also// keeps a division through its reciprocal clear of a subnormal reciprocal.let d = {{ type }}(denominator);let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);let quotient = sum / d;if (all((acc.exponent == {{ exponentType }}(0)) &(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &(abs(acc.lo) <= abs(acc.hi)) &(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {return quotient;}var result = {{ type }}(0.0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});{% endfor %}return result;}{% if align %}fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {var result = {{ exponentType }}(0);{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));{% endfor %}return result;}fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {var result = scaled_value_zero();{% for i in range(N) %}{% set c = "" if N == 1 else "[" ~ i ~ "]" %}let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;{% endfor %}return result;}{% endif %}{% endmacro %}{{ scaled_value_functions("f32", "f32", true) }}{% endif %}{% set QBUF = "query" %}{% set KBUF = "query" %}{% set VBUF = "query" %}29 unmodified linesvar<workgroup> partial: array<f32, WG>;var<workgroup> running_max: f32;var<workgroup> running_denom: f32;{% if not normalizedValues %}var<workgroup> running_out: array<f32, V_HEAD_DIM>;{% endif %}var<workgroup> previous_scale: f32;{% macro wgsl_tree_reduce_f32(name, mode, buffer="partial", wg="WG", trailingBarrier=true, valueType="f32") %}fn {{ name }}(value: {{ valueType }}, tid: u32) -> {{ valueType }} {14 unmodified linesbreak;}}let reduced = {{ buffer }}[0];// Every lane reads slot 0 above, so a following reduction's first store must not run until// all lanes have read it.workgroupBarrier();return reduced;}17 unmodified lines}fn packed_token_of(token: u32, seqPad: u32) -> PackedToken {var info: PackedToken;// An invalid prefix or mapping denotes an empty key range, so every consumer// writes a zero row. Check signed endpoints before unsigned subtraction and// keep all ranges inside this packed stream and its padded bias grid.if (cumulative_sequence_length[0] != 0|| cumulative_sequence_length[{{ batchSize }}u] != {{ tokenCount }}i) { return info; }var previous = 0i;for (var b = 1u; b <= {{ batchSize }}u; b++) {let end = cumulative_sequence_length[b];if (end < previous || end > {{ tokenCount }}i || u32(end - previous) > seqPad) { return info; }previous = end;}let signedFlat = token_offset[token];if (signedFlat < 0) { return info; }let flat = u32(signedFlat);if (flat / seqPad >= {{ batchSize }}u) { return info; }info.sequence = flat / seqPad;info.position = flat - info.sequence * seqPad;let start = u32(cumulative_sequence_length[info.sequence]);let end = u32(cumulative_sequence_length[info.sequence + 1u]);if (info.position > token || token - info.position != start || token >= end) {return PackedToken();}info.keyStart = start;info.keyEnd = end;return info;}11 unmodified lines}let tid = lid.x;{% if normalizedValues %}var output_acc: array<ScaledValue, (V_HEAD_DIM + WG - 1u) / WG>;for (var i = 0u; i < (V_HEAD_DIM + WG - 1u) / WG; i++) { output_acc[i] = scaled_value_zero(); }{% endif %}let info = packed_token_of(token, params.seqPad);let qBase = token * Q_ROW + h * Q_HEAD;let oBase = token * O_ROW + h * O_HEAD;2 unmodified linesrunning_max = -3.4028234663852886e38;running_denom = 0.0;}{% if not normalizedValues %} for (var d: u32 = tid; d < V_HEAD_DIM; d = d + WG) {running_out[d] = 0.0;}{% endif %}workgroupBarrier();for (var keyToken: u32 = info.keyStart; keyToken < info.keyEnd; keyToken = keyToken + 1u) {29 unmodified lineslet vBase = keyToken * V_ROW + h * V_HEAD + V_OFFSET;for (var d: u32 = tid; d < V_HEAD_DIM; d = d + WG) {var v_value = f32({{ VBUF }}[vBase + d]);{% if normalizedValues %}output_acc[d / WG] = scaled_value_add(scaled_value_rescale(output_acc[d / WG], previous_scale), probability_numerator, v_value);{% else %}running_out[d] = running_out[d] * previous_scale + probability_numerator * v_value;{% endif %}}workgroupBarrier();}// A token whose sequence carries no key leaves running_denom at zero; emit a// zero row rather than 0 * (1/0) = NaN.{% if not normalizedValues %}let inv_denom = select(0.0, 1.0 / running_denom, running_denom > 0.0);{% endif %}for (var d: u32 = tid; d < V_HEAD_DIM; d = d + WG) {output[oBase + d] = {{ outputScalar }}({% if normalizedValues %}scaled_value_mean(output_acc[d / WG], running_denom){% else %}running_out[d] * inv_denom{% endif %});}}
12 unmodified lines1314151617181970 unmodified lines9091929394959697989910010110210310410510610710812 unmodified lines{% set epiClose = "" %}{% set gemmWgX = ((gemmTileCols / gemmMicroCols) | int) %}{% set gemmWgY = ((gemmTileRows / gemmMicroRows) | int) %}{% set gemmTileK = 16 %}const BK: u32 = {{ gemmTileK }}u;const BM: u32 = {{ gemmTileRows }}u;const BN: u32 = {{ gemmTileCols }}u;70 unmodified lines{% set regT = "f32" %}{% set regCast = 1 if tileT != "f32" else 0 %}{% filter indent(8, true) %}{% set regAccumulator = "acc" %}let aRow = lid.y * TM;let bCol = lid.x * TN;for (var kv: u32 = 0u; kv < BK / 4u; kv = kv + 1u) {var av: array<vec4<{{ regT }}>, TM>;var bv: array<vec4<{{ regT }}>, TN>;for (var i: u32 = 0u; i < TM; i = i + 1u) { av[i] = {% if regCast %}vec4<{{ regT }}>(tileA[aRow + i][kv]){% else %}tileA[aRow + i][kv]{% endif %}; }for (var j: u32 = 0u; j < TN; j = j + 1u) { bv[j] = {% if regCast %}vec4<{{ regT }}>(tileB[bCol + j][kv]){% else %}tileB[bCol + j][kv]{% endif %}; }for (var i: u32 = 0u; i < TM; i = i + 1u) {for (var j: u32 = 0u; j < TN; j = j + 1u) {{{ regAccumulator }}[i * TN + j] = {{ regAccumulator }}[i * TN + j] + dot(av[i], bv[j]);}}}{% endfilter %}workgroupBarrier();}12 unmodified lines13141516171870 unmodified lines899091929394959697989910010110210310410510610710810911011111211312 unmodified lines{% set epiClose = "" %}{% set gemmWgX = ((gemmTileCols / gemmMicroCols) | int) %}{% set gemmWgY = ((gemmTileRows / gemmMicroRows) | int) %}const BK: u32 = {{ gemmTileK }}u;const BM: u32 = {{ gemmTileRows }}u;const BN: u32 = {{ gemmTileCols }}u;70 unmodified lines{% set regT = "f32" %}{% set regCast = 1 if tileT != "f32" else 0 %}{% filter indent(8, true) %}{% set regAccumulator = "acc" %}{% set regColumnStride = 0 %}{% set regStaticK = 0 %}{% macro regKAddress(literalKv, scale=1, offset=0) %}{% if regStaticK %}{{ scale * literalKv + offset }}u{% else %}kv{% endif %}{% endmacro %}{% macro regARead(row, literalKv) %}{% set aK = regKAddress(literalKv) %}{% if regCast %}vec4<{{ regT }}>(tileA[{{ row }}][{{ aK }}]){% else %}tileA[{{ row }}][{{ aK }}]{% endif %}{% endmacro %}{% macro regBRead(column, literalKv) %}{% set bK = regKAddress(literalKv) %}{% set regBWord = ("tileB[" ~ bK ~ "][" ~ column ~ "]") if regColumnStride else ("tileB[" ~ column ~ "][" ~ bK ~ "]") %}{% if regCast %}vec4<{{ regT }}>({{ regBWord }}){% else %}{{ regBWord }}{% endif %}{% endmacro %}let aRow = lid.y * TM;let bCol = lid.x * TN;{% for literalKv in range(regStaticK // 4 if regStaticK else 1) %}for (var kv: u32 = 0u; kv < BK / 4u; kv = kv + 1u) {var av: array<vec4<{{ regT }}>, TM>;var bv: array<vec4<{{ regT }}>, TN>;for (var i: u32 = 0u; i < TM; i = i + 1u) { av[i] = {{ regARead("aRow + i", literalKv) }}; }for (var j: u32 = 0u; j < TN; j = j + 1u) { bv[j] = {{ regBRead(("bCol + j * " ~ regColumnStride ~ "u") if regColumnStride else "bCol + j", literalKv) }}; }for (var i: u32 = 0u; i < TM; i = i + 1u) {for (var j: u32 = 0u; j < TN; j = j + 1u) {{{ regAccumulator }}[i * TN + j] = {{ regAccumulator }}[i * TN + j] + dot(av[i], bv[j]);}}}{% endfor %}{% endfilter %}workgroupBarrier();}
6 unmodified lines7891011121314151617181920211 unmodified line232425262728293031323334353637383940414243444546474849505152535455565758596061626318 unmodified lines82838485868788899011 unmodified lines1021031041051061071087 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391 unmodified line1411421431441451461471481491501511521531541551561571581 unmodified line16016116216316416516616716816917016 unmodified lines18718818919019119219319419519619719819920020120220320420520616 unmodified lines2232242252262272282292302312322332342352362372382392402412422432442452462472488 unmodified lines25725825926026126226311 unmodified lines2752762772782792802812822832842852862872882892902912922932944 unmodified lines2993003013023033043051 unmodified line3073083093103113123138 unmodified lines32232332432532632732832912 unmodified lines3423433443456 unmodified lines{{ env.wgsl.resourceDeclarations }}{% set operandScalar = mmaScalar %}{% set accScalar = "f32" %}{% set OUT = "y" %}{% set OUT_SCALAR = outScalar if outScalar is defined else yScalar %}{% set tileMValue = tileM if tileM is defined else 32 %}{% set tileNValue = tileN if tileN is defined else 64 %}{% set tileKValue = 32 %}{% set epiOpen = "" %}{% set epiClose = "" %}{% set useDirectStore = false %}{% set useDirectAStorage = directAStorage is defined and directAStorage %}{% set useDoubleBufferedB = doubleBufferedB is defined and doubleBufferedB %}1 unmodified line{% set columnTileBaseValue = 0 %}{% set rowTileBaseValue = rowTileBase if rowTileBase is defined else 0 %}// Four subgroups cover 32xN as a 2x2 grid, or taller tiles as four row bands.{% if tileMValue > 32 %}{% set subtileCols = tileNValue %}{% set subtileRows = (tileMValue / 4)|int %}{% else %}{% set subtileCols = (tileNValue / 2)|int %}{% set subtileRows = 16 %}{% endif %}{% set aTilesPerSubgroup = (subtileRows / 8)|int %}{% set bTilesPerSubgroup = (subtileCols / 8)|int %}{% set subgroupCount = 4 %}{% set scratchBanks = subgroupCount * aTilesPerSubgroup * bTilesPerSubgroup %}{% macro matrixAccumulators() %}{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}var matC{{ m }}{{ n }}: subgroup_matrix_result<{{ accScalar }}, 8, 8>;{% if useBalancedAccumulation %}var matD{{ m }}{{ n }}: subgroup_matrix_result<{{ accScalar }}, 8, 8>;var matE{{ m }}{{ n }}: subgroup_matrix_result<{{ accScalar }}, 8, 8>;var matF{{ m }}{{ n }}: subgroup_matrix_result<{{ accScalar }}, 8, 8>;{% endif %}{% endfor %}{% endfor %}{% endmacro %}{% macro storeMatrixAccumulators() %}{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}subgroupMatrixStore<row_major>(&scratch[bank + {{ m * bTilesPerSubgroup + n }}u], 0u, matC{{ m }}{{ n }}, 8u);{% if useBalancedAccumulation %}subgroupMatrixStore<row_major>(&tile_B, (bank + {{ m * bTilesPerSubgroup + n }}u) * 64u, matD{{ m }}{{ n }}, 8u);{% endif %}{% endfor %}{% endfor %}{% endmacro %}const IN_F: u32 = {{ inFeatures }}u;const OUT_F: u32 = {{ outFeatures }}u;{% set kLoopEndValue = "IN_F" %}const TILE_COLS: u32 = {{ tileNValue }}u;18 unmodified lines// it. Some subgroup-matrix implementations let a zero-padded left tile corrupt// the adjacent valid row. Replicating row M-1 avoids that boundary; the// replicated rows are discarded by storeOutput's row_limit guard, so every valid// output row stays bit-identical. M >= 1 is guaranteed by the when-clause args.M > 0.let col: u32 = c_idx * 8u;for (var row_offset: u32 = 0u; row_offset < TILE_ROWS; row_offset += {{ (1024 / tileKValue)|int }}u) {let r: u32 = row + row_offset;let a_global: u32 = min(tile_base + r, params.M - 1u);for (var col_offset: u32 = 0u; col_offset < 8u; col_offset++) {11 unmodified lineslet local_idx = row * {{ (tileKValue / 16)|int }}u + c_idx;let vectors_per_k = TILE_COLS / 4u;let total_vectors = TILE_K * vectors_per_k;for (var vector_idx = local_idx; vector_idx < total_vectors; vector_idx += 128u) {let k_local = vector_idx / vectors_per_k;let n4 = (vector_idx - k_local * vectors_per_k) * 4u;for (var component = 0u; component < 4u; component++) {7 unmodified lines{% set BIAS_1 = " + f32(bias[col_base + col])" %}{% set BIAS_2 = " + f32(bias[col_base + col2])" %}{% set ACC_1 = "(prior.x + (scratch[src_slot][row * 8u + col] + tile_B[src_slot * 64u + row * 8u + col]))" if useBalancedAccumulation else "scratch[src_slot][row * 8u + col]" %}{% set ACC_2 = "(prior.y + (scratch[src_slot][row * 8u + col2] + tile_B[src_slot * 64u + row * 8u + col2]))" if useBalancedAccumulation else "scratch[src_slot][row * 8u + col2]" %}fn storeOutput(offset: u32, col_base: u32, row: u32, col: u32, src_slot: u32, row_limit: i32{% if useBalancedAccumulation %}, prior: vec2<f32>{% endif %}) {if (row_limit > 0 && row < u32(row_limit)) {let col2: u32 = col + 1u;{{ OUT }}[offset + row * OUT_F + col] = {{ OUT_SCALAR }}({{ epiOpen }}{{ ACC_1 }}{{ BIAS_1 }}{{ epiClose }});{{ OUT }}[offset + row * OUT_F + col2] = {{ OUT_SCALAR }}({{ epiOpen }}{{ ACC_2 }}{{ BIAS_2 }}{{ epiClose }});}}@compute @workgroup_size(128, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) workgroup_id: vec3<u32>,@builtin(num_workgroups) nwg: vec3<u32>,@builtin(local_invocation_index) local_idx: u32,@builtin(subgroup_invocation_id) sg_id: u32,@builtin(subgroup_size) sg_size: u32) {// 2D-folded M-tile (row) base: workgroup_id.z carries the high bits when the// row tile exceeds the per-dimension dispatch limit.// Reduces to workgroup_id.y when nwg.z == 1; the row_limit guard in storeOutput1 unmodified linelet a_global_base: u32 = (ROW_TILE_BASE + workgroup_id.y + workgroup_id.z * nwg.y) * TILE_ROWS;let w_global_base: u32 = (COLUMN_TILE_BASE + workgroup_id.x) * TILE_COLS;let subtile_id: u32 = local_idx / sg_size;{% if tileMValue > 32 %}let subtile_idx: u32 = 0u;let subtile_idy: u32 = subtile_id;{% else %}let subtile_idx: u32 = subtile_id / 2u;let subtile_idy: u32 = subtile_id % 2u;{% endif %}let base_A: u32 = subtile_idy * SUB_ROWS;let base_B: u32 = subtile_idx * SUB_COLS;{{ matrixAccumulators() }}{% if useDoubleBufferedB %}// Large aligned f32 tiles do not benefit from staging A: each row band is// consumed by exactly one subgroup. Load those matrices directly from x and1 unmodified line// publishes the next B bank also proves the previous bank is no longer read,// reducing the steady-state schedule from two barriers per K tile to one.var b_bank: u32 = 0u;loadSHMB(w_global_base, 0u, local_idx / {{ (tileKValue / 16)|int }}u, local_idx % {{ (tileKValue / 16)|int }}u, 0u);workgroupBarrier();for (var kidx: u32 = 0u; kidx < {{ kLoopEndValue }}; kidx += TILE_K) {let b_bank_offset = b_bank * TILE_COLS * TILE_K;for (var step: u32 = 0u; step < TILE_K; step += {{ 32 if useBalancedAccumulation else 8 }}u) {{% if useBalancedAccumulation %}{% for stream in range(4) %}{16 unmodified lines{% endif %}{% for m in range(dynamicATiles) %}{% if directA %}var matA{{ m }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&{{ matrixAStorage }}, matrix_a_offset{% if m > 0 %} + {{ m * 8 }}u * {{ matrixAStride }}{% endif %}, {{ matrixAStride }});{% else %}var matA{{ m }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&tile_A, matrix_a_offset{% if m > 0 %} + {{ m * 8 }}u * TILE_K{% endif %}, TILE_K);{% endif %}{% endfor %}let matrix_b_offset = {{ B_BANK }}{{ matrixStep }} * TILE_COLS + subtile_idx * SUB_COLS;{% for n in range(bTilesPerSubgroup) %}var matB{{ n }}: subgroup_matrix_right<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_right<{{ operandScalar }}, 8, 8>, row_major>(&tile_B, matrix_b_offset + {{ n * 8 }}u, TILE_COLS);{% endfor %}{% for m in range(dynamicATiles) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixAccumulator }}{{ m }}{{ n }} = subgroupMatrixMultiplyAccumulate(matA{{ m }}, matB{{ n }}, {{ matrixAccumulator }}{{ m }}{{ n }});{% endfor %}{% endfor %}}16 unmodified lines{% endif %}{% for m in range(dynamicATiles) %}{% if directA %}var matA{{ m }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&{{ matrixAStorage }}, matrix_a_offset{% if m > 0 %} + {{ m * 8 }}u * {{ matrixAStride }}{% endif %}, {{ matrixAStride }});{% else %}var matA{{ m }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&tile_A, matrix_a_offset{% if m > 0 %} + {{ m * 8 }}u * TILE_K{% endif %}, TILE_K);{% endif %}{% endfor %}let matrix_b_offset = {{ B_BANK }}{{ matrixStep }} * TILE_COLS + subtile_idx * SUB_COLS;{% for n in range(bTilesPerSubgroup) %}var matB{{ n }}: subgroup_matrix_right<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_right<{{ operandScalar }}, 8, 8>, row_major>(&tile_B, matrix_b_offset + {{ n * 8 }}u, TILE_COLS);{% endfor %}{% for m in range(dynamicATiles) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixAccumulator }}{{ m }}{{ n }} = subgroupMatrixMultiplyAccumulate(matA{{ m }}, matB{{ n }}, {{ matrixAccumulator }}{{ m }}{{ n }});{% endfor %}{% endfor %}{% endif %}}let next_kidx = kidx + TILE_K;if (next_kidx < {{ kLoopEndValue }}) {let next_bank = 1u - b_bank;loadSHMB(w_global_base, next_kidx, local_idx / {{ (tileKValue / 16)|int }}u, local_idx % {{ (tileKValue / 16)|int }}u, next_bank * TILE_COLS * TILE_K);workgroupBarrier();8 unmodified linesloadSHMB(w_global_base, kidx, local_idx / {{ (tileKValue / 16)|int }}u, local_idx % {{ (tileKValue / 16)|int }}u, 0u);workgroupBarrier();for (var step: u32 = 0u; step < TILE_K; step += 8u) {{% set dynamicATiles = aTilesPerSubgroup if aTilesPerSubgroup is defined else 2 %}{% set matrixAccumulator = matrixAccumulator | default("matC") %}{% set matrixStepOffset = matrixStepOffset | default(0) %}11 unmodified lines{% endif %}{% for m in range(dynamicATiles) %}{% if directA %}var matA{{ m }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&{{ matrixAStorage }}, matrix_a_offset{% if m > 0 %} + {{ m * 8 }}u * {{ matrixAStride }}{% endif %}, {{ matrixAStride }});{% else %}var matA{{ m }}: subgroup_matrix_left<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_left<{{ operandScalar }}, 8, 8>, row_major>(&tile_A, matrix_a_offset{% if m > 0 %} + {{ m * 8 }}u * TILE_K{% endif %}, TILE_K);{% endif %}{% endfor %}let matrix_b_offset = {{ B_BANK }}{{ matrixStep }} * TILE_COLS + subtile_idx * SUB_COLS;{% for n in range(bTilesPerSubgroup) %}var matB{{ n }}: subgroup_matrix_right<{{ operandScalar }}, 8, 8> = subgroupMatrixLoad<subgroup_matrix_right<{{ operandScalar }}, 8, 8>, row_major>(&tile_B, matrix_b_offset + {{ n * 8 }}u, TILE_COLS);{% endfor %}{% for m in range(dynamicATiles) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixAccumulator }}{{ m }}{{ n }} = subgroupMatrixMultiplyAccumulate(matA{{ m }}, matB{{ n }}, {{ matrixAccumulator }}{{ m }}{{ n }});{% endfor %}{% endfor %}}4 unmodified lines{% if useBalancedAccumulation %}workgroupBarrier();{% endif %}let matrix_c_offset: u32 = (a_global_base + base_A) * OUT_F + w_global_base + base_B;let row: u32 = sg_id / 4u;let col: u32 = (sg_id % 4u) * 2u;// Stage every result into a distinct bank before one barrier. Tail/bias paths1 unmodified line// across lanes, so its cross-lane readback must be published before partial-M// guards diverge. The epilogue also handles output conversion and bias.let bank: u32 = subtile_id * {{ aTilesPerSubgroup * bTilesPerSubgroup }}u;{{ storeMatrixAccumulators() }}workgroupBarrier();{% if useBalancedAccumulation %}8 unmodified linesworkgroupBarrier();{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}subgroupMatrixStore<row_major>(&scratch[bank + {{ m * bTilesPerSubgroup + n }}u], 0u, matE{{ m }}{{ n }}, 8u);subgroupMatrixStore<row_major>(&tile_B, (bank + {{ m * bTilesPerSubgroup + n }}u) * 64u, matF{{ m }}{{ n }}, 8u);{% endfor %}{% endfor %}workgroupBarrier();12 unmodified lines);{% endfor %}{% endfor %}}6 unmodified lines789101112131415161718192021221 unmodified line242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848518 unmodified lines10410510610710810911011111211 unmodified lines1241251261271281291307 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222231 unmodified line2252262272282292302312322332342352362372382392402412421 unmodified line24424524624724824925025125225325425525616 unmodified lines27327427527627727827928028128228328428528628728828929029129216 unmodified lines3093103113123133143153163173183193203213223233243253263273283293303313323333348 unmodified lines34334434534634734834911 unmodified lines3613623633643653663673683693703713723733743753763773783793804 unmodified lines3853863873883893903911 unmodified line3933943953963973983998 unmodified lines40840941041141241341441512 unmodified lines4284294304314324334344354364374384394404414424434444454464474484494504516 unmodified lines{{ env.wgsl.resourceDeclarations }}{% set operandScalar = "f32" %}{% set accScalar = "f32" %}{% set OUT = "y" %}{% set OUT_SCALAR = "f32" %}{% set tileMValue = tileM if tileM is defined else 32 %}{% set tileNValue = tileN if tileN is defined else 64 %}{% set tileKValue = 32 %}{% set epiOpen = "" %}{% set epiClose = "" %}{% set packedKTail = false %}{% set useDirectStore = false %}{% set useDirectAStorage = directAStorage is defined and directAStorage %}{% set useDoubleBufferedB = doubleBufferedB is defined and doubleBufferedB %}1 unmodified line{% set columnTileBaseValue = 0 %}{% set rowTileBaseValue = rowTileBase if rowTileBase is defined else 0 %}// Four subgroups cover 32xN as a 2x2 grid, or taller tiles as four row bands.{% if tileMValue == 16 %}{% set subgroupCount = 4 %}{% set subgroupRows = 1 %}{% set subgroupCols = 4 %}{% set subtileCols = (tileNValue / 4)|int %}{% set subtileRows = 16 %}{% elif tileMValue == 48 %}{% set subgroupCount = 4 %}{% set subgroupRows = 2 %}{% set subgroupCols = 2 %}{% set subtileCols = (tileNValue / 2)|int %}{% set subtileRows = 24 %}{% elif tileMValue > 32 %}{% set subgroupCount = 4 %}{% set subgroupRows = 4 %}{% set subgroupCols = 1 %}{% set subtileCols = tileNValue %}{% set subtileRows = (tileMValue / 4)|int %}{% else %}{% set subgroupCount = 4 %}{% set subgroupRows = 2 %}{% set subgroupCols = 2 %}{% set subtileCols = (tileNValue / 2)|int %}{% set subtileRows = 16 %}{% endif %}{% set aTilesPerSubgroup = (subtileRows / 8)|int %}{% set bTilesPerSubgroup = (subtileCols / 8)|int %}{% set workgroupThreads = 128 %}{% set scratchBanks = subgroupCount * aTilesPerSubgroup * bTilesPerSubgroup %}{% set reuseB = false %}{% macro matrixAccumulators(matrixSoftware) %}{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}var matC{{ m }}{{ n }}: {{ matrixType(matrixSoftware, "result", accScalar) }};{% if useBalancedAccumulation %}var matD{{ m }}{{ n }}: {{ matrixType(matrixSoftware, "result", accScalar) }};var matE{{ m }}{{ n }}: {{ matrixType(matrixSoftware, "result", accScalar) }};var matF{{ m }}{{ n }}: {{ matrixType(matrixSoftware, "result", accScalar) }};{% endif %}{% endfor %}{% endfor %}{% endmacro %}{% macro storeMatrixAccumulators(matrixSoftware) %}{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixStore(matrixSoftware, "row_major", "&scratch[bank + " ~ (m * bTilesPerSubgroup + n) ~ "u]", "0u", "matC" ~ (m) ~ (n), "8u") }}{% if useBalancedAccumulation %}{{ matrixStore(matrixSoftware, "row_major", "&tile_B", "(bank + " ~ (m * bTilesPerSubgroup + n) ~ "u) * 64u", "matD" ~ (m) ~ (n), "8u") }}{% endif %}{% endfor %}{% endfor %}{% endmacro %}const IN_F: u32 = {{ inFeatures }}u;{% set useRegionStore = false %}{% set OUT_ROW = "OUT_F" %}const OUT_F: u32 = {{ outFeatures }}u;{% set kLoopEndValue = "IN_F" %}const TILE_COLS: u32 = {{ tileNValue }}u;18 unmodified lines// it. Some subgroup-matrix implementations let a zero-padded left tile corrupt// the adjacent valid row. Replicating row M-1 avoids that boundary; the// replicated rows are discarded by storeOutput's row_limit guard, so every valid// output row stays bit-identical. This assumes M >= 1.let col: u32 = c_idx * 8u;for (var row_offset: u32 = 0u; row_offset < TILE_ROWS; row_offset += {{ (workgroupThreads * 8 / tileKValue)|int }}u) {let r: u32 = row + row_offset;let a_global: u32 = min(tile_base + r, params.M - 1u);for (var col_offset: u32 = 0u; col_offset < 8u; col_offset++) {11 unmodified lineslet local_idx = row * {{ (tileKValue / 16)|int }}u + c_idx;let vectors_per_k = TILE_COLS / 4u;let total_vectors = TILE_K * vectors_per_k;for (var vector_idx = local_idx; vector_idx < total_vectors; vector_idx += {{ workgroupThreads }}u) {let k_local = vector_idx / vectors_per_k;let n4 = (vector_idx - k_local * vectors_per_k) * 4u;for (var component = 0u; component < 4u; component++) {7 unmodified lines{% set BIAS_1 = " + f32(bias[col_base + col])" %}{% set BIAS_2 = " + f32(bias[col_base + col2])" %}{% set ACC_1 = "(prior.x + (scratch[src_slot][row * 8u + col] + tile_B[src_slot * 64u + row * 8u + col]))" if useBalancedAccumulation else ("tile_B[src_slot * 64u + row * 8u + col]" if reuseB else "scratch[src_slot][row * 8u + col]") %}{% set ACC_2 = "(prior.y + (scratch[src_slot][row * 8u + col2] + tile_B[src_slot * 64u + row * 8u + col2]))" if useBalancedAccumulation else ("tile_B[src_slot * 64u + row * 8u + col2]" if reuseB else "scratch[src_slot][row * 8u + col2]") %}fn storeOutput(offset: u32, col_base: u32, row: u32, col: u32, src_slot: u32, row_limit: i32{% if useBalancedAccumulation %}, prior: vec2<f32>{% endif %}) {if (row_limit > 0 && row < u32(row_limit)) {let col2: u32 = col + 1u;{{ OUT }}[offset + row * OUT_F + col] = {{ OUT_SCALAR }}({{ epiOpen }}({{ ACC_1 }}{{ BIAS_1 }}){{ epiClose }});{{ OUT }}[offset + row * OUT_F + col2] = {{ OUT_SCALAR }}({{ epiOpen }}({{ ACC_2 }}{{ BIAS_2 }}){{ epiClose }});}}// A subgroup owns one matrix tile only after its actual population and the// workgroup-wide bank count are proven. The elected subgroup leader claims// the role; local invocation IDs only publish the workgroup-wide decision.var<workgroup> matrixRoleCount: atomic<u32>;var<workgroup> matrixRejected: atomic<u32>;var<workgroup> matrixAccepted: u32;fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {// WGSL initializes workgroup variables to zero before this entry point.let population = subgroupBallot(true);let populationCount = countOneBits(population.x) + countOneBits(population.y)+ countOneBits(population.z) + countOneBits(population.w);var claimed = 0u;if (subgroupElect()) {claimed = atomicAdd(&matrixRoleCount, 1u);if (width != requiredWidth || populationCount != requiredWidth) {atomicStore(&matrixRejected, 1u);}}// Reconverge every invocation before broadcasting the elected claim.workgroupBarrier();return subgroupBroadcastFirst(claimed);}fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {if (localIndex == 0u) {matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u&& atomicLoad(&matrixRoleCount) == bankCount);}// The uniform load both publishes the leader's decision and gives the// compiler a workgroup-uniform condition for the barrier-containing arms.return workgroupUniformLoad(&matrixAccepted) != 0u;}// The portable arm owns two result components per logical 32-invocation group.// Staging casts, 8-wide K steps, barriers and the epilogue match the// subgroup-matrix arm.var<private> matrixSoftwareLane: u32;fn matrixSoftwareMultiplyAccumulate(lhs: array<f32, 8>, rhs: array<vec2<f32>, 8>,acc: vec2<f32>) -> vec2<f32> {var value = acc;for (var k = 0u; k < 8u; k += 1u) {value = fma(vec2<f32>(lhs[k]), rhs[k], value);}return value;}{% macro matrixType(software, kind, scalar) %}{% if software %}{% if kind == "left" %}array<f32, 8>{% elif kind == "right" %}array<vec2<f32>, 8>{% else %}vec2<{{ scalar }}>{% endif %}{% else %}subgroup_matrix_{{ kind }}<{{ scalar }}, 8, 8>{% endif %}{% endmacro %}{% macro matrixLoad(software, kind, scalar, major, pointer, offset, stride) %}{% if not software %}subgroupMatrixLoad<{{ matrixType(false, kind, scalar) }}, {{ major }}>({{ pointer }}, {{ offset }}, {{ stride }}){% else %}{% if kind == "left" %}array<f32, 8>({% for k in range(8) %}f32((*({{ pointer }}))[({{ offset }}) + (matrixSoftwareLane / 4u) * ({{ stride }}) + {{ k }}u]){{ "," if k < 7 else "" }}{% endfor %}){% else %}array<vec2<f32>, 8>({% for k in range(8) %}vec2<f32>({% for h in range(2) %}f32((*({{ pointer }}))[({{ offset }}) + {{ k }}u * ({{ stride }}) + (matrixSoftwareLane % 4u) * 2u + {{ h }}u]){{ "," if h == 0 else "" }}{% endfor %}){{ "," if k < 7 else "" }}{% endfor %}){% endif %}{% endif %}{% endmacro %}{% macro matrixMma(software, scalar, lhs, rhs, acc) %}{% if not software %}subgroupMatrixMultiplyAccumulate({{ lhs }}, {{ rhs }}, {{ acc }}){% else %}vec2<{{ scalar }}>(matrixSoftwareMultiplyAccumulate({{ lhs }}, {{ rhs }}, vec2<f32>({{ acc }}))){% endif %}{% endmacro %}{% macro matrixStore(software, major, pointer, offset, value, stride) %}{% if not software %}subgroupMatrixStore<{{ major }}>({{ pointer }}, {{ offset }}, {{ value }}, {{ stride }});{% else %}{let matrixPointer = {{ pointer }};let matrixValue = {{ value }};{% for h in range(2) %} (*matrixPointer)[({{ offset }}) + {{ {"row_major": "(matrixSoftwareLane / 4u) * (" ~ stride ~ ") + (matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u", "col_major": "((matrixSoftwareLane % 4u) * 2u + " ~ h ~ "u) * (" ~ stride ~ ") + matrixSoftwareLane / 4u"}[major] }}] = matrixValue.{{ "x" if h == 0 else "y" }};{% endfor %}}{% endif %}{% endmacro %}{% macro matrixKernelBody(matrixSoftware) %}// 2D-folded M-tile (row) base: workgroup_id.z carries the high bits when the// row tile exceeds the per-dimension dispatch limit.// Reduces to workgroup_id.y when nwg.z == 1; the row_limit guard in storeOutput1 unmodified linelet a_global_base: u32 = (ROW_TILE_BASE + workgroup_id.y + workgroup_id.z * nwg.y) * TILE_ROWS;let w_global_base: u32 = (COLUMN_TILE_BASE + workgroup_id.x) * TILE_COLS;let subtile_id: u32 = matrixRole;{% if subgroupCols == 1 %}let subtile_idx: u32 = 0u;let subtile_idy: u32 = subtile_id;{% else %}let subtile_idx: u32 = subtile_id / {{ subgroupRows }}u;let subtile_idy: u32 = subtile_id % {{ subgroupRows }}u;{% endif %}let base_A: u32 = subtile_idy * SUB_ROWS;let base_B: u32 = subtile_idx * SUB_COLS;{{ matrixAccumulators(matrixSoftware) }}{% if useDoubleBufferedB %}// Large aligned f32 tiles do not benefit from staging A: each row band is// consumed by exactly one subgroup. Load those matrices directly from x and1 unmodified line// publishes the next B bank also proves the previous bank is no longer read,// reducing the steady-state schedule from two barriers per K tile to one.var b_bank: u32 = 0u;{% set kFirst = "0u" %}{% set kLast = "IN_F" %}loadSHMB(w_global_base, {{ kFirst }}, local_idx / {{ (tileKValue / 16)|int }}u, local_idx % {{ (tileKValue / 16)|int }}u, 0u);workgroupBarrier();for (var kidx: u32 = {{ kFirst }}; kidx < {{ kLast }}; kidx += TILE_K) {let b_bank_offset = b_bank * TILE_COLS * TILE_K;for (var step: u32 = 0u; step < {{ "min(TILE_K, IN_F - kidx)" if packedKTail else "TILE_K" }}; step += {{ 32 if useBalancedAccumulation else 8 }}u) {{% if useBalancedAccumulation %}{% for stream in range(4) %}{16 unmodified lines{% endif %}{% for m in range(dynamicATiles) %}{% if directA %}var matA{{ m }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&" ~ (matrixAStorage), ("matrix_a_offset" ~ (" + " ~ (m * 8) ~ "u * " ~ matrixAStride if m > 0 else "")), matrixAStride) }};{% else %}var matA{{ m }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&tile_A", ("matrix_a_offset" ~ (" + " ~ (m * 8) ~ "u * TILE_K" if m > 0 else "")), "TILE_K") }};{% endif %}{% endfor %}let matrix_b_offset = {{ B_BANK }}{{ matrixStep }} * TILE_COLS + subtile_idx * SUB_COLS;{% for n in range(bTilesPerSubgroup) %}var matB{{ n }}: {{ matrixType(matrixSoftware, "right", operandScalar) }} = {{ matrixLoad(matrixSoftware, "right", operandScalar, "row_major", "&tile_B", "matrix_b_offset + " ~ (n * 8) ~ "u", "TILE_COLS") }};{% endfor %}{% for m in range(dynamicATiles) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixAccumulator }}{{ m }}{{ n }} = {{ matrixMma(matrixSoftware, accScalar, "matA" ~ (m), "matB" ~ (n), (matrixAccumulator) ~ (m) ~ (n)) }};{% endfor %}{% endfor %}}16 unmodified lines{% endif %}{% for m in range(dynamicATiles) %}{% if directA %}var matA{{ m }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&" ~ (matrixAStorage), ("matrix_a_offset" ~ (" + " ~ (m * 8) ~ "u * " ~ matrixAStride if m > 0 else "")), matrixAStride) }};{% else %}var matA{{ m }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&tile_A", ("matrix_a_offset" ~ (" + " ~ (m * 8) ~ "u * TILE_K" if m > 0 else "")), "TILE_K") }};{% endif %}{% endfor %}let matrix_b_offset = {{ B_BANK }}{{ matrixStep }} * TILE_COLS + subtile_idx * SUB_COLS;{% for n in range(bTilesPerSubgroup) %}var matB{{ n }}: {{ matrixType(matrixSoftware, "right", operandScalar) }} = {{ matrixLoad(matrixSoftware, "right", operandScalar, "row_major", "&tile_B", "matrix_b_offset + " ~ (n * 8) ~ "u", "TILE_COLS") }};{% endfor %}{% for m in range(dynamicATiles) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixAccumulator }}{{ m }}{{ n }} = {{ matrixMma(matrixSoftware, accScalar, "matA" ~ (m), "matB" ~ (n), (matrixAccumulator) ~ (m) ~ (n)) }};{% endfor %}{% endfor %}{% endif %}}let next_kidx = kidx + TILE_K;if (next_kidx < {{ kLast }}) {let next_bank = 1u - b_bank;loadSHMB(w_global_base, next_kidx, local_idx / {{ (tileKValue / 16)|int }}u, local_idx % {{ (tileKValue / 16)|int }}u, next_bank * TILE_COLS * TILE_K);workgroupBarrier();8 unmodified linesloadSHMB(w_global_base, kidx, local_idx / {{ (tileKValue / 16)|int }}u, local_idx % {{ (tileKValue / 16)|int }}u, 0u);workgroupBarrier();for (var step: u32 = 0u; step < {{ "min(TILE_K, IN_F - kidx)" if packedKTail else "TILE_K" }}; step += 8u) {{% set dynamicATiles = aTilesPerSubgroup if aTilesPerSubgroup is defined else 2 %}{% set matrixAccumulator = matrixAccumulator | default("matC") %}{% set matrixStepOffset = matrixStepOffset | default(0) %}11 unmodified lines{% endif %}{% for m in range(dynamicATiles) %}{% if directA %}var matA{{ m }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&" ~ (matrixAStorage), ("matrix_a_offset" ~ (" + " ~ (m * 8) ~ "u * " ~ matrixAStride if m > 0 else "")), matrixAStride) }};{% else %}var matA{{ m }}: {{ matrixType(matrixSoftware, "left", operandScalar) }} = {{ matrixLoad(matrixSoftware, "left", operandScalar, "row_major", "&tile_A", ("matrix_a_offset" ~ (" + " ~ (m * 8) ~ "u * TILE_K" if m > 0 else "")), "TILE_K") }};{% endif %}{% endfor %}let matrix_b_offset = {{ B_BANK }}{{ matrixStep }} * TILE_COLS + subtile_idx * SUB_COLS;{% for n in range(bTilesPerSubgroup) %}var matB{{ n }}: {{ matrixType(matrixSoftware, "right", operandScalar) }} = {{ matrixLoad(matrixSoftware, "right", operandScalar, "row_major", "&tile_B", "matrix_b_offset + " ~ (n * 8) ~ "u", "TILE_COLS") }};{% endfor %}{% for m in range(dynamicATiles) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixAccumulator }}{{ m }}{{ n }} = {{ matrixMma(matrixSoftware, accScalar, "matA" ~ (m), "matB" ~ (n), (matrixAccumulator) ~ (m) ~ (n)) }};{% endfor %}{% endfor %}}4 unmodified lines{% if useBalancedAccumulation %}workgroupBarrier();{% endif %}let matrix_c_offset: u32 = (a_global_base + base_A) * {{ OUT_ROW }} + {{ "DST_COL + " if useRegionStore else "" }}w_global_base + base_B;let row: u32 = sg_id / 4u;let col: u32 = (sg_id % 4u) * 2u;// Stage every result into a distinct bank before one barrier. Tail/bias paths1 unmodified line// across lanes, so its cross-lane readback must be published before partial-M// guards diverge. The epilogue also handles output conversion and bias.let bank: u32 = subtile_id * {{ aTilesPerSubgroup * bTilesPerSubgroup }}u;{{ storeMatrixAccumulators(matrixSoftware) }}workgroupBarrier();{% if useBalancedAccumulation %}8 unmodified linesworkgroupBarrier();{% for m in range(aTilesPerSubgroup) %}{% for n in range(bTilesPerSubgroup) %}{{ matrixStore(matrixSoftware, "row_major", "&scratch[bank + " ~ (m * bTilesPerSubgroup + n) ~ "u]", "0u", "matE" ~ (m) ~ (n), "8u") }}{{ matrixStore(matrixSoftware, "row_major", "&tile_B", "(bank + " ~ (m * bTilesPerSubgroup + n) ~ "u) * 64u", "matF" ~ (m) ~ (n), "8u") }}{% endfor %}{% endfor %}workgroupBarrier();12 unmodified lines);{% endfor %}{% endfor %}{% endmacro %}@compute @workgroup_size({{ workgroupThreads }}, 1, 1){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}fn main(@builtin(workgroup_id) workgroup_id: vec3<u32>,@builtin(num_workgroups) nwg: vec3<u32>,@builtin(local_invocation_index) local_idx: u32,@builtin(subgroup_invocation_id) sg_id: u32,@builtin(subgroup_size) sg_size: u32) {let matrixRole = claimMatrixSubgroupRole(sg_size, 32u);let matrixAcceptedHere = matrixTopologyAccepted(local_idx, {{ workgroupThreads }}u / 32u);matrixSoftwareLane = local_idx % 32u;if (matrixAcceptedHere) {{{ matrixKernelBody(false) }}} else {let matrixRole = local_idx / 32u;let sg_id = local_idx % 32u;{{ matrixKernelBody(true) }}}}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061{"name": "com.microsoft.PackedAttention","id": "_com_microsoft_packedattention_webgpu_2e383dd","version": 1,"license": "Apache-2.0","backend": { "type": "webgpu" },"digest": {"algorithm": "sha256","files": {"attn-packed-varlen-cluster.wgsl.jinja": "M80JSlkb8TDwWae5JchL6XbpV286kAlQj5Vzibog8bQ=","attn-packed-varlen-scalar.wgsl.jinja": "tHu3bLC21Ptmb1VpMTt4ztk0sYa/zMjAqMGohlJGGgk=","bench.json": "8ZMv62kt75ShLjFueX/PRLS3gqcBHFs4BNOVE8RvzP8=","gemm-epilogue-tiled-reg.wgsl.jinja": "qQqLZ53/gvjjKWGMEydTYCqjBIX0DVYF1kGPt/tb0F4=","gemm-subgroup-matrix.wgsl.jinja": "nGflGDEU4lkkKKhH8SgascRjubigTw8iLGgHMUDqLV4=","manifest.json": "0UPOkWWzNh4GybUb6c4Nf2UNPNl6Lqb0t/mM10I6KTQ=","test.json": "Q/fxohWe7N1k2sg8Av4jtPf7tSvT3AEp1MERMj6KMRI="}},"provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } },"webgpu": {"manifestSpec": "2.1","variants": {"matrix_direct_f32_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f32_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f32_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"],"matrix_direct_f32_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f32_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f32_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"],"matrix_direct_f32_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f32_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f32_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"],"matrix_direct_f32_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f32_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f32_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"],"matrix_direct_f32_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f32_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f32_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"],"matrix_direct_f32_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f32_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f32_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"],"matrix_direct_f16_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f16_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f16_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"],"matrix_direct_f16_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f16_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f16_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"],"matrix_direct_f16_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f16_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f16_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"],"matrix_direct_f16_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f16_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f16_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"],"matrix_direct_f16_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f16_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f16_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"],"matrix_direct_f16_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"matrix_staged_f16_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-subgroup-matrix.wgsl.jinja"],"f16_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja", "gemm-epilogue-tiled-reg.wgsl.jinja"]}}}1{"name":"com.microsoft.PackedAttention","id":"_com_microsoft_packedattention_webgpu_ac9aa1d","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"attn-packed-varlen-cluster.wgsl.jinja":"gPpaCx4J1AeM+nyoLcQ4qAyYFWYp0juHQKv9zEYkFc0=","attn-packed-varlen-scalar.wgsl.jinja":"tdFbg3KVEVVmrjGKALTuoqHb+5mhh1BeRKoGglzHRyk=","bench.json":"8ZMv62kt75ShLjFueX/PRLS3gqcBHFs4BNOVE8RvzP8=","gemm-epilogue-tiled-reg.wgsl.jinja":"vMqUwFD2hjcbWaxZkQBrGlDO8qcAcJofLq0TWGyiDkM=","gemm-subgroup-matrix.wgsl.jinja":"d2vj9T9xsbW7rRTYh89FjpX5uigjwtlxuc3VQ4HOJBE=","manifest.json":"hJPr855vEpCUz0RJ12pgsegF02gpnL4iZObluYXU6LU=","projection-f16.wgsl.jinja":"xizRrm1wML3ilNE3ygJKwz2ypHx2KKiurSVSC21/VM0=","test.json":"ag16djFhv0Qbm2aSaR9iGSraY06rl3ZEzgEf7RdBx1s="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188{% set rows = gemmTileRows %}{% set cols = gemmTileCols %}{% set depth = gemmTileK %}{% set mr = 4 %}{% set mc = 4 %}{% set wgX = cols // mc %}{% set wgY = rows // mr %}{% set vector = "vec4<f32>" %}{% set loadWidth = 4 if compactHalfProjection else 1 %}{% set inputIndex = "((row_base + row) * K + start + k) / 4u" if compactHalfProjection else "(row_base + row) * K + start + k" %}{% set rowTail = tokenCount % rows != 0 %}{% set colTail = projection % cols != 0 %}{% set kTail = inputHidden % depth != 0 %}{{ env.wgsl.resourceDeclarations }}fn round_f16_bits_rte(value: f32) -> u32 { let bits = bitcast<u32>(value); let sign = (bits >> 16u) & 0x8000u; let exponent_f32 = (bits >> 23u) & 0xffu; let mantissa_f32 = bits & 0x7fffffu;
if (exponent_f32 == 0xffu) { if (mantissa_f32 != 0u) { return 0x7e00u; } return sign | 0x7c00u; }
var exponent_f16 = i32(exponent_f32) - 127 + 15; if (exponent_f16 >= 0x1f) { return sign | 0x7c00u; }
if (exponent_f16 <= 0) { if (exponent_f16 < -10) { return sign; } let significand = mantissa_f32 | 0x800000u; let shift = u32(14 - exponent_f16); let halfway = 1u << (shift - 1u); let discarded = significand & ((1u << shift) - 1u); var fraction = significand >> shift; if (discarded > halfway || (discarded == halfway && (fraction & 1u) == 1u)) { fraction = fraction + 1u; } return sign | fraction; }
let halfway = 1u << 12u; let discarded = mantissa_f32 & 0x1fffu; var mantissa_f16 = mantissa_f32 >> 13u; if (discarded > halfway || (discarded == halfway && (mantissa_f16 & 1u) == 1u)) { mantissa_f16 = mantissa_f16 + 1u; if (mantissa_f16 == 0x400u) { mantissa_f16 = 0u; exponent_f16 = exponent_f16 + 1; } } if (exponent_f16 >= 0x1f) { return sign | 0x7c00u; } return sign | (u32(exponent_f16) << 10u) | mantissa_f16;}
fn widen_f16_bits(value: u32) -> f32 { return unpack2x16float(value & 0xffffu).x;}
// Typed ONNX edges must survive arithmetic fusion and narrow/wide casts.// Integer rounding also fixes the ties-to-even rule independently of the// implementation's floating-point conversion rounding mode.fn half_stage(value: f32) -> f32 { return widen_f16_bits(round_f16_bits_rte(value));}
var<workgroup> inputs: array<array<f16, {{ depth }}>, {{ rows }}>;var<workgroup> weights: array<array<vec{{ mc }}<f16>, {{ wgX }}>, {{ depth }}>;
// Magnitude-ordered FastTwoSum. The two fused operations retain the rounding// residual even on targets that contract ordinary floating-point expressions.fn sum_error(a0: {{ vector }}, b0: {{ vector }}, sum: {{ vector }}) -> {{ vector }} { let swap = abs(b0) > abs(a0); let larger = select(a0, b0, swap); let smaller = select(b0, a0, swap); return fma({{ vector }}(-1.0), fma({{ vector }}(-1.0), larger, sum), smaller);}
@compute @workgroup_size({{ wgX }}, {{ wgY }})fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(num_workgroups) grid: vec3<u32>, @builtin(local_invocation_index) lane: u32, @builtin(local_invocation_id) lid: vec3<u32>) { let M = params.M; let N = params.N; let K = params.K; for (var tile_row = wg.y; tile_row < (M + {{ rows - 1 }}u) / {{ rows }}u; tile_row += grid.y) { let row_base = tile_row * {{ rows }}u; for (var tile_col = wg.x; tile_col < (N + {{ cols - 1 }}u) / {{ cols }}u; tile_col += grid.x) { let col_base = tile_col * {{ cols }}u;{% for r in range(mr) %} var high{{r}} = {{ vector }}(0.0); var low{{r}} = {{ vector }}(0.0);{% endfor %} for (var start = 0u; start < K; start += {{ depth }}u) { for (var i = lane; i < {{ rows * depth // loadWidth }}u; i += {{ wgX * wgY }}u) { let row = i / {{ depth // loadWidth }}u; let k = {% if compactHalfProjection %}(i % {{ depth // loadWidth }}u) * 4u{% else %}i % {{ depth }}u{% endif %};{% if rowTail or kTail %} var value = {{ "vec4<f16>(0.0h)" if compactHalfProjection else "0.0h" }}; if (row_base + row < M && start + k < K) { value = a[{{ inputIndex }}]; }{% else %} let value = a[{{ inputIndex }}];{% endif %}{% if compactHalfProjection %}{% for c in range(4) %} inputs[row][k + {{c}}u] = value[{{c}}];{% endfor %}{% else %} inputs[row][k] = value;{% endif %} } for (var i = lane; i < {{ depth * wgX }}u; i += {{ wgX * wgY }}u) { let k = i / {{ wgX }}u; let group_col = i % {{ wgX }}u; let col = col_base + group_col * {{ mc }}u; var value = vec{{ mc }}<f16>(0.0h);{% if kTail %} if (start + k < K) {{% endif %}{% if compactHalfProjection %} {% if colTail %}if (col < N) { {% endif %}value = b[((start + k) * N + col) / 4u];{% if colTail %} }{% endif %}{% else %}{% for c in range(mc) %} {% if colTail %}if (col + {{ c }}u < N) { {% endif %}value[{{ c }}] = b[(start + k) * N + col + {{ c }}u];{% if colTail %} }{% endif %}{% endfor %}{% endif %}{% if kTail %} }{% endif %} weights[k][group_col] = value; } workgroupBarrier();{% for step in range(depth if compactHalfProjection else 1) %}{% if compactHalfProjection %} { const k = {{ step }}u;{% else %} for (var k = 0u; k < {{ depth }}u; k++) {{% endif %} let w = {{ vector }}(weights[k][lid.x]);{% for r in range(mr) %} { let term = f32(inputs[lid.y + {{ r * wgY }}u][k]) * w; let sum = high{{r}} + term; low{{r}} += sum_error(high{{r}}, term, sum); high{{r}} = sum; }{% endfor %} }{% endfor %} workgroupBarrier(); } let col = col_base + lid.x * {{ mc }}u; var bias_value = {{ vector }}(0.0);{% for c in range(mc) %} {% if colTail %}if (col + {{ c }}u < N) { {% endif %}bias_value[{{ c }}] = f32(bias[col + {{ c }}u]);{% if colTail %} }{% endif %}{% endfor %}{% for r in range(mr) %} { let row = row_base + lid.y + {{ r * wgY }}u;{% if rowTail %} if (row < M) {{% endif %} let sum = high{{r}} + bias_value; let tail = low{{r}} + sum_error(high{{r}}, bias_value, sum); // Round the compensated sum to f32 before narrowing. Reassociating // the bias with the low part can cross an f16 midpoint. let value = select(sum, fma(sum, {{ vector }}(1.0), tail), abs(sum) <= {{ vector }}(0x1.fffffep127f));{% for c in range(mc) %} {% if colTail %}if (col + {{ c }}u < N) { {% endif %}y[row * N + col + {{ c }}u] = f16(half_stage(value[{{ c }}]));{% if colTail %} }{% endif %}{% endfor %}{% if rowTail %} }{% endif %} }{% endfor %} } }}123456730 unmodified lines38394041424344454644 unmodified lines9192939495969714 unmodified lines11211311411511611711811912012120 unmodified lines14214314414514614714819 unmodified lines16816917017117217317417521 unmodified lines19719819920020120220321 unmodified lines22522622722822923023123211 unmodified lines24424524624724824925027 unmodified lines2782792802812822832842856841 unmodified lines712771287129713071317132{"fixtureArrays": {"ort_no_pack_input_weightsT": [0.1, -0.2, 0.3, 1, 1.1, 0.3, 0.5, 0.2, 0.3, -0.6, 1.5, 2, 0.5, 0.1, 0.4, 1.6, 1, 2, 0.4, 0.8, 0.9, 0.1, -1.3, 0.7, 0.3, 0.2, 4, 2.2, 1.6, 1.1, 0.7, 0.2, 0.4, 1, 1.2, 0.5, 0.2, 0.1, 0.4, 1.6, 2.4, 3.3, 2.1, 4.2, 8.4, 0, 2.1, 3.2],"ort_no_pack_attention_bias_input_inputT": [0.8, -0.5, 0, 1, 0.5, 0.2, 0.3, -0.6, 0.8, -0.5, 0, 1, 0.5, 0.2, 0.3, -0.6],"ort_no_pack_attention_bias_output_outputT": [4.066014289855957, 0.0689978152513504, 4.25, 5.649999618530273, -1.8799558877944946, 0.32488855719566345, 4.25, 5.649999618530273, 4.066014289855957, 0.0689978152513504, 4.25, 5.649999618530273, -1.8799558877944946, 0.32488855719566345, 4.25, 5.649999618530273],"pa_matrix_float32_t31_k32_h2_d32_v32_tokenOffsetT": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 15],"pa_matrix_float32_t32_k64_h2_d32_v32_bias_tokenOffsetT": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],30 unmodified lines"fragment_schedule_634ea297a37d": [15, 16, 17, 18, 19, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 42, 43, 44],"fragment_schedule_326ff2747fbb": [0, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 131, 132, 133],"fragment_schedule_eb0c4a513a9e": [345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 1032, 1033, 1034],"fragment_schedule_2bf64e1b7d85": [0, 9, 10, 11, 12, 13, 14, 1, 2, 3, 4, 5, 6, 7, 8, 15, 16, 17]},"cases": [{"name": "ort_no_pack","provenance": {44 unmodified lines"inputT": {"dtype": "float32","shape": [4, 4],"data": { "kind": "values", "values": { "$ref": "#/fixtureArrays/ort_no_pack_attention_bias_input_inputT" } }},"weightsT": {"dtype": "float32",14 unmodified lines"attentionBiasT": {"dtype": "float32","shape": [2, 2, 2, 2],"data": {"kind": "values","values": [0.2, -0.1, 0.4, 2.5, 1.6, -1.1, 0.4, -2.5, 0.2, -0.1, 0.4, 2.5, 1.6, -1.1, 0.4, -2.5]}}},"outputs": {20 unmodified lines"inputT": {"dtype": "float32","shape": [4, 4],"data": { "kind": "values", "values": { "$ref": "#/fixtureArrays/ort_no_pack_attention_bias_input_inputT" } }},"weightsT": {"dtype": "float32",19 unmodified lines"dtype": "float32","shape": [2, 2, 4, 4],"data": {"kind": "values","values": [0.2, -0.1, 0.0, 0.0, 0.4, 2.5, 0.0, 0.0, 1.6, -1.1, 0.0, 0.0, 0.4, -2.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.2, -0.1, 0.0, 0.0, 0.4, 2.5, 0.0, 0.0, 1.6, -1.1, 0.0, 0.0, 0.4, -2.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}}},21 unmodified lines"inputT": {"dtype": "float32","shape": [4, 4],"data": { "kind": "values", "values": { "$ref": "#/fixtureArrays/ort_no_pack_attention_bias_input_inputT" } }},"weightsT": {"dtype": "float32",21 unmodified lines"dtype": "float32","shape": [4, 4],"data": {"kind": "values","values": [3.1495983600616455, 0.1084366887807846, 4.25, 5.649999618530273, 3.969679117202759, 0.07314367592334747, 4.249999523162842, 5.649999141693115, 3.1495983600616455, 0.1084366887807846, 4.25, 5.649999618530273, 3.969679117202759, 0.07314367592334747, 4.249999523162842, 5.649999141693115]}}},11 unmodified lines"inputT": {"dtype": "float32","shape": [4, 4],"data": { "kind": "values", "values": { "$ref": "#/fixtureArrays/ort_no_pack_attention_bias_input_inputT" } }},"weightsT": {"dtype": "float32",27 unmodified lines"dtype": "float32","shape": [4, 4],"data": {"kind": "values","values": [3.1967618465423584, 0.5190345644950867, 0.6305153965950012, 2.9394614696502686, 0.6533218026161194, 1.000949501991272, 0.7417502403259277, 2.8231701850891113, 3.1967618465423584, 0.5190345644950867, 0.6305153965950012, 2.9394614696502686, 0.6533218026161194, 1.000949501991272, 0.7417502403259277, 2.8231701850891113]}}},6841 unmodified lines"outputs": { "outputT": { "shape": [129, 1440], "dtype": "float16" } },"tolerance": 0.001,"relTolerance": 0.005}]}12345630 unmodified lines37383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518644 unmodified lines23123223323423523623714 unmodified lines25225325425525625725820 unmodified lines27928028128228328428519 unmodified lines30530630730830931031131221 unmodified lines33433533633733833934021 unmodified lines36236336436536636736836911 unmodified lines38138238338438538638727 unmodified lines4154164174184194204214226841 unmodified lines726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815{"fixtureArrays": {"ort_no_pack_input_weightsT": [0.1, -0.2, 0.3, 1, 1.1, 0.3, 0.5, 0.2, 0.3, -0.6, 1.5, 2, 0.5, 0.1, 0.4, 1.6, 1, 2, 0.4, 0.8, 0.9, 0.1, -1.3, 0.7, 0.3, 0.2, 4, 2.2, 1.6, 1.1, 0.7, 0.2, 0.4, 1, 1.2, 0.5, 0.2, 0.1, 0.4, 1.6, 2.4, 3.3, 2.1, 4.2, 8.4, 0, 2.1, 3.2],"ort_no_pack_attention_bias_output_outputT": [4.066014289855957, 0.0689978152513504, 4.25, 5.649999618530273, -1.8799558877944946, 0.32488855719566345, 4.25, 5.649999618530273, 4.066014289855957, 0.0689978152513504, 4.25, 5.649999618530273, -1.8799558877944946, 0.32488855719566345, 4.25, 5.649999618530273],"pa_matrix_float32_t31_k32_h2_d32_v32_tokenOffsetT": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 15],"pa_matrix_float32_t32_k64_h2_d32_v32_bias_tokenOffsetT": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31],30 unmodified lines"fragment_schedule_634ea297a37d": [15, 16, 17, 18, 19, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 42, 43, 44],"fragment_schedule_326ff2747fbb": [0, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 131, 132, 133],"fragment_schedule_eb0c4a513a9e": [345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 1032, 1033, 1034],"fragment_schedule_2bf64e1b7d85": [0, 9, 10, 11, 12, 13, 14, 1, 2, 3, 4, 5, 6, 7, 8, 15, 16, 17],"device_bounds_nonmonotone_prefix_input_biasT": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4],"device_bounds_negative_offset_valid_neighbor_output_outputT": [0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4],"f32_weighted_mean_large_finite_values_input_tokenOffsetT": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]},"cases": [{"name": "half-projection-partial-input-tile","attrs": { "num_heads": 1 },"inputs": {"inputT": {"shape": [32, 140],"dtype": "float16","data": { "kind": "fillFloat32", "sinStep": 0.952, "cosStep": 0.546, "scale": 0.5 }},"weightsT": {"shape": [140, 192],"dtype": "float16","data": { "kind": "fillFloat32", "sinStep": 0.969, "cosStep": 0.567, "scale": 0.05 }},"biasT": {"shape": [192],"dtype": "float16","data": { "kind": "fillFloat32", "sinStep": 0.986, "cosStep": 0.588, "scale": 0.1 }},"tokenOffsetT": {"dtype": "int32","shape": [1, 32],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/pa_matrix_float32_t32_k64_h2_d32_v32_bias_tokenOffsetT" }}},"cumulativeSequenceLengthT": { "dtype": "int32", "shape": [2], "data": { "kind": "values", "values": [0, 32] } }},"outputs": { "outputT": { "shape": [32, 64], "dtype": "float16" } },"tolerance": 0.001,"relTolerance": 0.005},{"name": "half-projection-cancellation-across-tiles","provenance": {"notes": "Each group of four contracted features cancels two large products around a small signed term. Uniform attention returns the biased projection in each value column."},"attrs": { "num_heads": 1 },"inputs": {"inputT": {"dtype": "float16","shape": [33, 132],"data": { "kind": "cycle", "values": [2048.0, 1.0, 2048.0, 0.0] }},"weightsT": {"dtype": "float16","shape": [132, 12],"data": {"kind": "cycle","values": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2048.0, 2048.0, 2048.0, 2048.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.125, -0.125, 0.25, -0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2048.0, -2048.0, -2048.0, -2048.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}},"biasT": {"dtype": "float16","shape": [12],"data": { "kind": "values", "values": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.25, -0.25, 0.25, -0.25] }},"tokenOffsetT": {"dtype": "int32","shape": [1, 33],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/f32_weighted_mean_large_finite_values_input_tokenOffsetT" }}},"cumulativeSequenceLengthT": { "dtype": "int32", "shape": [2], "data": { "kind": "values", "values": [0, 33] } }},"outputs": {"outputT": {"dtype": "float16","shape": [33, 4],"data": { "kind": "cycle", "values": [4.375, -4.375, 8.5, -8.5] }}},"tolerance": 0,"relTolerance": 0},{"name": "half-projection-bias-rounding-midpoint","provenance": {"notes": "Each sequence has one token. After bias, the exact projections are 1 + 2^-11 + 2^-24 ± 2^-28. Rounding to float32 first places one above the half midpoint and the other exactly on it."},"attrs": { "num_heads": 1 },"inputs": {"inputT": {"dtype": "float16","shape": [2, 4],"data": {"kind": "values","values": [0.5, 0.03125, 0.000244140625, 0.00006103515625, 0.5, 0.03125, 0.000244140625, -0.00006103515625]}},"weightsT": {"dtype": "float16","shape": [4, 3],"data": {"kind": "values","values": [0.5, 0.5, 0.5, 0.015625, 0.015625, 0.015625, 0.000244140625, 0.000244140625, 0.000244140625, 0.00006103515625, 0.00006103515625, 0.00006103515625]}},"biasT": { "dtype": "float16", "shape": [3], "data": { "kind": "constant", "value": 0.75 } },"tokenOffsetT": { "dtype": "int32", "shape": [2, 1], "data": { "kind": "values", "values": [0, 1] } },"cumulativeSequenceLengthT": {"dtype": "int32","shape": [3],"data": { "kind": "values", "values": [0, 1, 2] }}},"outputs": {"outputT": {"dtype": "float16","shape": [2, 1],"data": { "kind": "values", "values": [1.0009765625, 1.0] },"exactRounding": true}},"tolerance": 0,"relTolerance": 0},{"name": "half-projection-cancellation-before-bias","attrs": { "num_heads": 1 },"inputs": {"inputT": { "dtype": "float16", "shape": [1, 3], "data": { "kind": "values", "values": [2048.0, 1.0, 2048.0] } },"weightsT": {"dtype": "float16","shape": [3, 3],"data": { "kind": "values", "values": [0.0, 0.0, 2048.0, 0.0, 0.0, 0.125, 0.0, 0.0, -2048.0] }},"biasT": { "dtype": "float16", "shape": [3], "data": { "kind": "values", "values": [0.0, 0.0, 0.25] } },"tokenOffsetT": { "dtype": "int32", "shape": [1, 1], "data": { "kind": "values", "values": [0] } },"cumulativeSequenceLengthT": { "dtype": "int32", "shape": [2], "data": { "kind": "values", "values": [0, 1] } }},"outputs": { "outputT": { "dtype": "float16", "shape": [1, 1], "data": { "kind": "values", "values": [0.375] } } },"tolerance": 0,"relTolerance": 0},{"name": "ort_no_pack","provenance": {44 unmodified lines"inputT": {"dtype": "float32","shape": [4, 4],"data": { "kind": "cycle", "values": [0.8, -0.5, 0.0, 1.0, 0.5, 0.2, 0.3, -0.6] }},"weightsT": {"dtype": "float32",14 unmodified lines"attentionBiasT": {"dtype": "float32","shape": [2, 2, 2, 2],"data": { "kind": "cycle", "values": [0.2, -0.1, 0.4, 2.5, 1.6, -1.1, 0.4, -2.5] }}},"outputs": {20 unmodified lines"inputT": {"dtype": "float32","shape": [4, 4],"data": { "kind": "cycle", "values": [0.8, -0.5, 0.0, 1.0, 0.5, 0.2, 0.3, -0.6] }},"weightsT": {"dtype": "float32",19 unmodified lines"dtype": "float32","shape": [2, 2, 4, 4],"data": {"kind": "cycle","values": [0.2, -0.1, 0.0, 0.0, 0.4, 2.5, 0.0, 0.0, 1.6, -1.1, 0.0, 0.0, 0.4, -2.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}}},21 unmodified lines"inputT": {"dtype": "float32","shape": [4, 4],"data": { "kind": "cycle", "values": [0.8, -0.5, 0.0, 1.0, 0.5, 0.2, 0.3, -0.6] }},"weightsT": {"dtype": "float32",21 unmodified lines"dtype": "float32","shape": [4, 4],"data": {"kind": "cycle","values": [3.1495983600616455, 0.1084366887807846, 4.25, 5.649999618530273, 3.969679117202759, 0.07314367592334747, 4.249999523162842, 5.649999141693115]}}},11 unmodified lines"inputT": {"dtype": "float32","shape": [4, 4],"data": { "kind": "cycle", "values": [0.8, -0.5, 0.0, 1.0, 0.5, 0.2, 0.3, -0.6] }},"weightsT": {"dtype": "float32",27 unmodified lines"dtype": "float32","shape": [4, 4],"data": {"kind": "cycle","values": [3.1967618465423584, 0.5190345644950867, 0.6305153965950012, 2.9394614696502686, 0.6533218026161194, 1.000949501991272, 0.7417502403259277, 2.8231701850891113]}}},6841 unmodified lines"outputs": { "outputT": { "shape": [129, 1440], "dtype": "float16" } },"tolerance": 0.001,"relTolerance": 0.005},{"name": "device_bounds_nonmonotone_prefix","attrs": { "num_heads": 1 },"provenance": {"notes": "The cumulative sequence lengths [0, 3, 2] decrease, so every output is zero rather than reading another sequence's rows."},"inputs": {"tokenOffsetT": { "dtype": "int32", "shape": [2, 2], "data": { "kind": "values", "values": [0, 2, 1, 3] } },"cumulativeSequenceLengthT": {"dtype": "int32","shape": [3],"data": { "kind": "values", "values": [0, 3, 2] }},"inputT": { "dtype": "float32", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } },"weightsT": { "dtype": "float32", "shape": [8, 24], "data": { "kind": "constant", "value": 0.0 } },"biasT": {"dtype": "float32","shape": [24],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/device_bounds_nonmonotone_prefix_input_biasT" }}}},"outputs": { "outputT": { "dtype": "float32", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } } }},{"name": "device_bounds_negative_offset_valid_neighbor","attrs": { "num_heads": 1 },"provenance": {"notes": "The first token offset is -1, which is invalid: its output row is zero while the neighbouring token, whose offset is valid, keeps its normal output. The expected rows are fixed by this fixture, not taken from ONNX Runtime's CPU provider."},"inputs": {"tokenOffsetT": { "dtype": "int32", "shape": [2, 2], "data": { "kind": "values", "values": [-1, 2, 1, 3] } },"cumulativeSequenceLengthT": {"dtype": "int32","shape": [3],"data": { "kind": "values", "values": [0, 1, 2] }},"inputT": { "dtype": "float32", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } },"weightsT": { "dtype": "float32", "shape": [8, 24], "data": { "kind": "constant", "value": 0.0 } },"biasT": {"dtype": "float32","shape": [24],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/device_bounds_nonmonotone_prefix_input_biasT" }}}},"outputs": {"outputT": {"dtype": "float32","shape": [2, 8],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/device_bounds_negative_offset_valid_neighbor_output_outputT" }}}}},{"name": "device_bounds_offset_int32_max","attrs": { "num_heads": 1 },"provenance": {"notes": "The first token offset is 2147483647 (INT32_MAX), which is invalid: its output row is zero while the neighbouring token keeps its normal output. The expected rows are fixed by this fixture, not taken from ONNX Runtime's CPU provider."},"inputs": {"tokenOffsetT": {"dtype": "int32","shape": [2, 2],"data": { "kind": "values", "values": [2147483647, 2, 1, 3] }},"cumulativeSequenceLengthT": {"dtype": "int32","shape": [3],"data": { "kind": "values", "values": [0, 1, 2] }},"inputT": { "dtype": "float32", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } },"weightsT": { "dtype": "float32", "shape": [8, 24], "data": { "kind": "constant", "value": 0.0 } },"biasT": {"dtype": "float32","shape": [24],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/device_bounds_nonmonotone_prefix_input_biasT" }}}},"outputs": {"outputT": {"dtype": "float32","shape": [2, 8],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/device_bounds_negative_offset_valid_neighbor_output_outputT" }}}}},{"name": "device_bounds_offset_underflow","attrs": { "num_heads": 1 },"provenance": {"notes": "The token offsets are [1, 2, 0, 3] instead of [0, 2, 1, 3] (cumulative lengths [0, 1, 2]): one output row is zero and the other keeps its normal output. The expected rows are fixed by this fixture, not taken from ONNX Runtime's CPU provider."},"inputs": {"tokenOffsetT": { "dtype": "int32", "shape": [2, 2], "data": { "kind": "values", "values": [1, 2, 0, 3] } },"cumulativeSequenceLengthT": {"dtype": "int32","shape": [3],"data": { "kind": "values", "values": [0, 1, 2] }},"inputT": { "dtype": "float32", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } },"weightsT": { "dtype": "float32", "shape": [8, 24], "data": { "kind": "constant", "value": 0.0 } },"biasT": {"dtype": "float32","shape": [24],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/device_bounds_nonmonotone_prefix_input_biasT" }}}},"outputs": {"outputT": {"dtype": "float32","shape": [2, 8],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/device_bounds_negative_offset_valid_neighbor_output_outputT" }}}}},{"name": "device_bounds_negative_prefix","attrs": { "num_heads": 1 },"provenance": {"notes": "The cumulative sequence lengths [0, -1, 2] contain a negative value, so every output is zero. The all-zero output is fixed by this fixture, not taken from ONNX Runtime's CPU provider."},"inputs": {"tokenOffsetT": { "dtype": "int32", "shape": [2, 2], "data": { "kind": "values", "values": [0, 2, 1, 3] } },"cumulativeSequenceLengthT": {"dtype": "int32","shape": [3],"data": { "kind": "values", "values": [0, -1, 2] }},"inputT": { "dtype": "float32", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } },"weightsT": { "dtype": "float32", "shape": [8, 24], "data": { "kind": "constant", "value": 0.0 } },"biasT": {"dtype": "float32","shape": [24],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/device_bounds_nonmonotone_prefix_input_biasT" }}}},"outputs": { "outputT": { "dtype": "float32", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } } }},{"name": "device_bounds_prefix_int32_max","attrs": { "num_heads": 1 },"provenance": {"notes": "The cumulative sequence lengths [0, 2147483647, 2] contain INT32_MAX, so every output is zero. The all-zero output is fixed by this fixture, not taken from ONNX Runtime's CPU provider."},"inputs": {"tokenOffsetT": { "dtype": "int32", "shape": [2, 2], "data": { "kind": "values", "values": [0, 2, 1, 3] } },"cumulativeSequenceLengthT": {"dtype": "int32","shape": [3],"data": { "kind": "values", "values": [0, 2147483647, 2] }},"inputT": { "dtype": "float32", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } },"weightsT": { "dtype": "float32", "shape": [8, 24], "data": { "kind": "constant", "value": 0.0 } },"biasT": {"dtype": "float32","shape": [24],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/device_bounds_nonmonotone_prefix_input_biasT" }}}},"outputs": { "outputT": { "dtype": "float32", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } } }},{"name": "device_bounds_wrong_padded_position","attrs": { "num_heads": 1 },"provenance": {"notes": "The token offsets are [0, 3, 1, 2] instead of [0, 2, 1, 3] (cumulative lengths [0, 1, 2]): one output row is zero and the other keeps its normal output. The expected rows are fixed by this fixture, not taken from ONNX Runtime's CPU provider."},"inputs": {"tokenOffsetT": { "dtype": "int32", "shape": [2, 2], "data": { "kind": "values", "values": [0, 3, 1, 2] } },"cumulativeSequenceLengthT": {"dtype": "int32","shape": [3],"data": { "kind": "values", "values": [0, 1, 2] }},"inputT": { "dtype": "float32", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } },"weightsT": { "dtype": "float32", "shape": [8, 24], "data": { "kind": "constant", "value": 0.0 } },"biasT": {"dtype": "float32","shape": [24],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/device_bounds_nonmonotone_prefix_input_biasT" }}}},"outputs": {"outputT": {"dtype": "float32","shape": [2, 8],"data": {"kind": "values","values": [4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}}}},{"name": "device_bounds_malformed_prefix_float16","attrs": { "num_heads": 1 },"provenance": {"notes": "Float16 with the non-monotone cumulative sequence lengths [0, 3, 2]: every output is zero. The all-zero output is fixed by this fixture, not taken from ONNX Runtime's CPU provider."},"inputs": {"tokenOffsetT": { "dtype": "int32", "shape": [2, 2], "data": { "kind": "values", "values": [0, 2, 1, 3] } },"cumulativeSequenceLengthT": {"dtype": "int32","shape": [3],"data": { "kind": "values", "values": [0, 3, 2] }},"inputT": { "dtype": "float16", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } },"weightsT": { "dtype": "float16", "shape": [8, 24], "data": { "kind": "constant", "value": 0.0 } },"biasT": {"dtype": "float16","shape": [24],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/device_bounds_nonmonotone_prefix_input_biasT" }}}},"outputs": { "outputT": { "dtype": "float16", "shape": [2, 8], "data": { "kind": "constant", "value": 0.0 } } }},{"name": "matrix16_half_projection_three_axis_tails_packed_sequences","attrs": { "num_heads": 1 },"inputs": {"inputT": {"dtype": "float16","shape": [17, 35],"data": { "kind": "cycle", "values": [-2.0, 1.0, 0.0, 2.0, -1.0, 2.0, 0.0, -2.0, -1.0, 1.0, 0.0] }},"weightsT": {"dtype": "float16","shape": [35, 57],"data": { "kind": "cycle", "values": [1.0, -2.0, 0.0, 2.0, -1.0, 1.0, 0.0, -1.0, 2.0, -2.0, 1.0, 2.0, 0.0] }},"biasT": {"dtype": "float16","shape": [57],"data": { "kind": "cycle", "values": [0.125, -0.25, 0.0625, 0.375, -0.125] }},"tokenOffsetT": {"dtype": "int32","shape": [2, 12],"data": {"kind": "values","values": [0, 1, 2, 3, 4, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 5, 6, 7, 8, 9, 10, 11]}},"cumulativeSequenceLengthT": {"dtype": "int32","shape": [3],"data": { "kind": "values", "values": [0, 5, 17] }}},"outputs": { "outputT": { "dtype": "float16", "shape": [17, 19], "tolerance": 0.004, "relTolerance": 0.002 } }},{"name": "pa-staging-f16-t129-h3-d480-k32","attrs": { "num_heads": 3 },"inputs": {"inputT": {"shape": [129, 32],"dtype": "float16","data": { "kind": "fillFloat32", "sinStep": 0.191, "cosStep": 0.263, "scale": 0.2 }},"weightsT": {"shape": [32, 4320],"dtype": "float16","data": { "kind": "fillFloat32", "sinStep": 0.20800000000000002, "cosStep": 0.276, "scale": 0.2 }},"biasT": {"shape": [4320],"dtype": "float16","data": { "kind": "fillFloat32", "sinStep": 0.225, "cosStep": 0.289, "scale": 0.1 }},"tokenOffsetT": {"shape": [2, 131],"dtype": "int32","data": { "kind": "values", "values": { "$ref": "#/fixtureArrays/unequal_schedule_8" } }},"cumulativeSequenceLengthT": {"shape": [3],"dtype": "int32","data": { "kind": "values", "values": [0, 1, 129] }},"attentionBiasT": {"shape": [1, 1, 131, 131],"dtype": "float16","data": { "kind": "fillFloat32", "sinStep": 0.276, "cosStep": 0.32799999999999996, "scale": 0.1 }}},"outputs": { "outputT": { "shape": [129, 1440], "dtype": "float16" } },"tolerance": 0.001,"relTolerance": 0.005,"provenance": {"source": "Independent packed attention CPU reference","notes": "Wide equal query/value heads with a non-tile-aligned packed length, a short first sequence and additive attention bias."}},{"name": "pa-staging-f32-t513-h2-d176-broadcast-bias","attrs": { "num_heads": 2, "scale": 0 },"inputs": {"inputT": {"shape": [513, 32],"dtype": "float32","data": { "kind": "fillFloat32", "sinStep": 0.41200000000000003, "cosStep": 0.601, "scale": 0.2 }},"weightsT": {"shape": [32, 1056],"dtype": "float32","data": { "kind": "fillFloat32", "sinStep": 0.42900000000000005, "cosStep": 0.614, "scale": 0.2 }},"tokenOffsetT": {"shape": [3, 345],"dtype": "int32","data": { "kind": "values", "values": { "$ref": "#/fixtureArrays/fragment_schedule_eb0c4a513a9e" } }},"cumulativeSequenceLengthT": {"shape": [4],"dtype": "int32","data": { "kind": "values", "values": [0, 0, 171, 513] }},"attentionBiasT": {"shape": [1, 1, 345, 345],"dtype": "float32","data": { "kind": "fillFloat32", "sinStep": 0.48, "cosStep": 0.653, "scale": 0.1 }},"biasT": {"shape": [1056],"dtype": "float32","data": { "kind": "fillFloat32", "sinStep": 0.193, "cosStep": 0.267, "scale": 0.1 }}},"outputs": { "outputT": { "shape": [513, 352], "dtype": "float32" } },"tolerance": 0.00002,"relTolerance": 0.00002,"provenance": {"source": "Independent packed attention CPU reference","notes": "Three packed sequences include an empty sequence, query tails, fragmented heads and attention bias broadcast across batches and heads."}},{"name": "cluster_tail_underflow_projected_infinity_compact_k8","attrs": { "num_heads": 1, "scale": 1 },"tunables": { "CLUSTER_TILE_K": 8 },"inputs": {"tokenOffsetT": {"dtype": "int32","shape": [2, 16],"data": { "kind": "values", "values": { "$ref": "#/fixtureArrays/portable_schedule_14_tokenOffsetT" } }},"cumulativeSequenceLengthT": {"dtype": "int32","shape": [3],"data": { "kind": "values", "values": [0, 1, 17] }},"inputT": {"dtype": "float32","shape": [17, 4],"data": {"kind": "values","values": [1.0, 0.0, 2.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, 0.0, 3.0, 0.0, 1.0, -200.0, 3.0, 1e+38]}},"weightsT": {"dtype": "float32","shape": [4, 48],"data": {"kind": "values","values": [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}},"biasT": { "dtype": "float32", "shape": [48], "data": { "kind": "constant", "value": 0.0 } }},"outputs": {"outputT": {"dtype": "float32","shape": [17, 16],"data": {"kind": "values","values": [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, "NaN", 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0]},"allowNaN": true}},"provenance": {"source": "Independent closed form: finite projections yield Q=1, a final K=-200, constant V with one final projected infinity. The float32 softmax underflows that selected key and zero times infinity is NaN.","notes": "The large finite input and finite projection weight overflow only one value channel. The first sequence keeps finite outputs, while all sixteen queries in the other sequence preserve the selected nonfinite value even in a partial final key tile."}},{"name": "f32_weighted_mean_large_finite_values","provenance": {"notes": "Zero queries and keys give a uniform mean of large finite signed value columns, which must remain finite rather than overflowing an unnormalized numerator."},"attrs": { "num_heads": 1, "scale": 1 },"inputs": {"inputT": { "dtype": "float32", "shape": [33, 1], "data": { "kind": "constant", "value": 0.0 } },"weightsT": { "dtype": "float32", "shape": [1, 192], "data": { "kind": "constant", "value": 0.0 } },"biasT": {"dtype": "float32","shape": [192],"data": {"kind": "values","values": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37]}},"tokenOffsetT": {"dtype": "int32","shape": [1, 33],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/f32_weighted_mean_large_finite_values_input_tokenOffsetT" }}},"cumulativeSequenceLengthT": { "dtype": "int32", "shape": [2], "data": { "kind": "values", "values": [0, 33] } }},"outputs": {"outputT": {"dtype": "float32","shape": [33, 64],"data": { "kind": "cycle", "values": [1e+38, -1e+38, 5e+37, -5e+37] },"tolerance": 0,"relTolerance": 0.00002}}},{"name": "f32_weighted_mean_tiny_normal_weight_large_value","provenance": {"notes": "One rare key per 32-key cycle has score -85 and alternating large signed values; fifteen negligible keys and sixteen zero-value keys follow. Across 33 keys, two rare keys and sixteen dominant keys give a finite signed mean even when normalized probabilities become subnormal."},"attrs": { "num_heads": 1, "scale": 1 },"inputs": {"inputT": {"dtype": "float32","shape": [33, 2],"data": {"kind": "cycle","values": [-85.0, 1.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, -1000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}},"weightsT": {"dtype": "float32","shape": [2, 192],"data": {"kind": "values","values": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37, 1e+38, -1e+38, 5e+37, -5e+37]}},"biasT": {"dtype": "float32","shape": [192],"data": {"kind": "values","values": [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}},"tokenOffsetT": {"dtype": "int32","shape": [1, 33],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/f32_weighted_mean_large_finite_values_input_tokenOffsetT" }}},"cumulativeSequenceLengthT": { "dtype": "int32", "shape": [2], "data": { "kind": "values", "values": [0, 33] } }},"outputs": {"outputT": {"dtype": "float32","shape": [33, 64],"data": {"kind": "cycle","values": [1.5201240754654888, -1.5201240754654888, 0.7600620377327444, -0.7600620377327444]},"tolerance": 0,"relTolerance": 0.00002}}},{"name": "f32_weighted_mean_small_normal_values","provenance": {"notes": "Uniform attention preserves each signed small-normal value column. Accumulating the raw numerator before final normalization retains a normal mean even when individually normalized contributions would be subnormal."},"attrs": { "num_heads": 1, "scale": 1 },"inputs": {"inputT": { "dtype": "float32", "shape": [33, 1], "data": { "kind": "constant", "value": 0.0 } },"weightsT": { "dtype": "float32", "shape": [1, 192], "data": { "kind": "constant", "value": 0.0 } },"biasT": {"dtype": "float32","shape": [192],"data": {"kind": "values","values": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38, 1e-37, -1e-37, 5e-38, -5e-38]}},"tokenOffsetT": {"dtype": "int32","shape": [1, 33],"data": {"kind": "values","values": { "$ref": "#/fixtureArrays/f32_weighted_mean_large_finite_values_input_tokenOffsetT" }}},"cumulativeSequenceLengthT": { "dtype": "int32", "shape": [2], "data": { "kind": "values", "values": [0, 33] } }},"outputs": {"outputT": {"dtype": "float32","shape": [33, 64],"data": { "kind": "cycle", "values": [1e-37, -1e-37, 5e-38, -5e-38] },"tolerance": 0,"relTolerance": 0.00002}}}]}
README.md+30-44
build/webgpu/attn-packed-varlen-cluster.wgsl.jinja+525-34
build/webgpu/attn-packed-varlen-scalar.wgsl.jinja+432-9
build/webgpu/gemm-epilogue-tiled-reg.wgsl.jinja+9-4
build/webgpu/gemm-subgroup-matrix.wgsl.jinja+159-53
build/webgpu/manifest.json
build/webgpu/metadata.json+1-61
build/webgpu/projection-f16.wgsl.jinjaAdded+188
build/webgpu/test.json+699-16