com.microsoft.GroupQueryAttention / build /webgpu /attn-decode-gqa-splitk.wgsl.jinja
Xenova's picture
Xenova HF Staff
sync 4385228f788d
772a078 verified
Raw History Blame
31.5 kB
{%- set BHSD = true -%}
{%- set SEQLENS = BHSD and gqaSeqlens is defined and gqaSeqlens -%}
{%- if SEQLENS %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %}
{% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {{ attn_seqlens_count(index) }}){% endmacro %}
{% endif %}
{% set NORMALIZED_VALUES = gqaNormalizedValues | default(false) %}
{{ env.wgsl.resourceDeclarations }}
{% if NORMALIZED_VALUES %}
{% macro sum_error_function(name, type="f32", protectDifference=false) %}
{% set bitsType = type | replace("f32", "u32") %}
// Observing the rounded sum as bits preserves FastTwoSum on backends
// that otherwise reassociate its subtractions. Both signs of zero contribute zero.
fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} {
let bits = bitcast<{{ bitsType }}>(x);
return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u)));
}
fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} {
let swap = abs(a) < abs(b);
let larger = select(a, b, swap);
let smaller = select(b, a, swap);
// Keep the rounded high-part difference observable before subtracting it
// from the smaller addend. Reassociation here erases the residual.
return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger);
}
{% endmacro %}
{% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %}
{% set N = 1 if type == "f32" else (type[3] | int) %}
{% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "<i32>" %}
{% set boolType = "bool" if N == 1 else "vec" ~ N ~ "<bool>" %}
{% set exact = add or rescale or merge %}
{% set boundNumerator = boundValueNumerator | default(false) %}
{% if boundNumerator and (exact or tile) %}
// Even a u32 key count times this magnitude leaves a bit of f32 exponent
// headroom for a partial sum. Larger terms use the exponent-aware path.
const VALUE_FAST_LIMIT: f32 = 0x1p94f;
{% endif %}
struct ScaledValueScalar { hi: f32, lo: f32, exponent: i32 }
struct ScaledValue { hi: {{ type }}, lo: {{ type }}, exponent: {{ exponentType }} }
{% if exact %}
fn scaled_value_scalar_zero() -> ScaledValueScalar {
return ScaledValueScalar(0.0, 0.0, 0);
}
{% endif %}
fn scaled_value_scalar_finite(x: f32) -> bool {
return abs(x) <= 3.4028234663852886e38;
}
{% if exact or align %}
fn scaled_value_scalar_leading(a: ScaledValueScalar) -> i32 {
if (a.hi == 0.0) {
if (a.lo == 0.0) { return -1024; }
return a.exponent + frexp(a.lo).exp;
}
if (!scaled_value_scalar_finite(a.hi)) { return 1024; }
return a.exponent + frexp(a.hi).exp;
}
{% endif %}
// Scale the significand bits directly. WGSL ldexp may return zero for a
// shift <= -127 even when its input makes the final result normal; shifts
// above 128 are indeterminate. Neither limit applies to this exponent sum.
fn scaled_value_scalar_shift(value: f32, shift: i32) -> f32 {
let bits = bitcast<u32>(value);
let sign = bits & 0x80000000u;
let fraction = bits & 0x007fffffu;
let inputExponent = i32((bits >> 23u) & 0xffu);
if (inputExponent == 255 || (inputExponent == 0 && fraction == 0u)) { return value; }
var significand = fraction | 0x00800000u;
var exponent = inputExponent + shift;
if (inputExponent == 0) {
let normalize = countLeadingZeros(fraction) - 8u;
significand = fraction << normalize;
exponent = 1 + shift - i32(normalize);
}
if (exponent >= 255) { return bitcast<f32>(sign | 0x7f800000u); }
if (exponent > 0) {
return bitcast<f32>(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu));
}
let distance = u32(1 - exponent);
if (distance > 24u) { return bitcast<f32>(sign); }
let high = significand >> distance;
let remainder = significand & ((1u << distance) - 1u);
let halfway = 1u << (distance - 1u);
let roundUp = remainder > halfway || (remainder == halfway && (high & 1u) != 0u);
return bitcast<f32>(sign | (high + select(0u, 1u, roundUp)));
}
{% if exact or align %}
fn scaled_value_scalar_align(a: ScaledValueScalar, exponent: i32) -> ScaledValueScalar {
if (a.hi == 0.0 && a.lo == 0.0) { return ScaledValueScalar(0.0, 0.0, exponent); }
if (!scaled_value_scalar_finite(a.hi)) { return ScaledValueScalar(a.hi, 0.0, exponent); }
return ScaledValueScalar(scaled_value_scalar_shift(a.hi, a.exponent - exponent), scaled_value_scalar_shift(a.lo, a.exponent - exponent), exponent);
}
{% endif %}
{% if exact %}
{% if recoverSum %}
{{ sum_error_function("scaled_value_sum_error", protectDifference=true) }}
{% endif %}
fn scaled_value_scalar_finish(hi: f32, lo: f32, exponent: i32) -> ScaledValueScalar {
let nextHi = fma(hi, 1.0, lo);
let nextLo = {% if recoverSum %}scaled_value_sum_error(hi, lo, nextHi){% else %}fma(-1.0, fma(-1.0, hi, nextHi), lo){% endif %};
if (nextHi == 0.0) { return scaled_value_scalar_zero(); }
if (!scaled_value_scalar_finite(nextHi)) { return ScaledValueScalar(nextHi, 0.0, 0); }
let parts = frexp(nextHi);
let rawExponent = exponent + parts.exp;
// Ordinary magnitudes return to the unscaled fast path. The margin keeps
// boundary values away from overflow/underflow while scaling the low word.
if (rawExponent >= -120 && rawExponent <= 120) {
return ScaledValueScalar(scaled_value_scalar_shift(nextHi, exponent), scaled_value_scalar_shift(nextLo, exponent), 0);
}
return ScaledValueScalar(parts.fract, scaled_value_scalar_shift(nextLo, -parts.exp), rawExponent);
}
fn scaled_value_scalar_add_words(a: ScaledValueScalar, product: f32, error: f32) -> ScaledValueScalar {
let sum = fma(a.hi, 1.0, product);
let bv = fma(-1.0, a.hi, sum);
let av = fma(-1.0, bv, sum);
let ae = fma(-1.0, av, a.hi);
let be = fma(-1.0, bv, product);
let residual = fma(fma(fma(ae, 1.0, be), 1.0, a.lo), 1.0, error);
let hi = fma(sum, 1.0, residual);
return ScaledValueScalar(hi, fma(-1.0, fma(-1.0, sum, hi), residual), a.exponent);
}
fn scaled_value_scalar_combine(a: ScaledValueScalar, weight: f32, b: ScaledValueScalar) -> ScaledValueScalar {
if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(a.lo) ||
!scaled_value_scalar_finite(b.hi) || !scaled_value_scalar_finite(b.lo) ||
!scaled_value_scalar_finite(weight)) {
return ScaledValueScalar(fma(weight, b.hi, a.hi), 0.0, 0);
}
if (weight == 0.0 || (b.hi == 0.0 && b.lo == 0.0)) { return a; }
if (weight == 1.0 && a.hi == 0.0 && a.lo == 0.0) { return b; }
if (a.exponent == 0 && b.exponent == 0{% if boundNumerator %} && abs(a.hi) <= VALUE_FAST_LIMIT && abs(b.hi) <= VALUE_FAST_LIMIT{% endif %}) {
let product = fma(weight, b.hi, 0.0);
let lowProduct = fma(weight, b.lo, 0.0);
let rawSum = fma(a.hi, 1.0, product);
let productNormal = abs(product) >= 1.1754943508222875e-38;
if (productNormal && scaled_value_scalar_finite(product) &&
scaled_value_scalar_finite(lowProduct) && scaled_value_scalar_finite(rawSum)) {
let error = fma(fma(weight, b.hi, -product), 1.0, lowProduct);
let result = scaled_value_scalar_add_words(a, product, error);
if (scaled_value_scalar_finite(result.hi) && scaled_value_scalar_finite(result.lo)) { return result; }
}
}
// Decompose BEFORE multiplying: a merge coefficient may exceed one, so
// its unscaled product with a finite partial mean need not fit in f32.
var other = b;
if (other.hi == 0.0) { other = ScaledValueScalar(other.lo, 0.0, other.exponent); }
let wp = frexp(weight);
let vp = frexp(other.hi);
let productExponent = other.exponent + wp.exp + vp.exp;
let commonExponent = max(scaled_value_scalar_leading(a), productExponent);
let aligned = scaled_value_scalar_align(a, commonExponent);
let product = fma(wp.fract, vp.fract, 0.0);
let productError = fma(wp.fract, vp.fract, -product);
let shift = productExponent - commonExponent;
let highWord = scaled_value_scalar_shift(product, shift);
let lowWord = fma(scaled_value_scalar_shift(productError, shift), 1.0,
fma(wp.fract, scaled_value_scalar_shift(other.lo, other.exponent + wp.exp - commonExponent), 0.0));
{% if recoverSum %}
let sum = aligned.hi + highWord;
let low = (scaled_value_sum_error(aligned.hi, highWord, sum) + aligned.lo) + lowWord;
return scaled_value_scalar_finish(sum, low, commonExponent);
{% else %}
let result = scaled_value_scalar_add_words(aligned, highWord, lowWord);
return scaled_value_scalar_finish(result.hi, result.lo, commonExponent);
{% endif %}
}
{% endif %}
fn scaled_value_scalar_mean(a: ScaledValueScalar, denominator: f32) -> f32 {
if (denominator == 0.0) { return 0.0; }
if (a.hi == 0.0 && a.lo == 0.0) { return 0.0; }
if (!scaled_value_scalar_finite(a.hi) || !scaled_value_scalar_finite(denominator)) {
return fma(a.hi, 1.0, a.lo) / denominator;
}
let valueParts = frexp(a.hi);
let denominatorParts = frexp(denominator);
let mantissa = fma(valueParts.fract, 1.0, scaled_value_scalar_shift(a.lo, -valueParts.exp));
let quotient = mantissa / denominatorParts.fract;
return scaled_value_scalar_shift(quotient, a.exponent + valueParts.exp - denominatorParts.exp);
}
fn scaled_value_zero() -> ScaledValue {
return ScaledValue({{ type }}(0.0), {{ type }}(0.0), {{ exponentType }}(0));
}
{% if N > 1 or rescale or lean %}
// Vector form of scaled_value_scalar_add_words: applies it to every component at once.
fn scaled_value_add_words(acc: ScaledValue, product: {{ type }}, error: {{ type }}) -> ScaledValue {
let sum = fma(acc.hi, {{ type }}(1.0), product);
{% if magnitudeOrdered %}
// FastTwoSum recovers the rounding error with the larger magnitude first.
let takeProduct = abs(acc.hi) < abs(product);
let larger = select(acc.hi, product, takeProduct);
let smaller = select(product, acc.hi, takeProduct);
let roundoff = fma({{ type }}(-1.0), fma({{ type }}(-1.0), larger, sum), smaller);
let residual = fma(fma(roundoff, {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);
{% else %}
let bv = fma({{ type }}(-1.0), acc.hi, sum);
let av = fma({{ type }}(-1.0), bv, sum);
let ae = fma({{ type }}(-1.0), av, acc.hi);
let be = fma({{ type }}(-1.0), bv, product);
let residual = fma(fma(fma(ae, {{ type }}(1.0), be), {{ type }}(1.0), acc.lo), {{ type }}(1.0), error);
{% endif %}
let hi = fma(sum, {{ type }}(1.0), residual);
return ScaledValue(hi, fma({{ type }}(-1.0), fma({{ type }}(-1.0), sum, hi), residual), acc.exponent);
}
{% endif %}
{% if lean %}
// Lean folds: the compensated arithmetic of scaled_value_add_step with every
// check deferred to the fold's end. A fold that starts from a normalized pair at
// exponent zero (the high word is the words' rounded sum), ends with finite words
// (a non-finite word stays non-finite through the sum, so this covers the start
// too), and whose smallest nonzero weight times smallest nonzero value is normal
// took only steps whose result is scaled_value_add's, up to the sign of a zero
// word: each nonzero product was normal, every step leaves the pair normalized,
// and a zero product leaves a normalized pair unchanged.
fn scaled_value_lean_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {
let w = {{ type }}(weight);
let product = fma(w, value, {{ type }}(0.0));
return scaled_value_add_words(acc, product, fma(w, value, -product));
}
// The smallest nonzero magnitude among `low` and `value`, per component.
fn scaled_value_nonzero_low(low: {{ type }}, value: {{ type }}) -> {{ type }} {
return min(low, select({{ type }}(3.4028234663852886e38), abs(value), value != {{ type }}(0.0)));
}
fn scaled_value_lean_exact(start: ScaledValue, acc: ScaledValue, weightLow: {{ coefficientType }}, valueLow: {{ type }}) -> bool {
return all(start.exponent == {{ exponentType }}(0)) &&
all((fma(start.hi, {{ type }}(1.0), start.lo) == start.hi) &
(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &
({{ type }}(weightLow) * valueLow >= {{ type }}(1.1754943508222875e-38)));
}
{% endif %}
{% if N > 1 and tile %}
{% set uType = "vec" ~ N ~ "<u32>" %}
// Offset tile folds. A tile's products, at most `bound` in total magnitude per
// component, add onto `offset`, the power of two above 2.25 * bound, so every
// partial sum stays within [offset / 2, 2 * offset): each step's change to it is
// exact, and the low word gathers each step's remainder, at most half an ulp of
// the offset, rounded once. n steps err by at most n * (n + 3) / 2 * 2^-48 of the
// offset, where scaled_value_add steps err by about n * 2^-48 of the running value. A
// non-finite weight, value or bound leaves a non-finite word, and a bound past
// 2^126 an infinite offset, so a caller checks finiteness once, after its fold;
// scaled_value_tile_in_range checks what that cannot see.
struct ScaledValueTile { offset: {{ type }}, sum: {{ type }}, low: {{ type }} }
fn scaled_value_tile(bound: {{ type }}) -> ScaledValueTile {
let bits = bitcast<{{ uType }}>({{ type }}(2.25) * min(bound, {{ type }}(8.507059173023462e37)));
let offset = bitcast<{{ type }}>((bits & {{ uType }}(0x7f800000u)) + {{ uType }}(0x00800000u));
return ScaledValueTile(offset, offset, {{ type }}(0.0));
}
fn scaled_value_tile_step(tile: ScaledValueTile, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueTile {
let w = {{ type }}(weight);
let sum = fma(w, value, tile.sum);
let change = fma({{ type }}(-1.0), tile.sum, sum);
return ScaledValueTile(tile.offset, sum, fma(fma(w, value, -change), {{ type }}(1.0), tile.low));
}
// The tile's words, normalized, added as scaled_value_add adds a product.
fn scaled_value_tile_join(acc: ScaledValue, tile: ScaledValueTile) -> ScaledValue {
let high = fma({{ type }}(-1.0), tile.offset, tile.sum);
let sum = fma(high, {{ type }}(1.0), tile.low);
let bv = fma({{ type }}(-1.0), high, sum);
let error = fma(fma({{ type }}(-1.0), fma({{ type }}(-1.0), bv, sum), high), {{ type }}(1.0), fma({{ type }}(-1.0), bv, tile.low));
return scaled_value_add_words(acc, sum, error);
}
// An offset or start of at least 2^-76, or a zero bound, keeps every word a
// flush-to-zero device could drop below 2^-48 of the result.
fn scaled_value_tile_in_range(start: ScaledValue, tile: ScaledValueTile, bound: {{ type }}{% if boundNumerator %}, valueHigh: {{ type }}{% endif %}) -> bool {
return {% if boundNumerator %}all(valueHigh <= {{ type }}(VALUE_FAST_LIMIT)) &&
{% endif %}all((tile.offset >= {{ type }}(1.3234889800848443e-23)) | (abs(start.hi) >= {{ type }}(1.3234889800848443e-23)) |
(bound == {{ type }}(0.0)));
}
{% endif %}
{% if N > 1 and add %}
// One compensated fold step without branches, for a caller that folds many
// steps before it can afford a branch. From finite words at exponent zero, a
// normal product and a finite low word imply every other condition of this
// arithmetic in scaled_value_add: the low word is finite only if the high word
// is, then the sum is, then the product, the weight and the value. A zero
// weight with a finite value is the step whose exact result is the accumulator
// itself. `exact` is false in any component whose step only scaled_value_add
// computes.
struct ScaledValueStep { value: ScaledValue, exact: vec{{ N }}<bool> }
fn scaled_value_add_step(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValueStep {
let w = {{ type }}(weight);
let product = fma(w, value, {{ type }}(0.0));
let sum = scaled_value_add_words(acc, product, fma(w, value, -product));
let keep = all(w == {{ type }}(0.0)) && all(abs(value) <= {{ type }}(3.4028234663852886e38));
let fast = {% if boundNumerator %}(abs(value) <= {{ type }}(VALUE_FAST_LIMIT)) & (abs(acc.hi) <= {{ type }}(VALUE_FAST_LIMIT)) &
{% endif %}(abs(product) >= {{ type }}(1.1754943508222875e-38)) & (abs(sum.lo) <= {{ type }}(3.4028234663852886e38));
return ScaledValueStep(ScaledValue(select(sum.hi, acc.hi, keep), select(sum.lo, acc.lo, keep), acc.exponent),
fast | vec{{ N }}<bool>(keep));
}
{% endif %}
{% if add %}
fn scaled_value_add(acc: ScaledValue, weight: {{ coefficientType }}, value: {{ type }}) -> ScaledValue {
{% if N > 1 %}
// Ordinary raw products use one vector compensated sum. Every exceptional
// component falls back to the same scalar exponent-aware implementation.
if (all(acc.exponent == {{ exponentType }}(0)) &&
all(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) &&
all(abs(acc.lo) <= {{ type }}(3.4028234663852886e38))) {
let step = scaled_value_add_step(acc, weight, value);
if (all(step.exact)) { return step.value; }
}
{% endif %}
var result = scaled_value_zero();
{% for i in range(N) %}
{% set c = "" if N == 1 else "[" ~ i ~ "]" %}
let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), weight{% if coefficientType != "f32" %}[{{ i }}]{% endif %}, ScaledValueScalar(value{{ c }}, 0.0, 0));
result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
{% endfor %}
return result;
}
{% endif %}
{% if rescale or tile %}
{% macro rescale_words() %}
let w = {{ type }}(correction);
let product = fma(w, acc.hi, {{ type }}(0.0));
let scaled = scaled_value_add_words(scaled_value_zero(), product,
fma(fma(w, acc.hi, -product), {{ type }}(1.0), fma(w, acc.lo, {{ type }}(0.0))));
let zero = ((acc.hi == {{ type }}(0.0)) & (acc.lo == {{ type }}(0.0))) | {{ boolType }}(correction == 0.0);
let unit = correction == 1.0;
{% endmacro %}
{% macro rescale_vector_exact() %}abs(correction) <= 3.4028234663852886e38 && all((acc.exponent == {{ exponentType }}(0)) &
(abs(acc.hi) <= {{ type }}(3.4028234663852886e38)) & (abs(acc.lo) <= {{ type }}(3.4028234663852886e38)) &
(zero | {{ boolType }}(unit) | ((abs(product) >= {{ type }}(1.1754943508222875e-38)) &
(abs(scaled.lo) <= {{ type }}(3.4028234663852886e38))))){% endmacro %}
{% macro rescale_vector_value() %}ScaledValue(select(select(scaled.hi, acc.hi, unit), {{ type }}(0.0), zero),
select(select(scaled.lo, acc.lo, unit), {{ type }}(0.0), zero), acc.exponent){% endmacro %}
{% endif %}
{% if tile %}
// scaled_value_rescale's vector path alone; `exact` is false where only its
// scalar path applies.
struct ScaledValueRescaled { value: ScaledValue, exact: bool }
fn scaled_value_rescale_step(acc: ScaledValue, correction: f32) -> ScaledValueRescaled {
{{ rescale_words() }} return ScaledValueRescaled({{ rescale_vector_value() }}, {{ rescale_vector_exact() }});
}
{% endif %}
{% if rescale %}
fn scaled_value_rescale(acc: ScaledValue, correction: f32) -> ScaledValue {
// From finite words at exponent zero, the scalar path below leaves zero
// words for a zero value or correction, the value itself for a unit
// correction, and otherwise this compensated product onto zero words when
// the product is normal and the low word finite (which bounds the rest, as
// in scaled_value_add_step).
{{ rescale_words() }} if ({{ rescale_vector_exact() }}) {
return {{ rescale_vector_value() }};
}
var result = scaled_value_zero();
{% for i in range(N) %}
{% set c = "" if N == 1 else "[" ~ i ~ "]" %}
let r{{ i }} = scaled_value_scalar_combine(scaled_value_scalar_zero(), correction, ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));
result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
{% endfor %}
return result;
}
{% endif %}
{% if merge %}
fn scaled_value_merge(acc: ScaledValue, other: ScaledValue) -> ScaledValue {
var result = scaled_value_zero();
{% for i in range(N) %}
{% set c = "" if N == 1 else "[" ~ i ~ "]" %}
let r{{ i }} = scaled_value_scalar_combine(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), 1.0, ScaledValueScalar(other.hi{{ c }}, other.lo{{ c }}, other.exponent{{ c }}));
result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
{% endfor %}
return result;
}
{% endif %}
fn scaled_value_mean(acc: ScaledValue, denominator: {{ coefficientType }}) -> {{ type }} {
// Words at exponent zero well inside the normal range, with a normal
// quotient: the scalar path below divides this same sum by this same
// denominator, each scaled by a power of two, so it rounds to this quotient
// wherever division is scale-invariant. Bounding the denominator above also
// keeps a division through its reciprocal clear of a subnormal reciprocal.
let d = {{ type }}(denominator);
let sum = fma(acc.hi, {{ type }}(1.0), acc.lo);
let quotient = sum / d;
if (all((acc.exponent == {{ exponentType }}(0)) &
(abs(acc.hi) >= {{ type }}(8.673617379884035e-19)) & (abs(acc.hi) <= {{ type }}(1.152921504606847e18)) &
(abs(acc.lo) <= abs(acc.hi)) &
(abs(d) >= {{ type }}(8.673617379884035e-19)) & (abs(d) <= {{ type }}(1.152921504606847e18)) &
((abs(quotient) >= {{ type }}(2.350988701644575e-38)) | (sum == {{ type }}(0.0))))) {
return quotient;
}
var result = {{ type }}(0.0);
{% for i in range(N) %}
{% set c = "" if N == 1 else "[" ~ i ~ "]" %}
result{{ c }} = scaled_value_scalar_mean(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), denominator{% if coefficientType != "f32" %}[{{ i }}]{% endif %});
{% endfor %}
return result;
}
{% if align %}
fn scaled_value_leading_exponent(acc: ScaledValue) -> {{ exponentType }} {
var result = {{ exponentType }}(0);
{% for i in range(N) %}
{% set c = "" if N == 1 else "[" ~ i ~ "]" %}
result{{ c }} = scaled_value_scalar_leading(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}));
{% endfor %}
return result;
}
fn scaled_value_align(acc: ScaledValue, exponent: {{ exponentType }}) -> ScaledValue {
var result = scaled_value_zero();
{% for i in range(N) %}
{% set c = "" if N == 1 else "[" ~ i ~ "]" %}
let r{{ i }} = scaled_value_scalar_align(ScaledValueScalar(acc.hi{{ c }}, acc.lo{{ c }}, acc.exponent{{ c }}), exponent{{ c }});
result.hi{{ c }} = r{{ i }}.hi; result.lo{{ c }} = r{{ i }}.lo; result.exponent{{ c }} = r{{ i }}.exponent;
{% endfor %}
return result;
}
{% endif %}
{% endmacro %}
{{ scaled_value_functions("vec4<f32>", rescale=true, align=true) }}
{% endif %}
// FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep
// `m - m` finite so an empty lane / all--inf row contributes the exact
// accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret
// a zero final denominator according to their public semantics. Using -inf
// here changes +inf-row behavior.
const FLT_MAX: f32 = 3.4028234663852886e38;
fn is_finite_f32(value: f32) -> bool {
return select(false, value <= FLT_MAX, value >= -FLT_MAX);
}
// x - m that is exactly 0 when x equals a finite m, so exp(shifted) == 1
// exactly at the row max. `x - x` on an infinite max is a legal fast-math
// fold to 0, which would silently turn +inf rows finite — the explicit
// equality test keeps the NaN propagation of the serial kernels.
fn shifted_value(value: f32, maxValue: f32) -> f32 {
let equalFiniteMax = select(false, value == maxValue, is_finite_f32(maxValue));
return select(value - maxValue, 0.0, equalFiniteMax);
}
fn exp_shift(value: f32, maxValue: f32) -> f32 {
return exp(shifted_value(value, maxValue));
}
const HEAD_DIM_V4: u32 = {{ (headDim / 4) | int }}u;
const GROUP: u32 = {{ gqaGroup }}u;
const KV_HEADS: u32 = {{ numKvHeads }}u;
const NUM_SPLITS: u32 = {{ numSplits }}u;
const MIN_KEYS: u32 = {{ gqaMinKeys }}u;
const Q_HEADS: u32 = {{ numKvHeads * gqaGroup }}u;
const WG: u32 = 256u;
// Q.K: eight lanes per key, interleaved over its vec4s, so a block holds 32 keys.
const PARTS: u32 = 8u;
const BLOCK: u32 = WG / PARTS;
// P.V: one lane per output vec4, WG / HEAD_DIM_V4 lanes per vec4 over the block's keys.
const KEY_LANES: u32 = WG / HEAD_DIM_V4;
var<workgroup> q_sh: array<vec4<f32>, {{ gqaGroup * ((headDim / 4) | int) }}>;
// Per key, part and head: partial dots.
var<workgroup> part_sh: array<f32, {{ 256 * gqaGroup }}>;
// Per head and key: scores, then probabilities.
var<workgroup> p_sh: array<f32, {{ 32 * gqaGroup }}>;
// Per head: running maximum and sum, and this block's rescale factor.
var<workgroup> m_sh: array<f32, {{ gqaGroup }}>;
var<workgroup> l_sh: array<f32, {{ gqaGroup }}>;
var<workgroup> alpha_sh: array<f32, {{ gqaGroup }}>;
// Per key lane, head and vec4: output sums reduced at the end.
var<workgroup> o_sh: array<vec4<f32>, {{ 256 * gqaGroup }}>;
@compute @workgroup_size(256, 1, 1)
fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_index) tid: u32) {
let split = wid.x;
let kvHead = wid.y;
let b = wid.z;
let cacheSeq = params.kvSeq;
{% if SEQLENS %}
let kvSeq = {{ attn_seqlens_bound("cacheSeq", "b") }};
{% else %}
let kvSeq = cacheSeq;
{% endif %}
let keysPerSplit = max((kvSeq + NUM_SPLITS - 1u) / NUM_SPLITS, MIN_KEYS);
let splitStart = min(split * keysPerSplit, kvSeq);
let splitEnd = min(splitStart + keysPerSplit, kvSeq);
// Ranges past the live keys write nothing; the merge reads only the live ones.
if (splitStart >= splitEnd) {
return;
}
let kvBaseV4 = (b * KV_HEADS + kvHead) * cacheSeq * HEAD_DIM_V4;
let kvStrideV4 = HEAD_DIM_V4;
let headBase = b * Q_HEADS + kvHead * GROUP;
let qBaseV4 = headBase * HEAD_DIM_V4;
let scale = select(params.scale, inverseSqrt(f32(HEAD_DIM_V4 * 4u)), params.scale == 0.0);
for (var e = tid; e < GROUP * HEAD_DIM_V4; e += WG) {
q_sh[e] = vec4<f32>(query[qBaseV4 + e]);
}
if (tid < GROUP) {
m_sh[tid] = -FLT_MAX;
l_sh[tid] = 0.0;
}
let keyIndex = tid / PARTS;
let part = tid % PARTS;
let d4 = tid % HEAD_DIM_V4;
let keyLane = tid / HEAD_DIM_V4;
var o: array<{% if NORMALIZED_VALUES %}ScaledValue{% else %}vec4<f32>{% endif %}, {{ gqaGroup }}>;
workgroupBarrier();
for (var blockStart = splitStart; blockStart < splitEnd; blockStart += BLOCK) {
let blockKeys = min(BLOCK, splitEnd - blockStart);
// Partial dots of this lane's interleaved vec4s with every head of the group.
var dots: array<f32, {{ gqaGroup }}>;
for (var g = 0u; g < GROUP; g++) {
dots[g] = 0.0;
}
if (keyIndex < blockKeys) {
let row = kvBaseV4 + (blockStart + keyIndex) * kvStrideV4;
for (var i = part; i < HEAD_DIM_V4; i += PARTS) {
let k = vec4<f32>(key_cache[row + i]);
for (var g = 0u; g < GROUP; g++) {
dots[g] += dot(q_sh[g * HEAD_DIM_V4 + i], k);
}
}
}
for (var g = 0u; g < GROUP; g++) {
part_sh[tid * GROUP + g] = dots[g];
}
workgroupBarrier();
// Scores, per head and key.
var score = -FLT_MAX;
if (tid < GROUP * BLOCK) {
let g = tid / BLOCK;
let k = tid % BLOCK;
if (k < blockKeys) {
var s = 0.0;
for (var x = 0u; x < PARTS; x++) {
s += part_sh[(k * PARTS + x) * GROUP + g];
}
score = s * {{ "scale" if BHSD else "ATTN_SCALE" }};
}
p_sh[tid] = score;
}
workgroupBarrier();
// Each head's new running maximum and the rescale of its sums.
if (tid < GROUP) {
var blockMax = -FLT_MAX;
for (var k = 0u; k < blockKeys; k++) {
blockMax = max(blockMax, p_sh[tid * BLOCK + k]);
}
let next = max(m_sh[tid], blockMax);
alpha_sh[tid] = exp_shift(m_sh[tid], next);
m_sh[tid] = next;
}
workgroupBarrier();
if (tid < GROUP * BLOCK && tid % BLOCK < blockKeys) {
p_sh[tid] = exp_shift(score, m_sh[tid / BLOCK]);
}
workgroupBarrier();
if (tid < GROUP) {
var sum = 0.0;
for (var k = 0u; k < blockKeys; k++) {
sum += p_sh[tid * BLOCK + k];
}
l_sh[tid] = l_sh[tid] * alpha_sh[tid] + sum;
}
{% if NORMALIZED_VALUES %}
workgroupBarrier();
{% endif %}
// P.V: this lane's vec4 over every KEY_LANES-th key, for every head.
for (var g = 0u; g < GROUP; g++) {
{% if NORMALIZED_VALUES %}
o[g] = scaled_value_rescale(o[g], alpha_sh[g]);
{% else %}
o[g] *= alpha_sh[g];
{% endif %}
}
for (var k = keyLane; k < blockKeys; k += KEY_LANES) {
let v = vec4<f32>(value_cache[kvBaseV4 + (blockStart + k) * kvStrideV4 + d4]);
for (var g = 0u; g < GROUP; g++) {
{% if NORMALIZED_VALUES %}
o[g] = scaled_value_add(o[g], p_sh[g * BLOCK + k], v);
{% else %}
o[g] += p_sh[g * BLOCK + k] * v;
{% endif %}
}
}
workgroupBarrier();
}
{% if NORMALIZED_VALUES %}
// Reuse the output scratch for exponents, high words, and low words in
// successive barrier-separated phases. Keep raw states until the lane fold
// is complete, so individually subnormal normalized terms remain visible.
for (var g = 0u; g < GROUP; g++) {
o_sh[(keyLane * GROUP + g) * HEAD_DIM_V4 + d4] = vec4<f32>(scaled_value_leading_exponent(o[g]));
}
workgroupBarrier();
var commonExponent: array<vec4<i32>, {{ ceilDiv(gqaGroup * ((headDim / 4) | int), 256) }}>;
for (var e = tid; e < GROUP * HEAD_DIM_V4; e += WG) {
let g = e / HEAD_DIM_V4;
var leading = vec4<f32>(-1024.0);
for (var lane = 0u; lane < KEY_LANES; lane++) {
leading = max(leading, o_sh[(lane * GROUP + g) * HEAD_DIM_V4 + e % HEAD_DIM_V4]);
}
commonExponent[e / WG] = vec4<i32>(leading);
o_sh[e] = leading;
}
workgroupBarrier();
var aligned: array<ScaledValue, {{ gqaGroup }}>;
for (var g = 0u; g < GROUP; g++) {
aligned[g] = scaled_value_align(o[g], vec4<i32>(o_sh[g * HEAD_DIM_V4 + d4]));
}
workgroupBarrier();
for (var g = 0u; g < GROUP; g++) {
o_sh[(keyLane * GROUP + g) * HEAD_DIM_V4 + d4] = aligned[g].hi;
}
workgroupBarrier();
var highWord: array<vec4<f32>, {{ ceilDiv(gqaGroup * ((headDim / 4) | int), 256) }}>;
for (var e = tid; e < GROUP * HEAD_DIM_V4; e += WG) {
let g = e / HEAD_DIM_V4;
for (var lane = 0u; lane < KEY_LANES; lane++) {
highWord[e / WG] += o_sh[(lane * GROUP + g) * HEAD_DIM_V4 + e % HEAD_DIM_V4];
}
}
workgroupBarrier();
for (var g = 0u; g < GROUP; g++) {
o_sh[(keyLane * GROUP + g) * HEAD_DIM_V4 + d4] = aligned[g].lo;
}
workgroupBarrier();
for (var e = tid; e < GROUP * HEAD_DIM_V4; e += WG) {
let g = e / HEAD_DIM_V4;
var lowWord = vec4<f32>(0.0);
for (var lane = 0u; lane < KEY_LANES; lane++) {
lowWord += o_sh[(lane * GROUP + g) * HEAD_DIM_V4 + e % HEAD_DIM_V4];
}
let sum = scaled_value_mean(ScaledValue(highWord[e / WG], lowWord, commonExponent[e / WG]), l_sh[g]);
partial_out[(({{ "headBase" if BHSD else "kvHead * GROUP" }} + g) * NUM_SPLITS + split) * HEAD_DIM_V4 + e % HEAD_DIM_V4] = sum;
}
{% else %}
for (var g = 0u; g < GROUP; g++) {
o_sh[(keyLane * GROUP + g) * HEAD_DIM_V4 + d4] = o[g];
}
workgroupBarrier();
for (var e = tid; e < GROUP * HEAD_DIM_V4; e += WG) {
let g = e / HEAD_DIM_V4;
var sum = vec4<f32>(0.0);
for (var lane = 0u; lane < KEY_LANES; lane++) {
sum += o_sh[(lane * GROUP + g) * HEAD_DIM_V4 + e % HEAD_DIM_V4];
}
partial_out[(({{ "headBase" if BHSD else "kvHead * GROUP" }} + g) * NUM_SPLITS + split) * HEAD_DIM_V4 + e % HEAD_DIM_V4] = sum;
}
{% endif %}
if (tid < GROUP) {
partial_stats[({{ "headBase" if BHSD else "kvHead * GROUP" }} + tid) * NUM_SPLITS + split] = vec2<f32>(m_sh[tid], l_sh[tid]);
}
}