Repository navigation
🚨 Modeling changes for export, compile, and hybrid-attention standardization - #46738
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. |
| def create_recurrent_padding_mask( | ||
| config: PreTrainedConfig, | ||
| inputs_embeds: torch.Tensor, | ||
| attention_mask: torch.Tensor | None, | ||
| past_key_values: Cache | None = None, | ||
| **kwargs, | ||
| ) -> torch.Tensor | None: | ||
| """Return the 2D padding mask for mamba / linear-attention layers, or ``None`` if not needed. | ||
|
|
||
| Returns ``None`` when the input mask is missing, is already a custom 4D attention mask (no 2D | ||
| padding signal), or when the recurrent state already covers past tokens (cached forwards). | ||
| Otherwise pads the mask to ``past_key_values.max_cache_len`` under a compileable cache so its | ||
| shape is constant across decode steps — the consumer slices back to its local sequence length. | ||
| """ | ||
| if attention_mask is None or attention_mask.ndim != 2: | ||
| return None | ||
| if past_key_values is not None and past_key_values.has_previous_state(): | ||
| return None | ||
| if past_key_values is None or not past_key_values.is_compileable: | ||
| return attention_mask | ||
| pad_amount = past_key_values.max_cache_len - attention_mask.shape[-1] | ||
| return F.pad(attention_mask, (0, pad_amount)) if pad_amount > 0 else attention_mask |
vasqu
left a comment
There was a problem hiding this comment.
Ok my review is a bit split between this and the exporter PR (sorrry!!). The models mostly start after this comment in the other PR #41992 (comment)
I would love to run slow tests just to make sure we really didnt break anything
- big_bird
- bigbird_pegasus
- canine
- clap
- clvp
- donut_swin
- maskformer_swin
- minicpmv4_6
- paddleocr_vl
- patchtsmixer
- prophetnet
- reformer
- sam2
- sew
- swin
- video_llava
Re the masks, super happy with it :D I would like to make this a bit more involved and create layer types that are not just linear attention / mamba but are fused but with identity: So linear_attention_{type}, e.g. linear_attention_mamba2. This allows us to map to anything starting with linear_attention_* to the same while keeping proper unique identities which is highly needed! (e.g. for other libraries to properly patch and exchange layers such as vllm)
| # Alias used by hybrid mamba/attention models (jamba, bamba, falcon_h1, granitemoehybrid, nemotron_h). | ||
| "attention": create_causal_mask, | ||
| # Non-attention layers — they consume the raw 2D padding mask. We pad it to a stable length | ||
| # so its shape is constant under a compileable cache; the consumer slices back to the local seq. | ||
| "mamba": create_recurrent_padding_mask, | ||
| "linear_attention": create_recurrent_padding_mask, |
There was a problem hiding this comment.
Not on you but this convention is bad and we should change it so we can have a sense on what is the actual underlying layer type. Wdyt about
linear_attention_(mamba|mamba2|gated_delta_net|minimax|...)- change "attention" to the normal mapping
The mapping should then seek the recurrent padding mask under anything that starts with linear_attention but it still allows to have each one to have its own identity.
I know this will be breaking in a way but I think we should start doing this as we should show people the different types while making it easier for us
There was a problem hiding this comment.
done ! added some legacy remapping as well just in case
|
run-slow: big_bird, bigbird_pegasus, canine, clap, clvp, donut_swin, maskformer_swin, minicpmv4_6, paddleocr_vl, patchtsmixer, prophetnet, reformer, sam2, sew, swin, video_llava |
|
This comment contains models: ["models/big_bird", "models/bigbird_pegasus", "models/canine", "models/clap", "models/clvp", "models/minicpmv4_6", "models/paddleocr_vl", "models/patchtsmixer", "models/prophetnet", "models/reformer", "models/sam2", "models/sew", "models/swin", "models/video_llava"] |
|
slow tests are good, there are some relevant failures in fast ci, fixing them now |
# Conflicts: # src/transformers/cache_utils.py
vasqu
left a comment
There was a problem hiding this comment.
Ok some initial comments from my side, mostly to align the new layer types stuff a bit more. We need to add 🚨 + I think we also need to check minimax (1) as it's also linear attention.
Other than that, looks like CI is failing a bit + @ArthurZucker will take a look next week because this is quite important (for other future models as well)!
There was a problem hiding this comment.
Pull request overview
This PR makes broad modeling and test updates across the Transformers codebase to improve exportability (ONNX / torch.export / ExecuTorch), fullgraph torch.compile compatibility, and standardize hybrid / recurrent (“linear_attention”) layer-type + mask/caching behavior across many model families.
Changes:
- Standardizes hybrid/recurrent layer-type naming (
linear_attention/full_attention) with legacy config remapping, and centralizes recurrent-mask construction viacreate_recurrent_attention_mask+create_masks_for_generate-style dispatch. - Refactors multiple model implementations to be more compile/export-friendly (vectorized masks, removal of data-dependent Python control flow, attention backend dispatch standardization).
- Updates generation/masking/model tests and adds checkpoint conversion mappings to keep backwards compatibility with existing Hub checkpoints.
Reviewed changes
Copilot reviewed 152 out of 152 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| tests/utils/test_masking_utils.py | Updates unmapped-layer-type test to use moe as the canonical “unmapped” example. |
| tests/test_modeling_common.py | Removes exporter-time monkeypatching for legacy _update_*_mask helpers. |
| tests/models/patchtsmixer/test_modeling_patchtsmixer.py | Uses ModelOutput.to_tuple() for correct tuple equivalence semantics (drops None). |
| tests/models/moshi/test_modeling_moshi.py | Adjusts tests for unified ALL_ATTENTION_FUNCTIONS dispatch and adds required extra inputs. |
| tests/models/granitemoeshared/test_modeling_granitemoeshared.py | Aligns test config intermediate_size for grouped-mm alignment. |
| tests/models/granitemoehybrid/test_modeling_granitemoehybrid.py | Updates attention-only layer-type string to full_attention. |
| tests/models/granitemoe/test_modeling_granitemoe.py | Aligns test config intermediate_size for grouped-mm alignment. |
| tests/models/blt/test_modeling_blt.py | Adds targeted test skips for known BLT generation/cache limitations. |
| tests/generation/test_utils.py | Relaxes/gates certain generation compilation assertions for hybrid/recurrent caches and attention outputs. |
| src/transformers/vision_utils.py | Adds NaViT-style precompute helpers (get_vision_nearest_position_ids, get_vision_merged_shape). |
| src/transformers/models/zoedepth/modeling_zoedepth.py | Uses .clamp(min=..., max=...) style for export-friendly clamping. |
| src/transformers/models/zamba2/modular_zamba2.py | Stores per-layer layer_type on modules (standardization). |
| src/transformers/models/zamba2/modeling_zamba2.py | Stores per-layer layer_type on modules (standardization). |
| src/transformers/models/zamba2/configuration_zamba2.py | Remaps legacy layer-type strings and updates default to linear_attention naming. |
| src/transformers/models/zamba/modeling_zamba.py | Stores per-layer layer_type on modules (standardization). |
| src/transformers/models/zamba/configuration_zamba.py | Updates layer-type list generation to linear_attention naming. |
| src/transformers/models/xlstm/modeling_xlstm.py | Makes cache position counter tensor-based for compile/export friendliness. |
| src/transformers/models/vitdet/modeling_vitdet.py | Simplifies window partition/unpartition padding math and reshapes. |
| src/transformers/models/videoprism/modular_videoprism.py | Uses + 1.0 for export-friendly constant handling in LayerNorm weight expression. |
| src/transformers/models/videoprism/modeling_videoprism.py | Uses + 1.0 for export-friendly constant handling in LayerNorm weight expression. |
| src/transformers/models/video_llava/modeling_video_llava.py | Flattens video/image feature tensors before placeholder consistency checks. |
| src/transformers/models/univnet/modeling_univnet.py | Simplifies bias add and reshape path in location-variable convolution. |
| src/transformers/models/umt5/modeling_umt5.py | Adds compile-friendly checks for <eos> presence before reshaping selected tokens. |
| src/transformers/models/timesfm/modular_timesfm.py | Makes negative truncation export/compile-friendlier via torch.where gating. |
| src/transformers/models/timesfm/modeling_timesfm.py | Makes negative truncation export/compile-friendlier via torch.where gating. |
| src/transformers/models/t5gemma2/modular_t5gemma2.py | Extends get_encoder() signature to accept modality. |
| src/transformers/models/t5gemma2/modeling_t5gemma2.py | Extends get_encoder() signature to accept modality. |
| src/transformers/models/t5/modeling_t5.py | Adds compile-friendly checks for <eos> presence before reshaping selected tokens. |
| src/transformers/models/swinv2/modeling_swinv2.py | Vectorizes shifted-window cyclic attention-mask generation. |
| src/transformers/models/swin2sr/modeling_swin2sr.py | Vectorizes shifted-window cyclic attention-mask generation; makes mean casting device/dtype explicit. |
| src/transformers/models/swin/modular_swin.py | Vectorizes shifted-window cyclic attention-mask generation. |
| src/transformers/models/swin/modeling_swin.py | Vectorizes shifted-window cyclic attention-mask generation. |
| src/transformers/models/splinter/modeling_splinter.py | Removes Python list concat for question positions; uses vectorized indexing for export/compile. |
| src/transformers/models/smolvlm/modular_smolvlm.py | Uses merge_with_config_defaults + decorator ordering refactor; removes explicit cache/grad-ckpt warning block. |
| src/transformers/models/smolvlm/modeling_smolvlm.py | Uses merge_with_config_defaults + decorator ordering refactor; removes explicit cache/grad-ckpt warning block. |
| src/transformers/models/sew/modular_sew.py | Makes attention-mask pooling export-friendly (max_pool1d) and vectorizes feature-mask construction. |
| src/transformers/models/sew/modeling_sew.py | Makes attention-mask pooling export-friendly (max_pool1d) and vectorizes feature-mask construction. |
| src/transformers/models/sew_d/modeling_sew_d.py | Avoids 4D outer-product masks; export-friendly pooling and simplified alignment logic. |
| src/transformers/models/seamless_m4t/modeling_seamless_m4t.py | Extends get_encoder() signature to accept modality consistently. |
| src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py | Extends get_encoder() signature to accept modality consistently. |
| src/transformers/models/sam2/modular_sam2.py | Simplifies window padding math with single modulo expression. |
| src/transformers/models/sam2/modeling_sam2.py | Simplifies window partition/unpartition and padding math. |
| src/transformers/models/reformer/modeling_reformer.py | Adds torch_compilable_check bounds and uses safe ceil-div arithmetic for axial positions. |
| src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | Fixes get_decoder() to return the actual text model for generation utilities. |
| src/transformers/models/qwen3_next/modular_qwen3_next.py | Standardizes mask dispatch and per-layer type naming; opts into fullgraph compile. |
| src/transformers/models/qwen3_next/modeling_qwen3_next.py | Standardizes mask dispatch and per-layer type naming; opts into fullgraph compile. |
| src/transformers/models/qwen3_next/configuration_qwen3_next.py | Remaps legacy layer-type strings in config post-init. |
| src/transformers/models/qwen3_5/modular_qwen3_5.py | Standardizes mask dispatch and per-layer type naming; opts into fullgraph compile. |
| src/transformers/models/qwen3_5/modeling_qwen3_5.py | Standardizes mask dispatch and per-layer type naming; opts into fullgraph compile. |
| src/transformers/models/qwen3_5/configuration_qwen3_5.py | Remaps legacy layer-type strings in config post-init. |
| src/transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py | Standardizes per-layer type naming (block_type). |
| src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py | Standardizes mask dispatch and per-layer type naming; opts into fullgraph compile. |
| src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py | Remaps legacy layer-type strings in config post-init. |
| src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py | Fixes get_decoder() to return the actual text model for generation utilities. |
| src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | Fixes get_decoder() to return the actual text model for generation utilities. |
| src/transformers/models/prophetnet/modeling_prophetnet.py | Vectorizes ngram_attention_bias and replaces assert with torch_compilable_check. |
| src/transformers/models/pp_formulanet/modular_pp_formulanet.py | Extends get_encoder() signature to accept modality. |
| src/transformers/models/pp_formulanet/modeling_pp_formulanet.py | Extends get_encoder() signature to accept modality. |
| src/transformers/models/pp_doclayout_v2/modular_pp_doclayout_v2.py | Uses mask.int() in argsort for export friendliness. |
| src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py | Uses mask.int() in argsort for export friendliness. |
| src/transformers/models/plbart/modeling_plbart.py | Adds compile-friendly checks for <eos> presence before reshaping selected tokens. |
| src/transformers/models/perceiver/modeling_perceiver.py | Ensures tensors created on correct device for pos transforms / Fourier features. |
| src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py | Replaces pos-encoding interpolation loop with bilinear-index precompute; deprecates interpolate helper. |
| src/transformers/models/paddleocr_vl/modeling_paddleocr_vl.py | Replaces pos-encoding interpolation loop with bilinear-index precompute; deprecates interpolate helper. |
| src/transformers/models/olmo_hybrid/modular_olmo_hybrid.py | Standardizes mask dispatch, layer-type remap, and sets _can_compile_fullgraph = False w/ comment. |
| src/transformers/models/olmo_hybrid/modeling_olmo_hybrid.py | Standardizes mask dispatch and sets _can_compile_fullgraph = False w/ comment. |
| src/transformers/models/olmo_hybrid/configuration_olmo_hybrid.py | Remaps legacy layer-type strings in config post-init. |
| src/transformers/models/nemotron_h/modular_nemotron_h.py | Standardizes layer types and mask dispatch; adds create_masks_for_generate; opts into fullgraph compile. |
| src/transformers/models/nemotron_h/modeling_nemotron_h.py | Standardizes layer types and mask dispatch; adds create_masks_for_generate; opts into fullgraph compile. |
| src/transformers/models/nemotron_h/configuration_nemotron_h.py | Updates docs/validation/defaults to standardized layer-type names and adds legacy remap. |
| src/transformers/models/mvp/modeling_mvp.py | Adds compile-friendly checks for <eos> presence before reshaping selected tokens. |
| src/transformers/models/mt5/modeling_mt5.py | Adds compile-friendly checks for <eos> presence before reshaping selected tokens. |
| src/transformers/models/mlcd/modular_mlcd.py | Removes custom rotary embedding forward; uses position-id based rotary embedding API. |
| src/transformers/models/mlcd/modeling_mlcd.py | Switches rotary embedding to accept explicit position IDs rather than grid sizes. |
| src/transformers/models/minimax/modular_minimax.py | Standardizes per-layer type naming (block_type) and stores layer_type. |
| src/transformers/models/minimax/modeling_minimax.py | Standardizes per-layer type naming (block_type) and stores layer_type. |
| src/transformers/models/mbart/modeling_mbart.py | Adds compile-friendly checks for <eos> presence before reshaping selected tokens. |
| src/transformers/models/maskformer/modeling_maskformer_swin.py | Vectorizes shifted-window cyclic attention-mask generation. |
| src/transformers/models/mamba2/modeling_mamba2.py | Stores layer_type and opts into fullgraph compile. |
| src/transformers/models/mamba2/configuration_mamba2.py | Standardizes layer-type list to linear_attention. |
| src/transformers/models/mamba/modeling_mamba.py | Stores layer_type for standardization. |
| src/transformers/models/mamba/configuration_mamba.py | Standardizes layer-type list to linear_attention. |
| src/transformers/models/lfm2/modular_lfm2.py | Standardizes mask dispatch and stores layer_type. |
| src/transformers/models/lfm2/modeling_lfm2.py | Standardizes mask dispatch and opts into fullgraph compile. |
| src/transformers/models/lfm2_moe/modular_lfm2_moe.py | Standardizes mask dispatch (recurrent vs causal) for conv layers. |
| src/transformers/models/lfm2_moe/modeling_lfm2_moe.py | Standardizes mask dispatch and opts into fullgraph compile. |
| src/transformers/models/layoutlmv2/modeling_layoutlmv2.py | Ensures visual attention mask dtype matches attention mask. |
| src/transformers/models/jamba/modular_jamba.py | Standardizes mask dispatch and stores layer_type; opts into fullgraph compile. |
| src/transformers/models/jamba/modeling_jamba.py | Standardizes mask dispatch and stores layer_type; opts into fullgraph compile. |
| src/transformers/models/jamba/configuration_jamba.py | Updates layer_types mapping to standardized names. |
| src/transformers/models/informer/modular_informer.py | Replaces NumPy usage with math for export-friendly scalar computations. |
| src/transformers/models/informer/modeling_informer.py | Replaces NumPy usage with math for export-friendly scalar computations. |
| src/transformers/models/idefics3/modeling_idefics3.py | Normalizes use_cache defaulting before grad-ckpt compatibility warning. |
| src/transformers/models/idefics2/modeling_idefics2.py | Normalizes use_cache defaulting before grad-ckpt compatibility warning. |
| src/transformers/models/granitemoehybrid/modular_granitemoehybrid.py | Standardizes mask dispatch and layer-type naming; updates hybrid attention forward signature. |
| src/transformers/models/granitemoehybrid/configuration_granitemoehybrid.py | Standardizes default layer types and adds legacy remap. |
| src/transformers/models/granitemoe/modular_granitemoe.py | Refactors MoE router/experts for fullgraph compile and adds weight init updates. |
| src/transformers/models/granite_speech/modeling_granite_speech.py | Refactors 5D→4D attention computation for export friendliness. |
| src/transformers/models/granite_speech_plus/modeling_granite_speech_plus.py | Refactors 5D→4D attention computation for export friendliness. |
| src/transformers/models/git/modeling_git.py | Fixes dtype consistency for token type IDs and attention mask concatenation. |
| src/transformers/models/gemma3n/modular_gemma3n.py | Adds use_cache to config dataclass defaults. |
| src/transformers/models/gemma3n/configuration_gemma3n.py | Adds use_cache to config defaults. |
| src/transformers/models/funnel/modeling_funnel.py | Removes Python len() on tensor; uses shape[0] for trace friendliness. |
| src/transformers/models/flava/modeling_flava.py | Fixes masking logic and corrects tuple-return filtering; fixes logits return ordering. |
| src/transformers/models/falcon_mamba/modular_falcon_mamba.py | Standardizes layer types and fixes buffer registration (no Parameter in buffers). |
| src/transformers/models/falcon_mamba/modeling_falcon_mamba.py | Stores layer_type and fixes buffer registration (no Parameter in buffers). |
| src/transformers/models/falcon_mamba/configuration_falcon_mamba.py | Standardizes layer-type list to linear_attention. |
| src/transformers/models/falcon_h1/modular_falcon_h1.py | Standardizes mask creation and adds create_masks_for_generate; documents fullgraph compile blocker. |
| src/transformers/models/falcon_h1/modeling_falcon_h1.py | Standardizes mask creation and adds create_masks_for_generate; documents fullgraph compile blocker. |
| src/transformers/models/efficientloftr/modeling_efficientloftr.py | Uses tensor divisors for SymInt-friendly % and // under Dynamo. |
| src/transformers/models/edgetam_video/modeling_edgetam_video.py | Simplifies window padding math with single modulo expression. |
| src/transformers/models/dpt/modeling_dpt.py | Avoids len(tensor); uses shape[0] for trace friendliness. |
| src/transformers/models/donut/modeling_donut_swin.py | Switches to copied + vectorized Swin attention-mask computation. |
| src/transformers/models/diffusion_gemma/modeling_diffusion_gemma.py | Extends get_encoder() signature to accept modality. |
| src/transformers/models/dia/modular_dia.py | Replaces squeeze(1) with shape-stable view for tokens. |
| src/transformers/models/dia/modeling_dia.py | Replaces squeeze(1) with shape-stable view for tokens. |
| src/transformers/models/cohere_asr/configuration_cohere_asr.py | Adds use_cache to config defaults. |
| src/transformers/models/clvp/modeling_clvp.py | Vectorizes BOS/EOS padding and speech-decoder output fixing for export friendliness. |
| src/transformers/models/clap/modeling_clap.py | Vectorizes shifted-window cyclic attention-mask generation. |
| src/transformers/models/canine/modeling_canine.py | Fixes molecule attention-mask shape handling and mask creation call. |
| src/transformers/models/bros/modeling_bros.py | Fixes dtype/device consistency when concatenating invalid-token mask sentinel. |
| src/transformers/models/blt/configuration_blt.py | Adds use_cache to config defaults. |
| src/transformers/models/bart/modeling_bart.py | Adds compile-friendly checks for <eos> presence before reshaping selected tokens. |
| src/transformers/models/bamba/modular_bamba.py | Standardizes layer types, mask dispatch, and improves error message; opts into fullgraph compile. |
| src/transformers/models/bamba/modeling_bamba.py | Standardizes layer types, mask dispatch, and improves error message; opts into fullgraph compile. |
| src/transformers/models/bamba/configuration_bamba.py | Standardizes default layers_block_type values to full_attention / linear_attention. |
| src/transformers/models/afmoe/modular_afmoe.py | Simplifies fullgraph compile flag to unconditional True (removes availability check). |
| src/transformers/models/afmoe/modeling_afmoe.py | Simplifies fullgraph compile flag to unconditional True (removes availability check). |
| src/transformers/masking_utils.py | Adds create_recurrent_attention_mask and wires recurrent patterns into mask-dispatch mapping. |
| src/transformers/conversion_mapping.py | Adds conversion mapping entries and weight renames for Granite-MoE family compatibility. |
| src/transformers/configuration_utils.py | Adds legacy layer-type remapping helper and updates allowed layer-type set. |
| src/transformers/cache_utils.py | Updates dynamic/static cache layer-type mapping and improves cache batch-size behavior for uninitialized recurrent caches. |
| docs/source/en/model_doc/qwen3_5.md | Resolves stray merge-conflict artifact in model documentation. |
| docs/source/en/model_doc/pe_video.md | Resolves merge-conflict artifact and restores release/contribution note. |
| docs/source/en/model_doc/pe_audio.md | Resolves merge-conflict artifact and restores release/contribution note. |
| docs/source/en/model_doc/pe_audio_video.md | Resolves merge-conflict artifact and restores release/contribution note. |
| docs/source/en/model_doc/hyperclovax.md | Resolves merge-conflict artifact and restores release/contribution note. |
|
[For maintainers] Suggested jobs to run (before merge) run-slow: afmoe, bamba, bart, big_bird, bigbird_pegasus, blt, bros, canine, clap, clvp, cohere_asr, dia, diffllama, diffusion_gemma, donut, dpt |
…ization (huggingface#46738) * model fixes for export compatibility * add minicpmv vision utils * can compile * make ssms fully compilable * more ssms * address new comments * fast ci fixes * fix minimax * fix the last falcon fast ci failure * cleanup * use can_return_tuple in patchmixer * avoid 5D attention * granite export fix * address modeling comments * update * address more comments, unify linear attention and make more models support full graph compile * style * style * modeling changes for attn impl compatibility * fix * fixes * fix lfm2 conv errors * address most of anton's review comments * address cyril's comments * revert conv rename * simpler modular * keep max_batch_size check * fixes * fix moshi cuda graphs * added layer type class attr in mixers * fix repo * address comments * address comments * Merge branch 'main' into hf-exporters-models * fix merge * claude review findings * docs comments * address comments * style * claude review * small fix caught by copilot
## Purpose ## * Support compatibility with huggingface/transformers#46738 ## Changes ## * Remove custom linearization logic for granitemoe * Rename `DeepseekV3NaiveMoe`, `Glm4MoeNaiveMoe`, `Glm4MoeLiteNaiveMoe`, `GlmMoeDsaNaiveMoe`, and `GraniteMoeParallelExperts` ## Testing ## * `test_linearize_moe` passes Co-authored-by: Claude Opus 4.6 <[email protected]>
* fix(minicpmv4_6): correct get_sliced_grid semantics and tie-break for training parity * feat: add M-RoPE canvas * feat: add minicpmv4_7 with canvas mRoPE; revert minicpmv4_6 * refactor(minicpmv4_7): thin-inherit from minicpmv4_6 * refactor(minicpmv4_7): inherit processor from minicpmv4_6 * Fix canvas M-RoPE: resolve structural token ids from config, reject malformed visual spans, add regression tests * Order target_sizes_mrope by text placeholder order, not modality processing order * Drop stale canvas helper comment that cites a removed function * refactor(minicpmv4_7): drop redundant tp/ep plan rewriting from config __post_init__ * feat(minicpmv4_7): add packed-sequence training support with cu_seqlens * Reuse the shared get_max_seqlen utility in _prepare_packed_attention_kwargs instead of recomputing the packed max length inline * Remove packed-sequence handling from modeling since FA varlen kwargs are expected to come from a user data collator * Drop the unused CONFIG_MAPPING import and reformat so the code-quality gate stops skipping every CI test job * Move all processor classes into the modular file so no cross-model imports remain outside it * Stop numbering video placeholders with local image ids since a video is one temporal sequence and was trained without them * Remove low-value comments in the config class and the dangling video local-id note * Add the MiniCPM-V 4.7 model card and register the model in the doc toc and repo checks * Collapse per-axis canvas position writes into leading-axis slices and drop the input sanity checks the processor already guarantees * Merge vision windows per image so slicing batches with mixed patch grids no longer crash The vectorised merge lifted one (h, w) from target_sizes[0] and reshaped the whole batch against it. MiniCPM-V slicing emits a global thumbnail grid next to the slice grids, and the two differ whenever the image is not square-ish, e.g. 896x448 at max_slice_nums=9 gives [[24, 44], [32, 32], [32, 32]] and the view() raises. Merge each image against its own grid instead, matching the pre-huggingface#46738 behaviour. * Cover the vision window merger with mixed per-image patch grids Pins the token count a slicing batch produces when the thumbnail grid disagrees with the slice grids, and checks that an image merges the same way regardless of what else is packed next to it. * Drop the standalone mrope test module * fix(minicpmv4_7): regenerate modeling from modular * Cover canvas M-RoPE position ids with get_rope_index unit tests * review comments - rope tests are green * Add auto_docstring to the 4.7 model classes and drop the unreachable token-id branch gates (#3) * feat: reimpl mrope (#4) * Pin the canvas M-RoPE layouts with golden position ids Snapshot of the exact (3, batch, seq) coordinates for every layout the processor can emit, taken before refactoring the canvas internals. Verified identical to the pre-review implementation, so the numbers describe intended behaviour rather than the current code. * Return the cached-delta positions while decoding and drop a debug print * Derive the LLM grid from config.downsample_mode instead of counting tokens * Build the canvas from `mm_token_type_ids` and fold the video path into the image one * Let the LLM grid follow the per-call downsample_mode * Group adjacent frames whatever their modality * Drop the unused special_token_ids argument and fix the return-shape docstring * Drop the unreachable grid fallbacks and inline the one-line grid helper * test with bugfix (#5) * Keep the per-sample mrope grids out of tensor stacking and run the merger test on the accelerator * Pad the per-sample mrope grids into one tensor and refresh the video slice-mode token count * Regenerate the processing file so the new property sits where the converter puts it * Point the integration tests at MiniCPM-V-4.7 and refresh the expected generations * first clean-up on processors * modualr, will upstream in a sec on main * fix mrope tests and use shared fn for meshgrid * run fix repo * the missing test * be gone, now we have a test to check it matches * same here, remove - let config set attr to False * trf * delete tests as well * Anton won't like it here... * unnecesary revert * Update docs/source/en/model_doc/minicpmv4_7.md Co-authored-by: Anton Vlasjuk <[email protected]> * Update src/transformers/models/minicpmv4_7/modular_minicpmv4_7.py Co-authored-by: Anton Vlasjuk <[email protected]> * Update src/transformers/models/minicpmv4_7/modular_minicpmv4_7.py Co-authored-by: Anton Vlasjuk <[email protected]> * address comments (#7) * Guard window merger divisibility, rename patch_residual, and fix processor kwargs unpacking * Address review comments * address review comments: validate mm_token_type_ids, forward **kwargs to loss_function, align naming with Qwen VL, and regenerate modular files with pinned ruff (#8) * move _frame_end_idx and _group_visual_frames into MiniCPMV4_7Model (#9) * address review (#10) * unskip test_generate_from_inputs_embeds and test_left_padding_compatibility, which pass as-is * export MiniCPMV4_7VisionModel and register it in the auto model mapping, following Qwen3_5 * return metadata tuples instead of dicts from _group_visual_frames * last commit * CI checks * again, repo check * export * comment --------- Co-authored-by: airlsyn <[email protected]> Co-authored-by: Anton Vlasjuk <[email protected]>
Modeling changes for export, compile, and hybrid-attention standardization
A broad sweep of modeling-side changes that make a large set of models cleanly exportable (ONNX / torch.export / ExecuTorch), fullgraph-compilable, and consistent in how they declare their layer types and build masks/caches. Standalone from the exporter machinery PR — this is the model code side.
What's in here
Hybrid SSM / linear-attention standardization
"linear_attention"layer type inALLOWED_LAYER_TYPES(collapsed from the per-backbone variants iterated on during review). The recurrent backbone is determined byconfig.model_type, so per-layer suffixes were redundant._LEGACY_LAYER_TYPE_REMAP(privatized) —__post_init__remaps legacy Hub config strings ("mamba"→"linear_attention","attention"→"full_attention") transparently so existing checkpoints load unchanged.create_recurrent_padding_maskinmasking_utils.py+LAYER_PATTERN_TO_MASK_FUNCTION_MAPPINGdispatch."linear_attention"and"conv"(lfm2/lfm2_moe short-convolution layers — same recurrent cache shape, different mechanism) are both wired to the recurrent padding mask.causal_mask_mapping[layer_type]pattern applied acrossbamba,granitemoehybrid,nemotron_h,qwen3_5,qwen3_next,olmo_hybrid,jamba,falcon_h1,lfm2,lfm2_moe— replaces the various ad-hoccausal_mask+mamba_mask/linear_attn_maskpatterns with the gemma2-style dispatch. Letsgeneratepre-build a static-size mask dict viacreate_masks_for_generateand pass it straight through (avoids dynamo recompiles on growing 2Dattention_maskunder static-cache compile).Audio / legacy attention dispatch refactor
moshi/mimi/kyutai_speech_to_text/nemotron/diffllamanow use the standardALL_ATTENTION_FUNCTIONS.get_interface(...)dispatch with_supports_sdpa/_supports_flash_attn/_supports_flex_attn/_supports_attention_backendflags set, instead of bespoke per-backend*FlashAttention2/*SdpaAttention/*ATTENTION_CLASSESselectors.diffllamaspecifically: differential attention(softmax(Q1·K1ᵀ) - λ·softmax(Q2·K2ᵀ))·Vis now realized as two standard attention calls sharing Q/K and using the two halves of V. The V-doubling shortcut (Vof shape(B, H, S, 2D)) was slower in practice — asymmetric V trips PyTorch's SDPA backend selector (Flash/cuDNN requirehead_dim_v == head_dim_q) and forces the math kernel. Benchmarked: 2-call is ~30% faster on prefill / training / long-context. Docstring onDiffLlamaAttentionexplains the trap.Granite-MoE family refactor (
granitemoe/granitemoeshared/granitemoehybrid)*MoEblock into*TopKRouter(flatnn.Parameter(num_experts, hidden_size), returnstop_k_index+top_k_weights) +@use_experts_implementation-decorated*Expertswith directgate_up_proj/down_projparameters.expert_size = expert_size.tolist()data-dependent path that blocked fullgraph compile.experts_implementationisgrouped_mm/batched_mm(compilable); eager fallback for users who explicitly opt in.conversion_mapping.pyremaps legacyblock_sparse_moe.input_linear.weight/output_linear.weight/router.layer.weight→ newexperts.gate_up_proj/experts.down_proj/router.weight. Existing IBM Hub checkpoints (ibm/PowerMoE-3b,ibm-granite/granite-4.0-h-tiny, …) load with zero user action.Fullgraph-compile opt-ins
_can_compile_fullgraph = Trueon models whose codepath was verified clean:mamba2,granitemoe,granitemoeshared,granitemoehybrid,lfm2,lfm2_moe, on top of the originalbamba/jamba/nemotron_h/qwen3_5/qwen3_5_moe/qwen3_nextfrom the SSM-compile work. Theis_linear_attention_modeltolerance-relaxation intest_generate_with_static_cachewas verified unnecessary and dropped along with the helper.falcon_h1/zamba2/olmo_hybridremainFalsewith documented blockers in code.Export-friendly modeling rewrites
The bulk of the diff is rewriting modeling code that historically blocked export:
big_bird/bigbird_pegasustorch_bmm_nd/torch_bmm_nd_transposeremoved entirely (torch.matmulhandles arbitrary batch dims natively), 14 call sites inlined.swin/swinv2/sew/sew_d/mlcd/donut_swin/clap/maskformer_swincyclic-shift masks rewritten from Python-loop-over-slice-tuples toarange-based vectorized construction so the graph is static.granite_speech/granite_speech_plusconformer block (eliminates a special branch in the ONNX exporter's SDPA patch).@can_return_tuplerefactor inpatchtsmixer— drops the manualreturn_dictplumbing in 6 sub-classes' forwards.clvp(replaces Python loop withgather+masked_fill).ngram_attention_biasinprophetnet.sew/sew_dattention mask pooling — replaces thetorch.arange(max_encoder_length)indexing (which bakes seq length into the exported ONNX graph) withmax_pool1d.Unsqueeze(None,…)translations),torch_compilable_checkstandardization inreformer, NLLB classifier cast paths, granite_speech masked-fill via strided slice view, audio-model rewrites inclap/clvp/dia, vision rewrites inflava/git/mlcd/sam2/vitdet/efficientloftr/videoprism/paddleocr_vl/minicpmv4_6, etc.Vision utilities
vision_utils.pygainsget_image_patch_grid_thwand related helpers used by MiniCPMV4.6 (and other NaViT-packed vision encoders) to precompute data-dependent vision tensors before export.Test infrastructure
tests/generation/test_utils.py:test_generate_compile_model_forward_fullgraph: skip the "default cache is non-compileable" assertion for models whose defaultDynamicCacheis compileable by construction (fully-recurrent / hybrid SSM —LinearAttentionLayerisis_compileable=True).test_generate_compilation_all_outputs: gateoutput_attentionsonself.has_attentions(Mamba2 doesn't defineattentionson its output)._check_attentions_for_generate: for hybrid static caches, look upget_max_cache_shape()on the first layer that has a real max length — layer 0 may be a linear-attention layer that returns-1.tests/utils/test_masking_utils.py::test_create_masks_for_generate_defers_for_unmapped_layer_types: switched the canonical "unmapped" example from"linear_attention"(now mapped tocreate_recurrent_padding_mask) to"moe"(used by Nemotron-H and intentionally not mapped — MoE is a sub-layer composition, not an attention layer).tests/models/nemotron_h/: 4 hardcoded legacy-name assertions updated to the standardized names.tests/models/granitemoehybrid/:test_attention_only_forward— direct post-constructionconfig.layers_block_type = ["attention"] * Nwas bypassing the remap; updated to["full_attention"] * N.tests/models/blt/: 4 new skips for BLT's hash-embedding / EncoderDecoderCache cross-attention limitations (in line with the existing twoinputs_embedsskips). Tests:test_generate_continue_from_inputs_embeds,test_assisted_decoding_matches_greedy_search_{0_random,1_same},test_assisted_decoding_sample.Small review-comment fixes
== "linear_attention"everywhere instead of.startswith("linear_attention").nemotron_hmtp default["attention", "moe"]→["full_attention", "moe"].smolvlmuses@merge_with_config_defaultsinstead ofuse_cache = use_cache if … else self.config.use_cache.tests/generation/test_utils.py::is_hybrid_mamba_model→is_linear_attention_model(then removed entirely after the tolerance investigation showed the predicate wasn't needed).max_cache_lencomment inbamba.intermediate_size=37→40in granitemoe / granitemoeshared test configs fortorch._grouped_mm16-byte stride alignment.videoprismmodular:+ 1→+ 1.0(avoidprim.devicegraph node).Stats
147 files changed (
+2292 / −3567) — net code reduction despite adding new infrastructure, thanks to dropped helpers and inheritance simplifications.Test commands run
Notes for review
"linear_attention"collapse means existing Hub configs with["mamba", ...]or["linear_attention_*", ...](post-rename) all map to the same name. Legacy remap is unconditional in the model__post_init__— no opt-in flag."conv"is kept as a distinct layer type for lfm2 / lfm2_moe (not folded into"linear_attention") —Lfm2ShortConvis a 1D causal convolution, not an attention mechanism. It happens to share the recurrent cache shape with linear attention, same as"moe"/"mlp"in Nemotron-H share the cache shape without being attention layers.conversion_mapping.pyAPI. No_keys_to_ignore_on_load_missinghacks.swin/swinv2/sew/ etc. are functionally equivalent (verified by existing tests + numerical-equivalence check on saved outputs).🤖 AI-assisted; reviewed and tested end-to-end.
CI recap
Dashboard: View test results in Grafana
Latest run: 28429203342:1
Result:
success| Jobs: 14 | Tests: 73,495 | Failures: 0 | Duration: 7h 17m