Repository navigation
π¨ Multimodal getters: flat get_*_embeddings under the per-item ones, removing the host sync every multimodal forward pays today
#50733
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 61 commits
920bf22
9c00598
609d3b8
7f6d94d
77a987e
39de636
101ebe3
7a9b5fa
9d0eec9
8cb99ca
edaa6a2
cb4f81f
64ccca9
eaaf3b9
5f34687
987a483
ffa4d01
8f8c388
e651738
cb03df4
429155c
c304d77
fe1b02e
17397b9
81f62e8
33c0309
808f8f3
d2adad7
dabb4a9
a1e8e09
63bb0d9
3a71cad
28dda67
57ac726
766185c
0a0ffbf
b49b746
e95c079
c84b8de
4495b9a
558727a
937366c
8caeea1
258457b
d30c5ad
49eeadf
570c2bc
b145cd7
5994cc8
ddf6530
f560872
bad2875
e8dafbb
65bdb7a
980970f
0673b0f
5db9b16
7afabff
ff1b057
694de0a
ab20d12
75f4346
9bf7274
f929711
9c7fa43
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 ( | ||
|
|
@@ -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 = { | ||
| key: model_kwargs[key] | ||
| for key in inspect.signature(encoder_fn).parameters | ||
|
|
@@ -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, | ||
|
|
@@ -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) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. how expensive are all the additional copies?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
| ) | ||
| 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
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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)) | ||
|
|
||
|
|
@@ -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 | ||
|
|
@@ -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") | ||
|
|
||
| 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
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. placeholder_features is not for this? feels similar
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. unified, split, merge and the beam repeat now all go through one |
||
|
|
||
|
|
||
| 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): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. yes, both are |
||
| """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 | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. agreed, moved it to a dedicated |
||
|
|
||
|
|
||
| @dataclass | ||
| class BaseModelOutputWithPoolingAndNoAttention(ModelOutput): | ||
| """ | ||
|
|
||
There was a problem hiding this comment.
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