Repository navigation
🚨 Multimodal getters: flat get_*_embeddings under the per-item ones, removing the host sync every multimodal forward pays today - #50733
IlyasMoutawwakil wants to merge 65 commits into
Conversation
…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>
|
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: |
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>
return_flatget_image_embeddings / get_video_embeddings) under the per-item ones
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…image getter Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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>
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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>
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>
LLaVA's getter returns `[num_images, num_tokens, hidden]` as one tensor (#50733). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
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>
* 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>
…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>
get_image_embeddings / get_video_embeddings / get_audio_embeddings) under the per-item onesget_image_embeddings / get_video_embeddings / get_audio_embeddings) under the per-item ones
…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
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
| 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) |
There was a problem hiding this comment.
this is a one liner where i dont feel like we need to make this an actual util?
| 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 |
There was a problem hiding this comment.
placeholder_features is not for this? feels similar
There was a problem hiding this comment.
unified, split, merge and the beam repeat now all go through one map_features
| 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 |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
the tests heavily do this to check modalities
There was a problem hiding this comment.
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
| 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")) |
There was a problem hiding this comment.
yea same for here, id like to have it a bit simplified all under the mixin directly. this feels overengineered
There was a problem hiding this comment.
done, see above
| 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 |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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)
| 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") |
There was a problem hiding this comment.
we can keep the msg a bit more general for the future then -> holds no multimodal output
| # TODO: audio too, once audio models' forwards read pre-encoded `mm_encoder_outputs["audio"]` and generate | ||
| # encodes it with `get_audio_embeddings` |
There was a problem hiding this comment.
there was that one issue Raushan opened, can add it to the list then imo
There was a problem hiding this comment.
just to be sure its for the mro inheritances?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
also for my interest is the order here important?
There was a problem hiding this comment.
yeh was wondering the same, will check, maybe we can add some rules in another pr if not (like alphabetical decoratprs ordering)
… 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>
most models are the same mechanical change (getter returns the flat tensor +
|
…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>
… introduced and fixed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
zucchini-nlp
left a comment
There was a problem hiding this comment.
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
| 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) |
There was a problem hiding this comment.
nit: why a separate fn for a small code, since not seeing it used more than once per file
There was a problem hiding this comment.
inlined it, it was only used once per file
| # 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] |
There was a problem hiding this comment.
loong due even if breaking! IIRC there are a few more audio LLMs that do un-padding in forward, just for future
There was a problem hiding this comment.
yep, i'll add the other audio llms that unpad in forward to the tracker
| 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 |
There was a problem hiding this comment.
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 😬
There was a problem hiding this comment.
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
| @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) |
There was a problem hiding this comment.
for my understanding, why is so, if the model supports kinda single modality, i.e. pixel_values holds all pixels concatenated into one
There was a problem hiding this comment.
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
| ) -> 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 |
There was a problem hiding this comment.
very nice, a lot of old vision models were neglected by me to keep BC 😆
| 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), |
There was a problem hiding this comment.
iirc this had an extra dim for which we do flatten() again in main. Do we get a list of 2D arrays after splitting?
There was a problem hiding this comment.
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)
| @can_return_tuple | ||
| @auto_docstring(custom_intro="Encodes images into the features the decoder cross-attends to.") | ||
| def get_image_embeddings( |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
yess this work is actually to also enable those non gen models' export and fullgraph compilation, cc @tomaarsen
There was a problem hiding this comment.
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
| 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 |
There was a problem hiding this comment.
same here re non-gen VLMs, but ig it is more of a modular byproduct
There was a problem hiding this comment.
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>
not all were: qwen2_audio (never migrated, it unpadded in
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
the audio ones are fixed here (qwen2_audio, gemma3n), and i'll open the tracker for models without the flat getters after merge |
|
@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:
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>
get_image_embeddings / get_video_embeddings / get_audio_embeddings) under the per-item onesget_*_embeddings under the per-item ones, removing the host sync every multimodal forward pays today
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>
|
[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 |
|
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 |
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 |
What does this PR do?
Every multimodal forward on
mainpays a host sync for nothing.get_image_features/get_video_featuressplit the encoder output per item with sizes read through.tolist(), and the forward concatenates the pieces straight back formasked_scatter. This PR removes that round trip from 110 multimodal models (vision, video and audio), in eager,torch.compile, export andgenerate:maintorch.compileof the image encoder (Qwen2-VL-2B)torch.compile(dynamic=True)on 4, 2, 5, 3 imagesgenerategeneratewith beamssplit_sizesforward, depending on the modelIt is also what makes the whole multimodal forward compile with
fullgraph=Truein #50887.How: a flat level under the per-item getters, which forwards and
generateuse:get_image_embeddings/get_video_embeddings/get_audio_embeddings(new)split_sizes(rows per item)get_image_features/get_video_features/get_audio_featuresMultimodalMixin, from the flat getterMeasured 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
modeling_multimodal_utils(new)MultimodalMixin: per-item getters from the flat ones, heads reach their base model's, only for the modalities ininput_modalities(sohasattr(model, ...)tells which inputs a model takes);flatten_items;@merge_mm_encoder_outputs, which still accepts per-itemmm_encoder_outputsin forwards, with a deprecation warningBaseModelOutputWithSplitSizes(new)BaseModelOutputWithPoolingplussplit_sizes, for multimodal encoder outputs only: the flat getters return it, and the multimodal outputs (deepstack, Q-Former, VQ-VAE, ...) inherit from ittorch.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, ...)generatesplit_sizeswith one gather, no host sync. A_placeholder_token_idhook replaces the GLM-4V family, Nemotron-H Omni and Granite 4 Vision expansion overridesmm_encoder_outputspassed to forwards orgenerate, to be removed in v5.29GenerationMixin/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
get_image_featuresof models that returned one[num_images, num_tokens, hidden]tensor (PaliGemma, Gemma3, LLaVA withoutimage_sizes, ...)[num_tokens, hidden](indexes and iterates the same)get_image_featuresget_audio_featuresget_audio_embeddings. Voxtral's items are its 30-second chunks: its processor stacks every audio's chunks and returns nothing mapping them back to audiosget_image_featurespooler_outputmm_encoder_outputslast_hidden_statepooler_outputimage_hidden_states/video_hidden_states, SmolVLMimage_hidden_statesimage_hidden_statesreturn_dict=False(..., deepstack_features)(..., split_sizes, deepstack_features)deepstack_features(decoder layer, per-image features)pairsdeepstack_layer_mapthenspatial_target_layersorderNext in the stack
#50887 adds
get_data_dependent_inputsand checks the whole forward undertorch.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
cache_seqlens,seqused_q/seqused_k).model, with a checkpoint key mappingget_image_tokensbuilds 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)get_image_featuresreturns rows instead of feature maps🤖 Generated with Claude Code
🤖 mlinter review state
0071f75be6517381get_*_embeddingsunder the per-item ones, removing the host sync every multimodal forward pays today #50733 (review)