com.microsoft.MultiHeadAttention

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

Description

Computes multi-head self- or cross-attention over explicit query, key, and value tensors, with an optional fused QKV projection bias and additive attention bias. Supports causal masking through unidirectional and a configurable score scale that defaults to 1 / sqrt(head_size). Query, key, and value must have the same hidden width; distinct value-head widths, KV-cache, key-padding-mask, and diagnostic-QK modes are unsupported.

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

Differences from the ONNX Runtime spec

  • Input key_padding_mask: The optional key-padding mask input is unsupported.
  • Input past_key, input past_value, input past_sequence_length: Optional KV-cache inputs are unsupported.
  • Input cache_indirection: Beam-search cache indirection is unsupported.
  • Output present_key, output present_value: The inference package does not expose optional KV-cache outputs.
  • Output qk: The inference package does not expose the optional diagnostic QK output.
  • Attribute mask_filter_value: Has no effect, because key-padding masks are not supported.
  • Input keyT (ONNX key), input valueT (ONNX value): Explicit key and value tensors are required; packed QKV input is not supported.

Inputs

Name Upstream name Logical dtype Rank Shape Description Presence
queryT query T 3 — Query tensor of shape (batch_size, sequence_length, hidden_size). required
keyT key T 3 — Key tensor of shape (batch_size, kv_sequence_length, hidden_size); its hidden width must equal the query hidden width. required
valueT value T 3 — Value tensor of shape (batch_size, kv_sequence_length, v_hidden_size); v_hidden_size must equal the query hidden width. required
biasT bias T 1 — Optional fused bias from input projection with shape (hidden_size + hidden_size + v_hidden_size). optional
attentionBiasT attention_bias T 4 — Optional additive bias applied to the attention scores before softmax, of shape (batch_size or 1, num_heads or 1, sequence_length, kv_sequence_length); the first two dimensions broadcast. optional

Outputs

Name Upstream name Logical dtype Rank Shape Description Presence
outputT output T 3 [queryT[0], queryT[1], valueT[2]] Attention output of shape (batch_size, sequence_length, v_hidden_size). required

Attributes

Attributes and default values (overridable per request):

Attribute Default Description
num_heads — Number of attention heads.
scale — Optional score scale; zero or omission selects 1 / sqrt(head_size).
unidirectional 0 When 1, applies an upper-left causal mask: query position i attends only to key positions 0..min(i, kv_sequence_length - 1).

Type constraints

Variable Allowed dtypes
T float32, float16

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_no_bias_flash_sgmat16_split_f32 — Float32 online attention; a first pass copies the query into a contiguous float32 buffer. Query-key products, softmax probabilities and value accumulation remain float32, including wide-range and cancellation-sensitive inputs.
  • qkv_no_bias_flash_sgmat16_f16 — Half attention on 16x16x16 subgroup matrices with float32 accumulation: each workgroup sweeps one head's keys once for 64 queries with an online softmax, staging key and value tiles in workgroup memory.
  • qkv_no_bias_small_head_split — Partitions long small-head key reductions into device-bounded workgroup storage, reuses keys for a query pair when its shared and private budgets fit, and merges f32 softmax statistics and value sums. Wider heads use the unsplit cooperative variant when it fits and independent queries already supply enough workgroups.
  • qkv_no_bias_small_head_value_subgroups — Uses portable-width subgroup collectives with float32 scores, probabilities and accumulation. Query pairs reuse staged values when shared storage fits; subgroup geometry determines row pairing and the portable fallback.
  • qkv_no_bias_small_head_value_tree — Uses shared-memory tree reductions with float32 scores, probabilities and accumulation. Query pairs reuse staged values when shared storage fits; subgroup geometry determines row pairing and the portable fallback.
  • qkv_small_seq_blocked — Blocked whole-head attention for short key sequences with optional bias and causal masking. A workgroup stages one head's K and V, and each query in a small block is owned by a group of key lanes that merge online-softmax partials. Incomplete head vectors use masked scalar storage, and longer key sequences reuse bounded key/value tiles.
  • qkv_no_bias_small_seq — Whole-head attention for short bidirectional float32 requests without bias. One workgroup stages a head's complete key and value planes, and each participating invocation owns one query row through scoring, normalization, and context accumulation.
  • qkv_no_bias_tiled_nosg — Tiled prefill variant that runs on any device, used when no subgroup variant applies. It computes attention online without materializing the full score matrix.
  • qkv_no_bias_materialized_sgmat_fused_f16 — Materializes FP32 scores for subgroup-matrix score and value products, then folds softmax normalization into the apply pass using row statistics emitted by the score pass.
  • qkv_no_bias_flash_cluster_lpq4_nosg, qkv_no_bias_flash_cluster_nosg, qkv_bias_flash_cluster_nosg, qkv_no_bias_flash_cluster, qkv_bias_flash_cluster_single_query, qkv_no_bias_flash_cluster_attn_bias, qkv_bias_flash_cluster_attn_bias — Keeps query/key tiles and online-softmax state inside one workgroup instead of materializing all scores. The family supplies subgroup and portable forms for compatible prefill shapes.
  • qkv_no_bias_flash_splitk_nosg, qkv_bias_flash_splitk_nosg, qkv_no_bias_flash_splitk, qkv_bias_flash_splitk — Partitions the key reduction across workgroups and merges partial softmax statistics and values. Used when decode or another short query has too few independent query/head workgroups; the merge reassociates the key reduction.
  • qkv_no_bias_materialized_gemm_f16 — Materializes float32 scores and applies tiled score, softmax, and value passes without requiring subgroup-matrix support.
  • qkv_materialized_gemm_f32 — Materializes raw float32 scores, computes row maxima and denominators in a separate pass, and normalizes weighted values while applying the score matrix. With the fused projection bias, the query part is added when scores are formed and the value part when the result is written.
  • qkv_no_bias_portable_prefill_gemm_f32 — Materializes raw float32 scores, computes row maxima and denominators in a separate pass, and normalizes weighted values while applying the score matrix. Portable prefill form for float32, non-causal attention without the fused projection bias, with head sizes from 32 to 128 that are multiples of four.
  • qkv_materialized_gemm_fused_f32 — Materializes FP32 scores while writing out each row's maximum, combines those row statistics, then normalizes and applies the scores in one pass. It is used for large score matrices.
  • qkv_online_scalar — Portable scalar online attention with bias and additive-mask support. It applies online softmax while accumulating context, without materializing a score tensor.
  • qkv_flash — Computes one-pass online-softmax attention without score scratch, combining partial results with subgroup operations. Applies the optional fused projection bias (query and value parts) and the optional additive attention bias.
  • qkv_flash_nosg — Computes one-pass online-softmax attention with portable workgroup reductions. Applies the optional projection bias to query and value and accepts an additive attention bias.
  • qkv_no_bias_tiled_attn_bias_nosg — Tiled prefill variant for additive attention bias that runs on any device, used when no subgroup variant applies. It computes attention online without materializing the full score matrix.
  • qkv_materialized_sgmat_f32 — Computes compensated float32 scores with register tiles, normalizes them, and uses subgroup matrices for the value product.
  • matrix_shape_16x16x16_qkv_materialized_sgmat_fused — Experimental 16x16x16 subgroup-matrix attention that materializes scores with f32 results and full result banks; selected only after every non-experimental variant.
  • matrix_shape_16x8x16_qkv_materialized_sgmat_fused — Experimental 16x8x16 subgroup-matrix attention that materializes scores with f32 results and full result banks; selected only after every non-experimental variant.
  • matrix_shape_8x16x16_qkv_materialized_sgmat_fused — Experimental 8x16x16 subgroup-matrix attention that materializes scores with f32 results and full result banks; selected only after every non-experimental variant.
  • matrix_shape_16x16x32_qkv_materialized_sgmat_fused — Experimental 16x16x32 subgroup-matrix attention that materializes scores with f32 results and full result banks; selected only after every non-experimental variant.
  • matrix_shape_16x8x32_qkv_materialized_sgmat_fused — Experimental 16x8x32 subgroup-matrix attention that materializes scores with f32 results and full result banks; selected only after every non-experimental variant.
  • matrix_shape_16x16x16_qkv_materialized_sgmat_f32 — Experimental 16x16x16 subgroup-matrix attention that materializes scores with f32 results and full result banks; selected only after every non-experimental variant.
  • matrix_shape_16x8x16_qkv_materialized_sgmat_f32 — Experimental 16x8x16 subgroup-matrix attention that materializes scores with f32 results and full result banks; selected only after every non-experimental variant.
  • matrix_shape_8x16x16_qkv_materialized_sgmat_f32 — Experimental 8x16x16 subgroup-matrix attention that materializes scores with f32 results and full result banks; selected only after every non-experimental variant.
  • matrix_shape_16x16x32_qkv_materialized_sgmat_f32 — Experimental 16x16x32 subgroup-matrix attention that materializes scores with f32 results and full result banks; selected only after every non-experimental variant.
  • matrix_shape_16x8x32_qkv_materialized_sgmat_f32 — Experimental 16x8x32 subgroup-matrix attention that materializes scores with f32 results and full result banks; selected only after every non-experimental variant.
  • qkv_no_bias_materialized_chunked_f16 — Processes bidirectional half-storage attention in query tiles, reusing a bounded float32 score buffer across tiled score, normalization and value passes.
  • qkv_no_bias_short_keys_parallel — Parallelizes short bidirectional queries over key rows with compensated float32 score dots and stable softmax. Workgroup and storage limits bound its use. Unless the subgroup size varies between 16 and 32 and subgroup matrices are unavailable, it runs only where the small-head variants do not apply.
  • qkv_no_bias_flash_shared_marginal — Shares key/value tiles across query rows with f32 score and weighted-value arithmetic. When fewer than half of the workgroup's query lanes would have a query, other variants, such as the materialized-score one when it fits, are tried first.

Device requirements

Some implementation variants require subgroup-matrix, shader-f16, subgroup-size-control, 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.MultiHeadAttention", { version: 1 });

const queryTData = Float32Array.of(
  0.22789244, 0.22044024, 0.20084392, 0.17508654, 0.14936417, 0.12938726, 0.11974238,
  0.12337762, 0.14126305, 0.1722603, 0.21321473, 0.25926188, 0.30431902, 0.34171373,
  0.36488852, 0.3681124,
);
const keyTData = Float32Array.of(
  0.25060526, 0.24965166, 0.23909184, 0.22119953, 0.198571, 0.17396842, 0.15015538,
  0.12973358, 0.11498952, 0.10775946, 0.10931987, 0.12030941, 0.14068654, 0.16972525,
  0.20604907, 0.24770172, 0.29225072, 0.3369183, 0.37873298, 0.41469347, 0.44193655,
  0.45789945, 0.46046844, 0.44810566,
);
const valueTData = Float32Array.of(
  0.11755285, 0.037285462, -0.04018352, -0.09757858, -0.1210173, -0.10233293,
  -0.040449027, 0.05842166, 0.1817872, 0.312928, 0.43365, 0.52728313, 0.58142805,
  0.5899964, 0.55420554, 0.48236412, 0.38848296, 0.28994262, 0.20460331, 0.14783701,
  0.1299734, 0.15458316, 0.2178831, 0.30936182,
);

const { outputT } = await kernel({
  queryT: { data: queryTData, shape: [2, 2, 4] },
  keyT: { data: keyTData, shape: [2, 3, 4] },
  valueT: { data: valueTData, shape: [2, 3, 4] },
}, {
  attrs: { num_heads: 2 },
});
console.log({ outputT });
Downloads last month
-
kernel
webgpu
wgsl
apache-2.0
WebGPU

Requires WebGPU support. See the compatibility table.