{%- set BHSD = true -%} {%- set SEQLENS = BHSD and gqaSeqlens is defined and gqaSeqlens -%} {%- set OUT16 = (gqaOutScalar | default("f32")) == "f16" -%} {%- if SEQLENS %}{% macro attn_seqlens_count(index) %}(u32(max(seqlens_k[{{ index }}], 0)) + select(0u, 1u, seqlens_k[{{ index }}] >= 0)){% endmacro %} {% macro attn_seqlens_bound(capacity, index, queryFloor="") %}min({{ capacity }}, {{ attn_seqlens_count(index) }}){% endmacro %} {% endif %} {% set NORMALIZED_VALUES = gqaNormalizedValues | default(false) %} {{ env.wgsl.resourceDeclarations }} {% if NORMALIZED_VALUES %} {% macro sum_error_function(name, type="f32", protectDifference=false) %} {% set bitsType = type | replace("f32", "u32") %} // Observing the rounded sum as bits preserves FastTwoSum on backends // that otherwise reassociate its subtractions. Both signs of zero contribute zero. fn {{ name }}_rounded(x: {{ type }}) -> {{ type }} { let bits = bitcast<{{ bitsType }}>(x); return bitcast<{{ type }}>(select({{ bitsType }}(0u), bits, (bits & {{ bitsType }}(0x7fffffffu)) != {{ bitsType }}(0u))); } fn {{ name }}(a: {{ type }}, b: {{ type }}, sum: {{ type }}) -> {{ type }} { let swap = abs(a) < abs(b); let larger = select(a, b, swap); let smaller = select(b, a, swap); // Keep the rounded high-part difference observable before subtracting it // from the smaller addend. Reassociation here erases the residual. return smaller - {{ name }}_rounded({{ name }}_rounded(sum) - larger); } {% endmacro %} {% macro scaled_value_functions(type, coefficientType="f32", rescale=false, merge=false, align=false, lean=false, tile=false, add=true, magnitudeOrdered=false, recoverSum=false) %} {% set N = 1 if type == "f32" else (type[3] | int) %} {% set exponentType = "i32" if N == 1 else "vec" ~ N ~ "" %} {% set boolType = "bool" if N == 1 else "vec" ~ N ~ "" %} {% 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(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(sign | 0x7f800000u); } if (exponent > 0) { return bitcast(sign | (u32(exponent) << 23u) | (significand & 0x007fffffu)); } let distance = u32(1 - exponent); if (distance > 24u) { return bitcast(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(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 ~ "" %} // 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 }} } 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 }}(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") }} {% endif %} // FLT_MAX, not -inf, as the online (m, d) accumulator init: merges must keep // `m - m` finite so an empty lane / all--inf row contributes the exact // accumulator identity (m, d) = (-FLT_MAX, 0). Operator epilogues interpret // a zero final denominator according to their public semantics. Using -inf // here changes +inf-row behavior. const FLT_MAX: f32 = 3.4028234663852886e38; fn is_finite_f32(value: f32) -> bool { return select(false, value <= FLT_MAX, value >= -FLT_MAX); } // x - m that is exactly 0 when x equals a finite m, so exp(shifted) == 1 // exactly at the row max. `x - x` on an infinite max is a legal fast-math // fold to 0, which would silently turn +inf rows finite — the explicit // equality test keeps the NaN propagation of the serial kernels. fn shifted_value(value: f32, maxValue: f32) -> f32 { let equalFiniteMax = select(false, value == maxValue, is_finite_f32(maxValue)); return select(value - maxValue, 0.0, equalFiniteMax); } fn exp_shift(value: f32, maxValue: f32) -> f32 { return exp(shifted_value(value, maxValue)); } const HEAD_DIM_V4: u32 = {{ (headDim / 4) | int }}u; const NUM_SPLITS: u32 = {{ numSplits }}u; const MIN_KEYS: u32 = {{ gqaMinKeys }}u; const Q_HEADS: u32 = {{ numHeads | default(1) }}u; // One workgroup per query head; one lane per output vec4. @compute @workgroup_size({{ (headDim / 4) | int }}, 1, 1) fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_index) d4: u32) { let h = wid.z * Q_HEADS + wid.y; {% if SEQLENS %} let kvSeq = {{ attn_seqlens_bound("params.kvSeq", "wid.z") }}; {% else %} let kvSeq = params.kvSeq; {% endif %} let keysPerSplit = max((kvSeq + NUM_SPLITS - 1u) / NUM_SPLITS, MIN_KEYS); let live = (kvSeq + keysPerSplit - 1u) / keysPerSplit; var globalMax = -FLT_MAX; for (var s = 0u; s < live; s++) { globalMax = max(globalMax, partial_stats[h * NUM_SPLITS + s].x); } var globalDenom = 0.0; {% if not NORMALIZED_VALUES %} var outV = vec4(0.0); {% endif %} for (var s = 0u; s < live; s++) { let stats = partial_stats[h * NUM_SPLITS + s]; let w = exp_shift(stats.x, globalMax); globalDenom += stats.y * w; {% if not NORMALIZED_VALUES %} outV += partial_out[(h * NUM_SPLITS + s) * HEAD_DIM_V4 + d4] * w; {% endif %} } {% if NORMALIZED_VALUES %} var raw = scaled_value_zero(); for (var s = 0u; s < live; s++) { let stats = partial_stats[h * NUM_SPLITS + s]; let mass = stats.y * exp_shift(stats.x, globalMax); raw = scaled_value_add(raw, mass, partial_out[(h * NUM_SPLITS + s) * HEAD_DIM_V4 + d4]); } let outV = scaled_value_mean(raw, globalDenom); {% endif %} let outValue = select(vec4(0.0), outV{% if not NORMALIZED_VALUES %} / globalDenom{% endif %}, globalDenom > 0.0); output[h * HEAD_DIM_V4 + d4] = {{ "vec4(outValue)" if OUT16 else "outValue" }}; }