Skip to content

Commit ec0e03d

Browse files
justinchubyCopilot
andcommitted
Make Qwen4Exp video rejection EP-independent
Replace CUDA's fail-open out-of-range Gather guard with a dynamic Reshape element-count violation shared by CPU and CUDA ORT. Preserve runtime dependency after optimization and cover valid plus processor-native mixed execution on CPU and CUDA when available. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent abf40e4 commit ec0e03d

3 files changed

Lines changed: 70 additions & 30 deletions

File tree

‎docs/design/qwen4-exp-text-core.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,11 @@ explicitly image-only: config extraction validates the checkpoint's video token
6565
but removes it from runtime metadata, the embedding graph exposes no video
6666
feature input, and direct configs that request video support fail closed. The
6767
embedding graph also publishes `mobius.unsupported_token_ids` and carries a
68-
dynamic ONNX Gather guard: any source video token is sanitized before vocabulary
69-
lookup and then forces an out-of-range index error, so direct graph execution
70-
cannot silently treat `<|video_pad|>` as ordinary text.
68+
dynamic ONNX Reshape guard: any source video token is sanitized before
69+
vocabulary lookup and then requests two output elements from a one-element
70+
tensor. ONNX's element-count invariant is enforced before every ORT EP executes,
71+
so direct graph execution cannot silently treat `<|video_pad|>` as ordinary
72+
text. This deliberately avoids out-of-range Gather, which CUDA zero-fills.
7173

7274
QSA uses standard ONNX operators to reproduce the selected-token mask, then
7375
runs ordinary dense attention under that mask. This is numerically faithful,

‎src/mobius/models/qwen4_exp.py‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1422,18 +1422,25 @@ def forward(
14221422
image_features,
14231423
)
14241424

1425-
# Gather index 0 for image/text requests and index 1 for unsupported
1426-
# video requests. The one-element table makes video execution fail
1427-
# deterministically instead of treating <|video_pad|> as a text token.
1425+
# Reshape one zero element to [1] for image/text and [2] for video.
1426+
# ONNX Reshape requires equal input/output element counts, so every ORT
1427+
# EP rejects video before it can return sanitized embeddings. ORT CUDA
1428+
# calls the shared ReshapeHelper for this check
1429+
# (onnxruntime@b1f76d58, cuda/tensor/reshape.h); unlike out-of-range
1430+
# Gather, this cannot fail open by zero-filling on CUDA.
14281431
video_present = op.ReduceMax(
14291432
op.Cast(video_mask, to=ir.DataType.INT64),
14301433
keepdims=False,
14311434
)
1432-
guard = op.Gather(
1435+
guard_shape = op.Unsqueeze(
1436+
op.Add(video_present, op.Constant(value_int=1)),
1437+
[0],
1438+
)
1439+
guard = op.Reshape(
14331440
op.CastLike(op.Constant(value_floats=[0.0]), inputs_embeds),
1434-
video_present,
1441+
guard_shape,
14351442
)
1436-
return op.Add(inputs_embeds, guard)
1443+
return op.Add(inputs_embeds, op.ReduceSum(guard, keepdims=False))
14371444

14381445

14391446
class Qwen4ExpForConditionalGeneration(nn.Module):

‎src/mobius/models/qwen4_exp_test.py‎

Lines changed: 52 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -420,29 +420,57 @@ def test_multimodal_embedding_preserves_global_image_order():
420420
np.full(config.hidden_size, 202.0, dtype=np.float32),
421421
]
422422
)
423-
session = OnnxModelSession(embedding)
424-
try:
425-
actual = session.run(
426-
{
427-
"input_ids": input_ids,
428-
"image_features": image_features,
429-
}
430-
)["inputs_embeds"]
431-
video_input_ids = input_ids.copy()
432-
video_input_ids[0, 3] = config.unsupported_video_token_id
433-
with pytest.raises(
434-
ort.capi.onnxruntime_pybind11_state.InvalidArgument,
435-
match="indices element out of data bounds",
436-
):
437-
session.run(
423+
guard_reshape = next(
424+
node
425+
for node in embedding.graph
426+
if node.op_type == "Reshape"
427+
and node.inputs[1] is not None
428+
and node.inputs[1].producer() is not None
429+
and node.inputs[1].producer().op_type == "Unsqueeze"
430+
and node.inputs[1].producer().inputs[0].producer() is not None
431+
and node.inputs[1].producer().inputs[0].producer().op_type == "Add"
432+
)
433+
assert (
434+
guard_reshape.inputs[1].producer().inputs[0].producer().inputs[0].producer()
435+
is not None
436+
)
437+
438+
devices = ["cpu"]
439+
if "CUDAExecutionProvider" in ort.get_available_providers():
440+
devices.append("cuda")
441+
actual = None
442+
for device in devices:
443+
session = OnnxModelSession(embedding, device=device)
444+
try:
445+
device_actual = session.run(
438446
{
439-
"input_ids": video_input_ids,
447+
"input_ids": input_ids,
440448
"image_features": image_features,
441449
}
442-
)
443-
finally:
444-
session.close()
450+
)["inputs_embeds"]
451+
if actual is None:
452+
actual = device_actual
453+
else:
454+
np.testing.assert_array_equal(device_actual, actual)
455+
video_input_ids = input_ids.copy()
456+
video_input_ids[0, 3] = config.unsupported_video_token_id
457+
with pytest.raises(
458+
(
459+
ort.capi.onnxruntime_pybind11_state.Fail,
460+
ort.capi.onnxruntime_pybind11_state.RuntimeException,
461+
),
462+
match=r"cannot be reshaped|input_shape_size",
463+
):
464+
session.run(
465+
{
466+
"input_ids": video_input_ids,
467+
"image_features": image_features,
468+
}
469+
)
470+
finally:
471+
session.close()
445472

473+
assert actual is not None
446474
np.testing.assert_array_equal(actual[0, 1], image_features[0])
447475
np.testing.assert_array_equal(actual[1, 2], image_features[1])
448476
np.testing.assert_array_equal(actual[0, 0], weight[input_ids[0, 0]].numpy())
@@ -771,8 +799,11 @@ def test_real_video_and_mixed_processor_outputs_have_no_export_route():
771799
session = OnnxModelSession(embedding)
772800
try:
773801
with pytest.raises(
774-
ort.capi.onnxruntime_pybind11_state.InvalidArgument,
775-
match="indices element out of data bounds",
802+
(
803+
ort.capi.onnxruntime_pybind11_state.Fail,
804+
ort.capi.onnxruntime_pybind11_state.RuntimeException,
805+
),
806+
match=r"cannot be reshaped|input_shape_size",
776807
):
777808
session.run(
778809
{

0 commit comments

Comments
 (0)