Skip to content

Commit de35dfc

Browse files
Add get_data_dependent_inputs
The inputs a forward computes with data-dependent ops, computed outside it: passed back through the forward's kwargs, they keep torch.compile(fullgraph=True) and torch.export free of host syncs. Towers return them unprefixed, models prefixed by modality; generate computes them with the prompt's inputs. A common test compiles each modality encoder with fullgraph=True on them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2262b84 commit de35dfc

90 files changed

Lines changed: 2467 additions & 25 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/transformers/generation/utils.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -768,6 +768,13 @@ def prepare_inputs_for_generation(
768768
elif key not in model_inputs:
769769
model_inputs[key] = value
770770

771+
# 6. The forward's data-dependent inputs, computed with the prompt's; those already laid out are kept
772+
if is_first_iteration or not kwargs.get("use_cache", True):
773+
data_dependent_inputs = self.get_data_dependent_inputs(**model_inputs)
774+
model_inputs.update(
775+
{key: value for key, value in data_dependent_inputs.items() if key not in model_inputs}
776+
)
777+
771778
# BC for remote code models only: create `cache_position` on the fly here, as we don't want to maintain them in kwargs
772779
# between `forward`s
773780
if self.is_remote_code() and "cache_position" in set(inspect.signature(self.forward).parameters):
@@ -780,7 +787,7 @@ def prepare_inputs_for_generation(
780787
cache_position = torch.arange(sequence_length, device=input_ids.device) + past_seen_tokens
781788
model_inputs["cache_position"] = cache_position
782789

783-
# 6. Move the tensors the forward consumes onto the model device, right before the call.
790+
# 7. Move the tensors the forward consumes onto the model device, right before the call.
784791
# It lets the caller intentionally keep inputs on a different device (e.g. Neuron/TPU) so
785792
# the generation loop's growing-tensor bookkeeping stays off-device.
786793
input_tensor = model_inputs.get("inputs_embeds", model_inputs[input_ids_key]) # input_ids is None for embeds

‎src/transformers/modeling_utils.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1389,6 +1389,11 @@ def add_model_tags(self, tags: list[str] | str) -> None:
13891389
if tag not in self.model_tags:
13901390
self.model_tags.append(tag)
13911391

1392+
def get_data_dependent_inputs(self, **kwargs) -> dict[str, Any]:
1393+
"""The inputs the forward computes with data-dependent ops (host syncs, loops over images). Passed back to it,
1394+
they keep it traceable by `torch.compile(fullgraph=True)` and `torch.export`. None by default."""
1395+
return {}
1396+
13921397
@classmethod
13931398
def _from_config(cls, config, **kwargs):
13941399
"""

‎src/transformers/models/cohere_compass/modeling_cohere_compass.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import itertools
2222
from collections.abc import Callable
2323
from dataclasses import dataclass
24+
from typing import Any
2425

2526
import torch
2627
import torch.nn as nn
@@ -898,6 +899,28 @@ def __init__(self, config: CohereCompassVisionConfig, *inputs, **kwargs) -> None
898899

899900
self.post_init()
900901

902+
def get_data_dependent_inputs(self, grid_thw: torch.Tensor, **kwargs) -> dict[str, Any]:
903+
"""What the forward derives from `grid_thw` with data-dependent ops: the position embedding's `interp_indices`
904+
and `interp_weights`, the rotary `position_ids` of the patches, and the attention's `cu_seqlens` and
905+
`max_seqlen`."""
906+
interp_indices, interp_weights = get_vision_interpolation_indices_and_weights(
907+
grid_thw,
908+
num_grid_per_side=self.num_grid_per_side,
909+
mode=self.interpolation_mode,
910+
align_corners=self.interpolation_align_corners,
911+
spatial_merge_size=self.config.spatial_merge_size,
912+
kwargs=kwargs,
913+
)
914+
position_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size, kwargs=kwargs)
915+
cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs)
916+
return {
917+
"interp_indices": interp_indices,
918+
"interp_weights": interp_weights,
919+
"position_ids": position_ids,
920+
"cu_seqlens": cu_seqlens,
921+
"max_seqlen": max_seqlen,
922+
}
923+
901924
@merge_with_config_defaults
902925
@capture_outputs
903926
def forward(
@@ -1218,6 +1241,42 @@ def get_placeholder_mask(
12181241
)
12191242
return special_image_mask, special_video_mask
12201243

1244+
def get_data_dependent_inputs(
1245+
self,
1246+
input_ids: torch.LongTensor | None = None,
1247+
attention_mask: torch.Tensor | None = None,
1248+
image_grid_thw: torch.LongTensor | None = None,
1249+
video_grid_thw: torch.LongTensor | None = None,
1250+
mm_token_type_ids: torch.IntTensor | None = None,
1251+
position_ids: torch.LongTensor | None = None,
1252+
**kwargs,
1253+
) -> dict[str, Any]:
1254+
"""What the forward derives from the processor's outputs with data-dependent ops: the M-RoPE
1255+
`position_ids`, the vision tower's inputs (see
1256+
[`Qwen2VisionTransformerPretrainedModel.get_data_dependent_inputs`]) prefixed `image_` and `video_`, as
1257+
`get_image_embeddings` and `get_video_embeddings` take them."""
1258+
inputs = {}
1259+
for prefix, grid_thw in (("image_", image_grid_thw), ("video_", video_grid_thw)):
1260+
if grid_thw is not None:
1261+
tower_inputs = self.get_encoder(modality="image").get_data_dependent_inputs(grid_thw)
1262+
inputs.update({prefix + name: value for name, value in tower_inputs.items()})
1263+
has_vision = image_grid_thw is not None or video_grid_thw is not None
1264+
if position_ids is None and input_ids is not None and mm_token_type_ids is not None and has_vision:
1265+
vision_position_ids, _ = self.get_rope_index(
1266+
input_ids,
1267+
image_grid_thw=image_grid_thw,
1268+
video_grid_thw=video_grid_thw,
1269+
attention_mask=attention_mask,
1270+
mm_token_type_ids=mm_token_type_ids,
1271+
)
1272+
if attention_mask is not None:
1273+
text_position_ids = (attention_mask.long().cumsum(-1) - 1).masked_fill(attention_mask == 0, 0)
1274+
else:
1275+
text_position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).expand_as(input_ids)
1276+
# The text positions first: the text model builds the attention mask from them
1277+
inputs["position_ids"] = torch.cat([text_position_ids[None], vision_position_ids], dim=0)
1278+
return inputs
1279+
12211280
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
12221281
def compute_3d_position_ids(
12231282
self,
@@ -1447,6 +1506,10 @@ def get_image_embeddings(
14471506
"""
14481507
return self.model.get_image_embeddings(pixel_values, image_grid_thw, **kwargs)
14491508

1509+
def get_data_dependent_inputs(self, *args, **kwargs) -> dict[str, Any]:
1510+
r"""See [`CohereCompassModel.get_data_dependent_inputs`]."""
1511+
return self.model.get_data_dependent_inputs(*args, **kwargs)
1512+
14501513
@auto_docstring
14511514
def get_image_features(
14521515
self,

‎src/transformers/models/cosmos3_edge/modeling_cosmos3_edge.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
# limitations under the License.
2020
import itertools
2121
from collections.abc import Callable
22+
from typing import Any
2223

2324
import torch
2425
import torch.nn as nn
@@ -1032,6 +1033,42 @@ def get_placeholder_mask(
10321033
)
10331034
return special_image_mask, special_video_mask
10341035

1036+
def get_data_dependent_inputs(
1037+
self,
1038+
input_ids: torch.LongTensor | None = None,
1039+
attention_mask: torch.Tensor | None = None,
1040+
image_grid_thw: torch.LongTensor | None = None,
1041+
video_grid_thw: torch.LongTensor | None = None,
1042+
mm_token_type_ids: torch.IntTensor | None = None,
1043+
position_ids: torch.LongTensor | None = None,
1044+
**kwargs,
1045+
) -> dict[str, Any]:
1046+
"""What the forward derives from the processor's outputs with data-dependent ops: the M-RoPE
1047+
`position_ids`, the vision tower's inputs (see
1048+
[`Qwen2VisionTransformerPretrainedModel.get_data_dependent_inputs`]) prefixed `image_` and `video_`, as
1049+
`get_image_embeddings` and `get_video_embeddings` take them."""
1050+
inputs = {}
1051+
for prefix, grid_thw in (("image_", image_grid_thw), ("video_", video_grid_thw)):
1052+
if grid_thw is not None:
1053+
tower_inputs = self.get_encoder(modality="image").get_data_dependent_inputs(grid_thw)
1054+
inputs.update({prefix + name: value for name, value in tower_inputs.items()})
1055+
has_vision = image_grid_thw is not None or video_grid_thw is not None
1056+
if position_ids is None and input_ids is not None and mm_token_type_ids is not None and has_vision:
1057+
vision_position_ids, _ = self.get_rope_index(
1058+
input_ids,
1059+
image_grid_thw=image_grid_thw,
1060+
video_grid_thw=video_grid_thw,
1061+
attention_mask=attention_mask,
1062+
mm_token_type_ids=mm_token_type_ids,
1063+
)
1064+
if attention_mask is not None:
1065+
text_position_ids = (attention_mask.long().cumsum(-1) - 1).masked_fill(attention_mask == 0, 0)
1066+
else:
1067+
text_position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).expand_as(input_ids)
1068+
# The text positions first: the text model builds the attention mask from them
1069+
inputs["position_ids"] = torch.cat([text_position_ids[None], vision_position_ids], dim=0)
1070+
return inputs
1071+
10351072
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
10361073
def compute_3d_position_ids(
10371074
self,
@@ -1216,6 +1253,10 @@ def get_image_embeddings(
12161253
"""
12171254
return self.model.get_image_embeddings(pixel_values, image_grid_thw, **kwargs)
12181255

1256+
def get_data_dependent_inputs(self, *args, **kwargs) -> dict[str, Any]:
1257+
r"""See [`Cosmos3EdgeModel.get_data_dependent_inputs`]."""
1258+
return self.model.get_data_dependent_inputs(*args, **kwargs)
1259+
12191260
@auto_docstring
12201261
def get_image_features(
12211262
self,

‎src/transformers/models/cosmos3_omni/modeling_cosmos3_omni.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import itertools
2222
from dataclasses import dataclass
23+
from typing import Any
2324

2425
import torch
2526
import torch.nn as nn
@@ -354,6 +355,42 @@ def get_placeholder_mask(
354355
)
355356
return special_image_mask, special_video_mask
356357

358+
def get_data_dependent_inputs(
359+
self,
360+
input_ids: torch.LongTensor | None = None,
361+
attention_mask: torch.Tensor | None = None,
362+
image_grid_thw: torch.LongTensor | None = None,
363+
video_grid_thw: torch.LongTensor | None = None,
364+
mm_token_type_ids: torch.IntTensor | None = None,
365+
position_ids: torch.LongTensor | None = None,
366+
**kwargs,
367+
) -> dict[str, Any]:
368+
"""What the forward derives from the processor's outputs with data-dependent ops: the M-RoPE
369+
`position_ids`, the vision tower's inputs (see
370+
[`Qwen2VisionTransformerPretrainedModel.get_data_dependent_inputs`]) prefixed `image_` and `video_`, as
371+
`get_image_embeddings` and `get_video_embeddings` take them."""
372+
inputs = {}
373+
for prefix, grid_thw in (("image_", image_grid_thw), ("video_", video_grid_thw)):
374+
if grid_thw is not None:
375+
tower_inputs = self.get_encoder(modality="image").get_data_dependent_inputs(grid_thw)
376+
inputs.update({prefix + name: value for name, value in tower_inputs.items()})
377+
has_vision = image_grid_thw is not None or video_grid_thw is not None
378+
if position_ids is None and input_ids is not None and mm_token_type_ids is not None and has_vision:
379+
vision_position_ids, _ = self.get_rope_index(
380+
input_ids,
381+
image_grid_thw=image_grid_thw,
382+
video_grid_thw=video_grid_thw,
383+
attention_mask=attention_mask,
384+
mm_token_type_ids=mm_token_type_ids,
385+
)
386+
if attention_mask is not None:
387+
text_position_ids = (attention_mask.long().cumsum(-1) - 1).masked_fill(attention_mask == 0, 0)
388+
else:
389+
text_position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).expand_as(input_ids)
390+
# The text positions first: the text model builds the attention mask from them
391+
inputs["position_ids"] = torch.cat([text_position_ids[None], vision_position_ids], dim=0)
392+
return inputs
393+
357394
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
358395
def compute_3d_position_ids(
359396
self,
@@ -577,6 +614,10 @@ def get_image_embeddings(
577614
"""
578615
return self.model.get_image_embeddings(pixel_values, image_grid_thw, **kwargs)
579616

617+
def get_data_dependent_inputs(self, *args, **kwargs) -> dict[str, Any]:
618+
r"""See [`Cosmos3OmniModel.get_data_dependent_inputs`]."""
619+
return self.model.get_data_dependent_inputs(*args, **kwargs)
620+
580621
@auto_docstring
581622
def get_image_features(
582623
self,

‎src/transformers/models/deepseek_ocr2/modeling_deepseek_ocr2.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import math
2323
from collections.abc import Callable
2424
from dataclasses import dataclass
25+
from typing import Any
2526

2627
import torch
2728
import torch.nn.functional as F
@@ -1604,6 +1605,10 @@ def get_image_embeddings(
16041605
**kwargs,
16051606
)
16061607

1608+
def get_data_dependent_inputs(self, *args, **kwargs) -> dict[str, Any]:
1609+
r"""See [`DeepseekOcr2Model.get_data_dependent_inputs`]."""
1610+
return self.model.get_data_dependent_inputs(*args, **kwargs)
1611+
16071612
@can_return_tuple
16081613
@auto_docstring
16091614
def get_image_features(

‎src/transformers/models/deepseek_ocr2/modular_deepseek_ocr2.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -938,6 +938,9 @@ def __init__(self, config: DeepseekOcr2Config):
938938

939939
self.language_model = DeepseekOcr2TextModel(config.text_config)
940940

941+
def get_data_dependent_inputs(self):
942+
raise AttributeError("DeepseekOcr2 does not pack its image features as LLaVA-NeXT does")
943+
941944
def pack_image_features(self):
942945
raise NotImplementedError("DeepseekOcr2 does not use pack_image_features")
943946

‎src/transformers/models/dots3_note/modeling_dots3_note.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
# limitations under the License.
2020

2121
from collections.abc import Callable
22+
from typing import Any
2223

2324
import torch
2425
import torch.nn.functional as F
@@ -1534,6 +1535,13 @@ def __init__(self, config: Dots3NoteVisionConfig) -> None:
15341535

15351536
self.post_init()
15361537

1538+
def get_data_dependent_inputs(self, grid_thw: torch.Tensor, **kwargs) -> dict[str, Any]:
1539+
"""What the forward derives from `grid_thw` with data-dependent ops: the rotary `position_ids` of the patches,
1540+
and the attention's `cu_seqlens` and `max_seqlen`."""
1541+
position_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size, kwargs=kwargs)
1542+
cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs)
1543+
return {"position_ids": position_ids, "cu_seqlens": cu_seqlens, "max_seqlen": max_seqlen}
1544+
15371545
@merge_with_config_defaults
15381546
@capture_outputs
15391547
@auto_docstring

‎src/transformers/models/ernie4_5_vl_moe/modeling_ernie4_5_vl_moe.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import itertools
2222
from collections.abc import Callable
23+
from typing import Any
2324

2425
import torch
2526
import torch.nn as nn
@@ -918,6 +919,13 @@ def __init__(self, config: Ernie4_5_VLMoeVisionConfig) -> None:
918919

919920
self.post_init()
920921

922+
def get_data_dependent_inputs(self, grid_thw: torch.Tensor, **kwargs) -> dict[str, Any]:
923+
"""What the forward derives from `grid_thw` with data-dependent ops: the rotary `position_ids` of the patches,
924+
and the attention's `cu_seqlens` and `max_seqlen`."""
925+
position_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size, kwargs=kwargs)
926+
cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs)
927+
return {"position_ids": position_ids, "cu_seqlens": cu_seqlens, "max_seqlen": max_seqlen}
928+
921929
@merge_with_config_defaults
922930
@capture_outputs
923931
def forward(
@@ -1304,6 +1312,25 @@ def get_placeholder_mask(
13041312
)
13051313
return special_image_mask, special_video_mask
13061314

1315+
def get_data_dependent_inputs(
1316+
self,
1317+
image_grid_thw: torch.LongTensor | None = None,
1318+
video_grid_thw: torch.LongTensor | None = None,
1319+
**kwargs,
1320+
) -> dict[str, Any]:
1321+
"""The inputs the forward computes with data-dependent operations (see
1322+
[`Qwen2VLModel.get_data_dependent_inputs`]), and the resampler's `temporal_slice_index` (see
1323+
[`get_vision_temporal_slice_index`]), prefixed `image_` and `video_`."""
1324+
inputs = super().get_data_dependent_inputs(
1325+
image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, **kwargs
1326+
)
1327+
for prefix, grid_thw in (("image_", image_grid_thw), ("video_", video_grid_thw)):
1328+
if grid_thw is not None:
1329+
inputs[f"{prefix}temporal_slice_index"] = get_vision_temporal_slice_index(
1330+
grid_thw, self.resampler_model.spatial_merge_size
1331+
)
1332+
return inputs
1333+
13071334
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
13081335
def compute_3d_position_ids(
13091336
self,
@@ -1579,6 +1606,10 @@ def get_image_embeddings(
15791606
"""
15801607
return self.model.get_image_embeddings(pixel_values, image_grid_thw, **kwargs)
15811608

1609+
def get_data_dependent_inputs(self, *args, **kwargs) -> dict[str, Any]:
1610+
r"""See [`Ernie4_5_VLMoeModel.get_data_dependent_inputs`]."""
1611+
return self.model.get_data_dependent_inputs(*args, **kwargs)
1612+
15821613
@auto_docstring
15831614
def get_image_features(
15841615
self,

‎src/transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
import itertools
1717
from collections.abc import Callable
18+
from typing import Any
1819

1920
import torch
2021
import torch.nn as nn
@@ -887,6 +888,25 @@ def get_rope_index(
887888
mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
888889
return position_ids, mrope_position_deltas
889890

891+
def get_data_dependent_inputs(
892+
self,
893+
image_grid_thw: torch.LongTensor | None = None,
894+
video_grid_thw: torch.LongTensor | None = None,
895+
**kwargs,
896+
) -> dict[str, Any]:
897+
"""The inputs the forward computes with data-dependent operations (see
898+
[`Qwen2VLModel.get_data_dependent_inputs`]), and the resampler's `temporal_slice_index` (see
899+
[`get_vision_temporal_slice_index`]), prefixed `image_` and `video_`."""
900+
inputs = super().get_data_dependent_inputs(
901+
image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, **kwargs
902+
)
903+
for prefix, grid_thw in (("image_", image_grid_thw), ("video_", video_grid_thw)):
904+
if grid_thw is not None:
905+
inputs[f"{prefix}temporal_slice_index"] = get_vision_temporal_slice_index(
906+
grid_thw, self.resampler_model.spatial_merge_size
907+
)
908+
return inputs
909+
890910
def get_video_embeddings(
891911
self,
892912
pixel_values_videos: torch.Tensor,

0 commit comments

Comments
 (0)