Skip to content

Commit 73dc483

Browse files
justinchubyCopilot
andcommitted
Fix EP-capability gating bypass in DeepSeek-V4 GQA fusion
The previous commit (d2d5596) unconditionally emitted com.microsoft::GroupQueryAttention regardless of the target execution provider, bypassing this codebase's established EP-capability gating convention. mobius/_execution_providers.py deliberately declares gqa_dtypes=frozenset() for "default" (used whenever no execution_provider kwarg is passed -- essentially all existing tests and consumers), "onnx-standard", "qnn", and "openvino" specifically to guarantee their exported graphs stay free of com.microsoft custom ops. Since build_from_module defaults to execution_provider="default", the prior commit silently broke that portability contract for every default-EP DeepSeek-V4 build. Add _use_fused_gqa(), mirroring TextModel.forward's use_gqa gate (mobius/models/base.py) via ep_capabilities()/get_build_dtype(), and branch DeepSeekV4Attention.forward between the fused GroupQueryAttention path (unchanged from d2d5596, used only when the active EP declares GQA support for the build dtype) and a restored portable decomposed path (manual Transpose/Concat/MatMul/Softmax + explicit attention_bias + attention-sink Concat/slice, byte-identical to the pre-fusion implementation). seqlens_k/total_seq_len (fused) and attention_bias (decomposed) are threaded through DeepSeekV4DecoderLayer.forward, DeepSeekV4TextModel.forward, and DeepSeekV4Mtp.forward, with exactly one of the two computed per build based on _use_fused_gqa(). V4's gate omits base.py's caps.supports_fused_rope check: RoPE is always applied explicitly in-graph via _rotate in both paths (do_rotary stays at its default/off), so there's no fused-rotary mode being requested that could be EP-unsupported. Test changes in deepseek_v4_flash_test.py: - test_tiny_graph_builds_v4_backbone, test_csa_schedule_exports_compressor_and_indexer_tensors_with_dense_attention, and test_mtp_sidecar_exports_official_block_and_hyper_connection_state now assert GroupQueryAttention count == 0 under the default EP (in addition to their original decomposed-path assertions), proving the portability contract holds. - Three new tests build the same tiny configs with execution_provider="cpu" (whose gqa_dtypes={FLOAT} matches the tiny config's default dtype) and assert the fused-GQA structural properties previously (incorrectly) asserted unconditionally: node count == num_hidden_layers, com.microsoft domain, 12-input arity with attention_bias unset and head_sink populated, and halved Softmax count (only the Hyper-Connection combination softmax remains). Reviewed independently via a code-review sub-agent (verdict: APPROVE), which byte-diffed both branches against the pre-fusion and prior-commit implementations and confirmed plumbing/argument-order consistency and that the new EP-gated tests genuinely exercise the fused path. All 14 tests in deepseek_v4_flash_test.py pass; ruff check/format clean. Co-authored-by: Copilot <[email protected]>
1 parent d2d5596 commit 73dc483

2 files changed

Lines changed: 267 additions & 61 deletions

File tree

‎src/mobius/models/deepseek_v4.py‎

Lines changed: 187 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import torch
2424
from onnxscript import OpBuilder, nn
2525

26+
from mobius._build_context import ep_capabilities, get_build_dtype
2627
from mobius._configs import ArchitectureConfig
2728
from mobius._weight_utils import (
2829
pack_qmoe_expert_weights,
@@ -35,6 +36,7 @@
3536
MoELayer,
3637
QuantizedEmbedding,
3738
RMSNorm,
39+
create_attention_bias,
3840
initialize_rope,
3941
make_quantized_linear_factory,
4042
)
@@ -45,17 +47,24 @@
4547
logger = logging.getLogger(__name__)
4648

4749

48-
def _projection_class(config: ArchitectureConfig):
49-
quantization = config.quantization
50-
if quantization is None or quantization.quant_method == "none":
51-
return Linear
52-
zero_point_dtype = config.dtype if quantization.float_zero_point else ir.DataType.UINT8
53-
return make_quantized_linear_factory(
54-
bits=quantization.bits,
55-
block_size=quantization.group_size,
56-
has_zero_point=not quantization.sym,
57-
zero_point_dtype=zero_point_dtype,
58-
)
50+
def _use_fused_gqa() -> bool:
51+
"""Whether the active EP/build dtype supports direct ``GroupQueryAttention`` emission.
52+
53+
Mirrors ``TextModel.forward``'s ``use_gqa`` gate (``mobius/models/base.py``):
54+
the active EP must declare GQA support for the current build dtype via
55+
:func:`~mobius._build_context.ep_capabilities`. Unlike that generic path,
56+
V4 always applies RoPE explicitly in-graph (``do_rotary=0``), so this
57+
doesn't also need to check ``caps.supports_fused_rope`` -- V4's fused path
58+
never asks ``GroupQueryAttention`` to rotate internally.
59+
60+
EPs such as ``"default"``, ``"onnx-standard"``, ``"qnn"``, and
61+
``"openvino"`` declare an empty ``gqa_dtypes`` specifically so their
62+
exported graphs stay free of ``com.microsoft`` ops; V4 must fall back to
63+
the portable decomposed attention path for those, exactly like every
64+
other model in this codebase.
65+
"""
66+
caps = ep_capabilities()
67+
return get_build_dtype() in caps.gqa_dtypes
5968

6069

6170
def _gqa_kv_lengths(op: OpBuilder, attention_mask: ir.Value) -> tuple[ir.Value, ir.Value]:
@@ -81,6 +90,19 @@ def _gqa_kv_lengths(op: OpBuilder, attention_mask: ir.Value) -> tuple[ir.Value,
8190
return seqlens_k, total_seq_len
8291

8392

93+
def _projection_class(config: ArchitectureConfig):
94+
quantization = config.quantization
95+
if quantization is None or quantization.quant_method == "none":
96+
return Linear
97+
zero_point_dtype = config.dtype if quantization.float_zero_point else ir.DataType.UINT8
98+
return make_quantized_linear_factory(
99+
bits=quantization.bits,
100+
block_size=quantization.group_size,
101+
has_zero_point=not quantization.sym,
102+
zero_point_dtype=zero_point_dtype,
103+
)
104+
105+
84106
def _shape_anchor(op: OpBuilder, parameters: list[ir.Value]) -> ir.Value:
85107
"""Reference one element of each deferred-runtime tensor and produce zero."""
86108
total = None
@@ -461,12 +483,49 @@ def _rotate(
461483
rope = op.Reshape(rope, [0, 0, num_heads, self.rope_dim])
462484
return op.Reshape(op.Concat(nope, rope, axis=-1), [0, 0, -1])
463485

486+
def _expand_kv(
487+
self,
488+
op: OpBuilder,
489+
value: ir.Value,
490+
batch: ir.Value,
491+
sequence_length: ir.Value,
492+
) -> ir.Value:
493+
"""Broadcast the single MQA key/value head across all query heads.
494+
495+
Only used by the portable decomposed path below (EPs whose
496+
``gqa_dtypes`` is empty). The fused ``GroupQueryAttention`` path does
497+
this broadcast internally via its own ``kv_num_heads=1`` handling, so
498+
it never calls this helper.
499+
"""
500+
value = op.Unsqueeze(value, [2])
501+
value = op.Expand(
502+
value,
503+
op.Concat(
504+
batch,
505+
[1, self.num_heads],
506+
sequence_length,
507+
[self.head_dim],
508+
axis=0,
509+
),
510+
)
511+
return op.Reshape(
512+
value,
513+
op.Concat(
514+
batch,
515+
[self.num_heads],
516+
sequence_length,
517+
[self.head_dim],
518+
axis=0,
519+
),
520+
)
521+
464522
def forward(
465523
self,
466524
op: OpBuilder,
467525
hidden_states: ir.Value,
468526
position_embeddings: tuple,
469527
past_key_value: tuple | None = None,
528+
attention_bias: ir.Value | None = None,
470529
seqlens_k: ir.Value | None = None,
471530
total_seq_len: ir.Value | None = None,
472531
):
@@ -484,51 +543,97 @@ def forward(
484543
kv = self.kv_layernorm(op, self.kv_proj(op, hidden_states))
485544
kv = self._rotate(op, kv, position_embeddings, 1)
486545

487-
past_key = past_key_value[0] if past_key_value is not None else None
488-
past_value = past_key_value[1] if past_key_value is not None else None
489-
490-
# Fused causal attention core. `query`/`kv` are already RoPE-rotated
491-
# (trailing rope slice only, applied explicitly above via `_rotate`,
492-
# the same convention V2/V3 MLA uses with the plain `Attention` op),
493-
# so `GroupQueryAttention` only needs `do_rotary=0` (its default):
494-
# cos_cache/sin_cache/position_ids stay unset. V4 is MQA
495-
# (`kv_num_heads=1`): key and value are literally the same rotated
496-
# `kv` tensor, exactly matching the removed manual `value = key`
497-
# assignment and its `_expand_kv` broadcast (now redundant --
498-
# broadcasting kv_num_heads=1 across all query heads is the fused
499-
# op's own job). No explicit `attention_bias` is passed: this is a
500-
# plain causal decoder attention (no sliding window, no KV-sharing
501-
# across layers, no per-layer dual head_dim), so GQA's own implicit
502-
# causal masking plus `seqlens_k`/`total_seq_len` already carries
503-
# the exact same causal+padding semantics `create_attention_bias`
504-
# used to bake into an explicit float bias -- this is the same
505-
# "direct GQA" convention `Attention._forward_gqa`
506-
# (mobius/components/_attention.py) already uses for every other
507-
# simple-causal model in this codebase (see the
508-
# `attention-optimization` skill: "Use Contrib GQA when you don't
509-
# need attention bias"). `head_sink` carries the learned per-head
510-
# attention sink exactly as the removed
511-
# `Concat(scores, sinks) -> Softmax -> slice` sequence did, now as
512-
# a first-class op input instead of a manually broadcast Concat.
513-
output, present_key, present_value = op.GroupQueryAttention(
514-
query,
515-
kv,
516-
kv,
517-
past_key,
518-
past_value,
519-
seqlens_k,
520-
total_seq_len,
521-
None, # cos_cache: unused, RoPE already applied above
522-
None, # sin_cache: unused, RoPE already applied above
523-
None, # position_ids: unused, do_rotary=0
524-
None, # attention_bias: unused, plain causal + seqlens_k suffices
525-
op.CastLike(self.attn_sink, query), # head_sink
526-
num_heads=self.num_heads,
527-
kv_num_heads=1,
528-
scale=self.scale,
529-
_domain="com.microsoft",
530-
_outputs=3,
531-
)
546+
if seqlens_k is not None:
547+
# Fused causal attention core, used only when the active EP's
548+
# `ep_capabilities().gqa_dtypes` includes the build dtype (see
549+
# `_use_fused_gqa`). `query`/`kv` are already RoPE-rotated
550+
# (trailing rope slice only, applied explicitly above via
551+
# `_rotate`, the same convention V2/V3 MLA uses with the plain
552+
# `Attention` op), so `GroupQueryAttention` only needs
553+
# `do_rotary=0` (its default): cos_cache/sin_cache/position_ids
554+
# stay unset. V4 is MQA (`kv_num_heads=1`): key and value are
555+
# literally the same rotated `kv` tensor -- broadcasting
556+
# `kv_num_heads=1` across all query heads is the fused op's own
557+
# job, so `_expand_kv` isn't needed on this path. No explicit
558+
# `attention_bias` is passed: this is a plain causal decoder
559+
# attention (no sliding window, no KV-sharing across layers, no
560+
# per-layer dual head_dim), so GQA's own implicit causal masking
561+
# plus `seqlens_k`/`total_seq_len` already carries the exact same
562+
# causal+padding semantics `create_attention_bias` bakes into an
563+
# explicit float bias on the decomposed path below -- this is the
564+
# same "direct GQA" convention `Attention._forward_gqa`
565+
# (mobius/components/_attention.py) already uses for every other
566+
# simple-causal model in this codebase (see the
567+
# `attention-optimization` skill: "Use Contrib GQA when you don't
568+
# need attention bias"). `head_sink` carries the learned per-head
569+
# attention sink exactly as the decomposed path's
570+
# `Concat(scores, sinks) -> Softmax -> slice` sequence does, now
571+
# as a first-class op input instead of a manually broadcast
572+
# Concat.
573+
past_key = past_key_value[0] if past_key_value is not None else None
574+
past_value = past_key_value[1] if past_key_value is not None else None
575+
output, present_key, present_value = op.GroupQueryAttention(
576+
query,
577+
kv,
578+
kv,
579+
past_key,
580+
past_value,
581+
seqlens_k,
582+
total_seq_len,
583+
None, # cos_cache: unused, RoPE already applied above
584+
None, # sin_cache: unused, RoPE already applied above
585+
None, # position_ids: unused, do_rotary=0
586+
None, # attention_bias: unused, plain causal + seqlens_k suffices
587+
op.CastLike(self.attn_sink, query), # head_sink
588+
num_heads=self.num_heads,
589+
kv_num_heads=1,
590+
scale=self.scale,
591+
_domain="com.microsoft",
592+
_outputs=3,
593+
)
594+
else:
595+
# Portable decomposed path: used whenever the active EP declares
596+
# no GQA support for the build dtype (e.g. `"default"`,
597+
# `"onnx-standard"`, `"qnn"`, `"openvino"` -- see
598+
# `_use_fused_gqa`). Manually replicates the exact same
599+
# sink-aware dense causal attention using only standard ONNX
600+
# ops, so these EPs' exported graphs stay free of
601+
# `com.microsoft` custom ops.
602+
batch = op.Shape(query, start=0, end=1)
603+
query_length = op.Shape(query, start=1, end=2)
604+
query = op.Transpose(
605+
op.Reshape(query, [0, 0, self.num_heads, self.head_dim]),
606+
perm=[0, 2, 1, 3],
607+
)
608+
key = op.Transpose(op.Reshape(kv, [0, 0, 1, self.head_dim]), perm=[0, 2, 1, 3])
609+
value = key
610+
if past_key_value is not None:
611+
key = op.Concat(past_key_value[0], key, axis=2)
612+
value = op.Concat(past_key_value[1], value, axis=2)
613+
present_key, present_value = key, value
614+
615+
kv_length = op.Shape(key, start=2, end=3)
616+
key = self._expand_kv(op, key, batch, kv_length)
617+
value = self._expand_kv(op, value, batch, kv_length)
618+
scores = op.Mul(
619+
op.MatMul(query, op.Transpose(key, perm=[0, 1, 3, 2])),
620+
self.scale,
621+
)
622+
scores = op.Add(scores, attention_bias)
623+
sinks = op.Expand(
624+
op.Reshape(
625+
op.CastLike(self.attn_sink, scores),
626+
[1, self.num_heads, 1, 1],
627+
),
628+
op.Concat(batch, [self.num_heads], query_length, [1], axis=0),
629+
)
630+
probabilities = op.Softmax(op.Concat(scores, sinks, axis=-1), axis=-1)
631+
probabilities = op.Slice(probabilities, [0], [-1], [3])
632+
output = op.Reshape(
633+
op.Transpose(op.MatMul(probabilities, value), perm=[0, 2, 1, 3]),
634+
[0, 0, -1],
635+
)
636+
532637
output = self._rotate(op, output, position_embeddings, self.num_heads, inverse=True)
533638

534639
if self.compressor is not None:
@@ -638,6 +743,7 @@ def forward(
638743
input_ids: ir.Value,
639744
position_embeddings: tuple,
640745
past_key_value: tuple | None = None,
746+
attention_bias: ir.Value | None = None,
641747
seqlens_k: ir.Value | None = None,
642748
total_seq_len: ir.Value | None = None,
643749
):
@@ -654,6 +760,7 @@ def forward(
654760
self.input_layernorm(op, value),
655761
position_embeddings,
656762
past_key_value,
763+
attention_bias,
657764
seqlens_k,
658765
total_seq_len,
659766
)
@@ -750,7 +857,17 @@ def forward(
750857
)
751858
position_embeddings = self.rotary_emb(op, position_ids)
752859
compressed_position_embeddings = self.compressed_rotary_emb(op, position_ids)
753-
seqlens_k, total_seq_len = _gqa_kv_lengths(op, attention_mask)
860+
if _use_fused_gqa():
861+
attention_bias = None
862+
seqlens_k, total_seq_len = _gqa_kv_lengths(op, attention_mask)
863+
else:
864+
attention_bias = create_attention_bias(
865+
op,
866+
input_ids=hidden_states if input_ids is None else input_ids,
867+
attention_mask=attention_mask,
868+
dtype=self._dtype,
869+
)
870+
seqlens_k, total_seq_len = None, None
754871
presents = []
755872
past_kvs = past_key_values or [None] * len(self.layers)
756873
for layer, past_kv in zip(self.layers, past_kvs):
@@ -765,6 +882,7 @@ def forward(
765882
input_ids,
766883
layer_position_embeddings,
767884
past_kv,
885+
attention_bias,
768886
seqlens_k,
769887
total_seq_len,
770888
)
@@ -824,13 +942,24 @@ def forward(
824942
self.h_proj(op, self.hnorm(op, hidden_states)),
825943
)
826944
position_embeddings = self.rotary_emb(op, position_ids)
827-
seqlens_k, total_seq_len = _gqa_kv_lengths(op, attention_mask)
945+
if _use_fused_gqa():
946+
attention_bias = None
947+
seqlens_k, total_seq_len = _gqa_kv_lengths(op, attention_mask)
948+
else:
949+
attention_bias = create_attention_bias(
950+
op,
951+
input_ids=inputs_embeds,
952+
attention_mask=attention_mask,
953+
dtype=self._dtype,
954+
)
955+
seqlens_k, total_seq_len = None, None
828956
hidden_states, present = super().forward(
829957
op,
830958
hidden_states,
831959
None,
832960
position_embeddings,
833961
past_key_value,
962+
attention_bias,
834963
seqlens_k,
835964
total_seq_len,
836965
)

0 commit comments

Comments
 (0)