com.microsoft.GroupQueryAttention
com.microsoft · ONNX Runtime contrib operator · contrib since_version 1
Description
Grouped-query attention for explicit BSH Q/K/V and BNSH caches. Direct Q/K/V supports bidirectional attention or causal local windows and may store its generated float cache independently as float16 or float32; existing unquantized cache inputs match the Q/K/V dtype. Causal cache paths support rotary embeddings, sliding windows, bias, head sinks, softcap, smooth softmax, and paired Q/K RMS normalization. Int8/int4 caches require float32 Q/K/V and output; int4 is prompt-only. Packed QKV, position IDs, interleaved rotary, bfloat16/float8, and diagnostic QK output are not implemented.
See the ONNX Runtime GroupQueryAttention contrib-operator spec for the reference semantics.
Differences from the ONNX Runtime spec
- Input
position_ids: Positions are derived fromseqlens_k; explicit position IDs are unsupported. - Output
output_qk: The package does not expose the optional diagnostic QK matrix output. - Attribute
qk_output: The package does not exposeoutput_qk, so diagnostic QK output selection is not implemented. - Attribute
rotary_interleaved: Only the non-interleaved rotary layout is supported. - Input
keyT(ONNXkey): This package requires an explicit key tensor; packed QKV input is unsupported. - Input
valueT(ONNXvalue): This package requires an explicit value tensor; packed QKV input is unsupported. - Output
presentKeyT(ONNXpresent_key): The package always materializes the updated key cache. - Output
presentValueT(ONNXpresent_value): The package always materializes the updated value cache.
Inputs
| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |
|---|---|---|---|---|---|---|
queryT |
query |
T |
3 |
— | Query tensor of shape (batch_size, sequence_length, num_heads * head_size). |
required |
keyT |
key |
T |
3 |
— | Key tensor of shape (batch_size, kv_sequence_length, kv_num_heads * head_size). |
required |
valueT |
value |
T |
3 |
— | Value tensor of shape (batch_size, kv_sequence_length, kv_num_heads * head_size). |
required |
pastKeyT |
past_key |
T_CACHE |
4 |
— | Optional cached key state in BNSH format. Its sequence axis is max_sequence_length when the past and present buffers are shared, otherwise past_sequence_length; int4 stores each signed value as a +8-biased nibble, with the even head coordinate low, packing two values per logical uint8 element and widening each byte to one u32 WebGPU buffer word. |
optional |
pastValueT |
past_value |
T_CACHE |
4 |
— | Optional cached value state in BNSH format with the same length and packing semantics as past_key. |
optional |
seqlensKT |
seqlens_k |
M |
1 |
— | Int32 tensor of shape (batch_size) containing each sample's total sequence length minus one. Windowed caches keep absolute positions however many rows the cache holds. In windowed mode, a negative value or a total smaller than the new chunk zeroes that sample's attention output and present cache, even where its queries contain NaN. A seqlens_k value of INT32_MAX is handled without overflow, which goes beyond the ONNX Runtime spec. |
required |
totalSequenceLengthT |
total_sequence_length |
M |
1 |
— | Length-one int32 tensor containing the maximum total sequence length (past plus new) in the batch. The cache shaders use seqlens_k for addressing and do not read this scalar's contents; callers must supply a consistent maximum under the ORT contract. |
required |
cosCacheT |
cos_cache |
T |
2 |
— | Optional cosine cache for rotary embeddings with shape (max_sequence_length, head_size / 2). |
optional |
sinCacheT |
sin_cache |
T |
2 |
— | Optional sine cache for rotary embeddings with shape (max_sequence_length, head_size / 2). |
optional |
attentionBiasT |
attention_bias |
T |
4 |
— | Optional additive term for QK scores with shape (batch_size or 1, num_heads or 1, sequence_length, total_sequence_length); the first two dimensions broadcast. Windowed-cache columns use absolute key positions. If a bias row is narrower than the key count, the missing columns contribute zero and no other query row is read. |
optional |
headSinkT |
head_sink |
T |
1 |
— | Optional per-head smooth factor of shape (num_heads) added to the softmax denominator. |
optional |
kScaleT |
k_scale |
T_KV_SCALE |
1 |
— | Optional float32 key-cache scale: one value for PER_TENSOR, or kv_num_heads * head_size values for PER_CHANNEL. |
optional |
vScaleT |
v_scale |
T_KV_SCALE |
1 |
— | Optional float32 value-cache scale with the same shape convention as k_scale. |
optional |
qNormWeightT |
q_norm_weight |
T |
1 |
— | Optional per-head RMS-normalization weight of shape (head_size) applied to queries before rotary embedding. It must be provided together with k_norm_weight. |
optional |
kNormWeightT |
k_norm_weight |
T |
1 |
— | Optional per-head RMS-normalization weight of shape (head_size) applied to keys before rotary embedding. It must be provided together with q_norm_weight. |
optional |
Outputs
| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |
|---|---|---|---|---|---|---|
outputT |
output |
T |
3 |
same as queryT |
Attention output of shape (batch_size, sequence_length, hidden_size). |
required |
presentKeyT |
present_key |
T_CACHE |
4 |
— | Updated key cache in BNSH format. Its sequence axis is max_sequence_length for a shared buffer, otherwise past_sequence_length + kv_sequence_length; int4 stores each signed value as a +8-biased nibble, with the even head coordinate low, packing two values per logical uint8 element and widening each byte to one u32 WebGPU buffer word. In sliding_window_cache mode, capacity is fixed and only the block-eviction prefix described by that attribute is kept. |
required |
presentValueT |
present_value |
T_CACHE |
4 |
— | Updated value cache in BNSH format with the same length and packing semantics as present_key. |
required |
Attributes
Attributes and default values (overridable per request):
| Attribute | Default | Description |
|---|---|---|
causal |
1 |
Whether to apply a causal mask. Set to 0 for bidirectional attention; local_window_size must then be -1. |
do_rotary |
0 |
Set to 1 to apply rotary position embeddings. The default 0 disables them. |
k_quant_type |
"NONE" |
Key-cache quantization mode: NONE, PER_TENSOR, or PER_CHANNEL. |
kv_cache_bit_width |
— | Quantized cache bit width, either 8 or 4. Four-bit values are packed two per uint8 element. |
kv_num_heads |
— | Number of key/value attention heads. |
local_window_size |
-1 |
Left window size for causal local attention. The default -1 disables local attention, and the value must be -1 when causal is 0. |
num_heads |
— | Number of query attention heads. |
qk_norm_epsilon |
0.000001 |
Epsilon for the per-head Q/K RMS normalization applied when both normalization weights are provided. |
scale |
— | Optional QK score scale; zero or omission selects 1 / sqrt(head_size). |
sliding_window_cache |
0 |
Set to 1 for fixed-capacity block-eviction caches. Requires positive local_window_size W and capacity C>=W. With T=seqlens_k[b]+1, the defined prefix has L(T)=T for T<=C, otherwise W+((T-C-1) mod (C-W+1)); row i holds position T-L(T)+i. Attention stages the rows already cached plus the new chunk before compaction, including chunks larger than C. Rows after the prefix, which ONNX Runtime leaves undefined, are zeroed. Uneven multi-token batches go beyond what ONNX Runtime's CPU provider accepts. Rollback without editing is exact only if L(T-k)=L(T)-k; otherwise the caller must restore history. |
smooth_softmax |
-1 |
Set to 1 to enable the smooth-softmax denominator term. |
softcap |
0 |
Positive softcap applied to attention scores. The default 0 disables soft-capping. |
v_quant_type |
"NONE" |
Value-cache quantization mode: NONE, PER_TENSOR, or PER_CHANNEL. |
Type constraints
| Variable | Allowed dtypes |
|---|---|
T |
float32, float16 |
T_CACHE |
float32, float16, uint8, int8 |
T_KV_SCALE |
float32 |
M |
int32 |
Implementation variants
One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.
qkv_present_materialized_sgmat_f32— Bidirectional float32 prefill without past state. Subgroup matrices score queries and apply values. A per-tile roundoff check recomputes tiles whose query-key products are sensitive to rounding with compensated accumulation.cached_materialized_sgmat_f32— Updates the cache (a copy of the shared past, or the past merged with new rows), materializes causal scores with input-dtype subgroup-matrix tiles andf32accumulation, optionally adds the broadcast attention bias, and applies the normalized weights. Both passes skip key tiles past each query tile's right-aligned causal bound.past_kv_rotary_materialized_sgmat_f32— Rotates each query block at its absolute positions, then materializes causal scores against rotary-transformed cached keys and applies the normalized weights. The score and apply passes skip tiles beyond each query tile's causal bound.past_kv_rotary_materialized_sgmat_f16— Materializes the causal score matrix withf16operand tiles feedingf32-accumulating subgroup matrices over the shared cache and applies the softmax-normalized weights the same way; scores and row statistics stayf32. The score pass skips key tiles past each query tile's causal bound and the apply pass stops its reduction there.share_append_materialized_sgmat_f32— Materializes causal chunked-prefill attention while updating a shared-capacity cache in place. Score and apply passes bound every causal tile by the live length fromseqlens_k, not the buffer capacity, so right-padded batches remain left-aligned.new_kv_share_append_split— Retains a shared-capacity cache and appends new key/value rows in separate passes (rotating K when rotary is on), then runs portable attention with an optional per-head sink. Bidirectional (causal = 0) attention covers the whole live range[0, seqlens_k[b] + 1); the operator requireslocal_window_size = -1whencausal = 0.qkv_present_tiled_nosg— Tiled prefill without subgroups that computes attention online and writes the present cache separately. Used when the flash shape fits but no subgroup variant applies.qkv_stream_matrix8— Fuses bidirectional prefill scores, online softmax and value reduction within each 32-query tile. The 8×8 matrix contractions accumulate in float32 and keep probabilities and widened values in workgroup memory.qkv_present_flash_sgmat16_f16— Half prefill from direct query, key and value on 16x16x16 subgroup matrices with float32 accumulation: each workgroup sweeps one head's keys once for 64 queries with an online softmax over staged key and value tiles, bounded by each batch's sequence length; a separate pass writes the present cache.qkv_present_flash_sgmat16_split_f32— Float32 online attention after a pass that stores the query as float32. Query-key products, softmax probabilities and value accumulation remain float32, including wide-range and cancellation-sensitive inputs.qkv_present_flash,qkv_present— Computes online-softmax attention directly from Q/K/V and writes the present cache separately.causal=1withlocal_window_size=-1and no past cache applies the causal mask; keys then equal queries, so upper-left alignment is correct.append_decode_splitk— Appends the new key/value rows to the cache (int8-quantized for a quantized cache, or after the retained rows of a shared-capacity cache), partitions decode across the key axis, and merges partial online-softmax results. Used when one workgroup per head exposes too little independent work.qkv_present_flash_splitk— Partitions direct Q/K/V attention across the key axis, merges partial online-softmax results, and writes the present cache separately. It serves short-query shapes needing more key-axis parallelism.qkv_present_flash_cluster— Computes clustered online-softmax prefill directly from Q/K/V and writes the present cache separately. The family provides subgroup and portable reductions for the same tiled algorithm.qkv_present_flash_cluster_causal— Compute causal prompt prefill with subgroup query clusters and shared key/value tiles. Scores, softmax and weighted values accumulate in f32; keys beyond each query are excluded, and a separate pass writes the complete present cache.cached_decode_gqa— Updates the float cache in copy or merge mode, then one workgroup per key/value head and key range reads each cached row once for every query head of its group; a merge combines the ranges the live keys reach.cached_decode_splitk— Updates the float cache (a copy of the shared past, or the past merged with the new rows), then partitions cached decode across the key axis and combines partial online-softmax results. The family includes subgroup and portable forms.cached_flash_sgmat16_f16— Updates the float cache in the selected mode, then runs causal half prefill over the whole cache on 16x16x16 subgroup matrices with float32 accumulation: each workgroup sweeps one head's cached keys once for 64 queries with an online softmax over staged key and value tiles.past_kv_rotary_flash_sgmat16_f16— Copies the float cache, rotates the half queries once into a temporary buffer at their absolute positions (the cached keys are already rotated), then runs causal half prefill over the whole cache on 16x16x16 subgroup matrices with float32 accumulation.past_kv_flash_sgmat16_split_f32,new_kv_past_flash_sgmat16_split_f32— Updates the float cache in the selected mode, stores the query as float32, then runs causal float32 online attention over the cache. Products, softmax probabilities and value accumulation remain float32.cached_flash_prefill— Updates the float cache (a copy of the shared past, or the past merged with the new rows) and applies clustered online-softmax causal prefill, with optional fused rotary, softcap, additive bias, or head sink.qkv_present_flash_q32_broadcast,qkv_present_flash_q32_shared— Prefill over half QKV storage. Query-key products, probabilities and probability-value products use float32 arithmetic. Subgroup clusters are preferred when their complete workgroup fits; the shared-memory and broadcast variants remain available for devices with tighter limits.quant_flash_prefill— Builds an int8 or int4 cache and applies clustered online-softmax prefill directly from the packed values. The family supplies subgroup and portable reductions.share_append_split_flash_prefill— Retains shared-capacity cache rows, appends new rows separately, then applies clustered prefill: causal, or bidirectional (causal = 0) over the full live key range. It avoids rebuilding unchanged cache positions and includes subgroup and portable forms.share_append_split_flash_prefill_wide_cluster— Retains and appends shared-capacity caches, then increases the lanes cooperating on each query when fixed subgroup width, head divisibility and the workgroup budget permit. A proportionally smaller query tile preserves the invocation count.share_append_qnorm_rotary_decode_splitk— One-token decode over a shared-capacity float32 cache with paired Q/K RMS norms and rotary embeddings: a workgroup per new key head normalizes, rotates and appends it with its value; split-K decode then normalizes and rotates each query head in every split and merges partials stored beside their outputs.share_append_qnorm_rotary_decode_splitk_fused— One-token shared-cache decode with paired Q/K norms and rotary: the split owning the new position prepares its key and passes its unnormalized compensated value state to the merge, which adds the new value before normalizing that split and appends K/V once per KV head, using two attention dispatches and at most ten storage buffers.share_append_qnorm_rotary_flash_prefill— Causal prefill of a query block over a shared-capacity float32 cache with paired Q/K RMS norms and rotary embeddings: the new keys are normalized, rotated and appended, the queries prepared in a temporary buffer at their absolute positions, and clustered flash attention reads the live range.share_append_qnorm_rotary_split— Paired Q/K RMS normalization and rotary embeddings over a shared-capacity float32 cache for any query count: the normalized, rotated new keys are appended with their values, the queries prepared in a temporary buffer, and portable attention reads the live cache range. The fallback for blocks shorter than a flash query tile.window_shift_materialized_sgmat_f32— Stages cached history plus the new chunk, then materializes causal attention with the local-window mask. The score and value passes read the staged rows over the live length. Final compaction writes the block-eviction prefix and clears the suffix.window_shift_decode_splitk— Stages cached history and the new token, partitions decode across the staged key axis, then combines partial online-softmax results. Subgroup and portable forms preserve the block-eviction prefix during final compaction and clear the suffix.window_shift_decode_splitk_f16— Stages cached history and the new token in float16 storage, partitions decode across the staged key axis, then combines partial online-softmax results. Subgroup and portable forms preserve the block-eviction prefix during final compaction and clear the suffix.window_shift_flash_prefill— Stages cached history plus the new chunk for clustered online-softmax causal prefill with the local-window mask. Final compaction writes the block-eviction prefix and clears the suffix.window_shift_flash_prefill_f16— Stages cached history plus the new chunk in float16 storage for clustered online-softmax causal prefill with the local-window mask. Final compaction writes the block-eviction prefix and clears the suffix.window_shift_rotary_append— Stages cached history and appends new key/value rows, rotating K at its absolute position. Attention rotates Q likewise and applies cache-relative masks, an optional bias indexed by absolute key position, or a per-head softmax sink; compaction writes the block-eviction prefix and clears the suffix.window_shift_append,window_shift_append_f16— Windowed cached attention with optional additive bias or per-head softmax sink. Stages cached history plus the new chunk for attention, then writes the current block-eviction prefix and clears the suffix.matrix_shape_16x16x16_qkv_present_materialized_sgmat_f32— Experimental 16x16x16 value product for bidirectional float32 prefill. Uses compensated query-key scores and per-sample live key lengths.matrix_shape_16x8x16_qkv_present_materialized_sgmat_f32— Experimental 16x8x16 value product for bidirectional float32 prefill. Uses compensated query-key scores and per-sample live key lengths.matrix_shape_8x16x16_qkv_present_materialized_sgmat_f32— Experimental 8x16x16 value product for bidirectional float32 prefill. Uses compensated query-key scores and per-sample live key lengths.matrix_shape_16x16x32_qkv_present_materialized_sgmat_f32— Experimental 16x16x32 value product for bidirectional float32 prefill. Uses compensated query-key scores and per-sample live key lengths.matrix_shape_16x8x32_qkv_present_materialized_sgmat_f32— Experimental 16x8x32 value product for bidirectional float32 prefill. Uses compensated query-key scores and per-sample live key lengths.matrix_shape_16x16x16_cached_materialized_sgmat,matrix_shape_16x16x16_past_kv_rotary_materialized_sgmat— Experimental 16x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_16x8x16_cached_materialized_sgmat,matrix_shape_16x8x16_past_kv_rotary_materialized_sgmat— Experimental 16x8x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_8x16x16_cached_materialized_sgmat,matrix_shape_8x16x16_past_kv_rotary_materialized_sgmat— Experimental 8x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_16x16x32_cached_materialized_sgmat,matrix_shape_16x16x32_past_kv_rotary_materialized_sgmat— Experimental 16x16x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_16x8x32_cached_materialized_sgmat,matrix_shape_16x8x32_past_kv_rotary_materialized_sgmat— Experimental 16x8x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_16x16x16_share_append_materialized_sgmat_f32— Experimental 16x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_16x8x16_share_append_materialized_sgmat_f32— Experimental 16x8x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_8x16x16_share_append_materialized_sgmat_f32— Experimental 8x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_16x16x32_share_append_materialized_sgmat_f32— Experimental 16x16x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_16x8x32_share_append_materialized_sgmat_f32— Experimental 16x8x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_16x16x16_window_shift_materialized_sgmat_f32— Experimental 16x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_16x8x16_window_shift_materialized_sgmat_f32— Experimental 16x8x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_8x16x16_window_shift_materialized_sgmat_f32— Experimental 8x16x16 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_16x16x32_window_shift_materialized_sgmat_f32— Experimental 16x16x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.matrix_shape_16x8x32_window_shift_materialized_sgmat_f32— Experimental 16x8x32 subgroup-matrix attention that materializes scores with f32 matrix results; selected only after every non-experimental variant.
Device requirements
Some implementation variants require subgroup-matrix, shader-f16, and subgroups. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.
Files
metadata.json— kernel metadata (id, file digests, manifest spec, provenance)manifest.json— the op contract (source of truth)test.json— correctness casesbench.json— benchmark casesattention-flash-sgmat16.wgsl.jinjaattention-prepare-f32.wgsl.jinjaattention-rank4-tiled.wgsl.jinjaattn-decode-gqa-splitk-merge.wgsl.jinjaattn-decode-gqa-splitk.wgsl.jinjaattn-flash-decode-splitk-merge.wgsl.jinjaattn-flash-decode-splitk.wgsl.jinjaattn-flash-online.wgsl.jinjaattn-flash-prefill-cluster.wgsl.jinjaattn-flash-q32-broadcast.wgsl.jinjaattn-materialized-rowstats-combine-f32.wgsl.jinjaattn-materialized-score-f32.wgsl.jinjaattn-materialized-sgmat-f32.wgsl.jinjaattn-materialized-shaped.wgsl.jinjaattn-materialized-softmax-f32.wgsl.jinjaattn-online-scalar.wgsl.jinjagqa-attention.wgsl.jinjagqa-norm-rotate-rows.wgsl.jinjagqa-present.wgsl.jinjagqa-qprep.wgsl.jinjagqa-score-matrix.wgsl.jinjagqa-score-range.wgsl.jinjagqa-stream-matrix8.wgsl.jinjagqa-window-cache.wgsl.jinja
Use with @huggingface/kernels
npm install --save-exact @huggingface/kernels@0.0.1-preview.4
Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.
Outputs with inferable metadata are allocated automatically. Explicit outputs entries request optional results or provide metadata that cannot be inferred from the supplied inputs and attributes.
This example supplies explicit metadata for:
presentKeyTpresentValueT
The version: 1 option selects the published kernel contract; it is independent of any operator opset, contrib since_version, or model version.
It follows the v1 branch as fixes land. To pin exact artifact bytes, pass a 40-character commit revision instead of version.
import { getKernel } from "@huggingface/kernels";
const kernel = await getKernel("webgpu-kernels/com.microsoft.GroupQueryAttention", { version: 1 });
const queryTData = Float32Array.of(1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0);
const keyTData = Float32Array.of(0, 0, 0, 0, 0, 0, 0, 0, 3.1073449, 0, 0, 0, 0, 0, 0, 0);
const valueTData = Float32Array.of(1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3);
const seqlensKTData = Int32Array.of(1);
const totalSequenceLengthTData = Int32Array.of(2);
// Explicit destinations request optional results or supply metadata that cannot be inferred.
const { outputT, presentKeyT, presentValueT } = await kernel({
queryT: { data: queryTData, shape: [1, 2, 8] },
keyT: { data: keyTData, shape: [1, 2, 8] },
valueT: { data: valueTData, shape: [1, 2, 8] },
seqlensKT: { data: seqlensKTData, shape: [1] },
totalSequenceLengthT: { data: totalSequenceLengthTData, shape: [1] },
}, {
attrs: { num_heads: 1, kv_num_heads: 1 },
outputs: {
presentKeyT: { shape: [1, 1, 2, 8], dtype: "float32" },
presentValueT: { shape: [1, 1, 2, 8], dtype: "float32" },
},
});
console.log({ outputT, presentKeyT, presentValueT });
- Downloads last month
- -
Requires WebGPU support. See the compatibility table.