Repository navigation
🚨 Add get_data_dependent_inputs: compute a forward's data-dependent inputs outside it - #50887
IlyasMoutawwakil wants to merge 34 commits into
Conversation
|
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. |
4ac7719 to
de35dfc
Compare
There was a problem hiding this comment.
Model linter — first pass
transformers-mlinter found 3 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 |
3 | Public model, config, output and processor classes and their public methods must carry @auto_docstring. |
2 item(s) outside this diff
src/transformers/models/hy_v4_vl/modular_hy_v4_vl.py:514TRF057 — TRF057:HYV4VLModel.get_image_featuresin modeling_hy_v4_vl.py has no @auto_docstring. Declaring @can_return_tuple here drops every decorator of the parent method. Add @auto_docstring as the innermost decorator here.src/transformers/models/hy_v4_vl/modular_hy_v4_vl.py:538TRF057 — TRF057:HYV4VLModel.get_video_featuresin modeling_hy_v4_vl.py has no @auto_docstring. Declaring @can_return_tuple here drops every decorator of the parent method. Add @auto_docstring as the innermost decorator here.
61125af to
c6d7e3e
Compare
- 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>
c6d7e3e to
83d5ddd
Compare
… data-dependent-inputs
… data-dependent-inputs
… data-dependent-inputs GLM-Image's feature maps no longer carry the flat getter's split_sizes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… data-dependent-inputs # Conflicts: # src/transformers/models/hunyuan_vl/modular_hunyuan_vl.py # src/transformers/models/llava_next_video/modeling_llava_next_video.py # src/transformers/models/llava_onevision/modeling_llava_onevision.py # src/transformers/models/muse_spark/modular_muse_spark.py # src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py # src/transformers/models/qwen4_exp/modeling_qwen4_exp.py # src/transformers/models/video_llama_3/modular_video_llama_3.py
… data-dependent-inputs
… data-dependent-inputs
…ly where a model has it The mixin reaches the base model's, so 40 head delegates go; models outside it keep their own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ge, pass them through the image getters - Glm5Next: only the vision tower's inputs, its text model takes plain positions (it had no get_rope_index) - HunYuan-VL: drop the packed text row of position_ids, compilable placeholder check - Ernie: written out, super() reached the mixin's empty default in the generated file - Cosmos3-Edge: the vision tower returns its cu_seqlens / max_seqlen - Mistral3, Mistral-Large-4, LightOnOCR, LLaVA-NeXT(-Video), MiniCPM-V, HunYuan-VL: forward **kwargs to the image getter - Simpler common encoder compile test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… data-dependent-inputs
…anite 4 Vision and Cosmos3 Edge traceable - test_model_forward_compile_fullgraph_with_data_dependent_inputs replaces the per-encoder check: the whole forward compiles with fullgraph=True and matches eager, encoders on flash attention, text model on SDPA. - Granite 4 Vision: LLaVA-NeXT's packing indices (with a grid_size) plus a patch index, one gather per group. - Cosmos3 Edge: the antialiased position-table resize is a precomputed interpolation (vision_utils gains antialias). - GLM-5-Next and Qwen4-exp vision towers support flash attention. - FunASR-Nano: drop the head's get_data_dependent_inputs delegate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… data-dependent-inputs # Conflicts: # src/transformers/modeling_multimodal_utils.py # src/transformers/models/moss_transcribe_diarize/modeling_moss_transcribe_diarize.py # src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py # src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py
Under flash attention the vision encoder runs only the real patches, packed in one varlen sequence, and the perceiver resampler runs varlen cross-attention over each image's real patches and latents. Outputs match the padded path (padding is masked out downstream). get_data_dependent_inputs precomputes the real images' indices and both packings, so the whole forward compiles with fullgraph=True. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
get_data_dependent_inputs returns the patches each image was cut into and its packed features as (index, weight) taps into all patch tokens, the anyres_max bilinear downscale included, so get_image_embeddings has no per-image loop and the whole forward compiles with fullgraph=True. Matches F.interpolate to 2e-9 in fp32. The forward fullgraph test runs again on every model with get_data_dependent_inputs, its default included. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…lerance for the fullgraph forward test Under flash attention the adapter pools only the tokens with patches to pool, each attending to its valid patches as one varlen sequence, instead of a padded mask flash unpads with nonzero. get_data_dependent_inputs precomputes that packing, so the whole forward compiles with fullgraph=True. Outputs match SDPA. The fullgraph forward test compares in bf16 with atol=rtol=1e-2: compiled and eager differ by bf16 rounding. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s a base model without get_data_dependent_inputs
get_data_dependent_inputs returns the real (non-padding) images' indices, which get_image_embeddings otherwise
selects with a boolean mask, so the image batch has a static size under torch.compile. SmolVLM only overrides
which images count as real (it keeps one when all are padding) instead of the whole getter.
The mixin's get_data_dependent_inputs returns {} when the base model has none (T5Gemma2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…n their default attention - is_packed_inputs_modality_encoder: an encoder is packed when one of its own modules takes `cu_seqlens`. Packed encoders run flash attention's varlen path (SDPA splits them per item on the host); everything else keeps its default attention, which takes padding masks with static shapes. The padded-flash skips are gone (FunASR keeps one: its adaptor's attention implementation is never set). - Idefics2 and Molmo2 go back to their padded paths; only the real images (Idefics2) and the tokens with patches to pool (Molmo2) are precomputed. - AudioFlamingo3's forward passes its kwargs to the audio getter again (Qwen3-ASR's precomputed cu_seqlens). - RADIO declares its image modality. - GraniteDocling, ModernVBERT, UltraVBERT regenerated from Idefics3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… encoders' sub-configs in one pass Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…M-V 4.7, HY-V4-VL's merger layout - Qwen2.5-Omni / Qwen3-Omni thinker and MiniCPM-V 4.7: get_data_dependent_inputs returns the M-RoPE position_ids the forward otherwise computes with get_rope_index. - HY-V4-VL: its getters take the precomputed inputs (accepts_precomputed_kwargs), and its vision model precomputes the merger layout without begin and end tokens, as its merger lays it out (the HunYuan-VL one it inherited indexed past the merger's output). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Past the prompt the forward shifts the text positions by the cached rope_deltas, so get_data_dependent_inputs only returns position_ids while the cache is empty (as exporters' decode captures and generate's later steps would otherwise get prompt positions). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…lementation The projector held the adaptor's encoder layers as a plain module, so no sub-model owned adaptor_config: its attention implementation was never resolved (eager with a warning on every call, whatever was requested). It is now a FunAsrNanoPreTrainedModel owning adaptor_config (same parameter names), so attention dispatch reaches it at init and in set_attn_implementation, and the fullgraph forward test runs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…osite models Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
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. |
…_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>
…e_embeddings traces The exporter registry used to turn image_sizes into Python ints; get_data_dependent_inputs now returns image_token_index, which picks each image's kept tokens (and row EOLs) out of the uncropped grids. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
HunYuan-VL, HY-V4-VL, Cosmos3-Edge, GLM-5-Next and GLM-Image join the chunked vision attention patch (which now also finds an `o_proj` and a `scale`), so their forwards export. Inkling exports as is. GLM-Image keeps a static-cache generate skip (its decode recomputes M-RoPE from the cache length) and GLM-5-Next a generate.dynamic one (the merged decode doesn't grow its indexer's padding mask). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
get_data_dependent_inputs: compute a forward's data-dependent inputs outside itget_data_dependent_inputs: compute a forward's data-dependent inputs outside it
…rpolation helper, not a second helper Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ault already reaches the base model's Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BaseModelOutputWithSplitSizes, the plain-method mixin, inlined flatten_items and the review fixes. Idefics2/3 keep the precomputed real-image index and now split per image; GLM-Image keeps its per-image maps built on GLM-4V's flat getter; FunASR-Nano's head drops its deletion stub, as Qwen3-ASR's head no longer defines the method. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
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. |
|
|
||
| class FunAsrNanoMultiModalProjector(nn.Module): | ||
| """Projects audio features into the text space and applies the checkpoint's adaptor layers.""" | ||
| class FunAsrNanoMultiModalProjector(FunAsrNanoPreTrainedModel): |
There was a problem hiding this comment.
TRF055 — TRF055: generated modeling_fun_asr_nano.py:357: 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.
Why this matters
PreTrainedModel derives config_class from the config annotation. An assignment or a hand-written config_class keeps or drifts from the parent's, and a mismatched __init__ builds the model from one config while it advertises another.
class Gemma4VisionModel(Gemma4PreTrainedModel):
"""The Gemma 4 Vision Encoder."""
- config = Gemma4VisionConfig
+ config: Gemma4VisionConfig
- def __init__(self, config):
+ def __init__(self, config: Gemma4VisionConfig):Suppress with # trf-ignore: TRF055 if intentional.
| self.config = config.adaptor_config | ||
| self.post_init() | ||
|
|
||
| def forward( |
There was a problem hiding this comment.
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.
Why this matters
Without it, the class and its methods ship without parameter, return and example documentation, which then has to be written by hand for each model.
+@auto_docstring
@dataclass
class AcmeModelOutputWithPast(ModelOutput):
logits: torch.Tensor | None = None
+@auto_docstring
class AcmeForConditionalGeneration(AcmePreTrainedModel):
+ @auto_docstring
def forward(self, input_ids, pixel_values=None, **kwargs):
...Suppress with # trf-ignore: TRF057 if intentional.
…on at init As set_attn_implementation already does. FunASR-Nano's adaptor layers were built from such a config and ran eager with a warning on every call; its projector goes back to a plain module, which the modeling structure and repository checks expect. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nkling2's cu_seqlens device; skip what can't trace - Models without packed encoders run in fp32 (atol=rtol=1e-4), packed ones in bf16 (2e-2, one rounding step), built in that dtype so fp32-kept modules (MoE routers) stay so. set_attn_implementation is only called with packed encoders, as it re-applies the top-level implementation to sub-models whose config isn't a sub-config. - Inkling2's vision tower kept cu_seqlens on CPU, which flash attention rejects with or without compile. - Skipped with their reasons: Step3p7 (experts opt out of use_experts_implementation), Apertus1.5 vision and audio (items tokenized one by one at their own size), GLM-Image (per-image feature maps sized on the host). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… data-dependent-inputs
|
[For maintainers] Suggested jobs to run (before merge) run-slow: apertus1p5, audioflamingo3, cohere_compass, cosmos3_edge, cosmos3_omni, deepseek_ocr2, dots3_note, emu3, ernie4_5_vl_moe, exaone4_5, fun_asr_nano, glm46v, glm4v, glm4v_moe, glm5_next, glm_image |
|
most models are the same mechanical change (the forward's helpers take the precomputed value from kwargs or compute it,
|
What does this PR do?
Stacked on #50733 (flat
get_image_embeddings/get_video_embeddings/get_audio_embeddings).Many encoders compute part of their inputs with data-dependent operations:
cu_seqlensand window indices fromgrid_thw, rotary positions, interpolation sizes, packing indices. These come from host syncs (.tolist(),.item()) and loops over items, sotorch.compile(fullgraph=True)breaks andtorch.exportcan't trace the encoder.This adds
get_data_dependent_inputs: a model method that returns those inputs, computed outside the forward. Passed back to the forward, they make the whole forward traceable withfullgraph=True.MultimodalMixingives the model and head a default that delegates to the base model ({}when it has none)image_,video_,audio_), as its getters take themget_vision_cu_seqlens,get_vision_position_ids, ...) take the precomputed value from kwargs or compute it, andget_data_dependent_inputsmakes the same callsgenerateprepare_inputs_for_generationModels
The models that now define
get_data_dependent_inputs, and what each one moves out of its forward. Their forwards read the precomputed value when it is passed and still compute it otherwise, so calling them without it works as before.cu_seqlens,max_seqlen, rotaryposition_ids, window indices, interpolation tapsmerge_indeximage_newline; LLaVA-OneVision's anyres-max downscale as bilinear taps), soget_image_embeddingshas no loop over imagesget_vision_interpolation_indices_and_weights(gainsresize_to_longest_side), cls / register tokens and the pixel shuffle as gathers (get_vision_pixel_shuffle_index, moved tovision_utils)get_vision_interpolation_indices_and_weightsgainsantialias, matchingF.interpolate(antialias=True))position_idson the prompt tooimage_token_index: each image's crop of the VQ token grid to itsimage_sizes, as a gather over the uncropped gridssplit(tolist()),pad_sequenceand a boolean maskAlong the way: GLM-5-Next and Qwen4-exp's vision towers support flash attention; FunASR-Nano's adaptor owns its config, so it gets an attention implementation; RADIO declares its image modality;
select_hidden_statesfinds its selection argument once instead ofSignature.bindper call; TIPSv2's text pooling no longer upcasts bf16 to fp32; Nemotron-H Omni no longer reads the deprecatedconfig.torch_dtype, whose warning broke the graph.Exporters
prepare_for_exportprecomputes these inputs through the model's ownget_data_dependent_inputs. This replaces the exporters' registry of per-encoder preparers (grid_thwtowers, NaViTtarget_sizes,image_sizes, the Omni and Qwen3-ASR audio encoders) and itsget_rope_indexprobe, about 245 lines.Exports this enables, which were skipped:
torch.exporttests passgenerate.dynamicskip: the merged decode doesn't grow its indexer's padding mask)static-cacheskip: its decode recomputes M-RoPE from the cache length)The first four join the exporter's chunked vision attention patch, which now also finds an
o_projand ascale.Still failing or skipped:
(1, heads, T, dim)states andnum_attention_heads, which the chunked attention patch doesn't handle yetpixel_valuesandimage_sizes, without the precomputed inputs it was traced with (as with the registry)Test
test_model_forward_compile_fullgraph_with_data_dependent_inputscompiles the whole forward withfullgraph=Trueon these inputs and checks it matches eager. Packed encoders, those owning a module that takescu_seqlens(get_packed_inputs_encoders), run flash attention in bf16 (atol=rtol=2e-2), whose varlen path takes the precomputedcu_seqlens; SDPA would loop over their items on the host. Models without any run in fp32 with their default attention (atol=rtol=1e-4). There is no official way yet for users to know which encoders are packed; the test reads it from the modules' signatures.nonzerouse_experts_implementation(@no_inherit_decorator), so the eager loop over the experts hit runsFixed along the way: Inkling2's vision tower kept
cu_seqlenson CPU, so flash attention failed with or without compile.Breaking
resize_positional_embeddings(static method)Follow-ups
🤖 Generated with Claude Code
🤖 mlinter review state
c639078b8a6cf74cget_data_dependent_inputs: compute a forward's data-dependent inputs outside it #50887 (review)