Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
7236b16
Encoders: index gathers instead of per-image loops and host syncs
IlyasMoutawwakil Nov 18, 2026
83d5ddd
Add get_data_dependent_inputs
IlyasMoutawwakil Nov 18, 2026
7934c2f
Merge remote-tracking branch 'origin/vision-getters-return-flat' into…
IlyasMoutawwakil Nov 18, 2026
d0a9308
Merge remote-tracking branch 'origin/vision-getters-return-flat' into…
IlyasMoutawwakil Nov 19, 2026
5cd2b3d
Merge remote-tracking branch 'origin/vision-getters-return-flat' into…
IlyasMoutawwakil Nov 19, 2026
7615cc2
Merge remote-tracking branch 'origin/vision-getters-return-flat' into…
IlyasMoutawwakil Nov 20, 2026
bbbb88c
Merge remote-tracking branch 'origin/vision-getters-return-flat' into…
IlyasMoutawwakil Nov 20, 2026
13877b3
Merge remote-tracking branch 'origin/vision-getters-return-flat' into…
IlyasMoutawwakil Nov 22, 2026
58036ce
get_data_dependent_inputs: default on the multimodal mixin, called on…
IlyasMoutawwakil Nov 22, 2026
54297c2
Data-dependent inputs: fix Glm5Next, HunYuan-VL, Ernie and Cosmos3-Ed…
IlyasMoutawwakil Nov 22, 2026
7c36ef7
Merge remote-tracking branch 'origin/vision-getters-return-flat' into…
IlyasMoutawwakil Nov 23, 2026
89ad805
Data-dependent inputs: test the whole forward with fullgraph, make Gr…
IlyasMoutawwakil Nov 23, 2026
02b5739
Merge remote-tracking branch 'origin/vision-getters-return-flat' into…
IlyasMoutawwakil Nov 23, 2026
3ef6286
Idefics2: packed vision encoder and resampler under flash attention
IlyasMoutawwakil Nov 23, 2026
1c84ed2
LLaVA-OneVision: pack image features with precomputed bilinear taps
IlyasMoutawwakil Nov 23, 2026
d6c2473
Molmo2: varlen pooling cross-attention under flash attention; bf16 to…
IlyasMoutawwakil Nov 23, 2026
ec0b0a7
Idefics3, SmolVLM: precompute the real images; mixin default tolerate…
IlyasMoutawwakil Nov 24, 2026
390b4e0
Fullgraph forward test: flash only for packed encoders, padded ones o…
IlyasMoutawwakil Nov 24, 2026
797c126
Fullgraph forward test: get_packed_inputs_encoders returns the packed…
IlyasMoutawwakil Nov 24, 2026
a610113
Data-dependent inputs: M-RoPE positions for Qwen2.5/3-Omni and MiniCP…
IlyasMoutawwakil Nov 24, 2026
f2bc6b9
Qwen2.5/3-Omni: precompute the M-RoPE positions on the prompt only
IlyasMoutawwakil Nov 24, 2026
c044391
FunASR-Nano: the adaptor owns its config, so it gets an attention imp…
IlyasMoutawwakil Nov 24, 2026
e64e3a2
Fullgraph forward test: one attention mapping for standalone and comp…
IlyasMoutawwakil Nov 24, 2026
600f249
Exporters: precompute data-dependent inputs with the model's get_data…
IlyasMoutawwakil Nov 24, 2026
5a025bf
Emu3: precompute the per-image crop of the VQ token grids so get_imag…
IlyasMoutawwakil Nov 24, 2026
d4e64f8
Exporters: unskip the exports the precomputed inputs enable
IlyasMoutawwakil Nov 24, 2026
de5c861
vision_utils: the antialiased kernel is a branch of the per-axis inte…
IlyasMoutawwakil Nov 24, 2026
7663b5a
Qwen3-ASR: drop the head's get_data_dependent_inputs, the mixin's def…
IlyasMoutawwakil Nov 24, 2026
8a6cf74
Merge origin/vision-getters-return-flat into data-dependent-inputs
IlyasMoutawwakil Nov 24, 2026
0687bea
Sub-configs no sub-model owns take the model's attention implementati…
IlyasMoutawwakil Nov 24, 2026
67b55cf
Fullgraph forward test: fp32 unless packed encoders need flash; fix I…
IlyasMoutawwakil Nov 25, 2026
653c92b
Merge remote-tracking branch 'origin/vision-getters-return-flat' into…
IlyasMoutawwakil Nov 25, 2026
357dc8e
Merge remote-tracking branch 'origin/main' into data-dependent-inputs
IlyasMoutawwakil Nov 25, 2026
b9bdcfd
Merge branch 'vision-getters-return-flat' into data-dependent-inputs
IlyasMoutawwakil Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/transformers/exporters/exporter_dynamo.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,14 +396,14 @@ def _to_batched(t):
key_states,
value_states,
is_causal=False,
scale=self.scaling,
scale=getattr(self, "scaling", getattr(self, "scale", None)),
dropout_p=0.0 if not self.training else self.attention_dropout,
enable_gqa=getattr(self, "num_key_value_heads", self.num_heads) != self.num_heads,
)

# (n_seg, heads, seg_len, dim) → (n_seg, seg_len, heads, dim) → (seq, heads*dim).
attn_output = attn_output.transpose(1, 2).reshape(seq_length, -1)
out_proj = self.proj if hasattr(self, "proj") else self.out_proj
out_proj = next(getattr(self, name) for name in ("proj", "out_proj", "o_proj") if hasattr(self, name))
attn_output = out_proj(attn_output)

if needs_batch_restore:
Expand All @@ -427,8 +427,10 @@ def _to_batched(t):
"transformers.models.glm_ocr.modeling_glm_ocr.GlmOcrVisionAttention.forward",
"transformers.models.dots3_note.modeling_dots3_note.Dots3NoteVisionAttention.forward",
"transformers.models.ernie4_5_vl_moe.modeling_ernie4_5_vl_moe.Ernie4_5_VLMoeVisionAttention.forward",
"transformers.models.glm5_next.modeling_glm5_next.Glm5NextVisionAttention.forward",
# Combined `qkv` + optional `(cos, sin)` rotary + `.proj`
"transformers.models.cohere_compass.modeling_cohere_compass.CohereCompassVisionAttention.forward",
"transformers.models.glm_image.modeling_glm_image.GlmImageVisionAttention.forward",
# Asymmetric `qkv` split + `(cos, sin)` rotary + `.proj`
"transformers.models.exaone4_5.modeling_exaone4_5.Exaone4_5_VisionAttention.forward",
# Separate `.q` / `.k` / `.v` + single rotary tensor + `.proj`
Expand All @@ -447,6 +449,11 @@ def _to_batched(t):
"transformers.models.minicpm_ocr.modeling_minicpm_ocr.MiniCPMOcrVisionAttention.forward",
"transformers.models.minicpmv4_6.modeling_minicpmv4_6.MiniCPMV4_6VisionAttention.forward",
"transformers.models.minicpmv4_7.modeling_minicpmv4_7.MiniCPMV4_7VisionAttention.forward",
# Separate `_proj` + `.o_proj`, no rotary (tuple return)
"transformers.models.hunyuan_vl.modeling_hunyuan_vl.HunYuanVLVisionAttention.forward",
"transformers.models.hy_v4_vl.modeling_hy_v4_vl.HYV4VLVisionAttention.forward",
# Separate `_proj` + `.out_proj`, no rotary (single return)
"transformers.models.cosmos3_edge.modeling_cosmos3_edge.Cosmos3EdgeVisionAttention.forward",
# Audio attention: separate `_proj` + `.out_proj`, no rotary
"transformers.models.qwen2_5_omni.modeling_qwen2_5_omni.Qwen2_5OmniAudioAttention.forward",
"transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe.Qwen3OmniMoeAudioAttention.forward",
Expand Down
258 changes: 8 additions & 250 deletions src/transformers/exporters/utils.py

Large diffs are not rendered by default.

10 changes: 9 additions & 1 deletion src/transformers/generation/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -779,6 +779,14 @@ def prepare_inputs_for_generation(
elif key not in model_inputs:
model_inputs[key] = value

# 6. The forward's data-dependent inputs, computed with the prompt's; those already laid out are kept
get_data_dependent_inputs = getattr(self, "get_data_dependent_inputs", None)
if get_data_dependent_inputs is not None and (is_first_iteration or not kwargs.get("use_cache", True)):
data_dependent_inputs = get_data_dependent_inputs(**model_inputs)
model_inputs.update(
{key: value for key, value in data_dependent_inputs.items() if key not in model_inputs}
)

# BC for remote code models only: create `cache_position` on the fly here, as we don't want to maintain them in kwargs
# between `forward`s
if self.is_remote_code() and "cache_position" in set(inspect.signature(self.forward).parameters):
Expand All @@ -791,7 +799,7 @@ def prepare_inputs_for_generation(
cache_position = torch.arange(sequence_length, device=input_ids.device) + past_seen_tokens
model_inputs["cache_position"] = cache_position

# 6. Move the tensors the forward consumes onto the model device, right before the call.
# 7. Move the tensors the forward consumes onto the model device, right before the call.
# It lets the caller intentionally keep inputs on a different device (e.g. Neuron/TPU) so
# the generation loop's growing-tensor bookkeeping stays off-device.
input_tensor = model_inputs.get("inputs_embeds", model_inputs[input_ids_key]) # input_ids is None for embeds
Expand Down
13 changes: 12 additions & 1 deletion src/transformers/modeling_multimodal_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import copy
import functools
from typing import Any

import torch

Expand Down Expand Up @@ -55,10 +56,11 @@ class MultimodalMixin:
"""
`get_image_features`, `get_video_features` and `get_audio_features` from a model's flat `get_image_embeddings`,
`get_video_embeddings` and `get_audio_embeddings`, split per item by the `split_sizes` they return. A model with a
head reaches its base model's.
head reaches its base model's getters and `get_data_dependent_inputs`.
"""

model: "MultimodalMixin"
base_model: "MultimodalMixin"

def _base_model_getter(self, name: str):
# Only a head has a base model to reach: a base model without its own getter takes no such input
Expand Down Expand Up @@ -90,6 +92,15 @@ def get_audio_features(self, *args, **kwargs):
"""Each audio's features, from `get_audio_embeddings`."""
return split_modality_outputs(self.get_audio_embeddings(*args, return_dict=True, **kwargs))

def get_data_dependent_inputs(self, **kwargs) -> dict[str, Any]:
"""The inputs the forward computes with data-dependent ops (host syncs, loops over images). Passed back to it,
they keep it traceable by `torch.compile(fullgraph=True)` and `torch.export`. None unless the model computes
some."""
base_model = self.base_model
if base_model is self or not hasattr(base_model, "get_data_dependent_inputs"):
return {}
return base_model.get_data_dependent_inputs(**kwargs)


def merge_modality_outputs(outputs):
"""Concatenates per-item outputs back into the flat layout of `get_*_embeddings`."""
Expand Down
12 changes: 12 additions & 0 deletions src/transformers/modeling_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1335,6 +1335,18 @@ def post_init(self):
if ignore_save := getattr(module, "_keys_to_ignore_on_save", None):
self._keys_to_ignore_on_save.update({f"{name}.{k}" for k in ignore_save})

# A sub-config no sub-model owns (its layers are built from it directly) takes this model's attention
# implementation, as `set_attn_implementation` does, instead of none at all
owned_configs = {id(module.config) for module in self.modules() if isinstance(module, PreTrainedModel)}
for sub_config_key in self.config.sub_configs:
sub_config = getattr(self.config, sub_config_key, None)
if (
isinstance(sub_config, PreTrainedConfig)
and id(sub_config) not in owned_configs
and sub_config._attn_implementation_internal is None
):
sub_config._attn_implementation_internal = self.config._attn_implementation

# Maybe initialize the weights and tie the keys
self.init_weights()
self._backward_compatibility_gradient_checkpointing()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,7 @@ def forward(
audio_embeds = None
if input_features is not None and input_ids is not None:
audio_embeds = self.get_audio_embeddings(
input_features, input_features_mask, return_dict=True
input_features, input_features_mask, return_dict=True, **kwargs
).pooler_output

# replace text-audio token placeholders with audio embeddings
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ def forward(
audio_embeds = None
if input_features is not None and input_ids is not None:
audio_embeds = self.get_audio_embeddings(
input_features, input_features_mask, return_dict=True
input_features, input_features_mask, return_dict=True, **kwargs
).pooler_output

# replace text-audio token placeholders with audio embeddings
Expand Down
59 changes: 59 additions & 0 deletions src/transformers/models/cohere_compass/modeling_cohere_compass.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import itertools
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any

import torch
import torch.nn as nn
Expand Down Expand Up @@ -901,6 +902,28 @@ def __init__(self, config: CohereCompassVisionConfig, *inputs, **kwargs) -> None

self.post_init()

def get_data_dependent_inputs(self, grid_thw: torch.Tensor, **kwargs) -> dict[str, Any]:
"""What the forward derives from `grid_thw` with data-dependent ops: the position embedding's `interp_indices`
and `interp_weights`, the rotary `position_ids` of the patches, and the attention's `cu_seqlens` and
`max_seqlen`."""
interp_indices, interp_weights = get_vision_interpolation_indices_and_weights(
grid_thw,
num_grid_per_side=self.num_grid_per_side,
mode=self.interpolation_mode,
align_corners=self.interpolation_align_corners,
spatial_merge_size=self.config.spatial_merge_size,
kwargs=kwargs,
)
position_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size, kwargs=kwargs)
cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs)
return {
"interp_indices": interp_indices,
"interp_weights": interp_weights,
"position_ids": position_ids,
"cu_seqlens": cu_seqlens,
"max_seqlen": max_seqlen,
}

@merge_with_config_defaults
@capture_outputs
def forward(
Expand Down Expand Up @@ -1189,6 +1212,42 @@ def get_placeholder_mask(
)
return special_image_mask, special_video_mask

def get_data_dependent_inputs(
self,
input_ids: torch.LongTensor | None = None,
attention_mask: torch.Tensor | None = None,
image_grid_thw: torch.LongTensor | None = None,
video_grid_thw: torch.LongTensor | None = None,
mm_token_type_ids: torch.IntTensor | None = None,
position_ids: torch.LongTensor | None = None,
**kwargs,
) -> dict[str, Any]:
"""What the forward derives from the processor's outputs with data-dependent ops: the M-RoPE
`position_ids`, the vision tower's inputs (see
[`Qwen2VisionTransformerPretrainedModel.get_data_dependent_inputs`]) prefixed `image_` and `video_`, as
`get_image_embeddings` and `get_video_embeddings` take them."""
inputs = {}
for prefix, grid_thw in (("image_", image_grid_thw), ("video_", video_grid_thw)):
if grid_thw is not None:
tower_inputs = self.get_encoder(modality="image").get_data_dependent_inputs(grid_thw)
inputs.update({prefix + name: value for name, value in tower_inputs.items()})
has_vision = image_grid_thw is not None or video_grid_thw is not None
if position_ids is None and input_ids is not None and mm_token_type_ids is not None and has_vision:
vision_position_ids, _ = self.get_rope_index(
input_ids,
image_grid_thw=image_grid_thw,
video_grid_thw=video_grid_thw,
attention_mask=attention_mask,
mm_token_type_ids=mm_token_type_ids,
)
if attention_mask is not None:
text_position_ids = (attention_mask.long().cumsum(-1) - 1).masked_fill(attention_mask == 0, 0)
else:
text_position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).expand_as(input_ids)
# The text positions first: the text model builds the attention mask from them
inputs["position_ids"] = torch.cat([text_position_ids[None], vision_position_ids], dim=0)
return inputs

@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
def compute_3d_position_ids(
self,
Expand Down
Loading
Loading