com.microsoft.PagedAttention
com.microsoft · ONNX Runtime contrib operator · contrib since_version 1
Description
Attention over an in-place paged KV cache. Supports grouped heads, packed QKV, scaling, explicit slots, float16 storage, causal/full masks, left windows, RoPE, paired per-head Q/K RMS normalization and head sinks. Sequence lengths, block tables and rotary positions are checked on the GPU before indexing: invalid requests yield zero attention and skip the writes derived from them; invalid blocks or slots are skipped. Without RoPE, explicit slot writes do not depend on the sequence lengths. Softcap, LATENT layout, narrower value heads, quantized KV and attention metadata are unsupported.
See the ONNX Runtime PagedAttention contrib-operator spec for the reference semantics.
Differences from the ONNX Runtime spec
- Input
k_scale, attributek_cache_dtype, attributek_quant_type: Quantized key-cache storage is not implemented by this inference package. - Input
v_scale, attributev_cache_dtype, attributev_quant_type: Quantized value-cache storage is not implemented by this inference package. - Input
attention_metadata: The optional attention-metadata fast path is not implemented by this inference package. - Attribute
kv_cache_layout: Only the standard paged cache layout represented by the rank-4 cache inputs is implemented. - Attribute
rotary_offset: Only zero-offset prefix rotary embedding is supported by this inference package. - Attribute
softcap: Attention softcap is not implemented by this inference package. - Attribute
v_head_size: A value-head width distinct from the query/key head width is not implemented. - Input
valueCacheT(ONNXvalue_cache): This package requires a distinct value cache; the schema's key-only cache mode is unsupported. - Output
key_cache_out: Returned as outputkeyCacheT. - Output
value_cache_out: Returned as outputvalueCacheT. - Type
T: Query, key, value, and cache tensors must use one common float16 data type.
Inputs
| Name | Upstream name | Logical dtype | WebGPU storage | Rank | Shape | Description | Presence |
|---|---|---|---|---|---|---|---|
queryT |
query |
T |
same as logical dtype | 2 |
— | Packed queries of shape (num_tokens, num_heads * head_size), or (num_tokens, (num_heads + 2 * kv_num_heads) * head_size) when key and value are absent and Q, K and V share one row. |
required |
keyT |
key |
T |
same as logical dtype | 2 |
— | Keys of shape (num_tokens, kv_num_heads * head_size). Absent means query carries packed [Q|K|V]. |
optional |
valueT |
value |
T |
same as logical dtype | 2 |
— | Values of shape (num_tokens, kv_num_heads * head_size). Present exactly when key is. |
optional |
keyCacheT |
key_cache |
T |
same as logical dtype | 4 |
— | Block-based key cache of shape (num_blocks, block_size, kv_num_heads, head_size), updated in place. |
required |
valueCacheT |
value_cache |
T |
same as logical dtype | 4 |
— | Block-based value cache with the same shape as key_cache, updated in place. |
required |
cumulativeSequenceLengthT |
cumulative_sequence_length |
S |
int32 |
1 |
— | Exclusive prefix sums of the per-sequence token counts, shape (batch_size + 1); sequence b owns packed tokens [cum[b], cum[b+1]). |
required |
pastSeqlensT |
past_seqlens |
S |
int32 |
1 |
— | Cached history length per sequence, shape (batch_size). |
required |
blockTableT |
block_table |
S |
int32 |
2 |
— | Physical block index per sequence and logical block, shape (batch_size, max_blocks_per_sequence). |
required |
cosCacheT |
cos_cache |
T |
same as logical dtype | 2 |
— | Optional RoPE cosine cache, (positions, rotary_dim / 2), paired with sin_cache when do_rotary is 1. The positive even rotary span may be a prefix of a head. Inactive caches are ignored. |
optional |
sinCacheT |
sin_cache |
T |
same as logical dtype | 2 |
— | Optional sine cache with the same shape and dtype as cos_cache. RoPE uses absolute positions past[b] + local_token, before new keys enter the cache. |
optional |
slotMappingT |
slot_mapping |
S |
int32 |
1 |
— | Flat destination slot, block_id * block_size + offset, for each token; -1 suppresses that token's cache write. When omitted, the slot is derived from past_seqlens. block_table remains required because it defines the read path. |
optional |
headSinkT |
head_sink |
T |
same as logical dtype | 1 |
— | Optional (num_heads) already-scaled logits. Each query head adds exp(sink) to its softmax denominator once, including across Split-K. Negative infinity contributes no mass; NaN or positive infinity produces NaN on a valid row. Invalid sequence lengths ignore sinks and output zero. |
optional |
qNormT |
q_norm_weight |
T |
same as logical dtype | 1 |
— | Optional per-channel RMS multiplier shared across query heads. Query and key weights must be supplied together; absent weights leave both inputs unchanged. | optional |
kNormT |
k_norm_weight |
T |
same as logical dtype | 1 |
— | Optional per-channel RMS multiplier shared across key heads. Query and key weights must be supplied together; absent weights leave both inputs unchanged. | optional |
Outputs
| Name | Upstream name | Logical dtype | Rank | Shape | Description | Presence |
|---|---|---|---|---|---|---|
outputT |
output |
T |
2 |
derived | Attention output of shape (num_tokens, num_heads * head_size). |
required |
keyCacheT |
key_cache |
T |
4 |
same as keyCacheT |
Optional return alias for the updated in-place key cache. Both caches are updated even when only this result is requested. | optional |
valueCacheT |
value_cache |
T |
4 |
same as valueCacheT |
Optional return alias for the updated in-place value cache. Both caches are updated even when only this result is requested. | optional |
Attributes
Attributes and default values (overridable per request):
| Attribute | Default | Description |
|---|---|---|
do_rotary |
0 |
Value 1 rotates the Q/K prefix in FP32 and rounds it to float16 before attention/cache storage; other integer values disable rotation. Requires positive-width matching cosine/sine caches. Rotary offset remains zero. |
is_causal |
1 |
Whether to apply causal masking: 1 attends through the current token; 0 attends to the full live context, including later tokens in this request. |
kv_num_heads |
— | Number of key/value heads. |
local_window_size |
-1 |
Query-relative left window. A positive W includes the current token and at most W-1 earlier tokens; non-causal mode retains every later live token. Non-positive values disable the window. Must be a safe integer; windows larger than the logical cache capacity are equivalent to an unbounded left mask. |
num_heads |
— | Number of query heads. |
qk_norm_epsilon |
0.000001 |
Positive representable finite float32 epsilon added to each incoming head's float32 mean square before normalization. Used only when both normalization weights are present. Normalized values round to float16 before optional rotary embedding. |
rotary_interleaved |
0 |
Value 1 pairs adjacent channels; other integer values pair the two halves of the rotary prefix. |
scale |
— | Scale applied to query-key products; zero or omission selects 1 / sqrt(head_size). |
Type constraints
| Variable | Allowed dtypes |
|---|---|
T |
float16 |
S |
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.
paged_splitk_subgroups— Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation.paged_subgroups— Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation.paged_splitk— Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation.paged— Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation.paged_qknorm_fused_splitk_subgroups— Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. A first pass applies per-head RMS normalization to Q and K, with RoPE in the same pass when enabled.paged_qknorm_fused_subgroups— Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. A first pass applies per-head RMS normalization to Q and K, with RoPE in the same pass when enabled.paged_qknorm_fused_splitk— Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. A first pass applies per-head RMS normalization to Q and K, with RoPE in the same pass when enabled.paged_qknorm_fused— Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. A first pass applies per-head RMS normalization to Q and K, with RoPE in the same pass when enabled.paged_rotary_splitk_subgroups— Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. A first pass applies RoPE to Q and K.paged_rotary_subgroups— Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. A first pass applies RoPE to Q and K.paged_rotary_splitk— Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. A first pass applies RoPE to Q and K.paged_rotary— Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. A first pass applies RoPE to Q and K.paged_rotary_qknorm_splitk_subgroups— Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. Separate first passes normalize Q, normalize K, then apply RoPE.paged_rotary_qknorm_subgroups— Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses portable-width subgroup reductions with FP32 scores, probabilities and accumulation. Separate first passes normalize Q, normalize K, then apply RoPE.paged_rotary_qknorm_splitk— Splits each key history into contiguous ranges and merges online-softmax states. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. Separate first passes normalize Q, normalize K, then apply RoPE.paged_rotary_qknorm— Cooperatively attends each token over its paged key/value history. Grouped query heads reuse resolved cache rows. Uses shared-memory tree reductions with FP32 scores, probabilities and accumulation. Separate first passes normalize Q, normalize K, then apply RoPE.
Device requirements
Every implementation variant requires shader-f16, so the package does not run without it.
Some implementation variants require subgroups. Other variants run without it; 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 casesattn-flash-decode-splitk-merge.wgsl.jinjapaged-attention.wgsl.jinjapaged-qknorm.wgsl.jinjapaged-rotary-qk.wgsl.jinjapaged-scatter-kv.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. This example also needs a device that supports the kernel's required WebGPU features.
Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.
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.
The Uint16Array inputs hold raw float16 bits and work on browsers without a Float16Array constructor.
import { getKernel } from "@huggingface/kernels";
const kernel = await getKernel("webgpu-kernels/com.microsoft.PagedAttention", { version: 1 });
const queryTData = Uint16Array.of(14920, 15384, 15400, 14976, 13869, 45218, 47424, 48157);
const keyTData = Uint16Array.of(46304, 44288, 12572, 13876);
const valueTData = Uint16Array.of(14469, 14860, 15030, 14942);
const keyCacheTData = Uint16Array.of(
13415, 13638, 13778, 13842, 13844, 13799, 13727, 13644, 13565, 13500, 13455, 13429,
);
const valueCacheTData = Uint16Array.of(
44245, 12392, 13113, 12712, 10327, 45027, 45747, 45404, 8203, 13384, 14385, 14705,
);
const cumulativeSequenceLengthTData = Int32Array.of(0, 2);
const pastSeqlensTData = Int32Array.of(2);
const blockTableTData = Int32Array.of(2, 0, 1);
const { keyCacheT, valueCacheT, outputT } = await kernel({
queryT: { data: queryTData, shape: [2, 4] },
keyT: { data: keyTData, shape: [2, 2] },
valueT: { data: valueTData, shape: [2, 2] },
keyCacheT: { data: keyCacheTData, shape: [3, 2, 1, 2] },
valueCacheT: { data: valueCacheTData, shape: [3, 2, 1, 2] },
cumulativeSequenceLengthT: { data: cumulativeSequenceLengthTData, shape: [2] },
pastSeqlensT: { data: pastSeqlensTData, shape: [1] },
blockTableT: { data: blockTableTData, shape: [1, 3] },
}, {
attrs: { num_heads: 2, kv_num_heads: 1 },
});
console.log({ keyCacheT, valueCacheT, outputT });
- Downloads last month
- -
Requires WebGPU support. See the compatibility table.