Skip to content
Open
Show file tree
Hide file tree
Changes from 61 commits
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
920bf22
Vision getters: return all items' features as one tensor with return_…
IlyasMoutawwakil Nov 13, 2026
9c00598
LFM2-VL: return_flat concatenates the features of all images
IlyasMoutawwakil Nov 13, 2026
609d3b8
Vision getters: two levels instead of return_flat
IlyasMoutawwakil Nov 14, 2026
7f6d94d
Vision getters: trim the comments
IlyasMoutawwakil Nov 14, 2026
77a987e
ModernVBert, UltraVBert, EmbeddingGemma2: the forward takes the flat …
IlyasMoutawwakil Nov 14, 2026
39de636
Vision getters: leave LLaVA, Idefics3 and LFM2-VL single-level
IlyasMoutawwakil Nov 14, 2026
101ebe3
LLaVA: return the image features as one tensor, not a list
IlyasMoutawwakil Nov 14, 2026
7a9b5fa
Molmo2: auto_docstring on get_video_features
IlyasMoutawwakil Nov 15, 2026
9d0eec9
Merge remote-tracking branch 'origin/main' into vision-getters-return…
IlyasMoutawwakil Nov 17, 2026
8cb99ca
HY-V4-VL: regenerate from its modular file
IlyasMoutawwakil Nov 17, 2026
edaa6a2
HY-V4-VL: flat get_image_embeddings and get_video_embeddings, get_*_f…
IlyasMoutawwakil Nov 17, 2026
cb4f81f
ModalityFeaturesMixin: get_*_features from the flat get_*_embeddings
IlyasMoutawwakil Nov 18, 2026
64ccca9
Shorter comments
IlyasMoutawwakil Nov 18, 2026
eaaf3b9
Rename to MultimodalMixin, after the PreTrainedModel base
IlyasMoutawwakil Nov 18, 2026
5f34687
MultimodalMixin: declare the attributes it reads, for ty
IlyasMoutawwakil Nov 18, 2026
987a483
Qwen3-VL/Omni: one isinstance check for the pooled and deepstack feat…
IlyasMoutawwakil Nov 18, 2026
ffa4d01
MultimodalMixin: drop the modality hook, video tests check input_moda…
IlyasMoutawwakil Nov 18, 2026
8f8c388
Vision getters: drop the repeated flat-getter docstring intro
IlyasMoutawwakil Nov 18, 2026
e651738
Flat getters return split_sizes; MultimodalMixin splits by it
IlyasMoutawwakil Nov 18, 2026
cb03df4
BaseModelOutputWithPooling: pooler_output can be the split tuple
IlyasMoutawwakil Nov 18, 2026
429155c
Drop the get_video_features leftovers; video embeddings ask the image…
IlyasMoutawwakil Nov 18, 2026
c304d77
Generate encodes with the flat getters; every flat getter returns spl…
IlyasMoutawwakil Nov 18, 2026
fe1b02e
Merge branch 'main' into vision-getters-return-flat
IlyasMoutawwakil Nov 18, 2026
17397b9
Every VLM gets the flat get_*_embeddings and MultimodalMixin
IlyasMoutawwakil Nov 18, 2026
81f62e8
Merge remote-tracking branch 'origin/vision-getters-return-flat' into…
IlyasMoutawwakil Nov 18, 2026
33c0309
MiniCPM-V: split sizes from target_sizes, so the flat getter exports
IlyasMoutawwakil Nov 18, 2026
808f8f3
PI0: read PaliGemma's flat image embeddings
IlyasMoutawwakil Nov 18, 2026
d2adad7
MultimodalMixin in its own module, forwards merge per-item outputs wi…
IlyasMoutawwakil Nov 19, 2026
dabb4a9
generate: encode and expand flat outputs only, free them after the pr…
IlyasMoutawwakil Nov 19, 2026
a1e8e09
Address review: drop no-op reshapes and BC fallbacks, restore token c…
IlyasMoutawwakil Nov 20, 2026
63bb0d9
Merge remote-tracking branch 'origin/main' into vision-getters-return…
IlyasMoutawwakil Nov 20, 2026
3a71cad
Keep LLaVA's image_sizes comment and generate's blank line
IlyasMoutawwakil Nov 20, 2026
28dda67
Simplify: flatten_items, plain split/merge, standard Granite deepstac…
IlyasMoutawwakil Nov 20, 2026
57ac726
Expose modeling_multimodal_utils for the doc builder; shorten convert…
IlyasMoutawwakil Nov 20, 2026
766185c
Kosmos2: keep main's per-image getter, its forward takes no mm_encode…
IlyasMoutawwakil Nov 22, 2026
0a0ffbf
Tests: drop the split_sizes assertions, get_*_features already fails …
IlyasMoutawwakil Nov 23, 2026
b49b746
Review: decorator on every per-item forward, flat getters for PPFormu…
IlyasMoutawwakil Nov 23, 2026
e95c079
Multimodal mixin: audio getters return flat embeddings with split_sizes
IlyasMoutawwakil Nov 23, 2026
c84b8de
Inkling2: delete the inherited get_audio_embeddings, not get_audio_fe…
IlyasMoutawwakil Nov 23, 2026
4495b9a
Merge main into vision-getters-return-flat
IlyasMoutawwakil Nov 24, 2026
558727a
Generate never modifies the mm_encoder_outputs it is passed; tests ke…
IlyasMoutawwakil Nov 24, 2026
937366c
Generate: say why _placeholder_token_id exists; TODO for pre-encoded …
IlyasMoutawwakil Nov 24, 2026
8caeea1
Review pass: Qwen2-VL video getters delegate to the image one, Idefic…
IlyasMoutawwakil Nov 24, 2026
258457b
generate: copy each pre-encoded output once, next to the dict copy
IlyasMoutawwakil Nov 24, 2026
d30c5ad
Drop the split_sizes tests: the mixin's per-item getters are the flat…
IlyasMoutawwakil Nov 24, 2026
49eeadf
generate: repeat split_sizes with the flat rows for beams, as Nemotro…
IlyasMoutawwakil Nov 24, 2026
570c2bc
Keep main's split_sizes expressions in Ernie-4.5-VL-MoE, Kimi-K2.5, H…
IlyasMoutawwakil Nov 24, 2026
b145cd7
MultimodalMixin: a clear error when a model without a base model is a…
IlyasMoutawwakil Nov 24, 2026
5994cc8
generate: narrow split_sizes for the type checker
IlyasMoutawwakil Nov 24, 2026
ddf6530
MultimodalMixin: only the getters of the model's input modalities, so…
IlyasMoutawwakil Nov 24, 2026
f560872
modeling_multimodal_utils: merge_modality_outputs next to the decorat…
IlyasMoutawwakil Nov 24, 2026
bad2875
Gemma4, Gemma4-Unified tests: video getter tests on video inputs buil…
IlyasMoutawwakil Nov 24, 2026
e8dafbb
MultimodalMixin: getters as descriptors checking input_modalities, no…
IlyasMoutawwakil Nov 24, 2026
65bdb7a
One placeholder_features helper for the deepstack-only fallback; GLM-…
IlyasMoutawwakil Nov 24, 2026
980970f
Image getter above the video getter that calls it: Qwen2-VL, HyperCLO…
IlyasMoutawwakil Nov 24, 2026
0673b0f
MultimodalMixin: getters resolve on the class, and only instances hid…
IlyasMoutawwakil Nov 24, 2026
5db9b16
Review: one map_features for split, merge and the beam repeat; repeat…
IlyasMoutawwakil Nov 24, 2026
7afabff
Review: MultimodalMixin back to plain methods; flatten_items inlined …
IlyasMoutawwakil Nov 24, 2026
ff1b057
Review: split_sizes lives on a multimodal BaseModelOutputWithSplitSiz…
IlyasMoutawwakil Nov 24, 2026
694de0a
Nemotron-H Omni: drop the beam-search pruning test, for a bug this PR…
IlyasMoutawwakil Nov 25, 2026
ab20d12
Merge remote-tracking branch 'origin/main' into vision-getters-return…
IlyasMoutawwakil Nov 25, 2026
75f4346
Review: simpler getters and forwards across the multimodal models
IlyasMoutawwakil Nov 25, 2026
9bf7274
Audio getters: one row per audio token, checked for every audio model
IlyasMoutawwakil Nov 25, 2026
f929711
VibeVoice-ASR tester: real audio placeholders, one per audio token
IlyasMoutawwakil Nov 25, 2026
9c7fa43
Merge main into vision-getters-return-flat
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
4 changes: 4 additions & 0 deletions docs/source/en/main_classes/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ documented on their corresponding model page.

[[autodoc]] modeling_outputs.BaseModelOutputWithPooling

## BaseModelOutputWithSplitSizes

[[autodoc]] modeling_outputs.BaseModelOutputWithSplitSizes

## BaseModelOutputWithCrossAttentions

[[autodoc]] modeling_outputs.BaseModelOutputWithCrossAttentions
Expand Down
1 change: 1 addition & 0 deletions src/transformers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@
_import_structure["model_debugging_utils"] = ["model_addition_debugger_context"]
_import_structure["modeling_flash_attention_utils"] = []
_import_structure["modeling_layers"] = ["GradientCheckpointingLayer"]
_import_structure["modeling_multimodal_utils"] = []
_import_structure["modeling_outputs"] = []
_import_structure["modeling_rope_utils"] = ["ROPE_INIT_FUNCTIONS", "RopeParameters", "dynamic_rope_update"]
_import_structure["modeling_utils"] = ["AttentionInterface", "PreTrainedModel"]
Expand Down
100 changes: 72 additions & 28 deletions src/transformers/generation/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
)
from ..integrations.deepspeed import is_deepspeed_zero3_enabled
from ..masking_utils import create_masks_for_generate
from ..modeling_multimodal_utils import map_features, placeholder_features
from ..pytorch_utils import move_to_device
from ..tokenization_python import ExtensionsTrie
from ..utils import (
Expand Down Expand Up @@ -1038,10 +1039,8 @@ def _prepare_multimodal_encoder_kwargs_for_generation(
model_kwargs.setdefault("mm_encoder_outputs", {})
keys_to_pop = set()
for modality in ["image", "video"]:
if (
modality in self.input_modalities
and (encoder_fn := getattr(self.base_model, f"get_{modality}_features", None)) is not None
):
encoder_fn = getattr(self.base_model, f"get_{modality}_embeddings", None)
if modality in self.input_modalities and encoder_fn is not None:
encoder_kwargs = {
Comment on lines -1041 to 1044

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.

yea, completely fine with just swapping it with no fallback to get_x_feats - i doubt anyone actually relied on it in this short period

key: model_kwargs[key]
for key in inspect.signature(encoder_fn).parameters
Expand Down Expand Up @@ -1124,6 +1123,11 @@ def _prepare_decoder_input_ids_for_generation(

return decoder_input_ids, model_kwargs

def _placeholder_token_id(self: "GenerativePreTrainedModel", modality: str) -> int:
"""The token whose positions in the text hold the features of `modality`, to count each sample's rows when
repeating them for beams. Models whose videos reuse the image token (GLM-4V, Nemotron-H Omni) override it."""
return getattr(self.config, f"{modality}_token_id")

def _expand_multimodal_outputs(
self: "GenerativePreTrainedModel",
input_ids: torch.LongTensor,
Expand All @@ -1142,21 +1146,65 @@ def repeat_tensor_or_list(inputs: list | torch.Tensor, repeat_times: int):
# List of `bs` length where each entry is a tensor (seqlen, dim) is also repeat interleaved
return list(inputs) * repeat_times

def repeat_groups(counts: torch.LongTensor, total: int) -> torch.LongTensor:
# Index repeating each group of `counts` contiguous entries `expand_size` times in a row, without a host
# sync, as `input_ids.repeat_interleave` repeats each sample's row
sizes = counts * expand_size
group = torch.repeat_interleave(
torch.arange(len(counts), device=counts.device), sizes, output_size=total * expand_size
)
offset = torch.arange(total * expand_size, device=counts.device) - (sizes.cumsum(0) - sizes)[group]
return (counts.cumsum(0) - counts)[group] + offset % counts[group]

# Our own dict and outputs, as they may be the user's
mm_encoder_output = dict(mm_encoder_output)
for modality in ["image", "video"]:
modalily_outputs = mm_encoder_output.get(modality)
if modalily_outputs is None or getattr(modalily_outputs, "pooler_output", None) is None:
modality_outputs = mm_encoder_output.get(modality)
if modality_outputs is None:
continue
modality_outputs = mm_encoder_output[modality] = copy.copy(modality_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.

how expensive are all the additional copies?

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.

a copy is by reference, not a deep copy, only the container is copied (a list of pointers to the same tensors)

features = placeholder_features(modality_outputs)
is_flat = isinstance(features, torch.Tensor) and getattr(modality_outputs, "split_sizes", None) is not None
if not is_flat and isinstance(features, torch.Tensor) and features.ndim == 2:
raise ValueError(
f"The flat {modality} features of `mm_encoder_outputs` need their `split_sizes`, as returned by "
f"`get_{modality}_embeddings`."
)
if not is_flat and getattr(modality_outputs, "pooler_output", None) is None:
continue

# 1. compute cumulative number of placehlder tokens per sample and per each encoded mm-data
token_id_key = f"{modality}_token_id"
# 1. compute cumulative number of placeholder tokens per sample and per each encoded mm-data
token_id = self._placeholder_token_id(modality)
if (input_ids is None or input_ids.numel() == 0) and inputs_embeds is not None:
special_image_mask = inputs_embeds == self.get_input_embeddings()(
torch.full((), getattr(self.config, token_id_key), dtype=torch.long, device=inputs_embeds.device)
torch.full((), token_id, dtype=torch.long, device=inputs_embeds.device)
Comment on lines -1154 to +1180

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.

quite sure TRF had the rule for it made by Harry, maybe it doesn't run for non-model files πŸ€” gotta check

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 TRF021, it only checks modeling/modular files. this one already uses torch.full

)
num_image_tokens_in_text = special_image_mask.all(-1).sum(-1)
else:
num_image_tokens_in_text = (input_ids == getattr(self.config, token_id_key)).sum(-1)
num_image_tokens_in_vision = [len(out) for out in modalily_outputs.pooler_output]
num_image_tokens_in_text = (input_ids == token_id).sum(-1)

# Flat outputs from `get_*_embeddings`: each sample's rows are contiguous, one gather repeats them
if is_flat:
rows = repeat_groups(num_image_tokens_in_text.to(features.device), features.shape[0])
map_features(modality_outputs, lambda features: features[rows.to(features.device)])
# The items follow their rows: find each item's sample from where its rows start, then repeat them
split_sizes = cast(torch.LongTensor, modality_outputs.split_sizes).to(features.device)
item_start = split_sizes.cumsum(0) - split_sizes
item_sample = torch.searchsorted(num_image_tokens_in_text.cumsum(0), item_start, right=True)
items_per_sample = torch.zeros_like(num_image_tokens_in_text).scatter_add_(
0, item_sample, torch.ones_like(item_sample)
)
modality_outputs.split_sizes = split_sizes[repeat_groups(items_per_sample, len(split_sizes))]
continue

# Per-item outputs, passed by users: from `get_*_features` (deprecated, they keep their `split_sizes`) or
# their own encoder
Comment on lines +1200 to +1201

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.

no strong opinion on deprecating this tbh it's not hurting us much no?

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 still costs a concat at the forward boundary, a second copy of all the features kept through the lm, and keeping it deprecated lets us drop generate's per-item expansion path in v5.29

if getattr(modality_outputs, "split_sizes", None) is not None:
logger.warning_once(
f"Passing per-item `mm_encoder_outputs['{modality}']` (from `get_{modality}_features`) to `generate` "
f"is deprecated and will be removed in v5.29: pass the flat outputs of `get_{modality}_embeddings`."
)
num_image_tokens_in_vision = [len(out) for out in modality_outputs.pooler_output]
num_image_tokens_in_text = list(accumulate(num_image_tokens_in_text))
num_image_tokens_in_vision = list(accumulate(num_image_tokens_in_vision))

Expand All @@ -1166,31 +1214,27 @@ def repeat_tensor_or_list(inputs: list | torch.Tensor, repeat_times: int):
offsets = [0] + [
i + 1 for i, num in enumerate(num_image_tokens_in_vision) if num in num_image_tokens_in_text
]
is_split_images = not isinstance(modalily_outputs.pooler_output, torch.Tensor)
modalily_outputs.pooler_output = [
is_split_images = not isinstance(modality_outputs.pooler_output, torch.Tensor)
modality_outputs.pooler_output = [
out
for start, end in zip(offsets[:-1], offsets[1:])
for out in repeat_tensor_or_list(modalily_outputs.pooler_output[start:end], expand_size)
for out in repeat_tensor_or_list(modality_outputs.pooler_output[start:end], expand_size)
]

# 3. if `pooler_output` was a tensor, cat it back to follow model expectations
if not is_split_images:
modalily_outputs.pooler_output = torch.stack(modalily_outputs.pooler_output, dim=0)
modality_outputs.pooler_output = torch.stack(modality_outputs.pooler_output, dim=0)

# 4. If there are deepstack features, expand them as well. Most models have deeptack features
# per layer where each feature is a `list[torch.Tensor]`. GraniteVision has each feature as a
# `tuple(layer_idx, list[torch.Tensor])` and we skip it here. FIXME: we need a uniform deepstack layout
if getattr(modalily_outputs, "deepstack_features", None) is not None and isinstance(
modalily_outputs.deepstack_features[0][0], torch.Tensor
):
# 4. If there are deepstack features, expand them as well: per layer, each feature is a `list[torch.Tensor]`
if getattr(modality_outputs, "deepstack_features", None) is not None:
# Each deepstack feat is `(total_image_len, dim)` tensor
modalily_outputs.deepstack_features = [
modality_outputs.deepstack_features = [
[
expanded_feats
for start, end in zip(offsets[:-1], offsets[1:])
for expanded_feats in repeat_tensor_or_list(feature_list[start:end], expand_size)
]
for feature_list in modalily_outputs.deepstack_features
for feature_list in modality_outputs.deepstack_features
]

return mm_encoder_output
Expand Down Expand Up @@ -4422,15 +4466,15 @@ def _prefill(
def _slice_mm_encoder_output(output: ModelOutput, rows: torch.LongTensor) -> ModelOutput:
"""
Keeps the given rows of the flattened `(num_placeholder_tokens, hidden_size)` features of a pre-encoded multimodal
output, in the container type the model expects: a single-item list, or a tensor with a batch of one. Only the
pooled and deepstack features are kept, as those are what the models read from pre-encoded outputs.
output, in the container type the model expects: a single-item list, a flat tensor, or a tensor with a batch of one.
Only the pooled and deepstack features are kept, as those are what the models read from pre-encoded outputs.
"""

def slice_features(features):
rows_features = torch.cat([feature.reshape(-1, feature.shape[-1]) for feature in features])[rows]
if isinstance(features, torch.Tensor):
return rows_features.unsqueeze(0)
return [rows_features]
rows_features = features.reshape(-1, features.shape[-1])[rows]
return rows_features if features.ndim == 2 else rows_features.unsqueeze(0)
return [torch.cat([feature.reshape(-1, feature.shape[-1]) for feature in features])[rows]]

sliced = {"pooler_output": slice_features(output["pooler_output"])}
deepstack_features = output.get("deepstack_features")
Expand Down
122 changes: 122 additions & 0 deletions src/transformers/modeling_multimodal_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Copyright 2026 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""What models taking images, videos or audio share: their per-item getters, built on the flat ones (`MultimodalMixin`),
and the conversion of `mm_encoder_outputs` between the two layouts."""

import copy
import functools

import torch

from .utils import is_torchdynamo_compiling, logging
from .utils.generic import can_return_tuple


logger = logging.get_logger(__name__)


def placeholder_features(outputs):
"""The features of encoder `outputs` that fill the placeholder tokens: `pooler_output`, or the first deepstack
layer's for models only returning deepstack features (Granite 4 Vision)."""
pooler_output = getattr(outputs, "pooler_output", None)
if pooler_output is not None:
return pooler_output
deepstack_features = getattr(outputs, "deepstack_features", None)
return deepstack_features[0] if deepstack_features else None


def map_features(outputs, function):
"""Applies `function` to the pooled and deepstack features of encoder `outputs`, in place."""
if outputs.pooler_output is not None:
outputs.pooler_output = function(outputs.pooler_output)
if getattr(outputs, "deepstack_features", None) is not None:
outputs.deepstack_features = [function(features) for features in outputs.deepstack_features]
return outputs
Comment on lines +41 to +45

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



def split_modality_outputs(outputs):
"""Splits flat `get_*_embeddings` outputs per item by their `split_sizes`."""
split_sizes = outputs.split_sizes.tolist()
return map_features(outputs, lambda features: torch.split(features, split_sizes))


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.
"""

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
if getattr(self, "model", None) is None:
raise AttributeError(f"{type(self).__name__} has no `{name}`, as it takes no such input")
return getattr(self.model, name)

def get_image_embeddings(self, *args, **kwargs):
return self._base_model_getter("get_image_embeddings")(*args, **kwargs)

def get_video_embeddings(self, *args, **kwargs):
return self._base_model_getter("get_video_embeddings")(*args, **kwargs)

def get_audio_embeddings(self, *args, **kwargs):
return self._base_model_getter("get_audio_embeddings")(*args, **kwargs)

@can_return_tuple
def get_image_features(self, *args, **kwargs):
"""Each image's features, from `get_image_embeddings`."""
return split_modality_outputs(self.get_image_embeddings(*args, return_dict=True, **kwargs))

@can_return_tuple
def get_video_features(self, *args, **kwargs):
"""Each video's features, from `get_video_embeddings`."""
return split_modality_outputs(self.get_video_embeddings(*args, return_dict=True, **kwargs))

@can_return_tuple
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 merge_modality_outputs(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.

split and merge is very similar no? maybe can be unfied a bit?

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, both are map_features now (torch.split / torch.cat)

"""Concatenates per-item outputs back into the flat layout of `get_*_embeddings`."""
if not isinstance(placeholder_features(outputs), (tuple, list)):
return outputs
return map_features(copy.copy(outputs), torch.cat)


def merge_mm_encoder_outputs(forward):
"""Lets `forward` take per-item `mm_encoder_outputs`, as returned by `get_*_features`, by merging them into the
flat layout it consumes. Only for backward compatibility with users passing them, and deprecated."""

@functools.wraps(forward)
def wrapper(self, *args, mm_encoder_outputs=None, **kwargs):
# Idefics' deprecated `mm_encoder_outputs` can be a bare tensor: only a dict of outputs is merged
if isinstance(mm_encoder_outputs, dict) and mm_encoder_outputs:
merged = {modality: merge_modality_outputs(outputs) for modality, outputs in mm_encoder_outputs.items()}
per_item = [
modality for modality, outputs in mm_encoder_outputs.items() if merged[modality] is not outputs
]
if per_item and not is_torchdynamo_compiling():
modality = per_item[0]
logger.warning_once(
f"Passing per-item `mm_encoder_outputs['{modality}']` (from `get_{modality}_features`) is deprecated "
f"and will be removed in v5.29: pass the flat outputs of `get_{modality}_embeddings`."
)
mm_encoder_outputs = merged
return forward(self, *args, mm_encoder_outputs=mm_encoder_outputs, **kwargs)

return wrapper
18 changes: 18 additions & 0 deletions src/transformers/modeling_outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,24 @@ class BaseModelOutputWithPooling(ModelOutput):
attentions: tuple[torch.Tensor, ...] | None = None


@dataclass
class BaseModelOutputWithSplitSizes(BaseModelOutputWithPooling):
"""
Outputs of a multimodal model's encoder (`get_image_embeddings`, `get_video_embeddings`, `get_audio_embeddings`):
the features of all its images, videos or audios as one sequence, and each item's number of rows.

Args:
pooler_output (`torch.Tensor` of shape `(num_tokens, hidden_size)`):
The features of every item, concatenated. Split per item by `get_image_features`, `get_video_features` and
`get_audio_features`, as a tuple of `(num_item_tokens, hidden_size)` tensors.
split_sizes (`torch.LongTensor` of shape `(num_items,)`, *optional*):
The number of `pooler_output` rows of each image, video or audio.
"""

pooler_output: torch.Tensor | tuple[torch.Tensor, ...] | list[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



@dataclass
class BaseModelOutputWithPoolingAndNoAttention(ModelOutput):
"""
Expand Down
Loading
Loading