com.microsoft.SparseAttention

com.microsoft · ONNX Runtime contrib operator · contrib since_version 1

Description

CSR block-sparse causal attention with cyclic head layouts, grouped heads, packed/separate QKV, scaling, rotary and float16. Cache updates are in place. Invalid device counts yield zero output and preserve affected caches; invalid layouts yield zero attention but allow valid appends. Duplicate columns are idempotent; padding is ignored. Structurally masked V never participates, even if nonfinite; selected V preserves arithmetic at zero probability. Fully masked rows use uniform causal history. Head sizes are positive multiples of 8; bfloat16 is unsupported.

See the ONNX Runtime SparseAttention contrib-operator spec for the reference semantics.

Differences from the ONNX Runtime spec

  • Output present_key: Returned as output pastKeyT.
  • Output present_value: Returned as output pastValueT.

Inputs

Name Upstream name Logical dtype WebGPU storage Rank Shape Description Presence
queryT query T same as logical dtype 3 — Query (batch_size, sequence_length, num_heads * head_size), or packed [Q|K|V] (batch_size, sequence_length, (num_heads + 2 * kv_num_heads) * head_size) when key and value are omitted. required
keyT key T same as logical dtype 3 — Key (batch_size, sequence_length, kv_num_heads * head_size). Omitted for packed QKV. optional
valueT value T same as logical dtype 3 — Value (batch_size, sequence_length, kv_num_heads * head_size). Omitted for packed QKV. optional
pastKeyT past_key T same as logical dtype 4 — Key cache (batch_size, kv_num_heads, max_cache_sequence_length, head_size), updated in place. required
pastValueT past_value T same as logical dtype 4 — Value cache with the same shape as past_key, updated in place. required
blockRowIndicesT block_row_indices M int32 2 — CSR row pointers (num_layout, max_blocks + 1). Each layout starts at zero, is monotonically non-decreasing, and ends no later than that layout's block_col_indices width. required
blockColIndicesT block_col_indices M int32 2 — CSR column indices (num_layout, max_nnz_blocks), right-padded past each layout's non-zero count. Every active entry is in [0, max_blocks). required
totalSequenceLengthT total_sequence_length M int32 — — Scalar or one-element vector holding the maximum total key length. Equal to sequence_length exactly in the prompt case, which is how the past length is decided. The value fits the cache, the sparse layout's max_blocks * sparse_block_size capacity, and the rotary-cache row count when rotary is enabled. required
keyTotalSequenceLengthsT key_total_sequence_lengths M int32 1 — Per-batch total key length excluding padding, shape (batch_size). Each value is at most total_sequence_length and is at least 1 for a prompt or at least sequence_length otherwise. required
cosCacheT cos_cache T same as logical dtype 2 — Rotary cosine cache (max_rotary_sequence_length, rotary_dimension / 2), where the width is a multiple of 8 no larger than head_size / 2. Required with sin_cache when do_rotary is 1. optional
sinCacheT sin_cache T same as logical dtype 2 — Rotary sine cache with the same shape as cos_cache; required with it when do_rotary is 1. optional

Outputs

Name Upstream name Logical dtype Rank Shape Description Presence
outputT output T 3 derived Attention output (batch_size, sequence_length, num_heads * head_size). required
pastKeyT past_key T 4 same as pastKeyT The key cache tensor itself after the in-place append; ONNX names this output present_key. required
pastValueT past_value T 4 same as pastValueT The value cache tensor itself after the in-place append; ONNX names this output present_value. required

Attributes

Attributes and default values (overridable per request):

Attribute Default Description
do_rotary 0 Set to 1 to apply rotary embedding to Q and to K before it enters the cache; every other value disables rotary embedding.
kv_num_heads — Number of key/value heads; must divide num_heads.
num_heads — Number of query heads.
rotary_interleaved 0 Set to 1 to rotate adjacent pairs instead of using the NeoX half-split; every other value selects the NeoX layout.
scale — Scale applied to query-key products; omitted or zero uses 1 / sqrt(head_size).
sparse_block_size — Tokens per sparse block; one of 16, 32, 64, 128.

Type constraints

Variable Allowed dtypes
T float32, float16
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.

  • attention — Shares key and value loads across queries. Full-width f32 values use query pairs in large dispatches with the subgroup size fixed at 32. Underfilled f32 dispatches with many value partitions use one query per workgroup. Head width and workgroup storage bound partitioning and staging.
  • attention_flash — Block-tiled online attention shares each absolute-position query tile across its selected CSR key blocks.
  • attention_sgmat — Float32 subgroup-matrix online attention computes each score tile once, rescales output fragments through a workgroup-memory score tile, and directly loads complete query tiles. Only a partial query tile is staged; key-tile width and fragment-bank capacity follow the reported workgroup-storage limit.
  • attention_sgmat_tail — For a prompt, complete matrix tiles run first and a thin query tail then runs on the portable kernel of the non-matrix attention variants. History calls retain the full matrix computation. Tail size and value partitions follow workgroup capacity. Heads narrower than the query tile use the full matrix path.
  • attention_sgmat_certified — Float32 matrix attention. Appending checks each consumed 64-key tile of V for nonfinite values. KV heads with finite V use matrix contraction; the others contract only the keys their sparse layout selects, including zero weights. Other variants are used when resource limits are not met.
  • attention_sgmat_tail_certified — Float32 matrix attention. Appending checks each consumed 64-key tile of V for nonfinite values. KV heads with finite V use matrix contraction; the others contract only the keys their sparse layout selects, including zero weights. The thin query tail runs in a portable pass. Other variants are used when resource limits are not met.
  • attention_rotary — Shares key and value loads across queries. Full-width f32 values use query pairs in large dispatches with the subgroup size fixed at 32. Underfilled f32 dispatches with many value partitions use one query per workgroup. Head width and workgroup storage bound partitioning and staging. Adds a query rotary pass.
  • attention_rotary_flash — Block-tiled online attention shares each absolute-position query tile across its selected CSR key blocks. Adds a query rotary pass.
  • attention_rotary_sgmat — Float32 subgroup-matrix online attention computes each score tile once, rescales output fragments through a workgroup-memory score tile, and directly loads complete query tiles. Only a partial query tile is staged; key-tile width and fragment-bank capacity follow the reported workgroup-storage limit. Adds a query rotary pass.
  • attention_rotary_sgmat_tail — For a prompt, complete matrix tiles run first and a thin query tail then runs on the portable kernel of the non-matrix attention variants. History calls retain the full matrix computation. Tail size and value partitions follow workgroup capacity. Heads narrower than the query tile use the full matrix path. Adds a query rotary pass.
  • attention_rotary_sgmat_certified — Float32 matrix attention. Appending checks each consumed 64-key tile of V for nonfinite values. KV heads with finite V use matrix contraction; the others contract only the keys their sparse layout selects, including zero weights. Other variants are used when resource limits are not met. Adds a query rotary pass.
  • attention_rotary_sgmat_tail_certified — Float32 matrix attention. Appending checks each consumed 64-key tile of V for nonfinite values. KV heads with finite V use matrix contraction; the others contract only the keys their sparse layout selects, including zero weights. The thin query tail runs in a portable pass. Other variants are used when resource limits are not met. Adds a query rotary pass.

Device requirements

Some implementation variants require subgroup-matrix and subgroups. Other variants run without them; which variant runs also depends on the request's shapes and dtypes.

Files

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.

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.

import { getKernel } from "@huggingface/kernels";

const kernel = await getKernel("webgpu-kernels/com.microsoft.SparseAttention", { version: 1 });

const queryTData = new Float32Array(16);
const keyTData = new Float32Array(16).fill(2);
const valueTData = new Float32Array(16).fill(8);
const pastKeyTData = Float32Array.from({ length: 64 }, (_, i) => [0.125, -0.25, 0.375, -0.5, 0.625][i % 5] ?? 0.125);
const pastValueTData = Float32Array.from({ length: 64 }, (_, i) => [0.125, -0.25, 0.375, -0.5, 0.625][i % 5] ?? 0.125);
const blockRowIndicesTData = Int32Array.of(0, 1);
const blockColIndicesTData = new Int32Array(1);
const totalSequenceLengthTData = Int32Array.of(5);
const keyTotalSequenceLengthsTData = Int32Array.of(5, 1);

const { pastKeyT, pastValueT, outputT } = await kernel({
  queryT: { data: queryTData, shape: [2, 1, 8] },
  keyT: { data: keyTData, shape: [2, 1, 8] },
  valueT: { data: valueTData, shape: [2, 1, 8] },
  pastKeyT: { data: pastKeyTData, shape: [2, 1, 4, 8] },
  pastValueT: { data: pastValueTData, shape: [2, 1, 4, 8] },
  blockRowIndicesT: { data: blockRowIndicesTData, shape: [1, 2] },
  blockColIndicesT: { data: blockColIndicesTData, shape: [1, 1] },
  totalSequenceLengthT: { data: totalSequenceLengthTData, shape: [1] },
  keyTotalSequenceLengthsT: { data: keyTotalSequenceLengthsTData, shape: [2] },
}, {
  attrs: { num_heads: 1, kv_num_heads: 1, sparse_block_size: 16 },
});
console.log({ pastKeyT, pastValueT, outputT });
Downloads last month
-
kernel
webgpu
wgsl
apache-2.0
WebGPU

Requires WebGPU support. See the compatibility table.