sync 4385228f788d
Browse filesFiles changed (7)
11 unmodified lines1213141515161718192021222324253 unmodified lines293031283233343522 unmodified lines585960575859606162636465666768697071727374757677787980616263646566846768697088899091929371727374757677787980988182838485868788899010610791929394959697989910010110211311411511611710310410510610710810911011111211 unmodified lines
## Description
Multi-head self-attention over a padding-removed token stream. The `token_offset` and `cumulative_sequence_length` schedule maps every packed token to its sequence, and a token attends only the keys of that sequence. Query is either packed `[T, N, 3, H]` with key and value absent, or a separate `[T, hidden]` triple. The optional attention bias is indexed in PADDED coordinates. Float32 and float16 only; bfloat16 is not implemented.Self-attention over a padding-removed token stream. `token_offset` and `cumulative_sequence_length` map tokens to sequences; each token attends only its sequence. Query is packed `[T, N, 3, H]` or a separate `[T, hidden]` Q/K/V triple. Attention bias uses padded coordinates. Supports float32/float16. Malformed cumulative prefixes yield zero output; offsets inconsistent with a valid prefix yield zero rows. These inputs are validated on the GPU before use as unsigned indices, with nothing read back to the CPU. Bfloat16 is unsupported.
See the [ONNX Runtime `PackedMultiHeadAttention` contrib-operator spec](https://github.com/microsoft/onnxruntime/blob/main/docs/ContribOperators.md#com.microsoft.PackedMultiHeadAttention) for the reference semantics.
## Differences from the ONNX Runtime spec
- Attribute `mask_filter_value`: Has no effect, because this operator has no mask input.
## Inputs
| Name | Upstream name | Logical dtype | WebGPU storage | Rank | Shape | Description | Presence |3 unmodified lines| `valueT` | `value` | `T` | same as logical dtype | `2` | — | Values with shape `[token_count, v_hidden_size]`. Present only in the separate form. | optional || `biasT` | `bias` | `T` | same as logical dtype | `1` | — | Optional packed input-projection bias with shape `[hidden_size + hidden_size + v_hidden_size]`, added to Q, K and V. | optional || `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 || `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 |
## Outputs22 unmodified lines
One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
- `packed_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.- `packed_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.- `packed_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.- `packed_attn_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.- `packed_attn_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.- `packed_attn_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.- `packed_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.- `packed_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.- `packed_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.- `packed_bias_attn_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.- `packed_bias_attn_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.- `packed_bias_attn_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.- `separate_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.- `separate_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.- `separate_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.- `separate_attn_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.- `separate_attn_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.- `separate_attn_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.- `separate_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.- `separate_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.- `separate_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.- `separate_bias_attn_bias_flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count and yield to serial or wider portable clusters when reuse is limited.- `separate_bias_attn_bias_flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.- `separate_bias_attn_bias_serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.- `flash` — Tiled attention with independent Q/K and V slices and subgroup dot reductions. Equal wide heads target four `vec4` fragments per lane, bounded by subgroup/workgroup limits and native staging capacity. Unequal tiles cap work by token count.- `flash_nosg` — Portable tiled attention with independent query/key and value slices. Lanes cover the larger width, with guarded zero Q/K fragments and shared reductions. Device limits bound lane count and staging. Unequal-width tiles yield to serial attention below the query-reuse target.- `serial` — Portable serial-key attention: one workgroup owns one (packed token, head), walks that token's own sequence and reduces each dot through workgroup memory. Head dimensions need no alignment and the value head dimension may differ.
## Device requirements
Some implementation variants require `subgroups`. These are route-specific capabilities, not package-wide requirements; availability also depends on the request shape and dtype.Some implementation variants require `subgroups`. Other variants run without it; which variant runs also depends on the request's shapes and dtypes.
## 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)- [`metadata.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/metadata.json) — kernel metadata (id, file digests, manifest spec, provenance)- [`manifest.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/manifest.json) — the op contract (source of truth)- [`test.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/test.json) — correctness cases- [`bench.json`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/bench.json) — benchmark cases- [`attn-packed-varlen-cluster.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/attn-packed-varlen-cluster.wgsl.jinja)- [`attn-packed-varlen-scalar.wgsl.jinja`](https://huggingface.co/kernels/webgpu-kernels/com.microsoft.PackedMultiHeadAttention/blob/v1/build/webgpu/attn-packed-varlen-scalar.wgsl.jinja)
## Use with `@huggingface/kernels`
```shnpm install --save-exact @huggingface/kernels@0.0.1-preview.3npm 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`.
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.PackedMultiHeadAttention", { version: 1 });
const queryTData = new Float32Array(16);const keyTData = new Float32Array(16);const valueTData = new Float32Array(16).fill(4);const tokenOffsetTData = Int32Array.of(0, 2, 1, 3);const cumulativeSequenceLengthTData = Int32Array.of(0, 3, 2);
const { outputT } = await kernel({ queryT: { data: queryTData, shape: [1, 16] }, keyT: { data: keyTData, shape: [1, 16] }, valueT: { data: valueTData, shape: [1, 20] }, tokenOffsetT: { data: tokenOffsetTData, shape: [1, 1] }, cumulativeSequenceLengthT: { data: cumulativeSequenceLengthTData, shape: [2] }, queryT: { data: queryTData, shape: [2, 8] }, keyT: { data: keyTData, shape: [2, 8] }, valueT: { data: valueTData, shape: [2, 8] }, tokenOffsetT: { data: tokenOffsetTData, shape: [2, 2] }, cumulativeSequenceLengthT: { data: cumulativeSequenceLengthTData, shape: [3] },}, { attrs: { num_heads: 1 },});console.log({ outputT });```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014 unmodified lines40640740840941041141241341441541641741841942042142242342442542659 unmodified lines486487488854894904914922 unmodified lines495496497949549849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354412 unmodified lines5575585591175605615625635645655665675685695705715725735745755765771211225785795805815825835845855865875885891281295905915925935945952 unmodified lines5985996006016026036046056066076086091436106116126135 unmodified lines61962062115562262362462515 unmodified lines6416426431776446456466476484 unmodified lines65365465518818919065665765865966066166266366466510 unmodified lines67667767820720867968068168268368468568668768868969069169269369469569613 unmodified lines71071171223123271371471571671771823771972072172272372472572672772872918 unmodified lines7487497502657517522677537547557569 unmodified lines76676776828328476977077128628777277377477577657 unmodified lines83483583635135283783883984084135584284384484584684784884985085185285385485585685726 unmodified lines8848858863913923933943958878888898908918928938948958968978988999009019029039049059063989079089099103 unmodified lines9149159164089179189199209219229239249259261 unmodified line928929930931932933934935936937938939940941942943944426945946947948949950951952{% 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" if packedQkv else "key" %}{% set VBUF = "query" if packedQkv else "value" %}4 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 = resourceDistributed | default(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 an59 unmodified lines{% endif %}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.// 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// manifest admits the full tile; otherwise retain one key's reduction slots.// 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 { let flat = u32(token_offset[token]); 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; info.keyStart = token - info.position; info.keyEnd = u32(cumulative_sequence_length[info.sequence + 1u]); 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;}{% if hasBias %}
{% set biasScalarWiden = usesF16 %}{% set BW = "f32(" if biasScalarWiden is defined and biasScalarWiden else "" %}{% set BC = ")" if biasScalarWiden is defined and biasScalarWiden else "" %}{% set widenBias = biasScalarWiden if biasScalarWiden is defined else (inputScalar is defined and inputScalar == "f16") %}{% set BW = "f32(" if widenBias else "" %}{% set BC = ")" if widenBias else "" %}fn load_bias4(base: u32, d4: u32) -> vec4<f32> { let offset = base + d4 * 4u; return vec4<f32>({{ BW }}bias[offset]{{ BC }}, {{ BW }}bias[offset + 1u]{{ BC }}, {{ BW }}bias[offset + 2u]{{ BC }}, {{ BW }}bias[offset + 3u]{{ BC }});2 unmodified lines
{% 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 + {{ c }}u])); 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 }} = o{{ c }} + p * vec4<f32>(v_tile[vRow + {{ c }}u]); 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{% endif %} @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 lines return; }{% 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; } 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 wgStart = packed_token_of(firstToken, params.seqPad).keyStart; let wgEnd = packed_token_of(lastToken, params.seqPad).keyEnd; 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 %}13 unmodified lines qr{{ c }} = qr{{ c }} + load_bias4(h * HEAD_DIM, laneSlice + {{ c }}u);{% endif %}{% endif %}{% if not unequalValue %} var o{{ c }} = vec4<f32>(0.0);{% 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 }} = vec4<f32>(0.0); var o{{ c }} = {{ "scaled_value_zero()" if normalizedValues else "vec4<f32>(0.0)" }};{% endfor %}{% endif %}
{% if loopValues %} var valueOut: array<ScaledValue, SLICE>; let valueEnd = min(laneSlice + SLICE, HEAD_DIM_V4);{% endif %} var m: f32 = NEG_INF; var l: f32 = 0.0;
18 unmodified lines{% if hasBias %} word = word + load_bias4({{ biasRow }} + h * {{ biasWidth }}, d4);{% endif %} {{ tile }}[i] = vec4<{{ ST }}>(word); {{ tile }}[i{{ vswz("d4") if tile == "v_tile" else kswz("d4") }}] = vec4<{{ ST }}>(word); } else { {{ tile }}[i] = vec4<{{ ST }}>(0.0); {{ tile }}[i{{ vswz("d4") if tile == "v_tile" else kswz("d4") }}] = vec4<{{ ST }}>(0.0); } }{% endfor %}9 unmodified lines kWord = kWord + load_bias4(BIAS_K + h * HEAD_DIM, d4); vWord = vWord + load_bias4(BIAS_V + h * HEAD_DIM, d4);{% endif %} k_tile[i] = vec4<{{ ST }}>(kWord); v_tile[i] = vec4<{{ ST }}>(vWord); k_tile[i{{ kswz("d4") }}] = vec4<{{ ST }}>(kWord); v_tile[i{{ vswz("d4") }}] = vec4<{{ ST }}>(vWord); } else { k_tile[i] = vec4<{{ ST }}>(0.0); v_tile[i] = vec4<{{ ST }}>(0.0); k_tile[i{{ kswz("d4") }}] = vec4<{{ ST }}>(0.0); v_tile[i{{ vswz("d4") }}] = vec4<{{ ST }}>(0.0); } }{% endif %}57 unmodified lines s[kk] = NEG_INF;{{ packed_dot_fragment() }}{% if useSubgroups %} // log2(LPQ) butterfly all-reduce inside the cluster: every lane ends with // the full dot. // 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 %}{% 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 %}
// 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. // 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;{% if loopValues %}{% set valueColumn = ("(d4" ~ vswz("d4") ~ ")") if V_SWIZZLE else "d4" %} for (var d4 = laneSlice; d4 < valueEnd; d4++) { let c = d4 - laneSlice; var acc = scaled_value_rescale(valueOut[c], corr); for (var kk = 0u; kk < TILE_K; kk++) { let keyToken = kStart + kk; if (tileInterior || (keyToken >= minKj && keyToken < maxKj)) { let p = red[2u * WG + qSub * TILE_K + kk]; let v = v_tile[kk * HEAD_DIM_V4 + {{ valueColumn }}]; acc = scaled_value_add(acc, p, v); } } valueOut[c] = acc; }{% else %}{% for c in range(VALUE_SLICES) %} o{{ c }} = o{{ c }} * corr; 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 %}; if (p != 0.0) { let key_token = kStart + kk; if (key_token >= minKj && key_token < maxKj) {{{ packed_value_accumulate() }} } } }{% endif %}
kStart = kStart + TILE_K; }1 unmodified line if (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 }};{% if loopValues %} for (var d4 = laneSlice; d4 < valueEnd; d4++) { let c = d4 - laneSlice; output[outBase4 + c] = scaled_value_mean(valueOut[c], l); }{% else %}{% for c in range(VALUE_SLICES) %}{% if valueTail %} if ({{ valueLane }} + {{ c }}u < {{ valueWidth }}) {{% endif %} output[outBase4 + {{ c }}u] = vec4<{{ scalar }}>(o{{ c }} * inv); output[outBase4 + {{ c }}u] = vec4<{{ scalar }}>({% if normalizedValues %}scaled_value_mean(o{{ c }}, l){% else %}o{{ c }} * inv{% endif %});{% if valueTail %} }{% endif %}{% endfor %}{% endif %} }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639712 unmodified lines410411412202141341441541641723 unmodified lines4414424435144444544644744814 unmodified lines46346446572737446646746846947047117 unmodified lines4894904919949249349449549649749849950050150250350450550650750850910310451051151251351451551651751851911 unmodified lines5315325335345355365375385395402 unmodified lines54354454513054654754854955055155237 unmodified lines590591592593594595596597598599600601602603604605606607185608609610{{ 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" if packedQkv else "key" %}{% set VBUF = "query" if packedQkv else "value" %}12 unmodified lines// Source: separate token-major `[T, hidden]` query, key and value buffers.{% endif %}{% if hasBias %}// Packed `[Q; K; V]` bias rows are added to Q, K and V during the key walk,// which is where the reference adds them.// Add packed `[Q; K; V]` bias rows to Q, K and V during the key walk,// before computing scores and accumulating values.{% endif %}{% if hasAttnBias %}// The additive attention bias lives in PADDED coordinates: its trailing two23 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>;{% 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 lines break; } } // 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]; // 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 { let flat = u32(token_offset[token]); 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; info.keyStart = token - info.position; info.keyEnd = u32(cumulative_sequence_length[info.sequence + 1u]); 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 lines running_max = -3.4028234663852886e38; running_denom = 0.0; } for (var d: u32 = tid; d < V_HEAD_DIM; d = d + WG) {{% 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) {37 unmodified lines{% if hasBias %} v_value = v_value + f32(bias[BIAS_V + h * V_HEAD_DIM + d]);{% endif %}{% 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 }}(running_out[d] * inv_denom); output[oBase + d] = {{ outputScalar }}({% if normalizedValues %}scaled_value_mean(output_acc[d / WG], running_denom){% else %}running_out[d] * inv_denom{% endif %}); }}45 unmodified lines464748494950515245 unmodified lines "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] }, "tunableSpace": { "CLUSTER_TILE_K": [8, 16], "SCALAR_WORKGROUP_SIZE": [64, 128] }, "tunableSpace": { "SCALAR_WORKGROUP_SIZE": [64, 128] }, "cases": [ { "name": "pmha-minilm-b16-pad-f16",1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666671{ "domain": "com.microsoft", "name": "PackedMultiHeadAttention", "sinceVersion": 1, "inputs": { "queryT": { "onnx": "query", "dtype": "T" }, "keyT": { "onnx": "key", "dtype": "T", "rank": 2, "optional": true }, "valueT": { "onnx": "value", "dtype": "T", "rank": 2, "optional": true }, "biasT": { "onnx": "bias", "dtype": "T", "rank": 1, "optional": true }, "tokenOffsetT": { "onnx": "token_offset", "dtype": "M", "rank": 2, "storage": "int32" }, "cumulativeSequenceLengthT": { "onnx": "cumulative_sequence_length", "dtype": "M", "rank": 1, "storage": "int32" }, "attentionBiasT": { "onnx": "attention_bias", "dtype": "T", "rank": 4, "optional": true } }, "outputs": { "outputT": { "onnx": "output", "dtype": "T", "rank": 2, "shape": "[tokenCount, vHiddenSize]" } }, "attributes": { "num_heads": {}, "scale": {} }, "attributeConstraints": { "num_heads": { "required": true } }, "typeConstraints": { "T": ["float32", "float16"], "M": ["int32"] }, "tunables": { "CLUSTER_TILE_K": { "default": 16 }, "SCALAR_WORKGROUP_SIZE": { "default": 64 } }, "derive": { "numHeads": "attrs.num_heads", "qNumHeads": "numHeads", "packedQkv": "ranks.queryT == 4", "tokenCount": "dim(shapes.queryT, 0)", "batchSize": "dim(shapes.tokenOffsetT, 0) if ranks.tokenOffsetT == 2 else 0", "seqPad": "dim(shapes.tokenOffsetT, 1) if ranks.tokenOffsetT == 2 else 0", "packedHeadDim": "dim(shapes.queryT, 3) if packedQkv else 0", "hiddenSize": "numHeads * packedHeadDim if packedQkv else (dim(shapes.queryT, 1) if ranks.queryT == 2 else 0)", "vHiddenSize": "hiddenSize if packedQkv else (dim(shapes.valueT, 1) if present.valueT and ranks.valueT == 2 else 0)", "headDim": "hiddenSize / numHeads if numHeads > 0 and hiddenSize % numHeads == 0 else 0", "vHeadDim": "vHiddenSize / numHeads if numHeads > 0 and vHiddenSize % numHeads == 0 else 0", "attentionScale": "attrs.scale if has(attrs, \"scale\") else 0", "qRowStride": "numHeads * 3 * headDim if packedQkv else hiddenSize", "qHeadStride": "3 * headDim if packedQkv else headDim", "kRowStride": "qRowStride if packedQkv else hiddenSize", "kHeadStride": "qHeadStride if packedQkv else headDim", "kOffset": "headDim if packedQkv else 0", "vRowStride": "qRowStride if packedQkv else vHiddenSize", "vHeadStride": "qHeadStride if packedQkv else vHeadDim", "vOffset": "2 * headDim if packedQkv else 0", "oRowStride": "vHiddenSize", "oHeadStride": "vHeadDim", "biasKOffset": "hiddenSize", "biasVOffset": "2 * hiddenSize", "attnBiasHeads": "dim(shapes.attentionBiasT, 1) if present.attentionBiasT and ranks.attentionBiasT == 4 else 0", "maskSeqStride": "seqPad", "maskHeadStride": "0 if attnBiasHeads == 1 else seqPad * seqPad", "maskBatchStride": "0 if (not present.attentionBiasT) or ranks.attentionBiasT != 4 or dim(shapes.attentionBiasT, 0) == 1 else attnBiasHeads * seqPad * seqPad", "dtypeOk": "tensorDtypes.outputT == tensorDtypes.queryT and (tensorDtypes.queryT == \"float32\" or tensorDtypes.queryT == \"float16\") and f16Ok(dtypes.T)", "packedShapeOk": "packedQkv and not present.keyT and not present.valueT and dim(shapes.queryT, 1) == numHeads and dim(shapes.queryT, 2) == 3 and packedHeadDim > 0", "separateShapeOk": "ranks.queryT == 2 and present.keyT and present.valueT and ranks.keyT == 2 and ranks.valueT == 2 and sameShape(shapes.keyT, shapes.queryT) and dim(shapes.valueT, 0) == tokenCount and tensorDtypes.keyT == tensorDtypes.queryT and tensorDtypes.valueT == tensorDtypes.queryT", "scheduleOk": "ranks.tokenOffsetT == 2 and ranks.cumulativeSequenceLengthT == 1 and dim(shapes.cumulativeSequenceLengthT, 0) == batchSize + 1 and batchSize > 0 and seqPad > 0 and numel(shapes.tokenOffsetT) >= tokenCount", "outputShapeOk": "ranks.outputT == 2 and dim(shapes.outputT, 0) == tokenCount and dim(shapes.outputT, 1) == vHiddenSize", "biasOk": "present.biasT and ranks.biasT == 1 and dim(shapes.biasT, 0) == 2 * hiddenSize + vHiddenSize and tensorDtypes.biasT == tensorDtypes.queryT", "attnBiasOk": "present.attentionBiasT and ranks.attentionBiasT == 4 and (dim(shapes.attentionBiasT, 0) == 1 or dim(shapes.attentionBiasT, 0) == batchSize) and (attnBiasHeads == 1 or attnBiasHeads == numHeads) and dim(shapes.attentionBiasT, 2) == seqPad and dim(shapes.attentionBiasT, 3) == seqPad and tensorDtypes.attentionBiasT == tensorDtypes.queryT", "hasBias": "present.biasT", "hasAttnBias": "present.attentionBiasT", "baseContract": "dtypeOk and scheduleOk and outputShapeOk and numHeads > 0 and headDim > 0 and vHeadDim > 0 and tokenCount > 0 and (packedShapeOk or separateShapeOk)", "usesF16": "tensorDtypes.queryT == \"float16\"", "scalar": "\"f16\" if usesF16 else \"f32\"", "outputScalar": "scalar", "inputVec4": "\"vec4<f16>\" if usesF16 else \"vec4<f32>\"", "qkvBytes": "2 if usesF16 else 4", "packedStageBytes": "4 if usesF16 and present.biasT and vHeadDim != headDim else qkvBytes", "clusterWidthAligned": "headDim % 16 == 0 and vHeadDim % 4 == 0", "headDimV4": "headDim / 4", "qRowStrideV4": "qRowStride / 4", "qHeadStrideV4": "qHeadStride / 4", "kRowStrideV4": "kRowStride / 4", "kHeadStrideV4": "kHeadStride / 4", "kOffsetV4": "kOffset / 4", "vRowStrideV4": "vRowStride / 4", "vHeadStrideV4": "vHeadStride / 4", "vOffsetV4": "vOffset / 4", "oRowStrideV4": "oRowStride / 4", "oHeadStrideV4": "oHeadStride / 4", "scalarWg": "tunables.SCALAR_WORKGROUP_SIZE", "scalarBytes": "4 * scalarWg + 4 * vHeadDim + 12", "scalarOk": "scalarWg <= device.limits.maxComputeInvocationsPerWorkgroup and scalarWg <= device.limits.maxComputeWorkgroupSizeX and scalarBytes <= device.limits.maxComputeWorkgroupStorageSize and numHeads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)", "clusterTileQ": "min(16, pow2ceil(tokenCount)) if vHeadDim != headDim else 16", "clusterBaseLpq": "8 if headDim % 32 == 0 else 4", "clusterTileK": "min(tunables.CLUSTER_TILE_K, pow2ceil(tokenCount)) if vHeadDim != headDim else tunables.CLUSTER_TILE_K", "clusterTileBytes": "clusterTileK * (headDim + vHeadDim) * packedStageBytes", "clusterLaneTarget": "min(32, max(clusterBaseLpq, pow2ceil(headDim / 16)), device.adapterInfo.subgroupMinSize, pow2ceil(floor(min(device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX) / clusterTileQ) + 1) / 2) if vHeadDim == headDim and clusterWidthAligned and clusterTileBytes <= device.limits.maxComputeWorkgroupStorageSize and device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and device.adapterInfo.subgroupMinSize >= clusterBaseLpq else clusterBaseLpq", "clusterLpq": "clusterLaneTarget if ceilDiv(headDim, 4 * clusterBaseLpq) >= 2 * ceilDiv(headDim, 4 * clusterLaneTarget) else clusterBaseLpq", "clusterWg": "clusterTileQ * clusterLpq", "clusterNosgBytes": "clusterTileBytes + 4 * clusterWg", "clusterTiles": "ceilDiv(tokenCount, clusterTileQ)", "clusterShapeOk": "clusterWidthAligned and clusterWg <= device.limits.maxComputeInvocationsPerWorkgroup and clusterWg <= device.limits.maxComputeWorkgroupSizeX and numHeads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)", "clusterOk": "clusterShapeOk and clusterTileBytes <= device.limits.maxComputeWorkgroupStorageSize", "clusterNosgOk": "clusterShapeOk and clusterNosgBytes <= device.limits.maxComputeWorkgroupStorageSize", "clusterSubgroupsOk": "has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize >= clusterLpq and device.adapterInfo.subgroupMinSize % clusterLpq == 0 and device.adapterInfo.subgroupMaxSize >= device.adapterInfo.subgroupMinSize and device.adapterInfo.subgroupMaxSize % clusterLpq == 0", "portableLaneTarget": "min(64, pow2ceil(max(headDimV4, vHeadDim / 4) / 4), device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX)", "portableLpq": "max(clusterLpq, pow2ceil(portableLaneTarget + 1) / 2) if vHeadDim != headDim else (64 if portableLaneTarget >= 64 and headDimV4 % 64 == 0 else (32 if portableLaneTarget >= 32 and headDimV4 % 32 == 0 else (16 if portableLaneTarget >= 16 and headDimV4 % 16 == 0 else clusterLpq)))", "portableTileQ": "min(clusterTileQ, pow2ceil(tokenCount), max(1, floor(min(clusterWg, device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX) / portableLpq)))", "portableWg": "portableTileQ * portableLpq", "portableKeyCapacity": "max(1, floor(device.limits.maxComputeWorkgroupStorageSize / ((headDim + vHeadDim) * packedStageBytes + 4 * portableWg)))", "portableTileK": "min(clusterTileK, pow2ceil(tokenCount), pow2ceil(portableKeyCapacity + 1) / 2)", "clusterDistributedBytes": "portableTileK * (headDim + vHeadDim) * packedStageBytes + 4 * max(portableWg * portableTileK, 2 * portableWg + portableTileQ * portableTileK)", "clusterDistributedOk": "clusterDistributedBytes <= device.limits.maxComputeWorkgroupStorageSize", "clusterUseDistributed": "clusterDistributedOk and (clusterLpq > 4 or vHeadDim != headDim)", "portableTiles": "ceilDiv(tokenCount, portableTileQ if clusterUseDistributed else clusterTileQ)", "clusterPortableOk": "clusterShapeOk and (clusterUseDistributed or clusterNosgOk) and portableWg <= device.limits.maxComputeInvocationsPerWorkgroup and portableWg <= device.limits.maxComputeWorkgroupSizeX and ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)" }, "bindings": { "query": { "arg": "queryT", "name": "query" }, "key": { "arg": "keyT", "name": "key" }, "value": { "arg": "valueT", "name": "value" }, "bias": { "arg": "biasT", "name": "bias" }, "tokenOffset": { "arg": "tokenOffsetT", "name": "token_offset" }, "cumSeqLen": { "arg": "cumulativeSequenceLengthT", "name": "cumulative_sequence_length" }, "attnBias": { "arg": "attentionBiasT", "name": "attn_bias" }, "output": { "arg": "outputT", "name": "output" }, "query4": { "arg": "queryT", "name": "query", "elementType": "$inputVec4" }, "key4": { "arg": "keyT", "name": "key", "elementType": "$inputVec4" }, "value4": { "arg": "valueT", "name": "value", "elementType": "$inputVec4" }, "output4": { "arg": "outputT", "name": "output", "elementType": "$inputVec4" }, "params": { "name": "params", "struct": [ { "name": "tokenCount", "type": "u32", "value": "tokenCount" }, { "name": "seqPad", "type": "u32", "value": "seqPad" }, { "name": "scale", "type": "f32", "value": "attentionScale" } ] }, "paramsMask": { "name": "params", "struct": [ { "name": "tokenCount", "type": "u32", "value": "tokenCount" }, { "name": "seqPad", "type": "u32", "value": "seqPad" }, { "name": "scale", "type": "f32", "value": "attentionScale" }, { "name": "maskBatchStride", "type": "u32", "value": "maskBatchStride" }, { "name": "maskHeadStride", "type": "u32", "value": "maskHeadStride" }, { "name": "maskSeqStride", "type": "u32", "value": "maskSeqStride" } ] } }, "variants": [ { "id": "packed_flash", "priority": 40, "when": ["baseContract", "packedShapeOk", "not present.biasT", "not present.attentionBiasT", "clusterOk", "clusterSubgroupsOk"], "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "tokenOffset", "cumSeqLen", "output4", "params"], "dispatch": { "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)" } } ], "requires": { "features": ["subgroups"] }, "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"] }, { "id": "packed_flash_nosg", "priority": 20, "when": ["baseContract", "packedShapeOk", "not present.biasT", "not present.attentionBiasT", "clusterPortableOk"], "derive": { "useSubgroups": false, "LPQ": "portableLpq if clusterUseDistributed else clusterLpq", "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ", "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK", "distributedSoftmax": "clusterUseDistributed" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "tokenOffset", "cumSeqLen", "output4", "params"], "dispatch": { "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)" } } ], "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"] }, { "id": "packed_serial", "priority": 0, "when": ["baseContract", "packedShapeOk", "not present.biasT", "not present.attentionBiasT", "scalarOk"], "derive": { "workgroupSize": "scalarWg" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Serial", "shader": "attn-packed-varlen-scalar.wgsl.jinja", "bindings": ["query", "tokenOffset", "cumSeqLen", "output", "params"], "dispatch": { "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)" } } ] }, { "id": "packed_attn_bias_flash", "priority": 40, "when": ["baseContract", "packedShapeOk", "not present.biasT", "attnBiasOk", "clusterOk", "clusterSubgroupsOk"], "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"], "dispatch": { "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)" } } ], "requires": { "features": ["subgroups"] }, "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"] }, { "id": "packed_attn_bias_flash_nosg", "priority": 20, "when": ["baseContract", "packedShapeOk", "not present.biasT", "attnBiasOk", "clusterPortableOk"], "derive": { "useSubgroups": false, "LPQ": "portableLpq if clusterUseDistributed else clusterLpq", "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ", "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK", "distributedSoftmax": "clusterUseDistributed" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"], "dispatch": { "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)" } } ], "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"] }, { "id": "packed_attn_bias_serial", "priority": 0, "when": ["baseContract", "packedShapeOk", "not present.biasT", "attnBiasOk", "scalarOk"], "derive": { "workgroupSize": "scalarWg" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Serial", "shader": "attn-packed-varlen-scalar.wgsl.jinja", "bindings": ["query", "tokenOffset", "cumSeqLen", "attnBias", "output", "paramsMask"], "dispatch": { "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)" } } ] }, { "id": "packed_bias_flash", "priority": 40, "when": ["baseContract", "packedShapeOk", "biasOk", "not present.attentionBiasT", "clusterOk", "clusterSubgroupsOk"], "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "bias", "tokenOffset", "cumSeqLen", "output4", "params"], "dispatch": { "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)" } } ], "requires": { "features": ["subgroups"] }, "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"] }, { "id": "packed_bias_flash_nosg", "priority": 20, "when": ["baseContract", "packedShapeOk", "biasOk", "not present.attentionBiasT", "clusterPortableOk"], "derive": { "useSubgroups": false, "LPQ": "portableLpq if clusterUseDistributed else clusterLpq", "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ", "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK", "distributedSoftmax": "clusterUseDistributed" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "bias", "tokenOffset", "cumSeqLen", "output4", "params"], "dispatch": { "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)" } } ], "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"] }, { "id": "packed_bias_serial", "priority": 0, "when": ["baseContract", "packedShapeOk", "biasOk", "not present.attentionBiasT", "scalarOk"], "derive": { "workgroupSize": "scalarWg" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Serial", "shader": "attn-packed-varlen-scalar.wgsl.jinja", "bindings": ["query", "bias", "tokenOffset", "cumSeqLen", "output", "params"], "dispatch": { "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)" } } ] }, { "id": "packed_bias_attn_bias_flash", "priority": 40, "when": ["baseContract", "packedShapeOk", "biasOk", "attnBiasOk", "clusterOk", "clusterSubgroupsOk"], "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"], "dispatch": { "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)" } } ], "requires": { "features": ["subgroups"] }, "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"] }, { "id": "packed_bias_attn_bias_flash_nosg", "priority": 20, "when": ["baseContract", "packedShapeOk", "biasOk", "attnBiasOk", "clusterPortableOk"], "derive": { "useSubgroups": false, "LPQ": "portableLpq if clusterUseDistributed else clusterLpq", "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ", "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK", "distributedSoftmax": "clusterUseDistributed" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"], "dispatch": { "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)" } } ], "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"] }, { "id": "packed_bias_attn_bias_serial", "priority": 0, "when": ["baseContract", "packedShapeOk", "biasOk", "attnBiasOk", "scalarOk"], "derive": { "workgroupSize": "scalarWg" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Serial", "shader": "attn-packed-varlen-scalar.wgsl.jinja", "bindings": ["query", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output", "paramsMask"], "dispatch": { "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)" } } ] }, { "id": "separate_flash", "priority": 40, "when": ["baseContract", "separateShapeOk", "not present.biasT", "not present.attentionBiasT", "clusterOk", "clusterSubgroupsOk"], "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "key4", "value4", "tokenOffset", "cumSeqLen", "output4", "params"], "dispatch": { "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)" } } ], "requires": { "features": ["subgroups"] }, "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"] }, { "id": "separate_flash_nosg", "priority": 20, "when": ["baseContract", "separateShapeOk", "not present.biasT", "not present.attentionBiasT", "clusterPortableOk"], "derive": { "useSubgroups": false, "LPQ": "portableLpq if clusterUseDistributed else clusterLpq", "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ", "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK", "distributedSoftmax": "clusterUseDistributed" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "key4", "value4", "tokenOffset", "cumSeqLen", "output4", "params"], "dispatch": { "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)" } } ], "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"] }, { "id": "separate_serial", "priority": 0, "when": ["baseContract", "separateShapeOk", "not present.biasT", "not present.attentionBiasT", "scalarOk"], "derive": { "workgroupSize": "scalarWg" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Serial", "shader": "attn-packed-varlen-scalar.wgsl.jinja", "bindings": ["query", "key", "value", "tokenOffset", "cumSeqLen", "output", "params"], "dispatch": { "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)" } } ] }, { "id": "separate_attn_bias_flash", "priority": 40, "when": ["baseContract", "separateShapeOk", "not present.biasT", "attnBiasOk", "clusterOk", "clusterSubgroupsOk"], "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "key4", "value4", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"], "dispatch": { "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)" } } ], "requires": { "features": ["subgroups"] }, "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"] }, { "id": "separate_attn_bias_flash_nosg", "priority": 20, "when": ["baseContract", "separateShapeOk", "not present.biasT", "attnBiasOk", "clusterPortableOk"], "derive": { "useSubgroups": false, "LPQ": "portableLpq if clusterUseDistributed else clusterLpq", "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ", "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK", "distributedSoftmax": "clusterUseDistributed" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "key4", "value4", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"], "dispatch": { "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)" } } ], "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"] }, { "id": "separate_attn_bias_serial", "priority": 0, "when": ["baseContract", "separateShapeOk", "not present.biasT", "attnBiasOk", "scalarOk"], "derive": { "workgroupSize": "scalarWg" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Serial", "shader": "attn-packed-varlen-scalar.wgsl.jinja", "bindings": ["query", "key", "value", "tokenOffset", "cumSeqLen", "attnBias", "output", "paramsMask"], "dispatch": { "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)" } } ] }, { "id": "separate_bias_flash", "priority": 40, "when": ["baseContract", "separateShapeOk", "biasOk", "not present.attentionBiasT", "clusterOk", "clusterSubgroupsOk"], "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "key4", "value4", "bias", "tokenOffset", "cumSeqLen", "output4", "params"], "dispatch": { "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)" } } ], "requires": { "features": ["subgroups"] }, "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"] }, { "id": "separate_bias_flash_nosg", "priority": 20, "when": ["baseContract", "separateShapeOk", "biasOk", "not present.attentionBiasT", "clusterPortableOk"], "derive": { "useSubgroups": false, "LPQ": "portableLpq if clusterUseDistributed else clusterLpq", "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ", "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK", "distributedSoftmax": "clusterUseDistributed" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "key4", "value4", "bias", "tokenOffset", "cumSeqLen", "output4", "params"], "dispatch": { "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)" } } ], "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"] }, { "id": "separate_bias_serial", "priority": 0, "when": ["baseContract", "separateShapeOk", "biasOk", "not present.attentionBiasT", "scalarOk"], "derive": { "workgroupSize": "scalarWg" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Serial", "shader": "attn-packed-varlen-scalar.wgsl.jinja", "bindings": ["query", "key", "value", "bias", "tokenOffset", "cumSeqLen", "output", "params"], "dispatch": { "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)" } } ] }, { "id": "separate_bias_attn_bias_flash", "priority": 40, "when": ["baseContract", "separateShapeOk", "biasOk", "attnBiasOk", "clusterOk", "clusterSubgroupsOk"], "derive": { "useSubgroups": true, "LPQ": "clusterLpq", "TILE_Q": "clusterTileQ", "TILE_K": "clusterTileK" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "key4", "value4", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"], "dispatch": { "x": "min(clusterTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)" } } ], "requires": { "features": ["subgroups"] }, "demoteWhen": ["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))"] }, { "id": "separate_bias_attn_bias_flash_nosg", "priority": 20, "when": ["baseContract", "separateShapeOk", "biasOk", "attnBiasOk", "clusterPortableOk"], "derive": { "useSubgroups": false, "LPQ": "portableLpq if clusterUseDistributed else clusterLpq", "TILE_Q": "portableTileQ if clusterUseDistributed else clusterTileQ", "TILE_K": "portableTileK if clusterUseDistributed else clusterTileK", "distributedSoftmax": "clusterUseDistributed" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Cluster", "shader": "attn-packed-varlen-cluster.wgsl.jinja", "bindings": ["query4", "key4", "value4", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output4", "paramsMask"], "dispatch": { "x": "min(portableTiles, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH)" } } ], "demoteWhen": ["vHeadDim != headDim and tokenCount < clusterLpq"] }, { "id": "separate_bias_attn_bias_serial", "priority": 0, "when": ["baseContract", "separateShapeOk", "biasOk", "attnBiasOk", "scalarOk"], "derive": { "workgroupSize": "scalarWg" }, "passes": [ { "id": "main", "name": "PackedMultiHeadAttention.Serial", "shader": "attn-packed-varlen-scalar.wgsl.jinja", "bindings": ["query", "key", "value", "bias", "tokenOffset", "cumSeqLen", "attnBias", "output", "paramsMask"], "dispatch": { "x": "min(tokenCount, DISPATCH_FOLD_WIDTH)", "y": "numHeads", "z": "ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)" } } ] } ]}{"domain":"com.microsoft","name":"PackedMultiHeadAttention","sinceVersion":1,"inputs":{"queryT":{"onnx":"query","dtype":"T"},"keyT":{"onnx":"key","dtype":"T","rank":2,"optional":true},"valueT":{"onnx":"value","dtype":"T","rank":2,"optional":true},"biasT":{"onnx":"bias","dtype":"T","rank":1,"optional":true},"tokenOffsetT":{"onnx":"token_offset","dtype":"M","rank":2,"storage":"int32"},"cumulativeSequenceLengthT":{"onnx":"cumulative_sequence_length","dtype":"M","rank":1,"storage":"int32"},"attentionBiasT":{"onnx":"attention_bias","dtype":"T","rank":4,"optional":true}},"outputs":{"outputT":{"onnx":"output","dtype":"T","rank":2,"shape":"[tokenCount, vHiddenSize]"}},"attributes":{"num_heads":{},"scale":{}},"attributeConstraints":{"num_heads":{"required":true}},"typeConstraints":{"T":["float32","float16"],"M":["int32"]},"tunables":{"CLUSTER_TILE_K":{"default":16},"SCALAR_WORKGROUP_SIZE":{"default":64}},"derive":{"numHeads":"attrs.num_heads","qNumHeads":"numHeads","packedQkv":"ranks.queryT == 4","tokenCount":"dim(shapes.queryT, 0)","batchSize":"dim(shapes.tokenOffsetT, 0) if ranks.tokenOffsetT == 2 else 0","seqPad":"dim(shapes.tokenOffsetT, 1) if ranks.tokenOffsetT == 2 else 0","packedHeadDim":"dim(shapes.queryT, 3) if packedQkv else 0","hiddenSize":"numHeads * packedHeadDim if packedQkv else (dim(shapes.queryT, 1) if ranks.queryT == 2 else 0)","vHiddenSize":"hiddenSize if packedQkv else (dim(shapes.valueT, 1) if present.valueT and ranks.valueT == 2 else 0)","headDim":"hiddenSize / numHeads if numHeads > 0 and hiddenSize % numHeads == 0 else 0","vHeadDim":"vHiddenSize / numHeads if numHeads > 0 and vHiddenSize % numHeads == 0 else 0","attentionScale":"attrs.scale if has(attrs, \"scale\") else 0","qRowStride":"numHeads * 3 * headDim if packedQkv else hiddenSize","qHeadStride":"3 * headDim if packedQkv else headDim","kRowStride":"qRowStride if packedQkv else hiddenSize","kHeadStride":"qHeadStride if packedQkv else headDim","kOffset":"headDim if packedQkv else 0","vRowStride":"qRowStride if packedQkv else vHiddenSize","vHeadStride":"qHeadStride if packedQkv else vHeadDim","vOffset":"2 * headDim if packedQkv else 0","oRowStride":"vHiddenSize","oHeadStride":"vHeadDim","biasKOffset":"hiddenSize","biasVOffset":"2 * hiddenSize","attnBiasHeads":"dim(shapes.attentionBiasT, 1) if present.attentionBiasT and ranks.attentionBiasT == 4 else 0","maskSeqStride":"seqPad","maskHeadStride":"0 if attnBiasHeads == 1 else seqPad * seqPad","maskBatchStride":"0 if (not present.attentionBiasT) or ranks.attentionBiasT != 4 or dim(shapes.attentionBiasT, 0) == 1 else attnBiasHeads * seqPad * seqPad","dtypeOk":"tensorDtypes.outputT == tensorDtypes.queryT and (tensorDtypes.queryT == \"float32\" or tensorDtypes.queryT == \"float16\") and f16Ok(dtypes.T)","packedShapeOk":"packedQkv and not present.keyT and not present.valueT and dim(shapes.queryT, 1) == numHeads and dim(shapes.queryT, 2) == 3 and packedHeadDim > 0","separateShapeOk":"ranks.queryT == 2 and present.keyT and present.valueT and ranks.keyT == 2 and ranks.valueT == 2 and sameShape(shapes.keyT, shapes.queryT) and dim(shapes.valueT, 0) == tokenCount and tensorDtypes.keyT == tensorDtypes.queryT and tensorDtypes.valueT == tensorDtypes.queryT","scheduleOk":"ranks.tokenOffsetT == 2 and ranks.cumulativeSequenceLengthT == 1 and dim(shapes.cumulativeSequenceLengthT, 0) == batchSize + 1 and batchSize > 0 and seqPad > 0 and numel(shapes.tokenOffsetT) >= tokenCount and tokenCount <= 2147483647","outputShapeOk":"ranks.outputT == 2 and dim(shapes.outputT, 0) == tokenCount and dim(shapes.outputT, 1) == vHiddenSize","biasOk":"present.biasT and ranks.biasT == 1 and dim(shapes.biasT, 0) == 2 * hiddenSize + vHiddenSize and tensorDtypes.biasT == tensorDtypes.queryT","attnBiasOk":"present.attentionBiasT and ranks.attentionBiasT == 4 and (dim(shapes.attentionBiasT, 0) == 1 or dim(shapes.attentionBiasT, 0) == batchSize) and (attnBiasHeads == 1 or attnBiasHeads == numHeads) and dim(shapes.attentionBiasT, 2) == seqPad and dim(shapes.attentionBiasT, 3) == seqPad and tensorDtypes.attentionBiasT == tensorDtypes.queryT","hasBias":"present.biasT","hasAttnBias":"present.attentionBiasT","baseContract":"dtypeOk and scheduleOk and outputShapeOk and numHeads > 0 and headDim > 0 and vHeadDim > 0 and tokenCount > 0 and (packedShapeOk or separateShapeOk)","usesF16":"tensorDtypes.queryT == \"float16\"","scalar":"\"f16\" if usesF16 else \"f32\"","outputScalar":"scalar","inputVec4":"\"vec4<f16>\" if usesF16 else \"vec4<f32>\"","qkvBytes":"2 if usesF16 else 4","packedStageBytes":"4 if usesF16 and present.biasT and vHeadDim != headDim else qkvBytes","clusterWidthAligned":"headDim % 16 == 0 and vHeadDim % 4 == 0","nvidiaAdapter":"has(device.adapterInfo, \"vendor\") and device.adapterInfo.vendor == \"nvidia\"","adreno6xxAdapter":"has(device.adapterInfo, \"architecture\") and device.adapterInfo.architecture == \"adreno-6xx\"","headDimV4":"headDim / 4","qRowStrideV4":"qRowStride / 4","qHeadStrideV4":"qHeadStride / 4","kRowStrideV4":"kRowStride / 4","kHeadStrideV4":"kHeadStride / 4","kOffsetV4":"kOffset / 4","vRowStrideV4":"vRowStride / 4","vHeadStrideV4":"vHeadStride / 4","vOffsetV4":"vOffset / 4","oRowStrideV4":"oRowStride / 4","oHeadStrideV4":"oHeadStride / 4","scalarWg":"tunables.SCALAR_WORKGROUP_SIZE","scalarBytes":"4 * scalarWg + 4 * vHeadDim + 12","scalarOk":"scalarWg <= device.limits.maxComputeInvocationsPerWorkgroup and scalarWg <= device.limits.maxComputeWorkgroupSizeX and scalarBytes <= device.limits.maxComputeWorkgroupStorageSize and numHeads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","clusterTileQ":"min(16, pow2ceil(tokenCount)) if vHeadDim != headDim else 16","clusterBaseLpq":"8 if headDim % 32 == 0 else 4","clusterTileK":"min(tunables.CLUSTER_TILE_K, pow2ceil(tokenCount)) if vHeadDim != headDim else tunables.CLUSTER_TILE_K","clusterTileBytes":"clusterTileK * (headDim + vHeadDim) * packedStageBytes","clusterLaneTarget":"min(32, max(clusterBaseLpq, pow2ceil(headDim / 16)), device.adapterInfo.subgroupMinSize, pow2ceil(floor(min(device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX) / clusterTileQ) + 1) / 2) if vHeadDim == headDim and clusterWidthAligned and clusterTileBytes <= device.limits.maxComputeWorkgroupStorageSize and device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and device.adapterInfo.subgroupMinSize >= clusterBaseLpq else clusterBaseLpq","clusterLpq":"clusterLaneTarget if ceilDiv(headDim, 4 * clusterBaseLpq) >= 2 * ceilDiv(headDim, 4 * clusterLaneTarget) else clusterBaseLpq","clusterWg":"clusterTileQ * clusterLpq","clusterNosgBytes":"clusterTileBytes + 4 * clusterWg","clusterTiles":"ceilDiv(tokenCount, clusterTileQ)","clusterShapeOk":"clusterWidthAligned and clusterWg <= device.limits.maxComputeInvocationsPerWorkgroup and clusterWg <= device.limits.maxComputeWorkgroupSizeX and numHeads <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535) and ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","clusterOk":"clusterShapeOk and clusterTileBytes + 4 * clusterWg + 8 <= device.limits.maxComputeWorkgroupStorageSize","clusterNosgOk":"clusterShapeOk and clusterNosgBytes <= device.limits.maxComputeWorkgroupStorageSize","clusterSubgroupsOk":"has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize >= clusterLpq and device.adapterInfo.subgroupMinSize % clusterLpq == 0 and device.adapterInfo.subgroupMaxSize >= device.adapterInfo.subgroupMinSize and device.adapterInfo.subgroupMaxSize % clusterLpq == 0 and not adreno6xxAdapter","portableLaneTarget":"min(64, pow2ceil(max(headDimV4, vHeadDim / 4) / 4), device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX)","portableLpq":"max(clusterLpq, pow2ceil(portableLaneTarget + 1) / 2) if vHeadDim != headDim else (64 if portableLaneTarget >= 64 and headDimV4 % 64 == 0 else (32 if portableLaneTarget >= 32 and headDimV4 % 32 == 0 else (16 if portableLaneTarget >= 16 and headDimV4 % 16 == 0 else clusterLpq)))","portableTileQ":"min(clusterTileQ, pow2ceil(tokenCount), max(1, floor(min(clusterWg, device.limits.maxComputeInvocationsPerWorkgroup, device.limits.maxComputeWorkgroupSizeX) / portableLpq)))","portableWg":"portableTileQ * portableLpq","portableKeyCapacity":"max(1, floor(device.limits.maxComputeWorkgroupStorageSize / ((headDim + vHeadDim) * packedStageBytes + 4 * portableWg)))","portableTileK":"min(clusterTileK, pow2ceil(tokenCount), pow2ceil(portableKeyCapacity + 1) / 2)","clusterDistributedBytes":"portableTileK * (headDim + vHeadDim) * packedStageBytes + 4 * max(portableWg * portableTileK, 2 * portableWg + portableTileQ * portableTileK)","clusterDistributedOk":"clusterDistributedBytes <= device.limits.maxComputeWorkgroupStorageSize","clusterUseDistributed":"clusterDistributedOk and (clusterLpq > 4 or vHeadDim != headDim)","portableTiles":"ceilDiv(tokenCount, portableTileQ if clusterUseDistributed else clusterTileQ)","clusterPortableOk":"clusterShapeOk and (clusterUseDistributed or clusterNosgOk) and portableWg <= device.limits.maxComputeInvocationsPerWorkgroup and portableWg <= device.limits.maxComputeWorkgroupSizeX and ceilDiv(portableTiles, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","clusterDistributedPreferred":"vHeadDim == headDim and clusterUseDistributed and clusterPortableOk and clusterTiles * numHeads < 32 and (not usesF16 or (clusterDistributedBytes <= clusterTileBytes + 4 * clusterWg + 8 and clusterTiles * numHeads < 16)) and (present.attentionBiasT or headDimV4 > clusterLpq or clusterTiles == 1)","blackwellAdapter":"nvidiaAdapter and has(device.adapterInfo, \"architecture\") and device.adapterInfo.architecture == \"blackwell\"","storageLimitedF32":"blackwellAdapter and not usesF16 and vHeadDim == headDim and not clusterNosgOk","wideLanes":"min(portableWg, pow2ceil(portableLaneTarget + 1) / 2)","wideTileQ":"portableWg / wideLanes","wideQueryTiles":"ceilDiv(tokenCount, wideTileQ)","valueSlicesNeedLanes":"wideLanes > portableLpq and headDimV4 > portableLpq * portableTileK","spreadValueSlices":"storageLimitedF32 and valueSlicesNeedLanes and ceilDiv(wideQueryTiles, DISPATCH_FOLD_WIDTH) <= min(device.limits.maxComputeWorkgroupsPerDimension, 65535)","portableQueryTiles":"wideQueryTiles if spreadValueSlices else portableTiles","resourceDistributedShapeOk":"clusterLpq == 4 and portableLpq == clusterLpq and headDimV4 > clusterLpq","resourceDistributedStorageOk":"clusterShapeOk and clusterDistributedOk and portableTileK >= 1 and portableTileK == floor(portableTileK)","resourceDistributedOk":"storageLimitedF32 and resourceDistributedShapeOk and resourceDistributedStorageOk"},"when":["baseContract","biasOk or not hasBias","attnBiasOk or not hasAttnBias"],"bindings":{"query":{"arg":"queryT","name":"query"},"key":{"arg":"keyT","name":"key","when":"present.keyT"},"value":{"arg":"valueT","name":"value","when":"present.valueT"},"bias":{"arg":"biasT","name":"bias","when":"hasBias"},"tokenOffset":{"arg":"tokenOffsetT","name":"token_offset"},"cumSeqLen":{"arg":"cumulativeSequenceLengthT","name":"cumulative_sequence_length"},"attnBias":{"arg":"attentionBiasT","name":"attn_bias","when":"hasAttnBias"},"output":{"arg":"outputT","name":"output"},"query4":{"arg":"queryT","name":"query","elementType":"$inputVec4"},"key4":{"arg":"keyT","name":"key","elementType":"$inputVec4","when":"present.keyT"},"value4":{"arg":"valueT","name":"value","elementType":"$inputVec4","when":"present.valueT"},"output4":{"arg":"outputT","name":"output","elementType":"$inputVec4"},"params":{"name":"params","struct":[{"name":"tokenCount","type":"u32","value":"tokenCount"},{"name":"seqPad","type":"u32","value":"seqPad"},{"name":"scale","type":"f32","value":"attentionScale"}],"when":"not hasAttnBias"},"paramsMask":{"name":"params","struct":[{"name":"tokenCount","type":"u32","value":"tokenCount"},{"name":"seqPad","type":"u32","value":"seqPad"},{"name":"scale","type":"f32","value":"attentionScale"},{"name":"maskBatchStride","type":"u32","value":"maskBatchStride"},{"name":"maskHeadStride","type":"u32","value":"maskHeadStride"},{"name":"maskSeqStride","type":"u32","value":"maskSeqStride"}],"when":"hasAttnBias"}},"variants":[{"id":"flash","priority":40,"when":["clusterOk","clusterSubgroupsOk"],"derive":{"useSubgroups":true,"LPQ":"clusterLpq","TILE_Q":"clusterTileQ","TILE_K":"clusterTileK"},"passes":[{"id":"main","name":"PackedMultiHeadAttention.Cluster","shader":"attn-packed-varlen-cluster.wgsl.jinja","bindings":["query4","key4","value4","bias","tokenOffset","cumSeqLen","attnBias","output4","params","paramsMask"],"dispatch":{"x":"min(clusterTiles, DISPATCH_FOLD_WIDTH)","y":"numHeads","z":"ceilDiv(clusterTiles, DISPATCH_FOLD_WIDTH)"}}],"requires":{"features":["subgroups"]},"demoteWhen":["vHeadDim != headDim and (tokenCount < clusterLpq or (clusterUseDistributed and portableLpq > clusterLpq))","clusterDistributedPreferred","vHeadDim == headDim and clusterPortableOk and device.features.has(\"subgroups\") and has(device.adapterInfo, \"subgroupMinSize\") and has(device.adapterInfo, \"subgroupMaxSize\") and device.adapterInfo.subgroupMinSize == 16 and device.adapterInfo.subgroupMaxSize == 32 and 2 * clusterTileBytes >= device.limits.maxComputeWorkgroupStorageSize and (clusterLpq == clusterBaseLpq or tokenCount >= clusterTileQ * clusterLpq) and (not usesF16 or tokenCount >= clusterTileQ * clusterLpq) and (not usesF16 or (clusterUseDistributed and clusterDistributedBytes + packedStageBytes * portableWg * portableTileK <= clusterTileBytes + 4 * clusterWg + 8))"]},{"id":"flash_nosg","priority":20,"when":["clusterPortableOk or resourceDistributedOk"],"derive":{"resourceDistributed":"not clusterPortableOk or spreadValueSlices","useSubgroups":false,"distributedSoftmax":"clusterUseDistributed or resourceDistributed","LPQ":"wideLanes if spreadValueSlices else (portableLpq if distributedSoftmax else clusterLpq)","TILE_Q":"wideTileQ if spreadValueSlices else (portableTileQ if distributedSoftmax else clusterTileQ)","TILE_K":"portableTileK if distributedSoftmax else clusterTileK"},"passes":[{"id":"main","name":"PackedMultiHeadAttention.Cluster","shader":"attn-packed-varlen-cluster.wgsl.jinja","bindings":["query4","key4","value4","bias","tokenOffset","cumSeqLen","attnBias","output4","params","paramsMask"],"dispatch":{"x":"min(portableQueryTiles, DISPATCH_FOLD_WIDTH)","y":"numHeads","z":"ceilDiv(portableQueryTiles, DISPATCH_FOLD_WIDTH)"}}],"demoteWhen":["vHeadDim != headDim and tokenCount < clusterLpq"]},{"id":"serial","priority":0,"when":["scalarOk"],"derive":{"workgroupSize":"scalarWg"},"passes":[{"id":"main","name":"PackedMultiHeadAttention.Serial","shader":"attn-packed-varlen-scalar.wgsl.jinja","bindings":["query","key","value","bias","tokenOffset","cumSeqLen","attnBias","output","params","paramsMask"],"dispatch":{"x":"min(tokenCount, DISPATCH_FOLD_WIDTH)","y":"numHeads","z":"ceilDiv(tokenCount, DISPATCH_FOLD_WIDTH)"}}]}]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546471{ "name": "com.microsoft.PackedMultiHeadAttention", "id": "_com_microsoft_packedmultiheadattention_webgpu_96b8ba0", "version": 1, "license": "Apache-2.0", "backend": { "type": "webgpu" }, "digest": { "algorithm": "sha256", "files": { "attn-packed-varlen-cluster.wgsl.jinja": "p9O8Y9FODuK+3sS5XCmt34ubccsQ1rHO8KyYdKFbox8=", "attn-packed-varlen-scalar.wgsl.jinja": "6gm8Q90Uq/Fwm53KBabaxD39SZDE/XPt93lhHeOKEKo=", "bench.json": "QU1tbtEXCd2xke0vrPrixj1rlwWltGZXLr8StqGlVuM=", "manifest.json": "CImYmm6QB0MSplEddT1DpForRg78IeIsHWzBijr+yks=", "test.json": "Y3VjrtppOZI+cmCpPGhsEdWnF8qd981T9VIMTNux648=" } }, "provenance": { "kernel": { "sha": "6fdf6301e2bbcc2f03bf1eaf493b7ad55ef33afc", "dirty": false } }, "webgpu": { "manifestSpec": "2.1", "variants": { "packed_flash": ["attn-packed-varlen-cluster.wgsl.jinja"], "packed_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"], "packed_serial": ["attn-packed-varlen-scalar.wgsl.jinja"], "packed_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"], "packed_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"], "packed_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"], "packed_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"], "packed_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"], "packed_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"], "packed_bias_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"], "packed_bias_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"], "packed_bias_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"], "separate_flash": ["attn-packed-varlen-cluster.wgsl.jinja"], "separate_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"], "separate_serial": ["attn-packed-varlen-scalar.wgsl.jinja"], "separate_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"], "separate_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"], "separate_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"], "separate_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"], "separate_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"], "separate_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"], "separate_bias_attn_bias_flash": ["attn-packed-varlen-cluster.wgsl.jinja"], "separate_bias_attn_bias_flash_nosg": ["attn-packed-varlen-cluster.wgsl.jinja"], "separate_bias_attn_bias_serial": ["attn-packed-varlen-scalar.wgsl.jinja"] } }}{"name":"com.microsoft.PackedMultiHeadAttention","id":"_com_microsoft_packedmultiheadattention_webgpu_17a5f5c","version":1,"license":"Apache-2.0","backend":{"type":"webgpu"},"digest":{"algorithm":"sha256","files":{"attn-packed-varlen-cluster.wgsl.jinja":"uy6sVyGKPRfrloKCXZfcTcQDqjbaQAO07P/KMOPyOP4=","attn-packed-varlen-scalar.wgsl.jinja":"uV47zEaYCCHM8wGvHrctI8XIyMtEI072DMw4eKCp62k=","bench.json":"MiMPAxLiavb6A+R4tkJFaDfoEa85U0gqggFHVGCrWH4=","manifest.json":"SmdtEioZt9Ysg6ybDSMCgwVTH7XqpfdqcvJc9tQJVao=","test.json":"RggkJ/lGkIPqjHBx2YP7j0NKdzyNEQDhhR1JlGUEDos="}},"provenance":{"kernel":{"sha":"4385228f788ddaa1bd7aec6a80a20f3ddffd8011","dirty":false}},"webgpu":{"manifestSpec":"2.2"}}README.md+32-41
build/webgpu/attn-packed-varlen-cluster.wgsl.jinja+556-36
build/webgpu/attn-packed-varlen-scalar.wgsl.jinja+434-11
build/webgpu/bench.json+1-1
build/webgpu/manifest.json+1-667
build/webgpu/metadata.json+1-47
build/webgpu/test.json