Skip to content

Commit f2f9369

Browse files
justinchubyCopilot
andcommitted
Optimize Mage-VL fused vision graphs
Accept standard float32 processor output and cast at the vision graph boundary for reduced-precision builds. Construct packed-attention sequence metadata from per-grid-row window lengths so CUDA exports avoid a patch-by-visual expansion while preserving portable attention masks. Add regression coverage for processor-shaped video inputs, fused CUDA operators, and post-weight transpose folding. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 758184f commit f2f9369

3 files changed

Lines changed: 97 additions & 57 deletions

File tree

‎src/mobius/models/mage_vl.py‎

Lines changed: 50 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -358,68 +358,69 @@ def __init__(self, config: ArchitectureConfig):
358358
)
359359

360360
def _attention_metadata(self, op: OpBuilder, grid_thw: Value, hidden_states: Value):
361-
# Map each flattened patch to its visual sample and four-frame chunk.
361+
# Build per-window lengths directly from (T, H, W). The processor emits
362+
# one row per image/video frame, while custom callers may pack T>1 into a
363+
# row; padding to max_windows keeps this O(num_visuals * max_windows)
364+
# instead of materializing an O(total_patches * num_visuals) table.
365+
temporal = op.Gather(grid_thw, op.Constant(value_int=0), axis=1)
366+
spatial = op.Mul(
367+
op.Gather(grid_thw, op.Constant(value_int=1), axis=1),
368+
op.Gather(grid_thw, op.Constant(value_int=2), axis=1),
369+
)
370+
window = op.Constant(value_int=self.frame_windows_size)
371+
window_counts = op.Div(op.Add(temporal, self.frame_windows_size - 1), window)
372+
max_windows = op.Squeeze(op.ReduceMax(window_counts), [0])
373+
window_ids = op.Range(
374+
op.Constant(value_int=0),
375+
max_windows,
376+
op.Constant(value_int=1),
377+
)
378+
valid_windows = op.Less(
379+
op.Unsqueeze(window_ids, [0]),
380+
op.Unsqueeze(window_counts, [1]),
381+
)
382+
remaining_frames = op.Sub(
383+
op.Unsqueeze(temporal, [1]),
384+
op.Mul(op.Unsqueeze(window_ids, [0]), window),
385+
)
386+
window_frames = op.Min(remaining_frames, window)
387+
window_lengths = op.Mul(window_frames, op.Unsqueeze(spatial, [1]))
388+
lengths = op.Compress(
389+
op.Reshape(window_lengths, op.Constant(value_ints=[-1])),
390+
op.Reshape(valid_windows, op.Constant(value_ints=[-1])),
391+
)
392+
cu_seqlens = op.Concat(
393+
op.Constant(value_ints=[0]),
394+
op.CumSum(lengths, op.Constant(value_int=0)),
395+
axis=0,
396+
)
397+
if ep_capabilities().supports_packed_multi_head_attention:
398+
return None, cu_seqlens
399+
400+
# Portable ONNX Attention needs an explicit block-diagonal mask.
362401
total = op.Shape(hidden_states, start=1, end=2)
363402
patch_ids = op.Range(
364403
op.Constant(value_int=0),
365404
op.Squeeze(total, [0]),
366405
op.Constant(value_int=1),
367406
)
368-
sample_lengths = op.ReduceProd(grid_thw, axes=[1], keepdims=0)
369-
sample_ends = op.CumSum(sample_lengths, op.Constant(value_int=0))
370-
sample_ids = op.ReduceSum(
407+
segment_ends = op.Slice(
408+
cu_seqlens,
409+
starts=[1],
410+
ends=[9223372036854775807],
411+
axes=[0],
412+
)
413+
segment_ids = op.ReduceSum(
371414
op.Cast(
372415
op.GreaterOrEqual(
373416
op.Unsqueeze(patch_ids, [1]),
374-
op.Unsqueeze(sample_ends, [0]),
417+
op.Unsqueeze(segment_ends, [0]),
375418
),
376419
to=ir.DataType.INT64,
377420
),
378421
axes=[1],
379422
keepdims=0,
380423
)
381-
sample_starts = op.Concat(
382-
op.Constant(value_ints=[0]),
383-
op.Slice(sample_ends, starts=[0], ends=[-1], axes=[0]),
384-
axis=0,
385-
)
386-
local_ids = op.Sub(patch_ids, op.Gather(sample_starts, sample_ids))
387-
spatial_sizes = op.Mul(
388-
op.Gather(grid_thw, op.Constant(value_int=1), axis=1),
389-
op.Gather(grid_thw, op.Constant(value_int=2), axis=1),
390-
)
391-
window_sizes = op.Mul(
392-
op.Gather(spatial_sizes, sample_ids),
393-
op.Constant(value_int=self.frame_windows_size),
394-
)
395-
window_ids = op.Div(local_ids, window_sizes)
396-
same_as_previous = op.And(
397-
op.Equal(
398-
op.Slice(sample_ids, starts=[1], ends=[9223372036854775807], axes=[0]),
399-
op.Slice(sample_ids, starts=[0], ends=[-1], axes=[0]),
400-
),
401-
op.Equal(
402-
op.Slice(window_ids, starts=[1], ends=[9223372036854775807], axes=[0]),
403-
op.Slice(window_ids, starts=[0], ends=[-1], axes=[0]),
404-
),
405-
)
406-
segment_starts = op.Concat(
407-
op.Cast(op.Constant(value_ints=[1]), to=ir.DataType.BOOL),
408-
op.Not(same_as_previous),
409-
axis=0,
410-
)
411-
cu_seqlens = op.Concat(
412-
op.Compress(patch_ids, segment_starts),
413-
total,
414-
axis=0,
415-
)
416-
if ep_capabilities().supports_packed_multi_head_attention:
417-
return None, cu_seqlens
418-
419-
segment_ids = op.CumSum(
420-
op.Cast(segment_starts, to=ir.DataType.INT64),
421-
op.Constant(value_int=0),
422-
)
423424
attention_mask = op.Equal(
424425
op.Unsqueeze(segment_ids, [1]),
425426
op.Unsqueeze(segment_ids, [0]),
@@ -433,6 +434,8 @@ def forward(
433434
grid_thw: Value,
434435
patch_positions: Value,
435436
):
437+
if get_build_dtype() != ir.DataType.FLOAT:
438+
hidden_state = op.Cast(hidden_state, to=get_build_dtype())
436439
hidden_states = self.embeddings(op, hidden_state)
437440
cos, sin = self.video_rope(op, patch_positions)
438441
attention_mask, cu_seqlens = self._attention_metadata(op, grid_thw, hidden_states)

‎src/mobius/tasks/_vision_language_3model.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ def _build_vision(
257257
graph, builder = _make_graph(name="vision_encoder")
258258
pixel_values = builder.input(
259259
"pixel_values",
260-
dtype=config.dtype,
260+
dtype=ir.DataType.FLOAT,
261261
shape=[total_patches, pixel_dim],
262262
)
263263
image_grid_thw = builder.input(

‎tests/mage_vl_parity_test.py‎

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,11 @@ def _reference_vision(
4848
) -> torch.Tensor:
4949
prefix = "vision_encoder.visual"
5050
patch_weight = state[f"{prefix}.embeddings.patch_embedding.weight"]
51-
hidden = functional.conv2d(pixel_values.reshape(-1, 3, 4, 4), patch_weight, stride=4)
51+
hidden = functional.conv2d(
52+
pixel_values.to(patch_weight.dtype).reshape(-1, 3, 4, 4),
53+
patch_weight,
54+
stride=4,
55+
)
5256
hidden = hidden.reshape(1, -1, 64)
5357

5458
# Mage-VL uses independent frequency scales for its 4:6:6 T/H/W split.
@@ -111,8 +115,26 @@ def _rope(x: torch.Tensor, target_dtype: torch.dtype = qkv.dtype) -> torch.Tenso
111115
(ir.DataType.FLOAT16, torch.float16, 1e-2),
112116
],
113117
)
114-
def test_mage_vl_synthetic_video_parity(tmp_path, dtype, torch_dtype, atol):
115-
"""A nonzero five-frame clip matches PyTorch across the four-frame boundary."""
118+
@pytest.mark.parametrize(
119+
("grid_thw", "frame_positions"),
120+
[
121+
(torch.tensor([[5, 2, 2]], dtype=torch.int64), (0, 3, 7, 12, 18)),
122+
(
123+
torch.tensor([[1, 2, 2]] * 6, dtype=torch.int64),
124+
(0, 0, 180, 360, 539, 719),
125+
),
126+
],
127+
ids=["packed-five-frame", "processor-image-plus-five-frames"],
128+
)
129+
def test_mage_vl_synthetic_video_parity(
130+
tmp_path,
131+
dtype,
132+
torch_dtype,
133+
atol,
134+
grid_thw,
135+
frame_positions,
136+
):
137+
"""Nonzero packed and processor-shaped media match PyTorch window boundaries."""
116138
overrides = next(overrides for mt, overrides, _ in VL_CONFIGS if mt == "mage_vl")
117139
config = dataclasses.replace(_base_config(**overrides), dtype=dtype)
118140
package = build_from_module(
@@ -128,12 +150,11 @@ def test_mage_vl_synthetic_video_parity(tmp_path, dtype, torch_dtype, atol):
128150
for name, value in vision.graph.initializers.items()
129151
if value.const_value is None
130152
}
131-
pixel_values = torch.randn((20, 48), generator=generator).to(torch_dtype)
132-
grid_thw = torch.tensor([[5, 2, 2]], dtype=torch.int64)
153+
pixel_values = torch.randn((len(frame_positions) * 4, 48), generator=generator)
133154
patch_positions = torch.tensor(
134155
[
135156
(frame, height, width)
136-
for frame in (0, 3, 7, 12, 18)
157+
for frame in frame_positions
137158
for height in range(2)
138159
for width in range(2)
139160
],
@@ -183,20 +204,36 @@ def test_mage_vl_decode_embedding_accepts_no_new_media(tmp_path):
183204
)
184205

185206

186-
def test_mage_vl_cuda_uses_packed_attention():
187-
"""CUDA builds preserve four-frame segments without a quadratic dense mask."""
207+
def test_mage_vl_cuda_graph_is_fused_and_post_weight_optimized():
208+
"""FP16 CUDA builds fuse hot paths and fold weight transposes after loading."""
188209
overrides = next(overrides for mt, overrides, _ in VL_CONFIGS if mt == "mage_vl")
189-
config = _base_config(**overrides)
210+
config = dataclasses.replace(_base_config(**overrides), dtype=ir.DataType.FLOAT16)
190211
package = build_from_module(
191212
registry.get("mage_vl")(config),
192213
config,
193214
task="mage-vl",
194215
execution_provider="cuda",
195216
)
217+
decoder = package["decoder"]
196218
vision = package["vision_encoder"]
197219

220+
assert count_op_type(decoder.graph, "GroupQueryAttention") == 2
221+
assert count_op_type(decoder.graph, "Attention") == 0
222+
assert count_op_type(decoder.graph, "Swish") == 2
223+
assert count_op_type(decoder.graph, "SkipSimplifiedLayerNormalization") == 4
198224
assert count_op_type(vision.graph, "PackedMultiHeadAttention") == 2
199225
assert count_op_type(vision.graph, "Attention") == 0
226+
assert count_op_type(vision.graph, "SkipLayerNormalization") == 4
227+
assert count_op_type(vision.graph, "GreaterOrEqual") == 0
228+
229+
for model in (decoder, vision):
230+
state = {
231+
name: torch.randn(tuple(value.shape), dtype=torch.float32)
232+
for name, value in model.graph.initializers.items()
233+
if value.const_value is None
234+
}
235+
apply_weights(model, state)
236+
assert count_op_type(model.graph, "Transpose") == 0
200237

201238

202239
def test_mage_vl_embedding_uses_global_media_order_across_batch(tmp_path):

0 commit comments

Comments
 (0)