Skip to content

🚨 Multimodal getters: flat get_*_embeddings under the per-item ones, removing the host sync every multimodal forward pays today - #50733

Open
IlyasMoutawwakil wants to merge 65 commits into
mainfrom
vision-getters-return-flat
Open

IlyasMoutawwakil wants to merge 65 commits into
mainfrom
vision-getters-return-flat

Conversation

@IlyasMoutawwakil

@IlyasMoutawwakil IlyasMoutawwakil commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

What does this PR do?

🚨 Breaking: the per-item getters' outputs change for some models (see the Breaking table below), and per-item mm_encoder_outputs are deprecated, to be removed in v5.29.

Every multimodal forward on main pays a host sync for nothing. get_image_features / get_video_features split the encoder output per item with sizes read through .tolist(), and the forward concatenates the pieces straight back for masked_scatter. This PR removes that round trip from 110 multimodal models (vision, video and audio), in eager, torch.compile, export and generate:

main This PR
host sync per forward, just to split and re-concatenate the features yes, in every multimodal model 🟢 none
torch.compile of the image encoder (Qwen2-VL-2B) 2 graphs, 3 breaks 🟢 1 graph, 0 breaks
torch.compile(dynamic=True) on 4, 2, 5, 3 images 5 graphs (recompiles on the image count) 🟢 1 graph
peak memory, LLaVA-OneVision-7B, 8 × 1344² images a second copy of all features through the language model 🟢 −402 MiB prefill, −404 MiB generate
generate with beams per-item lists, host sync to regroup 🟢 one gather, no sync
getter outputs across models lists, stacked tensors, padded tensors depending on the model 🟢 one layout everywhere: flat rows + split_sizes
audio getters padding left in or removed in forward, depending on the model 🟢 one row per audio token, checked for every audio model

It is also what makes the whole multimodal forward compile with fullgraph=True in #50887.

How: a flat level under the per-item getters, which forwards and generate use:

Getter Returns Defined by
get_image_embeddings / get_video_embeddings / get_audio_embeddings (new) all items' features as one tensor, plus split_sizes (rows per item) each model
get_image_features / get_video_features / get_audio_features the same, split per item MultimodalMixin, from the flat getter

Measured on an A100, bf16: Qwen2-VL-2B's image encoder with flash attention and its vision inputs precomputed (latency unchanged), and LLaVA-OneVision-Qwen2-7B on 1344² images, where the language model sets the peak.

Changes

Where Change
modeling_multimodal_utils (new) MultimodalMixin: per-item getters from the flat ones, heads reach their base model's, only for the modalities in input_modalities (so hasattr(model, ...) tells which inputs a model takes); flatten_items; @merge_mm_encoder_outputs, which still accepts per-item mm_encoder_outputs in forwards, with a deprecation warning
BaseModelOutputWithSplitSizes (new) BaseModelOutputWithPooling plus split_sizes, for multimodal encoder outputs only: the flat getters return it, and the multimodal outputs (deepstack, Q-Former, VQ-VAE, ...) inherit from it
~80 VLMs, ~22 audio-in-text models flat getters; the forwards drop their split / torch.cat, and audio padding stripping moves into the getter. Video getters that go through the image path delegate to it (Qwen2-VL family, Molmo2, MiniCPM-V, ...)
generate encodes with the flat getters; beam search repeats each sample's rows and split_sizes with one gather, no host sync. A _placeholder_token_id hook replaces the GLM-4V family, Nemotron-H Omni and Granite 4 Vision expansion overrides
deprecation per-item mm_encoder_outputs passed to forwards or generate, to be removed in v5.29
modular converter a base listed again in a modular class is kept, not swapped for another base with the same suffix (GenerationMixin / MultimodalMixin)

Not on the mixin: CTC / streaming audio encoders, GLM-Image (its features are image-tokenizer feature maps), BLIP-family and CLIP-like models, SAM-family get_image_embeddings (unrelated).

Breaking

What Before After
get_image_features of models that returned one [num_images, num_tokens, hidden] tensor (PaliGemma, Gemma3, LLaVA without image_sizes, ...) a tensor a tuple of [num_tokens, hidden] (indexes and iterates the same)
Idefics2, Idefics3, SmolVLM get_image_features one entry per sample one entry per image
audio models' get_audio_features one tensor of all clips' frames (or padded per clip) a tuple of each clip's valid frames; the flat tensor is get_audio_embeddings. Voxtral's items are its 30-second chunks: its processor stacks every audio's chunks and returns nothing mapping them back to audios
Llama 4 get_image_features vision model output, projected in the forward projected features in pooler_output
Llama 4 / Fuyu forward with pre-encoded mm_encoder_outputs also read last_hidden_state read pooler_output
MiniMax-M3-VL image_hidden_states / video_hidden_states, SmolVLM image_hidden_states one tensor per item one tensor for all items
ModernVBert / UltraVBert forward image_hidden_states a tensor or a per-image list a tensor (its documented type)
Qwen3-VL family, return_dict=False (..., deepstack_features) (..., split_sizes, deepstack_features)
Granite 4 Vision deepstack_features (decoder layer, per-image features) pairs one tensor per decoder layer, in deepstack_layer_map then spatial_target_layers order

Next in the stack

#50887 adds get_data_dependent_inputs and checks the whole forward under torch.compile(fullgraph=True) against eager. Packed encoders (one sequence for all items, cu_seqlens: the Qwen-VL and GLM-4V families, Pixtral / Mistral3, ...) pass on flash attention. Padded-only encoders (Idefics2/3, SmolVLM, Aria, Molmo2, InstructBLIP(-Video), AudioFlamingo3, MusicFlamingo, FunASR-Nano, Nemotron3.5-Transcribe, OmniASR, Gemma4, EmbeddingGemma2) pass on their default SDPA.

Future work

What How Cost
packed paths for the padded encoders, exact where padding is never read after the encoder (Idefics2, Aria, Molmo2, InstructBLIP(-Video), Nemotron3.5-Transcribe, OmniASR, FunASR-Nano), flash gathers the valid positions once and runs varlen none: same outputs, no compute on padding, traceable
packed paths where flash and SDPA already disagree AudioFlamingo3 / MusicFlamingo pooling, Idefics3 / SmolVLM pixel shuffle: fill the padded slot, or use flash's length-based APIs (cache_seqlens, seqused_q / seqused_k) the padded rows' values, already implementation-dependent
BLIP-family on the mixin wrap their base models in .model, with a checkpoint key mapping a loading change
GLM-Image flat its tower output already is; get_image_tokens builds the per-image maps from the grids in the loop it already runs. Puts it on the mixin, dropping its special cases, and lets #50887's fullgraph forward test run on it (skipped there) 🚨 its get_image_features returns rows instead of feature maps

🤖 Generated with Claude Code

🤖 mlinter review state

…flat

`get_image_features` / `get_video_features` split their features per image or video, with sizes read through
`.tolist()`. Passing `return_flat=True` in kwargs returns them before the split, as one `(num_tokens, hidden_size)`
tensor: a traced graph (`torch.export`) can then take any number of images. The default output is unchanged.

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

HuggingFaceDocBuilderDev commented Nov 13, 2026 •

Copy link
Copy Markdown

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

Pages changed in this PR:

IlyasMoutawwakil added a commit that referenced this pull request Nov 13, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`get_image_embeddings` / `get_video_embeddings` return every item's features as one tensor, and the forward uses
them, so it no longer splits and concatenates them again. `get_image_features` / `get_video_features` split them per
item, as before, for callers that want one tensor per item (vLLM, pre-encoded `mm_encoder_outputs`). The
`return_flat` kwarg is gone, with its test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@IlyasMoutawwakil IlyasMoutawwakil changed the title Vision getters: return all items' features as one tensor with return_flat Vision getters: a flat level (get_image_embeddings / get_video_embeddings) under the per-item ones Nov 14, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Model linter — first pass

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

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

rule count what it checks
TRF057 1 Public model, config, output and processor classes and their public methods must carry @auto_docstring.

image_grids = torch.stack([num_frames * rows, cols, torch.zeros_like(cols), torch.zeros_like(cols)], dim=-1)
return self.get_image_embeddings(pixel_values_videos, video_token_pooling, image_grids, **kwargs)

def get_video_features(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

TRF057 — TRF057: Molmo2Model.get_video_features in modeling_molmo2.py has no @auto_docstring. No parent method it could inherit the decorator from declares it. Add @auto_docstring as the innermost decorator here.

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.

IlyasMoutawwakil and others added 2 commits November 14, 2026 08:10
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…image getter

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

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Model linter — first pass

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

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

rule count what it checks
TRF057 1 Public model, config, output and processor classes and their public methods must carry @auto_docstring.

image_grids = torch.stack([num_frames * rows, cols, torch.zeros_like(cols), torch.zeros_like(cols)], dim=-1)
return self.get_image_embeddings(pixel_values_videos, video_token_pooling, image_grids, **kwargs)

def get_video_features(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

TRF057 — TRF057: Molmo2Model.get_video_features in modeling_molmo2.py has no @auto_docstring. No parent method it could inherit the decorator from declares it. Add @auto_docstring as the innermost decorator here.

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.

Their modular children (Aria, Mistral3, InternVL, GraniteDocling, MiniCPM-V 4.6, ...) define their own
`get_image_features`, so a flat level on the parent only took a stub in each child to keep it out.

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

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Model linter — first pass

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

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

rule count what it checks
TRF057 1 Public model, config, output and processor classes and their public methods must carry @auto_docstring.

image_grids = torch.stack([num_frames * rows, cols, torch.zeros_like(cols), torch.zeros_like(cols)], dim=-1)
return self.get_image_embeddings(pixel_values_videos, video_token_pooling, image_grids, **kwargs)

def get_video_features(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

TRF057 — TRF057: Molmo2Model.get_video_features in modeling_molmo2.py has no @auto_docstring. No parent method it could inherit the decorator from declares it. Add @auto_docstring as the innermost decorator here.

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.

Without `image_sizes`, `get_image_features` returns `[num_images, num_tokens, hidden]` as is: indexed per image like
the list, and traced for any image count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
IlyasMoutawwakil added a commit that referenced this pull request Nov 14, 2026
LLaVA keeps a single getter (#50733), so its vision graph keeps the traced image count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
IlyasMoutawwakil added a commit that referenced this pull request Nov 14, 2026
LLaVA's getter returns `[num_images, num_tokens, hidden]` as one tensor (#50733).

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

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Model linter — first pass

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

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

rule count what it checks
TRF057 1 Public model, config, output and processor classes and their public methods must carry @auto_docstring.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
albertvillanova pushed a commit to albertvillanova/transformers that referenced this pull request Nov 17, 2026
* LFM2-VL: unpad and pixel-unshuffle all images with one gather

`get_image_features` looped over the images to unpad each one and run the projector on its own grid. One gather
(`get_vision_unshuffle_index`) now lays every image's `downsample_factor x downsample_factor` blocks side by side, and
the unchanged projector merges them in one call. The index is popped from `kwargs` when precomputed, so a traced
graph takes any number of images. The getter also takes `return_flat`.

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

* LFM2-VL: leave return_flat to huggingface#50733

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

* LFM2-VL: compute the unshuffle index with tensor ops

The gather index comes from the images' sizes with tensor ops, padded to the most tokens an image can have, then one
select keeps the real tokens. No `.tolist()` loop and no input to precompute.

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

* LFM2-VL: run the projector on every image's token slots, padding included

The projector's input no longer has a data-dependent length, so
`torch.compile(fullgraph=True)` lowers it; padding slots are dropped after.
The slow integration tests cover images of different sizes, so the
dedicated test goes.

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

* Record the A10's batched LFM2.5-VL completion

Batching the projector over all images rounds bf16 differently (outputs within 1e-3 of the per-image projector's,
3e-8 in float32), which flips a greedy token on the A10.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@IlyasMoutawwakil
IlyasMoutawwakil removed this pull request from stack #50787 November 17, 2026 16:19
IlyasMoutawwakil and others added 8 commits November 24, 2026 19:09
…sked for a getter it lacks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… hasattr tells which inputs it takes

Reverts what working around the extra getters needed: the input_modalities gates in the common getter tests and
X-CLIP's input_modalities.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…or that uses it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t from the testers' frames, instead of skipping them

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t added on class creation

The docs build mocks torch, and its mock nn.Module has an __init_subclass__ that does not call super(), so the mixin's
hook never ran there and the documented getters went missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…Image's comment says why its getter is per image

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…VAX Vision V2, Video-LLaMA3 and the models generated from them

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@IlyasMoutawwakil IlyasMoutawwakil changed the title Multimodal getters: a flat level (get_image_embeddings / get_video_embeddings / get_audio_embeddings) under the per-item ones 🚨 Multimodal getters: a flat level (get_image_embeddings / get_video_embeddings / get_audio_embeddings) under the per-item ones Nov 24, 2026
…e unsupported modalities

The docs builder walks every name in dir(cls) with getattr and no default, so a getter raising on the class broke it.
The common getter tests check classes, so they gate on input_modalities again, and X-CLIP lists its video input.

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

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Some more comments from me, I dont really want to go through every model so if you have a list you think are a bit more special or important that would help

pooler_output: torch.Tensor | tuple[torch.Tensor, ...] | list[torch.Tensor] | None = None
hidden_states: tuple[torch.Tensor, ...] | None = None
attentions: tuple[torch.Tensor, ...] | None = None
split_sizes: torch.LongTensor | None = None

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

should we be strict here and make this for mm models only? Id really like to only introduce things actually used by models and if this is optional it feels a bit weird

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

agreed, moved it to a dedicated BaseModelOutputWithSplitSizes (named like the other BaseModelOutputWith*), the flat getters return it and the multimodal outputs (deepstack, q-former, vq, ...) inherit from it, BaseModelOutputWithPooling is back to what it was

Comment on lines +29 to +32
def flatten_items(features: torch.Tensor) -> tuple[torch.Tensor, torch.LongTensor]:
"""The `(num_items, num_tokens, hidden_size)` features of fixed-size images or videos as one sequence, and the
`split_sizes` of each item."""
return features.flatten(0, 1), features.new_full(features.shape[:1], features.shape[1], dtype=torch.long)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this is a one liner where i dont feel like we need to make this an actual util?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

inlined

Comment on lines +49 to +53
if outputs.pooler_output is not None:
outputs.pooler_output = torch.split(outputs.pooler_output, split_sizes)
if getattr(outputs, "deepstack_features", None) is not None:
outputs.deepstack_features = [torch.split(features, split_sizes) for features in outputs.deepstack_features]
return outputs

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

placeholder_features is not for this? feels similar

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

unified, split, merge and the beam repeat now all go through one map_features

Comment on lines +56 to +82
def _features_getter(modality: str):
"""`get_<modality>_features`: `get_<modality>_embeddings` split per item."""

@can_return_tuple
def get_features(self, *args, **kwargs):
return split_modality_outputs(getattr(self, f"get_{modality}_embeddings")(*args, return_dict=True, **kwargs))

get_features.__name__ = f"get_{modality}_features"
get_features.__qualname__ = f"MultimodalMixin.{get_features.__name__}"
get_features.__doc__ = f"Each {modality}'s features, from `get_{modality}_embeddings`."
return get_features


def _embeddings_getter(modality: str):
"""`get_<modality>_embeddings` of a head: its base model's."""
name = f"get_{modality}_embeddings"

def get_embeddings(self, *args, **kwargs):
# Only a head has a base model to reach
if getattr(self, "model", None) is None:
raise AttributeError(f"{type(self).__name__} has no `{name}`")
return getattr(self.model, name)(*args, **kwargs)

get_embeddings.__name__ = name
get_embeddings.__qualname__ = f"MultimodalMixin.{name}"
get_embeddings.__doc__ = f"The base model's `{name}`."
return get_embeddings

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

looks overkill to me ngl

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yes i only did this for someone who was checking hasattr(model, get_*_features) to check if model supports modality, the alternative is that all models inheriting mm mixin would have all getters, the other way is theough overriding getattr, wdyt

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

the tests heavily do this to check modalities

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

went with the simplest, back to plain methods on the mixin, every model inheriting it has all getters and the tests check input_modalities instead of hasattr. __getattr__ couldn't work anyway, nn.Module.__getattr__ comes first in the mro and doesn't defer, and class-level lookups (docs, tests) wouldn't see the getters

Comment on lines +85 to +118
class _ModalityGetter:
"""A getter of `MultimodalMixin` that only exists on models taking its modality as input, so `hasattr` tells which
inputs a model takes."""

def __init__(self, modality: str, getter):
self.modality = modality
self.getter = getter

def __get__(self, instance, owner):
input_modalities = owner.input_modalities
input_modalities = (input_modalities,) if isinstance(input_modalities, str) else input_modalities
# A model defining its own per-item getter (GLM-Image's feature maps) has no flat level for the mixin to build on
features_owner = next(cls for cls in owner.__mro__ if f"get_{self.modality}_features" in cls.__dict__)
if self.modality not in input_modalities or features_owner is not MultimodalMixin:
raise AttributeError(f"{owner.__name__} has no `{self.getter.__name__}`")
return self.getter.__get__(instance, owner)


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. Only the modalities in `input_modalities` have them, so `hasattr` tells which inputs
a model takes.
"""

model: "MultimodalMixin"

get_image_embeddings = _ModalityGetter("image", _embeddings_getter("image"))
get_video_embeddings = _ModalityGetter("video", _embeddings_getter("video"))
get_audio_embeddings = _ModalityGetter("audio", _embeddings_getter("audio"))
get_image_features = _ModalityGetter("image", _features_getter("image"))
get_video_features = _ModalityGetter("video", _features_getter("video"))
get_audio_features = _ModalityGetter("audio", _features_getter("audio"))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

yea same for here, id like to have it a bit simplified all under the mixin directly. this feels overengineered

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

done, see above

Comment thread src/transformers/generation/utils.py Outdated
Comment on lines +4450 to +4482
def _repeat_index(counts: torch.LongTensor, repeats: int, total: int) -> torch.LongTensor:
"""Index repeating each group of `counts` contiguous entries `repeats` times in a row, without a host sync."""
sizes = counts * repeats
group = torch.repeat_interleave(
torch.arange(len(counts), device=counts.device), sizes, output_size=total * repeats
)
offset = torch.arange(total * repeats, device=counts.device) - (sizes.cumsum(0) - sizes)[group]
return (counts.cumsum(0) - counts)[group] + offset % counts[group]


def _repeat_flat_outputs(
outputs: BaseModelOutputWithPooling, rows_per_sample: torch.LongTensor, repeats: int
) -> BaseModelOutputWithPooling:
"""Repeats each sample's rows of flat `get_*_embeddings` outputs, as `input_ids.repeat_interleave` does its row."""
pooler_output = outputs.pooler_output
deepstack_features = getattr(outputs, "deepstack_features", None)
reference = placeholder_features(outputs)
rows = _repeat_index(rows_per_sample.to(reference.device), repeats, reference.shape[0])

def repeat(features: torch.Tensor) -> torch.Tensor:
return features[rows.to(features.device)]

if isinstance(pooler_output, torch.Tensor):
outputs.pooler_output = repeat(pooler_output)
if deepstack_features is not None:
outputs.deepstack_features = [repeat(features) for features in deepstack_features]

# The items follow their rows: find each item's sample from where its rows start, then repeat each sample's items
split_sizes = cast(torch.LongTensor, outputs.split_sizes).to(rows_per_sample.device)
item_sample = torch.searchsorted(rows_per_sample.cumsum(0), split_sizes.cumsum(0) - split_sizes, right=True)
items_per_sample = torch.zeros_like(rows_per_sample).scatter_add_(0, item_sample, torch.ones_like(item_sample))
outputs.split_sizes = split_sizes[_repeat_index(items_per_sample, repeats, len(split_sizes))]
return outputs

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

why not make this directly under the fn that uses this (its only 1 no?) also dont get why we split _repeat_index out, seems a bit much for doing it twice

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

moved both inside _expand_multimodal_outputs, next to repeat_tensor_or_list, the index helper stays a nested fn since it's used twice (rows and split sizes)

Comment thread tests/generation/test_utils.py Outdated
inputs_dict_with_encoded_outputs = model._prepare_multimodal_encoder_kwargs_for_generation(inputs_dict)
mm_encoder_outputs = inputs_dict_with_encoded_outputs.pop("mm_encoder_outputs")
if not mm_encoder_outputs:
self.skipTest(reason="The tester's inputs hold no images or videos")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

we can keep the msg a bit more general for the future then -> holds no multimodal output

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

done

Comment thread tests/generation/test_utils.py Outdated
Comment on lines +1602 to +1603
# TODO: audio too, once audio models' forwards read pre-encoded `mm_encoder_outputs["audio"]` and generate
# encodes it with `get_audio_embeddings`

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

there was that one issue Raushan opened, can add it to the list then imo

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

linked #50946 in the todo

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

just to be sure its for the mro inheritances?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yes, a child listing a base its parent already has (Child(Parent, MultimodalMixin) when Parent has GenerationMixin) got one mixin swapped for the other since they share the Mixin suffix, now a re-listed base is kept

@can_return_tuple
@auto_docstring
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
@merge_mm_encoder_outputs

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

also for my interest is the order here important?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yeh was wondering the same, will check, maybe we can add some rules in another pr if not (like alphabetical decoratprs ordering)

IlyasMoutawwakil and others added 2 commits November 24, 2026 22:09
… helpers inside their only caller; warnings name the modality

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

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

Copy link
Copy Markdown
Member Author

if you have a list you think are a bit more special or important that would help

most models are the same mechanical change (getter returns the flat tensor + split_sizes, forward drops its cat), the ones worth a look:

model why
Granite 4 Vision deepstack features are now one tensor per layer (layer ids from the config), its expansion override is gone
Nemotron-H Omni videos reuse the image token (_placeholder_token_id), video pruning reads split_sizes (now repeated for beams)
GLM-4V family, ERNIE 4.5-VL-MoE, Kimi K2.5 _placeholder_token_id replaces the expansion overrides, ernie/kimi delete it to use their own video token
Idefics2/3, SmolVLM split per image instead of per sample (breaking)
Gemma4, Gemma4-Unified, EmbeddingGemma2 audio padding stripping moved into the getter, video split by num_frames_per_video without a host sync
Llama 4, Fuyu the projection / patch embeddings move into pooler_output
Qwen3-VL family return_dict=False tuple gets split_sizes before deepstack_features
Qwen2-VL family get_video_embeddings delegates to the image one, so cosmos3-edge, hy-v4-vl, lfm3-vl, qwen3-vl lose their copies
HunYuan-VL, HY-V4-VL, Emu3 split_sizes count the extra tokens (row separators, begin/end, eol)
MiniCPM-V 4.6, Apertus1.5, Unlimited OCR, DeepSeek-OCR2, Step3p7 split_sizes from per-item lists the model already builds
Voxtral items are its 30s chunks, the processor doesn't say which audio each chunk belongs to
GLM-Image stays per image (image tokenizer feature maps), not on the mixin
PerceptionLM, InternVL new get_video_embeddings
MiniMax-M3-VL, SmolVLM, ModernVBert/UltraVBert *_hidden_states become one tensor
PI0, PPFormulaNet, DiffusionGemma, T5Gemma2 non-VLM users of the getters

…es, not on BaseModelOutputWithPooling

The flat getters wrap their towers' outputs in it, and the multimodal outputs (deepstack, Q-Former, VQ-VAE, ...) inherit
from it. AudioFlamingo3's encoder returns it, as its getter is shared with Nemotron3.5-Transcribe, whose own output
keeps its fields.

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

@zucchini-nlp zucchini-nlp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Oke, I looked over the models you listed as non-mechanic changes and the generic utils file. Didn't comment much on details, i'll leave that to Anton.

Three important q:

  • do we now return audio inputs unpadded/unmasked always from get_audio_embeds? I see gemma is fixed, but wondering if you fixed them all and do we have a test/checker or just ask audio team to keep an eye on it?
  • Ideifcs seems weird to me given its cropped pixel layout, can you check the returned pooler_outputs.split().expand().cat() works fine pls
  • and a small reminder on the follow-up tracker for models that aren't updated. I don't want reviewiers to have mental burden of knowing which method to use on new models

yes, the ones left are mostly encoder/contrastive models (blip, clip-likes, sam-likes) and glm-image, whose features are feature maps. i'll list them in the tracker after merge

Comment on lines +636 to +645
def get_video_split_sizes(
tokens_per_frame: torch.LongTensor, num_frames_per_video: torch.LongTensor
) -> torch.LongTensor:
"""Each video's number of tokens, the sum of its frames' `tokens_per_frame`, without a host sync."""
video_index = torch.repeat_interleave(
torch.arange(len(num_frames_per_video), device=tokens_per_frame.device),
num_frames_per_video.to(tokens_per_frame.device),
output_size=len(tokens_per_frame),
)
return tokens_per_frame.new_zeros(len(num_frames_per_video)).index_add_(0, video_index, tokens_per_frame)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: why a separate fn for a small code, since not seeing it used more than once per file

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

inlined it, it was only used once per file

Comment on lines +2578 to +2580
# Only the real audio soft tokens, the ones `attention_mask` is True on, as the image getter drops padding too
valid_mask = audio_outputs.attention_mask.to(audio_embeds.device)
audio_outputs.pooler_output = audio_embeds[valid_mask]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

loong due even if breaking! IIRC there are a few more audio LLMs that do un-padding in forward, just for future

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yep, i'll add the other audio llms that unpad in forward to the tracker

Comment on lines -840 to 846
image_outputs.pooler_output = [
f.reshape(-1, f.shape[-1]) for f in image_features.split(num_real_images_per_batch.tolist())
]

image_outputs = BaseModelOutputWithSplitSizes(
**image_outputs,
split_sizes=image_features.new_full((image_features.shape[0],), image_features.shape[1], dtype=torch.long),
)
image_outputs.pooler_output = image_features.flatten(0, 1)
return image_outputs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

not sure this will align with how beam/sampling expands. The expansion usually expects to get each entry to hold embeds of a whole image but this will hold only a single crop of image

Ideifcs is weird in a way that each image always gets cropped into 5 and then we also get multiple images per text sometimes. Prob the main is also buggy if used with many images per text 😬

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

it aligns: the flat path in generate repeats rows per sample, and assigns each item to the sample its rows start in, so all the crops of an image (and all the images of a text) stay with their sample. the items being crops only matters for the per-item get_image_features split

Comment on lines +542 to +553
@can_return_tuple
@auto_docstring
def get_video_embeddings(
self,
pixel_values_videos: torch.FloatTensor,
**kwargs: Unpack[TransformersKwargs],
) -> tuple | BaseModelOutputWithPooling:
r"""
pixel_values_videos (`torch.FloatTensor` of shape `(num_frames, channels, height, width)`):
The frames of the input videos, encoded like images.
"""
return self.get_image_embeddings(pixel_values_videos, return_dict=True, **kwargs)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

for my understanding, why is so, if the model supports kinda single modality, i.e. pixel_values holds all pixels concatenated into one

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

the processor folds the video frames into pixel_values, so the forward never needs it. it's there for the public getters and the video tests: a video is frames encoded like images, so it just delegates

Comment on lines +1183 to +1191
) -> tuple | BaseModelOutputWithSplitSizes:
image_outputs = self.vision_model(pixel_values, return_dict=True, **kwargs)
last_hidden_state = image_outputs.last_hidden_state
split_sizes = last_hidden_state.new_full(
(last_hidden_state.shape[0],), last_hidden_state.shape[1], dtype=torch.long
)
image_outputs = BaseModelOutputWithSplitSizes(**image_outputs, split_sizes=split_sizes)
image_outputs.pooler_output = self.multi_modal_projector(last_hidden_state.flatten(0, 1))
return image_outputs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

very nice, a lot of old vision models were neglected by me to keep BC 😆

Comment on lines -268 to +270
pooler_output=tuple(video_embeds.unflatten(0, (num_videos, num_tubelets)).flatten(1, 2)),
pooler_output=video_embeds.flatten(0, 1),
split_sizes=video_embeds.new_full((num_videos,), num_tubelets * video_embeds.shape[1], dtype=torch.long),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

iirc this had an extra dim for which we do flatten() again in main. Do we get a list of 2D arrays after splitting?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

no extra dim left: video_embeds is (num_videos * num_tubelets, tokens, dim), so flatten(0, 1) gives the 2D rows, and split_sizes is num_tubelets * tokens per video. splitting gives one 2D tensor per video, same as main's flatten(1, 2)

Comment on lines +361 to +363
@can_return_tuple
@auto_docstring(custom_intro="Encodes images into the features the decoder cross-attends to.")
def get_image_embeddings(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

oke, so it is not really used by model's forward by i suppose we add it for export/smth else?

note for follow-up: we have many non-generative models with the same helper, also not used by model but rather by Tom in ST (CLIP, Siglip, etc). IMO we need to formalize the recommended method depending on model and document it somehwere for contribs, communicate in slack as well.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yess this work is actually to also enable those non gen models' export and fullgraph compilation, cc @tomaarsen

@IlyasMoutawwakil IlyasMoutawwakil Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

it's the image getter the common multimodal tests run (it dropped 4 skips), and it gives it the same public get_image_features as the other models, so it's also there for anyone (or any tool) encoding images separately. +1 on documenting which getter each kind of model should have, i put it in the tracker

Comment on lines -275 to 281
class SLANeXtVisionEncoderOutput(BaseModelOutputWithPooling):
class SLANeXtVisionEncoderOutput(BaseModelOutputWithSplitSizes):
r"""
image_embeds (`torch.Tensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
The image embeddings obtained by applying the projection layer to the pooler_output.
"""

image_embeds: torch.Tensor | None = None

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

same here re non-gen VLMs, but ig it is more of a modular byproduct

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yes, it's a modular byproduct: its vision encoder output comes from GotOcr2's, which got split_sizes. it's just None for SLANeXt

Line-by-line simplifications (one-use helpers inlined, e.g. `get_video_split_sizes`, redundant re-wraps and casts
dropped); no behaviour change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Qwen2-Audio gets `get_audio_embeddings` (and the mixin's `get_audio_features`): the real audio tokens, flat with
  their `split_sizes`, instead of unpadding in `forward`; the legacy merge takes them as is
- Gemma3n pads each audio to its 188 soft tokens in `get_audio_embeddings` rather than in `forward`
- test_get_audio_embeddings_one_row_per_audio_token: the flat audio embeddings have one row per audio placeholder token

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

IlyasMoutawwakil commented Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

do we now return audio inputs unpadded/unmasked always from get_audio_embeds?

not all were: qwen2_audio (never migrated, it unpadded in forward) and gemma3n (padded to its 188 soft tokens in forward) now do it in get_audio_embeddings too. and there's a check now: test_get_audio_embeddings_one_row_per_audio_token in the common tests, the flat audio embeddings need one row per audio placeholder token, for every audio model (it caught vibevoice-asr's tester, whose prompt had no audio placeholders laid out, fixed too)

Ideifcs seems weird to me given its cropped pixel layout, can you check the returned pooler_outputs.split().expand().cat() works fine pls

checked: a batch with 1 real image + 1 padding image in one sample and 2 images in the other, beam search with 2 beams and 2 returned sequences gives the same tokens from pixel_values and from precomputed get_image_embeddings outputs. the padding image is dropped, and the expansion keeps each sample's crops together

and a small reminder on the follow-up tracker for models that aren't updated

the audio ones are fixed here (qwen2_audio, gemma3n), and i'll open the tracker for models without the flat getters after merge

@IlyasMoutawwakil

IlyasMoutawwakil commented Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

@eustlb @ebezzam could you have a look at the audio side of this PR? the audio getters follow the same layout as the vision ones now:

  • get_audio_embeddings returns the flat audio embeddings, one row per audio placeholder token (no padding), with their split_sizes, and forward scatters them as is. the per-audio get_audio_features comes from MultimodalMixin, split with split_sizes
  • the models doing it differently before: gemma4 (unpadding moved from forward into the getter), qwen2_audio (wasn't migrated, it unpadded in forward, now has the getter + mixin), gemma3n (the padding to its 188 soft tokens moved from forward into the getter)
  • new common check, test_get_audio_embeddings_one_row_per_audio_token, so new audio models keep that layout (it also caught vibevoice_asr's tester, whose prompt had no audio placeholders laid out, fixed)

audio models touched: apertus1p5, audioflamingo3, diffusion_gemma, dots3_note, embedding_gemma2, fun_asr_nano, gemma3n, gemma4, gemma4_unified, glmasr, granite_speech, granite_speech_plus, inkling, moss_transcribe_diarize, muse_spark, musicflamingo, nemotron3_5_transcribe, nemotron_h_omni, omniasr, qwen2_5_omni, qwen2_audio, qwen3_asr, qwen3_omni_moe, vibevoice, vibevoice_asr, voxtral

The 1s clip encoded to 12,000 audio tokens for a 25-token random prompt, so forward tests never placed the audio.
A 16-sample clip with its 8 placeholders laid out, and the one-row-per-audio-token check runs for it too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@IlyasMoutawwakil IlyasMoutawwakil changed the title 🚨 Multimodal getters: a flat level (get_image_embeddings / get_video_embeddings / get_audio_embeddings) under the per-item ones 🚨 Multimodal getters: flat get_*_embeddings under the per-item ones, removing the host sync every multimodal forward pays today Nov 25, 2026
Ovis2.5 (new on main) moves to the flat getters like the other models: `get_image_embeddings` /
`get_video_embeddings` return all items' rows with their `split_sizes` (no `.tolist()`), and its tests use them.

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

Copy link
Copy Markdown
Contributor

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

run-slow: apertus1p5, aria, audioflamingo3, aya_vision, blip_2, chameleon, cohere2_vision, cohere_compass, cosmos3_edge, cosmos3_omni, deepseek_ocr2, deepseek_vl, deepseek_vl_hybrid, diffusion_gemma, dots3_note, embedding_gemma2

@IlyasMoutawwakil

Copy link
Copy Markdown
Member Author

run-slow: granite4_vision, nemotron_h_omni, glm4v, glm4v_moe, glm46v, ernie4_5_vl_moe, kimi_k25, idefics2, idefics3, smolvlm, gemma3n, gemma4, gemma4_unified, embedding_gemma2, llama4, fuyu, qwen3_vl, qwen3_vl_moe, qwen2_vl, qwen2_5_vl, qwen2_5_omni, qwen3_omni_moe, hunyuan_vl, hy_v4_vl, emu3, minicpmv4_6, apertus1p5, unlimited_ocr, deepseek_ocr2, step3p7, voxtral, glm_image, perception_lm, internvl, minimax_m3_vl, modernvbert, ultravbert, pi0, pp_formulanet, diffusion_gemma, t5gemma2, qwen2_audio, ovis2_5

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

CI (Nvidia + AMD)

Nvidia · ⏳ Running... (models: ["models/apertus1p5", "models/deepseek_ocr2", "models/diffusion_gemma", "models/embedding_gemma2", "models/emu3", "models/ernie4_5_vl_moe", "models/fuyu", "models/gemma3n", "models/gemma4", "models/gemma4_unified", "models/glm46v", "models/glm4v", "models/glm4v_moe", "models/glm_image", "models/granite4_vision", "models/hunyuan_vl", "models/hy_v4_vl", "models/idefics2", "models/idefics3", "models/internvl", "models/kimi_k25", "models/llama4", "models/minicpmv4_6", "models/minimax_m3_vl", "models/modernvbert", "models/nemotron_h_omni", "models/ovis2_5", "models/perception_lm", "models/pi0", "models/pp_formulanet", "models/qwen2_5_omni", "models/qwen2_5_vl", "models/qwen2_audio", "models/qwen2_vl", "models/qwen3_omni_moe", "models/qwen3_vl", "models/qwen3_vl_moe", "models/smolvlm", "models/step3p7", "models/t5gemma2", "models/ultravbert", "models/unlimited_ocr", "models/voxtral"], quantizations: []) · ⚙️ Workflow

AMD · ⏳ Running... (models: ["models/apertus1p5", "models/deepseek_ocr2", "models/diffusion_gemma", "models/embedding_gemma2", "models/emu3", "models/ernie4_5_vl_moe", "models/fuyu", "models/gemma3n", "models/gemma4", "models/gemma4_unified", "models/glm46v", "models/glm4v", "models/glm4v_moe", "models/glm_image", "models/granite4_vision", "models/hunyuan_vl", "models/hy_v4_vl", "models/idefics2", "models/idefics3", "models/internvl", "models/kimi_k25", "models/llama4", "models/minicpmv4_6", "models/minimax_m3_vl", "models/modernvbert", "models/nemotron_h_omni", "models/ovis2_5", "models/perception_lm", "models/pi0", "models/pp_formulanet", "models/qwen2_5_omni", "models/qwen2_5_vl", "models/qwen2_audio", "models/qwen2_vl", "models/qwen3_omni_moe", "models/qwen3_vl", "models/qwen3_vl_moe", "models/smolvlm", "models/step3p7", "models/t5gemma2", "models/ultravbert", "models/unlimited_ocr", "models/voxtral"]) · ⚙️ Workflow

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants