Skip to content

Commit f51ad25

Browse files
titaiwangmsCopilot
andauthored
Emit bias-aware external-KV (TensorScatter + nonpad_kv_seqlen) attention for float-bias decoders (#367)
## What Adds a flag-gated, bias-aware variant of the shared static-cache `Attention` path: it can now carry an optional float additive bias (causal + sliding-window + Gemma-4 block-overlay + padding) over the opset-24 external KV cache (`TensorScatter` + `nonpad_kv_seqlen`), with `is_causal=0` strictly paired to bias-present. The maskless `is_causal=1` path (#345) stays the default and is byte-identical when the flag is off. This is the contract-independent, ORT-testable CORE of #349 (float-bias decoders → near-GQA decode). It does NOT re-emit Gemma-4 itself or wire genai — those are deliberately out of scope (see below). ## Changes - `components/_common.py`: NEW `create_static_cache_attention_bias` — emits a `(B,1,S_q,max_seq)` additive bias keyed on absolute query positions (`write_indices + arange(S_q)`) over dense cache slots with validity `slot < nonpad_kv_seqlen`, reusing the proven `create_attention_bias` causal/sliding/block-overlay/padding rules (re-keyed to static-cache geometry). Exported from `components/__init__.py`. - `components/_attention.py`: static branch now derives `(mask_arg, is_causal)` from `attn_mask` presence — bias-present ⇒ `is_causal=0` (strictly paired; incoming `is_causal` ignored so the two can never disagree), maskless ⇒ `is_causal=1`. `nonpad_kv_seqlen` kept as Attention input #6 in both modes. - `models/base.py`: `TextModel` threads the bias when `flags.static_cache_bias` is on AND the model has a `sliding_window` AND static cache is active; otherwise exact prior maskless behavior. - `_flags.py`: NEW `MOBIUS_STATIC_CACHE_BIAS` env flag (default OFF) → `flags.static_cache_bias`. - `tests/static_cache_bias_parity_test.py`: NEW — ORT CPU (MEA) manual-feed parity vs an independent numpy dense-attention reference for a prefill chunk, a decode step, a per-batch B=2 decode (write/nonpad broadcasting), a sliding-window sweep, and a nonpad padding-clamp; plus graph-wiring tests asserting flag-off=maskless, flag-on+sliding=bias-threaded (is_causal=0, bias input#3, nonpad input#6), and flag-on+non-sliding (llama) stays maskless. 10/10 on CPU; no genai, no Flash, no onnxruntime#28958 required. ## Why flag-gated / what's deferred (Phase 2, under #349) The bias geometry is a pure function of model semantics + cache layout, independent of how the runtime drives the graph — so it is safe to land before the genai consumer exists. Explicitly OUT OF SCOPE here: re-emitting Gemma-4's own task/model on the static path, `genai_config.json` wiring, single-graph vs prefill/decode-split packaging, e2e generation/decode profiling, the 4D KV layout migration, and block-overlay at non-zero write offsets (decode-time block overlay is a no-op under the current scatter-current-chunk geometry; TODO noted in the test file). ## Verified - 10/10 new parity tests on CPU (ORT MEA) vs an independent numpy dense reference; broad non-integration sanity 2927 passed / 43 skipped; lintrunner clean (real pyproject config). - Triple-reviewed (code + critical + readability) on the impl + a code/critical delta pass on the review polish. Critical empirically verified on CPU that the bias-MEA contract keeps every query row's diagonal slot valid (no fully-masked row → no NaN edge). ## Relationships - Closes #366 - Part of #349 (Gemma-4 end-to-end near-GQA decode consumer) - Sibling to #345 (maskless `is_causal=1` static-cache graph) — shares the `TensorScatter` + `nonpad_kv_seqlen` primitive; this PR adds the bias variant. - genai-side driving tracked separately at microsoft/onnxruntime-genai#2204. --------- Signed-off-by: titaiwang <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent 1ad4160 commit f51ad25

6 files changed

Lines changed: 1077 additions & 27 deletions

File tree

‎src/mobius/_flags.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,13 @@ class _Flags:
9090
- Use native ``MatMulNBits bits=2`` for Tencent SEQ Q1_0
9191
(smaller, semantically faithful, but ~20x slower on CPU EP
9292
pending an MLAS fast path).
93+
* - ``static_cache_bias``
94+
- ``MOBIUS_STATIC_CACHE_BIAS``
95+
- ``False``
96+
- Emit a float additive attention bias (causal + sliding window +
97+
block overlay + padding) on the external-KV static-cache
98+
``Attention`` path (``is_causal=0``) for float-bias decoders,
99+
instead of the maskless ``is_causal=1`` default.
93100
"""
94101

95102
suppress_dedup_warning: bool = dataclasses.field(
@@ -150,6 +157,27 @@ class _Flags:
150157
opt in to the smaller native form once kernel performance lands.
151158
"""
152159

160+
static_cache_bias: bool = dataclasses.field(
161+
default_factory=lambda: _env_bool("MOBIUS_STATIC_CACHE_BIAS", False)
162+
)
163+
"""Emit a float additive attention bias on the external-KV static-cache
164+
``Attention`` path instead of the maskless ``is_causal=1`` default.
165+
166+
When ``True`` (and the model declares a bias need, e.g. a sliding window
167+
or a block-overlay hook), :class:`~mobius.models.base.TextModel` builds a
168+
``(B, 1, S_q, max_seq)`` additive bias via
169+
:func:`~mobius.components.create_static_cache_attention_bias` (causal +
170+
sliding window + block overlay + padding, keyed on absolute query
171+
positions with KV validity ``slot < nonpad_kv_seqlen``) and threads it
172+
into the static-cache ``Attention`` op with ``is_causal=0``. This lets a
173+
single standard-``Attention`` graph carry an arbitrary additive bias that
174+
``com.microsoft.GroupQueryAttention`` cannot express, while still using the
175+
opset-24 external KV cache (``TensorScatter`` + ``nonpad_kv_seqlen``).
176+
177+
Default ``False``: the maskless ``is_causal=1`` static-cache emission is
178+
unchanged, so no shipped model's graph changes unless this flag is set.
179+
"""
180+
153181

154182
# Global singleton — import and use this directly.
155183
flags = _Flags()

‎src/mobius/components/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@
7474
"create_decoder_layer",
7575
"create_padding_mask",
7676
"create_sliding_window_mask",
77+
"create_static_cache_attention_bias",
7778
"get_activation",
7879
"initialize_rope",
7980
"make_quantized_linear_factory",
@@ -118,6 +119,7 @@
118119
create_attention_bias,
119120
create_padding_mask,
120121
create_sliding_window_mask,
122+
create_static_cache_attention_bias,
121123
)
122124
from mobius.components._conv import (
123125
BatchNorm2d,

‎src/mobius/components/_attention.py‎

Lines changed: 49 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,8 @@ class StaticCacheState(NamedTuple):
6262
``nonpad_kv_seqlen`` to indicate valid token counts.
6363
6464
Fields:
65-
key_cache: Pre-allocated key cache [B, max_seq, kv_hidden] 3D.
66-
value_cache: Pre-allocated value cache [B, max_seq, kv_hidden] 3D.
65+
key_cache: Pre-allocated key cache [B, max_seq_len, kv_hidden] 3D.
66+
value_cache: Pre-allocated value cache [B, max_seq_len, kv_hidden] 3D.
6767
write_indices: Position to write new tokens [B] int64.
6868
nonpad_kv_seqlen: Valid KV length per batch entry [B] int64.
6969
"""
@@ -101,7 +101,12 @@ def _apply_attention(
101101
Static cache mode (``static_cache is not None``):
102102
Scatters new key/value into the static cache via TensorScatter,
103103
then attends over the full cache using ``nonpad_kv_seqlen``.
104-
Also uses ``is_causal=1``.
104+
Uses ``is_causal=1`` when ``attn_mask`` is ``None`` (maskless
105+
default), or ``is_causal=0`` when ``attn_mask`` is a float additive
106+
bias (the bias then carries the full causal + sliding + block +
107+
padding mask). The incoming ``is_causal`` argument is ignored in
108+
this mode; causality is derived from ``attn_mask`` presence so the
109+
two can never disagree.
105110
Returns ``(attn_output, updated_key_cache, updated_value_cache)``.
106111
107112
Args:
@@ -114,10 +119,12 @@ def _apply_attention(
114119
unmasking encoded in the bias.
115120
116121
Note:
117-
Both paths default to ``is_causal=1`` on the Attention op, which
118-
enables built-in causal masking. This means ``attn_mask`` should
119-
encode only padding information (as a bool mask), not causality,
120-
unless ``is_causal=0`` is passed explicitly.
122+
This applies to the DYNAMIC cache path only. There, the Attention op
123+
defaults to ``is_causal=1`` for built-in causal masking, so
124+
``attn_mask`` should encode only padding information (as a bool mask),
125+
not causality, unless ``is_causal=0`` is passed explicitly. In STATIC
126+
cache mode the incoming ``is_causal`` argument is ignored — causality
127+
is derived from ``attn_mask`` presence (see above).
121128
122129
Note:
123130
``nonpad_kv_seqlen`` (input #6) is only valid in static cache mode
@@ -149,36 +156,53 @@ def _apply_attention(
149156
axis=1,
150157
) # [B, max_seq, kv_hidden]
151158

152-
# Attend over the full cache. We pass None for attn_mask and use
153-
# is_causal=1 instead — the Attention op handles causal + padding
154-
# masking internally via is_causal + nonpad_kv_seqlen. Using
155-
# create_attention_bias() here would produce incorrect causality
156-
# during prefill because it cannot represent the relationship
157-
# between query positions and the full cache length.
159+
# External-cache masking. Two modes, selected by whether the caller
160+
# supplied a float additive bias:
158161
#
159-
# NOTE: The ONNX Attention spec supports attn_mask alongside
160-
# nonpad_kv_seqlen for custom masking (e.g., user-defined masks
161-
# beyond causal + padding). Currently we rely on is_causal=1 +
162-
# nonpad_kv_seqlen for standard LLM causal + padding masking.
163-
# TODO(titaiwang): Support user-provided attn_mask in external
164-
# cache mode for advanced use cases (e.g., prefix masking,
165-
# document boundaries in batched inference).
166-
# TODO(titaiwang): Support sliding window (circular cache mode)
167-
# with static cache for long-context models that use local
168-
# attention windows.
162+
# * attn_mask is None (default, maskless): pass None and use
163+
# is_causal=1 — the Attention op derives causal + padding masking
164+
# internally from is_causal + nonpad_kv_seqlen. This is the
165+
# Flash-eligible form (onnx#8068 / onnxruntime#28958).
166+
# * attn_mask is not None (float-bias decoders): pass the bias and
167+
# STRICTLY pair it with is_causal=0. The bias already bakes in the
168+
# FULL mask (causal + sliding + Gemma4 block overlay + padding), so
169+
# leaving is_causal=1 would double-apply causality and cancel any
170+
# bidirectional unmasking encoded in the bias. This routes ORT to
171+
# the MEA external-cache path (Flash is precluded by any bias).
172+
#
173+
# nonpad_kv_seqlen stays as input #6 in BOTH modes: it bounds the valid
174+
# KV prefix and, on the CUDA Flash path, drives the fully-masked-row
175+
# zero guard (LaunchZeroFullyMaskedRows). In bias mode the additive
176+
# bias already encodes the same ``slot < nonpad`` validity. The
177+
# cross-repo invariant is ``nonpad == write_indices + valid_token_count``
178+
# (the count of UNPADDED query tokens), which equals
179+
# ``write_indices + S_q`` only when the chunk is unpadded — S_q is the
180+
# PADDED chunk width. When the chunk is unpadded, every query row keeps
181+
# its own diagonal slot valid, so a fully-masked (all-``dtype.min``) row
182+
# never arises. With intra-prompt padding plus a sliding window,
183+
# however, a pad-token query row CAN fall outside every valid slot and
184+
# become fully masked. In that case the CPU MEA path this bias mode uses
185+
# does NOT apply the Flash zero-guard: it returns a finite mean-of-V row
186+
# (not NaN, not exactly 0). This finite-row behavior was empirically
187+
# verified on ORT 1.27 CPU MEA; it is an observed ORT-version behavior,
188+
# not a permanent op-spec invariant — see test_fully_masked_row_stays_finite.
189+
if attn_mask is not None:
190+
mask_arg, causal = attn_mask, 0
191+
else:
192+
mask_arg, causal = None, 1
169193
attn_output, _, _ = op.Attention(
170194
query,
171195
updated_k,
172196
updated_v,
173-
None, # no attn_mask — is_causal handles masking
197+
mask_arg,
174198
None, # no past_key (full cache is already provided)
175199
None, # no past_value
176200
static_cache.nonpad_kv_seqlen,
177201
q_num_heads=num_attention_heads,
178202
kv_num_heads=num_key_value_heads,
179203
scale=scale,
180204
softcap=softcap,
181-
is_causal=is_causal,
205+
is_causal=causal,
182206
_outputs=3,
183207
)
184208
return attn_output, updated_k, updated_v

‎src/mobius/components/_common.py‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,146 @@ def create_attention_bias(
264264
return op.Unsqueeze(attention_bias, [1])
265265

266266

267+
def create_static_cache_attention_bias(
268+
op: OpBuilder,
269+
*,
270+
write_indices: ir.Value,
271+
seq_len: ir.Value,
272+
nonpad_kv_seqlen: ir.Value,
273+
max_seq_len: int,
274+
sliding_window: int | None = None,
275+
block_sequence_ids: ir.Value | None = None,
276+
dtype: ir.DataType = ir.DataType.FLOAT,
277+
) -> ir.Value:
278+
"""Build a float additive attention bias for the external-KV static cache.
279+
280+
Sibling to :func:`create_attention_bias`. That function masks against a
281+
*dense* ``[batch, total_length]`` ``attention_mask`` whose width grows with
282+
the sequence; this one masks against the *pre-allocated* static cache whose
283+
KV axis has a fixed width ``max_seq_len`` and whose valid prefix length is
284+
given per batch by ``nonpad_kv_seqlen``. It reuses the same masking rules
285+
(causal, sliding window, Gemma4 bidirectional block overlay, padding), only
286+
re-keyed onto the static-cache geometry:
287+
288+
* **KV axis width** is ``max_seq_len`` (every cache slot), not the running
289+
``total_length``.
290+
* **KV positions** are dense slot ids ``0 .. max_seq_len - 1`` (the absolute
291+
cache position each slot holds), so the causal/sliding comparisons use
292+
absolute positions directly instead of cumsum indices.
293+
* **Q positions** are absolute: ``write_indices[b] + arange(S_q)`` — the
294+
cache slots the current chunk is being scattered into.
295+
* **KV validity** is ``slot < nonpad_kv_seqlen[b]`` (replaces the cumsum
296+
padding term): a slot is real iff it lies inside the valid prefix.
297+
298+
The result is meant to be passed as the ``attn_mask`` of the static-cache
299+
``Attention`` op with ``is_causal=0`` (see
300+
:func:`~mobius.components._attention._apply_attention`).
301+
302+
Args:
303+
op: The OpBuilder.
304+
write_indices: ``[B]`` int64 start slot per batch (where the current
305+
chunk is scattered — the same tensor fed to ``TensorScatter``).
306+
seq_len: 1-D ``[1]`` int64 tensor holding the query-chunk length ``S_q``
307+
(e.g. ``op.Shape(input_ids, start=1, end=2)``); squeezed to a scalar
308+
internally.
309+
nonpad_kv_seqlen: ``[B]`` int64 count of valid cache slots *after* the
310+
current chunk is scattered. The cross-repo invariant is
311+
``nonpad_kv_seqlen == write_indices + valid_token_count``, where
312+
``valid_token_count`` is the number of *unpadded* query tokens in the
313+
chunk. This equals ``write_indices + S_q`` only when the chunk is
314+
**unpadded** (``S_q`` is the padded chunk width). With intra-prompt
315+
padding plus a sliding window, pad-token query rows can fall outside
316+
every valid slot and become fully masked — see the fully-masked-row
317+
behavior note in ``_apply_attention``.
318+
max_seq_len: Static width of the pre-allocated cache KV axis.
319+
sliding_window: Optional local-attention window; when set, a query at
320+
absolute position ``q`` attends slot ``k`` only if ``q - k < w``.
321+
block_sequence_ids: Optional ``[B, S_q]`` int64 block id per *current*
322+
query position (``>= 0`` for vision tokens sharing a block, ``-1``
323+
for text). When set, a bidirectional overlay is OR-ed onto the
324+
causal/sliding mask: two positions in the same block may attend to
325+
each other regardless of causal order — mirroring HuggingFace
326+
``blockwise_overlay`` for Gemma4. The per-slot KV block ids are
327+
built by scattering ``block_sequence_ids`` into a ``-1``-filled
328+
``[B, max_seq_len]`` buffer at ``write_indices`` (the same scatter
329+
geometry as K/V), so within a single forward only the current
330+
chunk's block ids participate; cross-step persistence of past block
331+
ids is a caller concern (out of scope for this primitive).
332+
dtype: Output dtype; masked entries use ``dtype.min``.
333+
334+
Returns:
335+
Additive bias of shape ``(B, 1, S_q, max_seq_len)``: ``0`` where the
336+
query may attend the slot, ``dtype.min`` where masked.
337+
"""
338+
zero_scalar = op.Constant(value_int=0)
339+
one_scalar = op.Constant(value_int=1)
340+
341+
# Q absolute positions: write_indices[b] + arange(S_q) -> (B, S_q, 1).
342+
seq_scalar = op.Squeeze(seq_len, op.Constant(value_ints=[0]))
343+
q_offsets = op.Range(zero_scalar, seq_scalar, one_scalar) # (S_q,)
344+
q_abs_2d = op.Add(
345+
op.Unsqueeze(write_indices, [1]), # (B, 1)
346+
op.Unsqueeze(q_offsets, [0]), # (1, S_q)
347+
) # (B, S_q)
348+
q_abs = op.Unsqueeze(q_abs_2d, [2]) # (B, S_q, 1)
349+
350+
# KV positions: dense cache slot ids 0 .. max_seq_len - 1 -> (max_seq_len,).
351+
kv_slots = op.Range(
352+
zero_scalar, op.Constant(value_int=max_seq_len), one_scalar
353+
) # (max_seq_len,)
354+
355+
# Causal: a query at absolute position q may attend slot k iff q >= k.
356+
# Broadcasting (B, S_q, 1) >= (max_seq_len,) -> (B, S_q, max_seq_len).
357+
full_mask = op.GreaterOrEqual(q_abs, kv_slots)
358+
359+
if sliding_window is not None:
360+
# Local window: keep slots within `sliding_window` of the query.
361+
dist = op.Sub(q_abs, kv_slots) # (B, S_q, max_seq_len)
362+
within_window = op.Less(dist, op.Constant(value_int=sliding_window))
363+
full_mask = op.And(full_mask, within_window)
364+
365+
if block_sequence_ids is not None:
366+
# Bidirectional vision-block overlay (OR-ed BEFORE the padding AND,
367+
# matching create_attention_bias / HF blockwise_overlay ordering).
368+
#
369+
# q_group: block id per current query position -> (B, S_q, 1).
370+
q_group = op.Unsqueeze(block_sequence_ids, [2]) # (B, S_q, 1)
371+
# kv_group: block id per cache slot -> (B, 1, max_seq_len). Built by
372+
# scattering the current chunk's block ids into a -1 buffer at
373+
# write_indices, exactly as K/V are scattered into the cache.
374+
batch_dim = op.Shape(write_indices, start=0, end=1) # (1,) == [B]
375+
cache_shape = op.Concat(
376+
batch_dim, op.Constant(value_ints=[max_seq_len]), axis=0
377+
) # (2,) == [B, max_seq_len]
378+
neg1_buffer = op.ConstantOfShape(
379+
cache_shape, value=ir.tensor(np.array([-1], dtype=np.int64))
380+
) # (B, max_seq_len) of -1
381+
kv_group_2d = op.TensorScatter(
382+
neg1_buffer, block_sequence_ids, write_indices, axis=1
383+
) # (B, max_seq_len)
384+
kv_group = op.Unsqueeze(kv_group_2d, [1]) # (B, 1, max_seq_len)
385+
same_block = op.And(
386+
op.Equal(q_group, kv_group),
387+
op.GreaterOrEqual(q_group, op.Constant(value_int=0)),
388+
)
389+
full_mask = op.Or(full_mask, same_block)
390+
391+
# KV validity (padding): a slot is real iff it lies inside the valid
392+
# prefix, slot < nonpad_kv_seqlen[b]. Broadcasting (max_seq_len,) <
393+
# (B, 1) -> (B, max_seq_len) -> (B, 1, max_seq_len).
394+
valid_kv = op.Less(kv_slots, op.Unsqueeze(nonpad_kv_seqlen, [1]))
395+
valid_kv = op.Unsqueeze(valid_kv, [1]) # (B, 1, max_seq_len)
396+
full_mask = op.And(full_mask, valid_kv)
397+
398+
# Convert to float bias: 0 where attended, dtype.min where masked.
399+
mask_value = float(dtype.min)
400+
attention_bias = op.Where(full_mask, 0.0, mask_value) # (B, S_q, max_seq_len)
401+
attention_bias = op.Cast(attention_bias, to=dtype)
402+
403+
# Unsqueeze to (B, 1, S_q, max_seq_len).
404+
return op.Unsqueeze(attention_bias, [1])
405+
406+
267407
def build_packed_token_offset(op: OpBuilder, cu_seqlens) -> ir.Value:
268408
"""Build ``token_offset`` for ``com.microsoft::PackedMultiHeadAttention``.
269409

0 commit comments

Comments
 (0)