Skip to content

Commit 41d2641

Browse files
apsonawaneCopilot
andauthored
Enable GQA for KV-shared layers and fix dtype issues in vision and audio (#279)
## [Gemma4] Enable GQA for KV-shared layers, fix vision encoder dtype, fix audio SkipNorm fusion ### Summary Four changes to enable optimized Gemma4 multimodal inference: 1. **GQA for KV-shared layers** — use `GroupQueryAttention` instead of standard `Attention` for the 20 KV-shared decoder layers 2. **Vision encoder float32 input** — accept float32 `pixel_values` and cast inside the model to prevent NaN 3. **Audio encoder SkipNorm fix** — prevent incorrect fusion of `Add(MatMul, 1D_bias) + RMSNorm` 4. **Enable `past_present_share_buffer`** — avoid per-step KV cache allocation --- ### 1. GQA for KV-shared layers (`gemma4.py`) KV-shared layers borrow K/V from a source layer's `present_key`/`present_value` (already in BNSH format). Instead of Transpose+Reshape into BSNH for the standard `Attention` op, we now pass: - Empty K/V tensors `[B, 0, kv_hidden]` (`kv_sequence_length=0`) - Source layer's present K/V directly as `past_key`/`past_value` This eliminates Transpose+Reshape ops from the graph for all 20 shared layers and uses the optimized GQA flash attention kernel. Requires corresponding ORT changes to support `kv_sequence_length=0` (separate ORT PR). **Decoder loop change:** All layers (shared and non-shared) now receive GQA context when the EP supports it. The previous `is_shared` exclusion and fallback attention bias/position embedding generation for shared layers are removed. ### 2. Vision encoder float32 input (`_gemma4.py`) **Problem:** The image processor in ORT-GenAI outputs float32 `pixel_values`, but the vision encoder declared its input as `config.dtype` (float16). The ORT-GenAI trimming path did a raw `memcpy` from float32 source into an fp16 tensor using fp16 strides — reinterpreting float32 bit patterns as fp16, producing NaN. **Fix:** Declare `pixel_values` as `ir.DataType.FLOAT` and add `op.Cast(pixel_values, to=config.dtype)` inside the ONNX model when needed. This keeps the host-side pipeline in float32 and lets the model handle the precision conversion safely. ### 3. Audio encoder SkipNorm fix (`_skip_norm.py`) **Problem:** The `AddRMSNormToSkipNorm` rewrite rule fused `Add(MatMul_result, 1D_bias) + RMSNorm` into `SkipSimplifiedLayerNormalization`. The 1D bias `[hidden]` became the `skip` input, but the op requires both inputs to have the same shape (`[B, S, hidden]`). This caused: - CPU: `skip is expected to have 3 or 2 dimensions, got 1` - CUDA: `input and skip shall have same shape when enable_skip_layer_norm_strict_mode is True` **Fix:** Add a rank equality check in the `check()` method. Fusion is skipped when the two Add inputs have different ranks (e.g., 3D tensor + 1D bias via broadcasting). ### 4. Enable `past_present_share_buffer` (`genai_config.py`) Set `past_present_share_buffer` to `true` by default for all EPs. This pre-allocates KV cache buffers and aliases past/present pointers, avoiding per-step allocation and past→present copies. --- ### Testing | Scenario | Status | |----------|--------| | Text-only generation (CPU) | ✅ | | Text-only generation (CUDA) | ✅ | | Multimodal image+text (CPU) | ✅ Clean output, no repetition | | Multimodal image+text (CUDA) | ✅ Clean output, no crashes | | Model graph | ✅ 35 GQA nodes (15 source + 20 shared), 0 Attention nodes | --------- Co-authored-by: Copilot <[email protected]>
1 parent fdf2c2e commit 41d2641

4 files changed

Lines changed: 98 additions & 93 deletions

File tree

‎src/mobius/_flags.py‎

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -84,11 +84,6 @@ class _Flags:
8484
- ``False``
8585
- Lower the ONNX opset declaration to 23 for non-CPU EPs
8686
(ORT ≤1.24.x workaround). Disabled by default.
87-
* - ``use_gqa_for_kv_shared``
88-
- ``MOBIUS_USE_GQA_FOR_KV_SHARED``
89-
- ``False``
90-
- Use GQA for KV-shared layers on CUDA EP. Requires ORT GQA
91-
new_kv_length=0 support.
9287
"""
9388

9489
suppress_dedup_warning: bool = dataclasses.field(
@@ -108,22 +103,6 @@ class _Flags:
108103
Set ``MOBIUS_ORT_CUDA_GROUPED_RMSNORM_WORKAROUND=1`` when targeting CUDA.
109104
"""
110105

111-
use_gqa_for_kv_shared: bool = dataclasses.field(
112-
default_factory=lambda: _env_bool("MOBIUS_USE_GQA_FOR_KV_SHARED", False)
113-
)
114-
"""Use GroupQueryAttention for KV-shared layers on CUDA EP.
115-
116-
When ``False`` (default), KV-shared layers that borrow K/V from a
117-
source layer use standard ONNX Attention (which falls back to unfused
118-
attention on CUDA EP). This avoids a CUTLASS MEA crash with the
119-
aligned kernel for certain sequence lengths when ``past_key`` is
120-
``nullptr``.
121-
122-
Set ``MOBIUS_USE_GQA_FOR_KV_SHARED=1`` when the ORT GQA kernel
123-
supports ``new_kv_length=0`` (KV-shared pattern), which will enable
124-
fused attention for these layers.
125-
"""
126-
127106
ort_lower_opset_for_ep: bool = dataclasses.field(
128107
default_factory=lambda: _env_bool("MOBIUS_ORT_LOWER_OPSET_FOR_EP", False)
129108
)

‎src/mobius/integrations/ort_genai/auto_export.py‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -655,14 +655,6 @@ def _write_genai_config(
655655
**audio_kwargs,
656656
)
657657

658-
# Disable past_present_share_buffer for models with dual head_dim
659-
# (e.g., different head_dim for sliding vs full-attention layers).
660-
# Shared buffers require uniform head_dim across all KV cache layers.
661-
global_head_dim = getattr(config, "global_head_dim", None)
662-
head_dim = getattr(config, "head_dim", None)
663-
if global_head_dim and head_dim and global_head_dim != head_dim:
664-
generator._search_overrides["past_present_share_buffer"] = False
665-
666658
return generator.write(output_dir)
667659

668660

‎src/mobius/models/gemma4.py‎

Lines changed: 83 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@
3535

3636
from mobius._build_context import ep_capabilities
3737
from mobius._configs import ArchitectureConfig, Gemma4Config
38-
from mobius._flags import flags
3938
from mobius._weight_utils import vlm_decoder_weights, vlm_embedding_weights
4039
from mobius.components import (
4140
MLP,
@@ -736,41 +735,79 @@ def forward(
736735
)
737736

738737
if self.is_kv_shared_layer:
739-
# KV-shared layers always use standard Attention path because
740-
# they borrow K,V from a source layer (no own KV cache).
741-
if use_gqa:
742-
raise ValueError(
743-
"KV-shared GQA path not yet implemented. "
744-
"Set MOBIUS_USE_GQA_FOR_KV_SHARED=0 or wait for "
745-
"ORT GQA new_kv_length=0 support."
746-
)
747-
# Borrow full-history K,V from source layer.
748-
# present_key/value from the ONNX Attention op is 4D:
749-
# [batch, kv_heads, total_seq, head_dim]
750-
# The Attention op expects key/value as 3D:
751-
# [batch, total_seq, kv_heads * head_dim]
752-
# Transpose and reshape to match.
738+
# KV-shared layers borrow K,V from a source layer (no own KV cache).
753739
src_key, src_value = shared_kv_states[self.kv_shared_layer_index]
754740

755-
# [B, kv_heads, total_seq, head_dim] → [B, total_seq, kv_heads*head_dim]
756-
src_key = op.Transpose(src_key, perm=[0, 2, 1, 3])
757-
src_key = op.Reshape(src_key, [0, 0, -1])
758-
src_value = op.Transpose(src_value, perm=[0, 2, 1, 3])
759-
src_value = op.Reshape(src_value, [0, 0, -1])
760-
761-
attn_output, present_key, present_value = _apply_attention(
762-
op,
763-
query_states,
764-
src_key,
765-
src_value,
766-
attention_bias,
767-
past_key=None,
768-
past_value=None,
769-
num_attention_heads=self.num_attention_heads,
770-
num_key_value_heads=self.num_key_value_heads,
771-
scale=self.scaling,
772-
softcap=self.softcap,
773-
)
741+
if use_gqa:
742+
# GQA path for shared KV: pass empty K/V tensors and wire the
743+
# source layer's present_key/value as past_key/past_value.
744+
# The shared buffer is already in BNSH format, so GQA reads it
745+
# directly — no Transpose/Reshape needed.
746+
gqa_ctx = attention_bias
747+
748+
# Create empty K/V tensors with kv_sequence_length=0.
749+
# Shape: [batch, 0, kv_heads * head_dim]
750+
batch_dim = op.Shape(query_states, start=0, end=1)
751+
kv_hidden = self.num_key_value_heads * self.head_dim
752+
empty_shape = op.Concat(
753+
batch_dim,
754+
op.Constant(value_ints=[0, kv_hidden]),
755+
axis=0,
756+
)
757+
empty_kv = op.CastLike(op.ConstantOfShape(empty_shape), query_states)
758+
759+
gqa_attrs: dict = {
760+
"num_heads": self.num_attention_heads,
761+
"kv_num_heads": self.num_key_value_heads,
762+
"scale": self.scaling,
763+
"do_rotary": 1,
764+
"rotary_interleaved": int(self._rope_interleave),
765+
}
766+
if self.softcap:
767+
gqa_attrs["softcap"] = self.softcap
768+
if self.rotary_embedding_dim:
769+
gqa_attrs["rotary_embedding_dim"] = self.rotary_embedding_dim
770+
if gqa_ctx.local_window_size > 0:
771+
gqa_attrs["local_window_size"] = gqa_ctx.local_window_size
772+
773+
attn_output, present_key, present_value = op.GroupQueryAttention(
774+
query_states,
775+
empty_kv, # key: empty (kv_sequence_length=0)
776+
empty_kv, # value: empty (kv_sequence_length=0)
777+
src_key, # past_key: shared KV in BNSH
778+
src_value, # past_value: shared KV in BNSH
779+
gqa_ctx.seqlens_k,
780+
gqa_ctx.total_seq_len,
781+
gqa_ctx.cos_cache,
782+
gqa_ctx.sin_cache,
783+
_domain="com.microsoft",
784+
_outputs=3,
785+
**gqa_attrs,
786+
)
787+
else:
788+
# Fallback Attention path: transpose shared KV from BNSH to 3D.
789+
# present_key/value from the ONNX Attention op is 4D:
790+
# [batch, kv_heads, total_seq, head_dim]
791+
# The Attention op expects key/value as 3D:
792+
# [batch, total_seq, kv_heads * head_dim]
793+
src_key = op.Transpose(src_key, perm=[0, 2, 1, 3])
794+
src_key = op.Reshape(src_key, [0, 0, -1])
795+
src_value = op.Transpose(src_value, perm=[0, 2, 1, 3])
796+
src_value = op.Reshape(src_value, [0, 0, -1])
797+
798+
attn_output, present_key, present_value = _apply_attention(
799+
op,
800+
query_states,
801+
src_key,
802+
src_value,
803+
attention_bias,
804+
past_key=None,
805+
past_value=None,
806+
num_attention_heads=self.num_attention_heads,
807+
num_key_value_heads=self.num_key_value_heads,
808+
scale=self.scaling,
809+
softcap=self.softcap,
810+
)
774811
elif use_gqa:
775812
# GQA path: emit com.microsoft.GroupQueryAttention directly.
776813
# The op fuses RoPE + attention + KV cache into a single op,
@@ -1477,11 +1514,12 @@ def forward(
14771514
)
14781515

14791516
if use_gqa:
1480-
# Realize cos/sin caches as ONNX graph initializers.
1481-
# The returned gathered embeddings are saved for potential reuse
1482-
# by KV-shared layers that fall back to standard Attention.
1483-
local_pos_emb = self.rotary_emb_local(op, position_ids)
1484-
global_pos_emb = self.rotary_emb_global(op, position_ids)
1517+
# Calling forward() on the RoPE modules materializes their
1518+
# cos_cache / sin_cache nn.Parameters as ONNX graph initializers.
1519+
# GQA references these caches directly; without the call the
1520+
# parameters are never emitted into the graph.
1521+
_ = self.rotary_emb_local(op, position_ids)
1522+
_ = self.rotary_emb_global(op, position_ids)
14851523

14861524
# seqlens_k[b] = sum(attention_mask[b]) - 1 (last valid KV idx)
14871525
# total_seq_len = attention_mask.shape[1] (past + current)
@@ -1525,18 +1563,11 @@ def forward(
15251563
"full_attention": self.rotary_emb_global(op, position_ids),
15261564
}
15271565

1528-
# Fallback attention bias for non-GQA layers (KV-shared layers use
1529-
# this when use_gqa_for_kv_shared is False, plus all layers when
1530-
# use_gqa is False).
1566+
# Fallback attention bias for non-GQA layers (used when use_gqa is False).
15311567
query_input = input_ids if input_ids is not None else hidden_states
15321568
fallback_bias_dict: dict[str, ir.Value | None] = {}
1533-
has_kv_shared = any(layer.self_attn.is_kv_shared_layer for layer in self.layers)
1534-
need_fallback = not use_gqa or (has_kv_shared and not flags.use_gqa_for_kv_shared)
1569+
need_fallback = not use_gqa
15351570
if need_fallback:
1536-
# All fallback layers use float additive bias masks encoding
1537-
# causal + sliding window + padding constraints. Float bias
1538-
# works with both unfused and MEA kernel paths on CUDA EP.
1539-
# Padding mask is required for batch > 1 correctness.
15401571
fallback_bias_dict = {
15411572
"sliding_attention": create_attention_bias(
15421573
op,
@@ -1552,16 +1583,7 @@ def forward(
15521583
dtype=self._dtype,
15531584
),
15541585
}
1555-
# KV-shared layers also need position embeddings for the
1556-
# standard Attention path (manual RoPE). Reuse the embeddings
1557-
# already gathered when realizing cos/sin caches above.
1558-
if use_gqa:
1559-
fallback_pos_dict = {
1560-
"sliding_attention": local_pos_emb,
1561-
"full_attention": global_pos_emb,
1562-
}
1563-
else:
1564-
fallback_pos_dict = position_embeddings_dict
1586+
fallback_pos_dict = position_embeddings_dict
15651587
else:
15661588
fallback_pos_dict = {}
15671589

@@ -1587,12 +1609,9 @@ def forward(
15871609
):
15881610
per_layer_input = per_layer_inputs[i] if per_layer_inputs is not None else None
15891611

1590-
# Per-layer decision: use GQA for non-shared layers when
1591-
# available, fall back to standard Attention for KV-shared
1592-
# layers (unless the use_gqa_for_kv_shared flag is set).
1593-
is_shared = layer.self_attn.is_kv_shared_layer
1594-
use_gqa_this_layer = use_gqa and (not is_shared or flags.use_gqa_for_kv_shared)
1595-
if use_gqa_this_layer:
1612+
# Per-layer decision: use GQA when available. KV-shared layers
1613+
# also use GQA (with empty K/V and shared past buffer).
1614+
if use_gqa:
15961615
attn_bias = gqa_ctx_dict[layer_type]
15971616
pos_emb = None
15981617
else:

‎src/mobius/rewrite_rules/_skip_norm.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,21 @@ def check(self, context, add_out, norm_out, **_):
6464
if producer is None or producer.op_type != "Add":
6565
return result.fail("Input to RMSNorm is not from an Add node")
6666

67+
# Both Add inputs must have the same rank (SkipSimplifiedLayerNormalization
68+
# requires input and skip to have the same shape). A rank mismatch
69+
# indicates broadcasting (e.g. Add(MatMul, bias) where bias is 1D).
70+
input_a = producer.inputs[0]
71+
input_b = producer.inputs[1]
72+
shape_a = input_a.shape
73+
shape_b = input_b.shape
74+
rank_a = len(shape_a) if shape_a is not None else None
75+
rank_b = len(shape_b) if shape_b is not None else None
76+
if rank_a is not None and rank_b is not None and rank_a != rank_b:
77+
return result.fail(
78+
f"Add inputs have different ranks ({rank_a} vs {rank_b}); "
79+
"SkipSimplifiedLayerNormalization requires same-shape inputs"
80+
)
81+
6782
# Don't fuse if add_out is itself a graph output — that indicates we're inside
6883
# an ONNX function body (e.g. SkipSimplifiedLayerNormalization_body) where
6984
# replace_all_uses_with would fail, or produce nested fusion.

0 commit comments

Comments
 (0)