Skip to content

Commit 83d5ddd

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 7236b16 commit 83d5ddd

90 files changed

Lines changed: 2471 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
@@ -1429,6 +1429,11 @@ def add_model_tags(self, tags: list[str] | str) -> None:
14291429
if tag not in self.model_tags:
14301430
self.model_tags.append(tag)
14311431

1432+
def get_data_dependent_inputs(self, **kwargs) -> dict[str, Any]:
1433+
"""The inputs the forward computes with data-dependent ops (host syncs, loops over images). Passed back to it,
1434+
they keep it traceable by `torch.compile(fullgraph=True)` and `torch.export`. None by default."""
1435+
return {}
1436+
14321437
@classmethod
14331438
def _from_config(cls, config, **kwargs):
14341439
"""

‎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
@@ -897,6 +898,28 @@ def __init__(self, config: CohereCompassVisionConfig, *inputs, **kwargs) -> None
897898

898899
self.post_init()
899900

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

1211+
def get_data_dependent_inputs(
1212+
self,
1213+
input_ids: torch.LongTensor | None = None,
1214+
attention_mask: torch.Tensor | None = None,
1215+
image_grid_thw: torch.LongTensor | None = None,
1216+
video_grid_thw: torch.LongTensor | None = None,
1217+
mm_token_type_ids: torch.IntTensor | None = None,
1218+
position_ids: torch.LongTensor | None = None,
1219+
**kwargs,
1220+
) -> dict[str, Any]:
1221+
"""What the forward derives from the processor's outputs with data-dependent ops: the M-RoPE
1222+
`position_ids`, the vision tower's inputs (see
1223+
[`Qwen2VisionTransformerPretrainedModel.get_data_dependent_inputs`]) prefixed `image_` and `video_`, as
1224+
`get_image_embeddings` and `get_video_embeddings` take them."""
1225+
inputs = {}
1226+
for prefix, grid_thw in (("image_", image_grid_thw), ("video_", video_grid_thw)):
1227+
if grid_thw is not None:
1228+
tower_inputs = self.get_encoder(modality="image").get_data_dependent_inputs(grid_thw)
1229+
inputs.update({prefix + name: value for name, value in tower_inputs.items()})
1230+
has_vision = image_grid_thw is not None or video_grid_thw is not None
1231+
if position_ids is None and input_ids is not None and mm_token_type_ids is not None and has_vision:
1232+
vision_position_ids, _ = self.get_rope_index(
1233+
input_ids,
1234+
image_grid_thw=image_grid_thw,
1235+
video_grid_thw=video_grid_thw,
1236+
attention_mask=attention_mask,
1237+
mm_token_type_ids=mm_token_type_ids,
1238+
)
1239+
if attention_mask is not None:
1240+
text_position_ids = (attention_mask.long().cumsum(-1) - 1).masked_fill(attention_mask == 0, 0)
1241+
else:
1242+
text_position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).expand_as(input_ids)
1243+
# The text positions first: the text model builds the attention mask from them
1244+
inputs["position_ids"] = torch.cat([text_position_ids[None], vision_position_ids], dim=0)
1245+
return inputs
1246+
11881247
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
11891248
def compute_3d_position_ids(
11901249
self,
@@ -1371,6 +1430,10 @@ def __init__(self, config: CohereCompassConfig):
13711430

13721431
self.post_init()
13731432

1433+
def get_data_dependent_inputs(self, *args, **kwargs) -> dict[str, Any]:
1434+
r"""See [`CohereCompassModel.get_data_dependent_inputs`]."""
1435+
return self.model.get_data_dependent_inputs(*args, **kwargs)
1436+
13741437
@can_return_tuple
13751438
@auto_docstring(checkpoint="CohereLabs/North-Micro-Vision-Instruct")
13761439
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")

‎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
@@ -1000,6 +1001,42 @@ def get_placeholder_mask(
10001001
)
10011002
return special_image_mask, special_video_mask
10021003

1004+
def get_data_dependent_inputs(
1005+
self,
1006+
input_ids: torch.LongTensor | None = None,
1007+
attention_mask: torch.Tensor | None = None,
1008+
image_grid_thw: torch.LongTensor | None = None,
1009+
video_grid_thw: torch.LongTensor | None = None,
1010+
mm_token_type_ids: torch.IntTensor | None = None,
1011+
position_ids: torch.LongTensor | None = None,
1012+
**kwargs,
1013+
) -> dict[str, Any]:
1014+
"""What the forward derives from the processor's outputs with data-dependent ops: the M-RoPE
1015+
`position_ids`, the vision tower's inputs (see
1016+
[`Qwen2VisionTransformerPretrainedModel.get_data_dependent_inputs`]) prefixed `image_` and `video_`, as
1017+
`get_image_embeddings` and `get_video_embeddings` take them."""
1018+
inputs = {}
1019+
for prefix, grid_thw in (("image_", image_grid_thw), ("video_", video_grid_thw)):
1020+
if grid_thw is not None:
1021+
tower_inputs = self.get_encoder(modality="image").get_data_dependent_inputs(grid_thw)
1022+
inputs.update({prefix + name: value for name, value in tower_inputs.items()})
1023+
has_vision = image_grid_thw is not None or video_grid_thw is not None
1024+
if position_ids is None and input_ids is not None and mm_token_type_ids is not None and has_vision:
1025+
vision_position_ids, _ = self.get_rope_index(
1026+
input_ids,
1027+
image_grid_thw=image_grid_thw,
1028+
video_grid_thw=video_grid_thw,
1029+
attention_mask=attention_mask,
1030+
mm_token_type_ids=mm_token_type_ids,
1031+
)
1032+
if attention_mask is not None:
1033+
text_position_ids = (attention_mask.long().cumsum(-1) - 1).masked_fill(attention_mask == 0, 0)
1034+
else:
1035+
text_position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).expand_as(input_ids)
1036+
# The text positions first: the text model builds the attention mask from them
1037+
inputs["position_ids"] = torch.cat([text_position_ids[None], vision_position_ids], dim=0)
1038+
return inputs
1039+
10031040
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
10041041
def compute_3d_position_ids(
10051042
self,
@@ -1145,6 +1182,10 @@ def __init__(self, config: Cosmos3EdgeConfig):
11451182

11461183
self.post_init()
11471184

1185+
def get_data_dependent_inputs(self, *args, **kwargs) -> dict[str, Any]:
1186+
r"""See [`Cosmos3EdgeModel.get_data_dependent_inputs`]."""
1187+
return self.model.get_data_dependent_inputs(*args, **kwargs)
1188+
11481189
@can_return_tuple
11491190
@auto_docstring
11501191
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")

‎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
@@ -321,6 +322,42 @@ def get_placeholder_mask(
321322
)
322323
return special_image_mask, special_video_mask
323324

325+
def get_data_dependent_inputs(
326+
self,
327+
input_ids: torch.LongTensor | None = None,
328+
attention_mask: torch.Tensor | None = None,
329+
image_grid_thw: torch.LongTensor | None = None,
330+
video_grid_thw: torch.LongTensor | None = None,
331+
mm_token_type_ids: torch.IntTensor | None = None,
332+
position_ids: torch.LongTensor | None = None,
333+
**kwargs,
334+
) -> dict[str, Any]:
335+
"""What the forward derives from the processor's outputs with data-dependent ops: the M-RoPE
336+
`position_ids`, the vision tower's inputs (see
337+
[`Qwen2VisionTransformerPretrainedModel.get_data_dependent_inputs`]) prefixed `image_` and `video_`, as
338+
`get_image_embeddings` and `get_video_embeddings` take them."""
339+
inputs = {}
340+
for prefix, grid_thw in (("image_", image_grid_thw), ("video_", video_grid_thw)):
341+
if grid_thw is not None:
342+
tower_inputs = self.get_encoder(modality="image").get_data_dependent_inputs(grid_thw)
343+
inputs.update({prefix + name: value for name, value in tower_inputs.items()})
344+
has_vision = image_grid_thw is not None or video_grid_thw is not None
345+
if position_ids is None and input_ids is not None and mm_token_type_ids is not None and has_vision:
346+
vision_position_ids, _ = self.get_rope_index(
347+
input_ids,
348+
image_grid_thw=image_grid_thw,
349+
video_grid_thw=video_grid_thw,
350+
attention_mask=attention_mask,
351+
mm_token_type_ids=mm_token_type_ids,
352+
)
353+
if attention_mask is not None:
354+
text_position_ids = (attention_mask.long().cumsum(-1) - 1).masked_fill(attention_mask == 0, 0)
355+
else:
356+
text_position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).expand_as(input_ids)
357+
# The text positions first: the text model builds the attention mask from them
358+
inputs["position_ids"] = torch.cat([text_position_ids[None], vision_position_ids], dim=0)
359+
return inputs
360+
324361
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
325362
def compute_3d_position_ids(
326363
self,
@@ -501,6 +538,10 @@ def __init__(self, config: Cosmos3OmniConfig):
501538

502539
self.post_init()
503540

541+
def get_data_dependent_inputs(self, *args, **kwargs) -> dict[str, Any]:
542+
r"""See [`Cosmos3OmniModel.get_data_dependent_inputs`]."""
543+
return self.model.get_data_dependent_inputs(*args, **kwargs)
544+
504545
@can_return_tuple
505546
@auto_docstring
506547
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")

‎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
@@ -1575,6 +1576,10 @@ def get_output_embeddings(self) -> nn.Module:
15751576
def pack_image_features(self):
15761577
raise NotImplementedError("DeepseekOcr2 does not use pack_image_features")
15771578

1579+
def get_data_dependent_inputs(self, *args, **kwargs) -> dict[str, Any]:
1580+
r"""See [`DeepseekOcr2Model.get_data_dependent_inputs`]."""
1581+
return self.model.get_data_dependent_inputs(*args, **kwargs)
1582+
15781583
@can_return_tuple
15791584
@auto_docstring
15801585
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")

‎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
@@ -1531,6 +1532,13 @@ def __init__(self, config: Dots3NoteVisionConfig) -> None:
15311532

15321533
self.post_init()
15331534

1535+
def get_data_dependent_inputs(self, grid_thw: torch.Tensor, **kwargs) -> dict[str, Any]:
1536+
"""What the forward derives from `grid_thw` with data-dependent ops: the rotary `position_ids` of the patches,
1537+
and the attention's `cu_seqlens` and `max_seqlen`."""
1538+
position_ids = get_vision_position_ids(grid_thw, self.spatial_merge_size, kwargs=kwargs)
1539+
cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs)
1540+
return {"position_ids": position_ids, "cu_seqlens": cu_seqlens, "max_seqlen": max_seqlen}
1541+
15341542
@merge_with_config_defaults
15351543
@capture_outputs
15361544
@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
@@ -917,6 +918,13 @@ def __init__(self, config: Ernie4_5_VLMoeVisionConfig) -> None:
917918

918919
self.post_init()
919920

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

1282+
def get_data_dependent_inputs(
1283+
self,
1284+
image_grid_thw: torch.LongTensor | None = None,
1285+
video_grid_thw: torch.LongTensor | None = None,
1286+
**kwargs,
1287+
) -> dict[str, Any]:
1288+
"""The inputs the forward computes with data-dependent operations (see
1289+
[`Qwen2VLModel.get_data_dependent_inputs`]), and the resampler's `temporal_slice_index` (see
1290+
[`get_vision_temporal_slice_index`]), prefixed `image_` and `video_`."""
1291+
inputs = super().get_data_dependent_inputs(
1292+
image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, **kwargs
1293+
)
1294+
for prefix, grid_thw in (("image_", image_grid_thw), ("video_", video_grid_thw)):
1295+
if grid_thw is not None:
1296+
inputs[f"{prefix}temporal_slice_index"] = get_vision_temporal_slice_index(
1297+
grid_thw, self.resampler_model.spatial_merge_size
1298+
)
1299+
return inputs
1300+
12741301
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")
12751302
def compute_3d_position_ids(
12761303
self,
@@ -1507,6 +1534,10 @@ def __init__(self, config: Ernie4_5_VLMoeConfig):
15071534

15081535
self.post_init()
15091536

1537+
def get_data_dependent_inputs(self, *args, **kwargs) -> dict[str, Any]:
1538+
r"""See [`Ernie4_5_VLMoeModel.get_data_dependent_inputs`]."""
1539+
return self.model.get_data_dependent_inputs(*args, **kwargs)
1540+
15101541
@can_return_tuple
15111542
@auto_docstring
15121543
@deprecate_kwarg("past_key_values", "5.40.0", new_name="cache")

‎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
@@ -885,6 +886,25 @@ def get_rope_index(
885886
mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
886887
return position_ids, mrope_position_deltas
887888

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

0 commit comments

Comments
 (0)