com.microsoft.GroupQueryAttention / build /webgpu /gqa-window-cache.wgsl.jinja
Xenova's picture
Xenova HF Staff
sync 4385228f788d
772a078 verified
Raw History Blame
6.71 kB
{% set stageRegion = stageRegion | default("all") %}
{% set hasRotary = hasRotary | default(false) %}
{% macro flat_index_2d(workgroupSize, name="i", bound="params.count") %}
{% set wgTerm = workgroupSize ~ "u" if workgroupSize is number else workgroupSize %}
// 2D-folded flat index: gid.y carries the high bits past the dispatch's
// per-axis workgroup fold width.
let {{ name }} = gid.x + gid.y * {{ DISPATCH_FOLD_WIDTH }}u * {{ wgTerm }};
{% if bound != "" %}
if ({{ name }} >= {{ bound }}) {
return;
}
{% endif %}
{% endmacro %}
{{ env.wgsl.resourceDeclarations }}
const HEAD_DIM: u32 = {{ headDim }}u;
const KV_HEADS: u32 = {{ kvHeads }}u;
const WG: u32 = {{ copyWorkgroupSize }}u;
{% if windowPhase == "stage" %}
{% if stageRegion != "append" %}const BATCH: u32 = {{ windowBatchCount }}u;
{% endif %}
{% if stageRegion != "shift" %}const KV_HIDDEN: u32 = KV_HEADS * HEAD_DIM;
{% if hasRotary %}const HALF: u32 = {{ half }}u;
{% endif %}{% endif %}
{% endif %}
// Equivalent to T-gap*ceil((T-C)/gap), without a product or rounded-up sum
// that can overflow. T is allowed to reach INT32_MAX+1; C>=W>0 is host-checked.
fn window_end(total: u32) -> u32 {
if (total <= params.capacity) { return total; }
let gap = params.capacity - params.windowSize + 1u;
return params.windowSize + (total - params.capacity - 1u) % gap;
}
struct WindowStep { total: u32, pastRows: u32, stageEnd: u32 }
fn window_step(last: i32) -> WindowStep {
var step = WindowStep(0u, 0u, 0u);
// Validate the signed value before conversion and subtraction. An invalid
// `seqlens_k` value clears this batch rather than reading another slice.
if (last < 0) { return step; }
let total = u32(last) + 1u;
if (total < params.keySeq) { return step; }
step.total = total;
step.pastRows = window_end(total - params.keySeq);
step.stageEnd = step.pastRows + params.keySeq;
return step;
}
{% set cooperativeWindow = windowCooperativeCopy and not (windowPhase == "stage" and stageRegion == "append") %}
{% set copyWidth = 2 if inputScalar == "f16" else 1 %}
{% macro channel_loop(bound, stores) %}
{% if cooperativeWindow %}
for (var dBase = lane * {{ copyWidth }}u; dBase < {{ bound }}; dBase += WG * {{ copyWidth }}u) {
{% for dc in range(copyWidth) %}
{ let d = dBase + {{ dc }}u;
{% for store in stores %} {{ store }}
{% endfor %} }
{% endfor %} }
{% else %}
for (var d = 0u; d < {{ bound }}; d += 1u) {
{% for store in stores %} {{ store }}
{% endfor %} }
{% endif %}
{% endmacro %}
@compute @workgroup_size(WG)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
{% if cooperativeWindow %}
{{ flat_index_2d("WG", "linear", "") }}
let lane = linear % WG;
let rowBase = linear - lane;
let rowEnd = min(params.count, rowBase + WG);
for (var i = rowBase; i < rowEnd; i++) {
{% else %}
{{ flat_index_2d("WG") }}
{% endif %}
{% if windowPhase == "compact" %}
let t = i % params.capacity;
let slice = i / params.capacity;
let hk = slice % KV_HEADS;
let b = slice / KV_HEADS;
let step = window_step(seqlens_k[params.batch + b]);
if (step.total == 0u && hk == 0u) {
// A rejected sample must be zero even if its query contained NaN/Inf.
// Attention has finished; cache rows partition all its query rows safely,
// including chunks longer than the cache capacity.
for (var s = t; s < params.keySeq; s += params.capacity) {
let outBase = (b * params.keySeq + s) * {{ windowQueryHeads }}u * HEAD_DIM;
{{ channel_loop(windowQueryHeads|string + "u * HEAD_DIM", ["output[outBase + d] = " + inputScalar + "(0.0);"]) }}
}
}
let end = window_end(step.total);
let dst = ((b * KV_HEADS + hk) * params.capacity + t) * HEAD_DIM;
if (t < end) {
// All attention passes have finished. Writing the real cache now is safe
// even when its allocation aliases past, and preserves early-query history.
let src = ((b * KV_HEADS + hk) * params.seq + step.stageEnd - end + t) * HEAD_DIM;
{{ channel_loop("HEAD_DIM", ["present_key[dst + d] = stage_k[src + d];", "present_value[dst + d] = stage_v[src + d];"]) }}
} else {
// Zero every cache slot outside the resident prefix [0, end).
{{ channel_loop("HEAD_DIM", ["present_key[dst + d] = " + inputScalar + "(0.0);", "present_value[dst + d] = " + inputScalar + "(0.0);"]) }}
}
{% else %}
{% if stageRegion == "append" %}
let j = i % params.keySeq;
let slice = i / params.keySeq;
{% else %}
let t = i % params.seq;
let slice = i / params.seq;
{% endif %}
let hk = slice % KV_HEADS;
let b = slice / KV_HEADS;
let step = window_step(seqlens_k[b]);
{% if stageRegion != "append" %}
if (hk == 0u && t == 0u{% if cooperativeWindow %} && lane == 0u{% endif %}) {
// Attention kernels consume resident lengths, while rotary/bias still need
// absolute positions. Both fit in one metadata binding.
stage_seqlens[b] = i32(step.stageEnd) - 1;
stage_seqlens[BATCH + b] = select(-1, seqlens_k[b], step.total != 0u);
}
{% endif %}
{% if stageRegion == "append" %}
let t = step.pastRows + j;
let dst = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM;
if (step.total == 0u || step.total - params.keySeq + j >= {{ windowRotaryRows }}u) {
{{ channel_loop("HEAD_DIM", ["present_key[dst + d] = " + inputScalar + "(0.0);", "present_value[dst + d] = " + inputScalar + "(0.0);"]) }}
return;
}
let src = (b * params.keySeq + j) * KV_HIDDEN + hk * HEAD_DIM;
let pos = step.total - params.keySeq + j;
for (var d = 0u; d < HALF; d += 1u) {
let cs = cos_cache[pos * HALF + d];
let sn = sin_cache[pos * HALF + d];
let x0 = new_k[src + d];
let x1 = new_k[src + d + HALF];
present_key[dst + d] = x0 * cs - x1 * sn;
present_key[dst + d + HALF] = x1 * cs + x0 * sn;
present_value[dst + d] = new_v[src + d];
present_value[dst + d + HALF] = new_v[src + d + HALF];
}
{% else %}
let dst = ((b * KV_HEADS + hk) * params.seq + t) * HEAD_DIM;
if (t < step.pastRows) {
let src = ((b * KV_HEADS + hk) * params.capacity + t) * HEAD_DIM;
{{ channel_loop("HEAD_DIM", ["present_key[dst + d] = past_k[src + d];", "present_value[dst + d] = past_v[src + d];"]) }}
{% if stageRegion != "shift" %}
} else if (t < step.stageEnd) {
let src = (b * params.keySeq + t - step.pastRows) * KV_HIDDEN + hk * HEAD_DIM;
{{ channel_loop("HEAD_DIM", ["present_key[dst + d] = new_k[src + d];", "present_value[dst + d] = new_v[src + d];"]) }}
{% endif %}
} else if (t >= step.stageEnd) {
{{ channel_loop("HEAD_DIM", ["present_key[dst + d] = " + inputScalar + "(0.0);", "present_value[dst + d] = " + inputScalar + "(0.0);"]) }}
}
{% endif %}
{% endif %}
{% if cooperativeWindow %} }
{% endif %}
}