Skip to content

Commit 068feef

Browse files
justinchubyCopilot
andcommitted
Unify packed token_offset helper and add CUDA golden build opt-in
Follow-ups from PR #358 review: - Make build_packed_token_offset materialise its axis/index tensors as explicit Constant nodes so it works under both the component OpBuilder and the onnxscript rewriter op. BlockDiagonalToPackedMHA.rewrite now calls the shared helper instead of duplicating the (previously copy-pasted) token_offset construction, keeping the rewrite rule and the vision encoders in sync. - Let the L4/L5 golden harness build an EP-specialized graph via the opt-in MOBIUS_TEST_BUILD_EP env var (default "default" leaves the portable build unchanged). Setting MOBIUS_TEST_BUILD_EP=cuda exercises the Qwen-VL PackedMultiHeadAttention path end-to-end; a build/runtime EP mismatch is rejected with a clear pytest.UsageError. Verified: the 3 Qwen-VL golden L4 cases pass with the CUDA-built packed graph. Co-authored-by: Copilot <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 8e7567d commit 068feef

3 files changed

Lines changed: 48 additions & 48 deletions

File tree

‎src/mobius/components/_common.py‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,15 @@ def build_packed_token_offset(op: OpBuilder, cu_seqlens) -> ir.Value:
292292
Returns:
293293
``(batch_size, max_seq_len)`` INT32 ``token_offset`` tensor.
294294
"""
295+
# Index/axis tensors are materialised as explicit Constant nodes (rather
296+
# than relying on Python-list auto-conversion) so this helper works under
297+
# both the component OpBuilder and the onnxscript rewriter op context.
298+
axes_0 = op.Constant(value_ints=[0])
299+
axes_1 = op.Constant(value_ints=[1])
300+
neg_one = op.Constant(value_ints=[-1])
301+
start_1 = op.Constant(value_ints=[1])
302+
int_max = op.Constant(value_ints=[INT64_MAX])
303+
295304
cu_seqlens_i32 = op.Cast(cu_seqlens, to=ir.DataType.INT32)
296305

297306
# batch_size = len(cu_seqlens) - 1 (number of packed sub-sequences).
@@ -301,26 +310,26 @@ def build_packed_token_offset(op: OpBuilder, cu_seqlens) -> ir.Value:
301310
)
302311

303312
# Per-sub-sequence lengths and the padded sequence dimension.
304-
starts = op.Slice(cu_seqlens_i32, [0], [-1], [0]) # cu[:-1]
305-
ends = op.Slice(cu_seqlens_i32, [1], [INT64_MAX], [0]) # cu[1:]
313+
starts = op.Slice(cu_seqlens_i32, axes_0, neg_one, axes_0) # cu[:-1]
314+
ends = op.Slice(cu_seqlens_i32, start_1, int_max, axes_0) # cu[1:]
306315
lengths = op.Sub(ends, starts) # (batch_size,)
307-
max_len = op.Squeeze(op.ReduceMax(lengths), [0]) # scalar INT32
316+
max_len = op.Squeeze(op.ReduceMax(lengths), axes_0) # scalar INT32
308317

309318
# Padded position grid: pos[b, s] = b * max_len + s.
310319
zero_i32 = op.Cast(op.Constant(value_int=0), to=ir.DataType.INT32)
311320
one_i32 = op.Cast(op.Constant(value_int=1), to=ir.DataType.INT32)
312321
rows = op.Range(zero_i32, batch_size, one_i32) # (batch_size,)
313322
cols = op.Range(zero_i32, max_len, one_i32) # (max_len,)
314323
pos_matrix = op.Add(
315-
op.Mul(op.Unsqueeze(rows, [1]), max_len),
316-
op.Unsqueeze(cols, [0]),
324+
op.Mul(op.Unsqueeze(rows, axes_1), max_len),
325+
op.Unsqueeze(cols, axes_0),
317326
) # (batch_size, max_len) INT32
318327
pos_matrix_shape = op.Shape(pos_matrix)
319328

320329
# Column s is a valid token for row b iff s < lengths[b].
321-
valid_mask = op.Less(op.Unsqueeze(cols, [0]), op.Unsqueeze(lengths, [1]))
322-
valid_mask_1d = op.Reshape(valid_mask, [-1])
323-
pos_1d = op.Reshape(pos_matrix, [-1])
330+
valid_mask = op.Less(op.Unsqueeze(cols, axes_0), op.Unsqueeze(lengths, axes_1))
331+
valid_mask_1d = op.Reshape(valid_mask, neg_one)
332+
pos_1d = op.Reshape(pos_matrix, neg_one)
324333

325334
# Valid positions first (packed order), then padding-slot positions.
326335
valid_indices = op.Compress(pos_1d, valid_mask_1d)

‎src/mobius/rewrite_rules/_packed_attention.py‎

Lines changed: 4 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
from onnxscript.rewriter._basics import MatchResult
2626
from onnxscript.rewriter._rewrite_rule import RewriteRuleClassBase, RewriteRuleSet
2727

28-
from mobius.components._common import INT64_MAX
28+
from mobius.components._common import build_packed_token_offset
2929

3030

3131
class BlockDiagonalToPackedMHA(RewriteRuleClassBase):
@@ -161,45 +161,9 @@ def rewrite(self, op, q, k, v, attn_bias_2d, attn_out, **_):
161161
cu_seqlens = self._trace_cu_seqlens(attn_bias_2d)
162162
cu_seqlens_i32 = op.Cast(cu_seqlens, to=6) # INT32
163163

164-
# Reusable constant tensors (rewrite context needs ir.Value, not lists)
165-
axes_0 = op.Constant(value_ints=[0])
166-
axes_1 = op.Constant(value_ints=[1])
167-
neg_one = op.Constant(value_ints=[-1])
168-
int_max = op.Constant(value_ints=[INT64_MAX])
169-
slice_start_0 = op.Constant(value_ints=[0])
170-
slice_start_1 = op.Constant(value_ints=[1])
171-
172-
# ---- token_offset computation ----
173-
# num_patches = len(cu_seqlens) - 1
174-
num_patches = op.Cast(
175-
op.Sub(op.Size(cu_seqlens), op.Constant(value_int=1)),
176-
to=6,
177-
)
178-
179-
# Sub-sequence lengths and maximum length
180-
starts = op.Slice(cu_seqlens_i32, slice_start_0, neg_one, axes_0)
181-
ends = op.Slice(cu_seqlens_i32, slice_start_1, int_max, axes_0)
182-
lengths = op.Sub(ends, starts)
183-
max_length = op.Squeeze(op.ReduceMax(lengths), axes_0)
184-
185-
# Position matrix (num_patches x max_length) in int32
186-
zero_i32 = op.Cast(op.Constant(value_int=0), to=6)
187-
one_i32 = op.Cast(op.Constant(value_int=1), to=6)
188-
rows = op.Range(zero_i32, num_patches, one_i32)
189-
cols = op.Range(zero_i32, max_length, one_i32)
190-
pos_matrix = op.Add(
191-
op.Mul(op.Unsqueeze(rows, axes_1), max_length),
192-
op.Unsqueeze(cols, axes_0),
193-
)
194-
pos_shape = op.Shape(pos_matrix)
195-
196-
# Build token_offset: valid positions first, then padding
197-
mask_2d = op.Less(op.Unsqueeze(cols, axes_0), op.Unsqueeze(lengths, axes_1))
198-
mask_1d = op.Reshape(mask_2d, neg_one)
199-
pos_1d = op.Reshape(pos_matrix, neg_one)
200-
valid = op.Compress(pos_1d, mask_1d)
201-
padded = op.Compress(pos_1d, op.Not(mask_1d))
202-
token_offset = op.Reshape(op.Concat(valid, padded, axis=0), pos_shape)
164+
# token_offset follows ORT's GetPaddingOffset convention; build it with
165+
# the shared helper so this rule and the vision encoders stay in sync.
166+
token_offset = build_packed_token_offset(op, cu_seqlens)
203167

204168
# com.microsoft::PackedMultiHeadAttention
205169
return op.op(

‎tests/e2e_golden_test.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@
1515
1616
# Run on CUDA GPU:
1717
MOBIUS_TEST_DEVICE=cuda pytest tests/e2e_golden_test.py -v
18+
19+
# Build a CUDA-specialized graph (e.g. PackedMultiHeadAttention for
20+
# Qwen-VL vision) and run it on CUDA:
21+
MOBIUS_TEST_DEVICE=cuda MOBIUS_TEST_BUILD_EP=cuda \
22+
pytest tests/e2e_golden_test.py -m golden -k "qwen2_5-vl-3b"
1823
"""
1924

2025
from __future__ import annotations
@@ -48,6 +53,27 @@
4853
_TESTDATA_DIR = Path(__file__).resolve().parent.parent / "testdata"
4954

5055

56+
def _get_test_build_ep() -> str:
57+
"""Return the ``execution_provider`` to build golden models with.
58+
59+
Defaults to ``"default"`` (portable ONNX, standard attention), matching
60+
how the golden references were generated. Set ``MOBIUS_TEST_BUILD_EP`` to
61+
build an EP-specialized graph instead (e.g. ``cuda`` to emit
62+
``PackedMultiHeadAttention`` for the Qwen-VL vision encoders).
63+
64+
Building a CUDA-specialized graph requires running on CUDA, since ops such
65+
as ``PackedMultiHeadAttention`` have no CPU kernel. A build/runtime EP
66+
mismatch is therefore rejected as a misconfiguration.
67+
"""
68+
build_ep = os.environ.get("MOBIUS_TEST_BUILD_EP", "default").strip().lower()
69+
if build_ep == "cuda" and os.environ.get("MOBIUS_TEST_DEVICE", "").lower() != "cuda":
70+
raise pytest.UsageError(
71+
"MOBIUS_TEST_BUILD_EP=cuda requires MOBIUS_TEST_DEVICE=cuda so that "
72+
"CUDA-specific ops (e.g. PackedMultiHeadAttention) run on CUDA."
73+
)
74+
return build_ep
75+
76+
5177
def _get_test_device_kwargs() -> dict[str, str]:
5278
"""Return OnnxModelSession kwargs from environment variables.
5379
@@ -301,6 +327,7 @@ def _build_model_package(case: GoldenTestCase) -> ModelPackage:
301327
dtype=case.dtype,
302328
load_weights=True,
303329
trust_remote_code=case.trust_remote_code,
330+
execution_provider=_get_test_build_ep(),
304331
)
305332

306333

0 commit comments

Comments
 (0)