Skip to content

Exporters: fixes to the export path, checked on inputs the exports never saw - #50785

Open
IlyasMoutawwakil wants to merge 62 commits into
data-dependent-inputsfrom
exporters-main-fixes
Open

IlyasMoutawwakil wants to merge 62 commits into
data-dependent-inputsfrom
exporters-main-fixes

Conversation

@IlyasMoutawwakil

@IlyasMoutawwakil IlyasMoutawwakil commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

What does this PR do?

Stacked on #50887 (on #50733), below #50249. Fixes to the export path for code already on main, so the multimodal and generation PRs above only carry their features.

The export tests now run each torch.export program again on new inputs drawn from the model tester (one more sample and one more token for a dynamic export). That check surfaced most of what follows.

ONNX

Fix Why
Opset 23 by default; 20 with ort_fusions or a quantizer Opset 23 exports SDPA, RMS norms and rotary embeddings as Attention, RMSNormalization and RotaryEmbedding. Qwen3-0.6B on ONNX Runtime CPU: 12.1 → 30.1 tokens/s. ONNX Runtime's fusions match the decompositions, and NNCF's QuantizeLinear at 23 mismatches its zero point
Our own scaled_dot_product_attention → Attention translation at opset 23 torchlib's compares head counts by shape, and fails on a cache's symbolic head axis
RotaryEmbedding's cos and sin expanded to the input's batch onnxscript's opset-23 rotary rewrite takes cos and sin computed for batch 1; the op needs them at the input's batch
onnxscript's SlicesSplit rewrite skipped Quadratic in the number of Slices: 45 of 47 minutes of a static Qwen3.5 prompt graph's export

ONNX Runtime fusions

Fix Why
A multidimensional rotary (Gemma 4's vision tower) becomes RotaryEmbedding EmbeddingGemma2 vision graph: 1007 → 749 nodes
Head transposes sunk past per-head norms, so they meet and cancel EmbeddingGemma2 language model: 146 → 2 Transpose
A norm scaled in float32 (Qwen3.5's 1 + weight) kept apart from its residual ONNX Runtime refused the mixed-precision SkipSimplifiedLayerNormalization
Batch transposes put back as Transpose where the CPU provider can't take them onnxscript fuses one into a FusedMatMul whose inputs have different ranks (Gemma3's and PaliGemma's vision towers failed to run)
GroupQueryAttention only for one-token queries when the model may attend bidirectionally (token types, a custom 4D mask) It masks the future on top of the bias: PaliGemma's bidirectional prefix became causal
OrtFusionConfig picks the fusions with a tradeoff (rotary, GroupQueryAttention, mixture of experts, packed projections); a provider string still gives its defaults Mixture of experts is off by default: ONNX Runtime's CUDA MoE needs a Hopper or newer GPU ("Arch unsupported for MoE GEMM" on an A100)

Runners

Fix Why
ONNX Runtime's CUDA provider uses TF32 for float32 matmuls only when torch does Its outputs then match torch's
A static ONNX export replays a CUDA graph by default; a dynamic one never does, explicit providers included A CUDA graph replays one input shape
OpenVINO compiles with the precision the export records OpenVINO 2026.4 ignores it, so fp32 exports ran in bf16 on AMX CPUs (the Gemma3, PaliGemma and Qwen3.5 mismatches)

Loops over the sequence

Fix Why
The chunked gated delta rule (Qwen3.5, Qwen3-Next, Olmo-Hybrid, Qwen4-Exp): its chunk loop as a scan, its triangular solve as a vectorized block inversion Tracing unrolled both for the traced length: a dynamic export only took prompts with the traced chunk count
Mamba's recurrence as a while_loop under export (Mamba; Falcon-Mamba and Jamba through modular; Zamba, whose copy is identical) Same: a dynamic export guarded on the traced length
OpenVINO: scan as a while_loop, a while_loop's closure inputs carried through it, index_copy as scatter OpenVINO has no scan conversion, counts closure inputs as carried, and can't convert index_copy in a loop body
ExecuTorch keeps both loops unrolled ExecuTorch lowers no while_loop, and its to_executorch replay refuses a scan with a dynamic batch
Window attention with uneven windows (Qwen2.5-VL, Qwen2.5-Omni, Exaone 4.5, Muse Spark, Muse Glimmer): one SDPA call masked to each segment The reshape-into-batch patch needed equal windows
ExecuTorch: a split with data-dependent sizes as narrows split_with_sizes_copy with unbacked sizes fails to lower

Modeling

PaliGemma builds its prefix mask (block_sequence_ids) on every step, not only the first. It's the same in eager, since later steps fall past the given ids, but a generation graph traced on a decode step needs it to run the prompt bidirectionally.

Tests

  • tests/exporters/test_export.py: each torch.export test runs the program on new inputs too. A model split into components (multimodal) is checked on its traced inputs only, since main's split precomputes some inputs (cu_seqlens, M-RoPE positions) for those alone. LFM2-VL, Mistral3 and SigLIP2 skip dynamic torch.export until LFM2-VL: run the projector on all images at once #50734 and SigLIP2: compute the position-embedding resize for all images with tensor ops #50736.
  • tests/exporters/test_utils.py: window attention on other uneven windows, and a dynamic Qwen3.5 export traced on two chunks against eager on one and four, on Dynamo, ONNX and OpenVINO.
  • tests/exporters/test_fusions.py: each OrtFusionConfig toggle, the CUDA-fused decode graph run on CUDA against the plain one, and the OpenVINO fusion check limited to the keys' and values' states (a sliding-window layer keeps its window as one too).
  • tests/exporters/test_runtime.py: TF32 following torch.
  • Run: tests/exporters (175 passed) and the export tests of Llama, Gemma3, PaliGemma, LLaVA, Qwen2.5-VL, Qwen3.5, Qwen3-Next, Olmo-Hybrid, Mamba, Falcon-Mamba, Jamba and Zamba on all four backends, and their eager suites for the models whose code changed.

🤖 Generated with Claude Code

🤖 mlinter review state

…ver saw

Export tests now run each torch.export program again on new inputs drawn from the model
tester (other sizes for a dynamic export), which surfaced most of these.

ONNX
- Opset 23 by default (Attention, RMSNormalization, RotaryEmbedding as single ops); 20 with
  ONNX Runtime fusions or a quantizer. Our own SDPA -> Attention translation, as torchlib's
  asserts on a symbolic head axis; RotaryEmbedding's cos/sin expanded to the input's batch.
- onnxscript's SlicesSplit rewrite skipped (quadratic on large graphs).
- ONNX Runtime fusions: multidimensional rotary, head transposes sunk past per-head norms,
  float32-scaled norms kept apart from their residual, batch transposes put back where the
  CPU provider can't take them, GroupQueryAttention only for one-token queries when the
  model may attend bidirectionally (token types, a custom 4D mask).
- `OrtFusionConfig` picks the fusions with a tradeoff; mixture of experts is off by default,
  its CUDA kernels needing a Hopper or newer GPU.
- Runner: TF32 as torch has it; a static export replays a CUDA graph by default.

OpenVINO
- The precision the export records is passed to compile_model (fp32 exports ran in bf16 on
  AMX CPUs); while_loop's closure inputs carried through the loop; index_copy as scatter.

Models and patches
- The chunked gated delta rule (Qwen3.5, Qwen3-Next, Olmo-Hybrid, Qwen4-Exp) and Mamba's
  recurrence (Mamba, Falcon-Mamba, Jamba, Zamba) export for any length; ExecuTorch keeps
  the loops unrolled. Uneven window attention; ExecuTorch splits with unbacked sizes.
- PaliGemma builds its prefix mask on every step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Model linter — first pass

transformers-mlinter found 1 item(s) in the model files this PR touches. These are structural conventions a maintainer would otherwise flag by hand.

This is automated and advisory — it does not block merging.

rule count what it checks
TRF057 1 Public model, config, output and processor classes and their public methods must carry @auto_docstring.
1 item(s) outside this diff
  • src/transformers/models/molmo2/modular_molmo2.py:1581 TRF057 — TRF057: Molmo2Model.get_video_features in modeling_molmo2.py has no @auto_docstring. No parent method it could inherit the decorator from declares it. Add @auto_docstring as the innermost decorator here.

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Pages changed in this PR:

IlyasMoutawwakil added a commit that referenced this pull request Nov 15, 2026
…porters-multimodal-decomposition

The export-path fixes and `OrtFusionConfig` move to #50785, below this PR, and the ModelOpt
quantizer (#50643) sits between them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
IlyasMoutawwakil and others added 3 commits November 15, 2026 19:22
… supports

optimum-intel records GPU options in `runtime_options` (`ACTIVATIONS_SCALE_FACTOR`), which the
CPU plugin refuses when compiling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ays dynamic

On a prompt of a whole number of 64-token chunks (128 tokens), the pad to the next chunk is 0
and the cut back to the prompt keeps every position, both of which a trace specializes on: the
export took prompts of the traced length only. It now pads by two chunks and cuts, and gathers
the prompt's positions back. The test traces on 128 tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…r directly

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
IlyasMoutawwakil added a commit that referenced this pull request Nov 15, 2026
Their selective scan runs as a `while_loop` under export (#50785), so the multi-token decode
graph takes the prefill call: the skips go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
IlyasMoutawwakil and others added 18 commits November 15, 2026 21:15
…pends on the data

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…al, not with -inf before it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…hich dynamic shapes truncated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tion may be causal

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…-dependent ops, computed outside it

A model's get_data_dependent_inputs returns what its forward would otherwise compute with host syncs or loops
over images (cu_seqlens, positions, window indices, M-RoPE positions), so they can be computed once and passed
back in, keeping torch.compile(fullgraph=True) and torch.export free of those operations. PreTrainedModel returns
none by default; generate passes them to the steps that carry the prompt's inputs.

- Qwen2-VL, Qwen2.5-VL (window attention) and Qwen3-VL (interpolation) towers and models, through modular to
  their families; HunYuan-VL's and Video-LLaMA 3's own towers.
- select_hidden_states finds its selection argument once instead of binding the signature on every call, which
  torch.compile can't trace.
- A common test compiling each modality encoder with fullgraph=True on these inputs, under flash attention where
  supported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tower's patch positions, attention max_seqlen and window-merger index come from get_data_dependent_inputs,
and its forward hands each to the submodule that uses it; the model's are prefixed image_, which
get_image_features now strips (accepts_precomputed_kwargs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The patch embedder's interpolation inputs move to get_interpolation_inputs, so Spark only overrides the (w, h)
grid read instead of copying the embedder's forward.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…vision tower

It inherits Video-LLaMA 3's model, whose method passes merge sizes to its own tower; this one prefixes the Qwen2.5-VL
tower's window inputs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tower method serves GLM-4V, GLM-4V-MoE, GLM-4.6V, GLM-OCR, GLM-5-Next and GLM-Image, whose forwards read it.
GLM-Image encodes the source images only, so its model method derives them from the source grids, and it gets the
flat get_image_embeddings the family has, which get_image_features splits per image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…puts, flat get_image_embeddings

Pixtral gathers each image's unpadded patches with one index instead of cropping and concatenating per image, and
builds the block mask from the patch-to-image index. The patch merger gathers each block's patches with a
precomputed merge_index instead of unfolding per image. Mistral3 and LightOnOCR get the flat getter the other VLMs
have, which get_image_features splits per image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ge_embeddings

The patches each image was cut into are gathered with one patch_index, and the projected features are packed with
one pack_index into them and image_newline: the same rearrangement and unpadding, applied to an index grid, so
get_image_embeddings has no loop over images. get_image_features splits it per image. LLaVA-NeXT-Video drops its
copy of get_image_features to inherit them. LLaVA-OneVision, Granite 4 Vision and DeepSeek-OCR 2 pack differently
and delete the inherited methods.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cosmos3 Edge resizes its position table per image with antialiasing; LLaVA-OneVision interpolates each image's
features to an anyres-max size; Granite 4 Vision packs its features in groups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…inputs stands alone

A forward calls the get_vision_* helpers as before, which take a precomputed value from kwargs or compute it, so it
carries no extra machinery; get_data_dependent_inputs makes the same calls and returns them. Pixtral, the Mistral3
merger and LLaVA-NeXT read theirs the same way, through methods that pop the precomputed value or compute it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…mask

These encoders pass their padding mask to flash attention, whose unpadding (nonzero, .item()) is data-dependent;
they trace under sdpa. A follow-up lets the flash path take precomputed unpad data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The padding mask's sum plus pooling_epsilon is float32, which upcast the pooled text embeddings and broke the
image-text matmul in bfloat16.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
IlyasMoutawwakil and others added 2 commits November 18, 2026 19:44
- Pixtral, Mistral3, LightOnOCR: gather each image's patches and merge blocks with one index.
- LLaVA-NeXT(-Video): gather the patches and pack the features with one index; LLaVA-OneVision, Granite 4 Vision
  and DeepSeek-OCR2 get their own flat getter.
- RADIO / Nemotron-H Omni, HunYuan-VL / HY-V4-VL, Video-LLaMA 3, ERNIE 4.5-VL-MoE: position tables, pixel
  (un)shuffles, patch mergers and temporal slicing as gathers.
- Qwen2.5-Omni, Qwen3-Omni, Qwen3-ASR: audio chunking and frame selection as gathers.
- Index builders are pop-or-compute functions, reading a precomputed value from the forward's kwargs.
- select_hidden_states no longer binds the signature on every call.
- Fixes: TIPSv2's text pooling dtype, Nemotron-H Omni's deprecated torch_dtype read, MOSS-Transcribe-Diarize's
  get_audio_features wrapper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The inputs a forward computes with data-dependent ops, computed outside it: passed back through the forward's
kwargs, they keep torch.compile(fullgraph=True) and torch.export free of host syncs. Towers return them
unprefixed, models prefixed by modality; generate computes them with the prompt's inputs. A common test compiles
each modality encoder with fullgraph=True on them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rters-main-fixes

# Conflicts:
#	src/transformers/models/cohere_compass/modeling_cohere_compass.py
#	src/transformers/models/cosmos3_edge/modeling_cosmos3_edge.py
#	src/transformers/models/cosmos3_omni/modeling_cosmos3_omni.py
#	src/transformers/models/deepseek_ocr2/modeling_deepseek_ocr2.py
#	src/transformers/models/embedding_gemma2/modeling_embedding_gemma2.py
#	src/transformers/models/ernie4_5_vl_moe/modeling_ernie4_5_vl_moe.py
#	src/transformers/models/exaone4_5/modeling_exaone4_5.py
#	src/transformers/models/gemma4/modeling_gemma4.py
#	src/transformers/models/gemma4/modular_gemma4.py
#	src/transformers/models/glm46v/modeling_glm46v.py
#	src/transformers/models/glm4v/modeling_glm4v.py
#	src/transformers/models/glm4v_moe/modeling_glm4v_moe.py
#	src/transformers/models/glm5_next/modeling_glm5_next.py
#	src/transformers/models/glm_ocr/modeling_glm_ocr.py
#	src/transformers/models/granite4_vision/modeling_granite4_vision.py
#	src/transformers/models/granite4_vision/modular_granite4_vision.py
#	src/transformers/models/hy_v4_vl/modeling_hy_v4_vl.py
#	src/transformers/models/hyperclovax_vision_v2/modeling_hyperclovax_vision_v2.py
#	src/transformers/models/kimi_k25/modeling_kimi_k25.py
#	src/transformers/models/lfm3_vl/modeling_lfm3_vl.py
#	src/transformers/models/lighton_ocr/modeling_lighton_ocr.py
#	src/transformers/models/lighton_ocr/modular_lighton_ocr.py
#	src/transformers/models/llava_next/modeling_llava_next.py
#	src/transformers/models/llava_next_video/modeling_llava_next_video.py
#	src/transformers/models/llava_onevision/modeling_llava_onevision.py
#	src/transformers/models/mistral3/modeling_mistral3.py
#	src/transformers/models/mistral3/modular_mistral3.py
#	src/transformers/models/mistral_large4/modeling_mistral_large4.py
#	src/transformers/models/muse_glimmer/modeling_muse_glimmer.py
#	src/transformers/models/muse_spark/modeling_muse_spark.py
#	src/transformers/models/nemotron_h_omni/modeling_nemotron_h_omni.py
#	src/transformers/models/nemotron_h_omni/modular_nemotron_h_omni.py
#	src/transformers/models/paddleocr_vl/modeling_paddleocr_vl.py
#	src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
#	src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py
#	src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py
#	src/transformers/models/qwen2_vl/modeling_qwen2_vl.py
#	src/transformers/models/qwen3_5/modeling_qwen3_5.py
#	src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py
#	src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
#	src/transformers/models/qwen3_vl/modeling_qwen3_vl.py
#	src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py
#	src/transformers/models/qwen4_exp/modeling_qwen4_exp.py
#	src/transformers/models/step3p7/modeling_step3p7.py
#	src/transformers/models/video_llama_3/modeling_video_llama_3.py
IlyasMoutawwakil and others added 6 commits November 22, 2026 22:08
…_dependent_inputs

prepare_for_export calls the model's get_data_dependent_inputs (keeping the inputs it already has) instead of
the exporters' own registry of per-encoder preparers and the get_rope_index probe, which the models' method now
covers: the grid_thw towers, NaViT target_sizes, Pixtral / LLaVA-NeXT image_sizes, the Omni and Qwen3-ASR audio
encoders, and the M-RoPE position_ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Model linter — first pass

transformers-mlinter found 2 item(s) in the model files this PR touches. These are structural conventions a maintainer would otherwise flag by hand.

This is automated and advisory — it does not block merging.

rule count what it checks
TRF055 1 PreTrainedModel classes declare their config with a config: SomeConfig annotation, matched by __init__(config: SomeConfig); never config_class.
TRF057 1 Public model, config, output and processor classes and their public methods must carry @auto_docstring.
2 item(s) outside this diff
  • src/transformers/models/fun_asr_nano/modular_fun_asr_nano.py:460 TRF055 — TRF055: generated modeling_fun_asr_nano.py:351: FunAsrNanoMultiModalProjector.__init__ takes config: FunAsrNanoConfig but the class overrides config: FunAsrNanoAdaptorConfig. Make them match; add or update config: FunAsrNanoConfig in the class body if that is intended.
  • src/transformers/models/fun_asr_nano/modular_fun_asr_nano.py:479 TRF057 — TRF057: FunAsrNanoMultiModalProjector.forward in modeling_fun_asr_nano.py has no @auto_docstring. No parent method it could inherit the decorator from declares it. Add @auto_docstring as the innermost decorator here.

@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: diffusion_gemma, embedding_gemma2, falcon_mamba, gemma4, jamba, mamba, paligemma, zamba

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants