com.microsoft.GroupQueryAttention / build /webgpu /attn-materialized-shaped.wgsl.jinja
Xenova's picture
Xenova HF Staff
sync 4385228f788d
772a078 verified
Raw History Blame
40.9 kB
{% set MT = "f16" if operandF16 | default(false) else "f32" %}
{% set ST = MT %}
{% set scorePhase = phase == "score" %}
{% set FUSED_SOFTMAX = fusedSoftmax | default(false) %}
{% set SAFE_VALUE_REDO = FUSED_SOFTMAX and not scorePhase and MT == "f32" %}
{% set EMIT_ROW_STATS = emitRowStats | default(false) %}
{% set SCORE_BIAS = scorePhase and scoreBias | default(false) %}
{% set USE_SEQLENS = useSeqlens | default(false) %}
{% set CAUSAL = causalRightAlign | default(false) %}
{% set SCORE_WINDOW = CAUSAL and scoreWindow | default(false) %}
{% set kvLayout = kvLayout | default(layout) %}
{% set kvHeadMajor = kvLayout == "bhsd" %}
{% set SCRATCH_HEAD = "(b * HEADS + h)" %}
{% set WIDTH = matrixSubgroupWidth %}
{% set GROUPS = (128 / WIDTH) | int %}
{% set OWNED = (4 / GROUPS) | int %}
{% set TM = matrixM * 2 %}
{% set TN = matrixN * 2 %}
{% set TK = matrixK %}
{% set A_COUNT = TM * TK %}
{% set B_COUNT = TN * TK %}
{% set C_COUNT = TM * TN %}
{% set OPERAND_BYTES = 2 if MT == "f16" else 4 %}
{% set ARENA_BYTES = max((A_COUNT + B_COUNT) * OPERAND_BYTES, C_COUNT * 4) %}
{% set USE_VIEW = device.wgslLanguageFeatures.has("buffer_view") %}
{% macro q_index(row, d) %}(b * params.qSeq + {{ row }}) * HIDDEN + h * HEAD_DIM + {{ d }}{% endmacro %}
{% macro kv_index(seq, d) %}{% if kvHeadMajor %}((b * KV_HEADS + h_kv) * params.kvSeq + {{ seq }}) * HEAD_DIM + {{ d }}{% else %}(b * params.kvSeq + {{ seq }}) * KV_HIDDEN + h_kv * HEAD_DIM + {{ d }}{% endif %}{% endmacro %}
{% macro operand(name, index) %}{{ name }}[{{ index }}]{% endmacro %}
{% 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 }}, {% if queryFloor %}max({{ queryFloor }}, {{ attn_seqlens_count(index) }}){% else %}{{ attn_seqlens_count(index) }}{% endif %}){% endmacro %}
enable subgroups;
enable chromium_experimental_subgroup_matrix;
diagnostic(off, chromium.subgroup_matrix_uniformity);
{% if USE_VIEW %}requires buffer_view;{% endif %}
{{ env.wgsl.resourceDeclarations }}
const HEADS: u32 = {{ qNumHeads }}u;
const KV_HEADS: u32 = {{ kvNumHeads | default(qNumHeads) }}u;
const HEAD_DIM: u32 = {{ headDim }}u;
const HIDDEN: u32 = {{ qHidden }}u;
{% if not kvHeadMajor %}const KV_HIDDEN: u32 = KV_HEADS * HEAD_DIM;{% endif %}
{% if EMIT_ROW_STATS %}const STAT_SLOTS: u32 = {{ statSlots }}u;{% endif %}
const TILE_M: u32 = {{ TM }}u;
const TILE_N: u32 = {{ TN }}u;
const TILE_K: u32 = {{ TK }}u;
{% if USE_VIEW %}
// Operand reads end at the final reduction barrier. Result fragments then
// overwrite that dead staging arena; the epilogue reads only its f32 view.
var<workgroup> matrixArena: buffer<{{ ARENA_BYTES }}>;
{% else %}
var<workgroup> tileA: array<{{ MT }}, {{ A_COUNT }}>;
var<workgroup> tileB: array<{{ MT }}, {{ B_COUNT }}>;
var<workgroup> tileC: array<f32, {{ C_COUNT }}>;
{% endif %}
{% if FUSED_SOFTMAX %}
var<workgroup> softmaxM: array<f32, {{ TM }}>;
var<workgroup> softmaxD: array<f32, {{ TM }}>;
{% endif %}
{% if FUSED_SOFTMAX or EMIT_ROW_STATS %}
// 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));
}
{% endif %}
{% if SAFE_VALUE_REDO %}
{% 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("f32") }}
{% endif %}
// A subgroup owns one matrix tile only after its actual population and the
// workgroup-wide bank count are proven. The elected subgroup leader claims
// the role; local invocation IDs only publish the workgroup-wide decision.
var<workgroup> matrixRoleCount: atomic<u32>;
var<workgroup> matrixRejected: atomic<u32>;
var<workgroup> matrixAccepted: u32;
fn claimMatrixSubgroupRole(width: u32, requiredWidth: u32) -> u32 {
// WGSL initializes workgroup variables to zero before this entry point.
let population = subgroupBallot(true);
let populationCount = countOneBits(population.x) + countOneBits(population.y)
+ countOneBits(population.z) + countOneBits(population.w);
var claimed = 0u;
if (subgroupElect()) {
claimed = atomicAdd(&matrixRoleCount, 1u);
if (width != requiredWidth || populationCount != requiredWidth) {
atomicStore(&matrixRejected, 1u);
}
}
// Reconverge every invocation before broadcasting the elected claim.
workgroupBarrier();
return subgroupBroadcastFirst(claimed);
}
fn matrixTopologyAccepted(localIndex: u32, bankCount: u32) -> bool {
if (localIndex == 0u) {
matrixAccepted = select(0u, 1u, atomicLoad(&matrixRejected) == 0u
&& atomicLoad(&matrixRoleCount) == bankCount);
}
// The uniform load both publishes the leader's decision and gives the
// compiler a workgroup-uniform condition for the barrier-containing arms.
return workgroupUniformLoad(&matrixAccepted) != 0u;
}
{% if not scorePhase and CAUSAL %}
// Visibility-changing nonfinite values require explicit per-row masks.
// Common visible values retain their ordinary native propagation.
var<workgroup> matrixNonFinite: atomic<u32>;
var<workgroup> matrixFinite: u32;
{% endif %}
{% macro views() %}{% if USE_VIEW %}
let tileA = bufferView<array<{{ MT }}, {{ A_COUNT }}>>(&matrixArena, 0u);
let tileB = bufferView<array<{{ MT }}, {{ B_COUNT }}>>(&matrixArena, {{ A_COUNT * OPERAND_BYTES }}u);
let tileC = bufferView<array<f32, {{ C_COUNT }}>>(&matrixArena, 0u);
{% endif %}{% endmacro %}
{% macro element(name, offset) %}{% if USE_VIEW %}(*{{ name }}){% else %}{{ name }}{% endif %}[{{ offset }}]{% endmacro %}
{% macro pointer(name) %}{% if USE_VIEW %}{{ name }}{% else %}&{{ name }}{% endif %}{% endmacro %}
{% macro loadTiles() %}
for (var flat = tid; flat < TILE_M * TILE_K; flat += 128u) {
let tileRow = flat / TILE_K;
let row = rowBase + tileRow;
let k = kk + flat % TILE_K;
var loaded = {{ MT }}(0);
{% if scorePhase %}
if (row < params.qSeq && k < HEAD_DIM) {
loaded = {{ operand("query", q_index("row", "k")) }};
}
{% else %}
if (row < params.qSeq && k < {% if CAUSAL %}inner{% else %}kvActive{% endif %}{% if CAUSAL %} && i32(k) <= causalOffset + i32(row){% endif %}{% if SCORE_WINDOW %} && i32(k) + i32(min(params.windowSize, kvActive)) > causalOffset + i32(row){% endif %}{% if FUSED_SOFTMAX and (CAUSAL or USE_SEQLENS) %} && softmaxD[tileRow] != 0.0{% endif %}) {
let score = scores[{{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq + row * params.kvSeq + k];
{% if SAFE_VALUE_REDO %}
let weight = exp_shift(score, softmaxM[tileRow]);
loaded = weight / softmaxD[tileRow];
if (weight > 0.0 && loaded < 1.0842021724855044e-19) { valueRangeNeedsFallback = true; }
{% else %}
loaded = {{ MT }}(exp_shift(score, softmaxM[tileRow]) / softmaxD[tileRow]);
{% endif %}
}
{% endif %}
{{ element("tileA", "flat") }} = loaded;
}
for (var flat = tid; flat < TILE_N * TILE_K; flat += 128u) {
let col = colBase + flat / TILE_K;
let k = kk + flat % TILE_K;
var loaded = {{ MT }}(0);
{% if scorePhase %}
if (col < kvActive && k < HEAD_DIM) { loaded = {{ operand("key", kv_index("col", "k")) }}; }
{% else %}
if (k < {% if CAUSAL %}inner{% else %}kvActive{% endif %}{% if SCORE_WINDOW %} && k >= firstLiveKey{% endif %} && col < HEAD_DIM) { loaded = {{ operand("value", kv_index("k", "col")) }}; }
{% if SAFE_VALUE_REDO %}
if (abs(loaded) > 0.0 && abs(loaded) < 1.0842021724855044e-19) { valueRangeNeedsFallback = true; }
{% endif %}
{% endif %}
{{ element("tileB", "flat") }} = loaded;
}
{% endmacro %}
{% macro scoreValue(value, row, col) %}
var scored = {{ value }} * {{ attentionScaleExpression }};
{% if SCORE_BIAS %}
let biasB = select(b, 0u, params.biasBatch == 1u);
let biasH = select(h, 0u, params.biasHeads == 1u);
scored += attention_bias[((biasB * params.biasHeads + biasH) * params.qSeq + {{ row }}) * params.kvSeq + {{ col }}];
{% endif %}
{% if CAUSAL %} if (i32({{ col }}) > causalOffset + i32({{ row }})) { scored = -FLT_MAX; }{% endif %}
{% if USE_SEQLENS %} if ({{ col }} >= kvActive) { scored = -FLT_MAX; }{% endif %}
{% if SCORE_WINDOW %} if (i32({{ col }}) + i32(min(params.windowSize, kvActive)) <= causalOffset + i32({{ row }})) { scored = -FLT_MAX; }{% endif %}
{% endmacro %}
@compute @workgroup_size(128, 1, 1)
fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_index) tid: u32,
@builtin(subgroup_size) width: u32) {
// Claim every active population before choosing lane-owned matrix banks.
// The uniform topology check completes before native ownership below.
let role = claimMatrixSubgroupRole(width, {{ WIDTH }}u);
{% if scorePhase or not CAUSAL %} let provenTopology = matrixTopologyAccepted(tid, {{ GROUPS }}u);{% endif %}
let h = wg.z % HEADS;
let b = wg.z / HEADS;
let h_kv = h / (HEADS / KV_HEADS);
let rowBase = wg.y * TILE_M;
let colBase = wg.x * TILE_N;
let kvActive = {% if USE_SEQLENS %}{{ attn_seqlens_bound("params.kvSeq", "b", "params.qSeq" if seqlensQueryFloor | default(true) else "") }}{% else %}params.kvSeq{% endif %};
{% if CAUSAL %} let causalOffset = i32(kvActive) - i32(params.qSeq);{% endif %}
{% if scorePhase and CAUSAL %}
// Whole dead key tiles publish the online identity before uniformly leaving.
if (i32(colBase) > causalOffset + i32(rowBase + TILE_M) - 1 || colBase >= kvActive{% if SCORE_WINDOW %}
|| i32(colBase + TILE_N) <= causalOffset + i32(rowBase) + 1 - i32(min(params.windowSize, kvActive)){% endif %}) {
for (var tileRow = tid; tileRow < TILE_M; tileRow += 128u) {
let row = rowBase + tileRow;
if (row < params.qSeq) {
let index = (({{ SCRATCH_HEAD }} * STAT_SLOTS + wg.x) * params.qSeq + row) * 2u;
scorePartials[index] = -FLT_MAX;
scorePartials[index + 1u] = 0.0;
}
}
return;
}
{% endif %}
{{ views() }}
{% if FUSED_SOFTMAX %}
for (var row = tid; row < TILE_M; row += 128u) {
let statRow = {{ SCRATCH_HEAD }} * params.qSeq + min(rowBase + row, params.qSeq - 1u);
softmaxM[row] = rowStats[statRow * 2u];
softmaxD[row] = rowStats[statRow * 2u + 1u];
}
workgroupBarrier();
{% endif %}
let inner = {% if scorePhase %}HEAD_DIM{% elif CAUSAL %}u32(clamp(causalOffset + i32(min(rowBase + TILE_M, params.qSeq)), 0, i32(kvActive))){% else %}kvActive{% endif %};
{% if not scorePhase and SCORE_WINDOW %}
let firstLiveKey = u32(max(causalOffset + i32(rowBase) + 1 - i32(min(params.windowSize, kvActive)), 0));
let innerStart = firstLiveKey / TILE_K * TILE_K;
{% endif %}
{% if not scorePhase and CAUSAL %}
let commonEnd = u32(clamp(causalOffset + i32(rowBase) + 1, 0, i32(kvActive)));
let commonStart = {% if SCORE_WINDOW %}u32(max(causalOffset + i32(min(rowBase + TILE_M, params.qSeq)) - i32(min(params.windowSize, kvActive)), 0)){% else %}0u{% endif %};
let leftEnd = min(commonStart, inner);
let rightStart = max(commonEnd, leftEnd);
// Scan union minus intersection: only visibility-changing keys require
// an explicit per-row mask when V is nonfinite after operand conversion.
{% for edge in range(2) %}
{
let edgeStart = {% if edge == 0 %}{% if SCORE_WINDOW %}firstLiveKey{% else %}0u{% endif %}{% else %}rightStart{% endif %};
let edgeEnd = {% if edge == 0 %}leftEnd{% else %}inner{% endif %};
let finiteColumn = colBase + tid % TILE_N;
for (var k = edgeStart + tid / TILE_N; k < edgeEnd; k += {{ 128 // TN }}u) {
if (finiteColumn < HEAD_DIM) {
let bits = bitcast<u32>(f32({{ MT }}({{ operand("value", kv_index("k", "finiteColumn")) }})));
if ((bits & 0x7f800000u) == 0x7f800000u) { atomicOr(&matrixNonFinite, 1u); }
}
}
}
{% endfor %}
let provenTopology = matrixTopologyAccepted(tid, {{ GROUPS }}u);
if (tid == 0u) { matrixFinite = select(0u, 1u, atomicLoad(&matrixNonFinite) == 0u); }
let nativeTopology = provenTopology && workgroupUniformLoad(&matrixFinite) != 0u;
{% else %}
let nativeTopology = provenTopology;
{% endif %}
{% if SAFE_VALUE_REDO %}
// The subgroup-layout check has finished with its scratch. Reuse it for the rare
// normalized-product range fallback without increasing workgroup storage.
if (tid == 0u) { atomicStore(&matrixRejected, 0u); }
workgroupBarrier();
var valueRangeNeedsFallback = false;
{% endif %}
if (nativeTopology) {
{% for slot in range(OWNED) %}
let bank{{ slot }} = role + {{ slot * GROUPS }}u;
let bankRow{{ slot }} = bank{{ slot }} / 2u * {{ matrixM }}u;
let bankCol{{ slot }} = bank{{ slot }} % 2u * {{ matrixN }}u;
var acc{{ slot }}: subgroup_matrix_result<f32, {{ matrixN }}, {{ matrixM }}>;
{% endfor %}
for (var kk = {% if not scorePhase and SCORE_WINDOW %}innerStart{% else %}0u{% endif %}; kk < inner; kk += TILE_K) {
{{ loadTiles() }}
workgroupBarrier();
{% for slot in range(OWNED) %}
let left{{ slot }} = subgroupMatrixLoad<subgroup_matrix_left<{{ MT }}, {{ matrixK }}, {{ matrixM }}>, row_major>({{ pointer("tileA") }}, bankRow{{ slot }} * TILE_K, TILE_K);
let right{{ slot }} = subgroupMatrixLoad<subgroup_matrix_right<{{ MT }}, {{ matrixN }}, {{ matrixK }}>, col_major>({{ pointer("tileB") }}, bankCol{{ slot }} * TILE_K, TILE_K);
acc{{ slot }} = subgroupMatrixMultiplyAccumulate(left{{ slot }}, right{{ slot }}, acc{{ slot }});
{% endfor %}
workgroupBarrier();
}
{% for slot in range(OWNED) %}
subgroupMatrixStore<row_major>({{ pointer("tileC") }}, bankRow{{ slot }} * TILE_N + bankCol{{ slot }}, acc{{ slot }}, TILE_N);
{% endfor %}
} else {
// Independent invocation ownership handles any legal subgroup partition.
var acc: array<f32, {{ (C_COUNT + 127) // 128 }}>;
for (var kk = {% if not scorePhase and SCORE_WINDOW %}innerStart{% else %}0u{% endif %}; kk < inner; kk += TILE_K) {
{{ loadTiles() }}
workgroupBarrier();
for (var cell = 0u; cell < {{ (C_COUNT + 127) // 128 }}u; cell++) {
let flat = tid + cell * 128u;
if (flat < TILE_M * TILE_N) {
let row = flat / TILE_N;
let col = flat % TILE_N;
for (var k = 0u; k < TILE_K; k++) {
{% if not scorePhase and CAUSAL %}
let key = kk + k;
let query = rowBase + row;
if (key < kvActive && softmaxD[row] != 0.0 && i32(key) <= causalOffset + i32(query){% if SCORE_WINDOW %} && i32(key) + i32(min(params.windowSize, kvActive)) > causalOffset + i32(query){% endif %}) {
{% endif %}
acc[cell] = fma(f32({{ element("tileA", "row * TILE_K + k") }}), f32({{ element("tileB", "col * TILE_K + k") }}), acc[cell]);
{% if not scorePhase and CAUSAL %}
}
{% endif %}
}
}
}
workgroupBarrier();
}
for (var cell = 0u; cell < {{ (C_COUNT + 127) // 128 }}u; cell++) {
let flat = tid + cell * 128u;
if (flat < TILE_M * TILE_N) { {{ element("tileC", "flat") }} = acc[cell]; }
}
}
workgroupBarrier();
{% if SAFE_VALUE_REDO %}
if (valueRangeNeedsFallback) { atomicOr(&matrixRejected, 1u); }
workgroupBarrier();
if (tid == 0u) { matrixAccepted = atomicLoad(&matrixRejected); }
if (workgroupUniformLoad(&matrixAccepted) != 0u) {
// Retain raw exp weights until the scaled value product. Both a tiny
// probability times a large V and many tiny products can have normal means.
for (var flat = tid; flat < TILE_M * TILE_N; flat += 128u) {
let tileRow = flat / TILE_N;
let row = rowBase + tileRow;
let col = colBase + flat % TILE_N;
if (row < params.qSeq && col < HEAD_DIM) {
let denominator = softmaxD[tileRow];
let rowEnd = {% if CAUSAL %}u32(clamp(causalOffset + i32(row) + 1, 0, i32(inner))){% else %}inner{% endif %};
let rowStart = {% if SCORE_WINDOW %}u32(max(causalOffset + i32(row) + 1 - i32(min(params.windowSize, kvActive)), 0)){% else %}0u{% endif %};
var sum = scaled_value_zero();
for (var key = rowStart; key < rowEnd && denominator != 0.0; key++) {
let score = scores[{{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq + row * params.kvSeq + key];
sum = scaled_value_add(sum, exp_shift(score, softmaxM[tileRow]), {{ operand("value", kv_index("key", "col")) }});
}
output[{{ q_index("row", "col") }}] = scaled_value_mean(sum, denominator);
}
}
return;
}
{% endif %}
for (var flat = tid; flat < TILE_M * TILE_N; flat += 128u) {
let row = rowBase + flat / TILE_N;
let col = colBase + flat % TILE_N;
if (row < params.qSeq && col < {% if scorePhase %}params.kvSeq{% else %}HEAD_DIM{% endif %}) {
{% if scorePhase %}
{{ scoreValue(element("tileC", "flat"), "row", "col") }}
scores[{{ SCRATCH_HEAD }} * params.qSeq * params.kvSeq + row * params.kvSeq + col] = scored;
{% else %}
output[{{ q_index("row", "col") }}] = {{ ST }}({% if FUSED_SOFTMAX and (CAUSAL or USE_SEQLENS) %}select({{ element("tileC", "flat") }}, 0.0, softmaxD[flat / TILE_N] == 0.0){% else %}{{ element("tileC", "flat") }}{% endif %});
{% endif %}
}
}
{% if EMIT_ROW_STATS %}
// One invocation owns each complete row, independently of physical lanes.
// Each key tile contributes one (m,d) slot; no 8-row quad assumption remains.
for (var tileRow = tid; tileRow < TILE_M; tileRow += 128u) {
let row = rowBase + tileRow;
if (row < params.qSeq) {
var m = -FLT_MAX;
var d = 0.0;
for (var tileCol = 0u; tileCol < TILE_N; tileCol++) {
let col = colBase + tileCol;
if (col < params.kvSeq{% if USE_SEQLENS %} && col < kvActive{% endif %}{% if CAUSAL %} && i32(col) <= causalOffset + i32(row){% endif %}{% if SCORE_WINDOW %} && i32(col) + i32(min(params.windowSize, kvActive)) > causalOffset + i32(row){% endif %}) {
{{ scoreValue(element("tileC", "tileRow * TILE_N + tileCol"), "row", "col") }}
let previous = m;
m = max(m, scored);
d = d * exp_shift(previous, m) + exp_shift(scored, m);
}
}
let index = (({{ SCRATCH_HEAD }} * STAT_SLOTS + wg.x) * params.qSeq + row) * 2u;
scorePartials[index] = m;
scorePartials[index + 1u] = d;
}
}
{% endif %}
}