Skip to content
Open
Show file tree
Hide file tree
Changes from 29 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
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
131 changes: 69 additions & 62 deletions src/transformers/models/cosmos3_edge/modeling_cosmos3_edge.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
# limitations under the License.
import itertools
from collections.abc import Callable
from typing import Any

import torch
import torch.nn as nn
import torch.nn.functional as F

from ...activations import ACT2FN
from ...cache_utils import Cache, DynamicCache
Expand Down Expand Up @@ -51,7 +51,7 @@
merge_with_config_defaults,
)
from ...utils.output_capturing import capture_outputs
from ...vision_utils import get_vision_attention_seqlens
from ...vision_utils import get_vision_attention_seqlens, get_vision_interpolation_indices_and_weights
from .configuration_cosmos3_edge import Cosmos3EdgeConfig, Cosmos3EdgeTextConfig, Cosmos3EdgeVisionConfig


Expand Down Expand Up @@ -357,74 +357,28 @@ def __init__(self, config: Cosmos3EdgeVisionConfig):
self.position_embedding_size = int(self.num_patches**0.5)
self.position_embedding = nn.Embedding(self.num_patches, self.embed_dim)

@staticmethod
def resize_positional_embeddings(
positional_embeddings: torch.Tensor,
grid_thw: torch.LongTensor,
spatial_merge_size: int,
) -> torch.Tensor:
"""Resize a learned reference grid independently for every packed image or video frame.

Args:
positional_embeddings (`torch.Tensor`):
Learned positional embeddings of shape `(height, width, hidden_size)`.
grid_thw (`torch.LongTensor`):
Temporal, height, and width patch-grid dimensions for every packed image or video.
spatial_merge_size (`int`):
Number of patches merged along each spatial axis by the projector.

Returns:
`torch.Tensor`: Positional embeddings packed in the same block-major order as the input patches.
"""
# The checkpoint uses a learned square reference grid, interpolated independently for every packed frame.
positional_embeddings = positional_embeddings.permute(2, 0, 1).unsqueeze(0)
source_dtype = positional_embeddings.dtype
# Upcast to float32 on CPU because antialias is not supported for bfloat16/float16 on CPU.
if positional_embeddings.device.type == "cpu":
positional_embeddings = positional_embeddings.float()

position_chunks = []
for temporal, height, width in grid_thw.tolist():
resized_embeddings = F.interpolate(
positional_embeddings,
size=(height, width),
mode="bilinear",
align_corners=False,
antialias=True,
)
resized_embeddings = resized_embeddings.squeeze(0).permute(1, 2, 0).to(source_dtype)
resized_embeddings = resized_embeddings.reshape(
height // spatial_merge_size,
spatial_merge_size,
width // spatial_merge_size,
spatial_merge_size,
-1,
)
# Preserve the processor's block-major 2x2 patch order before the projector groups adjacent patches.
resized_embeddings = resized_embeddings.transpose(1, 2).reshape(height * width, -1)
position_chunks.append(resized_embeddings.repeat(temporal, 1))

return torch.cat(position_chunks, dim=0)

def forward(self, pixel_values: torch.Tensor, grid_thw: torch.LongTensor) -> torch.Tensor:
def forward(self, pixel_values: torch.Tensor, grid_thw: torch.LongTensor, **kwargs) -> torch.Tensor:
"""
Args:
pixel_values (`torch.Tensor`):
Pixel values of shape (batch_size, max_num_patches, num_channels * patch_size * patch_size)
spatial_shapes (`list[tuple[int, int]]`):
Spatial shapes of shape (batch_size, 2) to resize the positional embeddings to
Packed patches of shape (num_patches, num_channels * patch_size * patch_size)
grid_thw (`torch.LongTensor`):
The temporal, height and width patch grid of every packed image or video, of shape (num_grids, 3)
"""
# Apply patch embeddings to already patchified pixel values.
target_dtype = self.patch_embedding.weight.dtype
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype))

# Get image-specific positional embeddings in the packed block-major order expected by the checkpoint.
positional_embeddings = self.position_embedding.weight.reshape(
self.position_embedding_size, self.position_embedding_size, -1
)
position_embeddings = self.resize_positional_embeddings(
positional_embeddings, grid_thw, self.config.spatial_merge_size
# The learned square table resized to every packed frame (antialiased bilinear), in the block-major patch order
interp_indices, interp_weights = get_vision_interpolation_indices_and_weights(
grid_thw,
self.position_embedding_size,
spatial_merge_size=self.config.spatial_merge_size,
antialias=True,
kwargs=kwargs,
)
table = self.position_embedding.weight
position_embeddings = (table[interp_indices].float() * interp_weights[..., None]).sum(1).to(table.dtype)
torch_compilable_check(
patch_embeds.shape[0] == position_embeddings.shape[0],
"The packed visual patch count does not match `grid_thw`.",
Expand Down Expand Up @@ -729,6 +683,23 @@ def __init__(self, config: Cosmos3EdgeVisionConfig):
self.post_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
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 attention's `cu_seqlens` and
`max_seqlen`, and the position table's `interp_indices` and `interp_weights`."""
cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs)
interp_indices, interp_weights = get_vision_interpolation_indices_and_weights(
grid_thw,
self.embeddings.position_embedding_size,
spatial_merge_size=self.config.spatial_merge_size,
antialias=True,
)
return {
"cu_seqlens": cu_seqlens,
"max_seqlen": max_seqlen,
"interp_indices": interp_indices,
"interp_weights": interp_weights,
}

@merge_with_config_defaults
@capture_outputs(tie_last_hidden_states=False)
@auto_docstring
Expand All @@ -737,7 +708,7 @@ def forward(self, pixel_values: torch.Tensor, grid_thw: torch.LongTensor, **kwar
grid_thw (`torch.LongTensor` of shape `(num_images_or_videos, 3)`):
The temporal, height, and width patch-grid dimensions for each packed image or video.
"""
hidden_states = self.embeddings(pixel_values, grid_thw)
hidden_states = self.embeddings(pixel_values, grid_thw, **kwargs)
hidden_states = self.encoder(hidden_states, grid_thw=grid_thw, **kwargs)
last_hidden_state = self.post_layernorm(hidden_states)
return BaseModelOutputWithPooling(last_hidden_state=last_hidden_state, pooler_output=last_hidden_state)
Expand Down Expand Up @@ -1009,6 +980,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