com.microsoft.GroupQueryAttention / build /webgpu /gqa-score-matrix.wgsl.jinja
Xenova's picture
Xenova HF Staff
sync 4385228f788d
772a078 verified
Raw History Blame
8.9 kB
enable subgroups;
{% if pinSubgroupSize32 %}
enable subgroup_size_control;
{% endif %}
enable chromium_experimental_subgroup_matrix;
diagnostic(off, chromium.subgroup_matrix_uniformity);
{% 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 %}
{{ env.wgsl.resourceDeclarations }}
const HEAD_DIM = {{ headDim }}u;
const Q_HEADS = {{ qNumHeads }}u;
const KV_HEADS = {{ kvNumHeads }}u;
{% set ATTN_SCALE_DIM = "HEAD_DIM" %}fn scale_value() -> f32 {
if (params.scale != 0.0) { return params.scale; }
return inverseSqrt(f32({{ ATTN_SCALE_DIM }}));
}
// 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;
}
const DOT_ROUNDOFF = 2.01 * (f32(HEAD_DIM) + 4.0) * 0x1p-24;
var<workgroup> kFullTile: array<f32, 512>;
var<workgroup> qHi: array<f32, 512>;
var<workgroup> qLow: array<f32, 512>;
var<workgroup> kHi: array<f32, 512>;
var<workgroup> kLow: array<f32, 512>;
var<workgroup> sums: array<f32, 768>;
@compute @workgroup_size(128){{ " @subgroup_size(32)" if pinSubgroupSize32 else "" }}
fn main(@builtin(workgroup_id) wg: vec3u, @builtin(num_workgroups) grid: vec3u,
@builtin(local_invocation_index) li: u32,
@builtin(subgroup_size) width: u32, @builtin(subgroup_invocation_id) lane: u32) {
let h = wg.z % Q_HEADS;
let b = wg.z / Q_HEADS;
let kvHead = h / (Q_HEADS / KV_HEADS);
let live = {{ attn_seqlens_bound("params.kvSeq", "b") }};
let q0 = wg.y * 32u;
let k0 = wg.x * 32u;
let headBase = b * (Q_HEADS * grid.y + KV_HEADS * grid.x);
let keyBase = headBase + Q_HEADS * grid.y + kvHead * grid.x;
let qRange = ranges[headBase + h * grid.y + wg.y];
let kRange = ranges[keyBase + wg.x];
let tileIndex = (wg.z * grid.y + wg.y) * grid.x + wg.x;
if (k0 >= live) {
if (li == 0u) { repair[tileIndex] = 0u; }
return;
}
// Ranges contain the grid step, row L2 bound, live |V| maximum and signed L1 bound.
let exactGrid = (qRange.w <= 0.0 && kRange.w <= 0.0) || qRange.y == 0.0 || kRange.y == 0.0;
if (li == 0u && (qRange.x < 0.0 || kRange.x < 0.0)) { atomicStore(&matrixRejected, 1u); }
// A score changes the normalization of every live value in this head.
// Require an exact dot or replay when any value can amplify weight rounding.
if (!exactGrid) {
for (var tile = li; tile < (live + 31u) / 32u; tile += 128u) {
if (ranges[keyBase + tile].z > 1.0) { atomicStore(&matrixRejected, 1u); }
}
}
let role = claimMatrixSubgroupRole(width, 32u);
if (!matrixTopologyAccepted(li, 4u)) {
if (li == 0u) { repair[tileIndex] = 1u; }
return;
}
let scoreBase = wg.z * params.qSeq * params.kvSeq;
let scale = scale_value();
// Cauchy-Schwarz bounds sum(abs(q*k)). Allow one product and one addition
// rounding per component, plus scaling and the final score rounding.
let plainError = DOT_ROUNDOFF * qRange.y * kRange.y * abs(scale);
let plain = exactGrid || plainError <= 0x1p-25;
let qFragment = role / 2u * 16u;
let kFragment = role % 2u * 16u;
{% for r in range(2) %}{% for c in range(2) %}{% for a in ['hi','left','right'] %}
var {{a}}{{r}}{{c}}: subgroup_matrix_result<f32, 8, 8>;
{% endfor %}{% endfor %}{% endfor %}
for (var depth = 0u; depth < HEAD_DIM; depth += 16u) {
for (var off = li; off < 512u; off += 128u) {
let row = off / 16u;
let d = depth + off % 16u;
{% for t,x,idx in [['q', 'qRange', '((b * params.qSeq + q0 + row) * Q_HEADS + h)'],['k', 'kRange', '((b * params.kvSeq + k0 + row) * KV_HEADS + kvHead)']] %}
var {{t}} = 0.0;
if ({{'q0 + row < params.qSeq' if t=='q' else 'k0 + row < live'}}) {
{{t}} = {{'query' if t=='q' else 'key'}}[{{idx}} * HEAD_DIM + d];
}
let {{t}}High = select(round({{t}} / {{x}}.x) * {{x}}.x, {{t}}, plain);
{{t}}Hi[off] = {{t}}High;
if (!plain) { {{t}}Low[off] = fma(-1.0, {{t}}High, {{t}}); }
{% if t == 'k' %} kFullTile[off] = k;
{% endif %}{% endfor %}
}
workgroupBarrier();
for (var d = 0u; d < 16u; d += 8u) {
{% for r in range(2) %}
let qHi{{r}} = subgroupMatrixLoad<subgroup_matrix_left<f32, 8, 8>, row_major>(&qHi, (qFragment + {{ r * 8 }}u) * 16u + d, 16u);
let kHi{{r}} = subgroupMatrixLoad<subgroup_matrix_right<f32, 8, 8>, col_major>(&kHi, (kFragment + {{ r * 8 }}u) * 16u + d, 16u);
{% endfor %}{% for r in range(2) %}{% for c in range(2) %}
hi{{r}}{{c}} = subgroupMatrixMultiplyAccumulate(qHi{{r}}, kHi{{c}}, hi{{r}}{{c}});
{% endfor %}{% endfor %}
if (!plain) {
{% for r in range(2) %}
let qLow{{r}} = subgroupMatrixLoad<subgroup_matrix_left<f32, 8, 8>, row_major>(&qLow, (qFragment + {{ r * 8 }}u) * 16u + d, 16u);
let kLow{{r}} = subgroupMatrixLoad<subgroup_matrix_right<f32, 8, 8>, col_major>(&kLow, (kFragment + {{ r * 8 }}u) * 16u + d, 16u);
let kFull{{r}} = subgroupMatrixLoad<subgroup_matrix_right<f32, 8, 8>, col_major>(&kFullTile, (kFragment + {{ r * 8 }}u) * 16u + d, 16u);
{% endfor %}{% for r in range(2) %}{% for c in range(2) %}
left{{r}}{{c}} = subgroupMatrixMultiplyAccumulate(qHi{{r}}, kLow{{c}}, left{{r}}{{c}});
right{{r}}{{c}} = subgroupMatrixMultiplyAccumulate(qLow{{r}}, kFull{{c}}, right{{r}}{{c}});
{% endfor %}{% endfor %}
}
}
workgroupBarrier();
}
// The leading product is exact. Only the two residual matrix products can
// accumulate error. Each low component is at most half its row grid step.
let qLowBound = select(0.5 * qRange.x, 0.0, qRange.w <= 0.0);
let kLowBound = select(0.5 * kRange.x, 0.0, kRange.w <= 0.0);
let sumAbs = kLowBound * (abs(qRange.w) + f32(HEAD_DIM) * qLowBound) + qLowBound * abs(kRange.w);
// Two roundings per component also cover non-fused or truncating matrix MACs.
// Four additional roundings enclose the sum and both interval endpoints.
let radius = sumAbs * DOT_ROUNDOFF;
{% for r in range(2) %}{% for c in range(2) %}
{
{% for a in ['hi','left','right'] %}
subgroupMatrixStore<row_major>(&sums, role * 192u + {{ loop.index0 * 64 }}u, {{a}}{{r}}{{c}}, 8u);
{% endfor %}
workgroupBarrier();
for (var cell = lane; cell < 64u; cell += 32u) {
let q = q0 + qFragment + {{ r * 8 }}u + cell / 8u;
let k = k0 + kFragment + {{ c * 8 }}u + cell % 8u;
let idx = role * 192u + cell;
if (q < params.qSeq && k < live) {
let leading = sums[idx];
var result = leading * scale;
if (!plain) {
// q*k = qHi*kHi + qHi*kLow + qLow*k. Round both endpoints in
// the same order as the score, including negative attention scales.
let correction = sums[idx + 64u] + sums[idx + 128u];
let lo = fma(1.0, leading, correction - radius) * scale;
let hi = fma(1.0, leading, correction + radius) * scale;
result = fma(1.0, leading, correction) * scale;
// For |V| <= 1, softmax's Jacobian bounds absolute output sensitivity
// by the largest absolute logit perturbation, including near cancellation.
if (!(lo == hi || max(abs(result - lo), abs(hi - result)) <= 0x1p-24)) {
atomicStore(&matrixRejected, 1u);
}
}
scores[scoreBase + q * params.kvSeq + k] = result;
}
}
workgroupBarrier();
}
{% endfor %}{% endfor %}
if (li == 0u) { repair[tileIndex] = atomicLoad(&matrixRejected); }
}