From 899f55f8e41654a106a414e93a6f5fd8f3b8bf37 Mon Sep 17 00:00:00 2001 From: "Wang, Yi" Date: Tue, 1 Sep 2026 10:59:30 +0800 Subject: [PATCH 001/996] Add TP-plan for muse_glimmer and fix dflash for sharded embedding (#47913) * This PR improves DFlash generation support for MuseGlimmer under tensor parallelism and reduces memory pressure during DFlash assisted decoding. Main changes: - Add selective hidden-state capture via `output_hidden_states_layers`, so DFlash only stores the main-model hidden states needed by the assistant instead of retaining all layers. - Update `DFlashTokenCandidateGenerator` to request only the configured target layers and prepare the assistant context from those sparse hidden states. - Support TP-sharded DFlash assistant context when the assistant encoder projection uses `rowwise` tensor parallelism, avoiding materializing the full concatenated context on every rank. - Fix DFlash with MuseGlimmer TP by letting its normed embedding module expose an `apply_norm=False` path, so DFlash can obtain raw noise-token embeddings without bypassing TP-aware embedding dispatch. - Add default tensor-parallel plans for MuseGlimmer text, vision, multimodal projection, LM head, and MuseGlimmer assistant modules. These changes allow DFlash to work correctly with MuseGlimmer/MuseGlimmer assistant in TP setups while reducing unnecessary hidden-state memory usage. Signed-off-by: Wang, Yi A * fmt Signed-off-by: Wang, Yi A * update Signed-off-by: Wang, Yi A * update Signed-off-by: Wang, Yi A * update Signed-off-by: Wang, Yi A * update Signed-off-by: Wang, Yi A * update Signed-off-by: Wang, Yi A * return outside try --------- Signed-off-by: Wang, Yi A Co-authored-by: Cyril Vallez --- .../generation/candidate_generator.py | 21 +++++++++++++++++-- .../configuration_muse_glimmer.py | 15 +++++++++++++ .../muse_glimmer/modeling_muse_glimmer.py | 1 + .../muse_glimmer/modular_muse_glimmer.py | 17 +++++++++++++++ .../configuration_muse_glimmer_assistant.py | 10 +++++++++ 5 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/transformers/generation/candidate_generator.py b/src/transformers/generation/candidate_generator.py index 63d3d45afd20..0a62d5a7c1e9 100644 --- a/src/transformers/generation/candidate_generator.py +++ b/src/transformers/generation/candidate_generator.py @@ -1620,6 +1620,24 @@ def __init__( self.is_main_model_prefill = True + def _get_noise_embeds(self, noise_ids: torch.LongTensor) -> torch.Tensor: + """ + Get noise token embeddings from the main model while bypassing its optional embedding normalization, which should not be used + for DFlash (the embedding may be a subclass of nn.Embedding with the additional normalization). + """ + embed_norm = getattr(self.main_model_input_embeddings, "embed_norm", None) + if embed_norm is None: + return self.main_model_input_embeddings(noise_ids) + + # For TP-aware models, the easiest workaround to avoid the norm is to temporarily set it to Identity + try: + self.main_model_input_embeddings.embed_norm = nn.Identity() + embeds = self.main_model_input_embeddings(noise_ids) + finally: + self.main_model_input_embeddings.embed_norm = embed_norm + + return embeds + def get_candidates( self, input_ids: torch.LongTensor, @@ -1673,8 +1691,7 @@ def get_candidates( # Create the new inputs corresponding to only the "noise", or "diffusion window". It's the last bonus token (or "anchor") from # the main model, and the noise tokens noise_ids = torch.cat([input_ids[:, -1:], self.noise_ids_mask.to(input_ids.device)], dim=-1) - # The assistant needs embedding without norm thus take the lookup table and call `F.embedding` - noise_embeds = torch.nn.functional.embedding(noise_ids, self.main_model_input_embeddings.weight) + noise_embeds = self._get_noise_embeds(noise_ids) # Append positions and mask for the noise tokens, because they correspond to positions beyond the last `num_last_main_model_tokens` # that will first be used to populate the assistant kv cache at those positions through the `context_hidden_states` diff --git a/src/transformers/models/muse_glimmer/configuration_muse_glimmer.py b/src/transformers/models/muse_glimmer/configuration_muse_glimmer.py index 19cb5a57eb43..597d1253a2a0 100644 --- a/src/transformers/models/muse_glimmer/configuration_muse_glimmer.py +++ b/src/transformers/models/muse_glimmer/configuration_muse_glimmer.py @@ -54,6 +54,15 @@ class MuseGlimmerVisionConfig(PreTrainedConfig): hidden_act: str = "gelu" rope_parameters: dict | None = None # defaults set by `RopeConfigMixin` max_position_embeddings: int = 32 * 32 # == `pos_h * pos_w` + base_model_tp_plan = { + "patch_embedder.patch_embedding": "colwise_gather_output", + "layers.*.attn.q_proj": "colwise", + "layers.*.attn.k_proj": "colwise", + "layers.*.attn.v_proj": "colwise", + "layers.*.attn.proj": "rowwise", + "layers.*.mlp.fc1": "colwise", + "layers.*.mlp.fc2": "rowwise", + } patch_temporal: int = 2 merge_size: int = 2 layer_norm_eps: float = 1e-05 @@ -91,6 +100,7 @@ class MuseGlimmerTextConfig(PreTrainedConfig): model_type = "muse_glimmer_text" keys_to_ignore_at_inference = ["past_key_values"] base_model_tp_plan = { + "embed_tokens": "embedding_rowwise", "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", @@ -188,6 +198,11 @@ class MuseGlimmerConfig(PreTrainedConfig): model_type = "muse_glimmer" sub_configs = {"text_config": MuseGlimmerTextConfig, "vision_config": MuseGlimmerVisionConfig} + base_model_tp_plan = { + "vision_adapter.fc1": "colwise", + "vision_adapter.fc2": "rowwise", + "vision_projection": "colwise_gather_output", + } text_config: dict | PreTrainedConfig | None = None vision_config: dict | PreTrainedConfig | None = None diff --git a/src/transformers/models/muse_glimmer/modeling_muse_glimmer.py b/src/transformers/models/muse_glimmer/modeling_muse_glimmer.py index 2bd5278248f1..453ec247ff10 100644 --- a/src/transformers/models/muse_glimmer/modeling_muse_glimmer.py +++ b/src/transformers/models/muse_glimmer/modeling_muse_glimmer.py @@ -1054,6 +1054,7 @@ class MuseGlimmerForConditionalGeneration(MuseGlimmerPreTrainedModel, Generation _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"} # Reference: fix gemma3 grad acc #37208 accepts_loss_kwargs = False + _tp_plan = {"lm_head": "colwise_gather_output"} def __init__(self, config): super().__init__(config) diff --git a/src/transformers/models/muse_glimmer/modular_muse_glimmer.py b/src/transformers/models/muse_glimmer/modular_muse_glimmer.py index 94c6e4991e6a..b5973eb2d19c 100644 --- a/src/transformers/models/muse_glimmer/modular_muse_glimmer.py +++ b/src/transformers/models/muse_glimmer/modular_muse_glimmer.py @@ -530,6 +530,15 @@ class MuseGlimmerVisionConfig(Kimi_K25VisionConfig): """ model_type = "muse_glimmer_vision" + base_model_tp_plan = { + "patch_embedder.patch_embedding": "colwise_gather_output", + "layers.*.attn.q_proj": "colwise", + "layers.*.attn.k_proj": "colwise", + "layers.*.attn.v_proj": "colwise", + "layers.*.attn.proj": "rowwise", + "layers.*.mlp.fc1": "colwise", + "layers.*.mlp.fc2": "rowwise", + } hidden_size: int = 1536 num_hidden_layers: int = 50 @@ -576,6 +585,7 @@ class MuseGlimmerTextConfig(Gemma2Config, PreTrainedConfig): model_type = "muse_glimmer_text" base_model_tp_plan = { + "embed_tokens": "embedding_rowwise", "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", @@ -658,6 +668,11 @@ class MuseGlimmerConfig(PreTrainedConfig): model_type = "muse_glimmer" sub_configs = {"text_config": MuseGlimmerTextConfig, "vision_config": MuseGlimmerVisionConfig} + base_model_tp_plan = { + "vision_adapter.fc1": "colwise", + "vision_adapter.fc2": "rowwise", + "vision_projection": "colwise_gather_output", + } text_config: dict | PreTrainedConfig | None = None vision_config: dict | PreTrainedConfig | None = None @@ -1097,6 +1112,8 @@ def get_image_features( class MuseGlimmerForConditionalGeneration(Kimi_K25ForConditionalGeneration): + _tp_plan = {"lm_head": "colwise_gather_output"} + def forward( self, input_ids: torch.LongTensor | None = None, diff --git a/src/transformers/models/muse_glimmer_assistant/configuration_muse_glimmer_assistant.py b/src/transformers/models/muse_glimmer_assistant/configuration_muse_glimmer_assistant.py index 184b610aeb41..6319a77e1f44 100644 --- a/src/transformers/models/muse_glimmer_assistant/configuration_muse_glimmer_assistant.py +++ b/src/transformers/models/muse_glimmer_assistant/configuration_muse_glimmer_assistant.py @@ -50,6 +50,16 @@ class MuseGlimmerAssistantConfig(PreTrainedConfig): model_type = "muse_glimmer_assistant" default_theta = 500000.0 + base_model_tp_plan = { + "encoder.fc": "rowwise_split_input", + "layers.*.self_attn.q_proj": "colwise", + "layers.*.self_attn.k_proj": "colwise", + "layers.*.self_attn.v_proj": "colwise", + "layers.*.self_attn.o_proj": "rowwise", + "layers.*.mlp.gate_proj": "colwise", + "layers.*.mlp.up_proj": "colwise", + "layers.*.mlp.down_proj": "rowwise", + } hidden_size: int = 6656 intermediate_size: int = 19968 From a932513aac5dc4c54dbec48684c8bcdc286c954e Mon Sep 17 00:00:00 2001 From: Yih-Dar <2521628+ydshieh@users.noreply.github.com> Date: Tue, 1 Sep 2026 04:04:39 +0000 Subject: [PATCH 002/996] [MiniCPMV4_6] Update test_small_model_vision_generation_batch expected output (value drift) (#48406) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [MiniCPMV4_6] Update test_small_model_vision_generation_batch expected output (value drift) Output drifted after #47625 refactored the Gated Delta Rule computation in `modeling_qwen3_5.py` (MiniCPMV4_6's text backbone). Verified by bisect: parent commit passes 3/3, the PR commit fails consistently. Co-Authored-By: Claude Sonnet 4.6 * Added expectations for b200 --------- Co-authored-by: ydshieh Co-authored-by: Claude Sonnet 4.6 Co-authored-by: remi-or Co-authored-by: Rémi Ouazan <83456801+remi-or@users.noreply.github.com> --- .../models/minicpmv4_6/test_modeling_minicpmv4_6.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/models/minicpmv4_6/test_modeling_minicpmv4_6.py b/tests/models/minicpmv4_6/test_modeling_minicpmv4_6.py index 86eb85ea3f1b..9f73270c3ce1 100644 --- a/tests/models/minicpmv4_6/test_modeling_minicpmv4_6.py +++ b/tests/models/minicpmv4_6/test_modeling_minicpmv4_6.py @@ -497,9 +497,11 @@ def test_small_model_vision_generation_batch(self): expected_texts = Expectations( { ("cuda", None): [ - "The animal in the image is a Pystylus, also known as the Eurasian pystylus or snow leopard cat. It's a", - "The animal in the image is a Pystylus, also known as the Eurasian pystylus or snow leopard cat. It's a", - ], + "The animal in the image is a Pystylus, also known as a Pystylus cat or Eurasian pystylus. It", + ] * 2, + ("cuda", 10): [ + "The animal in the image is a Pystylus, also known as a Eurasian pystylus or snow leopard cat. It's a", + ] * 2, } ) # fmt: skip EXPECTED_TEXT = expected_texts.get_expectation() @@ -547,6 +549,10 @@ def test_small_model_vision_generation_batch_mixed(self): "The animal in the image is a Pystylus, also known as the Eurasian pystylus or snow leopard cat. It's a", "I'm a model from the MiniCPM series, developed by Modelbest and OpenBMB. For more details, you can visit https://github", ], + ("cuda", 10): [ + "The animal in the image is a Pystylus, also known as a Eurasian pystylus or snow leopard cat. It's a", + "I'm a model from the MiniCPM series, developed by Modelbest and OpenBMB. For more details, you can visit https://github", + ], } ) # fmt: skip EXPECTED_TEXT = expected_texts.get_expectation() From 69a7fb1aca7f2e7487294846be5859ebb6db9462 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Quentin=20Gallou=C3=A9dec?= <45557362+qgallouedec@users.noreply.github.com> Date: Tue, 1 Sep 2026 04:13:27 +0000 Subject: [PATCH 003/996] Add offload to gradient checkpointing (#48444) * Add offload to gradient checkpointing Gradient checkpointing keeps one activation per checkpointed layer on the device, which is `layers x sequence x hidden` bytes and dominates at long sequence lengths. `offload` holds those in pinned host memory instead, through torch's `save_on_cpu`, so it follows whichever checkpointing path the model already uses. * Follow the repo conventions for the new option Document `offload` in `TrainingArguments.gradient_checkpointing_kwargs`, next to `every_n_layers`, and use the `backend_*` test helpers instead of `torch.accelerator` directly. --- docs/source/en/grad_checkpointing.md | 16 +++++++ src/transformers/modeling_utils.py | 21 ++++++++- src/transformers/trainer.py | 10 +++-- src/transformers/training_args.py | 7 ++- tests/utils/test_modeling_utils.py | 64 ++++++++++++++++++++++++++++ 5 files changed, 111 insertions(+), 7 deletions(-) diff --git a/docs/source/en/grad_checkpointing.md b/docs/source/en/grad_checkpointing.md index f29d8ef79334..9ec9caf71e77 100644 --- a/docs/source/en/grad_checkpointing.md +++ b/docs/source/en/grad_checkpointing.md @@ -43,6 +43,22 @@ args = TrainingArguments( ) ``` +## Offloading the saved activations + +Gradient checkpointing still keeps one activation per checkpointed layer on the GPU, and at long sequence lengths that alone is large: `layers x sequence x hidden` bytes, so 36 layers of an 8B model at 128k tokens is 36 GB. Set `offload` to hold those in pinned host memory instead, and pay a device-to-host copy in the forward and a host-to-device copy in the backward for them. + +```py +from transformers import TrainingArguments + +args = TrainingArguments( + ..., + gradient_checkpointing=True, + gradient_checkpointing_kwargs={"offload": True}, +) +``` + +Both copies run on the compute stream, so this trades a slower step for the memory. Reach for it when a run does not fit otherwise, not to speed one up. + ## Next steps - Read the [GPU memory usage](./model_memory_anatomy) doc to understand what is driving memory usage on the GPU during training. diff --git a/src/transformers/modeling_utils.py b/src/transformers/modeling_utils.py index 57709a67e161..ded5825dddc1 100644 --- a/src/transformers/modeling_utils.py +++ b/src/transformers/modeling_utils.py @@ -39,6 +39,7 @@ from safetensors.torch import load as _safe_load_bytes from safetensors.torch import save_file as safe_save_file from torch import Tensor, nn +from torch.autograd.graph import save_on_cpu from torch.distributions import constraints from torch.utils.checkpoint import checkpoint @@ -3183,7 +3184,9 @@ def init_weights(self): # Tie weights needs to be called here, but it can use the pre-computed `all_tied_weights_keys` self.tie_weights(recompute_mapping=False) - def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None, every_n_layers: int = 1): + def gradient_checkpointing_enable( + self, gradient_checkpointing_kwargs=None, every_n_layers: int = 1, offload: bool = False + ): """ Activates gradient checkpointing for the current model. @@ -3195,6 +3198,11 @@ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None, ever Checkpoint only every `every_n_layers`-th decoder layer, leaving the rest to keep their activations. `1` checkpoints every layer, which is the usual all-or-nothing behavior. Larger values trade memory back for speed, which is worth it whenever the memory freed by full checkpointing is going unused. + offload (`bool`, *optional*, defaults to `False`): + Hold the activations saved for the recompute in pinned host memory rather than on the accelerator. + This frees `layers x sequence x hidden` bytes of device memory, which is what dominates at long + sequence lengths, and costs a device-to-host copy in the forward and a host-to-device copy in the + backward. Both copies run on the compute stream, so the step gets slower. gradient_checkpointing_kwargs (dict, *optional*): Additional keyword arguments passed along to the `torch.utils.checkpoint.checkpoint` function. """ @@ -3204,7 +3212,16 @@ def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None, ever if gradient_checkpointing_kwargs is None: gradient_checkpointing_kwargs = {"use_reentrant": False} - gradient_checkpointing_func = functools.partial(checkpoint, **gradient_checkpointing_kwargs) + if offload: + device_type = torch.accelerator.current_accelerator().type + + def checkpoint_func(function, *args, **kwargs): + with save_on_cpu(pin_memory=True, device_type=device_type): + return checkpoint(function, *args, **kwargs) + else: + checkpoint_func = checkpoint + + gradient_checkpointing_func = functools.partial(checkpoint_func, **gradient_checkpointing_kwargs) # For old GC format (transformers < 4.35.0) for models that live on the Hub # we will fall back to the overwritten `_set_gradient_checkpointing` method diff --git a/src/transformers/trainer.py b/src/transformers/trainer.py index 351c4bb234a5..1a37e49911c8 100755 --- a/src/transformers/trainer.py +++ b/src/transformers/trainer.py @@ -1401,12 +1401,16 @@ def train( # Activate gradient checkpointing if needed if args.gradient_checkpointing: - # `every_n_layers` selects which layers are checkpointed; the remaining keys are forwarded to - # `torch.utils.checkpoint.checkpoint`, so it has to come out of the dict before that happens. + # `every_n_layers` selects which layers are checkpointed and `offload` where their saved + # activations live; the remaining keys are forwarded to `torch.utils.checkpoint.checkpoint`, so both + # have to come out of the dict before that happens. gc_kwargs = dict(args.gradient_checkpointing_kwargs or {}) every_n_layers = gc_kwargs.pop("every_n_layers", 1) + offload = gc_kwargs.pop("offload", False) self.model.gradient_checkpointing_enable( - gradient_checkpointing_kwargs=gc_kwargs or None, every_n_layers=every_n_layers + gradient_checkpointing_kwargs=gc_kwargs or None, + every_n_layers=every_n_layers, + offload=offload, ) # If the model uses a tokenizer, it may have a new tokens for fine-tuning purposes. diff --git a/src/transformers/training_args.py b/src/transformers/training_args.py index 8f42347bb232..b2cac7970e40 100644 --- a/src/transformers/training_args.py +++ b/src/transformers/training_args.py @@ -306,7 +306,9 @@ class TrainingArguments: gradient_checkpointing_kwargs (`dict`, *optional*, defaults to `None`): Keyword arguments passed to `gradient_checkpointing_enable()`. `every_n_layers` checkpoints only every n-th decoder layer instead of all of them; `1` is the usual all-or-nothing behavior, and larger values - give some memory back to speed. Any other key is forwarded to `torch.utils.checkpoint.checkpoint`. + give some memory back to speed. `offload` holds the saved activations in pinned host memory, which + frees `layers x sequence x hidden` bytes of device memory and makes the step slower. Any other key is + forwarded to `torch.utils.checkpoint.checkpoint`. > Compilation @@ -906,7 +908,8 @@ class TrainingArguments: metadata={ "help": "Keyword arguments passed to `gradient_checkpointing_enable()`. `every_n_layers` checkpoints " "only every n-th decoder layer instead of all of them; `1` is the usual all-or-nothing behavior, and " - "larger values give some memory back to speed. Any other key is forwarded to " + "larger values give some memory back to speed. `offload` holds the saved activations in pinned host " + "memory, which frees device memory and makes the step slower. Any other key is forwarded to " "`torch.utils.checkpoint.checkpoint`." }, ) diff --git a/tests/utils/test_modeling_utils.py b/tests/utils/test_modeling_utils.py index 3f1d61015203..93e245661dc6 100644 --- a/tests/utils/test_modeling_utils.py +++ b/tests/utils/test_modeling_utils.py @@ -67,6 +67,9 @@ LoggingLevel, TemporaryHubRepo, TestCasePlus, + backend_empty_cache, + backend_memory_allocated, + backend_synchronize, force_serialization_as_bin_files, hub_retry, is_staging_test, @@ -3903,3 +3906,64 @@ def forward(self, x): self.assertTrue(model.is_custom_code()) self.assertFalse(model.is_remote_code()) + + +@require_torch_accelerator +class GradientCheckpointingOffloadTest(unittest.TestCase): + """`gradient_checkpointing_enable(offload=True)` holds the saved activations in host memory.""" + + def _model(self, num_hidden_layers=8, hidden_size=256): + from transformers import LlamaModel, set_seed + + config = LlamaConfig( + num_hidden_layers=num_hidden_layers, + hidden_size=hidden_size, + intermediate_size=hidden_size * 2, + num_attention_heads=4, + num_key_value_heads=4, + vocab_size=128, + ) + set_seed(0) + return LlamaModel(config).to(torch_device).train() + + def _backward(self, model, input_ids): + model(input_ids=input_ids).last_hidden_state.float().pow(2).mean().backward() + + def test_gradients_match_the_non_offloaded_run(self): + model = self._model() + input_ids = torch.randint(0, 128, (1, 64), device=torch_device) + + model.gradient_checkpointing_enable() + self._backward(model, input_ids) + expected = [p.grad.clone() for p in model.parameters()] + + model.zero_grad(set_to_none=True) + model.gradient_checkpointing_enable(offload=True) + self._backward(model, input_ids) + + for expected_grad, param in zip(expected, model.parameters()): + torch.testing.assert_close(param.grad, expected_grad) + + def test_frees_exactly_the_saved_activations(self): + num_hidden_layers, hidden_size, seq_len = 8, 256, 2048 + # Each checkpointed layer saves one `seq_len x hidden_size` input for its recompute. + saved_bytes = num_hidden_layers * seq_len * hidden_size * 4 # fp32 + + resident = [] + for offload in (False, True): + model = self._model(num_hidden_layers, hidden_size) + model.gradient_checkpointing_enable(offload=offload) + input_ids = torch.randint(0, 128, (1, seq_len), device=torch_device) + self._backward(model, input_ids) # warm the allocator + model.zero_grad(set_to_none=True) + backend_synchronize(torch_device) + backend_empty_cache(torch_device) + + # Sampled after the forward, where every layer's saved input is still live. + base = backend_memory_allocated(torch_device) + output = model(input_ids=input_ids) + backend_synchronize(torch_device) + resident.append(backend_memory_allocated(torch_device) - base) + del output, model + + self.assertEqual(resident[0] - resident[1], saved_bytes) From 764ed518002a07e8f7733b33d79017caccccb8b3 Mon Sep 17 00:00:00 2001 From: Lysandre Debut Date: Tue, 1 Sep 2026 06:01:57 +0000 Subject: [PATCH 004/996] Clarify device placement in pipelines (#47367) --- docs/source/en/pipeline_tutorial.md | 2 +- src/transformers/pipelines/__init__.py | 13 ++++++++----- src/transformers/pipelines/base.py | 16 ++++++++++------ 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/docs/source/en/pipeline_tutorial.md b/docs/source/en/pipeline_tutorial.md index 64a98c59cd35..d22bf98282e9 100644 --- a/docs/source/en/pipeline_tutorial.md +++ b/docs/source/en/pipeline_tutorial.md @@ -111,7 +111,7 @@ This section introduces you to some of the more important parameters. ### Device -[`Pipeline`] is compatible with many hardware types, including GPUs, CPUs, Apple Silicon, and more. Configure the hardware type with the `device` parameter. By default, [`Pipeline`] runs on a CPU which is given by `device=-1`. +[`Pipeline`] is compatible with many hardware types, including GPUs, CPUs, Apple Silicon, and more. Configure the hardware type with the `device` parameter. By default, when `device` is left unset, [`Pipeline`] automatically places the model on the first available accelerator (CUDA GPU, Apple Silicon MPS, XPU, ...) and only falls back to a CPU when none is available. Pass `device="cpu"` to force it to run on a CPU. diff --git a/src/transformers/pipelines/__init__.py b/src/transformers/pipelines/__init__.py index d4a033d8b807..1c57ae578b10 100755 --- a/src/transformers/pipelines/__init__.py +++ b/src/transformers/pipelines/__init__.py @@ -793,9 +793,11 @@ def pipeline( token (`str` or *bool*, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated when running `hf auth login`. - device (`int` or `str` or `torch.device`): + device (`int` or `str` or `torch.device`, *optional*): Defines the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank like `1`) on which this - pipeline will be allocated. + pipeline will be allocated. When left unset, the pipeline is automatically placed on the first available + accelerator (CUDA, MPS, XPU, ...) and only falls back to CPU when none is available; the model is moved + there for you. Pass `device="cpu"` (or `-1`) to force CPU. Cannot be used together with `device_map`. device_map (`str` or `dict[str, Union[int, str, torch.device]`, *optional*): Sent directly as `model_kwargs` (just a simpler shortcut). When `accelerate` library is present, set `device_map="auto"` to compute the most optimized `device_map` automatically (see @@ -808,9 +810,10 @@ def pipeline( - dtype (`str` or `torch.dtype`, *optional*): - Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model - (`torch.float16`, `torch.bfloat16`, ... or `"auto"`). + dtype (`str` or `torch.dtype`, *optional*, defaults to `"auto"`): + Precision the model is loaded in, forwarded to `from_pretrained`. Defaults to `"auto"`, which loads the + model in the dtype it was saved in. Pass an explicit `torch.float16`, `torch.bfloat16`, `torch.float32`, + ... to override it. trust_remote_code (`bool`, *optional*, defaults to `False`): Whether or not to allow for custom code defined on the Hub in their own modeling, configuration, tokenization or even pipeline files. This option should only be set to `True` for repositories you trust diff --git a/src/transformers/pipelines/base.py b/src/transformers/pipelines/base.py index a174d63bc40f..cbeb140ba5cb 100644 --- a/src/transformers/pipelines/base.py +++ b/src/transformers/pipelines/base.py @@ -701,12 +701,16 @@ def build_pipeline_init_args( pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) . args_parser ([`~pipelines.ArgumentHandler`], *optional*): Reference to the object in charge of parsing supplied pipeline parameters. - device (`int`, *optional*, defaults to -1): - Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on - the associated CUDA device id. You can pass native `torch.device` or a `str` too - dtype (`str` or `torch.dtype`, *optional*): - Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model - (`torch.float16`, `torch.bfloat16`, ... or `"auto"`)""" + device (`int` or `str` or `torch.device`, *optional*): + Device on which the pipeline is allocated. When left unset, the pipeline is placed on the first available + accelerator (CUDA, MPS, XPU, ...) and falls back to CPU only when none is available; the model is moved + there automatically. Pass `device="cpu"` (or `-1`) to force CPU, a positive ordinal or `"cuda:1"` to select + a specific accelerator, or a native `torch.device`/`str`. This argument cannot be combined with a model + already loaded via `accelerate` (i.e. one with an `hf_device_map`). + dtype (`str` or `torch.dtype`, *optional*, defaults to `"auto"`): + Precision the model is loaded in, forwarded to `from_pretrained`. Defaults to `"auto"`, which loads the + model in the dtype it was saved in (read from the checkpoint's `config.dtype`, otherwise inferred from the + weights). Pass an explicit `torch.float16`, `torch.bfloat16`, `torch.float32`, ... to override it.""" if supports_binary_output: docstring += r""" binary_output (`bool`, *optional*, defaults to `False`): From be255fb83084fcdb612018309e74ccbfb0f87090 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Quentin=20Gallou=C3=A9dec?= <45557362+qgallouedec@users.noreply.github.com> Date: Tue, 1 Sep 2026 06:05:45 +0000 Subject: [PATCH 005/996] Raise a clear error when a token is both forced and suppressed (#47511) --- .../generation/configuration_utils.py | 18 ++++++++++++++++ tests/generation/test_configuration_utils.py | 21 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/transformers/generation/configuration_utils.py b/src/transformers/generation/configuration_utils.py index ec58ca28e6bb..51fecca1a944 100644 --- a/src/transformers/generation/configuration_utils.py +++ b/src/transformers/generation/configuration_utils.py @@ -827,6 +827,24 @@ def validate(self, strict=False, user_set_attributes: set[str] | None = None): f"`return_dict_in_generate` is not `True`, `{extra_output_flag}` is ignored." ) + # 2.7. Forcing a token while suppressing it. If every forced (bos/eos) token is also suppressed, all logits + # become `-inf` at the forcing step, yielding `nan` probabilities and a generation crash (see #24099). + if self.suppress_tokens is not None: + suppressed_tokens = set(self.suppress_tokens) + for forced_attr in ("forced_bos_token_id", "forced_eos_token_id"): + forced_tokens = getattr(self, forced_attr) + if forced_tokens is None: + continue + forced_tokens = {forced_tokens} if isinstance(forced_tokens, int) else set(forced_tokens) + if forced_tokens and forced_tokens.issubset(suppressed_tokens): + raise ValueError( + f"Every token in `{forced_attr}` ({sorted(forced_tokens)}) is also in `suppress_tokens`. " + "Forcing a token while suppressing it sets all logits to `-inf` at the forcing step, which " + "produces `nan` probabilities and crashes generation. Remove the overlapping token(s) from " + f"either `{forced_attr}` or `suppress_tokens` (if you meant to prevent an early EOS token, use " + "`min_new_tokens` instead)." + ) + # 3. Check common issue: passing `generate` arguments inside the generation config generate_arguments = ( "logits_processor", diff --git a/tests/generation/test_configuration_utils.py b/tests/generation/test_configuration_utils.py index 96065609bd4c..537d530115ba 100644 --- a/tests/generation/test_configuration_utils.py +++ b/tests/generation/test_configuration_utils.py @@ -258,6 +258,27 @@ def test_validate_assistant_ensemble_weight(self): with self.assertRaises(ValueError): GenerationConfig(assistant_ensemble_weight=invalid).validate() + def test_validate_suppress_forced_token_overlap(self): + """ + A token that is both forced (`forced_bos_token_id`/`forced_eos_token_id`) and suppressed (`suppress_tokens`) + makes all logits `-inf` at the forcing step, yielding `nan` probabilities and a generation crash (see #24099). + `validate` must reject this combination with a clear error. + """ + # Every forced token is also suppressed -> guaranteed crash -> must raise + with self.assertRaises(ValueError): + GenerationConfig(forced_eos_token_id=2, suppress_tokens=[2]) + with self.assertRaises(ValueError): + GenerationConfig(forced_bos_token_id=3, suppress_tokens=[3, 4]) + with self.assertRaises(ValueError): + GenerationConfig(forced_eos_token_id=[2, 5], suppress_tokens=[2, 5, 9]) + + # Partial overlap: at least one forced token survives, so no crash is possible -> must NOT raise + GenerationConfig(forced_eos_token_id=[2, 5], suppress_tokens=[2]).validate() + # No overlap, or only one of the two set -> must NOT raise + GenerationConfig(forced_eos_token_id=2, suppress_tokens=[5, 6]).validate() + GenerationConfig(suppress_tokens=[2]).validate() + GenerationConfig(forced_eos_token_id=2).validate() + def test_assistant_ensemble_weight_default_and_round_trip(self): """Default is `None`; values round-trip through `to_dict`/`from_dict`.""" self.assertIsNone(GenerationConfig().assistant_ensemble_weight) From 45bd05b8f8825d7639a180dcca7710a5fd654fc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Quentin=20Gallou=C3=A9dec?= <45557362+qgallouedec@users.noreply.github.com> Date: Tue, 1 Sep 2026 02:33:29 -0400 Subject: [PATCH 006/996] Init the process group with a load-scaled timeout for sharded loading (#48228) * Init the process group with a load-scaled timeout for sharded loading Sharded loading of a TB-scale checkpoint takes tens of minutes and ranks finish far apart (measured: >10 minutes spread on GLM-4.6, 714 GB over 16 ranks), so the fastest ranks' first collective dies on the default 10-minute NCCL watchdog. Use a 2-hour timeout when transformers initializes the group itself. * Move the timeout comment onto the argument it explains --- src/transformers/distributed/utils.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/transformers/distributed/utils.py b/src/transformers/distributed/utils.py index a21875ba96da..49f0f1c41814 100644 --- a/src/transformers/distributed/utils.py +++ b/src/transformers/distributed/utils.py @@ -14,6 +14,7 @@ from __future__ import annotations import os +from datetime import timedelta from typing import TYPE_CHECKING, TypeGuard from ..utils import is_torch_available, is_torch_distributed_available, is_torch_greater_or_equal, logging @@ -98,7 +99,12 @@ def _ensure_torch_distributed(device_type: str | None = None): getattr(torch, device_type).set_device(local_rank) device_id = torch.device(device_type, local_rank) torch.distributed.init_process_group( - backend=backend, rank=rank, world_size=world_size, device_id=device_id + backend=backend, + rank=rank, + world_size=world_size, + device_id=device_id, + # Sharded loading takes tens of minutes with high rank skew; the default 10-minute watchdog is too short + timeout=timedelta(hours=2), ) except Exception as e: raise OSError( From eed9b89292ce05ec68ed539db59b8e8d868cbf0c Mon Sep 17 00:00:00 2001 From: Pablo Montalvo <39954772+molbap@users.noreply.github.com> Date: Tue, 1 Sep 2026 06:42:27 +0000 Subject: [PATCH 007/996] Grounding dino fp16 dtype [backlog] (#48438) * align dtype of queries, keys in Grounding DINO To support #32672 * update dtype of grid_y, grid_x * Create dtype-dependent tensors at the model dtype in Grounding DINO valid_ratios and the reference point grid were built as float32 regardless of the model dtype, so grid_sample and the reference point head received float32 against half weights. fp16 and bf16 both crashed. get_valid_ratio gains the dtype parameter that deformable_detr, lw_detr, mask2former, oneformer and rf_detr already have. Fixes #32672 Co-authored-by: Sam --------- Co-authored-by: Sam --- .../grounding_dino/modeling_grounding_dino.py | 21 +++++++++---------- .../modeling_mm_grounding_dino.py | 21 +++++++++---------- 2 files changed, 20 insertions(+), 22 deletions(-) diff --git a/src/transformers/models/grounding_dino/modeling_grounding_dino.py b/src/transformers/models/grounding_dino/modeling_grounding_dino.py index b73d70f29edf..930974381816 100644 --- a/src/transformers/models/grounding_dino/modeling_grounding_dino.py +++ b/src/transformers/models/grounding_dino/modeling_grounding_dino.py @@ -1427,8 +1427,8 @@ def get_reference_points(spatial_shapes_list, valid_ratios, device): reference_points_list = [] for level, (height, width) in enumerate(spatial_shapes_list): ref_y, ref_x = torch.meshgrid( - torch.linspace(0.5, height - 0.5, height, dtype=torch.float32, device=device), - torch.linspace(0.5, width - 0.5, width, dtype=torch.float32, device=device), + torch.linspace(0.5, height - 0.5, height, dtype=valid_ratios.dtype, device=device), + torch.linspace(0.5, width - 0.5, width, dtype=valid_ratios.dtype, device=device), indexing="ij", ) # TODO: valid_ratios could be useless here. check https://github.com/fundamentalvision/Deformable-DETR/issues/36 @@ -1942,14 +1942,14 @@ def unfreeze_backbone(self): for name, param in self.backbone.conv_encoder.model.named_parameters(): param.requires_grad_(True) - def get_valid_ratio(self, mask): + def get_valid_ratio(self, mask, dtype=torch.float32): """Get the valid ratio of all feature maps.""" _, height, width = mask.shape - valid_height = torch.sum(mask[:, :, 0], 1) - valid_width = torch.sum(mask[:, 0, :], 1) - valid_ratio_height = valid_height.float() / height - valid_ratio_width = valid_width.float() / width + valid_height = torch.sum(mask[:, :, 0], 1, dtype=dtype) + valid_width = torch.sum(mask[:, 0, :], 1, dtype=dtype) + valid_ratio_height = valid_height / height + valid_ratio_width = valid_width / width valid_ratio = torch.stack([valid_ratio_width, valid_ratio_height], -1) return valid_ratio @@ -1978,8 +1978,8 @@ def generate_encoder_output_proposals(self, enc_output, padding_mask, spatial_sh valid_width = torch.sum(~mask_flatten_[:, 0, :, 0], 1) grid_y, grid_x = torch.meshgrid( - torch.linspace(0, height - 1, height, dtype=torch.float32, device=enc_output.device), - torch.linspace(0, width - 1, width, dtype=torch.float32, device=enc_output.device), + torch.linspace(0, height - 1, height, dtype=enc_output.dtype, device=enc_output.device), + torch.linspace(0, width - 1, width, dtype=enc_output.dtype, device=enc_output.device), indexing="ij", ) grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1) @@ -2147,8 +2147,7 @@ def forward( lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) spatial_shapes = torch.as_tensor(spatial_shapes_list, dtype=torch.long, device=source_flatten.device) level_start_index = torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1])) - valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1) - valid_ratios = valid_ratios.float() + valid_ratios = torch.stack([self.get_valid_ratio(m, dtype=source_flatten.dtype) for m in masks], 1) # Fourth, sent source_flatten + mask_flatten + lvl_pos_embed_flatten (backbone + proj layer output) through encoder # Also provide spatial_shapes, level_start_index and valid_ratios diff --git a/src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py b/src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py index 57a892950acb..8a36f9944c49 100644 --- a/src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py +++ b/src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py @@ -1099,8 +1099,8 @@ def get_reference_points(spatial_shapes_list, valid_ratios, device): reference_points_list = [] for level, (height, width) in enumerate(spatial_shapes_list): ref_y, ref_x = torch.meshgrid( - torch.linspace(0.5, height - 0.5, height, dtype=torch.float32, device=device), - torch.linspace(0.5, width - 0.5, width, dtype=torch.float32, device=device), + torch.linspace(0.5, height - 0.5, height, dtype=valid_ratios.dtype, device=device), + torch.linspace(0.5, width - 0.5, width, dtype=valid_ratios.dtype, device=device), indexing="ij", ) # TODO: valid_ratios could be useless here. check https://github.com/fundamentalvision/Deformable-DETR/issues/36 @@ -1839,14 +1839,14 @@ def unfreeze_backbone(self): for name, param in self.backbone.conv_encoder.model.named_parameters(): param.requires_grad_(True) - def get_valid_ratio(self, mask): + def get_valid_ratio(self, mask, dtype=torch.float32): """Get the valid ratio of all feature maps.""" _, height, width = mask.shape - valid_height = torch.sum(mask[:, :, 0], 1) - valid_width = torch.sum(mask[:, 0, :], 1) - valid_ratio_height = valid_height.float() / height - valid_ratio_width = valid_width.float() / width + valid_height = torch.sum(mask[:, :, 0], 1, dtype=dtype) + valid_width = torch.sum(mask[:, 0, :], 1, dtype=dtype) + valid_ratio_height = valid_height / height + valid_ratio_width = valid_width / width valid_ratio = torch.stack([valid_ratio_width, valid_ratio_height], -1) return valid_ratio @@ -1875,8 +1875,8 @@ def generate_encoder_output_proposals(self, enc_output, padding_mask, spatial_sh valid_width = torch.sum(~mask_flatten_[:, 0, :, 0], 1) grid_y, grid_x = torch.meshgrid( - torch.linspace(0, height - 1, height, dtype=torch.float32, device=enc_output.device), - torch.linspace(0, width - 1, width, dtype=torch.float32, device=enc_output.device), + torch.linspace(0, height - 1, height, dtype=enc_output.dtype, device=enc_output.device), + torch.linspace(0, width - 1, width, dtype=enc_output.dtype, device=enc_output.device), indexing="ij", ) grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1) @@ -2044,8 +2044,7 @@ def forward( lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) spatial_shapes = torch.as_tensor(spatial_shapes_list, dtype=torch.long, device=source_flatten.device) level_start_index = torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1])) - valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1) - valid_ratios = valid_ratios.float() + valid_ratios = torch.stack([self.get_valid_ratio(m, dtype=source_flatten.dtype) for m in masks], 1) # Fourth, sent source_flatten + mask_flatten + lvl_pos_embed_flatten (backbone + proj layer output) through encoder # Also provide spatial_shapes, level_start_index and valid_ratios From 4ff98bf236b4b5842229bae752b83826e940bdf5 Mon Sep 17 00:00:00 2001 From: lorenzozane Date: Tue, 1 Sep 2026 07:02:06 +0000 Subject: [PATCH 008/996] fix: decode() batch path respects self.clean_up_tokenization_spaces (#47793) Fix decode() batch path hardcoding clean_up_tokenization_spaces=False instead of None The batch path of decode() was hardcoding clean_up_tokenization_spaces=False when the kwarg was not explicitly provided, overriding self.clean_up_tokenization_spaces. The single-sequence path correctly leaves it unspecified (None), allowing _decode to fall back to the tokenizer's configured value. Co-authored-by: Ita Zaporozhets <31893021+itazap@users.noreply.github.com> --- src/transformers/tokenization_utils_base.py | 2 +- tests/models/bert/test_tokenization_bert.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/transformers/tokenization_utils_base.py b/src/transformers/tokenization_utils_base.py index 206e4b83955a..8972e0b04343 100644 --- a/src/transformers/tokenization_utils_base.py +++ b/src/transformers/tokenization_utils_base.py @@ -2881,7 +2881,7 @@ def decode( # If we received batched input, decode each sequence if isinstance(token_ids, (list, tuple)) and len(token_ids) > 0 and isinstance(token_ids[0], (list, tuple)): - clean_up_tokenization_spaces = kwargs.pop("clean_up_tokenization_spaces", False) + clean_up_tokenization_spaces = kwargs.pop("clean_up_tokenization_spaces", None) return [ self._decode( token_ids=seq, diff --git a/tests/models/bert/test_tokenization_bert.py b/tests/models/bert/test_tokenization_bert.py index b7aba73f2752..994837c8a4ac 100644 --- a/tests/models/bert/test_tokenization_bert.py +++ b/tests/models/bert/test_tokenization_bert.py @@ -32,3 +32,15 @@ class BertTokenizationTest(TokenizerTesterMixin, unittest.TestCase): integration_expected_token_ids = [2023, 2003, 1037, 3231, 100, 1045, 2001, 2141, 1999, 6227, 8889, 2692, 1010, 1998, 2023, 2003, 6270, 1012, 1910, 100, 1916, 1921, 100, 100, 7632, 7592, 7632, 7592, 7592, 1026, 1055, 1028, 7632, 1026, 1055, 1028, 2045, 1996, 2206, 5164, 2323, 2022, 7919, 12359, 1024, 7592, 1012, 2021, 20868, 2094, 1998, 100, 20868, 2094, 100, 4931, 2129, 2024, 2017, 2725] # fmt: skip expected_tokens_from_ids = ['this', 'is', 'a', 'test', '[UNK]', 'i', 'was', 'born', 'in', '92', '##00', '##0', ',', 'and', 'this', 'is', 'false', '.', '生', '[UNK]', '的', '真', '[UNK]', '[UNK]', 'hi', 'hello', 'hi', 'hello', 'hello', '<', 's', '>', 'hi', '<', 's', '>', 'there', 'the', 'following', 'string', 'should', 'be', 'properly', 'encoded', ':', 'hello', '.', 'but', 'ir', '##d', 'and', '[UNK]', 'ir', '##d', '[UNK]', 'hey', 'how', 'are', 'you', 'doing'] # fmt: skip integration_expected_decoded_text = "this is a test [UNK] i was born in 92000, and this is false. 生 [UNK] 的 真 [UNK] [UNK] hi hello hi hello hello < s > hi < s > there the following string should be properly encoded : hello. but ird and [UNK] ird [UNK] hey how are you doing" + + def test_decode_batch_uses_tokenizer_cleanup_setting(self): + tokenizer = self.get_tokenizer(clean_up_tokenization_spaces=True) + token_ids = tokenizer.encode("hello , world !", add_special_tokens=False) + tokenizer.backend_tokenizer.decoder.cleanup = False + + self.assertEqual(tokenizer.decode(token_ids), "hello, world!") + self.assertEqual(tokenizer.decode([token_ids]), ["hello, world!"]) + self.assertEqual( + tokenizer.decode([token_ids], clean_up_tokenization_spaces=False), + ["hello , world !"], + ) From 0cc72b4bb99a0907660471435c996986b6f1c678 Mon Sep 17 00:00:00 2001 From: Harshal Janjani Date: Tue, 1 Sep 2026 08:41:32 +0000 Subject: [PATCH 009/996] model: Add NVIDIA Canary-1B-v2 to Transformers (#46825) * CanaryConverter draft * init: Add files (canary-1b-v2) * fix: Resolve Bandit warning * fix: Make CI green 1 * refactor: Address review round 1 - 1 * refactor: Address review round 1 - 2 * refactor: Address review round 2 * DIrectly create config file since doesn't need modular. * Testing nits/refactor. * Refactor common processing utillities. * refactor: Address review round 3 * Nits * refactor: Address review round 4 * refactor: Address review round 5 * Modular nits * fix: CI issue * Address comments on docs. * Apply suggestion from @vasqu Co-authored-by: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com> * address config comment * fix: Make changes * address modular comments * fix: Make changes 2 * Move dtype casting. * Address comments * Add back decorators. * replace: NVIDIA Canary-1B-V2 repo --------- Co-authored-by: Eustache Le Bihan Co-authored-by: Eric B Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> Co-authored-by: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com> --- docs/source/en/_toctree.yml | 2 + docs/source/en/model_doc/audioflamingo3.md | 1 - docs/source/en/model_doc/canary.md | 168 +++++ src/transformers/audio_utils.py | 98 +++ src/transformers/convert_slow_tokenizer.py | 11 + src/transformers/models/__init__.py | 1 + .../processing_audioflamingo3.py | 6 +- src/transformers/models/auto/auto_mappings.py | 4 + .../models/auto/feature_extraction_auto.py | 1 + src/transformers/models/auto/modeling_auto.py | 2 + .../models/auto/tokenization_auto.py | 1 + src/transformers/models/canary/__init__.py | 28 + .../models/canary/configuration_canary.py | 156 ++++ .../canary/convert_canary_nemo_to_hf.py | 249 +++++++ .../models/canary/modeling_canary.py | 696 ++++++++++++++++++ .../models/canary/modular_canary.py | 300 ++++++++ .../models/canary/processing_canary.py | 178 +++++ .../models/glmasr/modular_glmasr.py | 6 +- .../models/glmasr/processing_glmasr.py | 6 +- .../models/qwen3_asr/processing_qwen3_asr.py | 74 +- .../vibevoice_asr/processing_vibevoice_asr.py | 8 +- .../canary/expected_results_batch.json | 6 + .../expected_results_transcription.json | 5 + .../canary/expected_results_translation.json | 5 + tests/models/canary/__init__.py | 0 tests/models/canary/test_modeling_canary.py | 562 ++++++++++++++ tests/models/canary/test_processing_canary.py | 94 +++ 27 files changed, 2587 insertions(+), 81 deletions(-) create mode 100644 docs/source/en/model_doc/canary.md create mode 100644 src/transformers/models/canary/__init__.py create mode 100644 src/transformers/models/canary/configuration_canary.py create mode 100644 src/transformers/models/canary/convert_canary_nemo_to_hf.py create mode 100644 src/transformers/models/canary/modeling_canary.py create mode 100644 src/transformers/models/canary/modular_canary.py create mode 100644 src/transformers/models/canary/processing_canary.py create mode 100644 tests/fixtures/canary/expected_results_batch.json create mode 100644 tests/fixtures/canary/expected_results_transcription.json create mode 100644 tests/fixtures/canary/expected_results_translation.json create mode 100644 tests/models/canary/__init__.py create mode 100644 tests/models/canary/test_modeling_canary.py create mode 100644 tests/models/canary/test_processing_canary.py diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index d623ad68b516..8c50587f1b72 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -1117,6 +1117,8 @@ title: Audio Spectrogram Transformer - local: model_doc/bark title: Bark + - local: model_doc/canary + title: Canary - local: model_doc/clap title: CLAP - local: model_doc/cohere_asr diff --git a/docs/source/en/model_doc/audioflamingo3.md b/docs/source/en/model_doc/audioflamingo3.md index 8e1a3fa4a870..45f9177b02d3 100644 --- a/docs/source/en/model_doc/audioflamingo3.md +++ b/docs/source/en/model_doc/audioflamingo3.md @@ -289,7 +289,6 @@ conversation = [ inputs = processor.apply_chat_template( conversation, tokenize=True, - add_generation_prompt=True, return_dict=True, processor_kwargs={"output_labels": True}, ).to(model.device, dtype=model.dtype) diff --git a/docs/source/en/model_doc/canary.md b/docs/source/en/model_doc/canary.md new file mode 100644 index 000000000000..b8bb2ebad6a0 --- /dev/null +++ b/docs/source/en/model_doc/canary.md @@ -0,0 +1,168 @@ + +*This model was published in HF papers on 2025-09-17 and contributed to Hugging Face Transformers on 2026-08-31.* + +
+SDPA +
+ +# Canary + +## Overview + +Canary-1B-v2 was proposed in [Canary-1B-v2 & Parakeet-TDT-0.6B-v3: Efficient and High-Performance Models for Multilingual ASR and AST](https://huggingface.co/papers/2509.14128) by Monica Sekoyan, Nithin Rao Koluguri, Nune Tadevosyan, Piotr Zelasko, Travis Bartley, Nikolay Karpov, Jagadeesh Balam, and Boris Ginsburg. + +The abstract from the paper is the following: + +*This report introduces Canary-1B-v2, a fast, robust multilingual model for Automatic Speech Recognition (ASR) and Speech-to-Text Translation (AST). Built with a FastConformer encoder and Transformer decoder, it supports 25 European languages. The model was trained on 1.7M hours of total data samples, including Granary and NeMo ASR Set 3.0, with non-speech audio added to reduce hallucinations for ASR and AST. We describe its two-stage pre-training and fine-tuning process with dynamic data balancing, as well as experiments with an nGPT encoder. Results show nGPT scales well with massive data, while FastConformer excels after fine-tuning. For timestamps, Canary-1B-v2 uses the NeMo Forced Aligner (NFA) with an auxiliary CTC model, providing reliable segment-level timestamps for ASR and AST. Evaluations show Canary-1B-v2 outperforms Whisper-large-v3 on English ASR while being 10× faster, and delivers competitive multilingual ASR and AST performance against larger models like Seamless-M4T-v2-large and LLM-based systems. We also release Parakeet-TDT-0.6B-v3, a successor to v2, offering multilingual ASR across the same 25 languages with just 600M parameters.* + +Canary reuses the [Fast Conformer](https://huggingface.co/papers/2305.05084) encoder from [Parakeet](./parakeet.md) (loaded through [`ParakeetEncoder`] / [`ParakeetEncoderConfig`]) and pairs it with a Transformer decoder that uses fixed sinusoidal positional embeddings, cross-attention to the encoder outputs and tied input/output embeddings. The task is selected through a decoder prompt prefix built by [`CanaryProcessor`] of the form `<|startofcontext|> <|startoftranscript|> <|emo:undefined|> <|noitn|> <|notimestamp|> <|nodiarize|>`, where `source_lang == target_lang` selects transcription and otherwise selects translation. + +The original implementation can be found in [NVIDIA NeMo](https://github.com/NVIDIA/NeMo). A model checkpoint is available at [nvidia/canary-1b-v2](https://huggingface.co/nvidia/canary-1b-v2). + +This model was contributed by [Harshal Janjani](https://huggingface.co/harshaljanjani). + +> [!NOTE] +> Segment-level timestamps for Canary-1B-v2 are produced by the external NeMo Forced Aligner (NFA) with an auxiliary CTC model, not by the decoder, so they are not part of the `generate` output. + +## Usage + +### Transcription + +The simplest way to transcribe audio is with `apply_transcription_request`, which builds the multitask decoder prompt for you (it is a convenience wrapper for `apply_chat_template`). + +```python +from datasets import load_dataset, Audio +from transformers import AutoProcessor, AutoModelForSpeechSeq2Seq + +processor = AutoProcessor.from_pretrained("nvidia/canary-1b-v2") +model = AutoModelForSpeechSeq2Seq.from_pretrained("nvidia/canary-1b-v2", device_map="auto") + +ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate)) + +inputs = processor.apply_transcription_request(audio=ds[0]["audio"]["array"], source_language="en").to(model.device) +generated_ids = model.generate(**inputs, max_new_tokens=128) +print(processor.decode(generated_ids, skip_special_tokens=True)[0]) +``` + +### Translation + +Set `target_language` to a different language than `source_language` for speech-to-text translation. + +```python +... + +inputs = processor.apply_transcription_request( + audio=ds[0]["audio"]["array"], source_language="en", target_language="de" +).to(model.device) +generated_ids = model.generate(**inputs, max_new_tokens=128) +print(processor.decode(generated_ids, skip_special_tokens=True)[0]) +``` + +### Batch inference + +Pass a list of audios and, optionally, a list of `source_language` / `target_language`. + +```python +... + +audios = [ds[0]["audio"]["array"], ds[1]["audio"]["array"]] +# single entries get broadcasted to list +inputs = processor.apply_transcription_request( + audio=audios, source_language="en", target_language=["en", "de"] +).to(model.device) +generated_ids = model.generate(**inputs, max_new_tokens=128) +for text in processor.decode(generated_ids, skip_special_tokens=True): + print(text) +``` + +### Torch compile + +For autoregressive transcription, `torch.compile` accelerates the per-token forward passes inside `generate` by providing a `CompileConfig` object. + +```python +... + +from transformers import CompileConfig + +inputs = processor.apply_transcription_request(audio=ds[0]["audio"]["array"], source_language="en").to(model.device) +compile_config = CompileConfig() + +# Warmup +for _ in range(3): + _ = model.generate(**inputs, max_new_tokens=128, cache_implementation="static", compile_config=compile_config) + +# Apply model +generated_ids = model.generate(**inputs, max_new_tokens=128, cache_implementation="static", compile_config=compile_config) +print(processor.decode(generated_ids, skip_special_tokens=True)[0]) +``` + +### Training + +Canary can be trained with the loss outputted by the model. Put the target transcript in the assistant turn and pass `output_labels=True`. Padding positions are masked automatically. + +```python +... + +model.train() +transcription = "mister Quilter is the apostle of the middle classes, and we are glad to welcome his gospel." + +conversation = [ + [ + { + "role": "user", + "content": [ + {"type": "audio", "audio": ds[0]["audio"]["array"]}, + {"type": "text", "source_language": "en", "target_language": "en", "punctuation": True}, + ], + }, + {"role": "assistant", "content": transcription}, + ] +] + +inputs = processor.apply_chat_template( + conversation, + tokenize=True, + return_dict=True, + processor_kwargs={"output_labels": True}, +).to(model.device) + +outputs = model(**inputs) +outputs.loss.backward() +``` + +## CanaryConfig + +[[autodoc]] CanaryConfig + +## CanaryDecoderConfig + +[[autodoc]] CanaryDecoderConfig + +## CanaryProcessor + +[[autodoc]] CanaryProcessor + +## CanaryModel + +[[autodoc]] CanaryModel + - forward + +## CanaryForConditionalGeneration + +[[autodoc]] CanaryForConditionalGeneration + - forward diff --git a/src/transformers/audio_utils.py b/src/transformers/audio_utils.py index ece33f081799..e29ffe4e6377 100644 --- a/src/transformers/audio_utils.py +++ b/src/transformers/audio_utils.py @@ -445,6 +445,104 @@ def make_list_of_audio_chat_template( return make_list_of_audio(audio) +def make_audio_chat_template_content(audio_item) -> dict: + """ + Build a chat-template content dict for a single audio item. + + Args: + audio_item (`str` or array-like): + A single audio item. Strings are treated as local paths or URLs; other values (numpy/torch arrays) are + forwarded directly. + + Returns: + `dict`: A chat-template content dict, e.g. `{"type": "audio", "path": ...}` for strings or + `{"type": "audio", "audio": ...}` otherwise. + """ + if isinstance(audio_item, str): + return {"type": "audio", "path": audio_item} + return {"type": "audio", "audio": audio_item} + + +def resolve_language(language: str | None, code_to_name: dict[str, str], return_code: bool = True) -> str | None: + """ + Map a language code or name to its canonical form, with validation. + + Accepts either a language code (e.g. ``"zh"``, ``"en"``) or a full name (e.g. ``"Chinese"``, ``"English"``) and + returns the canonical code or name depending on ``return_code``. ``None`` passes through unchanged (auto-detect). + + Args: + language (`str` or `None`): + The language code or full name to resolve. ``None`` is returned unchanged. + code_to_name (`dict[str, str]`): + Mapping from language code to full language name for the model's supported languages. + return_code (`bool`, *optional*, defaults to `True`): + Whether to return the canonical language ``code``. If ``False``, returns the full language ``name``. + + Returns: + `str` or `None`: The canonical language code or name, or ``None`` if ``language`` is ``None``. + + Raises: + `ValueError`: If the language is not recognized. + """ + if language is None: + return None + + language_lower = language.lower() + # Try code lookup first, then full-name lookup (both case-insensitive) + for code, name in code_to_name.items(): + if language_lower == code.lower() or language_lower == name.lower(): + return code if return_code else name + + raise ValueError( + f"Unsupported language: {language!r}. Use a language code " + f"(e.g. 'en', 'zh') or full name (e.g. 'English', 'Chinese'). " + f"Supported codes: {sorted(code_to_name.keys())}. " + f"Supported names: {sorted(set(code_to_name.values()))}." + ) + + +def prepare_language_inputs( + language: str | list[str] | None, + batch_size: int, + code_to_name: dict[str, str], + allow_broadcast: bool = False, + return_code: bool = True, +) -> list[str | None]: + """ + Broadcast and validate a language argument to match ``batch_size``. + + Accepts language codes (e.g. ``"zh"``, ``"en"``) or full names (e.g. ``"Chinese"``, ``"English"``). Each value is + resolved to its canonical form via [`resolve_language`]. + + Args: + language (`str`, `list[str]`, or `None`): + The language hint(s). A single value is broadcast to the whole batch; a list must match ``batch_size`` + (unless ``allow_broadcast`` is set). ``None`` disables language hints for the whole batch. + batch_size (`int`): + The number of samples in the batch. + code_to_name (`dict[str, str]`): + Mapping from language code to full language name for the model's supported languages. + allow_broadcast (`bool`, *optional*, defaults to `False`): + Whether a single-element list may be broadcast to the whole batch. + return_code (`bool`, *optional*, defaults to `True`): + Whether to return canonical language ``code``s. If ``False``, returns full language ``name``s. + + Returns: + `list[str | None]`: The resolved language for each sample. + """ + if language is None: + return [None] * batch_size + if isinstance(language, str): + return [resolve_language(language, code_to_name, return_code)] * batch_size + if isinstance(language, (list, tuple)): + if allow_broadcast and len(language) == 1 and batch_size > 1: + return [resolve_language(language[0], code_to_name, return_code)] * batch_size + if len(language) != batch_size: + raise ValueError(f"Got {len(language)} language(s) for {batch_size} sample(s); counts must match.") + return [resolve_language(lang, code_to_name, return_code) for lang in language] + raise TypeError("`language` must be a string, a list of strings, or `None`.") + + def hertz_to_mel(freq: float | np.ndarray, mel_scale: str = "htk") -> float | np.ndarray: """ Convert frequency from hertz to mels. diff --git a/src/transformers/convert_slow_tokenizer.py b/src/transformers/convert_slow_tokenizer.py index 9698e19627f4..cf6de5681b75 100644 --- a/src/transformers/convert_slow_tokenizer.py +++ b/src/transformers/convert_slow_tokenizer.py @@ -1876,6 +1876,17 @@ def tokenizer(self, proto): return tokenizer +class CanaryConverter(ParakeetConverter): + def __init__(self, vocab_file=None, *args): + super().__init__(vocab_file, *args) + # Only the `<|...|>` (type 4) control tokens are special; other type-4 pieces (digits, ``) are plain text. + self.special_tokens = { + piece.piece + for piece in self.proto.pieces + if piece.type == 4 and piece.piece.startswith("<|") and piece.piece.endswith("|>") + } + + def bytes_to_unicode(): """ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control diff --git a/src/transformers/models/__init__.py b/src/transformers/models/__init__.py index 6254391ed6c0..91ba473aa245 100644 --- a/src/transformers/models/__init__.py +++ b/src/transformers/models/__init__.py @@ -64,6 +64,7 @@ from .bros import * from .byt5 import * from .camembert import * + from .canary import * from .canine import * from .chameleon import * from .chinese_clip import * diff --git a/src/transformers/models/audioflamingo3/processing_audioflamingo3.py b/src/transformers/models/audioflamingo3/processing_audioflamingo3.py index 793b535b55a1..26d930d0ecfc 100644 --- a/src/transformers/models/audioflamingo3/processing_audioflamingo3.py +++ b/src/transformers/models/audioflamingo3/processing_audioflamingo3.py @@ -16,7 +16,7 @@ import numpy as np -from ...audio_utils import AudioInput, make_list_of_audio_chat_template +from ...audio_utils import AudioInput, make_audio_chat_template_content, make_list_of_audio_chat_template from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack from ...tokenization_utils_base import TextInput @@ -237,9 +237,7 @@ def apply_transcription_request( "role": "user", "content": [ {"type": "text", "text": prompt_text}, - {"type": "audio", "path": audio_item} - if isinstance(audio_item, str) - else {"type": "audio", "audio": audio_item}, + make_audio_chat_template_content(audio_item), ], } ] diff --git a/src/transformers/models/auto/auto_mappings.py b/src/transformers/models/auto/auto_mappings.py index 019d8e26d77b..4f400bef9891 100644 --- a/src/transformers/models/auto/auto_mappings.py +++ b/src/transformers/models/auto/auto_mappings.py @@ -75,6 +75,8 @@ ("bridgetower_vision_model", "BridgeTowerVisionConfig"), ("bros", "BrosConfig"), ("camembert", "CamembertConfig"), + ("canary", "CanaryConfig"), + ("canary_decoder", "CanaryDecoderConfig"), ("canine", "CanineConfig"), ("chameleon", "ChameleonConfig"), ("chameleon_vqgan", "ChameleonVQVAEConfig"), @@ -755,6 +757,7 @@ ("blt_patcher", "blt"), ("bridgetower_text_model", "bridgetower"), ("bridgetower_vision_model", "bridgetower"), + ("canary_decoder", "canary"), ("chameleon_vqgan", "chameleon"), ("chinese_clip_text_model", "chinese_clip"), ("chinese_clip_vision_model", "chinese_clip"), @@ -1063,6 +1066,7 @@ ("blip-2", "Blip2Processor"), ("bridgetower", "BridgeTowerProcessor"), ("bros", "BrosProcessor"), + ("canary", "CanaryProcessor"), ("chameleon", "ChameleonProcessor"), ("chinese_clip", "ChineseCLIPProcessor"), ("clap", "ClapProcessor"), diff --git a/src/transformers/models/auto/feature_extraction_auto.py b/src/transformers/models/auto/feature_extraction_auto.py index 4b776acfbf28..836404afd844 100644 --- a/src/transformers/models/auto/feature_extraction_auto.py +++ b/src/transformers/models/auto/feature_extraction_auto.py @@ -37,6 +37,7 @@ MISSING_FEATURE_EXTRACTOR_MAPPING_NAMES = OrderedDict( [ ("audioflamingo3", "WhisperFeatureExtractor"), + ("canary", "ParakeetFeatureExtractor"), ("csm", "EncodecFeatureExtractor"), ("data2vec-audio", "Wav2Vec2FeatureExtractor"), ("glmasr", "WhisperFeatureExtractor"), diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index 128061ad1b91..3dcd71acd08b 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -79,6 +79,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("bridgetower", "BridgeTowerModel"), ("bros", "BrosModel"), ("camembert", "CamembertModel"), + ("canary", "CanaryModel"), ("canine", "CanineModel"), ("chameleon", "ChameleonModel"), ("chinese_clip", "ChineseCLIPModel"), @@ -1355,6 +1356,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = OrderedDict( [ + ("canary", "CanaryForConditionalGeneration"), ("cohere_asr", "CohereAsrForConditionalGeneration"), ("dia", "DiaForConditionalGeneration"), ("granite_speech", "GraniteSpeechForConditionalGeneration"), diff --git a/src/transformers/models/auto/tokenization_auto.py b/src/transformers/models/auto/tokenization_auto.py index 897265ad04b2..8c181f1cd92e 100644 --- a/src/transformers/models/auto/tokenization_auto.py +++ b/src/transformers/models/auto/tokenization_auto.py @@ -90,6 +90,7 @@ ("bros", "BertTokenizer" if is_tokenizers_available() else None), ("byt5", "ByT5Tokenizer"), ("camembert", "CamembertTokenizer" if is_tokenizers_available() else None), + ("canary", "TokenizersBackend" if is_tokenizers_available() else None), ("canine", "CanineTokenizer"), ("chinese_clip", "BertTokenizer" if is_tokenizers_available() else None), ("clap", "RobertaTokenizer"), diff --git a/src/transformers/models/canary/__init__.py b/src/transformers/models/canary/__init__.py new file mode 100644 index 000000000000..40138c0d4905 --- /dev/null +++ b/src/transformers/models/canary/__init__.py @@ -0,0 +1,28 @@ +# Copyright 2026 The HuggingFace 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. +from typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_canary import * + from .modeling_canary import * + from .processing_canary import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/src/transformers/models/canary/configuration_canary.py b/src/transformers/models/canary/configuration_canary.py new file mode 100644 index 000000000000..5144a1cc53eb --- /dev/null +++ b/src/transformers/models/canary/configuration_canary.py @@ -0,0 +1,156 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/canary/modular_canary.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_canary.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# 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. +from huggingface_hub.dataclasses import strict + +from ...configuration_utils import PreTrainedConfig +from ...utils import auto_docstring +from ...utils.type_validators import interval +from ..auto import CONFIG_MAPPING, AutoConfig + + +@auto_docstring(checkpoint="nvidia/canary-1b-v2") +@strict +class CanaryDecoderConfig(PreTrainedConfig): + r""" + ```python + >>> from transformers import CanaryDecoderModel, CanaryDecoderConfig + + >>> # Initializing a CanaryDecoder canary_decoder-7b style configuration + >>> configuration = CanaryDecoderConfig() + + >>> # Initializing a model from the canary_decoder-7b style configuration + >>> model = CanaryDecoderModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "canary_decoder" + keys_to_ignore_at_inference = ["past_key_values"] + + vocab_size: int = 16384 + hidden_size: int = 1024 + intermediate_size: int = 4096 + num_hidden_layers: int = 8 + num_attention_heads: int = 8 + num_key_value_heads: int = 8 + hidden_act: str = "relu" + max_position_embeddings: int = 1024 + initializer_range: float = interval(min=0.0, max=1.0)(default=0.02) + use_cache: bool = True + pad_token_id: int | None = 2 + bos_token_id: int | None = 4 + eos_token_id: int | None = 3 + attention_bias: bool = True + attention_dropout: int | float | None = 0.0 + head_dim: int = 128 + is_encoder_decoder: bool = True + + def __post_init__(self, **kwargs): + if self.head_dim is None: + self.head_dim = self.hidden_size // self.num_attention_heads + if self.num_key_value_heads is None: + self.num_key_value_heads = self.num_attention_heads + + super().__post_init__(**kwargs) + + def validate_architecture(self): + """Part of `@strict`-powered validation. Validates the architecture of the config.""" + if self.hidden_size % self.num_attention_heads != 0: + raise ValueError( + f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention " + f"heads ({self.num_attention_heads})." + ) + + +@auto_docstring(checkpoint="nvidia/canary-1b-v2") +@strict +class CanaryConfig(PreTrainedConfig): + r""" + encoder_config (`Union[dict, ParakeetEncoderConfig]`, *optional*): + The config object or dictionary of the FastConformer encoder ([`ParakeetEncoderConfig`]). + decoder_config (`Union[dict, CanaryDecoderConfig]`, *optional*): + The config object or dictionary of the Transformer decoder ([`CanaryDecoderConfig`]). + decoder_start_token_id (`int`, *optional*, defaults to 7): + The token id that starts decoding (`<|startofcontext|>`, the first token of the multitask prompt). + + Example: + + ```python + >>> from transformers import CanaryForConditionalGeneration, CanaryConfig + + >>> # Initializing a Canary configuration + >>> configuration = CanaryConfig() + + >>> # Initializing a model from the configuration + >>> model = CanaryForConditionalGeneration(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ``` + """ + + model_type = "canary" + keys_to_ignore_at_inference = ["past_key_values"] + sub_configs = {"encoder_config": AutoConfig, "decoder_config": CanaryDecoderConfig} + + encoder_config: dict | PreTrainedConfig | None = None + decoder_config: dict | PreTrainedConfig | None = None + use_cache: bool = True + is_encoder_decoder: bool = True + tie_word_embeddings: bool = True + pad_token_id: int | None = 2 + bos_token_id: int | None = 4 + eos_token_id: int | None = 3 + decoder_start_token_id: int | None = 7 + initializer_range: float = 0.02 + vocab_size: int = 16384 + + def __post_init__(self, **kwargs): + if isinstance(self.encoder_config, dict): + self.encoder_config["model_type"] = self.encoder_config.get("model_type", "parakeet_encoder") + self.encoder_config = CONFIG_MAPPING[self.encoder_config["model_type"]](**self.encoder_config) + elif self.encoder_config is None: + self.encoder_config = CONFIG_MAPPING["parakeet_encoder"]( + num_hidden_layers=32, + num_mel_bins=128, + scale_input=False, + layerdrop=0.0, + ) + + if isinstance(self.decoder_config, dict): + self.decoder_config = CanaryDecoderConfig(**self.decoder_config) + elif self.decoder_config is None: + self.decoder_config = CanaryDecoderConfig() + + super().__post_init__(**kwargs) + + def validate_architecture(self): + if self.decoder_config.vocab_size != self.vocab_size: + raise ValueError( + f"The decoder config vocabulary size ({self.decoder_config.vocab_size}) does not match the Canary " + f"config vocabulary size ({self.vocab_size})." + ) + + def get_text_config(self, *args, **kwargs): + return self.decoder_config + + +__all__ = ["CanaryConfig", "CanaryDecoderConfig"] diff --git a/src/transformers/models/canary/convert_canary_nemo_to_hf.py b/src/transformers/models/canary/convert_canary_nemo_to_hf.py new file mode 100644 index 000000000000..60fdddf2671e --- /dev/null +++ b/src/transformers/models/canary/convert_canary_nemo_to_hf.py @@ -0,0 +1,249 @@ +# 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. + +import argparse +import gc +import os +import tarfile + +import torch +import yaml + +from transformers import ( + CanaryConfig, + CanaryDecoderConfig, + CanaryForConditionalGeneration, + CanaryProcessor, + ParakeetFeatureExtractor, + TokenizersBackend, +) +from transformers.convert_slow_tokenizer import CanaryConverter +from transformers.models.parakeet.convert_nemo_to_hf import convert_encoder_config, convert_key +from transformers.utils.hub import cached_file + + +CANARY_CHAT_TEMPLATE = ( + "{{- '<|startofcontext|><|startoftranscript|><|emo:undefined|>' -}}" + "{%- for message in messages -%}" + "{%- if message['role'] == 'user' -%}" + "{%- for content in message['content'] if content['type'] == 'text' -%}" + "{{- '<|' ~ content['source_language'] ~ '|>' -}}" + "{{- '<|' ~ content['target_language'] ~ '|>' -}}" + "{{- '<|pnc|>' if content['punctuation'] else '<|nopnc|>' -}}" + "{{- '<|noitn|><|notimestamp|><|nodiarize|>' -}}" + "{%- endfor -%}" + "{%- elif message['role'] == 'assistant' -%}" + "{{- message['content'] ~ '<|endoftext|>' -}}" + "{%- endif -%}" + "{%- endfor -%}" +) + + +NEMO_TO_HF_ENCODER_MAPPING = { + r"^encoder\.pre_encode\.conv\.": r"encoder.subsampling.layers.", + r"^encoder\.pre_encode\.out\.": r"encoder.subsampling.linear.", + r"^encoder\.pos_enc\.": r"encoder.encode_positions.", + r"^encoder\.layers\.(\d+)\.conv\.batch_norm\.": r"encoder.layers.\1.conv.norm.", + r"linear_([kv])": r"\1_proj", + r"linear_out": r"o_proj", + r"linear_q": r"q_proj", + r"pos_bias_([uv])": r"bias_\1", + r"linear_pos": r"relative_k_proj", +} + +DECODER_HIDDEN_DIM_INPUT_KEYS = ( + "embed_tokens.weight", + "proj_out.weight", + "q_proj.weight", + "self_attn.k_proj.weight", + "self_attn.v_proj.weight", + "mlp.fc1.weight", +) + +DECODER_HIDDEN_DIM_OUTPUT_KEYS = ( + "o_proj.weight", + "o_proj.bias", + "mlp.fc2.weight", + "mlp.fc2.bias", + "norm.weight", + "norm.bias", +) + +NEMO_TO_HF_DECODER_MAPPING = { + r"^transf_decoder\._embedding\.token_embedding\.": r"decoder.embed_tokens.", + r"^transf_decoder\._embedding\.layer_norm\.": r"decoder.embedding_layernorm.", + r"^transf_decoder\._decoder\.final_layer_norm\.": r"decoder.norm.", + r"^transf_decoder\._decoder\.layers\.(\d+)\.layer_norm_1\.": r"decoder.layers.\1.input_layernorm.", + r"^transf_decoder\._decoder\.layers\.(\d+)\.layer_norm_2\.": r"decoder.layers.\1.post_attention_layernorm.", + r"^transf_decoder\._decoder\.layers\.(\d+)\.layer_norm_3\.": r"decoder.layers.\1.final_layernorm.", + r"^transf_decoder\._decoder\.layers\.(\d+)\.first_sub_layer\.": r"decoder.layers.\1.self_attn.", + r"^transf_decoder\._decoder\.layers\.(\d+)\.second_sub_layer\.": r"decoder.layers.\1.encoder_attn.", + r"^transf_decoder\._decoder\.layers\.(\d+)\.third_sub_layer\.dense_in\.": r"decoder.layers.\1.mlp.fc1.", + r"^transf_decoder\._decoder\.layers\.(\d+)\.third_sub_layer\.dense_out\.": r"decoder.layers.\1.mlp.fc2.", + r"query_net": r"q_proj", + r"key_net": r"k_proj", + r"value_net": r"v_proj", + r"out_projection": r"o_proj", +} + + +def extract_nemo_archive(nemo_file_path: str, extract_dir: str) -> None: + """Extract a Canary `.nemo` (tar) archive into `extract_dir`.""" + print(f"Extracting NeMo archive: {nemo_file_path}") + with tarfile.open(nemo_file_path, "r", encoding="utf-8") as tar: + # filter="data" sanitizes members (PEP 706) so a malicious archive cannot write outside extract_dir + tar.extractall(extract_dir, filter="data") + + +def convert_decoder_config(nemo_config) -> CanaryConfig: + """Build a [`CanaryConfig`] from the NeMo `transf_decoder` and `head` config blocks.""" + decoder_config = nemo_config["transf_decoder"]["config_dict"] + head_config = nemo_config["head"] + encoder_config = convert_encoder_config(nemo_config) + + return CanaryConfig( + encoder_config=encoder_config.to_dict(), + decoder_config=CanaryDecoderConfig( + vocab_size=head_config["num_classes"], + hidden_size=decoder_config["hidden_size"], + num_hidden_layers=decoder_config["num_layers"], + num_attention_heads=decoder_config["num_attention_heads"], + intermediate_size=decoder_config["inner_size"], + hidden_act=decoder_config["hidden_act"], + max_position_embeddings=decoder_config["max_sequence_length"], + attention_dropout=decoder_config["attn_score_dropout"], + ), + ) + + +def permute_for_sinusoids(tensor, key, d_model): + """Permute the weights for the concatenated sin/cos formulation.""" + permutation = torch.empty(d_model, dtype=torch.long) + permutation[: d_model // 2] = torch.arange(0, d_model, 2) + permutation[d_model // 2 :] = torch.arange(1, d_model, 2) + if key.endswith(DECODER_HIDDEN_DIM_INPUT_KEYS): + return tensor[:, permutation] + if key.endswith(DECODER_HIDDEN_DIM_OUTPUT_KEYS): + return tensor[permutation] + return tensor + + +def load_and_convert_state_dict(model_files, d_model): + """Load the NeMo state dict and convert keys to the HF (`model.encoder.*` / `model.decoder.*`) layout.""" + state_dict = torch.load(model_files["model_weights"], map_location="cpu", weights_only=True) + converted_state_dict = {} + for key, value in state_dict.items(): + if key.startswith("preprocessor.") or key.endswith(".position_embedding.pos_enc"): + # featurizer buffers and the fixed sinusoidal table are recomputed, not loaded + continue + if key.startswith("encoder."): + converted_state_dict["model." + convert_key(key, NEMO_TO_HF_ENCODER_MAPPING)] = value + elif key.startswith("transf_decoder."): + converted_key = "model." + convert_key(key, NEMO_TO_HF_DECODER_MAPPING) + converted_state_dict[converted_key] = permute_for_sinusoids(value, converted_key, d_model) + elif key == "log_softmax.mlp.layer0.weight": + converted_state_dict["proj_out.weight"] = permute_for_sinusoids(value, "proj_out.weight", d_model) + elif key == "log_softmax.mlp.layer0.bias": + converted_state_dict["proj_out.bias"] = value + else: + raise ValueError(f"Unhandled NeMo weight key: {key}") + return converted_state_dict + + +def write_processor(nemo_config, model_files, output_dir, push_to_repo_id=None): + tokenizer_object = CanaryConverter(model_files["tokenizer_model_file"]).converted() + tokenizer = TokenizersBackend( + tokenizer_object=tokenizer_object, + clean_up_tokenization_spaces=False, + bos_token="<|startoftranscript|>", + eos_token="<|endoftext|>", + pad_token="", + unk_token="", + ) + + preprocessor = nemo_config["preprocessor"] + feature_extractor = ParakeetFeatureExtractor( + feature_size=preprocessor["features"], + sampling_rate=preprocessor["sample_rate"], + win_length=int(preprocessor["window_size"] * preprocessor["sample_rate"]), + hop_length=int(preprocessor["window_stride"] * preprocessor["sample_rate"]), + n_fft=preprocessor["n_fft"], + ) + + processor = CanaryProcessor( + feature_extractor=feature_extractor, tokenizer=tokenizer, chat_template=CANARY_CHAT_TEMPLATE + ) + processor.save_pretrained(output_dir) + if push_to_repo_id: + processor.push_to_hub(push_to_repo_id) + + +def main(hf_repo_id, output_dir, push_to_repo_id=None): + nemo_filename = f"{hf_repo_id.split('/')[-1]}.nemo" + filepath = cached_file(hf_repo_id, nemo_filename) + extract_dir = os.path.dirname(filepath) + extract_nemo_archive(filepath, extract_dir) + + nemo_config = yaml.load(open(os.path.join(extract_dir, "model_config.yaml"), "r"), Loader=yaml.FullLoader) + tokenizer_model_name = nemo_config["tokenizer"]["model_path"].split("nemo:")[-1] + model_files = { + "model_weights": os.path.join(extract_dir, "model_weights.ckpt"), + "tokenizer_model_file": os.path.join(extract_dir, tokenizer_model_name), + } + + write_processor(nemo_config, model_files, output_dir, push_to_repo_id) + + config = convert_decoder_config(nemo_config) + print(f"Converted config:\n{config}") + converted_state_dict = load_and_convert_state_dict(model_files, config.decoder_config.hidden_size) + + print("Loading the checkpoint in a Canary model.") + with torch.device("meta"): + model = CanaryForConditionalGeneration(config) + model.load_state_dict(converted_state_dict, strict=True, assign=True) + print("Checkpoint loaded successfully.") + + model.generation_config.decoder_start_token_id = config.decoder_start_token_id + model.generation_config.bos_token_id = config.bos_token_id + model.generation_config.eos_token_id = config.eos_token_id + model.generation_config.pad_token_id = config.pad_token_id + + print("Saving the model.") + model.save_pretrained(output_dir) + if push_to_repo_id: + model.push_to_hub(push_to_repo_id) + + del model + gc.collect() + print("Reloading the model to check it was saved correctly.") + CanaryForConditionalGeneration.from_pretrained(output_dir, dtype=torch.bfloat16) + print("Model reloaded successfully.") + + +""" +Conversion example: +```bash +python src/transformers/models/canary/convert_canary_nemo_to_hf.py \ + --hf_repo_id nvidia/canary-1b-v2 \ + --output_dir OUTPUT_DIR \ + --push_to_repo_id USERNAME/canary-1b-v2-hf +``` +""" +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--hf_repo_id", required=True, help="Model repo on huggingface.co") + parser.add_argument("--output_dir", required=True, help="Output directory for the HuggingFace model") + parser.add_argument("--push_to_repo_id", help="Repository ID to push the converted model to on the Hub") + args = parser.parse_args() + main(args.hf_repo_id, args.output_dir, args.push_to_repo_id) diff --git a/src/transformers/models/canary/modeling_canary.py b/src/transformers/models/canary/modeling_canary.py new file mode 100644 index 000000000000..13b30f0c13a4 --- /dev/null +++ b/src/transformers/models/canary/modeling_canary.py @@ -0,0 +1,696 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/canary/modular_canary.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_canary.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# 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. + +import math +from collections.abc import Callable + +import numpy as np +import torch +from torch import nn + +from ... import initialization as init +from ...activations import ACT2FN +from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache +from ...generation import GenerationMixin +from ...masking_utils import create_bidirectional_mask, create_causal_mask +from ...modeling_layers import GradientCheckpointingLayer +from ...modeling_outputs import ( + BaseModelOutput, + BaseModelOutputWithPastAndCrossAttentions, + Seq2SeqLMOutput, + Seq2SeqModelOutput, +) +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from ...processing_utils import Unpack +from ...utils import TransformersKwargs, auto_docstring +from ...utils.generic import can_return_tuple, merge_with_config_defaults +from ...utils.output_capturing import OutputRecorder, capture_outputs +from ..auto.modeling_auto import AutoModel +from .configuration_canary import CanaryConfig, CanaryDecoderConfig + + +class CanaryPositionalEmbedding(nn.Module): + """ + Identical to [`SinusoidsPositionEmbedding`] except that the timescales and the `1 / sqrt(channels)` scaling match + NeMo's `FixedPositionalEncoding`, and it is indexed by `position_ids`. + """ + + def __init__(self, length: int, channels: int): + super().__init__() + self.length = length + self.channels = channels + self.max_timescale = 10000 ** ((channels - 2) / channels) + if channels % 2 != 0: + raise ValueError("CanaryPositionalEmbedding needs even channels input") + position_embedding = self.compute_default_singular_positional_embedding() + self.positional_embedding = nn.Buffer(position_embedding, persistent=False) + + def compute_default_singular_positional_embedding(self) -> torch.Tensor: + log_timescale_increment = np.log(self.max_timescale) / (self.channels // 2 - 1) + inv_timescales = torch.exp(-log_timescale_increment * torch.arange(self.channels // 2).float()) + scaled_time = torch.arange(self.length)[:, np.newaxis] * inv_timescales[np.newaxis, :] + return torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1) + + def forward(self, position_ids: torch.Tensor) -> torch.Tensor: + return self.positional_embedding[position_ids] / math.sqrt(self.channels) + + +@auto_docstring +class CanaryPreTrainedModel(PreTrainedModel): + config: CanaryConfig + base_model_prefix = "model" + main_input_name = "input_features" + input_modalities = "audio" + supports_gradient_checkpointing = True + _no_split_modules = ["CanaryDecoderLayer"] + _supports_flash_attn = True + _supports_sdpa = True + + _can_compile_fullgraph = True + _keys_to_ignore_on_load_unexpected = [r"preprocessor\.featurizer\..*"] + + @torch.no_grad() + def _init_weights(self, module): + super()._init_weights(module) + if isinstance(module, CanaryPositionalEmbedding): + init.copy_(module.positional_embedding, module.compute_default_singular_positional_embedding()) + + +class CanaryDecoderMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.activation_fn = ACT2FN[config.hidden_act] + self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size) + self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.fc1(hidden_states) + hidden_states = self.activation_fn(hidden_states) + hidden_states = self.fc2(hidden_states) + return hidden_states + + +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, + num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + batch, num_key_value_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) + return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +def eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: torch.Tensor | None, + scaling: float, + dropout: float = 0.0, + **kwargs: Unpack[TransformersKwargs], +): + key_states = repeat_kv(key, module.num_key_value_groups) + value_states = repeat_kv(value, module.num_key_value_groups) + + attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling + if attention_mask is not None: + attn_weights = attn_weights + attention_mask + + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) + attn_output = torch.matmul(attn_weights, value_states) + attn_output = attn_output.transpose(1, 2).contiguous() + + return attn_output, attn_weights + + +# Modular automatically inherits RoPE, hence no inheritance for now +class CanarySelfAttention(nn.Module): + def __init__(self, config: CanaryConfig, layer_idx: int): + super().__init__() + self.config = config + self.layer_idx = layer_idx + self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) + self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads + self.scaling = self.head_dim**-0.5 + self.attention_dropout = config.attention_dropout + self.is_causal = True + + self.q_proj = nn.Linear( + config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias + ) + self.k_proj = nn.Linear( + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias + ) + self.v_proj = nn.Linear( + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias + ) + self.o_proj = nn.Linear( + config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias + ) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor, + past_key_values: Cache | None = None, + **kwargs, + ): + input_shape = hidden_states.shape[:-1] + hidden_shape = (*input_shape, -1, self.head_dim) + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.view(hidden_shape).transpose(1, 2) + key_states = key_states.view(hidden_shape).transpose(1, 2) + value_states = value_states.view(hidden_shape).transpose(1, 2) + + if past_key_values is not None: + past_key_values = past_key_values.self_attention_cache + key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward + ) + + attn_output, attn_weights = attention_interface( + self, + query_states, + key_states, + value_states, + attention_mask, + dropout=0.0 if not self.training else self.attention_dropout, + scaling=self.scaling, + **kwargs, + ) + + attn_output = attn_output.reshape(*input_shape, -1).contiguous() + attn_output = self.o_proj(attn_output) + return attn_output, attn_weights + + +# Modular automatically inherits RoPE, hence no inheritance for now +class CanaryCrossAttention(nn.Module): + def __init__(self, config: CanaryConfig, layer_idx: int): + super().__init__() + self.config = config + self.layer_idx = layer_idx + self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) + self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads + self.scaling = self.head_dim**-0.5 + self.attention_dropout = config.attention_dropout + self.is_causal = False + + self.q_proj = nn.Linear( + config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias + ) + self.k_proj = nn.Linear( + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias + ) + self.v_proj = nn.Linear( + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias + ) + self.o_proj = nn.Linear( + config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias + ) + + def forward( + self, + hidden_states: torch.Tensor, + encoder_hidden_states: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, + past_key_values: Cache | None = None, + **kwargs: Unpack[TransformersKwargs], + ): + # determine input shapes + bsz, tgt_len = hidden_states.shape[:-1] + src_len = encoder_hidden_states.shape[1] + + q_input_shape = (bsz, tgt_len, -1, self.head_dim) + kv_input_shape = (bsz, src_len, -1, self.head_dim) + + # get query proj + query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2) + + is_updated = past_key_values.is_updated.get(self.layer_idx) if past_key_values is not None else False + if past_key_values is not None and is_updated: + # reuse k,v, cross_attentions + key_states = past_key_values.cross_attention_cache.layers[self.layer_idx].keys + value_states = past_key_values.cross_attention_cache.layers[self.layer_idx].values + else: + key_states = self.k_proj(encoder_hidden_states).view(*kv_input_shape).transpose(1, 2) + value_states = self.v_proj(encoder_hidden_states).view(*kv_input_shape).transpose(1, 2) + + if past_key_values is not None: + # save all states to the cache + key_states, value_states = past_key_values.cross_attention_cache.update( + key_states, value_states, self.layer_idx + ) + # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls + past_key_values.is_updated[self.layer_idx] = True + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward + ) + + attn_output, attn_weights = attention_interface( + self, + query_states, + key_states, + value_states, + attention_mask, + dropout=0.0 if not self.training else self.attention_dropout, + scaling=self.scaling, + **kwargs, + ) + attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous() + attn_output = self.o_proj(attn_output) + return attn_output, attn_weights + + +class CanaryDecoderLayer(GradientCheckpointingLayer): + def __init__(self, config, layer_idx=None): + super().__init__() + self.self_attn = CanarySelfAttention(config=config, layer_idx=layer_idx) + self.encoder_attn = CanaryCrossAttention(config=config, layer_idx=layer_idx) + + self.mlp = CanaryDecoderMLP(config) + self.input_layernorm = nn.LayerNorm(config.hidden_size) + self.post_attention_layernorm = nn.LayerNorm(config.hidden_size) + self.final_layernorm = nn.LayerNorm(config.hidden_size) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor | None = None, + encoder_hidden_states: torch.Tensor | None = None, + encoder_attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + encoder_position_ids: torch.LongTensor | None = None, + past_key_values: Cache | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.FloatTensor, tuple[torch.FloatTensor, torch.FloatTensor] | None]: + residual = hidden_states + hidden_states = self.input_layernorm(hidden_states) + + hidden_states, _ = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + **kwargs, + ) + hidden_states = residual + hidden_states + + if encoder_hidden_states is not None: + residual = hidden_states + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states, _ = self.encoder_attn( + hidden_states=hidden_states, + encoder_hidden_states=encoder_hidden_states, + attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + ) + hidden_states = residual + hidden_states + + residual = hidden_states + hidden_states = self.final_layernorm(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + return hidden_states + + +@auto_docstring +class CanaryDecoder(CanaryPreTrainedModel): + main_input_name = "input_ids" + _can_record_outputs = { + "attentions": OutputRecorder(CanarySelfAttention, index=1, layer_name="self_attn"), + "hidden_states": CanaryDecoderLayer, + "cross_attentions": OutputRecorder(CanaryCrossAttention, index=1, layer_name="encoder_attn"), + } + config: CanaryDecoderConfig + + def __init__(self, config: CanaryDecoderConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([CanaryDecoderLayer(config, idx) for idx in range(config.num_hidden_layers)]) + self.norm = nn.LayerNorm(config.hidden_size) + self.gradient_checkpointing = False + self.pos_emb = CanaryPositionalEmbedding(config.max_position_embeddings, config.hidden_size) + self.embedding_layernorm = nn.LayerNorm(config.hidden_size) + + # Initialize weights and apply final processing + self.post_init() + + @merge_with_config_defaults + @capture_outputs + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + past_key_values: Cache | None = None, + inputs_embeds: torch.FloatTensor | None = None, + use_cache: bool | None = None, + encoder_hidden_states: torch.FloatTensor | None = None, + encoder_attention_mask: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPastAndCrossAttentions: + r""" + encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention + of the decoder. + encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + [What are attention masks?](../glossary#attention-mask) + """ + if (input_ids is None) ^ (inputs_embeds is not None): + raise ValueError("You must specify exactly one of input_ids or inputs_embeds") + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + if use_cache and past_key_values is None: + past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config)) + + if position_ids is None: + past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 + position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens + position_ids = position_ids.unsqueeze(0) + + # Fixed sinusoidal position embedding added to token embeddings, then layernorm + pos_emb = self.pos_emb(position_ids.squeeze(0)) + pos_emb = pos_emb.to(device=inputs_embeds.device, dtype=inputs_embeds.dtype) + inputs_embeds = self.embedding_layernorm(inputs_embeds + pos_emb) + + causal_mask = create_causal_mask( + config=self.config, + inputs_embeds=inputs_embeds, + attention_mask=attention_mask, + past_key_values=past_key_values, + position_ids=position_ids, + ) + encoder_attention_mask = create_bidirectional_mask( + config=self.config, + inputs_embeds=inputs_embeds, + attention_mask=encoder_attention_mask, + encoder_hidden_states=encoder_hidden_states, + ) + + hidden_states = inputs_embeds + for decoder_layer in self.layers: + hidden_states = decoder_layer( + hidden_states, + causal_mask, + encoder_hidden_states, # as a positional argument for gradient checkpointing + encoder_attention_mask=encoder_attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + **kwargs, + ) + + hidden_states = self.norm(hidden_states) + + return BaseModelOutputWithPastAndCrossAttentions( + last_hidden_state=hidden_states, + past_key_values=past_key_values if use_cache else None, + ) + + +@auto_docstring( + custom_intro=""" + The bare Canary model (FastConformer encoder + Transformer decoder) outputting raw hidden-states without any + specific head on top. + """ +) +class CanaryModel(CanaryPreTrainedModel): + def __init__(self, config: CanaryConfig): + super().__init__(config) + self.encoder = AutoModel.from_config(config.encoder_config) + self.decoder = CanaryDecoder(config.decoder_config) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.decoder.embed_tokens = value + + def freeze_encoder(self): + """ + Calling this function will disable the gradient computation for the Canary encoder so that its parameters will + not be updated during training. + """ + self.encoder._freeze_parameters() + + def _mask_input_features(self): + """ + Masks extracted features along time axis and/or along feature axis according to + [SpecAugment](https://huggingface.co/papers/1904.08779). + """ + raise AttributeError("Not needed for Canary") + + @can_return_tuple + @auto_docstring + def forward( + self, + input_features: torch.FloatTensor | None = None, + attention_mask: torch.LongTensor | None = None, + decoder_input_ids: torch.LongTensor | None = None, + decoder_attention_mask: torch.LongTensor | None = None, + encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None, + past_key_values: EncoderDecoderCache | None = None, + decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None, + decoder_position_ids: tuple[torch.LongTensor] | None = None, + use_cache: bool | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> Seq2SeqModelOutput: + r""" + input_features (`torch.FloatTensor` of shape `(batch_size, audio_length)`): + Float values of the raw speech waveform. Raw speech waveform can be + obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a + `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or + the soundfile library (`pip install soundfile`). To prepare the array into + `input_features`, the [`AutoFeatureExtractor`] should be used for padding + and conversion into a tensor of type `torch.FloatTensor`. + decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`): + Indices of positions of each input sequence tokens in the position embeddings. + Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings` + + Example: + + ```python + >>> import torch + >>> from transformers import AutoFeatureExtractor, CanaryModel + >>> from datasets import load_dataset + + >>> model = CanaryModel.from_pretrained("UsefulSensors/canary-tiny") + >>> feature_extractor = AutoFeatureExtractor.from_pretrained("UsefulSensors/canary-tiny") + >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt") + >>> input_features = inputs.input_features + >>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id + >>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state + >>> list(last_hidden_state.shape) + [1, 2, 288] + ``` + """ + # Main difference: uses `input_features` instead of `input_values` + if encoder_outputs is None: + encoder_outputs: BaseModelOutput = self.encoder(input_features, attention_mask=attention_mask, **kwargs) + + decoder_outputs: BaseModelOutputWithPastAndCrossAttentions = self.decoder( + input_ids=decoder_input_ids, + attention_mask=decoder_attention_mask, + encoder_hidden_states=encoder_outputs.last_hidden_state, + encoder_attention_mask=encoder_outputs.attention_mask, + past_key_values=past_key_values, + inputs_embeds=decoder_inputs_embeds, + position_ids=decoder_position_ids, + use_cache=use_cache, + **kwargs, + ) + + return Seq2SeqModelOutput( + last_hidden_state=decoder_outputs.last_hidden_state, + past_key_values=decoder_outputs.past_key_values, + decoder_hidden_states=decoder_outputs.hidden_states, + decoder_attentions=decoder_outputs.attentions, + cross_attentions=decoder_outputs.cross_attentions, + encoder_last_hidden_state=encoder_outputs.last_hidden_state, + encoder_hidden_states=encoder_outputs.hidden_states, + encoder_attentions=encoder_outputs.attentions, + ) + + +def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int): + """ + Shift input ids one token to the right. + """ + shifted_input_ids = input_ids.new_zeros(input_ids.shape) + shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() + shifted_input_ids[:, 0] = decoder_start_token_id + + if pad_token_id is None: + raise ValueError("self.model.config.pad_token_id has to be defined.") + # replace possible -100 values in labels by `pad_token_id` + shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) + + return shifted_input_ids + + +@auto_docstring( + custom_intro=""" + The Canary model with a language modeling head. Can be used for multilingual automatic speech recognition and + speech-to-text translation. + """ +) +class CanaryForConditionalGeneration(CanaryPreTrainedModel, GenerationMixin): + _tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"} + + def __init__(self, config: CanaryConfig): + super().__init__(config) + self.model = CanaryModel(config) + self.proj_out = nn.Linear(config.decoder_config.hidden_size, config.decoder_config.vocab_size, bias=True) + + # Initialize weights and apply final processing + self.post_init() + + def get_output_embeddings(self): + return self.proj_out + + def set_output_embeddings(self, new_embeddings): + self.proj_out = new_embeddings + + def get_input_embeddings(self) -> nn.Module: + return self.model.get_input_embeddings() + + @can_return_tuple + @auto_docstring + def forward( + self, + input_features: torch.FloatTensor | None = None, + attention_mask: torch.LongTensor | None = None, + decoder_input_ids: torch.LongTensor | None = None, + decoder_attention_mask: torch.LongTensor | None = None, + encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None, + past_key_values: EncoderDecoderCache | None = None, + decoder_inputs_embeds: tuple[torch.FloatTensor] | None = None, + decoder_position_ids: tuple[torch.LongTensor] | None = None, + use_cache: bool | None = None, + labels: torch.LongTensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> Seq2SeqLMOutput: + r""" + input_features (`torch.FloatTensor` of shape `(batch_size, audio_length)`): + Float values of the raw speech waveform. Raw speech waveform can be + obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a + `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or + the soundfile library (`pip install soundfile`). To prepare the array into + `input_features`, the [`AutoFeatureExtractor`] should be used for padding + and conversion into a tensor of type `torch.FloatTensor`. + decoder_position_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`): + Indices of positions of each input sequence tokens in the position embeddings. + Used to calculate the position embeddings up to `config.decoder_config.max_position_embeddings` + + Example: + + ```python + >>> import torch + >>> from transformers import AutoProcessor, CanaryForConditionalGeneration + >>> from datasets import load_dataset + + >>> processor = AutoProcessor.from_pretrained("UsefulSensors/canary-tiny") + >>> model = CanaryForConditionalGeneration.from_pretrained("UsefulSensors/canary-tiny") + + >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + + >>> inputs = processor(ds[0]["audio"]["array"], return_tensors="pt") + >>> input_features = inputs.input_features + + >>> generated_ids = model.generate(input_features, max_new_tokens=100) + + >>> transcription = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] + >>> transcription + 'Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.' + ```""" + # Main difference: uses `input_features` instead of `input_values` + if labels is not None: + if decoder_input_ids is None and decoder_inputs_embeds is None: + decoder_input_ids = shift_tokens_right( + labels, self.config.pad_token_id, self.config.decoder_start_token_id + ) + + outputs: Seq2SeqModelOutput = self.model( + input_features, + attention_mask=attention_mask, + decoder_input_ids=decoder_input_ids, + encoder_outputs=encoder_outputs, + decoder_attention_mask=decoder_attention_mask, + past_key_values=past_key_values, + decoder_inputs_embeds=decoder_inputs_embeds, + decoder_position_ids=decoder_position_ids, + use_cache=use_cache, + **kwargs, + ) + logits = self.proj_out(outputs.last_hidden_state) + + loss = None + if labels is not None: + shift_labels = kwargs.pop("shift_labels", labels) + loss = self.loss_function( + logits=logits, + labels=labels, + vocab_size=self.config.vocab_size, + shift_labels=shift_labels, + **kwargs, + ) + + return Seq2SeqLMOutput( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + decoder_hidden_states=outputs.decoder_hidden_states, + decoder_attentions=outputs.decoder_attentions, + cross_attentions=outputs.cross_attentions, + encoder_last_hidden_state=outputs.encoder_last_hidden_state, + encoder_hidden_states=outputs.encoder_hidden_states, + encoder_attentions=outputs.encoder_attentions, + ) + + def prepare_inputs_for_generation(self, *args, audio_chunk_index=None, **kwargs): + # audio_chunk_index is returned by the processor but not used by the model, absorb it here + return super().prepare_inputs_for_generation(*args, **kwargs) + + +__all__ = ["CanaryForConditionalGeneration", "CanaryModel", "CanaryPreTrainedModel"] diff --git a/src/transformers/models/canary/modular_canary.py b/src/transformers/models/canary/modular_canary.py new file mode 100644 index 000000000000..87aeb1d41dd2 --- /dev/null +++ b/src/transformers/models/canary/modular_canary.py @@ -0,0 +1,300 @@ +# 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. +"""PyTorch Canary model.""" + +import math + +import numpy as np +import torch +from huggingface_hub.dataclasses import strict +from torch import nn + +from ... import initialization as init +from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache +from ...configuration_utils import PreTrainedConfig +from ...masking_utils import create_bidirectional_mask, create_causal_mask +from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions +from ...modeling_utils import PreTrainedModel +from ...processing_utils import Unpack +from ...utils import TransformersKwargs, auto_docstring, logging +from ...utils.generic import merge_with_config_defaults +from ...utils.output_capturing import capture_outputs +from ..auto import CONFIG_MAPPING, AutoConfig +from ..cohere_asr.modeling_cohere_asr import ( + CohereAsrDecoder, + CohereAsrForConditionalGeneration, + CohereAsrModel, + CohereAsrPreTrainedModel, +) +from ..llama.configuration_llama import LlamaConfig +from ..qwen2_5_omni.modeling_qwen2_5_omni import SinusoidsPositionEmbedding + + +logger = logging.get_logger(__name__) + + +@auto_docstring(checkpoint="nvidia/canary-1b-v2") +@strict +class CanaryDecoderConfig(LlamaConfig): + model_type = "canary_decoder" + + vocab_size: int = 16384 + hidden_size: int = 1024 + num_hidden_layers: int = 8 + num_attention_heads: int = 8 + num_key_value_heads: int = 8 + intermediate_size: int = 4096 + hidden_act: str = "relu" + max_position_embeddings: int = 1024 + pad_token_id: int | None = 2 + eos_token_id: int | None = 3 + bos_token_id: int | None = 4 + is_encoder_decoder: bool = True + attention_bias: bool = True + head_dim: int = 128 + + rms_norm_eps = AttributeError() + pretraining_tp = AttributeError() + rope_parameters = AttributeError() + mlp_bias = AttributeError() + tie_word_embeddings = AttributeError() + base_model_tp_plan = AttributeError() + base_model_pp_plan = AttributeError() + + +@auto_docstring(checkpoint="nvidia/canary-1b-v2") +@strict +class CanaryConfig(PreTrainedConfig): + r""" + encoder_config (`Union[dict, ParakeetEncoderConfig]`, *optional*): + The config object or dictionary of the FastConformer encoder ([`ParakeetEncoderConfig`]). + decoder_config (`Union[dict, CanaryDecoderConfig]`, *optional*): + The config object or dictionary of the Transformer decoder ([`CanaryDecoderConfig`]). + decoder_start_token_id (`int`, *optional*, defaults to 7): + The token id that starts decoding (`<|startofcontext|>`, the first token of the multitask prompt). + + Example: + + ```python + >>> from transformers import CanaryForConditionalGeneration, CanaryConfig + + >>> # Initializing a Canary configuration + >>> configuration = CanaryConfig() + + >>> # Initializing a model from the configuration + >>> model = CanaryForConditionalGeneration(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ``` + """ + + model_type = "canary" + keys_to_ignore_at_inference = ["past_key_values"] + sub_configs = {"encoder_config": AutoConfig, "decoder_config": CanaryDecoderConfig} + + encoder_config: dict | PreTrainedConfig | None = None + decoder_config: dict | PreTrainedConfig | None = None + use_cache: bool = True + is_encoder_decoder: bool = True + tie_word_embeddings: bool = True + pad_token_id: int | None = 2 + bos_token_id: int | None = 4 + eos_token_id: int | None = 3 + decoder_start_token_id: int | None = 7 + initializer_range: float = 0.02 + vocab_size: int = 16384 + + def __post_init__(self, **kwargs): + if isinstance(self.encoder_config, dict): + self.encoder_config["model_type"] = self.encoder_config.get("model_type", "parakeet_encoder") + self.encoder_config = CONFIG_MAPPING[self.encoder_config["model_type"]](**self.encoder_config) + elif self.encoder_config is None: + self.encoder_config = CONFIG_MAPPING["parakeet_encoder"]( + num_hidden_layers=32, + num_mel_bins=128, + scale_input=False, + layerdrop=0.0, + ) + + if isinstance(self.decoder_config, dict): + self.decoder_config = CanaryDecoderConfig(**self.decoder_config) + elif self.decoder_config is None: + self.decoder_config = CanaryDecoderConfig() + + super().__post_init__(**kwargs) + + def validate_architecture(self): + if self.decoder_config.vocab_size != self.vocab_size: + raise ValueError( + f"The decoder config vocabulary size ({self.decoder_config.vocab_size}) does not match the Canary " + f"config vocabulary size ({self.vocab_size})." + ) + + def get_text_config(self, *args, **kwargs): + return self.decoder_config + + +class CanaryPositionalEmbedding(SinusoidsPositionEmbedding): + """ + Identical to [`SinusoidsPositionEmbedding`] except that the timescales and the `1 / sqrt(channels)` scaling match + NeMo's `FixedPositionalEncoding`, and it is indexed by `position_ids`. + """ + + def __init__(self, length: int, channels: int): + super().__init__(length, channels) + self.max_timescale = 10000 ** ((channels - 2) / channels) + + def compute_default_singular_positional_embedding(self) -> torch.Tensor: + log_timescale_increment = np.log(self.max_timescale) / (self.channels // 2 - 1) + inv_timescales = torch.exp(-log_timescale_increment * torch.arange(self.channels // 2).float()) + scaled_time = torch.arange(self.length)[:, np.newaxis] * inv_timescales[np.newaxis, :] + return torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1) + + def forward(self, position_ids: torch.Tensor) -> torch.Tensor: + return self.positional_embedding[position_ids] / math.sqrt(self.channels) + + +@auto_docstring +class CanaryPreTrainedModel(CohereAsrPreTrainedModel): + config: CanaryConfig + _no_split_modules = ["CanaryDecoderLayer"] + + def _get_feat_extract_output_lengths(self): + raise AttributeError("Not needed for Canary") + + @torch.no_grad() + def _init_weights(self, module): + PreTrainedModel._init_weights(self, module) + if isinstance(module, CanaryPositionalEmbedding): + init.copy_(module.positional_embedding, module.compute_default_singular_positional_embedding()) + + +class CanaryDecoder(CohereAsrDecoder): + config: CanaryDecoderConfig + + def __init__(self, config: CanaryDecoderConfig): + super().__init__(config) + self.pos_emb = CanaryPositionalEmbedding(config.max_position_embeddings, config.hidden_size) + del self.proj + + @merge_with_config_defaults + @capture_outputs + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + past_key_values: Cache | None = None, + inputs_embeds: torch.FloatTensor | None = None, + use_cache: bool | None = None, + encoder_hidden_states: torch.FloatTensor | None = None, + encoder_attention_mask: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | BaseModelOutputWithPastAndCrossAttentions: + r""" + encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention + of the decoder. + encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding indices in `encoder_hidden_states`. Mask values selected in `[0, 1]`: + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + [What are attention masks?](../glossary#attention-mask) + """ + if (input_ids is None) ^ (inputs_embeds is not None): + raise ValueError("You must specify exactly one of input_ids or inputs_embeds") + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + if use_cache and past_key_values is None: + past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config)) + + if position_ids is None: + past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 + position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens + position_ids = position_ids.unsqueeze(0) + + # Fixed sinusoidal position embedding added to token embeddings, then layernorm + pos_emb = self.pos_emb(position_ids.squeeze(0)) + pos_emb = pos_emb.to(device=inputs_embeds.device, dtype=inputs_embeds.dtype) + inputs_embeds = self.embedding_layernorm(inputs_embeds + pos_emb) + + causal_mask = create_causal_mask( + config=self.config, + inputs_embeds=inputs_embeds, + attention_mask=attention_mask, + past_key_values=past_key_values, + position_ids=position_ids, + ) + encoder_attention_mask = create_bidirectional_mask( + config=self.config, + inputs_embeds=inputs_embeds, + attention_mask=encoder_attention_mask, + encoder_hidden_states=encoder_hidden_states, + ) + + hidden_states = inputs_embeds + for decoder_layer in self.layers: + hidden_states = decoder_layer( + hidden_states, + causal_mask, + encoder_hidden_states, # as a positional argument for gradient checkpointing + encoder_attention_mask=encoder_attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + **kwargs, + ) + + hidden_states = self.norm(hidden_states) + + return BaseModelOutputWithPastAndCrossAttentions( + last_hidden_state=hidden_states, + past_key_values=past_key_values if use_cache else None, + ) + + +@auto_docstring( + custom_intro=""" + The bare Canary model (FastConformer encoder + Transformer decoder) outputting raw hidden-states without any + specific head on top. + """ +) +class CanaryModel(CohereAsrModel): + def __init__(self, config: CanaryConfig): + super().__init__(config) + self.decoder = CanaryDecoder(config.decoder_config) + + +@auto_docstring( + custom_intro=""" + The Canary model with a language modeling head. Can be used for multilingual automatic speech recognition and + speech-to-text translation. + """ +) +class CanaryForConditionalGeneration(CohereAsrForConditionalGeneration): + def __init__(self, config: CanaryConfig): + super().__init__(config) + self.proj_out = nn.Linear(config.decoder_config.hidden_size, config.decoder_config.vocab_size, bias=True) + + +__all__ = [ + "CanaryConfig", + "CanaryDecoderConfig", + "CanaryForConditionalGeneration", + "CanaryModel", + "CanaryPreTrainedModel", +] diff --git a/src/transformers/models/canary/processing_canary.py b/src/transformers/models/canary/processing_canary.py new file mode 100644 index 000000000000..b7e1d96eaa48 --- /dev/null +++ b/src/transformers/models/canary/processing_canary.py @@ -0,0 +1,178 @@ +# 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. + +from ...audio_utils import ( + AudioInput, + make_audio_chat_template_content, + make_list_of_audio_chat_template, + prepare_language_inputs, +) +from ...feature_extraction_utils import BatchFeature +from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack +from ...tokenization_utils_base import PreTokenizedInput, TextInput +from ...utils import auto_docstring, logging +from ...utils.import_utils import requires + + +logger = logging.get_logger(__name__) + + +# Languages supported by Canary. See https://huggingface.co/nvidia/canary-1b-v2 for details. +LANGUAGE_CODE_TO_NAME = { + "bg": "Bulgarian", + "hr": "Croatian", + "cs": "Czech", + "da": "Danish", + "nl": "Dutch", + "en": "English", + "et": "Estonian", + "fi": "Finnish", + "fr": "French", + "de": "German", + "el": "Greek", + "hu": "Hungarian", + "it": "Italian", + "lv": "Latvian", + "lt": "Lithuanian", + "mt": "Maltese", + "pl": "Polish", + "pt": "Portuguese", + "ro": "Romanian", + "sk": "Slovak", + "sl": "Slovenian", + "es": "Spanish", + "sv": "Swedish", + "ru": "Russian", + "uk": "Ukrainian", +} + + +class CanaryProcessorKwargs(ProcessingKwargs, total=False): # trf-ignore: TRF019 + _defaults = { + "audio_kwargs": { + "sampling_rate": 16000, + }, + "common_kwargs": { + "return_tensors": "pt", + }, + } + + +@requires(backends=("torch",)) +@auto_docstring +class CanaryProcessor(ProcessorMixin): + valid_processor_kwargs = CanaryProcessorKwargs + + def __init__(self, feature_extractor=None, tokenizer=None, chat_template=None): + super().__init__(feature_extractor, tokenizer, chat_template=chat_template) + + @auto_docstring + def __call__( + self, + audio: AudioInput, + text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None, + output_labels: bool = False, + **kwargs: Unpack[CanaryProcessorKwargs], + ) -> BatchFeature: + r""" + text (`str`, `list[str]`, *optional*): + The decoder prompt(s) produced by the chat template. It is tokenized into `decoder_input_ids`. + output_labels (`bool`, *optional*, defaults to `False`): + Whether to return labels for training. + """ + + if "return_tensors" in kwargs and kwargs["return_tensors"] != "pt": + raise ValueError(f"{self.__class__.__name__} only supports `return_tensors='pt'`.") + + model_inputs = super().__call__(audio=audio, text=text, **kwargs) + if text is not None: + input_ids = model_inputs.pop("input_ids") + if output_labels: + # the decoder inputs are already right-shifted with respect to `labels` + model_inputs["decoder_input_ids"] = input_ids[..., :-1] + labels = input_ids[..., 1:].clone() + labels[labels == self.tokenizer.pad_token_id] = -100 + model_inputs["labels"] = labels + else: + model_inputs["decoder_input_ids"] = input_ids + return BatchFeature(data=model_inputs, tensor_type="pt") + + def apply_transcription_request( + self, + audio: AudioInput | list[AudioInput], + source_language: str | list[str] = "en", + target_language: str | list[str] | None = None, + punctuation: bool = True, + **kwargs: Unpack[CanaryProcessorKwargs], + ) -> BatchFeature: + r""" + Prepare inputs for transcription or translation without manually writing the chat template. + + Args: + audio (`AudioInput` or `list[AudioInput]`): + Audio to transcribe or translate. Can be a URL string, local path, numpy array, or a list of these. + source_language (`str` or `list[str]`, *optional*, defaults to `"en"`): + The language of the input speech. Accepts ISO codes (e.g. `"en"`, `"de"`, `"fr"`) or full names + (e.g. `"English"`, `"German"`, `"French"`). + target_language (`str` or `list[str]`, *optional*): + The language of the output text. Accepts ISO codes or full names. Defaults to `source_language` + (transcription); set it to a different language for speech-to-text translation. + punctuation (`bool`, *optional*, defaults to `True`): + Whether to request punctuation and capitalization in the output. + **kwargs: + Additional keyword arguments forwarded to [`~CanaryProcessor.apply_chat_template`]. + + Returns: + [`BatchFeature`]: Processor outputs ready to be passed to + [`CanaryForConditionalGeneration.generate`]. + """ + audio_items = make_list_of_audio_chat_template(audio) + batch_size = len(audio_items) + if batch_size == 0: + raise ValueError("`audio` must contain at least one sample.") + + source_languages = prepare_language_inputs(source_language, batch_size, LANGUAGE_CODE_TO_NAME) + if target_language is None: + target_languages = list(source_languages) + else: + target_languages = prepare_language_inputs(target_language, batch_size, LANGUAGE_CODE_TO_NAME) + + conversations = [] + for source, target, audio_item in zip(source_languages, target_languages, audio_items): + content = [ + make_audio_chat_template_content(audio_item), + { + "type": "text", + "source_language": source, + "target_language": target, + "punctuation": punctuation, + }, + ] + conversations.append([{"role": "user", "content": content}]) + + return self.apply_chat_template( + conversations, + tokenize=True, + add_generation_prompt=True, + return_dict=True, + **kwargs, + ) + + @property + def model_input_names(self): + feature_extractor_input_names = self.feature_extractor.model_input_names + return feature_extractor_input_names + ["decoder_input_ids", "labels"] + + +__all__ = ["CanaryProcessor"] diff --git a/src/transformers/models/glmasr/modular_glmasr.py b/src/transformers/models/glmasr/modular_glmasr.py index 0027dd5992f6..8dd1bcf9591b 100644 --- a/src/transformers/models/glmasr/modular_glmasr.py +++ b/src/transformers/models/glmasr/modular_glmasr.py @@ -17,7 +17,7 @@ import numpy as np from ...activations import ACT2FN -from ...audio_utils import AudioInput, make_list_of_audio_chat_template +from ...audio_utils import AudioInput, make_audio_chat_template_content, make_list_of_audio_chat_template from ...cache_utils import Cache from ...feature_extraction_utils import BatchFeature from ...modeling_layers import GradientCheckpointingLayer @@ -146,9 +146,7 @@ def apply_transcription_request( { "role": "user", "content": [ - {"type": "audio", "path": audio_item} - if isinstance(audio_item, str) - else {"type": "audio", "audio": audio_item}, + make_audio_chat_template_content(audio_item), {"type": "text", "text": prompt_text}, ], } diff --git a/src/transformers/models/glmasr/processing_glmasr.py b/src/transformers/models/glmasr/processing_glmasr.py index 61366a5c47ec..4eb2c3d9fb9a 100644 --- a/src/transformers/models/glmasr/processing_glmasr.py +++ b/src/transformers/models/glmasr/processing_glmasr.py @@ -21,7 +21,7 @@ import numpy as np -from ...audio_utils import AudioInput, make_list_of_audio_chat_template +from ...audio_utils import AudioInput, make_audio_chat_template_content, make_list_of_audio_chat_template from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack from ...tokenization_utils_base import TextInput @@ -245,9 +245,7 @@ def apply_transcription_request( { "role": "user", "content": [ - {"type": "audio", "path": audio_item} - if isinstance(audio_item, str) - else {"type": "audio", "audio": audio_item}, + make_audio_chat_template_content(audio_item), {"type": "text", "text": prompt_text}, ], } diff --git a/src/transformers/models/qwen3_asr/processing_qwen3_asr.py b/src/transformers/models/qwen3_asr/processing_qwen3_asr.py index 4fc4e0ab64ad..0ef083f55fb0 100644 --- a/src/transformers/models/qwen3_asr/processing_qwen3_asr.py +++ b/src/transformers/models/qwen3_asr/processing_qwen3_asr.py @@ -16,7 +16,12 @@ import numpy as np -from ...audio_utils import AudioInput, make_list_of_audio_chat_template +from ...audio_utils import ( + AudioInput, + make_audio_chat_template_content, + make_list_of_audio_chat_template, + prepare_language_inputs, +) from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack, prepare_prompt_input from ...tokenization_utils_base import TextInput @@ -67,63 +72,6 @@ } # fmt: on -SUPPORTED_LANGUAGE_NAMES = set(LANGUAGE_CODE_TO_NAME.values()) - - -def resolve_language(language: str | None) -> str | None: - """Map a language code or name to the canonical full name, with validation. - - Accepts language codes (e.g. ``"zh"``, ``"en"``) or full names - (e.g. ``"Chinese"``, ``"English"``). Returns the full name. - Raises ``ValueError`` if the language is not recognized. - ``None`` passes through unchanged (auto-detect). - """ - if language is None: - return None - # Try code lookup first - resolved = LANGUAGE_CODE_TO_NAME.get(language.lower()) - if resolved is not None: - return resolved - # Check if it's already a valid full name (case-insensitive) - for name in SUPPORTED_LANGUAGE_NAMES: - if language.lower() == name.lower(): - return name - raise ValueError( - f"Unsupported language: {language!r}. Use a language code " - f"(e.g. 'en', 'zh') or full name (e.g. 'English', 'Chinese'). " - f"Supported codes: {sorted(LANGUAGE_CODE_TO_NAME.keys())}. " - f"Supported names: {sorted(SUPPORTED_LANGUAGE_NAMES)}." - ) - - -def _prepare_language_inputs( - language: str | list[str] | None, batch_size: int, allow_broadcast: bool = False -) -> list[str | None]: - """Broadcast / validate a language argument to match batch_size. - - Accepts language codes (e.g. ``"zh"``, ``"en"``) or full names - (e.g. ``"Chinese"``, ``"English"``). Each value is resolved to the - canonical full language name via :func:`resolve_language`. - """ - if language is None: - return [None] * batch_size - if isinstance(language, str): - return [resolve_language(language)] * batch_size - if isinstance(language, (list, tuple)): - if allow_broadcast and len(language) == 1 and batch_size > 1: - return [resolve_language(language[0])] * batch_size - if len(language) != batch_size: - raise ValueError(f"Got {len(language)} language(s) for {batch_size} sample(s); counts must match.") - return [resolve_language(lang) for lang in language] - raise TypeError("`language` must be a string, a list of strings, or `None`.") - - -def _audio_content_item(audio_item) -> dict: - """Build a chat-template content dict for a single audio item.""" - if isinstance(audio_item, str): - return {"type": "audio", "path": audio_item} - return {"type": "audio", "audio": audio_item} - def _is_cjk_char(char: str) -> bool: """ @@ -527,7 +475,7 @@ def apply_transcription_request( batch_size = len(audio_items) if batch_size == 0: raise ValueError("`audio` must contain at least one sample.") - languages = _prepare_language_inputs(language, batch_size) + languages = prepare_language_inputs(language, batch_size, LANGUAGE_CODE_TO_NAME, return_code=False) prompts = prepare_prompt_input(prompt, batch_size, input_name="prompt") @@ -536,7 +484,7 @@ def apply_transcription_request( messages = [] if prompt_text is not None: messages.append({"role": "system", "content": [{"type": "text", "text": prompt_text}]}) - messages.append({"role": "user", "content": [_audio_content_item(audio_item)]}) + messages.append({"role": "user", "content": [make_audio_chat_template_content(audio_item)]}) conversations.append(messages) # The language is forced by prefilling the assistant turn with "language " @@ -726,7 +674,9 @@ def prepare_forced_aligner_inputs( if len(transcript) != batch_size: raise ValueError(f"Got {len(transcript)} transcript(s) but {batch_size} audio(s); they must match 1:1.") - languages = _prepare_language_inputs(language, batch_size, allow_broadcast=True) + languages = prepare_language_inputs( + language, batch_size, LANGUAGE_CODE_TO_NAME, allow_broadcast=True, return_code=False + ) # Validate that all languages are supported by the forced aligner for lang in languages: @@ -744,7 +694,7 @@ def prepare_forced_aligner_inputs( conversations = [] for wl, audio_item in zip(word_lists, audio_items): - content = [_audio_content_item(audio_item)] + content = [make_audio_chat_template_content(audio_item)] content.extend({"type": "text", "text": word} for word in wl) conversations.append([{"role": "user", "content": content}]) diff --git a/src/transformers/models/vibevoice_asr/processing_vibevoice_asr.py b/src/transformers/models/vibevoice_asr/processing_vibevoice_asr.py index 01880f3a526f..8eed3485fa7d 100644 --- a/src/transformers/models/vibevoice_asr/processing_vibevoice_asr.py +++ b/src/transformers/models/vibevoice_asr/processing_vibevoice_asr.py @@ -17,7 +17,7 @@ import numpy as np -from ...audio_utils import AudioInput, make_list_of_audio_chat_template +from ...audio_utils import AudioInput, make_audio_chat_template_content, make_list_of_audio_chat_template from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack, prepare_prompt_input from ...tokenization_utils_base import TextInput @@ -210,11 +210,7 @@ def apply_transcription_request( conversations = [] for prompt_text, audio_item in zip(prompts, audio_items): - content = [] - if isinstance(audio_item, str): - content.append({"type": "audio", "path": audio_item}) - else: - content.append({"type": "audio", "audio": audio_item}) + content = [make_audio_chat_template_content(audio_item)] if prompt_text is not None: content.append({"type": "text", "text": prompt_text}) diff --git a/tests/fixtures/canary/expected_results_batch.json b/tests/fixtures/canary/expected_results_batch.json new file mode 100644 index 000000000000..2fcbd261ab45 --- /dev/null +++ b/tests/fixtures/canary/expected_results_batch.json @@ -0,0 +1,6 @@ +{ + "transcriptions": [ + "mister Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.", + "Auch Mister Quilters Manner ist nicht weniger interessant als sein Material." + ] +} \ No newline at end of file diff --git a/tests/fixtures/canary/expected_results_transcription.json b/tests/fixtures/canary/expected_results_transcription.json new file mode 100644 index 000000000000..c57f34bd12ad --- /dev/null +++ b/tests/fixtures/canary/expected_results_transcription.json @@ -0,0 +1,5 @@ +{ + "transcriptions": [ + "mister Quilter is the apostle of the middle classes, and we are glad to welcome his gospel." + ] +} \ No newline at end of file diff --git a/tests/fixtures/canary/expected_results_translation.json b/tests/fixtures/canary/expected_results_translation.json new file mode 100644 index 000000000000..323383b6174d --- /dev/null +++ b/tests/fixtures/canary/expected_results_translation.json @@ -0,0 +1,5 @@ +{ + "transcriptions": [ + "Mister Quilter ist der Apostel der Mittelschicht, und wir freuen uns, sein Evangelium willkommen zu hei\u00dfen." + ] +} \ No newline at end of file diff --git a/tests/models/canary/__init__.py b/tests/models/canary/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/models/canary/test_modeling_canary.py b/tests/models/canary/test_modeling_canary.py new file mode 100644 index 000000000000..ddbe2b8da42a --- /dev/null +++ b/tests/models/canary/test_modeling_canary.py @@ -0,0 +1,562 @@ +# 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. +"""Testing suite for the PyTorch Canary model.""" + +import copy +import json +import math +import unittest +from pathlib import Path + +from transformers import CanaryConfig, CanaryDecoderConfig, ParakeetEncoderConfig, is_torch_available +from transformers.testing_utils import is_flaky, require_torch, slow, torch_device + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import CanaryForConditionalGeneration, CanaryModel, StaticCache + + +class CanaryModelTester: + def __init__( + self, + parent, + batch_size=3, # need batch_size != num_hidden_layers + seq_length=80, + is_training=False, + use_labels=False, + num_mel_bins=80, + hidden_size=16, + intermediate_size=32, + num_hidden_layers=2, + num_attention_heads=2, + num_key_value_heads=2, + head_dim=8, + subsampling_factor=8, + subsampling_conv_channels=16, + decoder_seq_length=4, + vocab_size=99, + max_position_embeddings=40, + decoder_start_token_id=7, + pad_token_id=2, + bos_token_id=4, + eos_token_id=3, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.decoder_seq_length = decoder_seq_length + self.decoder_key_length = decoder_seq_length + self.is_training = is_training + self.use_labels = use_labels + self.num_mel_bins = num_mel_bins + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.num_key_value_heads = num_key_value_heads + self.head_dim = head_dim + self.subsampling_factor = subsampling_factor + self.subsampling_conv_channels = subsampling_conv_channels + self.vocab_size = vocab_size + self.max_position_embeddings = max_position_embeddings + self.decoder_start_token_id = decoder_start_token_id + self.pad_token_id = pad_token_id + self.bos_token_id = bos_token_id + self.eos_token_id = eos_token_id + + def get_config(self): + encoder_config = ParakeetEncoderConfig( + hidden_size=self.hidden_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + intermediate_size=self.intermediate_size, + num_mel_bins=self.num_mel_bins, + subsampling_factor=self.subsampling_factor, + subsampling_conv_channels=self.subsampling_conv_channels, + scale_input=False, + ) + decoder_config = CanaryDecoderConfig( + vocab_size=self.vocab_size, + hidden_size=self.hidden_size, + intermediate_size=self.intermediate_size, + num_hidden_layers=self.num_hidden_layers, + num_attention_heads=self.num_attention_heads, + num_key_value_heads=self.num_key_value_heads, + head_dim=self.head_dim, + max_position_embeddings=self.max_position_embeddings, + pad_token_id=self.pad_token_id, + ) + return CanaryConfig( + encoder_config=encoder_config, + decoder_config=decoder_config, + vocab_size=self.vocab_size, + decoder_start_token_id=self.decoder_start_token_id, + pad_token_id=self.pad_token_id, + bos_token_id=self.bos_token_id, + eos_token_id=self.eos_token_id, + ) + + def prepare_config_and_inputs_for_common(self): + config = self.get_config() + # `seq_length` is in mel frames; keep it a multiple of `subsampling_factor` so 8x subsampling does not collapse it. + input_features = floats_tensor([self.batch_size, self.seq_length, self.num_mel_bins], scale=1.0) + attention_mask = torch.ones([self.batch_size, self.seq_length], dtype=torch.long, device=torch_device) + decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) + decoder_attention_mask = decoder_input_ids.ne(self.pad_token_id) + inputs_dict = { + "input_features": input_features, + "attention_mask": attention_mask, + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": decoder_attention_mask, + } + return config, inputs_dict + + def get_subsampled_output_lengths(self, input_lengths): + """Computes the FastConformer subsampled length, used by the generation test mixin for encoder shapes.""" + kernel_size, stride = 3, 2 + padding = (kernel_size - 1) // 2 * 2 - kernel_size + for _ in range(int(math.log2(self.subsampling_factor))): + input_lengths = (input_lengths + padding) // stride + 1 + return input_lengths + + +@require_torch +class CanaryModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (CanaryModel, CanaryForConditionalGeneration) if is_torch_available() else () + all_generative_model_classes = (CanaryForConditionalGeneration,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "automatic-speech-recognition": CanaryForConditionalGeneration, + "feature-extraction": CanaryModel, + } + if is_torch_available() + else {} + ) + is_encoder_decoder = True + + def setUp(self): + self.model_tester = CanaryModelTester(self) + self.config_tester = ConfigTester(self, has_text_modality=False, config_class=CanaryConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + # Overridden because the FastConformer encoder subsamples the input, so encoder shapes use the subsampled length. + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + subsampled_seq_length = self.model_tester.get_subsampled_output_lengths(self.model_tester.seq_length) + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [subsampled_seq_length, self.model_tester.hidden_size], + ) + + if config.is_encoder_decoder: + hidden_states = outputs.decoder_hidden_states + self.assertIsInstance(hidden_states, (list, tuple)) + self.assertEqual(len(hidden_states), expected_num_layers) + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [self.model_tester.decoder_seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + self._set_subconfig_attributes(config, "output_hidden_states", True) + check_hidden_states_output(inputs_dict, config, model_class) + + # Overridden for the same subsampling reason as `test_hidden_states_output` (mirrors `WhisperModelTest`). + def test_attention_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + # force eager attention to support output attentions + config._attn_implementation = "eager" + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", 1) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", 1) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class._from_config(config, attn_implementation="eager") + config = model.config + model.to(torch_device) + model.eval() + + subsampled_encoder_seq_length = self.model_tester.get_subsampled_output_lengths(encoder_seq_length) + subsampled_encoder_key_length = self.model_tester.get_subsampled_output_lengths(encoder_key_length) + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + self._set_subconfig_attributes(config, "output_attentions", True) + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + out_len = len(outputs) + + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, subsampled_encoder_key_length], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + added_hidden_states = 2 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, subsampled_encoder_seq_length, subsampled_encoder_key_length], + ) + + # Overridden because Canary takes `input_features` + `decoder_input_ids`, not `input_ids` (like Whisper). + def test_resize_tokens_embeddings(self): + original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + if not self.test_resize_embeddings: + self.skipTest(reason="test_resize_embeddings is False") + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config) + model.to(torch_device) + if self.model_tester.is_training is False: + model.eval() + + # Retrieve the embeddings and clone theme + model_vocab_size = config.get_text_config().vocab_size + model_embed = model.resize_token_embeddings(model_vocab_size) + cloned_embeddings = model_embed.weight.clone() + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size + 10) + self.assertEqual(model.config.get_text_config().vocab_size, model_vocab_size + 10) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size - 15) + self.assertEqual(model.config.get_text_config().vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15) + + # make sure that decoder_input_ids are resized + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that adding and removing tokens has not modified the first part of the embedding matrix. + models_equal = True + for p1, p2 in zip(cloned_embeddings, model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + self.assertTrue(models_equal) + + # Overridden for the same audio-model reason as `test_resize_tokens_embeddings` (mirrors `WhisperModelTest`). + def test_resize_embeddings_untied(self): + original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + if not self.test_resize_embeddings: + self.skipTest(reason="test_resize_embeddings is False") + + original_config.tie_word_embeddings = False + + # if model cannot untied embeddings -> leave test + if original_config.tie_word_embeddings: + self.skipTest(reason="Model cannot untie embeddings") + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config).to(torch_device) + model.eval() + + # if no output embeddings -> leave test + if model.get_output_embeddings() is None: + continue + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_vocab_size = config.get_text_config().vocab_size + model.resize_token_embeddings(model_vocab_size + 10) + self.assertEqual(model.config.get_text_config().vocab_size, model_vocab_size + 10) + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size + 10) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size + 10) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model.resize_token_embeddings(model_vocab_size - 15) + self.assertEqual(model.config.get_text_config().vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size - 15) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size - 15) + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + @unittest.skip( + reason="Canary is an encoder-decoder ASR model that requires audio features and cannot generate from input ids only." + ) + def test_generate_without_input_ids(self): + pass + + @unittest.skip(reason="Canary automatically adds an attention_mask input") + def test_sdpa_can_dispatch_on_flash(self): + pass + + @is_flaky(description="Large difference with A10. Still flaky after setting larger tolerance") + def test_generate_continue_from_past_key_values(self): + super().test_generate_continue_from_past_key_values() + + # Overridden because the head count comes from the decoder sub-config (mirrors `DiaModelTest`). + def _check_attentions_for_generate( + self, batch_size, attentions, prompt_length, output_length, config, decoder_past_key_values + ): + self.assertIsInstance(attentions, tuple) + self.assertListEqual( + [isinstance(iter_attentions, tuple) for iter_attentions in attentions], [True] * len(attentions) + ) + self.assertEqual(len(attentions), (output_length - prompt_length)) + + use_cache = decoder_past_key_values is not None + has_static_cache = isinstance(decoder_past_key_values, StaticCache) + + # When `output_attentions=True`, each iteration of generate appends the attentions corresponding to the new + # token(s) + for generated_length, iter_attentions in enumerate(attentions): + # regardless of using cache, the first forward pass will have the full prompt as input + if use_cache and generated_length > 0: + model_input_length = 1 + else: + model_input_length = prompt_length + generated_length + if has_static_cache: + # hybrid caches have layers with no fixed max, so pick the first layer reporting a real length + query_length = next( + ( + decoder_past_key_values.get_max_length(i) + for i in range(len(decoder_past_key_values)) + if decoder_past_key_values.get_max_length(i) != -1 + ), + prompt_length + generated_length, + ) + else: + query_length = prompt_length + generated_length + + expected_shape = ( + batch_size, + config.decoder_config.num_attention_heads, # Decoder config + model_input_length, + query_length, + ) + # check attn size + self.assertListEqual( + [layer_attention.shape for layer_attention in iter_attentions], [expected_shape] * len(iter_attentions) + ) + + # Overridden for the same sub-config reason as `_check_attentions_for_generate` (mirrors `DiaModelTest`). + def _check_encoder_attention_for_generate(self, attentions, batch_size, config, prompt_length): + # Encoder config + encoder_expected_shape = (batch_size, config.encoder_config.num_attention_heads, prompt_length, prompt_length) + self.assertIsInstance(attentions, tuple) + self.assertListEqual( + [layer_attentions.shape for layer_attentions in attentions], + [encoder_expected_shape] * len(attentions), + ) + + # Overridden for the same sub-config reason as `_check_attentions_for_generate` (mirrors `DiaModelTest`). + def _check_hidden_states_for_generate( + self, batch_size, hidden_states, prompt_length, output_length, config, use_cache=False + ): + self.assertIsInstance(hidden_states, tuple) + self.assertListEqual( + [isinstance(iter_hidden_states, tuple) for iter_hidden_states in hidden_states], + [True] * len(hidden_states), + ) + self.assertEqual(len(hidden_states), (output_length - prompt_length)) + + # When `output_hidden_states=True`, each iteration of generate appends the hidden states corresponding to the + # new token(s) + # NOTE: `StaticCache` may have different lengths on different layers, if this test starts failing add more + # elaborate checks + for generated_length, iter_hidden_states in enumerate(hidden_states): + # regardless of using cache, the first forward pass will have the full prompt as input + if use_cache and generated_length > 0: + model_input_length = 1 + else: + model_input_length = prompt_length + generated_length + expected_shape = (batch_size, model_input_length, config.decoder_config.hidden_size) # Decoder config + # check hidden size + self.assertListEqual( + [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states], + [expected_shape] * len(iter_hidden_states), + ) + + # Overridden for the same sub-config reason as `_check_attentions_for_generate` (mirrors `DiaModelTest`). + def _check_encoder_hidden_states_for_generate(self, hidden_states, batch_size, config, prompt_length): + # Encoder config + encoder_expected_shape = (batch_size, prompt_length, config.encoder_config.hidden_size) + self.assertIsInstance(hidden_states, tuple) + self.assertListEqual( + [layer_hidden_states.shape for layer_hidden_states in hidden_states], + [encoder_expected_shape] * len(hidden_states), + ) + + +@require_torch +@slow +class CanaryIntegrationTest(unittest.TestCase): + checkpoint = "nvidia/canary-1b-v2" + + @classmethod + def setUp(cls): + from transformers import AutoProcessor + + cls.fixtures_path = Path(__file__).parent.parent.parent / "fixtures/canary" + cls.processor = AutoProcessor.from_pretrained(cls.checkpoint) + cls.model = CanaryForConditionalGeneration.from_pretrained(cls.checkpoint).to(torch_device).eval() + + def _load_datasamples(self, processor, num_samples): + from datasets import Audio, load_dataset + + ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate)) + speech_samples = ds.sort("id")[:num_samples]["audio"] + return [x["array"] for x in speech_samples] + + def test_transcription_en(self): + """ + reproducer: https://gist.github.com/harshaljanjani/ff11260652a115da61037ecfc288c74f#file-reproducer_transcription-py + """ + with open(self.fixtures_path / "expected_results_transcription.json") as f: + expected_transcriptions = json.load(f)["transcriptions"] + + inputs = self._load_datasamples(self.processor, 1) + features = self.processor.apply_transcription_request(audio=inputs, source_language="en").to(torch_device) + generated = self.model.generate(**features, max_new_tokens=128, do_sample=False) + transcriptions = [text.strip() for text in self.processor.decode(generated, skip_special_tokens=True)] + self.assertListEqual(transcriptions, expected_transcriptions) + + def test_transcription_en_batched(self): + """ + reproducer: https://gist.github.com/harshaljanjani/d93abd784d09a7f25291080ebcdf805d#file-reproducer_batch-py + """ + with open(self.fixtures_path / "expected_results_batch.json") as f: + expected_transcriptions = json.load(f)["transcriptions"] + + inputs = self._load_datasamples(self.processor, 2) + features = self.processor.apply_transcription_request( + audio=inputs, source_language="en", target_language=["en", "de"] + ).to(torch_device) + generated = self.model.generate(**features, max_new_tokens=128, do_sample=False) + transcriptions = [text.strip() for text in self.processor.decode(generated, skip_special_tokens=True)] + self.assertListEqual(transcriptions, expected_transcriptions) + + def test_translation_en_to_de(self): + """ + reproducer: https://gist.github.com/harshaljanjani/5b093d7fc25507694b7b6ada08fa7988#file-reproducer_translation-py + """ + with open(self.fixtures_path / "expected_results_translation.json") as f: + expected_transcriptions = json.load(f)["transcriptions"] + + inputs = self._load_datasamples(self.processor, 1) + features = self.processor.apply_transcription_request( + audio=inputs, source_language="en", target_language="de" + ).to(torch_device) + generated = self.model.generate(**features, max_new_tokens=128, do_sample=False) + transcriptions = [text.strip() for text in self.processor.decode(generated, skip_special_tokens=True)] + self.assertListEqual(transcriptions, expected_transcriptions) diff --git a/tests/models/canary/test_processing_canary.py b/tests/models/canary/test_processing_canary.py new file mode 100644 index 000000000000..039477e97727 --- /dev/null +++ b/tests/models/canary/test_processing_canary.py @@ -0,0 +1,94 @@ +# Copyright 2026 the HuggingFace 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. + +import shutil +import tempfile +import unittest + +import numpy as np + +from transformers import AutoProcessor, CanaryProcessor +from transformers.testing_utils import require_torch + + +def _get_prompt(source: str, target: str, pnc: bool = True) -> str: + return ( + "<|startofcontext|><|startoftranscript|><|emo:undefined|>" + f"<|{source}|><|{target}|>" + f"{'<|pnc|>' if pnc else '<|nopnc|>'}<|noitn|><|notimestamp|><|nodiarize|>" + ) + + +@require_torch +class CanaryProcessorTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.checkpoint = "nvidia/canary-1b-v2" + cls.tmpdirname = tempfile.mkdtemp() + CanaryProcessor.from_pretrained(cls.checkpoint).save_pretrained(cls.tmpdirname) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmpdirname, ignore_errors=True) + + def get_processor(self): + return AutoProcessor.from_pretrained(self.tmpdirname) + + def _audio(self, num_samples: int = 16000): + return np.zeros(num_samples, dtype=np.float32) + + def _decode_prompt(self, processor, inputs, index: int = 0) -> str: + return processor.tokenizer.decode(inputs["decoder_input_ids"][index], skip_special_tokens=False) + + def test_chat_template_is_loaded(self): + self.assertIsNotNone(self.get_processor().chat_template) + + def test_apply_transcription_request_transcription(self): + processor = self.get_processor() + inputs = processor.apply_transcription_request(audio=self._audio(), source_language="en") + self.assertIn("input_features", inputs) + self.assertEqual(self._decode_prompt(processor, inputs), _get_prompt("en", "en")) + + def test_apply_transcription_request_translation(self): + processor = self.get_processor() + inputs = processor.apply_transcription_request(audio=self._audio(), source_language="en", target_language="de") + self.assertEqual(self._decode_prompt(processor, inputs), _get_prompt("en", "de")) + + def test_punctuation_flag(self): + processor = self.get_processor() + inputs = processor.apply_transcription_request(audio=self._audio(), source_language="en", punctuation=False) + self.assertEqual(self._decode_prompt(processor, inputs), _get_prompt("en", "en", pnc=False)) + + def test_batch_broadcast_and_per_sample(self): + processor = self.get_processor() + inputs = processor.apply_transcription_request( + audio=[self._audio(), self._audio()], source_language="en", target_language=["en", "es"] + ) + self.assertEqual(len(inputs["decoder_input_ids"]), 2) + self.assertEqual(self._decode_prompt(processor, inputs, 0), _get_prompt("en", "en")) + self.assertEqual(self._decode_prompt(processor, inputs, 1), _get_prompt("en", "es")) + + def test_batch_length_mismatch_raises(self): + processor = self.get_processor() + with self.assertRaises(ValueError): + processor.apply_transcription_request(audio=[self._audio()], source_language=["en", "de"]) + + def test_call_output_labels(self): + processor = self.get_processor() + outputs = processor(audio=self._audio(), text="hello world", output_labels=True) + self.assertIn("input_features", outputs) + self.assertIn("decoder_input_ids", outputs) + self.assertIn("labels", outputs) + # the decoder inputs are already right-shifted with respect to `labels` + self.assertListEqual(outputs["decoder_input_ids"][..., 1:].tolist(), outputs["labels"][..., :-1].tolist()) From dce39210a56428d5cf5d6a03bbeb12f45c3918d0 Mon Sep 17 00:00:00 2001 From: eustlb <94853470+eustlb@users.noreply.github.com> Date: Tue, 1 Sep 2026 08:46:08 +0000 Subject: [PATCH 010/996] [fix] inkling: mps + cuda mel spec extraction (#47432) * fix Co-authored-by: alwaysprince05 <218506877+alwaysprince05@users.noreply.github.com> * add test * remove redundant --------- Co-authored-by: alwaysprince05 <218506877+alwaysprince05@users.noreply.github.com> --- .../inkling/feature_extraction_inkling.py | 3 +- .../models/inkling/processing_inkling.py | 7 ++- .../models/inkling/test_processing_inkling.py | 45 ++++++++++++------- 3 files changed, 36 insertions(+), 19 deletions(-) diff --git a/src/transformers/models/inkling/feature_extraction_inkling.py b/src/transformers/models/inkling/feature_extraction_inkling.py index 257ac4a00d3e..a48db0ccc41d 100644 --- a/src/transformers/models/inkling/feature_extraction_inkling.py +++ b/src/transformers/models/inkling/feature_extraction_inkling.py @@ -109,6 +109,7 @@ def __init__( self.mel_filters = torch.from_numpy(np.ascontiguousarray(mel_filters.T, dtype=np.float32)) def _torch_extract_fbank_features(self, waveform: torch.Tensor, device: str = "cpu") -> torch.Tensor: + waveform = waveform.to(device) right_pad = math.ceil(waveform.shape[-1] / self.hop_length) * self.hop_length - waveform.shape[-1] left_pad = max(self.n_fft - self.hop_length, 0) waveform = F.pad(waveform, (left_pad, right_pad)) @@ -232,7 +233,7 @@ def _to_mono(clip: "np.ndarray | torch.Tensor | list") -> torch.Tensor: # Number of valid frames per clip == ceil(audio_length / hop_length); everything beyond it is # padding, which we zero out so it carries `padding_value`. num_frames = torch.div( - padded_inputs.audio_lengths + self.hop_length - 1, self.hop_length, rounding_mode="floor" + padded_inputs.audio_lengths.to(device) + self.hop_length - 1, self.hop_length, rounding_mode="floor" ) input_features_mask = torch.arange(input_features.shape[1], device=device)[None, :] < num_frames[:, None] input_features = input_features * input_features_mask.unsqueeze(-1) diff --git a/src/transformers/models/inkling/processing_inkling.py b/src/transformers/models/inkling/processing_inkling.py index 4c1f5539a48e..7e6c502340ba 100644 --- a/src/transformers/models/inkling/processing_inkling.py +++ b/src/transformers/models/inkling/processing_inkling.py @@ -78,13 +78,16 @@ def __init__( self.num_dmel_bins = num_dmel_bins self.dmel_min_value = dmel_min_value self.dmel_max_value = dmel_max_value - self.bin_centers = torch.linspace(dmel_min_value, dmel_max_value, num_dmel_bins, dtype=torch.float64) + # float64 then cast to float32: reproduces the float64 bins exactly + self.bin_centers = torch.linspace(dmel_min_value, dmel_max_value, num_dmel_bins, dtype=torch.float64).to( + torch.float32 + ) super().__init__(feature_extractor, image_processor, tokenizer, chat_template=chat_template) def _extract_dmel_bins(self, input_features: "torch.Tensor") -> "torch.Tensor": bin_centers = self.bin_centers.to(input_features.device) - mel = input_features.to(torch.float64).clamp(min=self.dmel_min_value, max=self.dmel_max_value) + mel = input_features.clamp(min=self.dmel_min_value, max=self.dmel_max_value) return (mel.unsqueeze(-1) - bin_centers).abs().argmin(dim=-1).to(torch.int32) def _process_audio(self, audio, **kwargs): diff --git a/tests/models/inkling/test_processing_inkling.py b/tests/models/inkling/test_processing_inkling.py index c98ec78a5bf9..866600b2cfd3 100644 --- a/tests/models/inkling/test_processing_inkling.py +++ b/tests/models/inkling/test_processing_inkling.py @@ -23,7 +23,14 @@ from safetensors.torch import load_file from transformers import AutoProcessor, InklingProcessor, is_torch_available -from transformers.testing_utils import get_tests_dir, require_librosa, require_vision, slow +from transformers.testing_utils import ( + get_tests_dir, + require_librosa, + require_torch_accelerator, + require_vision, + slow, + torch_device, +) from transformers.utils import is_vision_available from ...test_processing_common import MODALITY_INPUT_DATA, ProcessorTesterMixin @@ -209,6 +216,7 @@ def test_processor_to_json_string(self): @slow +@require_torch_accelerator class InklingProcessingIntegrationTest(unittest.TestCase): """ Check against sglang reference.. @@ -262,22 +270,27 @@ def _expected_dmel_from_inputs(self, inputs) -> "torch.Tensor": return torch.cat(per_audio, dim=0) def _assert_matches_sglang(self, case: str, messages: list, has_audio: bool = False): - inputs = self.processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors="pt", - ) expected = self._load_expected(case) - - input_ids = inputs["input_ids"][0] - expected_input_ids = self._remap_sentinels(expected["input_ids"].to(torch.int64)) - torch.testing.assert_close(input_ids, expected_input_ids, rtol=0, atol=0) - - if has_audio: - dmel = self._expected_dmel_from_inputs(inputs) - torch.testing.assert_close(dmel, expected["audio_dmel"].to(torch.int32), rtol=0, atol=0) + for device in ["cpu", torch_device]: + processor_kwargs = {} if device == "cpu" else {"audio_kwargs": {"device": device}} + inputs = self.processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt", + processor_kwargs=processor_kwargs, + ).to(device) + + input_ids = inputs["input_ids"][0] + expected_input_ids = self._remap_sentinels(expected["input_ids"].to(torch.int64)).to(device) + torch.testing.assert_close(input_ids, expected_input_ids, rtol=0, atol=0) + + if has_audio: + dmel = self._expected_dmel_from_inputs(inputs) + torch.testing.assert_close( + dmel, expected["audio_dmel"].to(dtype=torch.int32, device=device), rtol=0, atol=0 + ) def test_apply_chat_template_text(self): messages = [{"role": "user", "content": [{"type": "text", "text": "What is the capital of France?"}]}] From 26865212c4138d7365ba39041ea02efa85471c3e Mon Sep 17 00:00:00 2001 From: JJJYmmm <92386084+JJJYmmm@users.noreply.github.com> Date: Tue, 1 Sep 2026 08:49:37 +0000 Subject: [PATCH 011/996] fix qwen4exp-fp8 ple embedding (#48368) * fix qwen4exp-fp8 ple embedding * fix weight_scale resave * add modules_to_convert * unnecessary dtype * lets use super * automatically anchor weight targets --- src/transformers/integrations/__init__.py | 4 +- .../integrations/finegrained_fp8.py | 40 +++++++++++++++++++ .../quantizers/quantizer_finegrained_fp8.py | 14 ++++++- src/transformers/utils/quantization_config.py | 5 +++ .../qwen4_exp/test_modeling_qwen4_exp.py | 15 +++++++ .../quantization/finegrained_fp8/test_fp8.py | 38 ++++++++++++++++++ 6 files changed, 113 insertions(+), 3 deletions(-) diff --git a/src/transformers/integrations/__init__.py b/src/transformers/integrations/__init__.py index 1cf5af8c3359..27c04bdd6bbf 100755 --- a/src/transformers/integrations/__init__.py +++ b/src/transformers/integrations/__init__.py @@ -50,7 +50,7 @@ ], "eetq": ["replace_with_eetq_linear"], "fbgemm_fp8": ["FbgemmFp8Linear", "FbgemmFp8Llama4TextExperts", "replace_with_fbgemm_fp8_linear"], - "finegrained_fp8": ["FP8Linear", "replace_with_fp8_linear"], + "finegrained_fp8": ["FP8Embedding", "FP8Linear", "replace_with_fp8_embedding", "replace_with_fp8_linear"], "fsdp": ["is_fsdp_enabled", "is_fsdp_managed_module"], "gemma_quant": [ "QuantizedEmbedding", @@ -210,7 +210,7 @@ ) from .eetq import replace_with_eetq_linear from .fbgemm_fp8 import FbgemmFp8Linear, FbgemmFp8Llama4TextExperts, replace_with_fbgemm_fp8_linear - from .finegrained_fp8 import FP8Linear, replace_with_fp8_linear + from .finegrained_fp8 import FP8Embedding, FP8Linear, replace_with_fp8_embedding, replace_with_fp8_linear from .fsdp import is_fsdp_enabled, is_fsdp_managed_module from .gemma_quant import ( QuantizedEmbedding, diff --git a/src/transformers/integrations/finegrained_fp8.py b/src/transformers/integrations/finegrained_fp8.py index 910a8bd82ac2..342abd9c35af 100644 --- a/src/transformers/integrations/finegrained_fp8.py +++ b/src/transformers/integrations/finegrained_fp8.py @@ -346,6 +346,30 @@ def forward(self, input: torch.Tensor) -> torch.Tensor: ) +class FP8Embedding(nn.Embedding): + """`nn.Embedding` whose table is stored in FP8 with a single per-tensor `weight_scale`. + + Qwen4-Exp's hashed n-gram table is ~48 GiB in FP8, too big to dequantize at load time, so the + rescale runs on the rows a lookup gathers instead. Build it on the `meta` device: like + `FP8Linear`, `__init__` lets `nn.Embedding` allocate a full-precision table first. + """ + + def __init__( + self, + num_embeddings: int, + embedding_dim: int, + padding_idx: int | None = None, + ): + super().__init__(num_embeddings, embedding_dim, padding_idx=padding_idx) + self.weight = nn.Parameter(torch.empty(num_embeddings, embedding_dim, dtype=_FP8_DTYPE), requires_grad=False) + # `(1,)` rather than a scalar: the shape checkpoints serialize per-tensor scales with. + self.weight_scale = nn.Parameter(torch.ones(1), requires_grad=False) + + def forward(self, input: torch.Tensor) -> torch.Tensor: + rows = super().forward(input) + return rows.to(self.weight_scale.dtype) * self.weight_scale + + class FP8GroupedLinear(FP8Linear): """FP8 drop-in for block-diagonal grouped linears. @@ -794,6 +818,22 @@ def _disable_deepgemm_on_multi_device(model: nn.Module) -> None: ) +def replace_with_fp8_embedding(model, patterns: list[str], modules_to_not_convert: list[str] | None = None): + """Swap every `nn.Embedding` whose name ends with one of `patterns` for `FP8Embedding`. + + Also runs under `dequantize=True`: a table worth quantizing is one we cannot afford to expand. + """ + for name, module in list(model.named_modules()): + if type(module) is nn.Embedding and any(name.endswith(p) for p in patterns): + if not should_convert_module(name, modules_to_not_convert): + continue + with torch.device("meta"): + new_module = FP8Embedding(module.num_embeddings, module.embedding_dim, module.padding_idx) + new_module._hf_quantized_needs_local_tp = True + model.set_submodule(name, new_module) + return model + + def replace_with_fp8_linear( model, modules_to_not_convert: list[str] | None = None, quantization_config=None, pre_quantized=False ): diff --git a/src/transformers/quantizers/quantizer_finegrained_fp8.py b/src/transformers/quantizers/quantizer_finegrained_fp8.py index 242ea9a657ce..b0b4d24c74b3 100644 --- a/src/transformers/quantizers/quantizer_finegrained_fp8.py +++ b/src/transformers/quantizers/quantizer_finegrained_fp8.py @@ -120,13 +120,17 @@ def _process_model_before_weight_loading( model: "PreTrainedModel", **kwargs, ): - from ..integrations.finegrained_fp8 import replace_with_fp8_linear + from ..integrations.finegrained_fp8 import replace_with_fp8_embedding, replace_with_fp8_linear self._normalize_modules_to_not_convert(model) self.modules_to_not_convert = self.get_modules_to_not_convert( model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules ) + modules_to_convert = self.quantization_config.modules_to_convert + if self.pre_quantized and modules_to_convert: + replace_with_fp8_embedding(model, modules_to_convert, self.modules_to_not_convert) + model = replace_with_fp8_linear( model, modules_to_not_convert=self.modules_to_not_convert, @@ -266,6 +270,14 @@ def update_weight_conversions(self, weight_conversions): scale_rename = WeightRenaming(source_patterns=r"^(.+)\.scale$", target_patterns=r"\1.weight_scale_inv") weight_conversions = [scale_rename] + list(weight_conversions) + # Some checkpoints shard weights (e.g. Qwen4-Exp's `ngram_embedding`). Since WeightConverter targets become source + # patterns when saving, anchor them to avoid matching the corresponding scale parameters. + for conv in weight_conversions: + if isinstance(conv, WeightConverter): + conv._original_target_patterns = [ + f"{p}$" if p.endswith(".weight") else p for p in conv._original_target_patterns + ] + if not (self.pre_quantized and self.quantization_config.dequantize): return weight_conversions + self.get_weight_conversions() diff --git a/src/transformers/utils/quantization_config.py b/src/transformers/utils/quantization_config.py index 7111012c1c7a..d6b47360ade4 100644 --- a/src/transformers/utils/quantization_config.py +++ b/src/transformers/utils/quantization_config.py @@ -1702,6 +1702,8 @@ class FineGrainedFP8Config(QuantizationConfigMixin): Whether to dequantize the model during loading. modules_to_not_convert (`list`, *optional*): A list of module names that should not be converted during quantization. + modules_to_convert (`list`, *optional*): + A list of additional module names, such as embedding tables, that should be converted during quantization. scale_fmt (`str`, *optional*, defaults to `"float"`): Storage dtype of the per-block weight scales: `"float"` (fp32, V3-style) or `"ue8m0"` (1-byte `torch.float8_e8m0fnu`, V4-style). @@ -1713,6 +1715,7 @@ def __init__( weight_block_size: tuple[int, int] = (128, 128), dequantize: bool = False, modules_to_not_convert: list | None = None, + modules_to_convert: list | None = None, scale_fmt: str = "float", **kwargs, ): @@ -1721,6 +1724,8 @@ def __init__( if modules_to_not_convert is None and "ignored_layers" in kwargs: modules_to_not_convert = kwargs.pop("ignored_layers") self.modules_to_not_convert = modules_to_not_convert + # TODO: check overlap with not to convert + self.modules_to_convert = modules_to_convert self.activation_scheme = activation_scheme self.weight_block_size = weight_block_size self.dequantize = dequantize diff --git a/tests/models/qwen4_exp/test_modeling_qwen4_exp.py b/tests/models/qwen4_exp/test_modeling_qwen4_exp.py index f9ce6e217564..b308989e1149 100644 --- a/tests/models/qwen4_exp/test_modeling_qwen4_exp.py +++ b/tests/models/qwen4_exp/test_modeling_qwen4_exp.py @@ -36,6 +36,7 @@ from transformers import ( AutoModelForCausalLM, DynamicCache, + FineGrainedFP8Config, Qwen4ExpConfig, Qwen4ExpForCausalLM, Qwen4ExpForConditionalGeneration, @@ -46,6 +47,8 @@ StaticCache, ) from transformers.distributed.fsdp import verify_fsdp_plan + from transformers.integrations import FP8Embedding + from transformers.quantizers.quantizer_finegrained_fp8 import FineGrainedFP8HfQuantizer class Qwen4ExpTextModelTester(CausalLMModelTester): @@ -250,6 +253,18 @@ def test_ple_layers_must_use_linear_attention(self): layer_types=["linear_attention", "qwen_sparse_attention"], ) + def test_finegrained_fp8_embedding_conversion(self): + config = self.model_tester.get_config(ple_layer_ids=[1], layer_types=["linear_attention"]) + with torch.device("meta"): + model = Qwen4ExpForCausalLM(config) + + quantization_config = FineGrainedFP8Config( + modules_to_convert=["ple.ple_embedding.ngram_embedding"], modules_to_not_convert=[] + ) + FineGrainedFP8HfQuantizer(quantization_config).preprocess_model(model) + + self.assertIsInstance(model.model.layers[0].ple.ple_embedding.ngram_embedding, FP8Embedding) + def test_ple_padding_and_static_cache_match_unpadded_sequence(self): torch.manual_seed(0) config = self.model_tester.get_config( diff --git a/tests/quantization/finegrained_fp8/test_fp8.py b/tests/quantization/finegrained_fp8/test_fp8.py index c99292a0c5fa..951559a7c255 100644 --- a/tests/quantization/finegrained_fp8/test_fp8.py +++ b/tests/quantization/finegrained_fp8/test_fp8.py @@ -461,6 +461,44 @@ def test_linear_with_diff_feature_size_preserves_shape(self): self.assertEqual(x_.shape, (1, 5, 256)) +class FP8EmbeddingTest(unittest.TestCase): + """ + Some checkpoints quantize an embedding *table* rather than a linear (Qwen4-Exp's n-gram/PLE + table). + """ + + def test_lookup_applies_the_per_tensor_scale(self): + """Without the rescale the rows come back as raw FP8 and blow up the next matmul.""" + from transformers.integrations import FP8Embedding + + table = torch.randn(64, 16, dtype=torch.bfloat16) + scale = table.abs().max().float() / torch.finfo(torch.float8_e4m3fn).max + embedding = FP8Embedding(64, 16) + embedding.weight = torch.nn.Parameter((table.float() / scale).to(torch.float8_e4m3fn), requires_grad=False) + embedding.weight_scale = torch.nn.Parameter(scale.to(torch.bfloat16).reshape(1), requires_grad=False) + + ids = torch.randint(0, 64, (2, 5)) + rows, expected = embedding(ids), table[ids] + + self.assertEqual(rows.dtype, expected.dtype) + error = (rows.float() - expected.float()).abs().max() / expected.float().abs().max() + self.assertLess(error, 0.1) + + def test_patterns_match_by_suffix_and_honour_the_skip_list(self): + """Suffixes match whether or not the text model is nested under a multimodal wrapper.""" + from transformers.integrations import FP8Embedding, replace_with_fp8_embedding + + model = torch.nn.ModuleDict( + {n: torch.nn.ModuleDict({"table": torch.nn.Embedding(8, 4)}) for n in ("layers", "language_model")} + ) + model.other = torch.nn.Embedding(8, 4) + replace_with_fp8_embedding(model, ["table"], modules_to_not_convert=["language_model.table"]) + + self.assertIsInstance(model["layers"]["table"], FP8Embedding) # matched by suffix + self.assertIs(type(model["language_model"]["table"]), torch.nn.Embedding) # skip-listed + self.assertIs(type(model.other), torch.nn.Embedding) # no pattern match + + class FP8DeepGEMMMultiDeviceTest(unittest.TestCase): """`_disable_deepgemm_on_multi_device` must flag FP8 modules based on the devices they actually occupy — DeepGEMM's kernels are bound to a single CUDA context and corrupt across devices, but a From 8e35c981dbdb2caf75b341023e243d834f829b2b Mon Sep 17 00:00:00 2001 From: Noxtimo <139155109+Noxtimo@users.noreply.github.com> Date: Tue, 1 Sep 2026 10:09:03 +0100 Subject: [PATCH 012/996] Fix MTP generation test regex gate for escaped layer ignore keys (#48003) (#48262) --- tests/generation/test_utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/generation/test_utils.py b/tests/generation/test_utils.py index 2229585907ae..e90768603a40 100644 --- a/tests/generation/test_utils.py +++ b/tests/generation/test_utils.py @@ -2488,7 +2488,7 @@ def test_generate_with_mtp(self): keys_to_ignore_unexpected = model_class._keys_to_ignore_on_load_unexpected or [] # If we don't have any mtp patterns, skip if not hasattr(config.get_text_config(), "num_mtp_layers") or not any( - "mtp" in x or re.search(r"layers\.\d+", x) is not None for x in keys_to_ignore_unexpected + "mtp" in x or re.search(r"layers\\?\.\d+", x) is not None for x in keys_to_ignore_unexpected ): self.skipTest("No MTP keys registered") From 1c05ce209c9eb4319da07e73f02dd6aba48a8eda Mon Sep 17 00:00:00 2001 From: Harshal Janjani Date: Tue, 1 Sep 2026 12:28:05 +0000 Subject: [PATCH 013/996] fix: Add DEIMv2 attribution (#48448) --- docs/source/en/model_doc/deimv2.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/source/en/model_doc/deimv2.md b/docs/source/en/model_doc/deimv2.md index 3d3afc6ab723..6ae725f3870f 100644 --- a/docs/source/en/model_doc/deimv2.md +++ b/docs/source/en/model_doc/deimv2.md @@ -25,6 +25,9 @@ The abstract from the paper is the following: *Driven by the simple and effective Dense O2O, DEIM demonstrates faster convergence and enhanced performance. In this work, we extend it with DINOv3 features, resulting in DEIMv2. DEIMv2 spans eight model sizes from X to Atto, covering GPU, edge, and mobile deployment. For the X, L, M, and S variants, we adopt DINOv3-pretrained / distilled backbones and introduce a Spatial Tuning Adapter (STA), which efficiently converts DINOv3's single-scale output into multi-scale features and complements strong semantics with fine-grained details to enhance detection. For ultra-lightweight models (Nano, Pico, Femto, and Atto), we employ HGNetv2 with depth and width pruning to meet strict resource budgets. Together with a simplified decoder and an upgraded Dense O2O, this unified design enables DEIMv2 to achieve a superior performance-cost trade-off across diverse scenarios, establishing new state-of-the-art results. Notably, our largest model, DEIMv2-X, achieves 57.8 AP with only 50.3M parameters, surpassing prior X-scale models that require over 60M parameters for just 56.5 AP. On the compact side, DEIMv2-S is the first sub-10M model (9.71M) to exceed the 50 AP milestone on COCO, reaching 50.9 AP. Even the ultra-lightweight DEIMv2-Pico, with just 1.5M parameters, delivers 38.5 AP-matching YOLOv10-Nano (2.3M) with ~50% fewer parameters.* +This model was contributed by [Harshal Janjani](https://huggingface.co/harshaljanjani). +The original code can be found [here](https://github.com/Intellindust-AI-Lab/DEIMv2). + ## Usage ```python From 49995e1a8c76de9158cf4f4e4995ac7454b8f141 Mon Sep 17 00:00:00 2001 From: "sergereview[bot]" <283583894+sergereview[bot]@users.noreply.github.com> Date: Tue, 1 Sep 2026 12:31:17 +0000 Subject: [PATCH 014/996] [serge] Fix 2 integration tests for model `cwm` failing with `import_or_config` (other (2)) (#48414) * [serge] Fix 2 integration tests for model `cwm` failing with `import_or_config` (other (2)) * Use CwmAttention.layer_type instead of adding attention_type to the layer --------- Co-authored-by: serge[bot] Co-authored-by: Tarek Ziade --- tests/models/cwm/test_modeling_cwm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/models/cwm/test_modeling_cwm.py b/tests/models/cwm/test_modeling_cwm.py index b201defea986..4a54764e00ef 100644 --- a/tests/models/cwm/test_modeling_cwm.py +++ b/tests/models/cwm/test_modeling_cwm.py @@ -109,7 +109,7 @@ def test_cwm_integration(self): for i, layer in enumerate(model.model.layers): expected_type = model.config.layer_types[i] - self.assertEqual(layer.attention_type, expected_type) + self.assertEqual(layer.self_attn.layer_type, expected_type) if expected_type == "sliding_attention": self.assertEqual(layer.self_attn.sliding_window, model.config.sliding_window) From 4c0dafa1e4a51fdd0a7f38110410b5942d25df82 Mon Sep 17 00:00:00 2001 From: "Ma, Guokai" Date: Tue, 1 Sep 2026 12:44:17 +0000 Subject: [PATCH 015/996] Batch Rebalance Data Sampler (#47340) * Add BatchRebalanceSampler for cost-balanced distributed training New sampler that balances sequence length cost across DP ranks while minimizing padding waste. Uses Poorman's Batch Rebalance algorithm with configurable cost model. Changes: - trainer_pt_utils.py: Add BatchRebalanceSampler class - training_args.py: Add 'batch_rebalance' to train_sampling_strategy choices, batch_rebalance_alpha and batch_rebalance_max_tokens params - trainer.py: Add batch_rebalance branch in _get_train_sampler Usage: TrainingArguments(train_sampling_strategy='batch_rebalance', batch_rebalance_alpha=0.001) * Add unit tests for BatchRebalanceSampler Tests cover: - Basic correctness (coverage, micro-batch count) - No overlap between ranks within same global batch - Effective batch size invariant - max_tokens constraint enforcement - Determinism (same seed = same result) - Custom cost_fn override * Fix: remove invalid super().__init__ call in BatchRebalanceSampler PyTorch's Sampler base class doesn't accept data_source kwarg. Drop the super().__init__() call entirely (consistent with other HF samplers like LengthGroupedSampler). * Remove unused micro_batch_size param, fix silent data loss in max_tokens rebalance - Remove micro_batch_size from BatchRebalanceSampler: it was stored but never read anywhere in the class, and its name was misleading since it did not reflect the actual minimum per-group size used by the algorithm. - Fix a bug in _poormans_rebalance where counts[gi] -= 1 was applied unconditionally before searching for a donor group, causing samples to be silently dropped when max_tokens could not be satisfied and no group had spare capacity. Now the decrement only happens once a donor is found, and a warning is logged (with a fallback to exceed max_tokens rather than drop samples) when no donor is available. - Fix docstring typo (Poorman's -> Poor Man's). - Update/add tests: drop micro_batch_size from existing tests, add a regression test for the max_tokens data-loss fix, and rewrite the cost_fn test to directly assert on _cost() output instead of an unstable partition overlap comparison. * Fix batch_rebalance sampling strategy: missing import and DataLoader wiring BatchRebalanceSampler yields a full batch of sample indices per iteration (BatchSampler semantics), but _get_dataloader() was passing it via DataLoader's sampler= kwarg together with batch_size=, which expects the sampler to yield one sample index at a time. This caused 'TypeError: list indices must be integers or slices, not list' as soon as train_sampling_strategy="batch_rebalance" was used with the Trainer. Also fixes a NameError (BatchEncoding was referenced in _get_train_sampler but never imported), which was the first failure hit before reaching the DataLoader wiring bug. Together these two bugs meant the batch_rebalance strategy could never actually run end-to-end through Trainer.train(); verified with a CPU multi-process (torchrun --nproc_per_node=4) benchmark on Qwen2.5-0.5B with a synthetic variable-length dataset after the fix. * Remove unused variable flagged by ruff F841 * Fix import sort order for BatchRebalanceSampler (ruff I001) * Apply ruff format to changed files * Replace dead count-adjustment code with explicit ValueError When n < K * min_per_group, there are not enough samples to fill all groups. Previously this was silently patched by trimming counts (and a dead 'total < n' branch that could never trigger). Now it raises a clear error telling the user to reduce effective_batch_size or increase dataset size. * Fix can_transfer accuracy and iterate all lo_candidates in rebalance - Replace can_increase(cts, gi) with can_transfer(cts, from_idx, to_idx) which simulates the actual -1/+1 transfer to compute the correct start index and max_len for the token limit check. The previous implementation used stale positions that didn't account for shifts caused by the donor group shrinking. - When the lowest-cost group cannot accept a transfer due to max_tokens, iterate through remaining candidates by ascending cost instead of falling through to the nail-house branch or breaking entirely. * Scale BatchRebalanceSampler iteration budget with effective batch size Each iteration of the rebalance loop moves exactly one sample between groups, so worst-case convergence is O(n). The fixed `K * 30` cap could therefore truncate before convergence for large `effective_batch_size` with a small `dp_size * grad_accum` (K), leaving the partition at a non-optimal cost spread. Use `max(K * 30, effective_batch_size)` as the budget: the `effective_batch_size` term covers the move-dominated regime (large batch, small K), while `K * 30` remains a floor for the detection-dominated regime (tiny batch, n ~= K) where convergence is reached via `spread == 0` / `seen` rather than the move budget. `best_counts` is still tracked, so hitting the cap only degrades the result gracefully (no samples are dropped). Adds a regression test (large n=246, small K=2, heavily skewed lengths) that asserts full sample coverage across all ranks and convergence to the brute-force-optimal contiguous K=2 cost spread. * Fix BatchRebalanceSampler correctness issues in Trainer integration Three review fixes for PR #47340: defeat double-sharding by neutralizing accelerate's BatchSamplerShard wrapper after prepare; fix effective_batch_size undercount (train_batch_size // world_size undercounts since train_batch_size excludes world_size in DDP); honor drop_last=False by yielding the padded trailing partial batch and passing dataloader_drop_last from the Trainer. Adds regression tests for all three. * Fix UnboundLocalError on `sampler` for iterable datasets in Trainer._get_dataloader `sampler` was only assigned inside the non-IterableDataset branch, but the post-`accelerator.prepare` check referenced it unconditionally. Initialize `sampler` to None so IterableDataset runs no longer raise. * Address sywangyi review: effective_batch_size DP fix, bounded tail padding, DDP integration test - trainer.py: effective_batch_size = train_batch_size * grad_accum * world_size (was per_device_train_batch_size * ...), so the DP (single-process, multi-GPU) case no longer drops the n_gpu factor. Covers both DDP and DP. - trainer_pt_utils.py: when drop_last=False and the remainder < dp_size*grad_accum, pad the tail up to K (dp_size*grad_accum) instead of the full effective_batch_size, avoiding heavy over-weighting of replayed samples in the final optimizer step. - test_trainer_data.py: extend effective_batch_size regression test to cover both DDP and DP; assert tail padding yields eff_bs + K (not eff_bs + eff_bs). - Add real DDP integration test (batch_rebalance_ddp.py + test_batch_rebalance_no_double_sharding) that exercises Trainer.get_train_dataloader -> accelerator.prepare -> patch path end-to-end under accelerate launch, verifying the structure-dependent wrapper detection and exact global sample coverage (no double-sharding drops). * Print summary line in batch_rebalance_ddp worker script execute_subprocess_async (the distributed test harness) treats a subprocess that produces no stdout/stderr as a failure. When launched with a full --config_file the script was silent on success, so the test raised 'produced no output'. Emit a one-line summary on the main process. * Trim redundant rationale from effective_batch_size comment * Apply ruff format to test_trainer_distributed_ddp * Pad tail by wrapping order when dataset is smaller than K order[:pad] returns at most len(order) elements, so for len(dataset) < K the tail underfills and _poormans_rebalance(..., min_per_group=1) raises ValueError. Repeat the order (math.ceil) to yield exactly pad padding indices. Adds an n=1, K=8 regression test. * Address comments Signed-off-by: Guokai Ma * Remove batch_rebalance_alpha and batch_rebalance_max_tokens args Per review: no ablation was run on these knobs and there is no user demand, so they do not belong in the public API. The quadratic cost weight is fixed at 0.001 (previous default) as an internal class constant; intercept and cost_fn were unused and are deleted along with the max_tokens machinery (feasibility repair loop, can_transfer, _padded_tokens, _within_token_limit). Output is bit-identical to the previous defaults, verified against the pre-change implementation over 30 randomized inputs. Signed-off-by: Guokai Ma * Simplify BatchRebalanceSampler for readability Per review: document and restructure the sampler internals. - _assign: explain the snake deal (groups ranked by cost, slot k takes ranks [k*dp_size, (k+1)*dp_size) so every slot has the same cost profile). - __iter__: deduplicate the full-batch loop and drop_last=False tail block into a single loop over global batches plus a _yield_global_batch helper. - _poormans_rebalance -> _balance_groups: drop the three redundant kwargs (derivable from self), document the hill-climbing search, and extract the freeze fallback into _slot_groups (pure: which groups share the capped group's slot) and _relieve_and_freeze (top up the slot from outside groups, then freeze it). Output verified bit-identical to the previous implementation over 286 randomized inputs, including adversarial freeze-prone configurations. Signed-off-by: Guokai Ma * Consolidate batch_rebalance tests and extend the DDP e2e to two epochs Per review: keep it to a few unit tests and focus on the DDP integration test. - Merge basic/no_overlap/eff_batch_size/deterministic into one basic test asserting coverage, no cross-rank overlap, exact per-global-batch counts and seed determinism (original hand-picked lengths kept). - Merge the four drop_last tests into one test covering: tail dropped with drop_last=True, tail yielded as-is otherwise, padding up to K (not effective_batch_size) when the remainder is smaller, and order wrap-around when the whole dataset is smaller than K. - Drop test_batch_rebalance_defeats_double_sharding: it simulated accelerate's BatchSamplerShard by hand; the real path is covered by the DDP e2e test. - Extend the DDP e2e worker to actually train for two epochs and assert the per-epoch invariants end to end: each epoch covers all samples across ranks, set_epoch reaches the wrapped sampler (inner_epoch advances) and later epochs reshuffle. Validated on 2x RTX 5090. Every assertion from the removed tests maps into the consolidated ones. Signed-off-by: Guokai Ma * Reuse train.py for the batch_rebalance DDP test Drop the bespoke batch_rebalance_ddp.py worker script and its white-box assertions in favour of the shared train.py, so the sampler is exercised against a real model end to end. train.py gains a --padding option because the default max_length padding makes every sample the same length, which leaves the rebalancing with nothing to do. * [docs] Add batch_rebalance sampling strategy to the training guide * [docs] Move batch_rebalance sampling guide to trainer_recipes Move the batch_rebalance sampling strategy docs from training.md to a dedicated section in trainer_recipes.md, next to Dataloader performance, following review feedback. The new section explains the two imbalances it addresses (padding within a micro-batch and idle time across devices), how the sampler works (sort then shard), the average per_device_train_batch_size semantics, and how to skip the startup length scan with precomputed lengths. --------- Signed-off-by: Guokai Ma Co-authored-by: Marc Sun <57196510+SunMarc@users.noreply.github.com> --- docs/source/en/trainer_recipes.md | 31 ++ src/transformers/trainer.py | 74 +++- src/transformers/trainer_pt_utils.py | 319 ++++++++++++++++++ src/transformers/training_args.py | 14 +- tests/trainer/distributed/scripts/train.py | 13 +- .../test_trainer_distributed_ddp.py | 22 ++ tests/trainer/test_trainer_data.py | 271 +++++++++++++++ 7 files changed, 730 insertions(+), 14 deletions(-) diff --git a/docs/source/en/trainer_recipes.md b/docs/source/en/trainer_recipes.md index 646320d66e13..db40ee691a72 100644 --- a/docs/source/en/trainer_recipes.md +++ b/docs/source/en/trainer_recipes.md @@ -157,6 +157,37 @@ args = TrainingArguments( ) ``` +## Batch rebalance sampling + +On variable-length datasets, imbalance within a micro-batch and across devices causes devices to waste time on padding and to idle at gradient synchronization steps. + +Set `train_sampling_strategy="batch_rebalance"` in [`TrainingArguments`] to reduce both effects. For each optimizer step, the sampler: + +1. Sorts the batch's samples by length. +2. Shards the sorted batch across devices so that the padded-token cost of each micro-batch is balanced. Micro-batches with long samples get fewer samples, and micro-batches with short samples get more. + +This reduces padding within each micro-batch, and each device finishes a micro-batch at roughly the same time, which reduces idle time at synchronization and keeps peak memory lower than `"group_by_length"`. This strategy is only supported for data-parallel training for now (tensor parallelism is not yet supported). + +```py +from transformers import Trainer, TrainingArguments + +trainer = Trainer( + model=model, + args=TrainingArguments( + output_dir="out", + train_sampling_strategy="batch_rebalance", # balance padding cost across devices + per_device_train_batch_size=8, # average samples per micro-batch + length_column_name="length", # optional: dataset column with precomputed lengths + ), + train_dataset=train_dataset, +) +trainer.train() +``` + +`per_device_train_batch_size` is an average here rather than an exact per-step count: some micro-batches have fewer samples and some have more, but the total number of samples trained per step stays the same as with a normal distributed sampling strategy. + +The sampler needs the length of every sample to sort and balance batches. By default, the [`Trainer`] scans the full dataset once at the start of training to compute these lengths. To skip this scan, precompute the lengths into a dataset column (during preprocessing, for example) and pass its name as `length_column_name` (`"length"` by default). + ## NEFTune [NEFTune](https://hf.co/papers/2310.05914) adds random noise to token embeddings during the forward pass. The noise acts as regularization and can improve performance for instruction fine-tuning. diff --git a/src/transformers/trainer.py b/src/transformers/trainer.py index 1a37e49911c8..7a5005146858 100755 --- a/src/transformers/trainer.py +++ b/src/transformers/trainer.py @@ -81,7 +81,7 @@ from .optimization import GreedyLR, get_scheduler from .processing_utils import ProcessorMixin from .pytorch_utils import is_torch_greater_or_equal_than_2_6 -from .tokenization_utils_base import PreTrainedTokenizerBase +from .tokenization_utils_base import BatchEncoding, PreTrainedTokenizerBase from .trainer_callback import ( CallbackHandler, DefaultFlowCallback, @@ -99,6 +99,7 @@ is_optimizer_factory, ) from .trainer_pt_utils import ( + BatchRebalanceSampler, EvalLoopContainer, IterableDatasetShard, LabelSmoother, @@ -999,10 +1000,17 @@ def _get_dataloader( if is_torch_greater_or_equal_than_2_6: dataloader_params["in_order"] = self.args.dataloader_in_order + sampler = None if not isinstance(dataset, torch.utils.data.IterableDataset): - if sampler_fn is not None: - dataloader_params["sampler"] = sampler_fn(dataset) - dataloader_params["drop_last"] = self.args.dataloader_drop_last + sampler = sampler_fn(dataset) if sampler_fn is not None else None + if isinstance(sampler, BatchRebalanceSampler): + # Pass as `batch_sampler`; it is mutually exclusive with `batch_size`/`sampler`/`drop_last`. + dataloader_params.pop("batch_size", None) + dataloader_params["batch_sampler"] = sampler + else: + if sampler is not None: + dataloader_params["sampler"] = sampler + dataloader_params["drop_last"] = self.args.dataloader_drop_last if is_training: dataloader_params["worker_init_fn"] = partial( seed_worker, num_workers=self.args.dataloader_num_workers, rank=self.args.process_index @@ -1010,6 +1018,15 @@ def _get_dataloader( dataloader = self.accelerator.prepare(DataLoader(dataset, **dataloader_params)) + # `BatchRebalanceSampler` is already rank-aware, so the `BatchSamplerShard` wrapper + # added by `accelerator.prepare` would re-shard it and silently drop samples. Neutralise + # it by making the wrapper a passthrough (num_processes=1) + if isinstance(sampler, BatchRebalanceSampler): + prepared_bs = getattr(dataloader, "batch_sampler", None) + if prepared_bs is not None and getattr(prepared_bs, "batch_sampler", None) is sampler: + prepared_bs.num_processes = 1 + prepared_bs.process_index = 0 + # Store the prepared dataloader for subsequent evaluations if using persistent workers. if dataloader_key is not None and self.args.dataloader_persistent_workers: if hasattr(self, "_eval_dataloaders"): @@ -1024,9 +1041,12 @@ def _get_train_sampler(self, train_dataset: Dataset | None = None) -> torch.util if train_dataset is None: train_dataset = self.train_dataset if train_dataset is None or not has_length(train_dataset): - if train_dataset is not None and self.args.train_sampling_strategy == "group_by_length": + if train_dataset is not None and self.args.train_sampling_strategy in ( + "group_by_length", + "batch_rebalance", + ): logger.warning( - "`train_sampling_strategy='group_by_length'` is ignored because the training dataset does not " + f"`train_sampling_strategy='{self.args.train_sampling_strategy}'` is ignored because the training dataset does not " "implement `__len__` (e.g. an `IterableDataset`). Examples will be consumed in the dataset's own " "order." ) @@ -1051,6 +1071,42 @@ def _get_train_sampler(self, train_dataset: Dataset | None = None) -> torch.util lengths=lengths, model_input_name=model_input_name, ) + elif self.args.train_sampling_strategy == "batch_rebalance": + if is_datasets_available() and isinstance(train_dataset, datasets.Dataset): + lengths = ( + train_dataset[self.args.length_column_name] + if self.args.length_column_name in train_dataset.column_names + else None + ) + else: + lengths = None + model_input_name = ( + self.processing_class.model_input_names[0] if self.processing_class is not None else None + ) + if lengths is None: + model_input_name = model_input_name if model_input_name is not None else "input_ids" + if not isinstance(train_dataset[0], (dict, BatchEncoding)) or model_input_name not in train_dataset[0]: + raise ValueError( + "Can only automatically infer lengths for datasets whose items are dictionaries with an " + f"'{model_input_name}' key." + ) + lengths = [len(feature[model_input_name]) for feature in train_dataset] + elif isinstance(lengths, torch.Tensor): + lengths = lengths.tolist() + + world_size = max(1, self.args.world_size) + rank = self.args.process_index if self.args.world_size > 1 else 0 + grad_accum = self.args.gradient_accumulation_steps + effective_batch_size = self.args.train_batch_size * grad_accum * world_size + + return BatchRebalanceSampler( + lengths=lengths, + effective_batch_size=effective_batch_size, + dp_size=world_size, + grad_accum=grad_accum, + rank=rank, + drop_last=self.args.dataloader_drop_last, + ) elif self.args.train_sampling_strategy == "sequential": return SequentialSampler(train_dataset) else: @@ -1728,6 +1784,12 @@ def _run_epoch( if hasattr(train_dataloader, "set_epoch"): train_dataloader.set_epoch(epoch) + # `DataLoaderShard.set_epoch` (accelerate) does not forward to a batch sampler wrapped + # in `BatchSamplerShard`, so reach it explicitly. + shard_wrapper = getattr(train_dataloader, "batch_sampler", None) + underlying_sampler = getattr(shard_wrapper, "batch_sampler", None) + if hasattr(underlying_sampler, "set_epoch"): + underlying_sampler.set_epoch(epoch) epoch_iterator = iter(train_dataloader) # We chunkify the epoch iterator into gradient accumulation steps `n` batches diff --git a/src/transformers/trainer_pt_utils.py b/src/transformers/trainer_pt_utils.py index a25dce79ba5b..0eb2e789385f 100644 --- a/src/transformers/trainer_pt_utils.py +++ b/src/transformers/trainer_pt_utils.py @@ -645,6 +645,325 @@ def __iter__(self) -> Iterator: return iter(indices) +class BatchRebalanceSampler(Sampler): + r""" + Sampler that balances sequence length cost across DP ranks while minimizing padding waste within each + micro-batch. Designed for distributed training with variable-length sequences (e.g., LLM fine-tuning). + + Uses a cost-aware rebalance algorithm ("Poor Man's Batch Rebalance") that: + 1. For each optimizer step, collects `effective_batch_size` samples (shuffled, same set on all ranks + via shared seed — no cross-rank communication needed). + 2. Sorts samples by length descending. + 3. Partitions into `dp_size * grad_accum` groups using an iterative cost-balancing algorithm that + adjusts group sizes (not sample assignments) until costs converge. + 4. Sorts groups by cost descending and assigns the top `dp_size` groups to the first micro-batch + (slot 0), the next `dp_size` to slot 1, etc. This ensures each micro-batch slot has balanced + cost across ranks. + 5. Each rank yields its `grad_accum` micro-batches (one from each slot). + + Cost model (fixed; captures padding waste plus attention's quadratic cost): + + cost(bs, max_len) = bs * max_len + QUADRATIC_COST_COEF * bs * max_len^2 + + where `bs` is the number of samples in the micro-batch and `max_len` is the length of the longest + sample (all samples are padded to this length). The linear term captures linear-layer compute and + padding waste; the quadratic term captures attention's O(L^2) cost. + + Key properties: + - **Variable batch size**: long-sequence groups get fewer samples, short-sequence groups get + more, keeping per-group cost balanced. + - **Fixed effective batch size**: total samples per optimizer step is always + `effective_batch_size`. + - **Zero communication**: all ranks run the same deterministic algorithm and yield only their + portion — no all-gather or broadcast needed. + - **Padding-aware**: the cost model explicitly accounts for padding waste, unlike + `LengthGroupedSampler` which only sorts by length. + + Args: + lengths (`list[int]`): + Token lengths of all samples in the dataset. + effective_batch_size (`int`): + Total samples per optimizer step (`dp_size * grad_accum * per-group batch size`). + dp_size (`int`): + Data parallel size (number of ranks). + grad_accum (`int`): + Gradient accumulation steps. + shuffle (`bool`, *optional*, defaults to `True`): + Whether to shuffle samples each epoch. + seed (`int`, *optional*, defaults to 42): + Random seed for shuffling. + rank (`int`, *optional*, defaults to 0): + Current rank index. + drop_last (`bool`, *optional*, defaults to `True`): + Drop incomplete last batch. + + Example: + + ```python + >>> from transformers.trainer_pt_utils import BatchRebalanceSampler + >>> sampler = BatchRebalanceSampler( + ... lengths=[100, 200, 300, ...], + ... effective_batch_size=16, + ... dp_size=4, + ... grad_accum=2, + ... rank=0, + ... ) + >>> for batch_indices in sampler: + ... # batch_indices is a list of sample indices for this rank's micro-batch + ... pass + ``` + """ + + # Weight of the attention's O(L^2) term in the cost model. + QUADRATIC_COST_COEF = 0.001 + + def __init__( + self, + lengths: list[int], + effective_batch_size: int, + dp_size: int, + grad_accum: int, + shuffle: bool = True, + seed: int = 42, + rank: int = 0, + drop_last: bool = True, + ): + assert dp_size >= 1 + assert grad_accum >= 1 + assert effective_batch_size >= dp_size * grad_accum + + self.lengths = list(lengths) + self.effective_batch_size = effective_batch_size + self.dp_size = dp_size + self.grad_accum = grad_accum + self.shuffle = shuffle + self.seed = seed + self.rank = rank + self.drop_last = drop_last + self.epoch = 0 + + self.num_full_batches = len(self.lengths) // effective_batch_size + self.remainder = len(self.lengths) % effective_batch_size + # When drop_last=False, the trailing partial batch is also yielded (padded up to the + # effective batch size when too small to fill every (rank, slot) group), mirroring how + # PyTorch's DistributedSampler pads the tail. Otherwise trailing samples are silently + # dropped even though the user asked to keep them. + self.has_tail = (not drop_last) and self.remainder > 0 + self.num_global_batches = self.num_full_batches + (1 if self.has_tail else 0) + + def set_epoch(self, epoch: int): + self.epoch = epoch + + def __iter__(self): + g = torch.Generator() + g.manual_seed(self.seed + self.epoch) + n = len(self.lengths) + + if self.shuffle: + order = torch.randperm(n, generator=g).tolist() + else: + order = list(range(n)) + + for gb in range(self.num_global_batches): + batch_indices = order[gb * self.effective_batch_size : (gb + 1) * self.effective_batch_size] + # The trailing partial batch (drop_last=False) may be smaller than the number of + # (rank, slot) groups (K = dp_size * grad_accum); pad it by repeating samples from + # the start of the epoch order (same strategy as torch.utils.data.DistributedSampler) + # so every group still has >= 1 sample and the all-reduce stays consistent. + if ( + self.has_tail + and gb == self.num_global_batches - 1 + and len(batch_indices) < self.dp_size * self.grad_accum + ): + pad = self.dp_size * self.grad_accum - len(batch_indices) + # Wrap `order` enough times to fill `pad` indices (handles len(order) < pad). + padding = (order * math.ceil(pad / len(order)))[:pad] + batch_indices = batch_indices + padding + yield from self._yield_global_batch(batch_indices) + + def _yield_global_batch(self, batch_indices): + batch_lengths = [self.lengths[i] for i in batch_indices] + rank_mbs = self._assign(batch_indices, batch_lengths) + for ga in range(self.grad_accum): + yield rank_mbs[self.rank][ga] + + def __len__(self): + return self.num_global_batches * self.grad_accum + + def _cost(self, bs: int, max_len: int) -> float: + return bs * max_len + self.QUADRATIC_COST_COEF * bs * max_len * max_len + + def _assign(self, indices, lengths): + # Snake assignment: after balancing, sort the K groups by cost descending and deal them + # round-wise — slot k receives groups ranked [k*dp_size, (k+1)*dp_size). The highest-cost + # groups land in slot 0, the next-highest in slot 1, etc., so every slot has the same + # cost profile across ranks (each rank's slot-k micro-batches cost roughly the same) and + # the totals even out across grad-accumulation steps. + sorted_pairs = sorted(zip(indices, lengths), key=lambda x: x[1], reverse=True) + + all_groups = self._balance_groups(sorted_pairs) + + group_costs = [(i, self._group_cost(g)) for i, g in enumerate(all_groups)] + group_costs.sort(key=lambda x: x[1], reverse=True) + + rank_mbs = [[[] for _ in range(self.grad_accum)] for _ in range(self.dp_size)] + + for slot_idx in range(self.grad_accum): + slot_start = slot_idx * self.dp_size + for r in range(self.dp_size): + g_idx = group_costs[slot_start + r][0] + rank_mbs[r][slot_idx] = [idx for idx, _ in all_groups[g_idx]] + + return rank_mbs + + def _balance_groups(self, sorted_pairs): + """ + Split `sorted_pairs` (sorted by length descending) into `K = dp_size * grad_accum` + contiguous groups with near-equal cost, by iterative hill climbing: each step moves one + sample from the most expensive group to the cheapest one that can receive it. + + The search stops at a local optimum: `seen` detects cycles (no improving move left), + and `best_counts` snapshots the lowest-spread state seen along the way so exhausting + the iteration budget only degrades the result gracefully (no samples are dropped). + + When the most expensive group is already at `min_per_group` samples it can no longer + give samples away, so spread cannot shrink further through it: its whole slot is + frozen (see `_relieve_and_freeze`) and the search continues on the remaining groups. + """ + n = len(sorted_pairs) + K = self.dp_size * self.grad_accum + min_per_group = 1 + + base = n // K + remainder = n % K + if n < K * min_per_group: + raise ValueError( + f"Not enough samples ({n}) to fill {K} groups with at least {min_per_group} sample(s) each. " + f"Reduce effective_batch_size or increase the dataset size." + ) + counts = [base + (1 if i < remainder else 0) for i in range(K)] + + def compute_groups_costs(cts): + # Materialize contiguous groups from per-group counts and price each one. + groups = [] + idx = 0 + for c in cts: + groups.append(sorted_pairs[idx : idx + c]) + idx += c + costs = [self._group_cost(g) for g in groups] + return groups, costs + + frozen = set() + seen = set() + best_spread = float("inf") + best_counts = list(counts) + + # Each iteration moves exactly one sample between groups, so worst-case + # convergence is O(n). `effective_batch_size` (= n) covers the move-dominated + # regime (large batch, small K) that a fixed `K * 30` cap could cut off + # prematurely; `K * 30` stays as a floor for the detection-dominated regime + # (tiny batch, n ~= K) where convergence is reached via `spread == 0` / `seen` + # rather than the move budget. `best_counts` is tracked below, so hitting the + # cap only degrades the result gracefully (no samples are dropped). + for _ in range(max(K * 30, self.effective_batch_size)): + key = tuple(counts) + if key in seen: + break + seen.add(key) + + groups, costs = compute_groups_costs(counts) + + active = [i for i in range(K) if i not in frozen] + if len(active) <= 1: + break + + active_costs = [costs[i] for i in active] + spread = max(active_costs) - min(active_costs) + if spread < best_spread: + best_spread = spread + best_counts = list(counts) + + hi_idx = max(active, key=lambda i: costs[i]) + + if costs[hi_idx] == costs[min(active, key=lambda i: costs[i])]: + break + + lo_candidates = sorted(active, key=lambda i: costs[i]) + transferred = False + for lo_idx in lo_candidates: + if lo_idx == hi_idx or costs[lo_idx] == costs[hi_idx]: + continue + if counts[hi_idx] > min_per_group: + counts[hi_idx] -= 1 + counts[lo_idx] += 1 + transferred = True + break + if not transferred: + if counts[hi_idx] <= min_per_group: + cap_cost = costs[hi_idx] + slot_members = self._slot_groups(costs, hi_idx) + self._relieve_and_freeze(counts, slot_members, hi_idx, frozen, sorted_pairs, cap_cost) + else: + break + + groups, _ = compute_groups_costs(best_counts) + return groups + + def _slot_groups(self, costs, pivot_idx): + """Return the groups that share `pivot_idx`'s slot.""" + K = len(costs) + dp_size = self.dp_size + cost_ranking = sorted(range(K), key=lambda i: costs[i], reverse=True) + pivot_rank = cost_ranking.index(pivot_idx) + slot_num = pivot_rank // dp_size + slot_start = slot_num * dp_size + slot_end = min(slot_start + dp_size, K) + return set(cost_ranking[slot_start:slot_end]) + + def _relieve_and_freeze(self, counts, slot_members, pivot_idx, frozen, sorted_pairs, cap_cost): + """Freeze `slot_members` and exclude them from further balancing. + + Called when the slot's most expensive group (`pivot_idx`) is down to `min_per_group` + samples and can no longer give samples away, so its cost cannot shrink anymore. + Before freezing, top up the slot's other groups from cheaper outside groups, never + letting a receiver's cost exceed `cap_cost` (the slot's peak). This moves samples + out of the outside groups, which helps balance the ones still active.""" + K = len(counts) + for gi in slot_members: + if gi in frozen or gi == pivot_idx: + continue + while True: + _, costs_now = self._groups_costs_from(counts, sorted_pairs) + idx_start = sum(counts[:gi]) + gi_max_len = sorted_pairs[idx_start][1] if counts[gi] > 0 else 0 + projected = self._cost(counts[gi] + 1, gi_max_len) + if projected > cap_cost: + break + donors = [i for i in range(K) if i not in frozen and i not in slot_members and counts[i] > 1] + if not donors: + break + donor = min(donors, key=lambda i: costs_now[i]) + counts[gi] += 1 + counts[donor] -= 1 + frozen.update(slot_members) + + def _groups_costs_from(self, counts, sorted_pairs): + groups = [] + idx = 0 + for c in counts: + groups.append(sorted_pairs[idx : idx + c]) + idx += c + costs = [self._group_cost(g) for g in groups] + return groups, costs + + def _group_cost(self, group): + if not group: + return 0.0 + max_len = group[0][1] + bs = len(group) + return self._cost(bs, max_len) + + class ShardSampler(Sampler): """ Sampler that shards batches between several processes. Dispatches indices batch by batch: on 2 processes with batch diff --git a/src/transformers/training_args.py b/src/transformers/training_args.py index b2cac7970e40..6cc527d59205 100644 --- a/src/transformers/training_args.py +++ b/src/transformers/training_args.py @@ -637,12 +637,16 @@ class TrainingArguments: - `"sequential"`: Uses `SequentialSampler`. - `"group_by_length"`: Uses `LengthGroupedSampler` to group samples of roughly the same length together (to minimize padding and be more efficient). + - `"batch_rebalance"`: Uses `BatchRebalanceSampler` to balance padded-token cost across devices + and gradient-accumulation steps within each effective batch, reducing padding waste and peak + memory vs `"group_by_length"`. Currently only supported for data-parallel training + (tensor parallelism is not yet supported). Note: When using an `IterableDataset`, this argument is ignored. length_column_name (`str`, *optional*, defaults to `"length"`): Column name for precomputed lengths. If the column exists, grouping by length will use these values rather - than computing them on train startup. Ignored unless `train_sampling_strategy` is `"group_by_length"` and the dataset - is an instance of `Dataset`. + than computing them on train startup. Ignored unless `train_sampling_strategy` is `"group_by_length"`or + `"batch_rebalance"` and the dataset is an instance of `Dataset`. > DDP (DistributedDataParallel) @@ -1358,14 +1362,14 @@ class TrainingArguments: train_sampling_strategy: str = field( default="random", metadata={ - "help": "Sampler for training: 'random' (default), 'sequential', or 'group_by_length'.", - "choices": ["random", "sequential", "group_by_length"], + "help": "Sampler for training: 'random' (default), 'sequential', 'group_by_length', or 'batch_rebalance'.", + "choices": ["random", "sequential", "group_by_length", "batch_rebalance"], }, ) length_column_name: str = field( default="length", metadata={ - "help": "Column name for precomputed lengths. Ignored unless `train_sampling_strategy` is 'group_by_length'." + "help": "Column name for precomputed lengths. Ignored unless `train_sampling_strategy` is 'group_by_length' or 'batch_rebalance'." }, ) diff --git a/tests/trainer/distributed/scripts/train.py b/tests/trainer/distributed/scripts/train.py index fb7b940e64a1..8ae7c379fcf3 100644 --- a/tests/trainer/distributed/scripts/train.py +++ b/tests/trainer/distributed/scripts/train.py @@ -20,7 +20,7 @@ Supports --do_train (default) and --do_eval via TrainingArguments. 32 training samples are created; with per_device_train_batch_size=4 -and 2 GPUs this gives 4 steps per epoch. +and 2 GPUs this gives 4 steps per epoch. Pass --padding do_not_pad for variable-length data. """ import json @@ -39,6 +39,7 @@ DTYPE_MAP = {"fp32": torch.float32, "bf16": torch.bfloat16, "fp16": torch.float16} +PADDING_CHOICES = ("max_length", "do_not_pad") def _pop_custom_arg(name): @@ -60,6 +61,11 @@ def main(): model_dtype = _pop_custom_arg("--model_dtype") attn_impl = _pop_custom_arg("--attn_implementation") pad_to_multiple_of = _pop_custom_arg("--pad_to_multiple_of") + # "max_length" (default) pads samples to max_length; "do_not_pad" gives variable-length + # training data. + padding = _pop_custom_arg("--padding") or "max_length" + if padding not in PADDING_CHOICES: + raise ValueError(f"--padding must be one of {PADDING_CHOICES}, got {padding!r}") parser = HfArgumentParser((TrainingArguments,)) (training_args,) = parser.parse_args_into_dataclasses() @@ -88,6 +94,7 @@ def main(): # Synthetic dataset — 32 samples of tokenized text # With per_device_train_batch_size=4 and 2 GPUs this gives 4 steps per epoch. + # The four texts tokenize to 51, 61, 61 and 81 tokens. texts = [ "The quick brown fox jumps over the lazy dog. " * 5, "A journey of a thousand miles begins with a single step. " * 5, @@ -98,9 +105,9 @@ def main(): train_dataset = None eval_dataset = None if training_args.do_train: - train_dataset = [tokenizer(text, max_length=128, truncation=True, padding="max_length") for text in texts] + train_dataset = [tokenizer(text, max_length=128, truncation=True, padding=padding) for text in texts] if training_args.do_eval: - eval_dataset = [tokenizer(text, max_length=128, truncation=True, padding="max_length") for text in texts[:8]] + eval_dataset = [tokenizer(text, max_length=128, truncation=True, padding=padding) for text in texts[:8]] collator_kwargs = {} if pad_to_multiple_of: diff --git a/tests/trainer/distributed/test_trainer_distributed_ddp.py b/tests/trainer/distributed/test_trainer_distributed_ddp.py index cf6ba839fee4..ee3f5f58e93c 100644 --- a/tests/trainer/distributed/test_trainer_distributed_ddp.py +++ b/tests/trainer/distributed/test_trainer_distributed_ddp.py @@ -298,3 +298,25 @@ def test_training_and_can_resume_normally(self): def test_eval(self): self.check_eval(config_file=DDP_CONFIG_FILE) + + @parameterized.expand([("no_accum", 1), ("with_accum", 2)]) + def test_training_with_batch_rebalance_sampler(self, _name, gradient_accumulation_steps): + """Training runs end to end under DDP with ``train_sampling_strategy="batch_rebalance"``. + + ``--padding do_not_pad`` gives the variable-length data the sampler rebalances. + """ + output_dir = self.get_auto_remove_tmp_dir() + script = os.path.join(SCRIPTS_DIR, "train.py") + args = self._get_default_script_args(output_dir, num_epochs=2) + [ + "--bf16", + "--padding", + "do_not_pad", + "--train_sampling_strategy", + "batch_rebalance", + "--gradient_accumulation_steps", + str(gradient_accumulation_steps), + ] + execute_subprocess_async( + self.get_accelerate_cmd(script, DDP_CONFIG_FILE, script_args=args), + env=self.get_env(), + ) diff --git a/tests/trainer/test_trainer_data.py b/tests/trainer/test_trainer_data.py index 71036da5ae16..d97f39dbd815 100644 --- a/tests/trainer/test_trainer_data.py +++ b/tests/trainer/test_trainer_data.py @@ -44,6 +44,7 @@ ) from transformers.tokenization_utils_base import BatchEncoding from transformers.trainer_pt_utils import ( + BatchRebalanceSampler, DistributedLengthGroupedSampler, DistributedSamplerWithLoop, EvalLoopContainer, @@ -573,6 +574,276 @@ def test_shard_sampler(self): self.check_shard_sampler(dataset, 4, drop_last=True, num_processes=3) self.check_shard_sampler(dataset, 4, drop_last=False, num_processes=3) + def test_batch_rebalance_basic(self): + """Core invariants: full coverage with no overlap between ranks, exact per-global-batch + sample counts, correct micro-batch count, and determinism for a fixed seed.""" + lengths = [ + 100, + 500, + 200, + 800, + 300, + 1000, + 50, + 600, + 150, + 400, + 250, + 700, + 120, + 900, + 350, + 2000, + 450, + 550, + 80, + 300, + 650, + 750, + 180, + 1200, + ] + dp_size = 2 + grad_accum = 2 + effective_batch_size = 4 # one micro-batch-size sample per (rank, slot) group + + samplers = [ + BatchRebalanceSampler( + lengths=lengths, + effective_batch_size=effective_batch_size, + dp_size=dp_size, + grad_accum=grad_accum, + rank=r, + ) + for r in range(dp_size) + ] + all_batches = [list(s) for s in samplers] + + # Micro-batch count per rank and per-global-batch totals across ranks. + num_global = len(all_batches[0]) // grad_accum + self.assertEqual(len(all_batches[0]), num_global * grad_accum) + all_indices = set() + for gb in range(num_global): + combined = set() + for slot in range(grad_accum): + for r in range(dp_size): + batch = all_batches[r][gb * grad_accum + slot] + self.assertEqual(len(combined & set(batch)), 0, f"Overlap in gb={gb}, slot={slot}") + combined.update(batch) + self.assertEqual(len(combined), effective_batch_size, f"gb={gb}") + all_indices.update(combined) + self.assertEqual(all_indices, set(range(len(lengths)))) + + # Same seed reproduces the same iteration. + again = [ + list( + BatchRebalanceSampler( + lengths=lengths, + effective_batch_size=effective_batch_size, + dp_size=dp_size, + grad_accum=grad_accum, + rank=r, + ) + ) + for r in range(dp_size) + ] + self.assertEqual(all_batches, again) + + def test_batch_rebalance_converges_for_large_effective_batch_size(self): + """ + Regression test for the rebalance iteration budget. + + With a large `effective_batch_size` and a small `dp_size * grad_accum` (K), the old + fixed cap `K * 30` was smaller than the number of single-sample moves needed to + converge, so the loop could hit the ceiling with a non-optimal spread. The budget is + now `max(K * 30, effective_batch_size)`, which is O(n) and matches the worst-case + move count. This test builds a heavily skewed batch (a few very long sequences plus + many short ones) under exactly that regime (large n=246, small K=2) and asserts that: + + 1. Every sample is still covered across all ranks combined (no data loss), and + 2. The rebalanced partition reaches the brute-force-optimal cost spread over all + contiguous K=2 partitions — i.e. the algorithm actually ran to convergence + instead of being truncated at the old `K * 30` cap (which stops at ~63 moves + and never reaches the optimum at counts[0] == 6). + """ + lengths = [100] * 240 + [8000, 6000, 5000, 4000, 3000, 2000] # 246 samples + dp_size = 2 + grad_accum = 1 + effective_batch_size = 246 # K = 2, so the old cap K * 30 = 60 < 246 = n + + # (1) Full coverage across ALL ranks combined — no samples dropped. Each rank only + # yields its own group, so the union over ranks must equal the whole batch. + all_indices = set() + for rank in range(dp_size): + sampler = BatchRebalanceSampler( + lengths=lengths, + effective_batch_size=effective_batch_size, + dp_size=dp_size, + grad_accum=grad_accum, + rank=rank, + ) + for batch in sampler: + all_indices.update(batch) + self.assertEqual(all_indices, set(range(len(lengths)))) + + # (2) Convergence: the produced spread must equal the brute-force optimum over all + # contiguous K=2 partitions. Under the old `K * 30` (=60) cap the loop truncated + # around counts[0] == 63 (spread ~4.5e6); the optimum is counts[0] == 6 (spread + # ~4.06e5), which only the larger budget reaches. + sampler = BatchRebalanceSampler( + lengths=lengths, + effective_batch_size=effective_batch_size, + dp_size=dp_size, + grad_accum=grad_accum, + rank=0, + ) + indices = list(range(effective_batch_size)) + batch_lengths = [lengths[i] for i in indices] + sorted_pairs = sorted(zip(indices, batch_lengths), key=lambda x: x[1], reverse=True) + + rebalanced_groups = sampler._assign(indices, batch_lengths) + # `rank_mbs` is nested as [rank][slot] -> list of sample indices; rebuild each + # micro-batch's cost from its indices -> lengths. + rebalanced_costs = [] + for rank_slots in rebalanced_groups: + for slot_indices in rank_slots: + bs = len(slot_indices) + max_len = max((lengths[i] for i in slot_indices), default=0) + rebalanced_costs.append(sampler._cost(bs, max_len)) + rebalanced_spread = max(rebalanced_costs) - min(rebalanced_costs) + + n = effective_batch_size + optimal_spread = float("inf") + for c in range(1, n): + g0 = sorted_pairs[:c] + g1 = sorted_pairs[c:] + spread = abs(sampler._group_cost(g0) - sampler._group_cost(g1)) + if spread < optimal_spread: + optimal_spread = spread + + self.assertAlmostEqual(rebalanced_spread, optimal_spread, places=6) + + def test_batch_rebalance_drop_last(self): + """Tail handling. With drop_last=True the trailing partial batch is dropped (default). + With drop_last=False it is yielded: a remainder smaller than K (= dp_size * grad_accum) + is padded up to K (not the full effective_batch_size, so duplication stays bounded), and + a dataset smaller than K is wrapped around repeatedly until K indices are available.""" + # drop_last=True: trailing samples beyond the last full batch are dropped. + s = BatchRebalanceSampler( + lengths=list(range(100, 118)), # 18 samples, eff_bs=16 -> remainder 2 + effective_batch_size=16, + dp_size=1, + grad_accum=1, + shuffle=False, + rank=0, + drop_last=True, + ) + covered = {i for batch in s for i in batch} + self.assertEqual(covered, set(range(16))) + self.assertEqual(s.num_global_batches, 1) + + # drop_last=False, remainder >= K: the tail is yielded as-is, nothing dropped. + s = BatchRebalanceSampler( + lengths=list(range(100, 118)), + effective_batch_size=16, + dp_size=1, + grad_accum=1, + shuffle=False, + rank=0, + drop_last=False, + ) + covered = {i for batch in s for i in batch} + self.assertEqual(covered, set(range(18))) + self.assertEqual(s.num_global_batches, 2) + + # drop_last=False, remainder < K: padded up to K, not to effective_batch_size. + # 20 samples, eff_bs=16, dp=4, ga=2 -> K=8, remainder=4 -> tail padded 4->8. + dp_size, grad_accum = 4, 2 + K = dp_size * grad_accum + total_yielded = 0 + covered = set() + for rank in range(dp_size): + s = BatchRebalanceSampler( + lengths=list(range(100, 120)), + effective_batch_size=16, + dp_size=dp_size, + grad_accum=grad_accum, + shuffle=False, + rank=rank, + drop_last=False, + ) + for batch in s: + covered.update(batch) + total_yielded += len(batch) + self.assertTrue(set(range(20)) <= covered) + # full batch (16) + padded tail (K=8) = 24, NOT 16 + eff_bs (16) = 32. + self.assertEqual(total_yielded, 16 + K) + + # drop_last=False, dataset smaller than K: padding wraps the order around. + total_yielded = 0 + micro_batch_sizes = [] + covered = set() + for rank in range(dp_size): + s = BatchRebalanceSampler( + lengths=[100], + effective_batch_size=8, + dp_size=dp_size, + grad_accum=grad_accum, # K = 8 > len(dataset) = 1 + shuffle=False, + rank=rank, + drop_last=False, + ) + for batch in s: + micro_batch_sizes.append(len(batch)) + covered.update(batch) + total_yielded += len(batch) + self.assertEqual(total_yielded, K) + self.assertEqual(len(micro_batch_sizes), dp_size * grad_accum) + self.assertTrue(all(sz >= 1 for sz in micro_batch_sizes)) + self.assertEqual(covered, {0}) + + def test_batch_rebalance_trainer_effective_batch_size_formula(self): + """Regression for the effective_batch_size calculation in Trainer._get_train_sampler. + + The correct formula is `train_batch_size * grad_accum * world_size`, where + `train_batch_size = per_device_train_batch_size * n_gpu` is the per-process batch (it + already excludes world_size). This must cover both distributed cases: + * DDP: world_size > 1, n_gpu == 1 -> train_batch_size == per_device + * DP : world_size == 1, n_gpu > 1 -> train_batch_size == per_device * n_gpu + + Using `per_device_train_batch_size * grad_accum * world_size` (the previous fix) is + correct for DDP but drops the n_gpu factor in the DP case. We simulate both setups by + overriding args.""" + from unittest.mock import MagicMock + + def build(per_device_train_batch_size, n_gpu, world_size, grad_accum=2): + n = 32 + fake_trainer = MagicMock() + fake_trainer.args.train_sampling_strategy = "batch_rebalance" + fake_trainer.args.world_size = world_size + fake_trainer.args.process_index = 0 + fake_trainer.args.per_device_train_batch_size = per_device_train_batch_size + # `train_batch_size` is a property = per_device_train_batch_size * max(1, n_gpu). + fake_trainer.args.train_batch_size = per_device_train_batch_size * max(1, n_gpu) + fake_trainer.args.gradient_accumulation_steps = grad_accum + fake_trainer.args.length_column_name = "length" + fake_trainer.args.dataloader_drop_last = True + fake_trainer.processing_class = None + fake_trainer.train_dataset = [{"input_ids": list(range((i % 5) + 1))} for i in range(n)] + return fake_trainer + + # DDP: 2 processes, 1 GPU each. per_device=4 -> train_batch_size=4. + # expected = train_batch_size(4) * grad_accum(2) * world_size(2) = 16. + sampler = Trainer._get_train_sampler(build(per_device_train_batch_size=4, n_gpu=1, world_size=2)) + self.assertIsInstance(sampler, BatchRebalanceSampler) + self.assertEqual(sampler.effective_batch_size, 16) + + # DP: 1 process, 4 GPUs. per_device=4 -> train_batch_size = 4*4 = 16. + # expected = train_batch_size(16) * grad_accum(2) * world_size(1) = 32. The previous + # formula used per_device directly and returned 8, dropping the n_gpu factor. + sampler = Trainer._get_train_sampler(build(per_device_train_batch_size=4, n_gpu=4, world_size=1)) + self.assertEqual(sampler.effective_batch_size, 32) + # --------------------------------------------------------------------------- # Batch size finder tests From cdfdcad31314fe4f23b40ab374e860a62403f72a Mon Sep 17 00:00:00 2001 From: Raushan Turganbay Date: Tue, 1 Sep 2026 12:52:22 +0000 Subject: [PATCH 016/996] No inherit decorator for NeoMME (#48457) fix --- src/transformers/models/neomme/modeling_neomme.py | 2 -- src/transformers/models/neomme/modular_neomme.py | 2 ++ 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/transformers/models/neomme/modeling_neomme.py b/src/transformers/models/neomme/modeling_neomme.py index 51cbcb4e8687..0eaf5ebb1feb 100644 --- a/src/transformers/models/neomme/modeling_neomme.py +++ b/src/transformers/models/neomme/modeling_neomme.py @@ -27,7 +27,6 @@ from ... import initialization as init from ...activations import ACT2FN -from ...integrations import use_kernelized_func from ...masking_utils import create_bidirectional_mask, create_bidirectional_sliding_window_mask from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, MaskedLMOutput @@ -269,7 +268,6 @@ def eager_attention_forward( return attn_output, attn_weights -@use_kernelized_func(apply_rotary_pos_emb) class NeoMMEAttention(nn.Module): """Bidirectional grouped-query attention with QK-norm, M-RoPE, and a sigmoid output gate. diff --git a/src/transformers/models/neomme/modular_neomme.py b/src/transformers/models/neomme/modular_neomme.py index 761fbd9eba4f..015bb769785f 100644 --- a/src/transformers/models/neomme/modular_neomme.py +++ b/src/transformers/models/neomme/modular_neomme.py @@ -37,6 +37,7 @@ TensorType, TransformersKwargs, auto_docstring, + no_inherit_decorator, torch_compilable_check, ) from ...utils.constants import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD @@ -328,6 +329,7 @@ def forward(self, attn_output: torch.Tensor, hidden_states: torch.Tensor) -> tor return self.o_proj(attn_output * torch.sigmoid(self.gate_proj(hidden_states))) +@no_inherit_decorator class NeoMMEAttention(MuseGlimmerTextAttention): """Bidirectional grouped-query attention with QK-norm, M-RoPE, and a sigmoid output gate. From c1555936f94d72a1fed986ddca6922fb8398cbc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Ouazan?= <83456801+remi-or@users.noreply.github.com> Date: Tue, 1 Sep 2026 14:54:40 +0000 Subject: [PATCH 017/996] [Fix] Sparse TikToken tokenizers silently fail (#48446) * Remove sentencepiece warning for tiktiokens * Fix non contiguous * Fix potential None * Added test * Inline a single use fn * Better size estimation --- src/transformers/convert_slow_tokenizer.py | 7 +- .../tokenization_utils_tokenizers.py | 176 +++++++++++------- tests/tokenization/test_tokenization_fast.py | 65 ++++++- 3 files changed, 177 insertions(+), 71 deletions(-) diff --git a/src/transformers/convert_slow_tokenizer.py b/src/transformers/convert_slow_tokenizer.py index cf6de5681b75..8d4f8127de5e 100644 --- a/src/transformers/convert_slow_tokenizer.py +++ b/src/transformers/convert_slow_tokenizer.py @@ -1931,15 +1931,18 @@ def __init__( extra_special_tokens.keys() if isinstance(extra_special_tokens, dict) else extra_special_tokens ) - def extract_vocab_merges_from_model(self, tiktoken_url: str): + @staticmethod + def load_tiktoken_bpe(tiktoken_url: str) -> dict[bytes, int]: try: from tiktoken.load import load_tiktoken_bpe except Exception: raise ValueError( "`tiktoken` is required to read a `tiktoken` file. Install it with `pip install tiktoken`." ) + return load_tiktoken_bpe(tiktoken_url) - bpe_ranks = load_tiktoken_bpe(tiktoken_url) + def extract_vocab_merges_from_model(self, tiktoken_url: str): + bpe_ranks = self.load_tiktoken_bpe(tiktoken_url) byte_encoder = bytes_to_unicode() def token_bytes_to_string(b): diff --git a/src/transformers/tokenization_utils_tokenizers.py b/src/transformers/tokenization_utils_tokenizers.py index 05e2cfbb6e4e..65b8eaad1bcb 100644 --- a/src/transformers/tokenization_utils_tokenizers.py +++ b/src/transformers/tokenization_utils_tokenizers.py @@ -62,6 +62,9 @@ # Slow tokenizers have an additional added tokens files ADDED_TOKENS_FILE = "added_tokens.json" +# Some repos use a tiktoken-style tokenizer with an obvious name +TIKTOKEN_LEGACY_NAME = "tiktoken.model" + INIT_TOKENIZER_DOCSTRING += """ tokenizer_object ([`tokenizers.Tokenizer`]): A [`tokenizers.Tokenizer`] object from 🤗 tokenizers to instantiate from. See [Using tokenizers from 🤗 @@ -210,77 +213,18 @@ def convert_to_native_format(cls, trust_remote_code=False, **kwargs): # SentencePiece model (with TikToken fallback) if isinstance(vocab_file, str) and os.path.isfile(vocab_file) and vocab_file.endswith(".model"): - try: - from .convert_slow_tokenizer import SentencePieceExtractor - - # 1. Extract vocab, merges, and spm_precompiled from the .model proto - extractor = SentencePieceExtractor(vocab_file) - local_kwargs = extractor.extract(cls.model, **local_kwargs) - - # 2. If a model-specific converter exists, use it. + # Unless the name is a known Tiktoken pattern, try to use SentencePiece + if os.path.basename(vocab_file) != TIKTOKEN_LEGACY_NAME: try: - from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS - - converter_class = SLOW_TO_FAST_CONVERTERS.get(cls.__name__) - if converter_class is not None and hasattr(converter_class, "convert_from_spm"): - local_kwargs = converter_class.convert_from_spm(**local_kwargs) - except Exception as e: + local_kwargs = cls._convert_from_sentencepiece(vocab_file, local_kwargs) + return local_kwargs + except Exception as e: # TODO only catch deserialization error here! logger.warning( - f"Could not reorder vocab using converter for {cls.__name__} due to {e}. Falling back to raw SentencePiece extraction." - ) - if hasattr(cls, "convert_from_spm_model"): - local_kwargs = cls.convert_from_spm_model(**local_kwargs) - - # 3. For non-model specific tokenizers (e.g. TokenizersBackend used - # for MODELS_WITH_INCORRECT_HUB_TOKENIZER_CLASS), build a _tokenizer - # from the proto so normalizer/decoder are configured correctly. - if "tokenizer_object" not in local_kwargs and ( - cls is TokenizersBackend or "__init__" not in cls.__dict__ - ): - vocab = local_kwargs.pop("vocab", None) - merges = local_kwargs.pop("merges", None) - - # Replace placeholder tokens as specified in added_tokens_decoder - added_tokens_decoder = local_kwargs.get("added_tokens_decoder") or {} - if vocab is not None and added_tokens_decoder: - id_to_token = {token_id: token for token, token_id in vocab.items()} - for token_id, new_token in added_tokens_decoder.items(): - token_id = int(token_id) - new_token = str(new_token) - current_token = id_to_token.get(token_id) - if current_token and current_token != new_token and new_token not in vocab: - vocab[new_token] = vocab.pop(current_token) - id_to_token[token_id] = new_token - - tokenizer_object = SpmConverter.build_tokenizer_from_spm_proto( - proto=extractor.proto, - vocab=vocab, - merges=merges, + f"Could not extract SentencePiece model from {vocab_file} using sentencepiece library due to" + f" {e}. Falling back to TikToken extractor." ) - if tokenizer_object is not None: - local_kwargs["tokenizer_object"] = tokenizer_object - # Set bos/eos tokens from proto spec if available. This is needed when - # building a tokenizer_object directly from a .model file because the - # tokenizer_object does not have bos/eos set. - proto_spec = extractor.proto.trainer_spec - if proto_spec.bos_id >= 0: - local_kwargs.setdefault("bos_token", proto_spec.bos_piece or "") - if proto_spec.eos_id >= 0: - local_kwargs.setdefault("eos_token", proto_spec.eos_piece or "") - if proto_spec.unk_id >= 0: - local_kwargs.setdefault("unk_token", proto_spec.unk_piece or "") - - except Exception as e: # TODO only catch deserialization error here! - logger.warning( - f"Could not extract SentencePiece model from {vocab_file} using sentencepiece library due to {e}. " - "Falling back to TikToken extractor." - ) - from .convert_slow_tokenizer import TikTokenConverter - - converter = TikTokenConverter( - vocab_file=vocab_file, extra_special_tokens=local_kwargs.get("extra_special_tokens") - ) - local_kwargs["tokenizer_object"] = converter.converted() + # If the name is a known Tiktoken pattern or the SentencePiece extraction failed, use TikToken + local_kwargs = cls._convert_from_tiktoken(vocab_file, local_kwargs) return local_kwargs # Fallback to standard vocab/merges files if they existed! @@ -325,6 +269,102 @@ def _iter_special_tokens(values: Iterable[Any]) -> list[str]: local_kwargs["merges"] = merges return local_kwargs + @classmethod + def _convert_from_tiktoken(cls, vocab_file: str, local_kwargs: dict[str, Any]) -> dict[str, Any]: + """Path to a vocab file and a list of extra special tokens.""" + from .convert_slow_tokenizer import TikTokenConverter + + # `added_tokens_decoder` is a (token_id -> token) dict of tokens that may not be contiguous + added_tokens_decoder: dict[int, str] = { + int(token_id): token["content"] if isinstance(token, dict) else str(token) + for token_id, token in (local_kwargs.get("added_tokens_decoder") or {}).items() + } + # `extra_special_tokens` is a list of tokens to append to the base vocabulary + extra_special_tokens: list[str] = local_kwargs.get("extra_special_tokens") or [] + if isinstance(extra_special_tokens, dict): + extra_special_tokens = list(extra_special_tokens.keys()) + + # Retrieve the vocab size from the vocab file + base_vocab_size = len(TikTokenConverter.load_tiktoken_bpe(vocab_file)) + + # If any of the tokens in `added_tokens_decoder` are not in the base vocabulary, they need to be added. To do so + # we bake them in the `extra_special_tokens` list, with placeholder if `added_tokens_decoder` is not contiguous + max_added_token_id = max(added_tokens_decoder.keys()) if added_tokens_decoder else 0 + if max_added_token_id >= base_vocab_size: + new_extras = [ + added_tokens_decoder.get(index, f"<|reserved_token_{index}|>") + for index in range(base_vocab_size, max_added_token_id + 1) + ] + set_new_extras = set(new_extras) + for special_token in extra_special_tokens: + if special_token not in set_new_extras: + new_extras.append(special_token) + extra_special_tokens = new_extras + + converter = TikTokenConverter(vocab_file=vocab_file, extra_special_tokens=extra_special_tokens) + local_kwargs["tokenizer_object"] = converter.converted() + return local_kwargs + + @classmethod + def _convert_from_sentencepiece(cls, vocab_file: str, local_kwargs: dict[str, Any]) -> dict[str, Any]: + from .convert_slow_tokenizer import SentencePieceExtractor + + # 1. Extract vocab, merges, and spm_precompiled from the .model proto + extractor = SentencePieceExtractor(vocab_file) + local_kwargs = extractor.extract(cls.model, **local_kwargs) + + # 2. If a model-specific converter exists, use it. + try: + from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS + + converter_class = SLOW_TO_FAST_CONVERTERS.get(cls.__name__) + if converter_class is not None and hasattr(converter_class, "convert_from_spm"): + local_kwargs = converter_class.convert_from_spm(**local_kwargs) + except Exception as e: + logger.warning( + f"Could not reorder vocab using converter for {cls.__name__} due to {e}. Falling back to raw SentencePiece extraction." + ) + if hasattr(cls, "convert_from_spm_model"): + local_kwargs = cls.convert_from_spm_model(**local_kwargs) + + # 3. For non-model specific tokenizers (e.g. TokenizersBackend used + # for MODELS_WITH_INCORRECT_HUB_TOKENIZER_CLASS), build a _tokenizer + # from the proto so normalizer/decoder are configured correctly. + if "tokenizer_object" not in local_kwargs and (cls is TokenizersBackend or "__init__" not in cls.__dict__): + vocab = local_kwargs.pop("vocab", None) + merges = local_kwargs.pop("merges", None) + + # Replace placeholder tokens as specified in added_tokens_decoder + added_tokens_decoder = local_kwargs.get("added_tokens_decoder") or {} + if vocab is not None and added_tokens_decoder: + id_to_token = {token_id: token for token, token_id in vocab.items()} + for token_id, new_token in added_tokens_decoder.items(): + token_id = int(token_id) + new_token = str(new_token) + current_token = id_to_token.get(token_id) + if current_token and current_token != new_token and new_token not in vocab: + vocab[new_token] = vocab.pop(current_token) + id_to_token[token_id] = new_token + + tokenizer_object = SpmConverter.build_tokenizer_from_spm_proto( + proto=extractor.proto, + vocab=vocab, + merges=merges, + ) + if tokenizer_object is not None: + local_kwargs["tokenizer_object"] = tokenizer_object + # Set bos/eos tokens from proto spec if available. This is needed when + # building a tokenizer_object directly from a .model file because the + # tokenizer_object does not have bos/eos set. + proto_spec = extractor.proto.trainer_spec + if proto_spec.bos_id >= 0: + local_kwargs.setdefault("bos_token", proto_spec.bos_piece or "") + if proto_spec.eos_id >= 0: + local_kwargs.setdefault("eos_token", proto_spec.eos_piece or "") + if proto_spec.unk_id >= 0: + local_kwargs.setdefault("unk_token", proto_spec.unk_piece or "") + return local_kwargs + def __init__(self, *args, **kwargs): # Truncation/padding dicts extracted from tokenizer.json by convert_to_native_format # when a class with a custom __init__ rebuilds the backend tokenizer from scratch. diff --git a/tests/tokenization/test_tokenization_fast.py b/tests/tokenization/test_tokenization_fast.py index 48f6f75a16eb..b136e2a16bd8 100644 --- a/tests/tokenization/test_tokenization_fast.py +++ b/tests/tokenization/test_tokenization_fast.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import base64 import concurrent.futures import json import os @@ -23,7 +24,7 @@ from tokenizers.models import BPE, WordLevel from transformers import AutoTokenizer, PreTrainedTokenizerFast -from transformers.testing_utils import require_tokenizers +from transformers.testing_utils import require_tiktoken, require_tokenizers @require_tokenizers @@ -277,6 +278,68 @@ def test_non_bpe_tokenizer_still_cleans_up(self): self.assertNotIn(" .", decoded) +@require_tokenizers +@require_tiktoken +class TikTokenAddedTokensTest(unittest.TestCase): + """Loading a tiktoken vocab must place `added_tokens_decoder` tokens on their declared ids. + + Repos such as `moonshotai/Kimi-K2.7-Code` ship a tiktoken vocab and declare their special tokens at sparse ids in a + reserved range above it. If the ids are appended in a contiguous block, the tokenizer will silently produce a false + mapping. The tests below mirror that shape at a small scale so the test needs no network. + """ + + BASE_TOKENS = list("abcdefghijklmnop") + # Sparse and non-contiguous, like the reserved range of a real tiktoken checkpoint: a hole at 19 + # and a far tail pair, so declaration order and id order disagree. + ADDED_TOKENS = {16: "[BOS]", 17: "[EOS]", 18: "<|im_end|>", 20: "<|start_header_id|>", 30: "[UNK]", 31: "[PAD]"} + + def _write_tiktoken_repo(self, directory, base_tokens, added_tokens): + with open(os.path.join(directory, "tiktoken.model"), "w") as vocab_file: + vocab_file.writelines( + f"{base64.b64encode(token.encode()).decode()} {rank}\n" for rank, token in enumerate(base_tokens) + ) + config = { + "tokenizer_class": "PreTrainedTokenizerFast", + "added_tokens_decoder": { + str(token_id): { + "content": content, + "lstrip": False, + "normalized": False, + "rstrip": False, + "single_word": False, + "special": True, + } + for token_id, content in added_tokens.items() + }, + } + with open(os.path.join(directory, "tokenizer_config.json"), "w") as config_file: + json.dump(config, config_file) + + def test_added_tokens_keep_their_declared_ids(self): + """Every declared added token resolves to the id its config declares.""" + with tempfile.TemporaryDirectory() as directory: + self._write_tiktoken_repo(directory, self.BASE_TOKENS, self.ADDED_TOKENS) + tokenizer = AutoTokenizer.from_pretrained(directory) + + misplaced = { + content: (token_id, tokenizer.convert_tokens_to_ids(content)) + for token_id, content in self.ADDED_TOKENS.items() + if tokenizer.convert_tokens_to_ids(content) != token_id + } + self.assertEqual(misplaced, {}, f"tokens landed on the wrong ids (declared, actual): {misplaced}") + + def test_gaps_between_added_tokens_are_padded(self): + """Ids with no declared token are filled with reserved placeholders, not left to collapse.""" + with tempfile.TemporaryDirectory() as directory: + self._write_tiktoken_repo(directory, self.BASE_TOKENS, self.ADDED_TOKENS) + tokenizer = AutoTokenizer.from_pretrained(directory) + + # 19 is the hole between "<|im_end|>" (18) and "<|start_header_id|>" (20). + self.assertEqual(tokenizer.convert_ids_to_tokens(19), "<|reserved_token_19|>") + # The vocabulary runs to the highest declared id and no further. + self.assertEqual(len(tokenizer), max(self.ADDED_TOKENS) + 1) + + @require_tokenizers class TokenizerVersioningTest(unittest.TestCase): def test_local_versioning(self): From 05e078a1d276d0f9dcfc08d1f2964cb8abb33b04 Mon Sep 17 00:00:00 2001 From: Steven Liu <59462357+stevhliu@users.noreply.github.com> Date: Tue, 1 Sep 2026 15:25:44 +0000 Subject: [PATCH 018/996] [docs] Fix code snippets (#47772) * fix * updates * tp docs --- docs/source/en/backbones.md | 4 +- docs/source/en/chat_templating.md | 6 +- docs/source/en/chat_templating_writing.md | 2 +- docs/source/en/custom_tokenizers.md | 5 +- docs/source/en/data_collators.md | 4 +- docs/source/en/deepspeed.md | 26 +- docs/source/en/how_to_hack_models.md | 15 +- docs/source/en/llm_tutorial.md | 4 +- docs/source/en/model_doc/llama4.md | 19 +- docs/source/en/model_doc/mistral.md | 9 +- docs/source/en/model_doc/siglip2.md | 2 +- docs/source/en/models.md | 2 + docs/source/en/monkey_patching.md | 4 +- docs/source/en/optimization_overview.md | 5 +- docs/source/en/optimizers.md | 32 --- docs/source/en/perf_infer_gpu_multi.md | 229 ++++++++---------- docs/source/en/pipeline_tutorial.md | 6 +- docs/source/en/processors.md | 2 +- docs/source/en/quantization/fbgemm_fp8.md | 2 +- .../source/en/quantization/finegrained_fp8.md | 2 +- docs/source/en/quantization/higgs.md | 2 +- docs/source/en/quantization/torchao.md | 2 - docs/source/en/run_scripts.md | 8 +- docs/source/en/serialization.md | 4 +- docs/source/en/tasks/asr.md | 2 +- docs/source/en/tasks/image_text_to_text.md | 10 +- docs/source/en/tasks/keypoint_matching.md | 2 +- .../en/tasks/masked_language_modeling.md | 6 +- docs/source/en/tasks/prompting.md | 2 +- .../en/tasks/sequence_classification.md | 1 + 30 files changed, 197 insertions(+), 222 deletions(-) diff --git a/docs/source/en/backbones.md b/docs/source/en/backbones.md index fbd420e9bda7..b1317cf1acef 100644 --- a/docs/source/en/backbones.md +++ b/docs/source/en/backbones.md @@ -72,7 +72,7 @@ The example below loads a [ResNet](./model_doc/resnet) backbone and neck for use Note that initializing from config will create the model with random weights. If you want to load a pretrained model, use `from_pretrained` API. ```py -from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation +from transformers import AutoConfig, MaskFormerConfig, MaskFormerForInstanceSegmentation backbone_config = AutoConfig.from_pretrained("microsoft/resnet-50") config = MaskFormerConfig(backbone_config=backbone_config) @@ -100,7 +100,7 @@ model = MaskFormerForInstanceSegmentation(config) [timm](https://hf.co/docs/timm/index) is a collection of vision models for training and inference. Transformers supports timm models as backbones with the [`TimmBackbone`] and [`TimmBackboneConfig`] classes. Set the necessary backbone checkpoint in `backbone` to create a model with Timm backbone with randomly initialized weights. ```py -from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation +from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, TimmBackboneConfig backbone_config = TimmBackboneConfig(backbone="resnet50", out_indices=[-1]) config = MaskFormerConfig(backbone_config=backbone_config) diff --git a/docs/source/en/chat_templating.md b/docs/source/en/chat_templating.md index 2e0e62220685..5c31b4747a68 100644 --- a/docs/source/en/chat_templating.md +++ b/docs/source/en/chat_templating.md @@ -94,8 +94,8 @@ messages = [ {"role": "system", "content": "You are a friendly chatbot who always responds in the style of a pirate",}, {"role": "user", "content": "How many helicopters can a human eat in one sitting?"}, ] -tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt") -print(tokenizer.decode(tokenized_chat[0])) +tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device) +print(tokenizer.decode(tokenized_chat["input_ids"][0])) ``` ```md @@ -109,7 +109,7 @@ How many helicopters can a human eat in one sitting? Pass the tokenized chat to [`~GenerationMixin.generate`] to generate a response. ```py -outputs = model.generate(tokenized_chat, max_new_tokens=128) +outputs = model.generate(**tokenized_chat, max_new_tokens=128) print(tokenizer.decode(outputs[0])) ``` diff --git a/docs/source/en/chat_templating_writing.md b/docs/source/en/chat_templating_writing.md index 8507195ce8be..0f919c309e2d 100644 --- a/docs/source/en/chat_templating_writing.md +++ b/docs/source/en/chat_templating_writing.md @@ -20,7 +20,7 @@ A chat template is a [Jinja](https://jinja.palletsprojects.com/en/stable/templat ```jinja {%- for message in messages %} - {{- '<|' + message['role'] + |>\n' }} + {{- '<|' + message['role'] + '|>\n' }} {{- message['content'] + eos_token }} {%- endfor %} {%- if add_generation_prompt %} diff --git a/docs/source/en/custom_tokenizers.md b/docs/source/en/custom_tokenizers.md index 27ae94c4a8b7..1e44c56fd0cc 100644 --- a/docs/source/en/custom_tokenizers.md +++ b/docs/source/en/custom_tokenizers.md @@ -166,7 +166,8 @@ Train or save the new empty tokenizer. tokenizer = NewTokenizer() # train on new corpus -tokenizer.train_new_from_iterator() +corpus = ["The stock market rallied today.", "Bond yields fell sharply."] +trained_tokenizer = tokenizer.train_new_from_iterator(corpus, vocab_size=32000) # save tokenizer -tokenizer.save_pretrained("./new-tokenizer") +trained_tokenizer.save_pretrained("./new-tokenizer") ``` diff --git a/docs/source/en/data_collators.md b/docs/source/en/data_collators.md index a4f4c8cd646c..48d61e4fb50f 100644 --- a/docs/source/en/data_collators.md +++ b/docs/source/en/data_collators.md @@ -82,9 +82,11 @@ Subclass [`DataCollatorMixin`] for full control over batch assembly and implemen ```py import torch -from transformers import DataCollatorMixin +from dataclasses import dataclass +from transformers.data.data_collator import DataCollatorMixin from trl.trainer.utils import pad +@dataclass class DataCollatorForPreference(DataCollatorMixin): pad_token_id: int pad_to_multiple_of: int | None = None diff --git a/docs/source/en/deepspeed.md b/docs/source/en/deepspeed.md index d6269f32cd67..765d219a1184 100644 --- a/docs/source/en/deepspeed.md +++ b/docs/source/en/deepspeed.md @@ -64,12 +64,24 @@ Use `"auto"` in your config for values you want DeepSpeed to fill from [`Trainin > See the [DeepSpeed Configuration JSON](https://www.deepspeed.ai/docs/config-json/) reference for a complete list of DeepSpeed config options. ```json -"train_micro_batch_size_per_gpu": "auto", // ← per_device_train_batch_size in TrainingArguments -"gradient_accumulation_steps": "auto", // ← gradient_accumulation_steps in TrainingArguments -"optimizer.params.lr": "auto", // ← learning_rate in TrainingArguments -"fp16.enabled": "auto", // ← fp16 flag in TrainingArguments +{ + "train_micro_batch_size_per_gpu": "auto", + "gradient_accumulation_steps": "auto", + "optimizer": { + "type": "AdamW", + "params": { "lr": "auto" } + }, + "fp16": { "enabled": "auto" } +} ``` +| DeepSpeed config | [`TrainingArguments`] | +|---|---| +| `train_micro_batch_size_per_gpu` | `per_device_train_batch_size` | +| `gradient_accumulation_steps` | `gradient_accumulation_steps` | +| `optimizer.params.lr` | `learning_rate` | +| `fp16.enabled` | `fp16` | + Pass the config to the `deepspeed` argument. ```py @@ -173,8 +185,8 @@ Select a ZeRO stage config to use as a starting point. "stage3_prefetch_bucket_size": "auto", "stage3_param_persistence_threshold": "auto", "stage3_gather_16bit_weights_on_model_save": true, - "offload_optimizer": { "device": "cpu", "pin_memory": true }, // optional offloading - "offload_param": { "device": "cpu", "pin_memory": true } // optional offloading + "offload_optimizer": { "device": "cpu", "pin_memory": true }, + "offload_param": { "device": "cpu", "pin_memory": true } }, "gradient_clipping": "auto", "train_micro_batch_size_per_gpu": "auto", @@ -217,7 +229,7 @@ The following fields are important for customizing training. { "zero_optimization": { "stage": 3, - "stage3_gather_16bit_weights_on_model_save": true, + "stage3_gather_16bit_weights_on_model_save": true } } ``` diff --git a/docs/source/en/how_to_hack_models.md b/docs/source/en/how_to_hack_models.md index 908a047720cc..94d68503fd00 100644 --- a/docs/source/en/how_to_hack_models.md +++ b/docs/source/en/how_to_hack_models.md @@ -57,7 +57,7 @@ class SamVisionAttentionSplit(SamVisionAttention, nn.Module): self._register_load_state_dict_pre_hook(self.split_q_k_v_load_hook) ``` -2. The `_split_qkv_load_hook` function splits the pretrained `qkv` weights into separate `q`, `k`, and `v` weights when loading the model to ensure compatibility with any pretrained model. +2. The `split_q_k_v_load_hook` function splits the pretrained `qkv` weights into separate `q`, `k`, and `v` weights when loading the model to ensure compatibility with any pretrained model. ```py def split_q_k_v_load_hook(self, state_dict, prefix, *args): @@ -105,18 +105,17 @@ class SamVisionAttentionSplit(SamVisionAttention, nn.Module): Assign the custom `SamVisionAttentionSplit` class to the original models `SamVisionAttention` module to replace it. All instances of `SamVisionAttention` in the model are replaced with the split attention version. -Load the model with [`~PreTrainedModel.from_pretrained`]. +Swap the class *before* calling [`~PreTrainedModel.from_pretrained`]. The load hook only runs while the checkpoint is loading, so replacing the modules on an already loaded model leaves the new `q`, `k`, and `v` layers randomly initialized. ```py from transformers import SamModel +from transformers.models.sam import modeling_sam -# load the pretrained SAM model -model = SamModel.from_pretrained("facebook/sam-vit-base") +# replace the attention class the vision layers instantiate +modeling_sam.SAM_VISION_ATTENTION_CLASSES["eager"] = SamVisionAttentionSplit -# replace the attention class in the vision_encoder module -for layer in model.vision_encoder.layers: - if hasattr(layer, "attn"): - layer.attn = SamVisionAttentionSplit(model.config.vision_config, model.config.vision_config.window_size) +# load the pretrained SAM model, the hook splits the qkv weights during loading +model = SamModel.from_pretrained("facebook/sam-vit-base", attn_implementation="eager") ``` ## LoRA diff --git a/docs/source/en/llm_tutorial.md b/docs/source/en/llm_tutorial.md index e43123b8a097..bb1c9c598d63 100644 --- a/docs/source/en/llm_tutorial.md +++ b/docs/source/en/llm_tutorial.md @@ -291,8 +291,8 @@ messages = [ {"role": "user", "content": "How many cats does it take to change a light bulb?"}, ] model_inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device) -input_length = model_inputs.shape[1] -generated_ids = model.generate(model_inputs, do_sample=True, max_new_tokens=50) +input_length = model_inputs["input_ids"].shape[1] +generated_ids = model.generate(**model_inputs, do_sample=True, max_new_tokens=50) print(tokenizer.batch_decode(generated_ids[:, input_length:], skip_special_tokens=True)[0]) "Arr, matey! According to me beliefs, 'twas always one cat to hold the ladder and another to climb up it an’ change the light bulb, but if yer looking to save some catnip, maybe yer can ``` diff --git a/docs/source/en/model_doc/llama4.md b/docs/source/en/model_doc/llama4.md index b87c3f018fda..d6abb8ffaa8a 100644 --- a/docs/source/en/model_doc/llama4.md +++ b/docs/source/en/model_doc/llama4.md @@ -88,18 +88,17 @@ from transformers import AutoTokenizer, Llama4ForConditionalGeneration model_id = "meta-llama/Llama-4-Scout-17B-16E-Instruct" tokenizer = AutoTokenizer.from_pretrained(model_id) +model = Llama4ForConditionalGeneration.from_pretrained( + model_id, + device_map="auto", +) messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device) -model = Llama4ForConditionalGeneration.from_pretrained( - model_id, - device_map="auto", -) - -outputs = model.generate(**inputs.to(model.device), max_new_tokens=100) +outputs = model.generate(**inputs, max_new_tokens=100) outputs = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[-1]:]) print(outputs[0]) ``` @@ -227,19 +226,19 @@ model = Llama4ForConditionalGeneration.from_pretrained( messages = [ {"role": "user", "content": f"Look at the following texts: [{very_long_text}]\n\n\n\nWhat are the books, and who wrote them? Make me a nice list."}, ] -input_ids = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device) +inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True).to(model.device) -torch_device_module = getattr(torch, device, torch.cuda) +torch_device_module = getattr(torch, model.device.type, torch.cuda) torch_device_module.synchronize() start = time.time() out = model.generate( - input_ids.to(model.device), + **inputs, prefill_chunk_size=2048*8, max_new_tokens=300, cache_implementation="hybrid", ) print(time.time()-start) -print(tokenizer.batch_decode(out[:, input_ids.shape[-1]:])) +print(tokenizer.batch_decode(out[:, inputs["input_ids"].shape[-1]:])) print(f"{torch_device_module.max_memory_allocated(model.device) / 1024**3:.2f} GiB") ``` diff --git a/docs/source/en/model_doc/mistral.md b/docs/source/en/model_doc/mistral.md index 2bf8a0af094a..5c0fee9ee6ac 100644 --- a/docs/source/en/model_doc/mistral.md +++ b/docs/source/en/model_doc/mistral.md @@ -72,7 +72,7 @@ messages = [ model_inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device) -generated_ids = model.generate(model_inputs, max_new_tokens=100, do_sample=True) +generated_ids = model.generate(**model_inputs, max_new_tokens=100, do_sample=True) tokenizer.batch_decode(generated_ids)[0] "Mayonnaise can be made as follows: (...)" ``` @@ -92,6 +92,7 @@ Quantization reduces the memory burden of large models by representing the weigh The example below uses [bitsandbytes](../quantization/bitsandbytes) to only quantize the weights to 4-bits. ```python +import torch from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig @@ -99,10 +100,10 @@ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", - bnb_4bit_compute_dtype="torch.float16", + bnb_4bit_compute_dtype=torch.float16, ) -model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3", quantization_config=True, device_map="auto") +model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3", quantization_config=quantization_config, device_map="auto") tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3") prompt = "My favourite condiment is" @@ -115,7 +116,7 @@ messages = [ model_inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device) -generated_ids = model.generate(model_inputs, max_new_tokens=100, do_sample=True) +generated_ids = model.generate(**model_inputs, max_new_tokens=100, do_sample=True) tokenizer.batch_decode(generated_ids)[0] "The expected output" ``` diff --git a/docs/source/en/model_doc/siglip2.md b/docs/source/en/model_doc/siglip2.md index cf4f97e79319..8663f953b1ac 100644 --- a/docs/source/en/model_doc/siglip2.md +++ b/docs/source/en/model_doc/siglip2.md @@ -174,7 +174,7 @@ from transformers import AutoModel, AutoProcessor model_id = "google/siglip2-so400m-patch14-384" processor = AutoProcessor.from_pretrained(model_id) -model = AutoModel.from_pretrained(model_id).eval(device_map="auto") +model = AutoModel.from_pretrained(model_id, device_map="auto").eval() texts = [ "HOME084 Timbangan Badan Digital Kaca Transparan 28CM Body Scale Personal Scale", diff --git a/docs/source/en/models.md b/docs/source/en/models.md index 15044a9fbb63..019b6c81d538 100644 --- a/docs/source/en/models.md +++ b/docs/source/en/models.md @@ -123,6 +123,8 @@ Parameters load in parallel and peak memory only depends on model size. Use `max ```py import json +import os +import tempfile with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(tmp_dir, max_shard_size="50GB") diff --git a/docs/source/en/monkey_patching.md b/docs/source/en/monkey_patching.md index fb7435ff02ac..b263d42546c8 100644 --- a/docs/source/en/monkey_patching.md +++ b/docs/source/en/monkey_patching.md @@ -240,7 +240,7 @@ register_patch_mapping( ) register_checkpoint_conversion_mapping( - model_type="llama", + model_type_or_class_name="llama", mapping=[ WeightConverter( source_patterns=["q_proj", "k_proj", "v_proj"], @@ -405,7 +405,7 @@ register_patch_mapping( # - Override the original conversion mapping for qwen2_moe which concatenated the experts into a single parameter format. # - Concatenate the q_proj, k_proj, v_proj weights/biases into a single qkv_proj weight/bias for the new fused attention module. register_checkpoint_conversion_mapping( - model_type="qwen2_moe", + model_type_or_class_name="qwen2_moe", mapping=[ WeightConverter( source_patterns=["q_proj", "k_proj", "v_proj"], diff --git a/docs/source/en/optimization_overview.md b/docs/source/en/optimization_overview.md index c0fe9fcaee77..fb2578ac7fc6 100644 --- a/docs/source/en/optimization_overview.md +++ b/docs/source/en/optimization_overview.md @@ -145,7 +145,7 @@ Use [`~ContinuousMixin.generate_batch`] to enable continuous batching. ```py import torch from transformers import AutoModelForCausalLM, AutoTokenizer -from transformers.generation import GenerationConfig +from transformers.generation import ContinuousBatchingConfig, GenerationConfig model = AutoModelForCausalLM.from_pretrained( "Qwen/Qwen3-0.6B", @@ -167,12 +167,13 @@ generation_config = GenerationConfig( eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.pad_token_id, do_sample=False, - max_batch_tokens=512, ) +continuous_batching_config = ContinuousBatchingConfig(max_batch_tokens=512) outputs = model.generate_batch( inputs=inputs, generation_config=generation_config, + continuous_batching_config=continuous_batching_config, ) for request_id, output in outputs.items(): diff --git a/docs/source/en/optimizers.md b/docs/source/en/optimizers.md index 21ea4ca056e5..ba5b208bd78c 100644 --- a/docs/source/en/optimizers.md +++ b/docs/source/en/optimizers.md @@ -102,7 +102,6 @@ Transformers integrates third-party optimizers for specialized training scenario | Optimizer | Install | `optim="value"` | Description | |---|---|---|---| | APOLLO | `apollo-torch` | `apollo_adamw` | Memory-efficient full-param via random projections; rank-1 sufficient | -| FlashOptim | `flashoptim` | `flash_adamw`, `flash_adam`, `flash_sgd`, `flash_sgdw`, `flash_lion` | Reduces optimizer memory with low-precision master weights | | GrokAdamW | `grokadamw` | `grokadamw` | Targets delayed generalization (grokking) | | LOMO / AdaLomo | `lomo-optim` | `lomo` / `adalomo` | Fuses gradient + update step for low-memory full-param fine-tuning | | Schedule Free | `schedulefree` | `schedule_free_adamw`, `schedule_free_radam`, `schedule_free_sgd` | Eliminates LR annealing; pair with `lr_scheduler_type="constant"` | @@ -152,37 +151,6 @@ args = TrainingArguments( ) ``` -
- - -```bash -pip install flashoptim -``` - -[FlashOptim](https://huggingface.co/papers/2602.23349) reduces optimizer memory by storing master weights in lower precision. It supports AdamW, Adam, SGD, SGDW, and Lion variants. - -> [!TIP] -> FlashOptim requires bf16 or fp16 model weights. It automatically disables `master_weight_bits` and warns if your model uses fp32. - -```diff -args = TrainingArguments( -+ optim="flash_adamw", -+ bf16=True, - ... # remaining args from the TrainingArguments intro config -) -``` - -`master_weight_bits` controls the precision of the optimizer's master weight copy. By default, it stores the master copy in 24 bits. Set it to `"None"` to remove the master copy entirely for maximum memory savings at the cost of a slightly higher loss. - -```diff -args = TrainingArguments( -+ optim="flash_adamw", -+ optim_args="master_weight_bits=None", -+ bf16=True, - ... # remaining args from the TrainingArguments intro config -) -``` - diff --git a/docs/source/en/perf_infer_gpu_multi.md b/docs/source/en/perf_infer_gpu_multi.md index 2771978f6f29..c7fa4e4e1e64 100644 --- a/docs/source/en/perf_infer_gpu_multi.md +++ b/docs/source/en/perf_infer_gpu_multi.md @@ -17,35 +17,25 @@ rendered properly in your Markdown viewer. [Tensor parallelism](./perf_train_gpu_many#tensor-parallelism) slices a model layer into pieces so multiple hardware accelerators work on it simultaneously. This lets you run models that exceed a single GPU's memory capacity and achieve higher throughput. You'll need fast intra-node communication because GPUs exchange partial results at each layer. -The list below shows models with native tensor parallelism support. Open a GitHub issue or pull request to add support for a model. +A model supports tensor parallelism if its config defines `base_model_tp_plan`. Check a loaded model with the `supports_tp_plan` property. -
-Show supported models - -* [Cohere](./model_doc/cohere) and [Cohere 2](./model_doc/cohere2) -* [Gemma](./model_doc/gemma) and [Gemma 2](./model_doc/gemma2) -* [GLM](./model_doc/glm) -* [Granite](./model_doc/granite) -* [Llama](./model_doc/llama) -* [Mistral](./model_doc/mistral) -* [Mixtral](./model_doc/mixtral) -* [OLMo](./model_doc/olmo) and [OLMo2](./model_doc/olmo2) -* [Phi](./model_doc/phi) and [Phi-3](./model_doc/phi3) -* [Qwen2](./model_doc/qwen2), [Qwen2Moe](./model_doc/qwen2_moe), and [Qwen2-VL](./model_doc/qwen2_5_vl) -* [Starcoder2](./model_doc/starcoder2) +```py +from transformers import AutoModelForCausalLM -
+model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct") +print(model.supports_tp_plan) +``` This guide covers enabling tensor parallelism in Transformers and the available partitioning strategies. ## Partitioning a model -Transformers supports tensor parallelism for models with a predefined plan. Configure the number of tensor parallel devices with `tp_size` in [`DistributedConfig`]. +Configure the number of tensor parallel devices with `tp_size` in [`DistributedConfig`]. - Set `DistributedConfig(tp_size=N)` to use the model's predefined plan. -- Define a manual `tp_plan` and pass it to [`DistributedConfig`] with `tp_size`. +- Define a manual `tp_plan` and pass it to [`DistributedConfig`] along with `tp_size`. -You can also set `tp_plan="auto"` in [`DistributedConfig`]. When `tp_size` is omitted, it is inferred from `WORLD_SIZE`. Passing `tp_plan` directly to [`~PreTrainedModel.from_pretrained`] is deprecated and will be removed in v5.18. +You can also set `tp_plan="auto"` to request the predefined plan explicitly. When `tp_size` is omitted and a `tp_plan` is set, `tp_size` is derived from `WORLD_SIZE` divided by the other parallel sizes. Passing `tp_plan` directly to [`~PreTrainedModel.from_pretrained`] is deprecated and will be removed in v5.18. @@ -61,7 +51,7 @@ model = AutoModelForCausalLM.from_pretrained( dtype=torch.bfloat16, distributed_config=distributed_config, ) -print(model._tp_plan) +print(model.tp_plan) tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct") prompt = "Can I help" @@ -84,6 +74,8 @@ Define a tensor parallel plan for each layer in `tp_plan` and pass it through [` Manual partitioning requires a deep understanding of model architecture and strategy interactions. Poor partitioning choices create slow models that fail or produce incorrect results. The [Ultra-Scale Playbook](https://huggingface.co/spaces/nanotron/ultrascale-playbook?section=tensor_parallelism) explains partitioning strategies in detail. +Keys are module or parameter names, with `*` standing in for layer indices. An unrecognized strategy name raises a `ValueError` listing the supported names, and Transformers logs a warning for plan rules that matched nothing and for parameters that no rule covered. + ```py from transformers import AutoModelForCausalLM, DistributedConfig @@ -109,48 +101,59 @@ print(model.tp_plan) ## Partitioning strategies -The [`ParallelInterface`] class defines all partitioning strategies. It maps a string to the strategy implementation. You don't need to interact with this class directly since you set strategies with `tp_plan` in [`DistributedConfig`]. It's useful for checking available strategies. +The `ParallelInterface` class maps each strategy name you can use in a `tp_plan` to a configured strategy instance. You don't interact with it directly to shard a model, but it's the authoritative list of available names. ```py -class ParallelInterface(MutableMapping): - """ - Dict-like object keeping track of allowed attention functions. You can easily add a new attention function - with a call to `register()`. If a model needs to locally overwrite an existing attention function, say `sdpa`, - it needs to declare a new instance of this class inside the `modeling_.py`, and declare it on that instance. - """ +class ParallelInterface(GeneralInterface): _global_mapping = { - "colwise": ColwiseParallel(), - "rowwise": RowwiseParallel(), - "colwise_rep": ColwiseParallel(output_layouts=Replicate()), - "rowwise_rep": RowwiseParallel(input_layouts=Replicate()), - "local_colwise": ColwiseParallel(use_dtensor=False), - "local_rowwise": RowwiseParallel(use_dtensor=False), - "local": IsolatedParallel(), - "moe_tp_experts": MoeTensorParalellExperts(), - "local_packed_rowwise": PackedRowwiseParallel(use_dtensor=False), - "sequence_parallel": SequenceParallel(), - "replicate": ReplicateParallel(), + "embedding_rowwise": RowwiseParallel(input_layouts=Replicate(), output_layouts=Replicate()), + "colwise_gather_output": ColwiseParallel(input_layouts=Replicate(), output_layouts=Replicate()), + "colwise_rep": ColwiseParallel(input_layouts=Replicate(), output_layouts=Replicate()), + "colwise": ColwiseParallel(input_layouts=Replicate(), output_layouts=Shard(-1)), + "rowwise": RowwiseParallel(input_layouts=Shard(-1), output_layouts=Replicate()), + "rowwise_split_input": RowwiseParallel(input_layouts=Replicate(), output_layouts=Replicate()), + "rowwise_rep": RowwiseParallel(input_layouts=Replicate(), output_layouts=Replicate()), + "packed_colwise": PackedColwiseParallel(), + "packed_rowwise": PackedRowwiseParallel(), + "sequence_parallel": SequenceParallel(use_local_output=True), + "grouped_gemm": MoEParamShard(Shard(0), shards_expert_dim=True), + "ep_router": EpRouterParallel(), + "megamoe_router": RouterParallelMegaMoe(), + "moe_tp_experts": MoeExpertsParallel(), + "megamoe_experts": MoeTensorParalellMegaMoeExperts(), + "moe_identity_expert": MoeIdentityParallel(), + "replicated_with_grad_allreduce": ReplicatedWithGradAllReduce(), + "mla_kv_a_proj": MlaKvAProjParallel(), + "all_reduce": AllReduceParallel(), } ``` +Every strategy is a subclass of `TensorParallelLayer` in [distributed/tensor_parallel.py](https://github.com/huggingface/transformers/blob/main/src/transformers/distributed/tensor_parallel.py). The two you'll reach for most, `ColwiseParallel` and `RowwiseParallel`, take `input_layouts` and `output_layouts` placements, which is how one class covers several plan names. `colwise` leaves its output sharded on the last dim for a following `rowwise` layer to consume, while `colwise_gather_output` all-gathers it back to a full tensor. + The table below describes each strategy. | Strategy | Description | |---|---| -| `ColwiseParallel` | Partitions weights and biases column-wise. | -| `RowwiseParallel` | Partitions weights and biases row-wise. Supports `nn.Embedding` modules partitioning. | -| `SequenceParallel` | Sequence parallel implementation to support `LayerNorm` and `Dropout` layers. Supports Python implementation of [RMSNorm](https://github.com/facebookresearch/llama/blob/main/llama/model.py#L34). | -| `PackedColwiseParallel` | A variant of `ColwiseParallel` that supports packed weights (for example, packing `up_proj` and `gate_proj` together). Refer to the [code](https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/tensor_parallel.py#L79-#L108) for more details. | -| `PackedRowwiseParallel` | A variant of `RowwiseParallel` that supports packed weights (refer to the [code](https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/tensor_parallel.py#L79-#L108) for more details). | -| `GatherParallel` | Gathers module outputs across devices. | -| `IsolatedParallel` | Isolates a module from other devices. Used for Experts in Mixture-of-Experts (MoE) layers. | -| `ReplicateParallel` | Replicates modules across all devices. Prevents `torch.distributed` APIs from breaking due to a partially sharded model. | +| `ColwiseParallel` | Shards a weight on its output-feature dim (`Shard(0)` for a 2D `nn.Linear` weight, `Shard(1)` for `nn.Embedding`) and shards a 1D bias. Redistributes the input to `Replicate()`, then places the output at `output_layouts`. | +| `RowwiseParallel` | Shards a weight on its input-feature dim (`Shard(-1)`, or `Shard(0)` for `nn.Embedding`) and replicates the bias, which is added after the reduction. Each rank's forward produces a `Partial()` output holding its share of the sum, and `transform_output_post_forward` redistributes that to `output_layouts`. Reducing to `Replicate()` issues an all-reduce, and reducing to `Shard(1)` issues a reduce-scatter. | +| `PackedColwiseParallel` | A variant of `ColwiseParallel` for fused weights, for example `up_proj` and `gate_proj` packed into `gate_up_proj`. Use `split_factor` when a weight packs a number of layers other than two. | +| `PackedRowwiseParallel` | The row-wise counterpart, for weights packed along the final dim. Replicates 1D parameters. | +| `SequenceParallel` | Replicates the module's parameters and shards its input on `sequence_dim` (defaults to `1`). Used for norms that operate per-token, such as `LayerNorm` and `RMSNorm`. | +| `ReplicatedWithGradAllReduce` | Replicates a parameter but all-reduces its gradient. Needed for norms that sit between a column-wise and a row-wise layer and normalize along a sharded axis, where each rank only sees its own heads. | +| `AllReduceParallel` | All-reduces a module's `Partial()` forward output to `Replicate()`. Use it as a sync point for a module whose compute ends in a partial sum. | +| `MlaKvAProjParallel` | Splits the `kv_a_proj_with_mqa` output of DeepSeek-V2 style MLA attention and all-reduces the gradient of the RoPE half, which bypasses `kv_b_proj` and would otherwise keep a partial gradient. Requires `qk_rope_head_dim` in the model config. | +| `MoEParamShard` | Shards MoE expert weights on a given placement. Backs the `grouped_gemm` name, where `shards_expert_dim=True` also rewrites `module.num_experts` to the per-rank expert count. | +| `EpRouterParallel` | Masks router scores for non-local experts and remaps global expert IDs to local ones, so each rank runs only the experts it owns. Requires `num_experts` to be divisible by the mesh size. | +| `RouterParallelMegaMoe` | Router variant for DeepGEMM Mega MoE, which dispatches experts inside the kernel which wants the router output untouched. | +| `MoeExpertsParallel` | Tensor parallel MoE experts. All-reduces the expert output forward and adds the backward all-reduces for hidden states and routing weights. | +| `MoeTensorParalellMegaMoeExperts` | Inference-only experts layer for DeepGEMM Mega MoE. Skips the gradient syncs and passes the process group into the module so the kernel can set up its shared buffers on the first forward. | +| `MoeIdentityParallel` | Pre-divides the input of a zero or identity expert by the mesh size, cancelling the all-reduce that `moe_tp_experts` applies downstream. | ### Packed strategies Weight packing combines multiple linear layers into a single, larger layer. The `PackedColwiseParallel` and `PackedRowwiseParallel` strategies shard packed weights correctly. Basic `ColwiseParallel` or `RowwiseParallel` strategies shard packed weights incorrectly. -The example below packs `up_proj` and `gate_proj` into a single `gate_up_proj` module and requires the `PackedRowwiseParallel` strategy to shard `gate_up_proj`. +The example below packs `up_proj` and `gate_proj` into a single `gate_up_proj` module and requires the `packed_rowwise` strategy to shard `gate_up_proj`. ```python class Llama4TextExperts(nn.Module): @@ -167,95 +170,86 @@ def forward(self, hidden_states): gate, up = gate_up.chunk(2, dim=-1) # Split the output into gate and up ``` -> [!TIP] -> See [this comment](https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/tensor_parallel.py#L79-#L108) for a visual representation of why `Packed*` needs to be used. - -### Local strategies - -Local strategies (`local_colwise`, `local_rowwise`, `local_packed_rowwise`) don't use [DTensor](https://docs.pytorch.org/docs/stable/distributed.tensor.html) because it lacks support for some operations like [torch.chunk](https://docs.pytorch.org/docs/stable/generated/torch.chunk.html). Instead, local strategies use the basic [torch.Tensor](https://docs.pytorch.org/docs/stable/tensors.html) and perform distributed logic manually. - - +A plain `Shard` splits that dimension into contiguous blocks, so a rank would receive the tail of `gate` and the head of `up` instead of a slice of each. The packed strategies use `_StridedShard` with `split_factor` (`2` by default) to interleave the split, giving every rank a matching slice of both halves so `chunk` still lines up after sharding. ## Custom partitioning strategies -Inherit from [TensorParallelLayer](https://github.com/huggingface/transformers/blob/main/src/transformers/integrations/tensor_parallel.py) to create a custom partitioning strategy. Implement `partition_tensor`, `_prepare_input_fn` and `_prepare_output_fn`. +Inherit from `TensorParallelLayer` in [distributed/tensor_parallel.py](https://github.com/huggingface/transformers/blob/main/src/transformers/distributed/tensor_parallel.py) to create a custom partitioning strategy. Override only the hooks your strategy needs, since every one has a no-op default. -Register the strategy in the `ParallelInterface` mapping so the dispatching logic finds it when specified in `tp_plan`. +| Hook | Purpose | +|---|---| +| `validate_param` | Reject a parameter this strategy can't shard, before any weights load. | +| `shard_param` | Replace one parameter with a `DTensor` placeholder so the loader knows which shard belongs to this rank. | +| `transform_inputs_pre_forward` | Redistribute the module's inputs to the layout its forward expects. | +| `context_around_forward` | Wrap the forward in a context manager, for example to expose local tensors to a kernel. | +| `transform_output_post_forward` | Redistribute or reduce the module's output. | +| `should_use_local_tensors` | Report that this module's forward needs plain tensors rather than `DTensor`s. | +| `install_forward` | Replace `module.forward` outright. Override this only when the hooks above aren't enough, as `ReplicatedWithGradAllReduce` does to register a backward hook. | -The example below shows how to implement `ColwiseParallel` with this workflow. +The example below walks through a trimmed version of `ColwiseParallel`. -1. Inherit from `TensorParallelLayer`. In the `__init__` method, define `input_layouts` and `output_layouts` to describe how the input and output tensors should be placed on devices. The `desired_input_layouts` attribute is used to specify *how* the input should be placed on devices. +1. Inherit from `TensorParallelLayer` and store the placements the strategy works with. The base class defines no `__init__`, so there's nothing to call `super()` on. ```python class ColwiseParallel(TensorParallelLayer): - def __init__( - self, - *, - input_layouts: Optional[Placement] = None, # The input layout coming from the previous layer - output_layouts: Optional[Placement] = None, # The output layout we want to achieve - use_local_output: bool = True, # Whether to use local output or not - use_dtensor=True, # Whether to use DTensor or not - ): - self.input_layouts = (input_layouts or Replicate(),) # The input sharding coming from the previous layer - self.output_layouts = (output_layouts or Shard(-1),) # Desired output sharding - self.desired_input_layouts = (Replicate(),) # Desired input sharding, inputs should be replicated across GPUs + def __init__(self, *, input_layouts=None, output_layouts=None, use_local_output: bool = True): + self.input_layouts = input_layouts or Replicate() + self.output_layouts = output_layouts if output_layouts is not None else Shard(-1) self.use_local_output = use_local_output - self.use_dtensor = use_dtensor ``` -2. Implement the `partition_tensor`, `_prepare_input_fn`, and `_prepare_output_fn` methods. - - The `partition_tensor` method partitions the tensor and fills `empty_param` with the partitioned tensor. Use the utility function `get_tensor_shard` to help you get the correct shard of the original parameter for a given rank and `get_packed_weights` to help with packed weights. +2. Implement `shard_param` to wrap one parameter as a `DTensor` placeholder. It runs on meta tensors, so `distribute_tensor` only builds metadata and moves no data. Pass `src_data_rank=None` because there's no full tensor to scatter from yet. ```python - def partition_tensor( - self, - param, # Full tensor of the parameter - empty_param, # Empty tensor of the parameter, will be filled with the partitioned tensor - param_type, # Type of the parameter, `bias` or `weight` - param_casting_dtype, # The type to cast the parameter to - to_contiguous, # Whether to convert the tensor to a contiguous memory layout - rank, # The rank of the current device - device_mesh, # The device mesh - ) -> nn.Parameter: # Return the partitioned parameter - ... + def shard_param(self, module, param, mesh): + meta = module._parameters.get(param) + if meta is None: + return + # Output features live on dim 0 for a 2D weight and dim -1 for a 1D bias + placement = Shard(1) if isinstance(module, torch.nn.Embedding) else Shard(meta.ndim - 2) + module._parameters[param] = torch.nn.Parameter( + distribute_tensor(meta, mesh, [placement], src_data_rank=None), + requires_grad=meta.requires_grad, + ) ``` - The `_prepare_input_fn` and `_prepare_output_fn` methods are used in the [pre-forward](https://docs.pytorch.org/docs/stable/generated/torch.nn.modules.module.register_module_forward_pre_hook.html) and [forward](https://docs.pytorch.org/docs/stable/generated/torch.nn.modules.module.register_module_forward_hook.html) hooks. They redistribute the inputs and outputs to the desired layout as specified in the `__init__`. +3. Implement the input and output transforms. `install_forward` calls them around the module's original forward, so they only need to move tensors between layouts. Column-wise partitioning expects a replicated input and produces an output sharded on the last dim. ```python - def _prepare_input_fn(input_layouts, desired_input_layouts, mod, inputs, device_mesh): - ... - # Do some custom logic, cast to DTensor etc. - ... - return inputs.redistribute(placements=desired_input_layouts, device_mesh=device_mesh) - def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh): - ... - # Do some custom logic, cast to DTensor etc. - ... - return outputs.redistribute(placements=output_layouts, device_mesh=device_mesh) + def transform_inputs_pre_forward(self, module, args, kwargs, mesh): + x = args[0] + if not isinstance(x, DTensor): + x = DTensor.from_local(x, mesh, [self.input_layouts], run_check=False) + if x.placements != (Replicate(),): + x = x.redistribute(placements=[Replicate()]) + return (x,) + args[1:], kwargs + + def transform_output_post_forward(self, module, output, mesh): + if not isinstance(output, DTensor): + output = DTensor.from_local(output, mesh, [Shard(-1)], run_check=False) + if output.placements != (self.output_layouts,): + output = output.redistribute(placements=[self.output_layouts]) + return output.to_local() if self.use_local_output else output ``` -3. Register the strategy to [`ParallelInterface`] to enable it for use with `tp_plan`. + The shipped `ColwiseParallel` adds fast paths on top of this that skip the `DTensor` round trip for plain `nn.Linear` inference and for quantized modules that need local tensors. Read the source before copying it if your strategy needs the same treatment. + +4. Register the strategy so a `tp_plan` can name it. Registration takes a strategy instance, so the placements you pass to `__init__` are stored with the name. Note the `()` below. ```python import torch from transformers import AutoModelForCausalLM, DistributedConfig - from transformers.integrations.tensor_parallel import ParallelInterface + from transformers.distributed.tensor_parallel import ParallelInterface - ParallelInterface.register_strategy("colwise_custom", ColwiseParallel) + ParallelInterface.register("colwise_custom", ColwiseParallel()) tp_plan = { "model.layers.*.self_attn.q_proj": "colwise_custom", ... } distributed_config = DistributedConfig(tp_size=4, tp_plan=tp_plan) model = AutoModelForCausalLM.from_pretrained( - model_id, + "meta-llama/Meta-Llama-3-8B-Instruct", dtype=torch.bfloat16, distributed_config=distributed_config, ) @@ -292,36 +286,27 @@ Most `torch.distributed` parallelization strategies apply to the mesh itself or ### DTensor -`DTensor` (Distributed Tensor) handles distributed logic on top of usual tensor operations. Most model weights in tensor parallelism are stored as `DTensor`s. +`DTensor` (Distributed Tensor) handles distributed logic on top of usual tensor operations. Model weights under tensor parallelism are stored as `DTensor`s, which is what lets a strategy describe communication as a change of layout instead of an explicit collective. -The `placement` attribute tells PyTorch how to place a tensor on devices in `DeviceMesh`. It accepts the following values: +The `placements` attribute tells PyTorch how a tensor is laid out across the devices in a `DeviceMesh`. It accepts the following values: -- `Shard(dimension)` shards a `DTensor` across a given dimension over the `DeviceMesh` it was constructed under. The example below shows how to shard weights over different dimensions for column-wise partitioning. +- `Shard(dimension)` splits a `DTensor` across a given dimension over the `DeviceMesh` it was constructed under. Column-wise partitioning shards the output-feature dim of the weight and the only dim of the bias. ```python - weight = ... - weight = DTensor.from_local(weight, device_mesh["tp"], placements=[Shard(0)]) # Shard across the 1st (column-wise) dimension - bias = ... - bias = DTensor.from_local(bias, device_mesh["tp"], placements=[Shard(-1)]) # Shard across the ONLY dimension + weight = DTensor.from_local(weight, device_mesh["tp"], placements=[Shard(0)]) # Shard the output features + bias = DTensor.from_local(bias, device_mesh["tp"], placements=[Shard(-1)]) # Shard the ONLY dimension ``` - This example shows how to shard weights over different dimensions for row-wise partitioning. + Row-wise partitioning shards the input-feature dim instead and replicates the bias, because the bias is added once after the reduction rather than on every rank. ```python - weight = ... - weight = DTensor.from_local(weight, device_mesh["tp"], placements=[Shard(1)]) # Shard across the 2nd (row-wise) dimension - bias = ... + weight = DTensor.from_local(weight, device_mesh["tp"], placements=[Shard(-1)]) # Shard the input features bias = DTensor.from_local(bias, device_mesh["tp"], placements=[Replicate()]) # Replicate bias across all GPUs ``` -- `Replicate()` replicates a `DTensor` across the `DeviceMesh`. It creates a full copy of the tensor on each device. - - ```py - bias = ... - bias = DTensor.from_local(bias, device_mesh["tp"], placements=[Replicate()]) # Replicate bias across all GPUs - ``` +- `Replicate()` replicates a `DTensor` across the `DeviceMesh`, creating a full copy of the tensor on each device. -- `Partial()` indicates a tensor is pending a reduction operation (not typically relevant for Transformers usage). +- `Partial()` marks a tensor as pending a reduction. A row-wise layer's forward output is `Partial()`, and redistributing it to `Replicate()` is what issues the all-reduce. ## Resources diff --git a/docs/source/en/pipeline_tutorial.md b/docs/source/en/pipeline_tutorial.md index d22bf98282e9..82efe779dc71 100644 --- a/docs/source/en/pipeline_tutorial.md +++ b/docs/source/en/pipeline_tutorial.md @@ -187,7 +187,7 @@ import datasets device = Accelerator().device # KeyDataset is a utility that returns the item in the dict returned by the dataset -dataset = datasets.load_dataset("stanfordnlp/imdb", name="plain_text", split="unsupervised") +dataset = load_dataset("stanfordnlp/imdb", name="plain_text", split="unsupervised") pipeline = pipeline(task="text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english", device=device) for out in pipeline(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"): print(out) @@ -217,7 +217,7 @@ Pass the `return_timestamps="word"` parameter to [`Pipeline`] to return when eac from transformers import pipeline pipeline = pipeline(task="automatic-speech-recognition", model="openai/whisper-large-v3") -pipeline(audio="https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac", return_timestamp="word") +pipeline(audio="https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac", return_timestamps="word") {'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.', 'chunks': [{'text': ' I', 'timestamp': (0.0, 1.1)}, {'text': ' have', 'timestamp': (1.1, 1.44)}, @@ -300,7 +300,7 @@ from datasets import load_dataset device = Accelerator().device -dataset = datasets.load_dataset("stanfordnlp/imdb", name="plain_text", split="unsupervised") +dataset = load_dataset("stanfordnlp/imdb", name="plain_text", split="unsupervised") pipeline = pipeline(task="text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english", device=device) for out in pipeline(KeyDataset(dataset, "text"), batch_size=8, truncation="only_first"): print(out) diff --git a/docs/source/en/processors.md b/docs/source/en/processors.md index 650dcbf95c1a..bac73138eefe 100644 --- a/docs/source/en/processors.md +++ b/docs/source/en/processors.md @@ -91,7 +91,7 @@ Automatic speech recognition (ASR) tasks require a processor that can handle tex ```py from datasets import load_dataset -dataset = load_dataset("lj_speech", split="train") +dataset = load_dataset("keithito/lj_speech", split="train") dataset = dataset.map(remove_columns=["file", "id", "normalized_text"]) dataset[0]["audio"] {'array': array([-7.3242188e-04, -7.6293945e-04, -6.4086914e-04, ..., diff --git a/docs/source/en/quantization/fbgemm_fp8.md b/docs/source/en/quantization/fbgemm_fp8.md index d9fbd8177159..503eb87dd087 100644 --- a/docs/source/en/quantization/fbgemm_fp8.md +++ b/docs/source/en/quantization/fbgemm_fp8.md @@ -47,7 +47,7 @@ quantized_model = AutoModelForCausalLM.from_pretrained( ```py quant_path = "/path/to/save/quantized/model" -model.save_pretrained(quant_path) +quantized_model.save_pretrained(quant_path) model = AutoModelForCausalLM.from_pretrained(quant_path, device_map="auto") ``` diff --git a/docs/source/en/quantization/finegrained_fp8.md b/docs/source/en/quantization/finegrained_fp8.md index 8eaccd47b8d5..efc601c1cdae 100644 --- a/docs/source/en/quantization/finegrained_fp8.md +++ b/docs/source/en/quantization/finegrained_fp8.md @@ -57,7 +57,7 @@ Use [`~PreTrainedModel.save_pretrained`] to save the quantized model and reload ```py quant_path = "/path/to/save/quantized/model" -model.save_pretrained(quant_path) +quantized_model.save_pretrained(quant_path) model = AutoModelForCausalLM.from_pretrained(quant_path, device_map="auto") ``` diff --git a/docs/source/en/quantization/higgs.md b/docs/source/en/quantization/higgs.md index bbefe71140ba..160115954867 100644 --- a/docs/source/en/quantization/higgs.md +++ b/docs/source/en/quantization/higgs.md @@ -33,7 +33,7 @@ pip install flute-kernel ```bash -pip install flute-kernel -i https://flute-ai.github.io/whl/cu12.4 +pip install flute-kernel -i https://flute-ai.github.io/whl/cu11.8 ``` diff --git a/docs/source/en/quantization/torchao.md b/docs/source/en/quantization/torchao.md index cbdff6e59a39..632b4fd3e8fb 100644 --- a/docs/source/en/quantization/torchao.md +++ b/docs/source/en/quantization/torchao.md @@ -186,7 +186,6 @@ print(tokenizer.decode(output[0], skip_special_tokens=True)) ``` - ```py @@ -257,7 +256,6 @@ print(tokenizer.decode(output[0], skip_special_tokens=True)) ``` - ```py diff --git a/docs/source/en/run_scripts.md b/docs/source/en/run_scripts.md index cdf619b8d5e9..f51ee3a6dbaf 100644 --- a/docs/source/en/run_scripts.md +++ b/docs/source/en/run_scripts.md @@ -54,7 +54,7 @@ Start with a smaller dataset by including the `max_train_samples`, `max_eval_sam > Not all example scripts support the `max_predict_samples` parameter. Run the command below to check whether a script supports it or not. > > ```bash -> examples/pytorch/summarization/run_summarization.py -h +> python examples/pytorch/summarization/run_summarization.py -h > ``` The example below fine-tunes [T5-small](https://huggingface.co/google-t5/t5-small) on the [CNN/DailyMail](https://huggingface.co/datasets/abisee/cnn_dailymail) dataset. T5 requires an additional `source_prefix` parameter to prompt it to summarize. @@ -67,10 +67,11 @@ Resuming training from a checkpoint is very useful if training is interrupted be Share your model on the [Hub](https://huggingface.co/) with the `--push_to_hub` parameter. It creates a repository and uploads the model to the folder name specified in `--output_dir`. You could also use the `--push_to_hub_model_id` parameter to specify the repository name. +Drop the `max_train_samples`, `max_eval_samples`, and `max_predict_samples` parameters once everything works, and add `--resume_from_checkpoint path_to_specific_checkpoint` to resume from a checkpoint. + ```bash python examples/pytorch/summarization/run_summarization.py \ --model_name_or_path google-t5/t5-small \ - # remove the `max_train_samples`, `max_eval_samples` and `max_predict_samples` if everything works --max_train_samples 50 \ --max_eval_samples 50 \ --max_predict_samples 50 \ @@ -84,8 +85,7 @@ python examples/pytorch/summarization/run_summarization.py \ --per_device_eval_batch_size=4 \ --push_to_hub \ --push_to_hub_model_id finetuned-t5-cnn_dailymail \ - # --resume_from_checkpoint path_to_specific_checkpoint \ - --predict_with_generate \ + --predict_with_generate ``` For mixed precision and distributed training, include the following parameters and launch training with [torchrun](https://pytorch.org/docs/stable/elastic/run.html). diff --git a/docs/source/en/serialization.md b/docs/source/en/serialization.md index 9ec6439bcb0d..07412c29a746 100644 --- a/docs/source/en/serialization.md +++ b/docs/source/en/serialization.md @@ -73,7 +73,7 @@ optimum-cli export onnx --model Qwen/Qwen3-8B Qwen/Qwen3-8b-onnx/ Run the following command to view all available arguments or refer to the [Export a model to ONNX with optimum.exporters.onnx](https://huggingface.co/docs/optimum-onnx/onnx/usage_guides/export_a_model) guide for more details. ```bash -optimum cli export onnx --help +optimum-cli export onnx --help ``` To export a local model, save the weights and tokenizer files in the same directory. Pass the directory path to the `--model` argument and use the `--task` argument to specify the [task](https://huggingface.co/docs/optimum/exporters/task_manager#transformers). If you don't provide `--task`, the system auto-infers it from the model or uses an architecture without a task-specific head. @@ -104,7 +104,7 @@ from optimum.onnxruntime import ORTModelForCausalLM from transformers import AutoTokenizer ort_model = ORTModelForCausalLM.from_pretrained("Qwen/Qwen3-8b", export=True) -tokenizer = AutoTokenizer.from_pretrained("onnx/") +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8b") ort_model.save_pretrained("onnx/") tokenizer.save_pretrained("onnx/") diff --git a/docs/source/en/tasks/asr.md b/docs/source/en/tasks/asr.md index 21b8df1b3f37..7c85304732a0 100644 --- a/docs/source/en/tasks/asr.md +++ b/docs/source/en/tasks/asr.md @@ -188,7 +188,7 @@ Unlike other data collators, this specific data collator needs to apply a differ ... return batch ``` -Now instantiate your `DataCollatorForCTCWithPadding`: +Now instantiate your `DataCollatorCTCWithPadding`: ```py >>> data_collator = DataCollatorCTCWithPadding(processor=processor, padding="longest") diff --git a/docs/source/en/tasks/image_text_to_text.md b/docs/source/en/tasks/image_text_to_text.md index 29dc0624319c..9b13934f839a 100644 --- a/docs/source/en/tasks/image_text_to_text.md +++ b/docs/source/en/tasks/image_text_to_text.md @@ -169,6 +169,10 @@ outputs[0]["generated_text"] If you prefer, you can also load the images separately and pass them to the pipeline like so: ```python +import requests +from PIL import Image +from transformers import pipeline + pipe = pipeline("image-text-to-text", model="HuggingFaceTB/SmolVLM-256M-Instruct") img_urls = [ @@ -205,10 +209,12 @@ outputs[0]['input_text'] 'image': }, {'type': 'image', 'image': }, - {'type': 'text', 'text': 'What do you see in these images?'}]}]## Streaming + {'type': 'text', 'text': 'What do you see in these images?'}]}] """ ``` +## Streaming + We can use [text streaming](../generation_features#streaming) for a better generation experience. Transformers supports streaming with the [`TextStreamer`] or [`TextIteratorStreamer`] classes. We will use the [`TextIteratorStreamer`] with IDEFICS-8B. Assume we have an application that keeps chat history and takes in the new user input. We will preprocess the inputs as usual and initialize [`TextIteratorStreamer`] to handle the generation in a separate thread. This allows you to stream the generated text tokens in real-time. Any generation arguments can be passed to [`TextIteratorStreamer`]. @@ -318,7 +324,7 @@ messages = [ ] }, ] -inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device) +inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(quantized_model.device) input_len = len(inputs.input_ids[0]) with torch.no_grad(): diff --git a/docs/source/en/tasks/keypoint_matching.md b/docs/source/en/tasks/keypoint_matching.md index aa39dba9968a..a1b0a2ee43dc 100644 --- a/docs/source/en/tasks/keypoint_matching.md +++ b/docs/source/en/tasks/keypoint_matching.md @@ -28,7 +28,7 @@ from transformers import AutoImageProcessor, AutoModelForKeypointMatching import torch processor = AutoImageProcessor.from_pretrained("zju-community/matchanything_eloftr") -model = AutoModelForKeypointMatching.from_pretrained("zju-community/matchanything_eloftr")) +model = AutoModelForKeypointMatching.from_pretrained("zju-community/matchanything_eloftr") ``` Load two images that have the same object of interest. The second photo is taken a second apart, it's colors are edited, and it is further cropped and rotated. diff --git a/docs/source/en/tasks/masked_language_modeling.md b/docs/source/en/tasks/masked_language_modeling.md index f8dac82f051e..69b38e2396f6 100644 --- a/docs/source/en/tasks/masked_language_modeling.md +++ b/docs/source/en/tasks/masked_language_modeling.md @@ -26,7 +26,7 @@ require a good contextual understanding of an entire sequence. BERT is an exampl This guide will show you how to: -1. Finetune [DistilRoBERTa](https://huggingface.co/distilbert/distilroberta-base) on the [r/askscience](https://www.reddit.com/r/askscience/) subset of the [ELI5](https://huggingface.co/datasets/eli5) dataset. +1. Finetune [DistilRoBERTa](https://huggingface.co/distilbert/distilroberta-base) on the [r/askscience](https://www.reddit.com/r/askscience/) subset of the [ELI5](https://huggingface.co/datasets/dany0407/eli5_category) dataset. 2. Use your finetuned model for inference. @@ -51,12 +51,12 @@ We encourage you to log in to your Hugging Face account so you can upload and sh ## Load ELI5 dataset -Start by loading the first 5000 examples from the [ELI5-Category](https://huggingface.co/datasets/eli5_category) dataset with the 🤗 Datasets library. This'll give you a chance to experiment and make sure everything works before spending more time training on the full dataset. +Start by loading the first 5000 examples from the [ELI5-Category](https://huggingface.co/datasets/dany0407/eli5_category) dataset with the 🤗 Datasets library. This'll give you a chance to experiment and make sure everything works before spending more time training on the full dataset. ```py >>> from datasets import load_dataset ->>> eli5 = load_dataset("eli5_category", split="train[:5000]") +>>> eli5 = load_dataset("dany0407/eli5_category", split="train[:5000]") ``` Split the dataset's `train` split into a train and test set with the [`~datasets.Dataset.train_test_split`] method: diff --git a/docs/source/en/tasks/prompting.md b/docs/source/en/tasks/prompting.md index 4abfd836e0f8..c112128bb8ee 100644 --- a/docs/source/en/tasks/prompting.md +++ b/docs/source/en/tasks/prompting.md @@ -26,7 +26,7 @@ Try prompting a LLM to classify some text. When you create a prompt, it's import from transformers import pipeline import torch -pipeline = pipeline(task="text-generation", model="mistralai/Mistal-7B-Instruct-v0.1", dtype=torch.bfloat16, device_map="auto") +pipeline = pipeline(task="text-generation", model="mistralai/Mistral-7B-Instruct-v0.1", dtype=torch.bfloat16, device_map="auto") prompt = """Classify the text into neutral, negative or positive. Text: This movie is definitely one of my favorite movies of its kind. The interaction between respectable and morally strong characters is an ode to chivalry and the honor code amongst thieves and policemen. Sentiment: diff --git a/docs/source/en/tasks/sequence_classification.md b/docs/source/en/tasks/sequence_classification.md index c9804d72447d..becdab03a76e 100644 --- a/docs/source/en/tasks/sequence_classification.md +++ b/docs/source/en/tasks/sequence_classification.md @@ -238,6 +238,7 @@ Tokenize the text and return PyTorch tensors: Pass your inputs to the model and return the `logits`: ```py +>>> import torch >>> from transformers import AutoModelForSequenceClassification >>> model = AutoModelForSequenceClassification.from_pretrained("stevhliu/my_awesome_model") From ac3244569528944b9d5773cafea525cd8a8b63de Mon Sep 17 00:00:00 2001 From: Steven Liu <59462357+stevhliu@users.noreply.github.com> Date: Tue, 1 Sep 2026 15:50:49 +0000 Subject: [PATCH 019/996] [docs] Fix failing audio doctest (#48380) * fix * feedback --- docs/source/en/tasks/audio_text_to_text.md | 42 ++++++++++++---------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/docs/source/en/tasks/audio_text_to_text.md b/docs/source/en/tasks/audio_text_to_text.md index de5f0d0591c3..34f09d18fbe4 100644 --- a/docs/source/en/tasks/audio_text_to_text.md +++ b/docs/source/en/tasks/audio_text_to_text.md @@ -139,7 +139,7 @@ Create a data collator that processes audio-text pairs into the format expected ... "role": "user", ... "content": [ ... {"type": "text", "text": "Describe the audio."}, -... {"type": "audio", "audio": feature["audio"].get_all_samples().data}, +... {"type": "audio", "audio": feature["audio"].get_all_samples().data[0].numpy()}, ... ], ... }, ... { @@ -214,7 +214,7 @@ trainable params: 44,302,336 || all params: 8,311,517,696 || trainable%: 0.5330 ``` > [!TIP] -> [LoRA](https://huggingface.co/docs/peft/main/conceptual_guides/lora) significantly reduces memory usage and training time by only updating a small number of adapter parameters instead of the full model. This configuration targets the language model's attention and feed-forward layers while keeping the audio encoder frozen, making it possible to fine-tune on a single GPU. +> LoRA significantly reduces memory usage and training time by only updating a small number of adapter parameters instead of the full model. This configuration targets the language model's attention and feed-forward layers while keeping the audio encoder frozen, making it possible to fine-tune on a single GPU. ### Setup training @@ -300,7 +300,7 @@ Load an audio sample for inference: >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000)) >>> sample = next(iter(dataset)) >>> audio = sample["audio"] ->>> audio_array = audio.get_all_samples().data if hasattr(audio, "get_all_samples") else audio["array"] +>>> audio_array = audio.get_all_samples().data[0].numpy() if hasattr(audio, "get_all_samples") else audio["array"] ``` Prepare the input with a conversation format: @@ -337,25 +337,29 @@ Generate a response: ## Pipeline -You can also use the [`Pipeline`] API for quick inference. Pass the fine-tuned PEFT model directly to the pipeline: +For quick inference, use the [`Pipeline`] API with an `any-to-any` model. The example below uses [Voxtral](https://huggingface.co/mistralai/Voxtral-Mini-3B-2507), which accepts audio and text inputs and generates text. See the [any-to-any task guide](./any_to_any) for more examples. -```py ->>> from transformers import pipeline ->>> pipe = pipeline( -... "audio-text-to-text", -... model=model, -... processor=processor, -... ) ->>> result = pipe( -... audio_array, -... generate_kwargs={"max_new_tokens": 100}, -... ) ->>> print(result[0]["generated_text"]) -``` +```python +from transformers import pipeline -> [!TIP] -> For more advanced use cases like multi-turn conversations with audio, you can structure your messages with alternating user and assistant roles, similar to [image-text-to-text](./image_text_to_text) models. +pipe = pipeline("any-to-any", model="mistralai/Voxtral-Mini-3B-2507") +messages = [ + { + "role": "user", + "content": [ + { + "type": "audio", + "url": "https://huggingface.co/datasets/raushan-testing-hf/audio-test/resolve/main/glass-breaking-151256.mp3", + }, + {"type": "text", "text": "What do you hear in this audio?"}, + ], + }, +] + +outputs = pipe(text=messages, max_new_tokens=100, return_full_text=False) +print(outputs[0]["generated_text"]) +``` ## Further Reading From 57ddd708d56b03ec56a9b25a4236098ace9bdd56 Mon Sep 17 00:00:00 2001 From: Elad Segal Date: Wed, 2 Sep 2026 08:50:35 +0300 Subject: [PATCH 020/996] Support per-layer MTP configuration (#48264) * Support per-layer configuration in MTP masks * Add tests * mtp mask creation bug fix * slighty easier --------- Co-authored-by: Elad Segal <13485709+eladsegal@users.noreply.github.com> Co-authored-by: Cyril Vallez --- src/transformers/configuration_utils.py | 3 ++ src/transformers/modeling_layers.py | 10 +++-- tests/generation/test_utils.py | 37 +++++++++++++++++ .../heterogeneity/test_configuration_utils.py | 40 +++++++++++++++++++ 4 files changed, 86 insertions(+), 4 deletions(-) diff --git a/src/transformers/configuration_utils.py b/src/transformers/configuration_utils.py index 5e810b4ba81a..e58087e54905 100755 --- a/src/transformers/configuration_utils.py +++ b/src/transformers/configuration_utils.py @@ -1419,6 +1419,9 @@ def get_mtp_config(self) -> "PreTrainedConfig": if hasattr(text_config, "first_k_dense_replace"): text_config.first_k_dense_replace = 0 + # MTP uses independent per-layer overrides + text_config.per_layer_config = getattr(text_config, "mtp_per_layer_config", None) + return text_config diff --git a/src/transformers/modeling_layers.py b/src/transformers/modeling_layers.py index 34bff894c429..485b66a584d4 100644 --- a/src/transformers/modeling_layers.py +++ b/src/transformers/modeling_layers.py @@ -430,12 +430,13 @@ def create_masks_for_mtp_layer( self, layer_idx: int, inputs_embeds: torch.Tensor, mtp_cache: MtpCache, position_ids: torch.Tensor ): """ - Create the (potentially several) masks required for layer `layer_idx`. This relies on the `layer_type` - attribute of the mtp layer if any, otherwise simply create a causal mask for full attention. + Create the (potentially several) masks required for layer `layer_idx`. This relies on the `layer_types` from the MTP config + if defined, and otherwise uses full attention. """ # Note that `_assisted_decoding` raises on batch_size > 1, so there is no padding mask to add + layer_config = self.config.per_layer_config[layer_idx] if self.config.is_heterogeneous else self.config mask_kwargs = { - "config": self.config, + "config": layer_config, "inputs_embeds": inputs_embeds, "attention_mask": None, "past_key_values": mtp_cache, @@ -444,7 +445,8 @@ def create_masks_for_mtp_layer( "layer_idx": layer_idx, } - mtp_layer_type = getattr(self.layers[layer_idx], "layer_type", None) + mtp_layer_types = getattr(self.config, "layer_types", None) + mtp_layer_type = mtp_layer_types[layer_idx] if mtp_layer_types is not None else None masks = {} if mtp_layer_type is not None and mtp_layer_type in LAYER_PATTERN_TO_MASK_FUNCTION_MAPPING: mask_function = LAYER_PATTERN_TO_MASK_FUNCTION_MAPPING[mtp_layer_type] diff --git a/tests/generation/test_utils.py b/tests/generation/test_utils.py index e90768603a40..6d28ed58799b 100644 --- a/tests/generation/test_utils.py +++ b/tests/generation/test_utils.py @@ -87,6 +87,7 @@ LinearAttentionAndFullAttentionLayer, LinearAttentionAndSlidingWindowAttentionLayer, LinearAttentionLayer, + MtpCache, QuantoQuantizedLayer, StaticCache, ) @@ -3950,6 +3951,42 @@ def test_generated_length_assisted_generation(self): ) self.assertTrue(out.shape[-1] <= (input_length + 7)) + def test_mtp_mask_creation_uses_per_layer_config(self): + config = AutoConfig.for_model( + "llama", + hidden_size=16, + intermediate_size=32, + num_hidden_layers=2, + num_attention_heads=2, + num_key_value_heads=2, + head_dim=8, + vocab_size=32, + max_position_embeddings=16, + sliding_window=None, + ) + config.num_mtp_layers = 2 + config.layer_types = ["full_attention", "full_attention"] + config.mtp_layer_types = ["sliding_attention", "full_attention"] + config.mtp_per_layer_config = { + 0: {"sliding_window": 2}, + 1: {"sliding_window": None}, + } + config._attn_implementation = "eager" + main_model = AutoModelForCausalLM.from_config(config) + mtp_model = MtpModel(main_model, num_mtp_layers=2) + + inputs_embeds = torch.randn(1, 4, config.hidden_size) + position_ids = torch.arange(4).unsqueeze(0) + mtp_cache = MtpCache() + sliding_mask = mtp_model.create_masks_for_mtp_layer(0, inputs_embeds, mtp_cache, position_ids)[ + "attention_mask" + ] + full_mask = mtp_model.create_masks_for_mtp_layer(1, inputs_embeds, mtp_cache, position_ids)["attention_mask"] + + min_dtype = torch.finfo(inputs_embeds.dtype).min + torch.testing.assert_close(sliding_mask[0, 0, -1], torch.tensor([min_dtype, min_dtype, 0.0, 0.0])) + torch.testing.assert_close(full_mask[0, 0, -1], torch.zeros(4)) + @require_torch_multi_accelerator def test_mtp_use_correct_device_when_drafting(self): """Test that when drafting the new token, mtp puts it back on the correct same device as `input_ids`""" diff --git a/tests/heterogeneity/test_configuration_utils.py b/tests/heterogeneity/test_configuration_utils.py index 356d5d553e7b..6a9ddcb33da8 100644 --- a/tests/heterogeneity/test_configuration_utils.py +++ b/tests/heterogeneity/test_configuration_utils.py @@ -406,3 +406,43 @@ def test_per_layer_config_can_serialize_explicit_layer_overrides(self): "3": {"num_key_value_heads": 8}, }, ) + + +class TestMtpHeterogeneousConfig(unittest.TestCase): + def test_get_mtp_config_drops_main_model_per_layer_config_by_default(self): + config = _tiny_llama_config(per_layer_config={3: {"intermediate_size": 64}}) + config.num_mtp_layers = 2 + + mtp_config = config.get_mtp_config() + + self.assertEqual(mtp_config.num_hidden_layers, 2) + self.assertFalse(mtp_config.is_heterogeneous) + self.assertEqual(mtp_config.intermediate_size, object.__getattribute__(config, "intermediate_size")) + self.assertTrue(config.is_heterogeneous) + + def test_get_mtp_config_uses_independent_mtp_per_layer_config(self): + config = _tiny_llama_config(per_layer_config={3: {"intermediate_size": 64}}) + config.num_mtp_layers = 2 + config.mtp_per_layer_config = { + 0: {"intermediate_size": 80}, + 1: {"num_key_value_heads": 2}, + } + + mtp_config = config.get_mtp_config() + + self.assertTrue(mtp_config.is_heterogeneous) + self.assertEqual(mtp_config.num_hidden_layers, 2) + self.assertEqual(mtp_config.per_layer_config[0].intermediate_size, 80) + self.assertEqual( + mtp_config.per_layer_config[1].intermediate_size, + object.__getattribute__(config, "intermediate_size"), + ) + self.assertEqual(mtp_config.per_layer_config[1].num_key_value_heads, 2) + + def test_get_mtp_config_validates_overrides_against_mtp_layer_count(self): + config = _tiny_llama_config() + config.num_mtp_layers = 2 + config.mtp_per_layer_config = {2: {"intermediate_size": 80}} + + with self.assertRaisesRegex(ValueError, r"range \[0, 2\)"): + config.get_mtp_config() From 65f70d49d17b8e5d39d306861029ba7515cbafa9 Mon Sep 17 00:00:00 2001 From: "Wang, Yi" Date: Wed, 2 Sep 2026 13:53:25 +0800 Subject: [PATCH 021/996] Allow capturing only necessary hidden_states with capture_outputs (#48081) * [feat] Add selective hidden-state capture via output_hidden_states_layers. This PR extends the generic output-capturing hook so callers can request only specific hidden-state layers: outputs = model(..., output_hidden_states_layers=[1, 3]) When this argument is provided, hidden-state capture is enabled automatically, but tensors are only retained for the requested layer ids. Non-requested positions are kept as None placeholders so the existing indexing convention remains unchanged Signed-off-by: Wang, Yi A * update Signed-off-by: Wang, Yi A * add dflash case Signed-off-by: Wang, Yi A * format Signed-off-by: Wang, Yi A * fmt Signed-off-by: Wang, Yi A * remove unnecessary test Signed-off-by: Wang, Yi A * use a single kwarg * add general test --------- Signed-off-by: Wang, Yi A Co-authored-by: Cyril Vallez Co-authored-by: Cyril Vallez --- src/transformers/backbone_utils.py | 11 ++++ .../generation/candidate_generator.py | 6 +- .../models/colpali/modeling_colpali.py | 8 +-- src/transformers/models/dpt/modeling_dpt.py | 22 ++----- src/transformers/utils/output_capturing.py | 40 +++++++++++-- .../bridgetower/test_modeling_bridgetower.py | 4 ++ .../maskformer/test_modeling_maskformer.py | 4 ++ tests/test_modeling_common.py | 60 +++++++++++++++++++ 8 files changed, 125 insertions(+), 30 deletions(-) diff --git a/src/transformers/backbone_utils.py b/src/transformers/backbone_utils.py index 050c25e90b4f..7b5622fdbda0 100644 --- a/src/transformers/backbone_utils.py +++ b/src/transformers/backbone_utils.py @@ -173,6 +173,17 @@ def wrapper(self, *args, **kwargs): if not output_hidden_states: filtered_output_data = {k: v for k, v in output.items() if k != "hidden_states"} output = type(output)(**filtered_output_data) + elif isinstance(output_hidden_states, (list, tuple, set)): + capture_initial_hidden_state = getattr( + (self._can_record_outputs or {}).get("hidden_states"), "capture_initial_hidden_state", True + ) + # When using a list of layer indices, we never collect the first input, so we may need to start at the index 1 + collected_hidden_states = ( + output["hidden_states"][1:] if capture_initial_hidden_state else output["hidden_states"] + ) + output["hidden_states"] = [ + x if i in output_hidden_states else None for i, x in enumerate(collected_hidden_states) + ] return output return wrapper diff --git a/src/transformers/generation/candidate_generator.py b/src/transformers/generation/candidate_generator.py index 0a62d5a7c1e9..b251b7b975d6 100644 --- a/src/transformers/generation/candidate_generator.py +++ b/src/transformers/generation/candidate_generator.py @@ -1580,7 +1580,7 @@ class DFlashTokenCandidateGenerator(CandidateGenerator): """ requires_model_outputs: bool = True - # We always need to pass the hidden states at `draft_config.target_layer_ids` from the main model + # This will be overriden in the __init__ to capture only the required layer's hidden_states model_kwargs_overrides: dict[str, Any] = {"output_hidden_states": True} def __init__( @@ -1603,6 +1603,8 @@ def __init__( # Get the layers used to obtain the intermediate hidden_states from main model, and prepare the diffusion window ids tensor self.target_layer_ids = assistant_model.config.target_layer_ids + # Override to capture only those specific layers + self.model_kwargs_overrides = {"output_hidden_states": self.target_layer_ids} self.block_size = assistant_model.config.block_size self.mask_token_id = assistant_model.config.mask_token_id self.noise_ids_mask = torch.tensor([self.mask_token_id] * (self.block_size - 1))[None, ...] @@ -1668,7 +1670,7 @@ def get_candidates( # hidden states of only accepted tokens thus crop out the rest context_hidden_states: torch.Tensor = torch.cat( [ - model_outputs.hidden_states[i + 1][:, :num_last_main_model_tokens].to(self.device) + model_outputs.hidden_states[i][:, :num_last_main_model_tokens].to(self.device) for i in self.target_layer_ids ], dim=-1, diff --git a/src/transformers/models/colpali/modeling_colpali.py b/src/transformers/models/colpali/modeling_colpali.py index 7d63585183c5..b773dd973700 100644 --- a/src/transformers/models/colpali/modeling_colpali.py +++ b/src/transformers/models/colpali/modeling_colpali.py @@ -20,6 +20,7 @@ from transformers import AutoModel +from ...backbone_utils import filter_output_hidden_states from ...cache_utils import Cache from ...modeling_utils import PreTrainedModel from ...processing_utils import Unpack @@ -106,6 +107,7 @@ def __init__(self, config: ColPaliConfig): @can_return_tuple @auto_docstring + @filter_output_hidden_states def forward( self, input_ids: torch.LongTensor | None = None, @@ -115,18 +117,14 @@ def forward( ) -> ColPaliForRetrievalOutput: if pixel_values is not None: pixel_values = pixel_values.to(dtype=self.dtype) - output_hidden_states = kwargs.pop("output_hidden_states", None) - if output_hidden_states is None: - output_hidden_states = self.config.output_hidden_states vlm_output = self.vlm( input_ids=input_ids, attention_mask=attention_mask, pixel_values=pixel_values, - output_hidden_states=True, **kwargs, ) - vlm_hidden_states = vlm_output.hidden_states if output_hidden_states else None + vlm_hidden_states = vlm_output.hidden_states vlm_image_hidden_states = vlm_output.image_hidden_states if pixel_values is not None else None last_hidden_states = vlm_output[0] # (batch_size, sequence_length, hidden_size) diff --git a/src/transformers/models/dpt/modeling_dpt.py b/src/transformers/models/dpt/modeling_dpt.py index ea09034ee0b1..ee642391999e 100755 --- a/src/transformers/models/dpt/modeling_dpt.py +++ b/src/transformers/models/dpt/modeling_dpt.py @@ -28,7 +28,7 @@ from ... import initialization as init from ...activations import ACT2FN -from ...backbone_utils import load_backbone +from ...backbone_utils import filter_output_hidden_states, load_backbone from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutput, DepthEstimatorOutput, SemanticSegmenterOutput from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel @@ -941,6 +941,7 @@ def __init__(self, config): @can_return_tuple @auto_docstring + @filter_output_hidden_states def forward( self, pixel_values: torch.FloatTensor, @@ -989,13 +990,6 @@ def forward( if labels is not None: raise NotImplementedError("Training is not implemented yet") - # Internally the model always needs to output hidden states, we control the output - # per user request on the final output - user_requested_hidden_states = kwargs.get("output_hidden_states") or getattr( - self.config, "output_hidden_states", False - ) - kwargs["output_hidden_states"] = True - if self.backbone is not None: outputs = self.backbone.forward_with_filtered_kwargs(pixel_values, **kwargs) hidden_states = outputs.feature_maps @@ -1030,7 +1024,7 @@ def forward( return DepthEstimatorOutput( loss=loss, predicted_depth=predicted_depth, - hidden_states=outputs.hidden_states if user_requested_hidden_states else None, + hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @@ -1094,6 +1088,7 @@ def __init__(self, config: DPTConfig): @can_return_tuple @auto_docstring + @filter_output_hidden_states def forward( self, pixel_values: torch.FloatTensor | None = None, @@ -1127,13 +1122,6 @@ def forward( if labels is not None and self.config.num_labels == 1: raise ValueError("The number of labels should be greater than one") - # Internally the model always needs to output hidden states, we control the output - # per user request on the final output - user_requested_hidden_states = kwargs.get("output_hidden_states") or getattr( - self.config, "output_hidden_states", False - ) - kwargs["output_hidden_states"] = True - outputs: BaseModelOutputWithPoolingAndIntermediateActivations = self.dpt(pixel_values, **kwargs) hidden_states = outputs.hidden_states @@ -1177,7 +1165,7 @@ def forward( return SemanticSegmenterOutput( loss=loss, logits=logits, - hidden_states=outputs.hidden_states if user_requested_hidden_states else None, + hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) diff --git a/src/transformers/utils/output_capturing.py b/src/transformers/utils/output_capturing.py index 7dc3e2f33894..6cf4c00df4a7 100644 --- a/src/transformers/utils/output_capturing.py +++ b/src/transformers/utils/output_capturing.py @@ -109,8 +109,27 @@ def output_capturing_hook(module, args, output): if collected_outputs is None or key not in collected_outputs.keys(): return - if capture_initial_hidden_state and key == "hidden_states" and len(collected_outputs[key]) == 0: + # Optionally capture only some layer's hidden_states + hidden_states_layers = collected_outputs.get("_hidden_states_layers") + + # Historically, the first hidden_states output is actually the input of layer 0 (or inputs_embeds), so the hidden_states outputs + # have length `num_hidden_layers + 1`. When we request a list of explicit layers to capture, do not add this into the result, so + # that the indexing of the output is the same as the actual requested layers + if ( + capture_initial_hidden_state + and key == "hidden_states" + and len(collected_outputs[key]) == 0 + and hidden_states_layers is None + ): collected_outputs[key].append(args[0]) + + # If we are capturing only some layer's hidden_states, skip capture if not part of the requested indices + if key == "hidden_states" and hidden_states_layers is not None: + current_layer_idx = len(collected_outputs[key]) + if current_layer_idx not in hidden_states_layers: + collected_outputs[key].append(None) + return + if not isinstance(output, tuple): collected_outputs[key].append(output) elif output[index] is not None: @@ -221,10 +240,9 @@ def capture_outputs(func=None, *, tie_last_hidden_states=True): Args: tie_last_hidden_states (`bool`, *optional*, defaults to `True`): - Whether to overwrite `out.hidden_states[-1]` with the `out.last_hidden_state`. - This is true for all language models and should be toggled off only if - `out.hidden_states[-1]` has to be the hidden state before last layer norm, which - is needed for some vision models (e.g. CLIP, SigLIP) + Whether to overwrite `out.hidden_states[-1]` with the `out.last_hidden_state`. This is true for all language models + and should be toggled off only if `out.hidden_states[-1]` has to be the hidden state before last layer norm, which + is needed for some vision models (e.g. CLIP, SigLIP). """ def wrapped_fn(func): @@ -251,6 +269,12 @@ def wrapper(self, *args, **kwargs): ) collected_outputs = {k.replace("output_", ""): [] for k, v in recordable_keys.items() if v} + # We accept a list of layer indices as `output_hidden_states`, to capture only specific layer outputs - in this case + # we need to add the layers to the `collected_outputs`'s dict to tell the hook which ones we need + if "output_hidden_states" in recordable_keys and isinstance( + recordable_keys["output_hidden_states"], (list, tuple, set) + ): + collected_outputs["_hidden_states_layers"] = set(recordable_keys["output_hidden_states"]) # Make sure hooks are installed if we need to collect outputs if len(collected_outputs) > 0: maybe_install_capturing_hooks(self) @@ -264,10 +288,14 @@ def wrapper(self, *args, **kwargs): finally: _active_collector.reset(output_token) + hidden_states_layers = collected_outputs.pop("_hidden_states_layers", None) # Inject collected outputs into model output (return everything as tuples for BC) for key in collected_outputs: if key == "hidden_states": - if not tie_last_hidden_states: + # If we specifically don't tie, or did not capture the last layer, do nothing + if not tie_last_hidden_states or ( + hidden_states_layers is not None and collected_outputs[key][-1] is None + ): pass elif hasattr(outputs, "vision_hidden_states"): collected_outputs[key] = collected_outputs[key][:-1] diff --git a/tests/models/bridgetower/test_modeling_bridgetower.py b/tests/models/bridgetower/test_modeling_bridgetower.py index 9250b96bf235..8a672c93187f 100644 --- a/tests/models/bridgetower/test_modeling_bridgetower.py +++ b/tests/models/bridgetower/test_modeling_bridgetower.py @@ -446,6 +446,10 @@ def test_inputs_embeds(self): def test_inputs_embeds_matches_input_ids(self): pass + @unittest.skip(reason="hidden states are concatenated as 3 tuples of text/image/cross") + def test_can_capture_specific_layers_hidden_states(self): + pass + # We will verify our results on an image of cute cats def prepare_img(): diff --git a/tests/models/maskformer/test_modeling_maskformer.py b/tests/models/maskformer/test_modeling_maskformer.py index 430d728727bc..cf291103f32e 100644 --- a/tests/models/maskformer/test_modeling_maskformer.py +++ b/tests/models/maskformer/test_modeling_maskformer.py @@ -489,6 +489,10 @@ def test_backbone_selection(self): elif model.__class__.__name__ == "MaskFormerForUniversalSegmentation": self.assertEqual(model.model.pixel_level_module.encoder.out_indices, [1, 2, 3]) + @unittest.skip(reason="hidden states are concatenated weirdly inside the model") + def test_can_capture_specific_layers_hidden_states(self): + pass + TOLERANCE = 2e-4 diff --git a/tests/test_modeling_common.py b/tests/test_modeling_common.py index 7b0e294fda2d..b9e52733facc 100644 --- a/tests/test_modeling_common.py +++ b/tests/test_modeling_common.py @@ -5814,6 +5814,66 @@ def test_format_of_can_record_outputs(self): is_valid_recorder = isinstance(recorder, (str, type, OutputRecorder)) self.assertTrue(is_valid_recorder, f"Invalid recorder: {recorder}") + def test_can_capture_specific_layers_hidden_states(self): + """ + Test that we can capture only a subset of the hidden states with `output_hidden_states`. + """ + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + # Each individual model is a subtest + with self.subTest(model_class.__name__): + model = model_class(copy.deepcopy(config)).to(device=torch_device) + model.eval() + + can_set_hidden_states_layers = any( + "hidden_states" in (module._can_record_outputs or {}) + and not isinstance(module._can_record_outputs["hidden_states"], list) + for module in model.modules() + if isinstance(module, PreTrainedModel) + ) + if not can_set_hidden_states_layers: + self.skipTest( + "Cannot capture hidden states, or cannot correctly set layer indices due to several classes capturing at the same time" + ) + + # Prepare inputs + inputs = self._prepare_for_class(inputs_dict, model_class) + + # Despite the previous skip based on decorators, some models do not propagate the outputs correctly....... + out = model(**inputs, output_hidden_states=True) + if "hidden_states" in out: + hidden_states = out.hidden_states + elif "text_model_output" in out and "hidden_states" in out.text_model_output: + hidden_states = out.text_model_output.hidden_states + else: + self.skipTest( + f"{model_class.__name__} does not propagate hidden states correctly or uses another name" + ) + + skips_first_input = any( + not module._can_record_outputs["hidden_states"].capture_initial_hidden_state + for module in model.modules() + if isinstance(module, PreTrainedModel) + and hasattr( + (module._can_record_outputs or {}).get("hidden_states", None), "capture_initial_hidden_state" + ) + ) + N_layers = len(hidden_states) if skips_first_input else len(hidden_states) - 1 + # Capture one every 2 layers + indices_to_capture = list(range(0, N_layers, 2)) + out = model(**inputs, output_hidden_states=indices_to_capture) + + hidden_states = out.hidden_states if "hidden_states" in out else out.text_model_output.hidden_states + # hidden_states = out.hidden_states + # We should have the same number of captured hidden_states, i.e. we do not add the first input + self.assertEqual(len(hidden_states), N_layers) + # assert we correctly captured the layers + self.assertTrue(all(hidden_states[i] is None for i in range(N_layers) if i not in indices_to_capture)) + self.assertTrue( + all(isinstance(hidden_states[i], torch.Tensor) for i in range(N_layers) if i in indices_to_capture) + ) + @require_kernels @require_torch_accelerator def test_kernels_can_load_without_crashing(self): From c5ff582c156ff1c1f870a40e34fd98aa781247c5 Mon Sep 17 00:00:00 2001 From: Cyril Vallez Date: Wed, 2 Sep 2026 15:45:13 +0900 Subject: [PATCH 022/996] [MTP] Save memory by only capturing the last layer's hidden_states (#48475) capture only last --- src/transformers/generation/candidate_generator.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/transformers/generation/candidate_generator.py b/src/transformers/generation/candidate_generator.py index b251b7b975d6..44e19fe7cdc4 100644 --- a/src/transformers/generation/candidate_generator.py +++ b/src/transformers/generation/candidate_generator.py @@ -1422,7 +1422,8 @@ def get_candidates( class MTPCandidateGenerator(AssistedCandidateGenerator): requires_model_outputs: bool = True - # We always need to pass the hidden states from the main model + # We always need to pass the hidden states from the main model - it will be overriden in the __init__ to capture only the + # last layer's hidden_states model_kwargs_overrides: dict[str, Any] = {"output_hidden_states": True} def __init__( @@ -1442,6 +1443,10 @@ def __init__( "mtp weights." ) + # Override to capture only the last main model's layer to save memory + last_layer_idx = main_model.config.get_text_config().num_hidden_layers - 1 + self.model_kwargs_overrides = {"output_hidden_states": [last_layer_idx]} + # Heuristic: use the device of the last layer of the main model for the MTP layers base_model = main_model.get_decoder() self.device = next(x.device for x in base_model.layers[-1].parameters()) # type: ignore From 7c65cdb570646e8b01cc30d069579f2f4b60c398 Mon Sep 17 00:00:00 2001 From: Cyril Vallez Date: Wed, 2 Sep 2026 15:46:30 +0900 Subject: [PATCH 023/996] Remove deprecated mask functions (#48476) remove deprecated functions --- src/transformers/modeling_utils.py | 110 +---------------------------- 1 file changed, 1 insertion(+), 109 deletions(-) diff --git a/src/transformers/modeling_utils.py b/src/transformers/modeling_utils.py index ded5825dddc1..3bbd2b3b46d5 100644 --- a/src/transformers/modeling_utils.py +++ b/src/transformers/modeling_utils.py @@ -38,7 +38,7 @@ from safetensors import safe_open from safetensors.torch import load as _safe_load_bytes from safetensors.torch import save_file as safe_save_file -from torch import Tensor, nn +from torch import nn from torch.autograd.graph import save_on_cpu from torch.distributions import constraints from torch.utils.checkpoint import checkpoint @@ -916,114 +916,6 @@ def dtype(self: "PreTrainedModel") -> torch.dtype: """ return next(param.dtype for param in self.parameters() if param.is_floating_point()) - def invert_attention_mask(self: "PreTrainedModel", encoder_attention_mask: Tensor) -> Tensor: - """ - Invert an attention mask (e.g., switches 0. and 1.). - - Args: - encoder_attention_mask (`torch.Tensor`): An attention mask. - - Returns: - `torch.Tensor`: The inverted attention mask. - """ - logger.warning_once( - "Detected the usage of `invert_attention_mask`: This function is deprecated and will be removed in v5.12.0. " - "Please use the new API in `transformers.masking_utils`" - ) - - if encoder_attention_mask.dim() == 3: - encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :] - if encoder_attention_mask.dim() == 2: - encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :] - # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition - # encoder_extended_attention_mask = (encoder_extended_attention_mask == - # encoder_extended_attention_mask.transpose(-1, -2)) - encoder_extended_attention_mask = encoder_extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility - encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * torch.finfo(self.dtype).min - - return encoder_extended_attention_mask - - @staticmethod - def create_extended_attention_mask_for_decoder(input_shape, attention_mask): - logger.warning_once( - "Detected the usage of `create_extended_attention_mask_for_decoder`: This function is deprecated and will be removed in v5.12.0. " - "Please use the new API in `transformers.masking_utils`" - ) - - device = attention_mask.device - batch_size, seq_length = input_shape - seq_ids = torch.arange(seq_length, device=device) - causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None] - # in case past_key_values are used we need to add a prefix ones mask to the causal mask - causal_mask = causal_mask.to(attention_mask.dtype) - - if causal_mask.shape[1] < attention_mask.shape[1]: - prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1] - causal_mask = torch.cat( - [ - torch.ones((batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype), - causal_mask, - ], - dim=-1, - ) - - extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :] - return extended_attention_mask - - def get_extended_attention_mask( - self: "PreTrainedModel", - attention_mask: Tensor, - input_shape: tuple[int, ...], - dtype: torch.dtype | None = None, - ) -> Tensor: - """ - Makes broadcastable attention and causal masks so that future and masked tokens are ignored. - - Arguments: - attention_mask (`torch.Tensor`): - Mask with ones indicating tokens to attend to, zeros for tokens to ignore. - input_shape (`tuple[int]`): - The shape of the input to the model. - - Returns: - `torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`. - """ - logger.warning_once( - "Detected the usage of `get_extended_attention_mask`: This function is deprecated and will be removed in v5.12.0. " - "Please use the new API in `transformers.masking_utils`" - ) - - if dtype is None: - dtype = self.dtype - - # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] - # ourselves in which case we just need to make it broadcastable to all heads. - if attention_mask.dim() == 3: - extended_attention_mask = attention_mask[:, None, :, :] - elif attention_mask.dim() == 2: - # Provided a padding mask of dimensions [batch_size, seq_length] - # - if the model is a decoder, apply a causal mask in addition to the padding mask - # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length] - if getattr(self.config, "is_decoder", None): - extended_attention_mask = ModuleUtilsMixin.create_extended_attention_mask_for_decoder( - input_shape, attention_mask - ) - else: - extended_attention_mask = attention_mask[:, None, None, :] - else: - raise ValueError( - f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})" - ) - - # Since attention_mask is 1.0 for positions we want to attend and 0.0 for - # masked positions, this operation will create a tensor which is 0.0 for - # positions we want to attend and the dtype's smallest value for masked positions. - # Since we are adding it to the raw scores before the softmax, this is - # effectively the same as removing these entirely. - extended_attention_mask = extended_attention_mask.to(dtype=dtype) # fp16 compatibility - extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(dtype).min - return extended_attention_mask - def num_parameters(self: "PreTrainedModel", only_trainable: bool = False, exclude_embeddings: bool = False) -> int: """ Get number of (optionally, trainable or non-embeddings) parameters in the module. From e15d467466e5cef29b16340887918dfd40c94dbe Mon Sep 17 00:00:00 2001 From: Cyril Vallez Date: Wed, 2 Sep 2026 16:34:07 +0900 Subject: [PATCH 024/996] Fix rotary embedding regression (#48477) * recurrent gemma * pp * fix --- .../models/pp_doclayout_v2/modeling_pp_doclayout_v2.py | 2 +- .../models/pp_doclayout_v2/modular_pp_doclayout_v2.py | 2 +- .../models/recurrent_gemma/modeling_recurrent_gemma.py | 7 ++++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py b/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py index 409e36ab169e..1d0e460b9fd0 100644 --- a/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py +++ b/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py @@ -795,7 +795,7 @@ def _init_weights(self, module): init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1))) if isinstance(module, PPDocLayoutV2PositionRelationEmbedding): inv_freq, _ = module.compute_default_rope_parameters(module.config) - module.register_buffer("inv_freq", inv_freq, persistent=False) + init.copy_(module.inv_freq, inv_freq) @auto_docstring( diff --git a/src/transformers/models/pp_doclayout_v2/modular_pp_doclayout_v2.py b/src/transformers/models/pp_doclayout_v2/modular_pp_doclayout_v2.py index a1e37f728f34..802a82d98040 100644 --- a/src/transformers/models/pp_doclayout_v2/modular_pp_doclayout_v2.py +++ b/src/transformers/models/pp_doclayout_v2/modular_pp_doclayout_v2.py @@ -636,7 +636,7 @@ def _init_weights(self, module): init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1))) if isinstance(module, PPDocLayoutV2PositionRelationEmbedding): inv_freq, _ = module.compute_default_rope_parameters(module.config) - module.register_buffer("inv_freq", inv_freq, persistent=False) + init.copy_(module.inv_freq, inv_freq) @auto_docstring( diff --git a/src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py b/src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py index e4327b07fb67..c06c5be574c0 100644 --- a/src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py +++ b/src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py @@ -62,9 +62,7 @@ def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.eps}" -# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->RecurrentGemma class RecurrentGemmaRotaryEmbedding(nn.Module): - # Ignore copy def __init__(self, config: RecurrentGemmaConfig, device=None): super().__init__() self.config = config @@ -95,7 +93,9 @@ def compute_default_rope_parameters( post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ base = config.rope_parameters["rope_theta"] - dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0) + head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + dim = int(head_dim * partial_rotary_factor) attention_factor = 1.0 # Unused in this type of RoPE # Compute the inverse frequencies @@ -104,6 +104,7 @@ def compute_default_rope_parameters( @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) + # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding.forward with Llama->RecurrentGemma def forward(self, x, position_ids): inv_freq_expanded = ( self.inv_freq[None, :, None].expand(position_ids.shape[0], -1, 1).to(dtype=torch.float, device=x.device) From 58d5a2b70ebf594ce312ba0d154edfd64ad6acde Mon Sep 17 00:00:00 2001 From: jiqing-feng Date: Wed, 2 Sep 2026 11:23:22 +0000 Subject: [PATCH 025/996] Fix VoxtralRealtime rejecting non-static cache implementations (#48082) * Fix VoxtralRealtime rejecting non-static cache implementations `_prepare_cache_for_generation` is overridden only to pre-allocate a `StaticCache` for the audio encoder, but it also raised on any `cache_implementation` that is not static. This was inconsistent: the default (`cache_implementation=None`) already goes through a `DynamicCache`, lazily created by the encoder, and produces the exact same output as the static path. Explicitly asking for `"dynamic"` (or `"offloaded"`) therefore failed for no reason. Only pre-allocate the encoder cache for static implementations and let the generic `generate` logic handle the rest, so unsupported combinations are reported by the framework instead of a model-level allowlist. Also fix the `test_generate_with_quant_cache` skip reason: quantized cache is unsupported because the model uses sliding attention layers. * Drop the offloaded cache from the new generation test `offloaded` follows the exact same code path as `dynamic` here (no pre-allocation, the encoder lazily creates its own `DynamicCache`), so it added no coverage while requiring an accelerator: `Cache.__init__` builds a prefetch stream upfront, which fails on CPU-only runners. * Address review: mark generate test and rely on generic quant cache skip - add `@pytest.mark.generate` to `test_generate_with_cache_implementation` - drop the model-level `test_generate_with_quant_cache` skip and make the generic skip in `GenerationTesterMixin` use `get_layer_types_and_kwargs`, the same helper `QuantizedCache` uses, so models that only set `sliding_window` (without an explicit `layer_types`) are skipped too --- .../modeling_voxtral_realtime.py | 16 ++++++------- .../modular_voxtral_realtime.py | 16 ++++++------- tests/generation/test_utils.py | 5 +++- .../test_modeling_voxtral_realtime.py | 23 ++++++++++++++----- 4 files changed, 35 insertions(+), 25 deletions(-) diff --git a/src/transformers/models/voxtral_realtime/modeling_voxtral_realtime.py b/src/transformers/models/voxtral_realtime/modeling_voxtral_realtime.py index e3abf0c60b9b..ef57aaaca516 100644 --- a/src/transformers/models/voxtral_realtime/modeling_voxtral_realtime.py +++ b/src/transformers/models/voxtral_realtime/modeling_voxtral_realtime.py @@ -1215,15 +1215,13 @@ def _prepare_cache_for_generation( # NOTE: we use the encoder prefix here this is not a classical encoder-decoder model - no cross-attention # the model is better seen as a VLM/ AudioLM, so with an encoder that can take psat_key_values for it's forward pass - if generation_config.cache_implementation is not None: - if generation_config.cache_implementation in ("static", "offloaded_static"): - model_kwargs["encoder_past_key_values"] = self._get_encoder_cache( - cache_implementation=generation_config.cache_implementation, - batch_size=batch_size, - max_cache_len=self.config.audio_config.sliding_window, - ) - else: - raise ValueError(f"{generation_config.cache_implementation} is not supported for VoxtralRealtime") + # Only static caches need pre-allocation here: dynamic ones are lazily initialized by the encoder itself. + if generation_config.cache_implementation in ("static", "offloaded_static"): + model_kwargs["encoder_past_key_values"] = self._get_encoder_cache( + cache_implementation=generation_config.cache_implementation, + batch_size=batch_size, + max_cache_len=self.config.audio_config.sliding_window, + ) def _get_encoder_cache(self, cache_implementation: str, batch_size: int, max_cache_len: int) -> Cache: offload_cache = "offloaded" in cache_implementation diff --git a/src/transformers/models/voxtral_realtime/modular_voxtral_realtime.py b/src/transformers/models/voxtral_realtime/modular_voxtral_realtime.py index 22db189aedef..f80dd13daccf 100644 --- a/src/transformers/models/voxtral_realtime/modular_voxtral_realtime.py +++ b/src/transformers/models/voxtral_realtime/modular_voxtral_realtime.py @@ -828,15 +828,13 @@ def _prepare_cache_for_generation( # NOTE: we use the encoder prefix here this is not a classical encoder-decoder model - no cross-attention # the model is better seen as a VLM/ AudioLM, so with an encoder that can take psat_key_values for it's forward pass - if generation_config.cache_implementation is not None: - if generation_config.cache_implementation in ("static", "offloaded_static"): - model_kwargs["encoder_past_key_values"] = self._get_encoder_cache( - cache_implementation=generation_config.cache_implementation, - batch_size=batch_size, - max_cache_len=self.config.audio_config.sliding_window, - ) - else: - raise ValueError(f"{generation_config.cache_implementation} is not supported for VoxtralRealtime") + # Only static caches need pre-allocation here: dynamic ones are lazily initialized by the encoder itself. + if generation_config.cache_implementation in ("static", "offloaded_static"): + model_kwargs["encoder_past_key_values"] = self._get_encoder_cache( + cache_implementation=generation_config.cache_implementation, + batch_size=batch_size, + max_cache_len=self.config.audio_config.sliding_window, + ) def _get_encoder_cache(self, cache_implementation: str, batch_size: int, max_cache_len: int) -> Cache: offload_cache = "offloaded" in cache_implementation diff --git a/tests/generation/test_utils.py b/tests/generation/test_utils.py index 6d28ed58799b..f769fe9ddd1b 100644 --- a/tests/generation/test_utils.py +++ b/tests/generation/test_utils.py @@ -90,6 +90,7 @@ MtpCache, QuantoQuantizedLayer, StaticCache, + get_layer_types_and_kwargs, ) from transformers.generation import ( CompileConfig, @@ -1574,7 +1575,9 @@ def test_generate_with_quant_cache(self): if config.is_encoder_decoder or not model_class._supports_default_dynamic_cache(): self.skipTest(reason="This model does not support the quantized cache format") - layer_types = getattr(config.get_text_config(), "layer_types", None) or [] + # Same source of truth as `QuantizedCache`: models that don't set `layer_types` explicitly still + # infer non-full attention from e.g. `sliding_window`. + layer_types, _ = get_layer_types_and_kwargs(config.get_text_config(decoder=True)) if any(layer_type != "full_attention" for layer_type in layer_types): self.skipTest(reason="`QuantizedCache` is only supported for models with full attention layers") diff --git a/tests/models/voxtral_realtime/test_modeling_voxtral_realtime.py b/tests/models/voxtral_realtime/test_modeling_voxtral_realtime.py index ff2113a4556f..d6831515f197 100644 --- a/tests/models/voxtral_realtime/test_modeling_voxtral_realtime.py +++ b/tests/models/voxtral_realtime/test_modeling_voxtral_realtime.py @@ -19,6 +19,7 @@ from threading import Thread import numpy as np +import pytest from parameterized import parameterized from transformers import ( @@ -260,17 +261,27 @@ def test_left_padding_compatibility(self): def test_multi_gpu_data_parallel_forward(self): pass - @unittest.skip( - reason="VoxtralRealtime only supports static and offloaded_static cache implementations, not quantized cache" - ) - def test_generate_with_quant_cache(self): - pass - @parameterized.expand([("linear",), ("dynamic",), ("yarn",)]) @unittest.skip("Model needs special input preparation!") def test_model_rope_scaling_from_config(self, scaling_type): pass + @pytest.mark.generate + @parameterized.expand([("dynamic",), ("static",)]) + def test_generate_with_cache_implementation(self, cache_implementation): + """Any `cache_implementation` should match the default one, which already uses a `DynamicCache`.""" + config, inputs_dict = self.prepare_config_and_inputs_for_generate() + model = VoxtralRealtimeForConditionalGeneration(config).to(torch_device).eval() + + generation_kwargs = { + "max_new_tokens": self.max_new_tokens, + "do_sample": False, + "use_cache": True, + } + expected = model.generate(**inputs_dict, **generation_kwargs) + output = model.generate(**inputs_dict, **generation_kwargs, cache_implementation=cache_implementation) + torch.testing.assert_close(output, expected) + @require_torch class VoxtralRealtimeForConditionalGenerationIntegrationTest(unittest.TestCase): From e84aa52cbd5ee7341a80774ea4cbc96e1f0e3cab Mon Sep 17 00:00:00 2001 From: "sergereview[bot]" <283583894+sergereview[bot]@users.noreply.github.com> Date: Wed, 2 Sep 2026 11:39:03 +0000 Subject: [PATCH 026/996] [serge] Fix 1 integration tests regressed by commit bd9509355c8a (PR #47493) (#48426) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [serge] Fix 1 integration tests regressed by commit bd9509355c8a (PR #47493) * Say why force_cpu is set here, and point at the precedent The PR body claimed this matched "the existing pattern used for oversized concatenations" without saying where that pattern is. It does exist — exactly once, on qwen4_exp_text's ngram_embedding converter further down this file — but a reader had to grep for it, and that precedent carries a comment explaining itself while these two copies carried none. Names the mechanism, points at both the sibling converter and core_model_loading.convert_and_load_state_dict_in_model where force_cpu is actually applied, and records the caveat the PR body omitted: it is a no-op under tp_plan, which shards before converting. Also notes why the second converter qualifies. Its operations are [MergeModulelist(dim=0)] with no Concatenate, so "oversized concatenations" does not literally describe it — MergeModulelist merges every expert's w2 into one tensor and takes the same temporary buffer. Comments only; no behaviour change. * Reserve device headroom with max_memory instead of patching the loader Reverts the `force_cpu=True` change to `conversion_mapping.py`. That flag is for EXTREME single-parameter cases — it was added for qwen4, whose ngram embedding is ~50B parameters, ~100 GiB in one tensor — and phimoe's parameters are ordinary. Setting it there would also have changed conversion for every user of the model, in production, to make one CI runner pass. The cause is on the test side. `device_map="auto"` plans against each device's full capacity, so the placement consumes the room the loader still needs: merging the per-expert w1/w3 weights into the fused gate_up_proj allocates a temporary buffer on the device the parameter is being placed on, and that is what OOMs inside from_pretrained. Restricting per-device memory is what `max_memory` is for. The previous `cap_psutil_cpu_memory` cap could not do it — it only steers how much goes to CPU/disk — and it scaled *up* with accelerator count, so it was loosest on the multi-GPU configuration where this test actually failed. Reserves ~15% of each accelerator and keeps an explicit CPU budget, so `auto` still offloads what does not fit. * Name the real cause: get_balanced_memory reserves nothing on multi-GPU Replaces the previous max_memory revision with a better-diagnosed one, found by replaying this failure through the new prompt harness. `get_balanced_memory` applies its 10% safety margin only when a SINGLE accelerator is visible — `max_memory[key] *= 0.9` sits inside `if num_devices == 1`. With several devices it hands each its full capacity, so Phi-3.5-MoE (~78 GiB in bf16) lands entirely on 4 x 22.30 GiB with nothing spilled, and GPU 0 is at ~21.5/22.30 when the phimoe WeightConverter merges the experts' w1/w3 into gate_up_proj — a torch.cat needing a ~1.7 GiB temporary per layer. That is also why only the multi-gpu variant fails: single-gpu does get the 0.9 margin and spills to CPU. Also records why the previous mitigation never fired. cap_psutil_cpu_memory(60 GiB x num_accelerators) is a double no-op here: patch_psutil_cpu_memory computes min(mem.total, limit), so a 240 GiB "cap" changes nothing on this runner, and a CPU-side budget cannot create accelerator headroom in any case. Budget 80% of each accelerator via the existing get_accelerator_total_memory_gib helper, preserve #48290's 60 GiB x n CPU budget by passing it as max_memory through the supported API rather than by lying to psutil, and keep offload_folder for the disk tier. Stays None when no accelerator reports memory. * Read each device directly: the tidier budget was a silent no-op The previous revision derived the per-device budget from `get_accelerator_total_memory_gib()` and guarded it with `if num_accelerators > 0 and total_accelerator_memory > 0`, falling back to `max_memory=None`. That helper returns 0.0 whenever `torch_device` is not exactly "cuda"/"xpu", so the guard fell through and the patch set no budget at all. It verified `not_fixed` on GPU (5 runs per tree) with 20.24 GiB allocated on GPU 0 — above the cap it believed it had set — failing on the same `Concatenate` for `layers.15.mlp.experts.gate_up_proj`. The earlier revision, which read `torch.cuda.get_device_properties(i)` per device, verified `fixed`. So: read the devices directly, take the minimum so a heterogeneous box is budgeted by its smallest card, and raise SkipTest when there is no accelerator instead of quietly loading with no budget. A fallback that silently disables the fix is exactly how the original bug survived `cap_psutil_cpu_memory`, whose `min(mem.total, limit)` made a 240 GiB "cap" inert — repeating that shape in the fix would have been the same mistake twice. * Budget 70%, not 85%: at 85% the headroom is the size of the noise Three GPU verifies of near-identical budgets came back fixed, not_fixed, not_fixed — including one that restored the numbers of the run that passed. The v3 traceback says why: the 18 GiB cap WAS honoured (18.67 GiB allocated) and the test still OOMed with 168.69 MiB free of 22.30 GiB, the rest "reserved by PyTorch but unallocated". The failing request is 1.56 GiB, so at 85% the headroom and the allocator's fragmentation are the same size and the outcome flips between runs. 70% leaves ~6.7 GiB against that 1.56 GiB — margin instead of a coin toss. Also asks the allocator not to fragment the reservation away, which the OOM message itself recommends. Best-effort on purpose: the setter is absent on older torch and refused once the allocator is configured, and CUDA may already be initialised by the time a single test runs. The budget is what this rests on. Uses `getattr(torch, torch_device)` rather than `torch.cuda` directly, so the budget is computed on xpu too. * Cut the comment down to what is not evident from the code Sixteen lines of measurement history for six lines of code. The verify verdicts and GiB figures belong in the PR discussion, not in the test file — and the lines they described (a fraction, a dict of budgets) say what they do on their own. Two lines left: why a budget is needed at all, which the code cannot say, and one inline note that the allocator setter is absent on older torch, which is why it is suppressed. * Drop the second, stale copy of the same comment An earlier revision's 15-line block survived alongside the trimmed one, so the file explained the same thing twice — and the older copy still said "budget 80%" after the code moved to 70%, which is worse than verbose. Three lines now, stating only the part the code cannot: that `auto` budgets each device to its full capacity when several are visible, so the merge temporary has nowhere to go. --------- Co-authored-by: serge[bot] Co-authored-by: Tarek Ziade --- tests/models/phimoe/test_modeling_phimoe.py | 34 +++++++++++++-------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/tests/models/phimoe/test_modeling_phimoe.py b/tests/models/phimoe/test_modeling_phimoe.py index 3ab00c46c729..1dfa332719d8 100644 --- a/tests/models/phimoe/test_modeling_phimoe.py +++ b/tests/models/phimoe/test_modeling_phimoe.py @@ -14,6 +14,7 @@ """Testing suite for the PyTorch PhiMoE model.""" +import contextlib import tempfile import unittest @@ -21,8 +22,6 @@ from transformers import StaticCache, is_torch_available from transformers.testing_utils import ( - backend_device_count, - cap_psutil_cpu_memory, cleanup, require_torch, slow, @@ -122,17 +121,26 @@ class PhimoeIntegrationTest(unittest.TestCase): def get_model(cls): if cls.model is None: cls.offload_dir = tempfile.TemporaryDirectory() - # Cap psutil CPU memory to 60 GiB × num_accelerators so device_map="auto" offloads some - # layers to disk, preventing GPU OOM at inference time. See #48290 for full rationale. - num_accelerators = max(1, backend_device_count(torch_device)) if torch_device is not None else 1 - with cap_psutil_cpu_memory(int(60 * num_accelerators * 1024**3)): - cls.model = PhimoeForCausalLM.from_pretrained( - "microsoft/Phi-3.5-MoE-instruct", - experts_implementation="eager", - dtype="auto", - device_map="auto", - offload_folder=cls.offload_dir.name, - ) + # `device_map="auto"` budgets each device to its full capacity when more + # than one is visible, leaving nothing for the ~1.6 GiB temporary the + # expert gate/up merge allocates while loading. + with contextlib.suppress(Exception): # absent on older torch + torch.cuda.memory._set_allocator_settings("expandable_segments:True") + if not torch.cuda.is_available() or torch.cuda.device_count() == 0: + raise unittest.SkipTest("phimoe integration test needs an accelerator") + accel = getattr(torch, torch_device) + n = accel.device_count() + per_device = int(min(accel.get_device_properties(i).total_memory for i in range(n)) * 0.70 / 1024**3) + max_memory = dict.fromkeys(range(n), f"{per_device}GiB") + max_memory["cpu"] = "60GiB" + cls.model = PhimoeForCausalLM.from_pretrained( + "microsoft/Phi-3.5-MoE-instruct", + experts_implementation="eager", + dtype="auto", + device_map="auto", + max_memory=max_memory, + offload_folder=cls.offload_dir.name, + ) return cls.model @classmethod From fc236b614108dab2dda2fcf7b8bf1210c542c71a Mon Sep 17 00:00:00 2001 From: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com> Date: Wed, 2 Sep 2026 12:16:03 +0000 Subject: [PATCH 027/996] [`DSA`] Fix vanillas SDPA with padding (#48363) * fix dsa on sdpa * fix the other models as well * aya * change into bool based accounting * need to keep in signature * this time --- src/transformers/masking_utils.py | 4 ++- src/transformers/models/axk2/modeling_axk2.py | 30 ++++++++--------- src/transformers/models/axk2/modular_axk2.py | 17 +++++----- .../deepseek_v32/modeling_deepseek_v32.py | 33 ++++++++++--------- .../deepseek_v32/modular_deepseek_v32.py | 33 ++++++++++--------- .../glm_moe_dsa/modeling_glm_moe_dsa.py | 30 ++++++++--------- .../models/glm_moe_dsa/modular_glm_moe_dsa.py | 30 ++++++++--------- tests/models/axk2/test_modeling_axk2.py | 4 --- .../test_modeling_deepseek_v32.py | 6 ++-- .../glm_moe_dsa/test_modeling_glm_moe_dsa.py | 6 ++-- 10 files changed, 93 insertions(+), 100 deletions(-) diff --git a/src/transformers/masking_utils.py b/src/transformers/masking_utils.py index 7bd46c8bb287..0b6ea5e01945 100644 --- a/src/transformers/masking_utils.py +++ b/src/transformers/masking_utils.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. from collections.abc import Callable +from functools import partial import torch import torch.nn.functional as F @@ -1511,7 +1512,8 @@ def create_recurrent_attention_mask( "compressed_sparse_attention": create_sliding_window_causal_mask, "heavily_compressed_attention": create_sliding_window_causal_mask, "minimax_m3_sparse": create_causal_mask, - "deepseek_sparse_attention": create_causal_mask, + # DSA always needs to materialize the mask to account for causality (no SDPA `is_cauasal` shortcut) + "deepseek_sparse_attention": partial(create_causal_mask, allow_is_causal_skip=False), "qwen_sparse_attention": create_causal_mask, "linear_attention": create_recurrent_attention_mask, "conv": create_recurrent_attention_mask, diff --git a/src/transformers/models/axk2/modeling_axk2.py b/src/transformers/models/axk2/modeling_axk2.py index a9e5238eafa9..4eaa88d5d435 100644 --- a/src/transformers/models/axk2/modeling_axk2.py +++ b/src/transformers/models/axk2/modeling_axk2.py @@ -228,8 +228,8 @@ def forward( hidden_states: torch.Tensor, q_resid: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], - attention_mask: torch.Tensor | None, - position_ids: torch.Tensor, + attention_mask: torch.Tensor, + position_ids: torch.Tensor, # Kept for BC past_key_values: Cache | None = None, ) -> torch.Tensor: """ @@ -279,12 +279,10 @@ def forward( index_scores = torch.matmul(weights.unsqueeze(-2), scores).squeeze(-2) # Causality needs to be taken into account when computing scores so padding tokens don't affect computation - if attention_mask is not None: - index_scores = index_scores + attention_mask + if attention_mask.dtype == torch.bool: + index_scores = index_scores.masked_fill(~attention_mask, float("-inf")) else: - key_positions = torch.arange(index_scores.shape[-1], device=index_scores.device) - causal = key_positions[None, None, :] > position_ids[:, :, None] # [B, S, T] - index_scores = index_scores.masked_fill(causal, float("-inf")) + index_scores = index_scores + attention_mask topk = min(self.index_topk, index_scores.shape[-1]) return index_scores.topk(topk, dim=-1).indices.to(torch.int32) # [B, S, topk] @@ -588,7 +586,7 @@ def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], - attention_mask: torch.Tensor | None, + attention_mask: torch.Tensor, past_key_values: Cache | None = None, position_ids: torch.Tensor | None = None, **kwargs: Unpack[FlashAttentionKwargs], @@ -625,13 +623,12 @@ def forward( key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) # The indexer scores against a 3D `[B, S, T]` mask; the attention mask is 4D `[B, 1, S, T]`. - indexer_mask = attention_mask[:, 0, :, :] if attention_mask is not None else None topk_indices = self.indexer( hidden_states, q_resid, position_embeddings, - indexer_mask, - position_ids, + attention_mask[:, 0, :, :], + position_ids, # Kept for BC past_key_values=past_key_values, ) @@ -642,11 +639,11 @@ def forward( .scatter(-1, topk_indices.long(), False) .unsqueeze(1) ) - if attention_mask is None: - key_positions = torch.arange(key_states.shape[2], device=hidden_states.device) - index_mask = index_mask | (key_positions[None, None, None, :] > position_ids[:, None, :, None]) - attention_mask = hidden_states.new_zeros((batch_size, 1, seq_length, key_states.shape[2])) - attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) + + if attention_mask.dtype == torch.bool: + attention_mask = attention_mask & ~index_mask + else: + attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) else: sparse_indices = topk_indices @@ -803,6 +800,7 @@ def forward( "attention_mask": attention_mask, "past_key_values": past_key_values, "position_ids": position_ids, + "allow_is_causal_skip": False, # Always force creation to account for causality in the indexer } causal_mask_mapping = {"deepseek_sparse_attention": create_causal_mask(**mask_kwargs)} diff --git a/src/transformers/models/axk2/modular_axk2.py b/src/transformers/models/axk2/modular_axk2.py index 4bd767cb9d79..92b9d6ba35c1 100644 --- a/src/transformers/models/axk2/modular_axk2.py +++ b/src/transformers/models/axk2/modular_axk2.py @@ -315,7 +315,7 @@ def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], - attention_mask: torch.Tensor | None, + attention_mask: torch.Tensor, past_key_values: Cache | None = None, position_ids: torch.Tensor | None = None, **kwargs: Unpack[FlashAttentionKwargs], @@ -352,13 +352,12 @@ def forward( key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) # The indexer scores against a 3D `[B, S, T]` mask; the attention mask is 4D `[B, 1, S, T]`. - indexer_mask = attention_mask[:, 0, :, :] if attention_mask is not None else None topk_indices = self.indexer( hidden_states, q_resid, position_embeddings, - indexer_mask, - position_ids, + attention_mask[:, 0, :, :], + position_ids, # Kept for BC past_key_values=past_key_values, ) @@ -369,11 +368,11 @@ def forward( .scatter(-1, topk_indices.long(), False) .unsqueeze(1) ) - if attention_mask is None: - key_positions = torch.arange(key_states.shape[2], device=hidden_states.device) - index_mask = index_mask | (key_positions[None, None, None, :] > position_ids[:, None, :, None]) - attention_mask = hidden_states.new_zeros((batch_size, 1, seq_length, key_states.shape[2])) - attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) + + if attention_mask.dtype == torch.bool: + attention_mask = attention_mask & ~index_mask + else: + attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) else: sparse_indices = topk_indices diff --git a/src/transformers/models/deepseek_v32/modeling_deepseek_v32.py b/src/transformers/models/deepseek_v32/modeling_deepseek_v32.py index 8bf0f009b1a5..1607ec844463 100644 --- a/src/transformers/models/deepseek_v32/modeling_deepseek_v32.py +++ b/src/transformers/models/deepseek_v32/modeling_deepseek_v32.py @@ -194,8 +194,8 @@ def forward( hidden_states: torch.Tensor, q_resid: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], - attention_mask: torch.Tensor | None, - position_ids: torch.Tensor, + attention_mask: torch.Tensor, + position_ids: torch.Tensor, # Kept for BC past_key_values: Cache | None = None, ) -> torch.Tensor: """ @@ -245,12 +245,10 @@ def forward( index_scores = torch.matmul(weights.unsqueeze(-2), scores).squeeze(-2) # Causality needs to be taken into account when computing scores so padding tokens don't affect computation - if attention_mask is not None: - index_scores = index_scores + attention_mask + if attention_mask.dtype == torch.bool: + index_scores = index_scores.masked_fill(~attention_mask, float("-inf")) else: - key_positions = torch.arange(index_scores.shape[-1], device=index_scores.device) - causal = key_positions[None, None, :] > position_ids[:, :, None] # [B, S, T] - index_scores = index_scores.masked_fill(causal, float("-inf")) + index_scores = index_scores + attention_mask topk = min(self.index_topk, index_scores.shape[-1]) return index_scores.topk(topk, dim=-1).indices.to(torch.int32) # [B, S, topk] @@ -433,7 +431,7 @@ def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], - attention_mask: torch.Tensor | None, + attention_mask: torch.Tensor, past_key_values: Cache | None = None, position_ids: torch.Tensor | None = None, **kwargs: Unpack[FlashAttentionKwargs], @@ -462,9 +460,13 @@ def forward( key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) # The indexer scores against a 3D `[B, S, T]` mask; the attention mask is 4D `[B, 1, S, T]`. - indexer_mask = attention_mask[:, 0, :, :] if attention_mask is not None else None topk_indices = self.indexer( - hidden_states, q_resid, position_embeddings, indexer_mask, position_ids, past_key_values=past_key_values + hidden_states, + q_resid, + position_embeddings, + attention_mask[:, 0, :, :], + position_ids, # Kept for BC + past_key_values=past_key_values, ) # [B, S, topk] sparse_indices = None @@ -475,11 +477,11 @@ def forward( .scatter(-1, topk_indices.long(), False) .unsqueeze(1) ) # [B, 1, S, T]; True = masked - if attention_mask is None: - key_positions = torch.arange(key_states.shape[2], device=hidden_states.device) - index_mask = index_mask | (key_positions[None, None, None, :] > position_ids[:, None, :, None]) - attention_mask = hidden_states.new_zeros((batch_size, 1, seq_length, key_states.shape[2])) - attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) + + if attention_mask.dtype == torch.bool: + attention_mask = attention_mask & ~index_mask + else: + attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) else: sparse_indices = topk_indices @@ -752,6 +754,7 @@ def forward( "attention_mask": attention_mask, "past_key_values": past_key_values, "position_ids": position_ids, + "allow_is_causal_skip": False, # Always force creation to account for causality in the indexer } causal_mask_mapping = {"deepseek_sparse_attention": create_causal_mask(**mask_kwargs)} diff --git a/src/transformers/models/deepseek_v32/modular_deepseek_v32.py b/src/transformers/models/deepseek_v32/modular_deepseek_v32.py index 4025511daa2a..cf4689b944f9 100644 --- a/src/transformers/models/deepseek_v32/modular_deepseek_v32.py +++ b/src/transformers/models/deepseek_v32/modular_deepseek_v32.py @@ -208,8 +208,8 @@ def forward( hidden_states: torch.Tensor, q_resid: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], - attention_mask: torch.Tensor | None, - position_ids: torch.Tensor, + attention_mask: torch.Tensor, + position_ids: torch.Tensor, # Kept for BC past_key_values: Cache | None = None, ) -> torch.Tensor: """ @@ -259,12 +259,10 @@ def forward( index_scores = torch.matmul(weights.unsqueeze(-2), scores).squeeze(-2) # Causality needs to be taken into account when computing scores so padding tokens don't affect computation - if attention_mask is not None: - index_scores = index_scores + attention_mask + if attention_mask.dtype == torch.bool: + index_scores = index_scores.masked_fill(~attention_mask, float("-inf")) else: - key_positions = torch.arange(index_scores.shape[-1], device=index_scores.device) - causal = key_positions[None, None, :] > position_ids[:, :, None] # [B, S, T] - index_scores = index_scores.masked_fill(causal, float("-inf")) + index_scores = index_scores + attention_mask topk = min(self.index_topk, index_scores.shape[-1]) return index_scores.topk(topk, dim=-1).indices.to(torch.int32) # [B, S, topk] @@ -284,7 +282,7 @@ def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], - attention_mask: torch.Tensor | None, + attention_mask: torch.Tensor, past_key_values: Cache | None = None, position_ids: torch.Tensor | None = None, **kwargs: Unpack[FlashAttentionKwargs], @@ -313,9 +311,13 @@ def forward( key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) # The indexer scores against a 3D `[B, S, T]` mask; the attention mask is 4D `[B, 1, S, T]`. - indexer_mask = attention_mask[:, 0, :, :] if attention_mask is not None else None topk_indices = self.indexer( - hidden_states, q_resid, position_embeddings, indexer_mask, position_ids, past_key_values=past_key_values + hidden_states, + q_resid, + position_embeddings, + attention_mask[:, 0, :, :], + position_ids, # Kept for BC + past_key_values=past_key_values, ) # [B, S, topk] sparse_indices = None @@ -326,11 +328,11 @@ def forward( .scatter(-1, topk_indices.long(), False) .unsqueeze(1) ) # [B, 1, S, T]; True = masked - if attention_mask is None: - key_positions = torch.arange(key_states.shape[2], device=hidden_states.device) - index_mask = index_mask | (key_positions[None, None, None, :] > position_ids[:, None, :, None]) - attention_mask = hidden_states.new_zeros((batch_size, 1, seq_length, key_states.shape[2])) - attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) + + if attention_mask.dtype == torch.bool: + attention_mask = attention_mask & ~index_mask + else: + attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) else: sparse_indices = topk_indices @@ -400,6 +402,7 @@ def forward( "attention_mask": attention_mask, "past_key_values": past_key_values, "position_ids": position_ids, + "allow_is_causal_skip": False, # Always force creation to account for causality in the indexer } causal_mask_mapping = {"deepseek_sparse_attention": create_causal_mask(**mask_kwargs)} diff --git a/src/transformers/models/glm_moe_dsa/modeling_glm_moe_dsa.py b/src/transformers/models/glm_moe_dsa/modeling_glm_moe_dsa.py index 5d7ba1a8f3df..9da14d312a24 100644 --- a/src/transformers/models/glm_moe_dsa/modeling_glm_moe_dsa.py +++ b/src/transformers/models/glm_moe_dsa/modeling_glm_moe_dsa.py @@ -198,8 +198,8 @@ def forward( hidden_states: torch.Tensor, q_resid: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], - attention_mask: torch.Tensor | None, - position_ids: torch.Tensor, + attention_mask: torch.Tensor, + position_ids: torch.Tensor, # Kept for BC past_key_values: Cache | None = None, ) -> torch.Tensor: """ @@ -244,12 +244,10 @@ def forward( index_scores = torch.matmul(weights.unsqueeze(-2), scores).squeeze(-2) # Causality needs to be taken into account when computing scores so padding tokens don't affect computation - if attention_mask is not None: - index_scores = index_scores + attention_mask + if attention_mask.dtype == torch.bool: + index_scores = index_scores.masked_fill(~attention_mask, float("-inf")) else: - key_positions = torch.arange(index_scores.shape[-1], device=index_scores.device) - causal = key_positions[None, None, :] > position_ids[:, :, None] # [B, S, T] - index_scores = index_scores.masked_fill(causal, float("-inf")) + index_scores = index_scores + attention_mask topk = min(self.index_topk, index_scores.shape[-1]) return index_scores.topk(topk, dim=-1).indices.to(torch.int32) # [B, S, topk] @@ -399,7 +397,7 @@ def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], - attention_mask: torch.Tensor | None, + attention_mask: torch.Tensor, past_key_values: Cache | None = None, position_ids: torch.Tensor | None = None, prev_topk_indices: torch.Tensor | None = None, @@ -431,13 +429,12 @@ def forward( # DSA: select this layer's top-k tokens, or reuse the previous full layer's on `"shared"` layers. if self.indexer is not None: - indexer_mask = attention_mask[:, 0, :, :] if attention_mask is not None else None topk_indices = self.indexer( hidden_states, q_resid, position_embeddings, - indexer_mask, - position_ids, + attention_mask[:, 0, :, :], + position_ids, # Kept for BC past_key_values=past_key_values, ) # [B, S, topk] else: @@ -452,11 +449,11 @@ def forward( .scatter(-1, topk_indices.long(), False) .unsqueeze(1) ) - if attention_mask is None: - key_positions = torch.arange(key_states.shape[2], device=hidden_states.device) - index_mask = index_mask | (key_positions[None, None, None, :] > position_ids[:, None, :, None]) - attention_mask = hidden_states.new_zeros((batch_size, 1, seq_length, key_states.shape[2])) - attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) + + if attention_mask.dtype == torch.bool: + attention_mask = attention_mask & ~index_mask + else: + attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) else: sparse_indices = topk_indices @@ -730,6 +727,7 @@ def forward( "attention_mask": attention_mask, "past_key_values": past_key_values, "position_ids": position_ids, + "allow_is_causal_skip": False, # Always force creation to account for causality in the indexer } causal_mask_mapping = {"deepseek_sparse_attention": create_causal_mask(**mask_kwargs)} diff --git a/src/transformers/models/glm_moe_dsa/modular_glm_moe_dsa.py b/src/transformers/models/glm_moe_dsa/modular_glm_moe_dsa.py index 1400a2a9531d..91f90e90b83e 100644 --- a/src/transformers/models/glm_moe_dsa/modular_glm_moe_dsa.py +++ b/src/transformers/models/glm_moe_dsa/modular_glm_moe_dsa.py @@ -137,8 +137,8 @@ def forward( hidden_states: torch.Tensor, q_resid: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], - attention_mask: torch.Tensor | None, - position_ids: torch.Tensor, + attention_mask: torch.Tensor, + position_ids: torch.Tensor, # Kept for BC past_key_values: Cache | None = None, ) -> torch.Tensor: """ @@ -183,12 +183,10 @@ def forward( index_scores = torch.matmul(weights.unsqueeze(-2), scores).squeeze(-2) # Causality needs to be taken into account when computing scores so padding tokens don't affect computation - if attention_mask is not None: - index_scores = index_scores + attention_mask + if attention_mask.dtype == torch.bool: + index_scores = index_scores.masked_fill(~attention_mask, float("-inf")) else: - key_positions = torch.arange(index_scores.shape[-1], device=index_scores.device) - causal = key_positions[None, None, :] > position_ids[:, :, None] # [B, S, T] - index_scores = index_scores.masked_fill(causal, float("-inf")) + index_scores = index_scores + attention_mask topk = min(self.index_topk, index_scores.shape[-1]) return index_scores.topk(topk, dim=-1).indices.to(torch.int32) # [B, S, topk] @@ -214,7 +212,7 @@ def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], - attention_mask: torch.Tensor | None, + attention_mask: torch.Tensor, past_key_values: Cache | None = None, position_ids: torch.Tensor | None = None, prev_topk_indices: torch.Tensor | None = None, @@ -246,13 +244,12 @@ def forward( # DSA: select this layer's top-k tokens, or reuse the previous full layer's on `"shared"` layers. if self.indexer is not None: - indexer_mask = attention_mask[:, 0, :, :] if attention_mask is not None else None topk_indices = self.indexer( hidden_states, q_resid, position_embeddings, - indexer_mask, - position_ids, + attention_mask[:, 0, :, :], + position_ids, # Kept for BC past_key_values=past_key_values, ) # [B, S, topk] else: @@ -267,11 +264,11 @@ def forward( .scatter(-1, topk_indices.long(), False) .unsqueeze(1) ) - if attention_mask is None: - key_positions = torch.arange(key_states.shape[2], device=hidden_states.device) - index_mask = index_mask | (key_positions[None, None, None, :] > position_ids[:, None, :, None]) - attention_mask = hidden_states.new_zeros((batch_size, 1, seq_length, key_states.shape[2])) - attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) + + if attention_mask.dtype == torch.bool: + attention_mask = attention_mask & ~index_mask + else: + attention_mask = attention_mask.masked_fill(index_mask, torch.finfo(hidden_states.dtype).min) else: sparse_indices = topk_indices @@ -366,6 +363,7 @@ def forward( "attention_mask": attention_mask, "past_key_values": past_key_values, "position_ids": position_ids, + "allow_is_causal_skip": False, # Always force creation to account for causality in the indexer } causal_mask_mapping = {"deepseek_sparse_attention": create_causal_mask(**mask_kwargs)} diff --git a/tests/models/axk2/test_modeling_axk2.py b/tests/models/axk2/test_modeling_axk2.py index 44e4e57c5cd5..2391f8be8243 100644 --- a/tests/models/axk2/test_modeling_axk2.py +++ b/tests/models/axk2/test_modeling_axk2.py @@ -74,10 +74,6 @@ class AXK2ModelTest(CausalLMModelTest, unittest.TestCase): model_tester_class = AXK2ModelTester model_split_percents = [0.5, 0.7, 0.8] - @unittest.skip("Can be fixed by #47438, currently does not properly considers cases where topk > prefill") - def test_left_padding_compatibility(self): - pass - @unittest.skip("Fundamentally incompatible with indexer as there is no boundary between sequences") def test_eager_padding_matches_padding_free_with_position_ids(self): pass diff --git a/tests/models/deepseek_v32/test_modeling_deepseek_v32.py b/tests/models/deepseek_v32/test_modeling_deepseek_v32.py index 2543c7446688..bfcc28a86c6a 100644 --- a/tests/models/deepseek_v32/test_modeling_deepseek_v32.py +++ b/tests/models/deepseek_v32/test_modeling_deepseek_v32.py @@ -121,6 +121,7 @@ def __init__( first_k_dense_replace=1, n_group=1, topk_group=1, + index_topk=8, ): super().__init__(parent=parent) self.n_routed_experts = n_routed_experts @@ -131,6 +132,7 @@ def __init__( self.first_k_dense_replace = first_k_dense_replace self.n_group = n_group self.topk_group = topk_group + self.index_topk = index_topk @require_torch @@ -205,10 +207,6 @@ def test_eager_matches_sdpa_inference(self, *args, **kwargs): def test_eager_matches_batched_and_grouped_inference(self, *args, **kwargs): pass - @unittest.skip("DSA hard top-k selection is sensitive to padding shifts (selection can flip).") - def test_left_padding_compatibility(self): - pass - @unittest.skip("DSA hard top-k selection is sensitive to sequence packing (selection can flip).") def test_eager_padding_matches_padding_free_with_position_ids(self): pass diff --git a/tests/models/glm_moe_dsa/test_modeling_glm_moe_dsa.py b/tests/models/glm_moe_dsa/test_modeling_glm_moe_dsa.py index 2c67b33383ab..a21a81b5f677 100644 --- a/tests/models/glm_moe_dsa/test_modeling_glm_moe_dsa.py +++ b/tests/models/glm_moe_dsa/test_modeling_glm_moe_dsa.py @@ -61,6 +61,7 @@ def __init__( v_head_dim=128, num_hidden_layers=2, mlp_layer_types=["sparse", "dense"], + index_topk=8, ): super().__init__(parent=parent, num_hidden_layers=num_hidden_layers) self.n_routed_experts = n_routed_experts @@ -70,6 +71,7 @@ def __init__( self.qk_rope_head_dim = qk_rope_head_dim self.v_head_dim = v_head_dim self.mlp_layer_types = mlp_layer_types + self.index_topk = index_topk @require_torch @@ -108,10 +110,6 @@ def test_eager_matches_sdpa_inference(self, *args): def test_eager_matches_batched_and_grouped_inference(self, *args): pass - @unittest.skip("DSA hard top-k selection is sensitive to padding shifts (selection can flip).") - def test_left_padding_compatibility(self): - pass - @unittest.skip("DSA hard top-k selection is sensitive to sequence packing (selection can flip).") def test_eager_padding_matches_padding_free_with_position_ids(self): pass From 9c8478e3a393164b510d4f4c300f6053473e925a Mon Sep 17 00:00:00 2001 From: Harry Julian <103032375+harryjulian@users.noreply.github.com> Date: Wed, 2 Sep 2026 12:19:27 +0000 Subject: [PATCH 028/996] Add support for NeuCodec (#47143) * V1 of NeuCodec support * added docs * altered checkpoint conversion, added README * added sketch of tests * Fixed tests, updated `sampling_rate` to be `input_sampling_rate` parameter. * Review related changes: remove duplicated `encode` method, fix docstring. * Update neucodec doc with batched and compiled inference examples * update overview in README.md * Re-generated files, marked NeuCodec and XCodec2 as un-exportable. * Update src/transformers/models/neucodec/modular_neucodec.py Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> * Update src/transformers/models/neucodec/modular_neucodec.py Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> * Update src/transformers/models/neucodec/modular_neucodec.py Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> * Update src/transformers/models/neucodec/modular_neucodec.py Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> * Update src/transformers/models/neucodec/modular_neucodec.py Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> * Simpler modular, fix tests, style checks. * Remove exposed torch from feature extractor. * V1 of NeuCodec support * added docs * altered checkpoint conversion, added README * added sketch of tests * Fixed tests, updated `sampling_rate` to be `input_sampling_rate` parameter. * Review related changes: remove duplicated `encode` method, fix docstring. * Update neucodec doc with batched and compiled inference examples * update overview in README.md * Re-generated files, marked NeuCodec and XCodec2 as un-exportable. * Update src/transformers/models/neucodec/modular_neucodec.py Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> * Update src/transformers/models/neucodec/modular_neucodec.py Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> * Update src/transformers/models/neucodec/modular_neucodec.py Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> * Update src/transformers/models/neucodec/modular_neucodec.py Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> * Update src/transformers/models/neucodec/modular_neucodec.py Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> * Simpler modular, fix tests, style checks. * Remove exposed torch from feature extractor. * fixed integration test * add gist for creating integration test expected results * Nits, and adapt test like xcodec2. * Fix torch compile and nits. * Update tests/models/neucodec/test_modeling_neucodec.py Co-authored-by: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com> * Address comments, and better conversion script for gated model. * comment nits --------- Co-authored-by: Eli Joe Co-authored-by: Eric Bezzam <4757445+ebezzam@users.noreply.github.com> Co-authored-by: Eric B Co-authored-by: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com> --- docs/source/en/_toctree.yml | 2 + docs/source/en/model_doc/neucodec.md | 155 +++ src/transformers/models/__init__.py | 1 + src/transformers/models/auto/auto_mappings.py | 2 + src/transformers/models/auto/modeling_auto.py | 2 + src/transformers/models/neucodec/__init__.py | 28 + .../models/neucodec/configuration_neucodec.py | 130 ++ .../neucodec/convert_neucodec_checkpoint.py | 372 ++++++ .../neucodec/feature_extraction_neucodec.py | 243 ++++ .../models/neucodec/modeling_neucodec.py | 1148 +++++++++++++++++ .../models/neucodec/modular_neucodec.py | 444 +++++++ .../models/xcodec2/modeling_xcodec2.py | 9 +- .../models/xcodec2/modular_xcodec2.py | 9 +- tests/fixtures/neucodec/expected_results.json | 1 + tests/models/neucodec/__init__.py | 0 .../test_feature_extraction_neucodec.py | 176 +++ .../models/neucodec/test_modeling_neucodec.py | 333 +++++ tests/models/xcodec2/test_modeling_xcodec2.py | 1 + 18 files changed, 3048 insertions(+), 8 deletions(-) create mode 100644 docs/source/en/model_doc/neucodec.md create mode 100644 src/transformers/models/neucodec/__init__.py create mode 100644 src/transformers/models/neucodec/configuration_neucodec.py create mode 100644 src/transformers/models/neucodec/convert_neucodec_checkpoint.py create mode 100644 src/transformers/models/neucodec/feature_extraction_neucodec.py create mode 100644 src/transformers/models/neucodec/modeling_neucodec.py create mode 100644 src/transformers/models/neucodec/modular_neucodec.py create mode 100644 tests/fixtures/neucodec/expected_results.json create mode 100644 tests/models/neucodec/__init__.py create mode 100644 tests/models/neucodec/test_feature_extraction_neucodec.py create mode 100644 tests/models/neucodec/test_modeling_neucodec.py diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index 8c50587f1b72..e4917327dc9e 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -1169,6 +1169,8 @@ title: Nemotron 3.5 ASR - local: model_doc/nemotron_asr_streaming title: Nemotron ASR Streaming + - local: model_doc/neucodec + title: NeuCodec - local: model_doc/parakeet title: Parakeet - local: model_doc/pe_audio diff --git a/docs/source/en/model_doc/neucodec.md b/docs/source/en/model_doc/neucodec.md new file mode 100644 index 000000000000..97f3eda57831 --- /dev/null +++ b/docs/source/en/model_doc/neucodec.md @@ -0,0 +1,155 @@ + +*This model was published in HF papers on 2025-09-11 and contributed to Hugging Face Transformers on 2026-09-02.* + +# NeuCodec + +
+SDPA +
+ +## Overview + +The NeuCodec model was proposed in [Finite Scalar Quantization Enables Redundant and Transmission-Robust Neural Audio Compression at Low Bit-rates](https://huggingface.co/papers/2509.09550). + +NeuCodec is a neural audio codec extending on XCodec2. It takes advantage of the following features: + +- Finite Scalar Quantization (FSQ) quantisation resulting in a **single codebook**, making it ideal for downstream modeling with Speech Language Models. +- Trained with CC data such that there are **no Non-Commercial data restrictions**. +- At 50 tokens/sec and 16 bits per token, the overall bit-rate is **0.8kbps**. +- The codec takes in 16kHz input and outputs **24kHz** using an **upsampling decoder**. +- The FSQ encoding scheme allows for bit-level error resistance suitable for unreliable and noisy channels. + +The original modelling code can be found [here](https://github.com/neuphonic/neucodec). + +## Usage example + +Here is a quick example of how to encode and decode an audio using this model: + +```python +from datasets import Audio, load_dataset +from transformers import AutoFeatureExtractor, AutoModel + +model_id = "neuphonic/neucodec" +model = AutoModel.from_pretrained(model_id, device_map="auto") +feature_extractor = AutoFeatureExtractor.from_pretrained(model_id) + +dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate)) +audio = dataset[0]["audio"]["array"] +inputs = feature_extractor(audio=audio, sampling_rate=feature_extractor.sampling_rate, return_tensors="pt").to( + model.device, model.dtype +) +print("Input waveform shape:", inputs["input_values"].shape) +# Input waveform shape: torch.Size([1, 1, 93760]) + +# encoder and decoder +audio_codes = model.encode(**inputs).audio_codes +print("Audio codes shape:", audio_codes.shape) +# Audio codes shape: torch.Size([1, 1, 292]) +audio_values = model.decode(audio_codes).audio_values +print("Audio values shape:", audio_values.shape) + +# Equivalently, you can do encoding and decoding in one step +model_output = model(**inputs) +audio_codes = model_output.audio_codes +audio_values = model_output.audio_values +``` + +### Batch processing + +This implementation also supports batched input! + +```python +from datasets import Audio, load_dataset +from transformers import AutoFeatureExtractor, AutoModel + +batch_size = 2 +model_id = "neuphonic/neucodec" +model = AutoModel.from_pretrained(model_id, device_map="auto") +feature_extractor = AutoFeatureExtractor.from_pretrained(model_id) + +dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate)) +audios = [dataset[i]["audio"]["array"] for i in range(batch_size)] +inputs = feature_extractor(audio=audios, sampling_rate=feature_extractor.sampling_rate, return_tensors="pt").to( + model.device, model.dtype +) +print("Input waveform shape:", inputs["input_values"].shape) +# Input waveform shape: torch.Size([2, 1, 93760]) + +# encoder and decoder +encoder_output = model.encode(**inputs) +audio_codes = encoder_output.audio_codes +print("Audio codes shape:", audio_codes.shape) +# Audio codes shape: torch.Size([2, 1, 292]) +audio_values = model.decode(audio_codes).audio_values +print("Audio values shape:", audio_values.shape) + +# Equivalently, you can do encoding and decoding in one step +model_output = model(**inputs) +audio_codes = model_output.audio_codes +audio_values = model_output.audio_values +``` + +### Speed-up with `torch.compile` + +You can speed up inference with [`torch.compile`](https://pytorch.org/docs/stable/generated/torch.compile.html). The first few calls will be slower due to compilation overhead, but subsequent calls will be faster. + +```python +import torch +from datasets import Audio, load_dataset +from transformers import AutoFeatureExtractor, AutoModel + +batch_size = 4 +model_id = "neuphonic/neucodec" +model = AutoModel.from_pretrained(model_id, device_map="auto") +feature_extractor = AutoFeatureExtractor.from_pretrained(model_id) + +dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") +dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate)) +audios = [dataset[i]["audio"]["array"] for i in range(batch_size)] +inputs = feature_extractor( + audio=audios, sampling_rate=feature_extractor.sampling_rate, padding=True, return_tensors="pt" +).to(model.device, model.dtype) + +compiled_model = torch.compile(model, fullgraph=True) + +# Warmup (includes compilation on first call) +for _ in range(10): + with torch.inference_mode(): + _ = compiled_model(**inputs) + +with torch.inference_mode(): + output = compiled_model(**inputs) +print("Audio values shape:", output.audio_values.shape) +``` + +## NeuCodecConfig + +[[autodoc]] NeuCodecConfig + +## NeuCodecFeatureExtractor + +[[autodoc]] NeuCodecFeatureExtractor + - __call__ + +## NeuCodecModel + +[[autodoc]] NeuCodecModel + - decode + - encode + - forward diff --git a/src/transformers/models/__init__.py b/src/transformers/models/__init__.py index 91ba473aa245..05bf957e7d86 100644 --- a/src/transformers/models/__init__.py +++ b/src/transformers/models/__init__.py @@ -328,6 +328,7 @@ from .nemotron_asr_streaming import * from .nemotron_h import * from .neomme import * + from .neucodec import * from .nllb import * from .nllb_moe import * from .nomic_bert import * diff --git a/src/transformers/models/auto/auto_mappings.py b/src/transformers/models/auto/auto_mappings.py index 4f400bef9891..f413ea52fdd7 100644 --- a/src/transformers/models/auto/auto_mappings.py +++ b/src/transformers/models/auto/auto_mappings.py @@ -440,6 +440,7 @@ ("nemotron_asr_streaming_encoder", "NemotronAsrStreamingEncoderConfig"), ("nemotron_h", "NemotronHConfig"), ("neomme", "NeoMMEConfig"), + ("neucodec", "NeuCodecConfig"), ("nllb-moe", "NllbMoeConfig"), ("nomic_bert", "NomicBertConfig"), ("nougat", "NougatConfig"), @@ -1038,6 +1039,7 @@ ("kyutai_speech_to_text", "KyutaiSpeechToTextFeatureExtractor"), ("musicgen_melody", "MusicgenMelodyFeatureExtractor"), ("nemotron_asr_streaming", "NemotronAsrStreamingFeatureExtractor"), + ("neucodec", "NeuCodecFeatureExtractor"), ("pe_audio", "PeAudioFeatureExtractor"), ("phi4_multimodal", "Phi4MultimodalFeatureExtractor"), ("pop2piano", "Pop2PianoFeatureExtractor"), diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index 3dcd71acd08b..c6d153074b28 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -371,6 +371,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("nemotron_asr_streaming_encoder", "NemotronAsrStreamingEncoder"), ("nemotron_h", "NemotronHModel"), ("neomme", "NeoMMEModel"), + ("neucodec", "NeuCodecModel"), ("nllb-moe", "NllbMoeModel"), ("nomic_bert", "NomicBertModel"), ("nystromformer", "NystromformerModel"), @@ -2026,6 +2027,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): [ ("dac", "DacModel"), ("higgs_audio_v2_tokenizer", "HiggsAudioV2TokenizerModel"), + ("neucodec", "NeuCodecModel"), ("vibevoice_acoustic_tokenizer", "VibeVoiceAcousticTokenizerModel"), ("xcodec2", "Xcodec2Model"), ] diff --git a/src/transformers/models/neucodec/__init__.py b/src/transformers/models/neucodec/__init__.py new file mode 100644 index 000000000000..8d408dfee9d6 --- /dev/null +++ b/src/transformers/models/neucodec/__init__.py @@ -0,0 +1,28 @@ +# Copyright 2026 The HuggingFace 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. +from typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_neucodec import * + from .feature_extraction_neucodec import * + from .modeling_neucodec import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/src/transformers/models/neucodec/configuration_neucodec.py b/src/transformers/models/neucodec/configuration_neucodec.py new file mode 100644 index 000000000000..9e71ed9d062c --- /dev/null +++ b/src/transformers/models/neucodec/configuration_neucodec.py @@ -0,0 +1,130 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/neucodec/modular_neucodec.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_neucodec.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# 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. + +import numpy as np +from huggingface_hub.dataclasses import strict + +from ...configuration_utils import PreTrainedConfig +from ...modeling_rope_utils import RopeParameters +from ...utils import auto_docstring +from ...utils.type_validators import interval +from ..auto import CONFIG_MAPPING, AutoConfig + + +@auto_docstring(checkpoint="neuphonic/neucodec") +@strict +class NeuCodecConfig(PreTrainedConfig): + r""" + downsampling_ratios (`list[int]`, *optional*, defaults to `[2, 2, 4, 4, 5]`): + Ratios for downsampling in the encoder. + semantic_model_config (`Union[Dict, Wav2Vec2BertConfig]`, *optional*): + An instance of the configuration object for the semantic (Wav2Vec2BertConfig) model. + quantization_dim (`int`, *optional*, defaults to 2048): + Dimension for the vector quantization codebook. + quantization_levels (`list[int]`, *optional*, defaults to `[4, 4, 4, 4, 4, 4, 4, 4]`): + Levels for the vector quantization codebook. + input_sampling_rate (`int`, *optional*, defaults to 16000): + Sampling rate, in hertz (Hz), of the encoder's input audio waveform. + output_sampling_rate (`int`, *optional*, defaults to 24000): + Sampling rate, in hertz (Hz), of the decoder's output audio waveform. + + Example: + + ```python + >>> from transformers import NeuCodecConfig, NeuCodecModel + + >>> # Initializing configuration + >>> configuration = NeuCodecConfig() + + >>> # Initializing a model (with random weights) from the configuration + >>> model = NeuCodecModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "neucodec" + keys_to_ignore_at_inference = ["past_key_values"] + hidden_size: int = 1024 + intermediate_size: int = 4096 + num_hidden_layers: int = 12 + num_attention_heads: int = 16 + num_key_value_heads: int = 16 + hidden_act: str = "silu" + max_position_embeddings: int = 4096 + initializer_range: float = interval(min=0.0, max=1.0)(default=0.02) + rms_norm_eps: float = 1e-6 + pad_token_id: int | None = None + tie_word_embeddings: bool = False + rope_parameters: RopeParameters | dict | None = None + attention_bias: bool = False + attention_dropout: int | float | None = 0.0 + head_dim: int = 64 + sub_configs = {"semantic_model_config": AutoConfig} + + encoder_hidden_size: int = 48 + downsampling_ratios: list[int] | tuple[int, ...] = (2, 2, 4, 4, 5) + semantic_model_config: dict | PreTrainedConfig | None = None + activation_dropout: float = 0.1 + quantization_dim: int = 2048 + quantization_levels: list[int] | tuple[int, ...] = (4, 4, 4, 4, 4, 4, 4, 4) + input_sampling_rate: int = 16_000 + output_sampling_rate: int = 24_000 + + def __post_init__(self, **kwargs): + if isinstance(self.semantic_model_config, dict): + self.semantic_model_config["model_type"] = self.semantic_model_config.get("model_type", "wav2vec2-bert") + self.semantic_model_config = CONFIG_MAPPING[self.semantic_model_config["model_type"]]( + **self.semantic_model_config + ) + elif self.semantic_model_config is None: + self.semantic_model_config = CONFIG_MAPPING["wav2vec2-bert"](num_hidden_layers=16) + if self.head_dim is None: + self.head_dim = self.hidden_size // self.num_attention_heads + if self.num_key_value_heads is None: + self.num_key_value_heads = self.num_attention_heads + + super().__post_init__(**kwargs) + + def validate_architecture(self): + """Part of `@strict`-powered validation. Validates the architecture of the config.""" + if self.hidden_size % self.num_attention_heads != 0: + raise ValueError( + f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention " + f"heads ({self.num_attention_heads})." + ) + + @property + def hop_length(self) -> int: + # The ISTFT head (which reads `hop_length`/`n_fft` off the config) synthesizes audio at + # `output_sampling_rate`, so the encoder's native hop_length is rescaled into that domain. + return int(self.encoder_hop_length * self.output_sampling_rate / self.input_sampling_rate) + + @property + def n_fft(self) -> int: + return self.hop_length * 4 + + @property + def encoder_hop_length(self) -> int: + """Hop length, in samples at `input_sampling_rate`, between successive codes (i.e. the encoder frame rate).""" + return int(np.prod(self.downsampling_ratios)) + + +__all__ = ["NeuCodecConfig"] diff --git a/src/transformers/models/neucodec/convert_neucodec_checkpoint.py b/src/transformers/models/neucodec/convert_neucodec_checkpoint.py new file mode 100644 index 000000000000..6b3540a4bb34 --- /dev/null +++ b/src/transformers/models/neucodec/convert_neucodec_checkpoint.py @@ -0,0 +1,372 @@ +# 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. + +import argparse +import re +import tempfile + +import torch +import torch.nn as nn +from huggingface_hub import create_branch, hf_hub_download, upload_folder + +from transformers import ( + AutoConfig, + AutoFeatureExtractor, + AutoModel, + NeuCodecConfig, + NeuCodecFeatureExtractor, + NeuCodecModel, + logging, +) + + +logging.set_verbosity_info() +logger = logging.get_logger("transformers.models.neucodec") + +# The original checkpoint lives in a gated repo, so it has to be downloaded through an authenticated +# `hf_hub_download` (run `hf auth login` first) rather than a plain HTTP request. +ORIGINAL_REPO_ID = "neuphonic/neucodec" +ORIGINAL_CHECKPOINT_FILENAME = "pytorch_model.bin" + +# Original key names: https://github.com/neuphonic/neucodec/blob/main/neucodec/model.py +# NeuCodec forked its module naming directly from xcodec2 (https://huggingface.co/HKUSTAudio/xcodec2), so the +# mapping below mirrors `xcodec2/convert_xcodec2_checkpoint.py`. Mappings are applied sequentially per key; order +# matters. +# fmt: off +STATE_DICT_MAPPING = { + # ── Semantic encoder (semantic_model -> semantic_encoder) ── + r"^semantic_model\.": r"semantic_encoder.", + + # ── Acoustic encoder (CodecEnc -> acoustic_encoder) ── + r"^CodecEnc\.conv_blocks\.0\.": r"acoustic_encoder.conv1.", + r"^CodecEnc\.conv_final_block\.0\.": r"acoustic_encoder.snake1.", + r"^CodecEnc\.conv_final_block\.1\.": r"acoustic_encoder.conv2.", + r"^CodecEnc\.conv_blocks\.(\d+)\.": r"acoustic_encoder.block.SHIFT_DOWN.\1.", + r"^CodecEnc\.": r"acoustic_encoder.", + # -- EncoderBlock: block.{0,1,2} -> res_unit{1,2,3}, block.3 -> snake1, block.4 -> conv1 + # NOTE: These must come BEFORE ResidualUnit mappings so keys are transformed first + r"(\.block\.\d+)\.block\.0\.": r"\1.res_unit1.", + r"(\.block\.\d+)\.block\.1\.": r"\1.res_unit2.", + r"(\.block\.\d+)\.block\.2\.": r"\1.res_unit3.", + r"(\.block\.\d+)\.block\.3\.": r"\1.snake1.", + r"(\.block\.\d+)\.block\.4\.": r"\1.conv1.", + # -- ResidualUnit: block.{0,1,2,3} -> {snake1,conv1,snake2,conv2} + r"(\.res_unit\d+)\.block\.0\.": r"\1.snake1.", + r"(\.res_unit\d+)\.block\.1\.": r"\1.conv1.", + r"(\.res_unit\d+)\.block\.2\.": r"\1.snake2.", + r"(\.res_unit\d+)\.block\.3\.": r"\1.conv2.", + # -- ResidualUnit nested structure: res_unit{1,2,3,4} -> {snake1,conv1,snake2,conv2} + r"(\.res_unit\d+)\.res_unit1\.": r"\1.snake1.", + r"(\.res_unit\d+)\.res_unit2\.": r"\1.conv1.", + r"(\.res_unit\d+)\.res_unit3\.": r"\1.snake2.", + r"(\.res_unit\d+)\.res_unit4\.": r"\1.conv2.", + # -- DownSample1d: lowpass.filter -> filter (LowPassFilter1d inlined) + r"\.downsample\.lowpass\.filter": r".downsample.filter", + + # ── Quantizer: lives on main model, not inside decoder ── + r"^generator\.quantizer\.layers\.0\.": r"quantizer.quantizer.", + r"^generator\.quantizer\.": r"quantizer.", + + # ── Decoder (generator -> acoustic_decoder) ── + # -- Handle backbone components: now directly in decoder (no backbone. prefix) + r"^generator\.backbone\.prior_net\.": r"acoustic_decoder.prior_net.", + r"^generator\.backbone\.post_net\.": r"acoustic_decoder.post_net.", + r"^generator\.backbone\.final_layer_norm\.": r"acoustic_decoder.norm.", + r"^generator\.backbone\.": r"acoustic_decoder.", + # -- General generator mapping + r"^generator\.": r"acoustic_decoder.", + # -- ISTFT head: out -> linear + r"acoustic_decoder\.head\.out\.": r"acoustic_decoder.head.linear.", + # -- Transformer layers: transformers -> layers + r"\.transformers\.": r".layers.", + r"\.att\.c_proj\.": r".self_attn.o_proj.", + r"\.att_norm\.": r".input_layernorm.", + r"\.ffn_norm\.": r".post_attention_layernorm.", + + # ── Semantic adapter (SemanticEncoder_module -> semantic_adapter) ── + r"^SemanticEncoder_module\.": r"semantic_adapter.", + r"semantic_adapter\.initial_conv\.": r"semantic_adapter.conv1.", + r"semantic_adapter\.final_conv\.": r"semantic_adapter.conv4.", + r"semantic_adapter\.residual_blocks\.0\.": r"semantic_adapter.act1.", + r"semantic_adapter\.residual_blocks\.1\.": r"semantic_adapter.conv2.", + r"semantic_adapter\.residual_blocks\.2\.": r"semantic_adapter.act2.", + r"semantic_adapter\.residual_blocks\.3\.": r"semantic_adapter.conv3.", + + # ── Linear layers (fc_prior -> fc_encoder, fc_post_a -> acoustic_decoder.fc) ── + r"^fc_prior\.": r"fc_encoder.", + r"^fc_post_a\.": r"acoustic_decoder.fc.", +} +# fmt: on + +# Training-only keys present in the released checkpoint that have no counterpart in the inference-only +# HF port: a semantic reconstruction auxiliary head (`fc_post_s`, `SemanticDecoder`). See +# https://github.com/neuphonic/neucodec/blob/main/neucodec/model.py#L69 (`ignore_keys` for `neuphonic/neucodec`). +IGNORED_KEY_SUBSTRINGS = ["fc_post_s", "SemanticDecoder"] + + +def permute_for_rope(input_tensor, n_heads, dim1, dim2): + input_tensor = input_tensor.reshape(dim1, dim2) + input_tensor = input_tensor.view(n_heads, dim1 // n_heads // 2, 2, dim2) + input_tensor = input_tensor.transpose(1, 2).reshape(dim1, dim2) + return input_tensor + + +def map_old_key_to_new(old_key): + new_key = old_key + for pattern, replacement in STATE_DICT_MAPPING.items(): + match = re.search(pattern, new_key) + if match: + # Handle index shift: conv_blocks index N (N>=1) -> encoder_blocks index N-1 + if "SHIFT_DOWN" in replacement and match.groups(): + layer_idx = int(match.group(1)) + replacement = replacement.replace(r"SHIFT_DOWN.\1", str(layer_idx - 1)) + new_key = re.sub(pattern, replacement, new_key) + return new_key + + +def _is_unused_semantic_layer(key, num_layers): + """Check if a key belongs to a semantic encoder layer beyond the ones we keep.""" + match = re.search(r"semantic_encoder\.encoder\.layers\.(\d+)\.", key) + return match is not None and int(match.group(1)) >= num_layers + + +def convert_state_dict(state_dict, hf_model): + new_state_dict = {} + + state_dict = {k: v for k, v in state_dict.items() if not any(s in k for s in IGNORED_KEY_SUBSTRINGS)} + + for old_key, tensor in state_dict.items(): + # Special case: c_attn is a fused QKV projection that must be split into 3 tensors + if ".att.c_attn." in old_key: + w_q, w_k, w_v = torch.chunk(tensor, chunks=3, dim=0) + w_q = permute_for_rope(w_q, hf_model.config.num_attention_heads, w_q.shape[0], w_q.shape[1]) + w_k = permute_for_rope(w_k, hf_model.config.num_attention_heads, w_k.shape[0], w_k.shape[1]) + base_key = map_old_key_to_new(old_key.replace(".att.c_attn.", ".self_attn.PROJ.")) + new_state_dict[base_key.replace("PROJ", "q_proj")] = w_q + new_state_dict[base_key.replace("PROJ", "k_proj")] = w_k + new_state_dict[base_key.replace("PROJ", "v_proj")] = w_v + continue + + new_key = map_old_key_to_new(old_key) + + new_state_dict[new_key] = tensor + if old_key != new_key: + logger.debug(f"Converted: {old_key} -> {new_key}") + + state_dict = new_state_dict + + # Like Xcodec2 LFilter out non-persistent buffers (recomputed in _init_weights) and + # unused semantic encoder layers (original has 24 layers, we only use 16) + num_semantic_layers = hf_model.config.semantic_model_config.num_hidden_layers + state_dict = { + k: v + for k, v in state_dict.items() + if not ( + k.endswith("upsample.filter") + or k.endswith("downsample.filter") + or k.endswith(".window") + or _is_unused_semantic_layer(k, num_semantic_layers) + or (k.endswith(".weight") and f"{k}_g" in state_dict) + ) + } + + extra_keys = set(state_dict.keys()) - set(hf_model.state_dict().keys()) + missing_keys = set(hf_model.state_dict().keys()) - set(state_dict.keys()) + if len(extra_keys) != 0: + raise ValueError(f"{len(extra_keys)} extra keys found: {extra_keys}") + if len(missing_keys) != 0: + raise ValueError(f"{len(missing_keys)} missing keys found: {missing_keys}") + hf_model.load_state_dict(state_dict, strict=True) + + n_params = sum(p.numel() for p in hf_model.parameters()) + logger.info(f"model loaded: {round(n_params / 1e6, 1)}M params") + + del state_dict + return hf_model + + +def apply_weight_norm(model): + weight_norm = nn.utils.weight_norm + + weight_norm(model.acoustic_encoder.conv1) + for encoder_block in model.acoustic_encoder.block: + weight_norm(encoder_block.res_unit1.conv1) + weight_norm(encoder_block.res_unit1.conv2) + weight_norm(encoder_block.res_unit2.conv1) + weight_norm(encoder_block.res_unit2.conv2) + weight_norm(encoder_block.res_unit3.conv1) + weight_norm(encoder_block.res_unit3.conv2) + weight_norm(encoder_block.conv1) + weight_norm(model.acoustic_encoder.conv2) + + # NeuCodec's `CodecDecoderVocos.apply_weight_norm` (unlike xcodec2's) weight-norms every Conv1d in the + # backbone, including `embed` and the pre/post ResNet blocks: https://github.com/neuphonic/neucodec/blob/main/neucodec/codec_decoder_vocos.py + weight_norm(model.acoustic_decoder.embed) + for resnet_block in [*model.acoustic_decoder.prior_net, *model.acoustic_decoder.post_net]: + weight_norm(resnet_block.conv1) + weight_norm(resnet_block.conv2) + + +def remove_weight_norm(model): + param_remove = nn.utils.remove_weight_norm + + param_remove(model.acoustic_encoder.conv1) + for encoder_block in model.acoustic_encoder.block: + param_remove(encoder_block.res_unit1.conv1) + param_remove(encoder_block.res_unit1.conv2) + param_remove(encoder_block.res_unit2.conv1) + param_remove(encoder_block.res_unit2.conv2) + param_remove(encoder_block.res_unit3.conv1) + param_remove(encoder_block.res_unit3.conv2) + param_remove(encoder_block.conv1) + param_remove(model.acoustic_encoder.conv2) + + param_remove(model.acoustic_decoder.embed) + for resnet_block in [*model.acoustic_decoder.prior_net, *model.acoustic_decoder.post_net]: + param_remove(resnet_block.conv1) + param_remove(resnet_block.conv2) + + +@torch.no_grad() +def convert_checkpoint( + checkpoint_path=None, + pytorch_dump_folder_path=None, + repo_id=None, + repo_subfolder=None, + revision=None, +): + # NeuCodec ships a bare `pytorch_model.bin` state dict with no accompanying `config.json` (only a `meta.yaml` + # tracking downloads), so the architecture hyperparameters below are hardcoded from + # https://github.com/neuphonic/neucodec/blob/main/neucodec/model.py and + # https://github.com/neuphonic/neucodec/blob/main/neucodec/codec_encoder.py + config = NeuCodecConfig( + encoder_hidden_size=48, + hidden_size=1024, + output_sampling_rate=24000, + semantic_model_config=AutoConfig.from_pretrained("facebook/w2v-bert-2.0", num_hidden_layers=16), + ) + + if not torch.cuda.is_available(): + raise ValueError("Run this script on a machine with a GPU for weight norm layers to be correctly copied.") + torch_device = "cuda" + model = NeuCodecModel(config).to(torch_device).eval() + + if checkpoint_path is None: + checkpoint_path = hf_hub_download(repo_id=ORIGINAL_REPO_ID, filename=ORIGINAL_CHECKPOINT_FILENAME) + original_checkpoint = torch.load(checkpoint_path, map_location="cpu") + # Unlike xcodec2, NeuCodec's `pytorch_model.bin` does not bundle semantic-encoder weights: at load time the + # reference implementation always fetches a frozen `facebook/w2v-bert-2.0` from the Hub instead + # (https://github.com/neuphonic/neucodec/blob/main/neucodec/model.py#L28). Merge those weights in under the + # `semantic_model.` prefix so `STATE_DICT_MAPPING` can route them like any other key. + semantic_model = AutoModel.from_pretrained("facebook/w2v-bert-2.0") + original_checkpoint.update({f"semantic_model.{k}": v for k, v in semantic_model.state_dict().items()}) + + apply_weight_norm(model) + model = convert_state_dict(original_checkpoint, model) + remove_weight_norm(model) + + dac_fe = AutoFeatureExtractor.from_pretrained("descript/dac_16khz") + semantic_fe = AutoFeatureExtractor.from_pretrained("facebook/w2v-bert-2.0") + if semantic_fe.sampling_rate != dac_fe.sampling_rate: + raise ValueError( + f"Sampling rates for DAC and semantic feature extractor must match, got {dac_fe.sampling_rate} and {semantic_fe.sampling_rate}." + ) + feature_extractor = NeuCodecFeatureExtractor( + feature_size=semantic_fe.feature_size, + sampling_rate=semantic_fe.sampling_rate, + padding_value=semantic_fe.padding_value, + hop_length=dac_fe.hop_length, + ) + + if pytorch_dump_folder_path is not None: + model.save_pretrained(pytorch_dump_folder_path) + feature_extractor.save_pretrained(pytorch_dump_folder_path) + + if repo_id: + print("Pushing to the hub...") + if revision: + # `upload_folder`/`create_commit` (unlike `push_to_hub`) don't create a missing branch on their own. + create_branch(repo_id=repo_id, branch=revision, exist_ok=True) + if repo_subfolder: + # `push_to_hub` always writes to the repo root, so for a subfolder destination (e.g. keeping the + # original, non-HF checkpoint at the repo root while adding a converted copy alongside it) save + # locally first and upload that folder to `repo_subfolder`. + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + feature_extractor.save_pretrained(tmp_dir) + upload_folder(repo_id=repo_id, folder_path=tmp_dir, path_in_repo=repo_subfolder, revision=revision) + else: + feature_extractor.push_to_hub(repo_id, revision=revision) + model.push_to_hub(repo_id, revision=revision) + + +""" +NeuCodec extends xcodec2 (see modular_neucodec.py): same encoder/decoder architecture and the same 16kHz-input +Wav2Vec2-BERT semantic encoder truncated to 16 layers, but the decoder synthesizes audio at 24kHz (hop_length=480) +instead of 16kHz (hop_length=320). See https://huggingface.co/neuphonic/neucodec. + +Conversion example usage: +``` +# `neuphonic/neucodec` is gated, so log in first (the original weights are downloaded automatically unless +# `--checkpoint_path` points at a local copy) +hf auth login + +# run conversion, first pushing to a test branch to sanity-check the result before touching `main` +python src/transformers/models/neucodec/convert_neucodec_checkpoint.py \ + --push_to_hub neuphonic/neucodec \ + --revision test-hf-conversion + +# once verified, push to the repo root on `main` (config.json / model.safetensors sit alongside the existing +# pytorch_model.bin / meta.yaml without conflict, see `--repo_subfolder` for isolating them in a subfolder instead) +python src/transformers/models/neucodec/convert_neucodec_checkpoint.py \ + --push_to_hub neuphonic/neucodec +``` + +""" +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--checkpoint_path", + default=None, + type=str, + help=f"Path to a local copy of the original checkpoint. If unset, `{ORIGINAL_CHECKPOINT_FILENAME}` is " + f"downloaded from `{ORIGINAL_REPO_ID}` (a gated repo, so run `hf auth login` first).", + ) + parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") + parser.add_argument( + "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." + ) + parser.add_argument( + "--repo_subfolder", + default=None, + type=str, + help="Subfolder of `--push_to_hub` to upload the converted model to, leaving the repo root untouched " + "(e.g. the original, non-HF checkpoint). If unset, uploads to the repo root as usual.", + ) + parser.add_argument( + "--revision", + default=None, + type=str, + help="Branch of `--push_to_hub` to upload the converted model to (created if it doesn't exist yet), e.g. " + "for testing on a branch before merging to `main`. If unset, uploads to `main`.", + ) + + args = parser.parse_args() + convert_checkpoint( + args.checkpoint_path, + args.pytorch_dump_folder_path, + args.push_to_hub, + args.repo_subfolder, + args.revision, + ) diff --git a/src/transformers/models/neucodec/feature_extraction_neucodec.py b/src/transformers/models/neucodec/feature_extraction_neucodec.py new file mode 100644 index 000000000000..c8e21a207f36 --- /dev/null +++ b/src/transformers/models/neucodec/feature_extraction_neucodec.py @@ -0,0 +1,243 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/neucodec/modular_neucodec.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_neucodec.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# 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. + +import copy +from typing import Any + +from ...audio_utils import AudioInput, make_list_of_audio +from ...feature_extraction_sequence_utils import SequenceFeatureExtractor +from ...feature_extraction_utils import BatchFeature +from ...utils import PaddingStrategy, TensorType, is_torch_available, logging +from ...utils.import_utils import is_torchaudio_available, requires + + +if is_torchaudio_available(): + import torchaudio +if is_torch_available(): + import torch + import torch.nn.functional as F + + +logger = logging.get_logger(__name__) + + +@requires(backends=("torchaudio",)) +class NeuCodecFeatureExtractor(SequenceFeatureExtractor): + r""" + Constructs a NeuCodec feature extractor, which computes mel-filter bank features for the semantic encoder and padded + audio for the acoustic encoder. + + This feature extractor inherits from [`SequenceFeatureExtractor`] which contains most of the main methods. Users + should refer to this superclass for more information regarding those methods. + + Args: + feature_size (`int`, *optional*, defaults to 80): + The feature dimension of the extracted features. + sampling_rate (`int`, *optional*, defaults to 16000): + The sample rate at which the audio files should be digitalized expressed in hertz (Hz). + padding_value (`float`, *optional*, defaults to 1.0): + The value that is used to fill the padding vectors for the mel spectrogram. + hop_length (`int`, *optional*, defaults to 320): + Number of audio samples encoded per frame. Equivalent to product of downsampling ratios. + Needed for acoustic encoder input padding. + """ + + model_input_names = ["input_features", "input_values", "padding_mask", "input_features_mask"] + + def __init__( + self, + feature_size=80, + sampling_rate=16000, + padding_value=1.0, + hop_length=320, + **kwargs, + ): + super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs) + + # Acoustic encoder feature extraction (similar to DAC). Defining sub feature extractor as workaround for + # padding audio with hop_length multiple, and relying on the parent class for padding the spectrogram. + self.hop_length = hop_length + self.acoustic_encoder_padder = SequenceFeatureExtractor( + feature_size=1, + sampling_rate=sampling_rate, + padding_value=0.0, + ) + self.acoustic_encoder_padder.model_input_names = ["audio", "padding_mask"] + + # Semantic encoder feature extraction (similar to SeamlessM4T) + self.stride = 2 + self.num_mel_bins = 80 + self.frame_length = 400 + self.frame_shift = 160 + + @requires(backends=("torch", "torchaudio")) + def __call__( + self, + audio: AudioInput, + padding: bool | str | PaddingStrategy = True, + max_length: int | None = None, + truncation: bool = False, + return_tensors: str | TensorType | None = None, + sampling_rate: int | None = None, + device: str = "cpu", + **kwargs, + ) -> BatchFeature: + """ + Args: + audio (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`): + Numpy array or torch tensor with shape (num_channels, sequence_length). A list of such arrays or + tensors can also be provided for a batch of inputs. + padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`): + Select a strategy to pad the returned sequences (according to the model's padding side and padding + index) among: + + - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single + sequence if provided). + - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum + acceptable input length for the model if that argument is not provided. + - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different + lengths). + max_length (`int`, *optional*): + Maximum length of the returned list and optionally padding length (see above). + truncation (`bool`): + Activates truncation to cut input sequences longer than *max_length* to *max_length*. + return_tensors (`str` or [`~utils.TensorType`], *optional*): + If set, will return tensors instead of list of python integers. Acceptable values are: + + - `'tf'`: Return TensorFlow `tf.constant` objects. + - `'pt'`: Return PyTorch `torch.Tensor` objects. + - `'np'`: Return Numpy `np.ndarray` objects. + sampling_rate (`int`, *optional*): + The sample rate at which the `audio` input was sampled. It is strongly recommended to pass + `sampling_rate` at the forward call to prevent silent errors. + device (`str`, *optional*, defaults to `"cpu"`): + Device for PyTorch tensors during mel-filter bank feature extraction. + kwargs (*optional*): + Remaining dictionary of keyword arguments that will be passed to the tokenizer or the feature + extractor. + """ + + if sampling_rate is not None: + if sampling_rate != self.sampling_rate: + raise ValueError( + f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of" + f" {self.sampling_rate}. Please make sure that the provided `audio` input was sampled with" + f" {self.sampling_rate} and not {sampling_rate}." + ) + else: + logger.warning( + f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. " + "Failing to do so can result in silent errors that might be hard to debug." + ) + + audio = make_list_of_audio(audio) + for example in audio: + if example.ndim > 2: + raise ValueError(f"Expected input shape (channels, length) but got shape {example.shape}") + batch_size = len(audio) + + # 1) Acoustic encoder padding + audio = [F.pad(torch.as_tensor(a), (0, 1), value=0.0) for a in audio] + padded_inputs = self.acoustic_encoder_padder.pad( + BatchFeature({"audio": audio}), + max_length=max_length, + truncation=truncation, + padding=padding, + return_attention_mask=padding, + pad_to_multiple_of=self.hop_length, + return_tensors="pt", + ) + padding_mask = padded_inputs.pop("attention_mask") + padded_audio = padded_inputs["audio"][:, None, :] + + # 2) Semantic encoder feature extraction (mel spectrogram). Unlike Xcodec2FeatureExtractor, NeuCodec's + # reference implementation feeds the acoustic-padded waveform directly into the mel computation, with no extra + # "valid_len" trimming or symmetric hop-sized padding: https://github.com/neuphonic/neucodec/blob/ed3e6cd1bdc374ce14a21355e5eee66a777149ce/neucodec/model.py#L128 + # Padded per-sample (not via the batch-collated `padded_audio`): the CMVN normalization below is computed + # over the whole padded signal, so batch-padding a short sample to the batch's longest would skew it. + # TODO (ebezzam): can batch processing be done without regression from expected outputs? + mel_features = [] + for i in range(batch_size): + single_padded_audio = self.acoustic_encoder_padder.pad( + BatchFeature({"audio": [audio[i]]}), + pad_to_multiple_of=self.hop_length, + return_tensors="pt", + ) + waveform = single_padded_audio["audio"].to(device) + features = torchaudio.compliance.kaldi.fbank( + waveform * (2**15), + num_mel_bins=self.num_mel_bins, + frame_length=self.frame_length / self.sampling_rate * 1000, + frame_shift=self.frame_shift / self.sampling_rate * 1000, + sample_frequency=self.sampling_rate, + window_type="povey", + preemphasis_coefficient=0.97, + remove_dc_offset=True, + use_log_fbank=True, + use_energy=False, + dither=0.0, + snip_edges=True, + low_freq=20, + high_freq=self.sampling_rate // 2, + ) + features = (features - features.mean(0)) / torch.sqrt(features.var(0, unbiased=True) + 1e-7) + mel_features.append(features) + encoded_inputs = BatchFeature({"input_features": mel_features}) + padded_mel = self.pad( + encoded_inputs, + padding=padding, + max_length=max_length, + truncation=truncation, + pad_to_multiple_of=self.stride, + return_attention_mask=padding, + return_tensors="pt", + ) + audio_spectrogram = padded_mel["input_features"] + spectrogram_mask = padded_mel.get("attention_mask") + trimmed_frames = audio_spectrogram.shape[1] - (audio_spectrogram.shape[1] % self.stride) + audio_spectrogram = audio_spectrogram[:, :trimmed_frames, :].reshape( + batch_size, trimmed_frames // self.stride, self.num_mel_bins * self.stride + ) + if spectrogram_mask is not None: + spectrogram_mask = ( + spectrogram_mask[:, :trimmed_frames] + .reshape(batch_size, trimmed_frames // self.stride, self.stride) + .min(dim=-1) + .values + ) + + return BatchFeature( + { + "input_values": padded_audio, + "padding_mask": padding_mask, + "input_features": audio_spectrogram, + "input_features_mask": spectrogram_mask, + }, + tensor_type=return_tensors, + ) + + def to_dict(self) -> dict[str, Any]: + output = copy.deepcopy(self.__dict__) + output["feature_extractor_type"] = self.__class__.__name__ + output.pop("acoustic_encoder_padder", None) + return output + + +__all__ = ["NeuCodecFeatureExtractor"] diff --git a/src/transformers/models/neucodec/modeling_neucodec.py b/src/transformers/models/neucodec/modeling_neucodec.py new file mode 100644 index 000000000000..48fbebf323ef --- /dev/null +++ b/src/transformers/models/neucodec/modeling_neucodec.py @@ -0,0 +1,1148 @@ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from src/transformers/models/neucodec/modular_neucodec.py. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# modular_neucodec.py file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# 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. + +import math +from collections.abc import Callable +from dataclasses import dataclass + +import numpy as np +import torch.nn as nn +from torch.nn import Parameter + +from ... import initialization as init +from ...activations import ACT2FN +from ...cache_utils import Cache +from ...integrations import use_kernel_forward_from_hub, use_kernelized_func +from ...masking_utils import create_bidirectional_mask +from ...modeling_layers import GradientCheckpointingLayer +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from ...processing_utils import Unpack +from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, is_torch_available +from ...utils.deprecation import deprecate_kwarg +from ...utils.generic import maybe_autocast +from ..auto import AutoModel +from .configuration_neucodec import NeuCodecConfig + + +if is_torch_available(): + import torch + import torch.nn.functional as F + + +@auto_docstring +@dataclass +class NeuCodecOutput(ModelOutput): + r""" + audio_values (`torch.FloatTensor` of shape `(batch_size, 1, sequence_length)`, *optional*): + Decoded audio waveform values in the time domain, obtained using the decoder + part of NeuCodec. These represent the reconstructed audio signal. + audio_codes (`torch.LongTensor` of shape `(batch_size, 1, codes_length)`, *optional*): + Discrete code embeddings computed using `model.encode`. These are the quantized + representations of the input audio used for further processing or generation. + latents (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`): + Quantized continuous representation of input's embedding. + audio_codes_mask (`torch.int32` of shape `(batch_size, 1, codes_length)`, *optional*): + Downsampled `padding_mask` for indicating valid audio codes in `audio_codes`. + """ + + audio_values: torch.FloatTensor | None = None + audio_codes: torch.LongTensor | None = None + latents: torch.Tensor | None = None + audio_codes_mask: torch.Tensor | None = None + + +@auto_docstring +@dataclass +class NeuCodecEncoderOutput(ModelOutput): + r""" + audio_codes (`torch.LongTensor` of shape `(batch_size, 1, codes_length)`, *optional*): + Discrete code embeddings computed using `model.encode`. These represent + the compressed, quantized form of the input audio signal that can be + used for storage, transmission, or generation. + latents (`torch.Tensor` of shape `(batch_size, dimension, time_steps)`): + Quantized continuous representation of input's embedding. + audio_codes_mask (`torch.int32` of shape `(batch_size, 1, codes_length)`, *optional*): + Downsampled `padding_mask` for indicating valid audio codes in `audio_codes`. + """ + + audio_codes: torch.LongTensor | None = None + latents: torch.Tensor | None = None + audio_codes_mask: torch.Tensor | None = None + + +@auto_docstring +@dataclass +class NeuCodecDecoderOutput(ModelOutput): + r""" + audio_values (`torch.FloatTensor` of shape `(batch_size, 1, segment_length)`, *optional*): + Decoded audio waveform values in the time domain, obtained by converting + the discrete codes back into continuous audio signals. This represents + the reconstructed audio that can be played back. + """ + + audio_values: torch.FloatTensor | None = None + + +class NeuCodecMLP(nn.Module): + def __init__(self, config: NeuCodecConfig): + super().__init__() + self.config = config + self.activation_fn = ACT2FN[config.hidden_act] + self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) + self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=False) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.fc1(hidden_states) + hidden_states = self.activation_fn(hidden_states) + hidden_states = self.fc2(hidden_states) + return hidden_states + + +def rotate_half(x): + """Rotates half the hidden dims of the input.""" + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + +@use_kernel_forward_from_hub("rotary_pos_emb") +def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. + + Args: + q (`torch.Tensor`): The query tensor. + k (`torch.Tensor`): The key tensor. + cos (`torch.Tensor`): The cosine part of the rotary embedding. + sin (`torch.Tensor`): The sine part of the rotary embedding. + unsqueeze_dim (`int`, *optional*, defaults to 1): + The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and + sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note + that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and + k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes + cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have + the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. + Returns: + `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. + """ + cos = cos.unsqueeze(unsqueeze_dim) + sin = sin.unsqueeze(unsqueeze_dim) + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + return q_embed, k_embed + + +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, + num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + batch, num_key_value_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) + return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +def eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: torch.Tensor | None, + scaling: float, + dropout: float = 0.0, + **kwargs: Unpack[TransformersKwargs], +): + key_states = repeat_kv(key, module.num_key_value_groups) + value_states = repeat_kv(value, module.num_key_value_groups) + + attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling + if attention_mask is not None: + attn_weights = attn_weights + attention_mask + + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) + attn_output = torch.matmul(attn_weights, value_states) + attn_output = attn_output.transpose(1, 2).contiguous() + + return attn_output, attn_weights + + +@use_kernelized_func(apply_rotary_pos_emb) +class NeuCodecAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__(self, config: NeuCodecConfig, layer_idx: int): + super().__init__() + self.config = config + self.layer_idx = layer_idx + self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) + self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads + self.scaling = self.head_dim**-0.5 + self.attention_dropout = config.attention_dropout + self.is_causal = False + + self.q_proj = nn.Linear( + config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias + ) + self.k_proj = nn.Linear( + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias + ) + self.v_proj = nn.Linear( + config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias + ) + self.o_proj = nn.Linear( + config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias + ) + + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, + attention_mask: torch.Tensor | None = None, + past_key_values: Cache | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple[torch.Tensor, torch.Tensor]: + input_shape = hidden_states.shape[:-1] + hidden_shape = (*input_shape, -1, self.head_dim) + + query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) + key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) + value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) + + cos, sin = position_embeddings + # NeuCodec uses position_ids of shape (1, num_attention_heads) so cos/sin have shape + # (batch, num_attention_heads, head_dim). unsqueeze_dim=2 broadcasts correctly against + # q/k of shape (batch, num_heads, seq_len, head_dim), unlike Llama's default of 1. + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, unsqueeze_dim=2) + + if past_key_values is not None: + key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward + ) + + attn_output, attn_weights = attention_interface( + self, + query_states, + key_states, + value_states, + attention_mask, + dropout=0.0 if not self.training else self.attention_dropout, + scaling=self.scaling, + **kwargs, + ) + + attn_output = attn_output.reshape(*input_shape, -1).contiguous() + attn_output = self.o_proj(attn_output) + return attn_output, attn_weights + + +@use_kernel_forward_from_hub("RMSNorm") +class NeuCodecRMSNorm(nn.Module): + def __init__(self, hidden_size, eps: float = 1e-6) -> None: + """ + NeuCodecRMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) + return self.weight * hidden_states.to(input_dtype) + + def extra_repr(self): + return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" + + +class NeuCodecDecoderLayer(GradientCheckpointingLayer): + def __init__(self, config: NeuCodecConfig, layer_idx: int): + super().__init__() + self.hidden_size = config.hidden_size + + self.self_attn = NeuCodecAttention(config=config, layer_idx=layer_idx) + + self.mlp = NeuCodecMLP(config) + self.input_layernorm = NeuCodecRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = NeuCodecRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + past_key_values: Cache | None = None, + use_cache: bool | None = False, + position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> torch.Tensor: + residual = hidden_states + hidden_states = self.input_layernorm(hidden_states) + # Self Attention + hidden_states, _ = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + use_cache=use_cache, + position_embeddings=position_embeddings, + **kwargs, + ) + hidden_states = residual + hidden_states + + # Fully Connected + residual = hidden_states + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + return hidden_states + + +class NeuCodecSnakeBeta(nn.Module): + """ + A modified Snake function which uses separate parameters for the magnitude of the periodic components + Shape: + - Input: (B, C, T) + - Output: (B, C, T), same shape as the input + Parameters: + - alpha - trainable parameter that controls frequency + - beta - trainable parameter that controls magnitude + References: + - This activation function is a modified version based on this paper by Liu Ziyin, Tilman Hartwig, Masahito Ueda: + https://huggingface.co/papers/2006.08195 + """ + + def __init__(self, in_features, alpha=1.0): + super().__init__() + self.in_features = in_features + + # initialize alpha + self.alpha = Parameter(torch.zeros(in_features) * alpha) + self.beta = Parameter(torch.zeros(in_features) * alpha) + + self.no_div_by_zero = 0.000000001 + + def forward(self, hidden_states): + """ + Forward pass of the function. + Applies the function to the input elementwise. + SnakeBeta ∶= x + 1/b * sin^2 (xa) + """ + alpha = self.alpha.unsqueeze(0).unsqueeze(-1) # line up with x to [B, C, T] + beta = self.beta.unsqueeze(0).unsqueeze(-1) + alpha = torch.exp(alpha) + beta = torch.exp(beta) + hidden_states = hidden_states + (1.0 / (beta + self.no_div_by_zero)) * torch.pow( + torch.sin(hidden_states * alpha), 2 + ) + + return hidden_states + + +def kaiser_sinc_filter1d(cutoff, half_width, kernel_size): + """Generates a 1D Kaiser-windowed sinc filter. + + Args: + cutoff (float): Normalized cutoff frequency (0 to 0.5). + half_width (float): Transition bandwidth. + kernel_size (int): Number of filter taps. + + Returns: + torch.Tensor: A tensor of shape (1, 1, kernel_size) representing the filter. + """ + is_even = kernel_size % 2 == 0 + half_size = kernel_size // 2 + + # Compute Kaiser window parameters + delta_f = 4 * half_width + attenuation = 2.285 * (half_size - 1) * math.pi * delta_f + 7.95 + + if attenuation > 50.0: + beta = 0.1102 * (attenuation - 8.7) + elif attenuation >= 21.0: + beta = 0.5842 * (attenuation - 21) ** 0.4 + 0.07886 * (attenuation - 21.0) + else: + beta = 0.0 + + kaiser_window = torch.kaiser_window(kernel_size, beta=beta, periodic=False, dtype=torch.float32) + + # Compute time indices + if is_even: + time_indices = torch.arange(-half_size, half_size) + 0.5 + else: + time_indices = torch.arange(kernel_size) - half_size + + # Compute sinc filter + if cutoff == 0: + return torch.zeros((1, 1, kernel_size), dtype=torch.float32) # Ensures correct shape + + sinc_filter = torch.sinc(2 * cutoff * time_indices) + normalized_filter = 2 * cutoff * kaiser_window * sinc_filter + + # Normalize to ensure sum = 1 (avoid leakage of constant component) + normalized_filter /= normalized_filter.sum() + + return normalized_filter.view(1, 1, kernel_size) + + +class NeuCodecDownSample1d(nn.Module): + def __init__(self, ratio=2, kernel_size=None): + super().__init__() + cutoff = 0.5 / ratio + half_width = 0.6 / ratio + self.cutoff = cutoff + self.half_width = half_width + self.kernel_size = kernel_size + + if cutoff < 0.0: + raise ValueError("Minimum cutoff must be larger than zero.") + if cutoff > 0.5: + raise ValueError("A cutoff above 0.5 does not make sense.") + + self.even = kernel_size % 2 == 0 + self.pad_left = kernel_size // 2 - int(self.even) + self.pad_right = kernel_size // 2 + self.stride = ratio + filter = kaiser_sinc_filter1d(cutoff, half_width, kernel_size) + self.filter = nn.Buffer(filter, persistent=False) + + def forward(self, hidden_states): + channels = hidden_states.shape[1] + hidden_states = F.pad(hidden_states, (self.pad_left, self.pad_right), mode="replicate") + out = F.conv1d( + hidden_states, + # add casting to avoid dtype mismatch for SDPA + self.filter.to(hidden_states.dtype).expand(channels, -1, -1), + stride=self.stride, + groups=channels, + ) + return out + + +class NeuCodecUpSample1d(nn.Module): + def __init__(self, ratio=2, kernel_size=None): + super().__init__() + self.ratio = ratio + self.kernel_size = int(6 * ratio // 2) * 2 if kernel_size is None else kernel_size + self.stride = ratio + self.pad = self.kernel_size // ratio - 1 + self.pad_left = self.pad * self.stride + (self.kernel_size - self.stride) // 2 + self.pad_right = self.pad * self.stride + (self.kernel_size - self.stride + 1) // 2 + + filter = kaiser_sinc_filter1d(cutoff=0.5 / ratio, half_width=0.6 / ratio, kernel_size=self.kernel_size) + self.filter = nn.Buffer(filter, persistent=False) + + def forward(self, hidden_states): + channels = hidden_states.shape[1] + hidden_states = F.pad(hidden_states, (self.pad, self.pad), mode="replicate") + hidden_states = self.ratio * F.conv_transpose1d( + hidden_states, + # add casting to avoid dtype mismatch for SDPA + self.filter.to(hidden_states.dtype).expand(channels, -1, -1), + stride=self.stride, + groups=channels, + ) + hidden_states = hidden_states[..., self.pad_left : -self.pad_right] + return hidden_states + + +class NeuCodecFiniteScalarQuantization(nn.Module): + """ + Finite Scalar Quantization (FSQ) module that quantizes continuous latent representations into discrete codes. + Original code: https://github.com/lucidrains/vector-quantize-pytorch/blob/353d46027888dfb140c3c65a67a7356f1492d71d/vector_quantize_pytorch/finite_scalar_quantization.py#L64 + + Original modeling uses `ResidualFSQ` with a single quantizer: https://huggingface.co/HKUSTAudio/neucodec/blob/main/vq/codec_decoder_vocos.py#L389 + But we can directly use FSQ since a main feature of NeuCodec is that it uses a single codebook. + """ + + def __init__(self, config: NeuCodecConfig): + super().__init__() + self.quantization_levels = list(config.quantization_levels) + levels, basis, codebook = self._compute_buffers() + self.levels = nn.Buffer(levels, persistent=False) + self.basis = nn.Buffer(basis, persistent=False) + self.codebook = nn.Buffer(codebook, persistent=False) + + def _compute_buffers(self, device=None): + """Compute the levels, basis, and codebook buffers for the FSQ quantizer.""" + levels = torch.tensor(self.quantization_levels, dtype=torch.int32, device=device) + basis = torch.cumprod( + torch.tensor([1] + self.quantization_levels[:-1], device=device), dim=0, dtype=torch.int32 + ) + indices = torch.arange(int(np.prod(self.quantization_levels)), device=device).unsqueeze(-1) + level_indices = (indices // basis) % levels + half_width = levels // 2 + codebook = (level_indices - half_width) / half_width + return levels, basis, codebook + + def _indices_to_codes(self, indices: torch.Tensor) -> torch.Tensor: + """ + Convert integer codebook indices to normalized per-dimension codes in [-1, 1]. + """ + indices = indices.unsqueeze(-1) + level_indices = (indices // self.basis) % self.levels + half_width = self.levels // 2 + codes = (level_indices - half_width) / half_width + return codes + + def bound(self, hidden_states: torch.Tensor, eps: float = 1e-3) -> torch.Tensor: + """ + Constrain `hidden_states` to the valid quantization range for each dimension. + + Uses a scaled tanh to soft-clip values into the interval + $[-(L-1)/2, (L-1)/2]$ (offset by 0.5 for even-level dimensions), where $L$ is + the number of quantization levels. The small `eps` margin prevents values from + saturating exactly at the boundary, which would zero out gradients. + + Args: + hidden_states (`torch.Tensor`): Continuous input to be bounded. + eps (`float`, *optional*, defaults to `1e-3`): + Small margin added to the level range to avoid gradient saturation at boundaries. + + Returns: + `torch.Tensor`: Bounded values in the valid quantization range. + """ + half_range = (self.levels - 1) * (1 + eps) / 2 + offset = torch.where(self.levels % 2 == 0, 0.5, 0.0) + shift = (offset / half_range).atanh() + return (hidden_states + shift).tanh() * half_range - offset + + def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + # NOTE: could rewrite to pass tensor to a decorator such that device type is handled internally + original_dtype = hidden_states.dtype + device_type = ( + hidden_states.device.type + if isinstance(hidden_states.device.type, str) and hidden_states.device.type != "mps" + else "cpu" + ) + with maybe_autocast(device_type=device_type, enabled=False): # Force float32 + hidden_states = hidden_states.float() + half_width = self.levels // 2 + # Quantize: bound and round with straight-through gradient + hidden_states = self.bound(hidden_states) + rounded = hidden_states.round() + codes = hidden_states + (rounded - hidden_states).detach() + codes = codes / half_width + # Code to indices + code_scaled = (codes * half_width) + half_width + indices = (code_scaled * self.basis).sum(dim=-1).to(torch.int32) + return codes.to(original_dtype), indices + + +class NeuCodecISTFTHead(nn.Module): + """ + Head for converting decoder outputs to waveform via STFT projection and ISTFT. + + Uses custom "same" padding ISTFT from Vocos: + https://github.com/gemelo-ai/vocos/blob/c859e3b7b534f3776a357983029d34170ddd6fc3/vocos/spectral_ops.py#L47 + """ + + def __init__(self, config: NeuCodecConfig): + super().__init__() + self.linear = nn.Linear(config.hidden_size, config.n_fft + 2) + self.n_fft = config.n_fft + self.hop_length = config.hop_length + self.padding = (self.n_fft - self.hop_length) // 2 + window = torch.hann_window(config.n_fft) + self.window = nn.Buffer(window, persistent=False) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + stft_pred = self.linear(hidden_states) + # Keep the frequency axis last for `torch.polar` compatibility with torch.compile + magnitude, phase = stft_pred.chunk(2, dim=-1) + # Cast to float32: complex exponential and irfft are not supported for fp16 (ComplexHalf) + magnitude = magnitude.float() + phase = phase.float() + # Clamp like original: https://huggingface.co/HKUSTAudio/neucodec/blob/main/vq/codec_decoder_vocos.py#L138 + magnitude = torch.exp(magnitude).clamp(max=1e2) + spectrogram_complex = torch.polar(magnitude, phase) + + # Back to audio (ISTFT with manual "same" padding: torch.istft lacks a native same-padding mode, + # so we use irfft + fold with explicit pre-computed padding to replicate it) + time_frames = torch.fft.irfft(spectrogram_complex, self.n_fft, dim=-1, norm="backward").transpose(1, 2) + time_frames = time_frames * self.window[None, :, None] + num_frames = spectrogram_complex.shape[1] + output_size = (num_frames - 1) * self.hop_length + self.n_fft + audio = F.fold( + time_frames, + output_size=(1, output_size), + kernel_size=(1, self.n_fft), + stride=(1, self.hop_length), + )[:, 0, 0, self.padding : -self.padding] + + # Normalize + window_envelope = F.fold( + self.window.square().expand(1, num_frames, -1).transpose(1, 2), + output_size=(1, output_size), + kernel_size=(1, self.n_fft), + stride=(1, self.hop_length), + ).squeeze()[self.padding : -self.padding] + # Clamp as expected by original: https://huggingface.co/HKUSTAudio/neucodec/blob/main/vq/codec_decoder_vocos.py#L82 + window_envelope = window_envelope.clamp(min=1e-11) + audio = audio / window_envelope + return audio.unsqueeze(1) + + +@auto_docstring +class NeuCodecPreTrainedModel(PreTrainedModel): + config: NeuCodecConfig + base_model_prefix = "neucodec" + input_modalities = ("audio",) + supports_gradient_checkpointing = True + _no_split_modules = None + _skip_keys_device_placement = ["past_key_values"] + _supports_flash_attn = True + _supports_sdpa = True + _supports_flex_attn = True + _supports_cache_class = True + _supports_attention_backend = True + _can_compile_fullgraph = True + main_input_name = "input_values" + _can_record_outputs = { + "hidden_states": NeuCodecDecoderLayer, + "attentions": NeuCodecDecoderLayer, + } + + def _init_weights(self, module): + super()._init_weights(module) + if isinstance(module, NeuCodecSnakeBeta): + init.zeros_(module.alpha) + init.zeros_(module.beta) + elif isinstance(module, NeuCodecISTFTHead): + window = torch.hann_window(module.n_fft) + init.copy_(module.window, window) + elif isinstance(module, NeuCodecFiniteScalarQuantization): + levels, basis, codebook = module._compute_buffers(device=module.levels.device) + init.copy_(module.levels, levels) + init.copy_(module.basis, basis) + init.copy_(module.codebook, codebook) + elif isinstance(module, NeuCodecUpSample1d): + filter_tensor = kaiser_sinc_filter1d(0.5 / module.ratio, 0.6 / module.ratio, module.kernel_size) + init.copy_(module.filter, filter_tensor) + elif isinstance(module, NeuCodecDownSample1d): + filter_tensor = kaiser_sinc_filter1d(module.cutoff, module.half_width, module.kernel_size) + init.copy_(module.filter, filter_tensor) + + +class NeuCodecRotaryEmbedding(nn.Module): + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: NeuCodecConfig, device=None): + super().__init__() + self.max_seq_len_cached = config.max_position_embeddings + self.original_max_seq_len = config.max_position_embeddings + + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_default_rope_parameters + if self.rope_type != "default": + rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_default_rope_parameters(config: NeuCodecConfig, device=None, **kwargs) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + + attention_factor = 1.0 # Unused in this type of RoPE + # Compute the inverse frequencies + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) + def forward(self, x, position_ids): + inv_freq_expanded = ( + self.inv_freq[None, :, None].expand(position_ids.shape[0], -1, 1).to(dtype=torch.float, device=x.device) + ) + position_ids_expanded = position_ids[:, None, :].float() + + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + # Disable any outside autocast context if any, to really force fp32 + with maybe_autocast(device_type=device_type, enabled=False): + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) + emb = torch.cat((freqs, freqs), dim=-1) + cos = emb.cos() * self.attention_scaling + sin = emb.sin() * self.attention_scaling + + return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + + +class NeuCodecAntiAliasedActivation1d(nn.Module): + def __init__( + self, + activation, + up_ratio: int = 2, + down_ratio: int = 2, + up_kernel_size: int = 12, + down_kernel_size: int = 12, + ): + super().__init__() + if not callable(activation): + raise TypeError("Activation function must be callable") + self.act = activation + self.upsample = NeuCodecUpSample1d(up_ratio, up_kernel_size) + self.downsample = NeuCodecDownSample1d(down_ratio, down_kernel_size) + + def forward(self, hidden_states): + hidden_states = self.upsample(hidden_states) + hidden_states = self.act(hidden_states) + hidden_states = self.downsample(hidden_states) + + return hidden_states + + +class NeuCodecResidualUnit(nn.Module): + """ + A residual unit composed of Snake1d and weight-normalized Conv1d layers with dilations. + """ + + def __init__(self, dimension, dilation): + super().__init__() + pad = ((7 - 1) * dilation) // 2 + self.snake1 = NeuCodecAntiAliasedActivation1d(activation=NeuCodecSnakeBeta(dimension)) + self.conv1 = nn.Conv1d(dimension, dimension, kernel_size=7, dilation=dilation, padding=pad) + self.snake2 = NeuCodecAntiAliasedActivation1d(activation=NeuCodecSnakeBeta(dimension)) + self.conv2 = nn.Conv1d(dimension, dimension, kernel_size=1) + + def forward(self, hidden_state): + """ + Forward pass through the residual unit. + + Args: + hidden_state (`torch.Tensor` of shape `(batch_size, channels, time_steps)`): + Input tensor . + + Returns: + output_tensor (`torch.Tensor` of shape `(batch_size, channels, time_steps)`): + Input tensor after passing through the residual unit. + """ + output_tensor = hidden_state + output_tensor = self.conv1(self.snake1(output_tensor)) + output_tensor = self.conv2(self.snake2(output_tensor)) + + padding = (hidden_state.shape[-1] - output_tensor.shape[-1]) // 2 + if padding > 0: + hidden_state = hidden_state[..., padding:-padding] + output_tensor = hidden_state + output_tensor + return output_tensor + + +class NeuCodecEncoderBlock(nn.Module): + """Encoder block used in NEUCODEC encoder.""" + + def __init__(self, config: NeuCodecConfig, stride: int = 1, stride_index: int = 1): + super().__init__() + dimension = config.encoder_hidden_size * 2**stride_index + self.res_unit1 = NeuCodecResidualUnit(dimension // 2, dilation=1) + self.res_unit2 = NeuCodecResidualUnit(dimension // 2, dilation=3) + self.res_unit3 = NeuCodecResidualUnit(dimension // 2, dilation=9) + self.snake1 = NeuCodecAntiAliasedActivation1d(activation=NeuCodecSnakeBeta(dimension // 2)) + self.conv1 = nn.Conv1d( + dimension // 2, dimension, kernel_size=2 * stride, stride=stride, padding=math.ceil(stride / 2) + ) + + def forward(self, hidden_state): + hidden_state = self.res_unit1(hidden_state) + hidden_state = self.res_unit2(hidden_state) + hidden_state = self.snake1(self.res_unit3(hidden_state)) + hidden_state = self.conv1(hidden_state) + + return hidden_state + + +class NeuCodecEncoder(nn.Module): + """NEUCODEC Encoder""" + + def __init__(self, config: NeuCodecConfig): + super().__init__() + + # Create first convolution + self.conv1 = nn.Conv1d(1, config.encoder_hidden_size, kernel_size=7, padding=3) + + self.block = [] + # Create EncoderBlocks that double channels as they downsample by `stride` + for stride_index, stride in enumerate(config.downsampling_ratios): + stride_index = stride_index + 1 + self.block += [NeuCodecEncoderBlock(config, stride=stride, stride_index=stride_index)] + + self.block = nn.ModuleList(self.block) + d_model = config.encoder_hidden_size * 2 ** len(config.downsampling_ratios) + self.snake1 = NeuCodecAntiAliasedActivation1d(activation=NeuCodecSnakeBeta(d_model)) + self.conv2 = nn.Conv1d(d_model, config.hidden_size, kernel_size=3, padding=1) + + def forward(self, hidden_state): + hidden_state = self.conv1(hidden_state) + + for module in self.block: + hidden_state = module(hidden_state) + + hidden_state = self.snake1(hidden_state) + hidden_state = self.conv2(hidden_state) + + return hidden_state + + +class NeuCodecResNetBlock(nn.Module): + def __init__(self, config: NeuCodecConfig): + super().__init__() + self.norm1 = nn.GroupNorm(num_groups=32, num_channels=config.hidden_size, eps=1e-6, affine=True) + self.activation1 = nn.SiLU() + self.conv1 = nn.Conv1d(config.hidden_size, config.hidden_size, kernel_size=3, stride=1, padding=1) + self.norm2 = nn.GroupNorm(num_groups=32, num_channels=config.hidden_size, eps=1e-6, affine=True) + self.activation2 = nn.SiLU() + self.activation_dropout = config.activation_dropout + self.conv2 = nn.Conv1d(config.hidden_size, config.hidden_size, kernel_size=3, stride=1, padding=1) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = hidden_states.transpose(1, 2) + residual = hidden_states + hidden_states = self.norm1(hidden_states) + hidden_states = self.activation1(hidden_states) + hidden_states = self.conv1(hidden_states) + hidden_states = self.norm2(hidden_states) + hidden_states = self.activation2(hidden_states) + hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training) + hidden_states = self.conv2(hidden_states) + return (hidden_states + residual).transpose(1, 2) + + +class NeuCodecQuantizer(nn.Module): + def __init__(self, config: NeuCodecConfig): + super().__init__() + self.quantizer = NeuCodecFiniteScalarQuantization(config) + self.project_in = nn.Linear(config.quantization_dim, len(config.quantization_levels)) + self.project_out = nn.Linear(len(config.quantization_levels), config.quantization_dim) + + def from_codes(self, indices: torch.Tensor) -> torch.Tensor: + indices = indices.squeeze(-1) # Remove channel dimension + codes = self.quantizer.codebook[indices] + return self.project_out(codes) + + def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + hidden_states = self.project_in(hidden_states) + original_dtype = hidden_states.dtype + hidden_states = self.quantizer.bound(hidden_states) # For consistency with original checkpoint + quantized_out, indices = self.quantizer(hidden_states) + quantized_out = self.project_out(quantized_out.to(original_dtype)) + indices = indices.unsqueeze(-1) # Add channel dimension for single codebook + return quantized_out, indices + + +class NeuCodecDecoder(nn.Module): + """Vocos-based decoder with ResNet, Transformer, and ISTFT head for audio reconstruction.""" + + def __init__(self, config: NeuCodecConfig): + super().__init__() + self.fc = nn.Linear(config.hidden_size + config.semantic_model_config.hidden_size, config.hidden_size) + self.embed = nn.Conv1d(config.hidden_size, config.hidden_size, kernel_size=7, padding=3) + self.prior_net = nn.ModuleList([NeuCodecResNetBlock(config), NeuCodecResNetBlock(config)]) + self.num_attention_heads = config.num_attention_heads + self.rotary_emb = NeuCodecRotaryEmbedding(config=config) + self.layers = nn.ModuleList( + [NeuCodecDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + ) + self.post_net = nn.ModuleList([NeuCodecResNetBlock(config), NeuCodecResNetBlock(config)]) + self.norm = nn.LayerNorm(config.hidden_size, eps=1e-6) + self.head = NeuCodecISTFTHead(config) + + def forward(self, hidden_states: torch.Tensor, **kwargs) -> torch.Tensor: + hidden_states = self.fc(hidden_states) + hidden_states = hidden_states.transpose(1, 2) + hidden_states = self.embed(hidden_states) + hidden_states = hidden_states.transpose(1, 2) + + # Conv ResNet + for layer in self.prior_net: + hidden_states = layer(hidden_states) + + # Transformer: (batch, time, hidden) + # position_ids uses num_attention_heads so that RoPE produces cos/sin of shape (batch, num_heads, head_dim), + # which broadcasts correctly against q/k of shape (batch, num_heads, seq_len, head_dim) via unsqueeze_dim=2 + # in `apply_rotary_pos_emb`. NOTE: this is non-standard and could be unsafe under tensor parallelism + # (TP shards see only a subset of heads), but TP is not used for this model in practice. + position_ids = torch.arange(self.num_attention_heads, device=hidden_states.device).unsqueeze(0) + position_embeddings = self.rotary_emb(hidden_states, position_ids) + for layer in self.layers: + hidden_states = layer(hidden_states, position_embeddings=position_embeddings, **kwargs) + + # Conv ResNet + for layer in self.post_net: + hidden_states = layer(hidden_states) + + return self.head(self.norm(hidden_states)) + + +class NeuCodecSemanticAdapter(nn.Module): + def __init__(self, config: NeuCodecConfig): + super().__init__() + self.conv1 = nn.Conv1d( + in_channels=config.semantic_model_config.hidden_size, + out_channels=config.semantic_model_config.hidden_size, + kernel_size=3, + padding=1, + bias=False, + ) + self.act1 = nn.ReLU() + self.conv2 = nn.Conv1d( + config.semantic_model_config.hidden_size, + config.semantic_model_config.hidden_size, + kernel_size=3, + padding=1, + bias=True, + ) + self.act2 = nn.ReLU() + self.conv3 = nn.Conv1d( + config.semantic_model_config.hidden_size, + config.semantic_model_config.hidden_size, + kernel_size=3, + padding=1, + bias=True, + ) + self.conv4 = nn.Conv1d( + in_channels=config.semantic_model_config.hidden_size, + out_channels=config.semantic_model_config.hidden_size, + kernel_size=3, + padding=1, + bias=False, + ) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.conv1(hidden_states) + hidden_states = self.act1(hidden_states) + residual = hidden_states + hidden_states = self.conv2(hidden_states) + hidden_states = self.act2(hidden_states) + hidden_states = self.conv3(hidden_states) + hidden_states = hidden_states + residual + hidden_states = self.conv4(hidden_states) + return hidden_states + + +@auto_docstring(custom_intro="NeuCodec neural audio codec model.") +class NeuCodecModel(NeuCodecPreTrainedModel): + config_class = NeuCodecConfig + + def __init__(self, config: NeuCodecConfig): + super().__init__(config) + # `Xcodec2Model.hop_length` mirrors `config.hop_length`, which for NeuCodec is expressed in the decoder's + # (24kHz) domain. The mask arithmetic in `encode()` operates on `input_values` in the encoder's (16kHz) + # domain, so it must use the un-rescaled hop length instead. + self.hop_length = config.encoder_hop_length + self.semantic_encoder = AutoModel.from_config(config.semantic_model_config) + self.semantic_adapter = NeuCodecSemanticAdapter(config) + self.acoustic_encoder = NeuCodecEncoder(config) + self.fc_encoder = nn.Linear( + config.hidden_size + config.semantic_model_config.hidden_size, + config.hidden_size + config.semantic_model_config.hidden_size, + ) + self.quantizer = NeuCodecQuantizer(config) + self.acoustic_decoder = NeuCodecDecoder(config) + self.sample_rate_conversion_factor = config.output_sampling_rate / config.input_sampling_rate + + self.post_init() + + @auto_docstring + @can_return_tuple + def encode( + self, + input_values: torch.Tensor, + input_features: torch.Tensor, + padding_mask: torch.Tensor | None = None, + input_features_mask: torch.Tensor | None = None, + output_latents: bool = False, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | NeuCodecEncoderOutput: + r""" + input_values (`torch.Tensor` of shape `(batch_size, 1, sequence_length)`): + Input audio waveform. + input_features (`torch.Tensor` of shape `(batch_size, mel_bins, time_steps)`): + Input audio mel spectrogram for semantic encoding. + padding_mask (`torch.Tensor` of shape `(batch_size, 1, sequence_length)`): + Padding mask used to pad `input_values`. + input_features_mask (`torch.Tensor` of shape `(batch_size, time_steps)`, *optional*): + Attention mask for the spectrogram input to the semantic encoder. `1` for valid frames, `0` for padding. + output_latents (`bool`, *optional*, defaults to `False`): + Whether to return the continuous latent representation from the quantizer. + """ + + # Semantic embedding + with torch.no_grad(): + semantic_output = self.semantic_encoder(input_features, attention_mask=input_features_mask) + semantic_hidden_states = semantic_output.last_hidden_state.transpose(1, 2) + semantic_hidden_states = self.semantic_adapter(semantic_hidden_states) + + # Acoustic embedding + acoustic_hidden_states = self.acoustic_encoder(input_values) + + # The two branches downsample independently and can differ by a frame; trim to the shorter one, matching + # the reference: https://github.com/neuphonic/neucodec/blob/ed3e6cd1bdc374ce14a21355e5eee66a777149ce/neucodec/model.py#L173 + min_length = min(acoustic_hidden_states.shape[-1], semantic_hidden_states.shape[-1]) + acoustic_hidden_states = acoustic_hidden_states[..., :min_length] + semantic_hidden_states = semantic_hidden_states[..., :min_length] + + hidden_states = torch.cat([semantic_hidden_states, acoustic_hidden_states], dim=1) + hidden_states = self.fc_encoder(hidden_states.transpose(1, 2)) + + # Quantize + latents, audio_codes = self.quantizer(hidden_states) + latents = latents.transpose(1, 2) + audio_codes = audio_codes.transpose(1, 2) + + # If provided, compute corresponding padding mask for audio codes + audio_codes_mask = None + if padding_mask is not None: + audio_length = padding_mask.sum(dim=-1, keepdim=True) + audio_length = audio_length * self.sample_rate_conversion_factor + token_length = audio_length // self.hop_length + idx = torch.arange(audio_codes.shape[-1], device=padding_mask.device).view(1, -1) + audio_codes_mask = (idx < token_length).to(padding_mask.dtype) + + return NeuCodecEncoderOutput( + audio_codes=audio_codes, + latents=latents if output_latents else None, + audio_codes_mask=audio_codes_mask, + ) + + @auto_docstring + @can_return_tuple + def decode( + self, + audio_codes: torch.Tensor | None = None, + latents: torch.Tensor | None = None, + audio_codes_mask: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | NeuCodecDecoderOutput: + r""" + audio_codes (`torch.LongTensor` of shape `(batch_size, 1, codes_length)`): + Discrete code indices computed using `model.encode`. + latents (torch.Tensor of shape `(batch_size, dimension, time_steps)`, *optional*): + Quantized continuous representation of input. + audio_codes_mask (`torch.Tensor` of shape `(batch_size, codes_length)`, *optional*): + Mask marking valid (non-padding) positions, as returned by `model.encode`. Needed for correct + batched decoding of variable-length audio. + """ + if latents is None and audio_codes is None: + raise ValueError("Either `latents` or `audio_codes` must be provided.") + + if audio_codes is not None: + latents = self.quantizer.from_codes(audio_codes.transpose(1, 2)) + else: + latents = latents.transpose(1, 2) + + # Difference to xcodec2 is the additional mask + attention_mask = create_bidirectional_mask( + config=self.config, + inputs_embeds=latents, + attention_mask=audio_codes_mask, + ) + + recon_audio = self.acoustic_decoder(latents, attention_mask=attention_mask, **kwargs) + return NeuCodecDecoderOutput(audio_values=recon_audio) + + @auto_docstring + @can_return_tuple + def forward( + self, + input_values: torch.Tensor, + input_features: torch.Tensor, + padding_mask: torch.Tensor | None = None, + input_features_mask: torch.Tensor | None = None, + output_latents: bool = False, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | NeuCodecOutput: + r""" + input_values (`torch.Tensor` of shape `(batch_size, 1, sequence_length)`): + Input audio waveform, sampled at `config.input_sampling_rate`. + input_features (`torch.Tensor` of shape `(batch_size, mel_bins, time_steps)`): + Input audio mel spectrogram for semantic encoding. + padding_mask (`torch.Tensor` of shape `(batch_size, 1, sequence_length)`): + Padding mask used to pad `input_values`. + input_features_mask (`torch.Tensor` of shape `(batch_size, time_steps)`, *optional*): + Attention mask for the spectrogram input to the semantic encoder. `1` for valid frames, `0` for padding. + output_latents (`bool`, *optional*, defaults to `False`): + Whether to return the continuous latent representation from the quantizer. + + Examples: + + ```python + >>> from datasets import load_dataset + >>> from transformers import AutoFeatureExtractor, NeuCodecModel + + >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + >>> audio = dataset["train"]["audio"][0]["array"] + + >>> model_id = "neuphonic/neucodec" + >>> model = NeuCodecModel.from_pretrained(model_id) + >>> feature_extractor = AutoFeatureExtractor.from_pretrained(model_id) + + >>> inputs = feature_extractor(audio=audio, sampling_rate=feature_extractor.sampling_rate, return_tensors="pt") + + >>> outputs = model(**inputs) + >>> audio_codes = outputs.audio_codes + >>> audio_values = outputs.audio_values # sampled at 24kHz + ```""" + # NeuCodec's decoder outputs audio at `output_sampling_rate`, which differs from the `input_sampling_rate` of + input_length = input_values.shape[-1] + output_length = int(input_length * self.sample_rate_conversion_factor) + + encoder_outputs = self.encode( + input_values, + input_features=input_features, + padding_mask=padding_mask, + input_features_mask=input_features_mask, + output_latents=True, + return_dict=True, + ) + audio_values = self.decode( + latents=encoder_outputs.latents, + audio_codes_mask=encoder_outputs.audio_codes_mask, + return_dict=True, + **kwargs, + )[0][..., :output_length] + + return NeuCodecOutput( + audio_values=audio_values, + audio_codes=encoder_outputs.audio_codes, + latents=encoder_outputs.latents if output_latents else None, + audio_codes_mask=encoder_outputs.audio_codes_mask, + ) + + +__all__ = ["NeuCodecModel", "NeuCodecPreTrainedModel"] diff --git a/src/transformers/models/neucodec/modular_neucodec.py b/src/transformers/models/neucodec/modular_neucodec.py new file mode 100644 index 000000000000..90e07b982e21 --- /dev/null +++ b/src/transformers/models/neucodec/modular_neucodec.py @@ -0,0 +1,444 @@ +# 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. + +import numpy as np +from huggingface_hub.dataclasses import strict + +from ...audio_utils import AudioInput, make_list_of_audio +from ...feature_extraction_utils import BatchFeature +from ...masking_utils import create_bidirectional_mask +from ...processing_utils import Unpack +from ...utils import ( + PaddingStrategy, + TensorType, + TransformersKwargs, + auto_docstring, + can_return_tuple, + is_torch_available, + logging, +) +from ...utils.import_utils import is_torchaudio_available, requires +from ..xcodec2.configuration_xcodec2 import Xcodec2Config +from ..xcodec2.feature_extraction_xcodec2 import Xcodec2FeatureExtractor +from ..xcodec2.modeling_xcodec2 import ( + Xcodec2DecoderOutput, + Xcodec2EncoderOutput, + Xcodec2Model, + Xcodec2Output, + Xcodec2PreTrainedModel, +) + + +if is_torch_available(): + import torch + import torch.nn.functional as F + +if is_torchaudio_available(): + import torchaudio + + +logger = logging.get_logger(__name__) + + +@auto_docstring(checkpoint="neuphonic/neucodec") +@strict +class NeuCodecConfig(Xcodec2Config): + r""" + downsampling_ratios (`list[int]`, *optional*, defaults to `[2, 2, 4, 4, 5]`): + Ratios for downsampling in the encoder. + semantic_model_config (`Union[Dict, Wav2Vec2BertConfig]`, *optional*): + An instance of the configuration object for the semantic (Wav2Vec2BertConfig) model. + quantization_dim (`int`, *optional*, defaults to 2048): + Dimension for the vector quantization codebook. + quantization_levels (`list[int]`, *optional*, defaults to `[4, 4, 4, 4, 4, 4, 4, 4]`): + Levels for the vector quantization codebook. + input_sampling_rate (`int`, *optional*, defaults to 16000): + Sampling rate, in hertz (Hz), of the encoder's input audio waveform. + output_sampling_rate (`int`, *optional*, defaults to 24000): + Sampling rate, in hertz (Hz), of the decoder's output audio waveform. + + Example: + + ```python + >>> from transformers import NeuCodecConfig, NeuCodecModel + + >>> # Initializing configuration + >>> configuration = NeuCodecConfig() + + >>> # Initializing a model (with random weights) from the configuration + >>> model = NeuCodecModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "neucodec" + input_sampling_rate: int = 16_000 + output_sampling_rate: int = 24_000 + sampling_rate = AttributeError() + + @property + def encoder_hop_length(self) -> int: + """Hop length, in samples at `input_sampling_rate`, between successive codes (i.e. the encoder frame rate).""" + return int(np.prod(self.downsampling_ratios)) + + @property + def hop_length(self) -> int: + # The ISTFT head (which reads `hop_length`/`n_fft` off the config) synthesizes audio at + # `output_sampling_rate`, so the encoder's native hop_length is rescaled into that domain. + return int(self.encoder_hop_length * self.output_sampling_rate / self.input_sampling_rate) + + +class NeuCodecOutput(Xcodec2Output): + pass + + +class NeuCodecEncoderOutput(Xcodec2EncoderOutput): + pass + + +class NeuCodecDecoderOutput(Xcodec2DecoderOutput): + pass + + +class NeuCodecPreTrainedModel(Xcodec2PreTrainedModel): + pass + + +@auto_docstring(custom_intro="NeuCodec neural audio codec model.") +class NeuCodecModel(Xcodec2Model): + def __init__(self, config: NeuCodecConfig): + super().__init__(config) + # `Xcodec2Model.hop_length` mirrors `config.hop_length`, which for NeuCodec is expressed in the decoder's + # (24kHz) domain. The mask arithmetic in `encode()` operates on `input_values` in the encoder's (16kHz) + # domain, so it must use the un-rescaled hop length instead. + self.hop_length = config.encoder_hop_length + self.sample_rate_conversion_factor = config.output_sampling_rate / config.input_sampling_rate + + @auto_docstring + @can_return_tuple + def encode( + self, + input_values: torch.Tensor, + input_features: torch.Tensor, + padding_mask: torch.Tensor | None = None, + input_features_mask: torch.Tensor | None = None, + output_latents: bool = False, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | NeuCodecEncoderOutput: + r""" + input_values (`torch.Tensor` of shape `(batch_size, 1, sequence_length)`): + Input audio waveform. + input_features (`torch.Tensor` of shape `(batch_size, mel_bins, time_steps)`): + Input audio mel spectrogram for semantic encoding. + padding_mask (`torch.Tensor` of shape `(batch_size, 1, sequence_length)`): + Padding mask used to pad `input_values`. + input_features_mask (`torch.Tensor` of shape `(batch_size, time_steps)`, *optional*): + Attention mask for the spectrogram input to the semantic encoder. `1` for valid frames, `0` for padding. + output_latents (`bool`, *optional*, defaults to `False`): + Whether to return the continuous latent representation from the quantizer. + """ + + # Semantic embedding + with torch.no_grad(): + semantic_output = self.semantic_encoder(input_features, attention_mask=input_features_mask) + semantic_hidden_states = semantic_output.last_hidden_state.transpose(1, 2) + semantic_hidden_states = self.semantic_adapter(semantic_hidden_states) + + # Acoustic embedding + acoustic_hidden_states = self.acoustic_encoder(input_values) + + # The two branches downsample independently and can differ by a frame; trim to the shorter one, matching + # the reference: https://github.com/neuphonic/neucodec/blob/ed3e6cd1bdc374ce14a21355e5eee66a777149ce/neucodec/model.py#L173 + min_length = min(acoustic_hidden_states.shape[-1], semantic_hidden_states.shape[-1]) + acoustic_hidden_states = acoustic_hidden_states[..., :min_length] + semantic_hidden_states = semantic_hidden_states[..., :min_length] + + hidden_states = torch.cat([semantic_hidden_states, acoustic_hidden_states], dim=1) + hidden_states = self.fc_encoder(hidden_states.transpose(1, 2)) + + # Quantize + latents, audio_codes = self.quantizer(hidden_states) + latents = latents.transpose(1, 2) + audio_codes = audio_codes.transpose(1, 2) + + # If provided, compute corresponding padding mask for audio codes + audio_codes_mask = None + if padding_mask is not None: + audio_length = padding_mask.sum(dim=-1, keepdim=True) + audio_length = audio_length * self.sample_rate_conversion_factor + token_length = audio_length // self.hop_length + idx = torch.arange(audio_codes.shape[-1], device=padding_mask.device).view(1, -1) + audio_codes_mask = (idx < token_length).to(padding_mask.dtype) + + return NeuCodecEncoderOutput( + audio_codes=audio_codes, + latents=latents if output_latents else None, + audio_codes_mask=audio_codes_mask, + ) + + @auto_docstring + @can_return_tuple + def decode( + self, + audio_codes: torch.Tensor | None = None, + latents: torch.Tensor | None = None, + audio_codes_mask: torch.Tensor | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | NeuCodecDecoderOutput: + r""" + audio_codes (`torch.LongTensor` of shape `(batch_size, 1, codes_length)`): + Discrete code indices computed using `model.encode`. + latents (torch.Tensor of shape `(batch_size, dimension, time_steps)`, *optional*): + Quantized continuous representation of input. + audio_codes_mask (`torch.Tensor` of shape `(batch_size, codes_length)`, *optional*): + Mask marking valid (non-padding) positions, as returned by `model.encode`. Needed for correct + batched decoding of variable-length audio. + """ + if latents is None and audio_codes is None: + raise ValueError("Either `latents` or `audio_codes` must be provided.") + + if audio_codes is not None: + latents = self.quantizer.from_codes(audio_codes.transpose(1, 2)) + else: + latents = latents.transpose(1, 2) + + # Difference to xcodec2 is the additional mask + attention_mask = create_bidirectional_mask( + config=self.config, + inputs_embeds=latents, + attention_mask=audio_codes_mask, + ) + + recon_audio = self.acoustic_decoder(latents, attention_mask=attention_mask, **kwargs) + return NeuCodecDecoderOutput(audio_values=recon_audio) + + @auto_docstring + @can_return_tuple + def forward( + self, + input_values: torch.Tensor, + input_features: torch.Tensor, + padding_mask: torch.Tensor | None = None, + input_features_mask: torch.Tensor | None = None, + output_latents: bool = False, + **kwargs: Unpack[TransformersKwargs], + ) -> tuple | NeuCodecOutput: + r""" + input_values (`torch.Tensor` of shape `(batch_size, 1, sequence_length)`): + Input audio waveform, sampled at `config.input_sampling_rate`. + input_features (`torch.Tensor` of shape `(batch_size, mel_bins, time_steps)`): + Input audio mel spectrogram for semantic encoding. + padding_mask (`torch.Tensor` of shape `(batch_size, 1, sequence_length)`): + Padding mask used to pad `input_values`. + input_features_mask (`torch.Tensor` of shape `(batch_size, time_steps)`, *optional*): + Attention mask for the spectrogram input to the semantic encoder. `1` for valid frames, `0` for padding. + output_latents (`bool`, *optional*, defaults to `False`): + Whether to return the continuous latent representation from the quantizer. + + Examples: + + ```python + >>> from datasets import load_dataset + >>> from transformers import AutoFeatureExtractor, NeuCodecModel + + >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + >>> audio = dataset["train"]["audio"][0]["array"] + + >>> model_id = "neuphonic/neucodec" + >>> model = NeuCodecModel.from_pretrained(model_id) + >>> feature_extractor = AutoFeatureExtractor.from_pretrained(model_id) + + >>> inputs = feature_extractor(audio=audio, sampling_rate=feature_extractor.sampling_rate, return_tensors="pt") + + >>> outputs = model(**inputs) + >>> audio_codes = outputs.audio_codes + >>> audio_values = outputs.audio_values # sampled at 24kHz + ```""" + # NeuCodec's decoder outputs audio at `output_sampling_rate`, which differs from the `input_sampling_rate` of + input_length = input_values.shape[-1] + output_length = int(input_length * self.sample_rate_conversion_factor) + + encoder_outputs = self.encode( + input_values, + input_features=input_features, + padding_mask=padding_mask, + input_features_mask=input_features_mask, + output_latents=True, + return_dict=True, + ) + audio_values = self.decode( + latents=encoder_outputs.latents, + audio_codes_mask=encoder_outputs.audio_codes_mask, + return_dict=True, + **kwargs, + )[0][..., :output_length] + + return NeuCodecOutput( + audio_values=audio_values, + audio_codes=encoder_outputs.audio_codes, + latents=encoder_outputs.latents if output_latents else None, + audio_codes_mask=encoder_outputs.audio_codes_mask, + ) + + +class NeuCodecFeatureExtractor(Xcodec2FeatureExtractor): + @requires(backends=("torch", "torchaudio")) + def __call__( + self, + audio: AudioInput, + padding: bool | str | PaddingStrategy = True, + max_length: int | None = None, + truncation: bool = False, + return_tensors: str | TensorType | None = None, + sampling_rate: int | None = None, + device: str = "cpu", + **kwargs, + ) -> BatchFeature: + """ + Args: + audio (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`): + Numpy array or torch tensor with shape (num_channels, sequence_length). A list of such arrays or + tensors can also be provided for a batch of inputs. + padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`): + Select a strategy to pad the returned sequences (according to the model's padding side and padding + index) among: + + - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single + sequence if provided). + - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum + acceptable input length for the model if that argument is not provided. + - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different + lengths). + max_length (`int`, *optional*): + Maximum length of the returned list and optionally padding length (see above). + truncation (`bool`): + Activates truncation to cut input sequences longer than *max_length* to *max_length*. + return_tensors (`str` or [`~utils.TensorType`], *optional*): + If set, will return tensors instead of list of python integers. Acceptable values are: + + - `'tf'`: Return TensorFlow `tf.constant` objects. + - `'pt'`: Return PyTorch `torch.Tensor` objects. + - `'np'`: Return Numpy `np.ndarray` objects. + sampling_rate (`int`, *optional*): + The sample rate at which the `audio` input was sampled. It is strongly recommended to pass + `sampling_rate` at the forward call to prevent silent errors. + device (`str`, *optional*, defaults to `"cpu"`): + Device for PyTorch tensors during mel-filter bank feature extraction. + kwargs (*optional*): + Remaining dictionary of keyword arguments that will be passed to the tokenizer or the feature + extractor. + """ + + if sampling_rate is not None: + if sampling_rate != self.sampling_rate: + raise ValueError( + f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of" + f" {self.sampling_rate}. Please make sure that the provided `audio` input was sampled with" + f" {self.sampling_rate} and not {sampling_rate}." + ) + else: + logger.warning( + f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. " + "Failing to do so can result in silent errors that might be hard to debug." + ) + + audio = make_list_of_audio(audio) + for example in audio: + if example.ndim > 2: + raise ValueError(f"Expected input shape (channels, length) but got shape {example.shape}") + batch_size = len(audio) + + # 1) Acoustic encoder padding + audio = [F.pad(torch.as_tensor(a), (0, 1), value=0.0) for a in audio] + padded_inputs = self.acoustic_encoder_padder.pad( + BatchFeature({"audio": audio}), + max_length=max_length, + truncation=truncation, + padding=padding, + return_attention_mask=padding, + pad_to_multiple_of=self.hop_length, + return_tensors="pt", + ) + padding_mask = padded_inputs.pop("attention_mask") + padded_audio = padded_inputs["audio"][:, None, :] + + # 2) Semantic encoder feature extraction (mel spectrogram). Unlike Xcodec2FeatureExtractor, NeuCodec's + # reference implementation feeds the acoustic-padded waveform directly into the mel computation, with no extra + # "valid_len" trimming or symmetric hop-sized padding: https://github.com/neuphonic/neucodec/blob/ed3e6cd1bdc374ce14a21355e5eee66a777149ce/neucodec/model.py#L128 + # Padded per-sample (not via the batch-collated `padded_audio`): the CMVN normalization below is computed + # over the whole padded signal, so batch-padding a short sample to the batch's longest would skew it. + # TODO (ebezzam): can batch processing be done without regression from expected outputs? + mel_features = [] + for i in range(batch_size): + single_padded_audio = self.acoustic_encoder_padder.pad( + BatchFeature({"audio": [audio[i]]}), + pad_to_multiple_of=self.hop_length, + return_tensors="pt", + ) + waveform = single_padded_audio["audio"].to(device) + features = torchaudio.compliance.kaldi.fbank( + waveform * (2**15), + num_mel_bins=self.num_mel_bins, + frame_length=self.frame_length / self.sampling_rate * 1000, + frame_shift=self.frame_shift / self.sampling_rate * 1000, + sample_frequency=self.sampling_rate, + window_type="povey", + preemphasis_coefficient=0.97, + remove_dc_offset=True, + use_log_fbank=True, + use_energy=False, + dither=0.0, + snip_edges=True, + low_freq=20, + high_freq=self.sampling_rate // 2, + ) + features = (features - features.mean(0)) / torch.sqrt(features.var(0, unbiased=True) + 1e-7) + mel_features.append(features) + encoded_inputs = BatchFeature({"input_features": mel_features}) + padded_mel = self.pad( + encoded_inputs, + padding=padding, + max_length=max_length, + truncation=truncation, + pad_to_multiple_of=self.stride, + return_attention_mask=padding, + return_tensors="pt", + ) + audio_spectrogram = padded_mel["input_features"] + spectrogram_mask = padded_mel.get("attention_mask") + trimmed_frames = audio_spectrogram.shape[1] - (audio_spectrogram.shape[1] % self.stride) + audio_spectrogram = audio_spectrogram[:, :trimmed_frames, :].reshape( + batch_size, trimmed_frames // self.stride, self.num_mel_bins * self.stride + ) + if spectrogram_mask is not None: + spectrogram_mask = ( + spectrogram_mask[:, :trimmed_frames] + .reshape(batch_size, trimmed_frames // self.stride, self.stride) + .min(dim=-1) + .values + ) + + return BatchFeature( + { + "input_values": padded_audio, + "padding_mask": padding_mask, + "input_features": audio_spectrogram, + "input_features_mask": spectrogram_mask, + }, + tensor_type=return_tensors, + ) + + +__all__ = ["NeuCodecConfig", "NeuCodecModel", "NeuCodecPreTrainedModel", "NeuCodecFeatureExtractor"] diff --git a/src/transformers/models/xcodec2/modeling_xcodec2.py b/src/transformers/models/xcodec2/modeling_xcodec2.py index 64612b5cf871..7a419f037a3d 100644 --- a/src/transformers/models/xcodec2/modeling_xcodec2.py +++ b/src/transformers/models/xcodec2/modeling_xcodec2.py @@ -761,8 +761,9 @@ def __init__(self, config: Xcodec2Config): self.window = nn.Buffer(window, persistent=False) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - stft_pred = self.linear(hidden_states).transpose(1, 2) - magnitude, phase = stft_pred.chunk(2, dim=1) + stft_pred = self.linear(hidden_states) + # Keep the frequency axis last for `torch.polar` compatibility with torch.compile + magnitude, phase = stft_pred.chunk(2, dim=-1) # Cast to float32: complex exponential and irfft are not supported for fp16 (ComplexHalf) magnitude = magnitude.float() phase = phase.float() @@ -772,9 +773,9 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # Back to audio (ISTFT with manual "same" padding: torch.istft lacks a native same-padding mode, # so we use irfft + fold with explicit pre-computed padding to replicate it) - time_frames = torch.fft.irfft(spectrogram_complex, self.n_fft, dim=1, norm="backward") + time_frames = torch.fft.irfft(spectrogram_complex, self.n_fft, dim=-1, norm="backward").transpose(1, 2) time_frames = time_frames * self.window[None, :, None] - num_frames = spectrogram_complex.shape[-1] + num_frames = spectrogram_complex.shape[1] output_size = (num_frames - 1) * self.hop_length + self.n_fft audio = F.fold( time_frames, diff --git a/src/transformers/models/xcodec2/modular_xcodec2.py b/src/transformers/models/xcodec2/modular_xcodec2.py index f376ea898983..0539c914f61b 100644 --- a/src/transformers/models/xcodec2/modular_xcodec2.py +++ b/src/transformers/models/xcodec2/modular_xcodec2.py @@ -444,8 +444,9 @@ def __init__(self, config: Xcodec2Config): self.window = nn.Buffer(window, persistent=False) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: - stft_pred = self.linear(hidden_states).transpose(1, 2) - magnitude, phase = stft_pred.chunk(2, dim=1) + stft_pred = self.linear(hidden_states) + # Keep the frequency axis last for `torch.polar` compatibility with torch.compile + magnitude, phase = stft_pred.chunk(2, dim=-1) # Cast to float32: complex exponential and irfft are not supported for fp16 (ComplexHalf) magnitude = magnitude.float() phase = phase.float() @@ -455,9 +456,9 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # Back to audio (ISTFT with manual "same" padding: torch.istft lacks a native same-padding mode, # so we use irfft + fold with explicit pre-computed padding to replicate it) - time_frames = torch.fft.irfft(spectrogram_complex, self.n_fft, dim=1, norm="backward") + time_frames = torch.fft.irfft(spectrogram_complex, self.n_fft, dim=-1, norm="backward").transpose(1, 2) time_frames = time_frames * self.window[None, :, None] - num_frames = spectrogram_complex.shape[-1] + num_frames = spectrogram_complex.shape[1] output_size = (num_frames - 1) * self.hop_length + self.n_fft audio = F.fold( time_frames, diff --git a/tests/fixtures/neucodec/expected_results.json b/tests/fixtures/neucodec/expected_results.json new file mode 100644 index 000000000000..eb36ba9a6c9b --- /dev/null +++ b/tests/fixtures/neucodec/expected_results.json @@ -0,0 +1 @@ +{"dataset_indices": [0, 1, 6, 8, 10, 45, 55, 58, 68, 44], "lengths": [93680, 77040, 90240, 81920, 89600, 92960, 90880, 96000, 90400, 81440], "audio_codes": [[50569, 52425, 49498, 59867, 49222, 52443, 36423, 39115, 57574, 49366, 51674, 33120, 26854, 24658, 43237, 19585, 39381, 22951, 47298, 27761, 38128, 38117, 11430, 28902, 27728, 2277, 39009, 60851, 57003, 45953, 17812, 45906, 8223, 18491, 52465, 42134, 9242, 30470, 2693, 57026, 51366, 64661, 15468, 26632, 25630, 25677, 24479, 8820, 15705, 15925], [39138, 26801, 30933, 21906, 35029, 51354, 50248, 59596, 50774, 49818, 55758, 58698, 62621, 54345, 55453, 52046, 57757, 63705, 49809, 51674, 54608, 25830, 30966, 22577, 25831, 11429, 59557, 58790, 46707, 31926, 31415, 43395, 29528, 65261, 1812, 15992, 3412, 3749, 19925, 3729, 3718, 15120, 42821, 13824, 262, 29216, 13318, 2336, 6682, 32294], [36053, 23770, 55525, 50773, 51406, 49538, 60638, 55879, 55533, 51721, 52701, 55562, 56558, 50465, 36038, 52377, 59434, 44265, 10673, 38132, 22697, 31937, 25697, 22966, 38954, 6630, 55541, 58565, 32029, 1653, 24152, 48098, 17755, 42283, 47508, 45860, 2323, 23971, 62619, 47210, 4158, 29522, 30864, 1362, 6564, 30614, 31723, 31366, 31298, 28309], [52378, 54382, 51418, 53818, 55690, 58665, 55662, 49435, 51534, 57622, 58397, 56428, 37133, 52300, 40974, 43101, 53258, 51468, 53786, 51532, 57637, 55508, 54485, 26849, 11505, 26849, 55730, 58896, 62544, 45393, 43272, 16930, 47377, 47984, 23814, 7195, 3113, 1049, 16391, 9225, 8205, 35485, 40676, 11496, 7876, 59720, 36080, 39137, 28801, 47125], [38326, 26850, 10354, 2533, 51370, 46158, 51630, 6322, 55794, 58725, 41499, 49003, 45970, 45681, 14849, 20117, 47936, 26700, 31072, 48263, 12780, 19801, 49178, 51239, 1058, 50202, 48812, 29869, 23732, 38426, 64793, 62217, 19728, 6916, 28288, 20244, 31377, 36708, 32389, 36453, 32405, 32277, 57305, 55687, 23783, 10358, 10726, 5317, 51402, 54658], [54541, 51404, 54536, 56780, 54622, 56780, 56726, 52684, 55769, 44244, 27766, 30966, 40084, 39401, 26809, 42218, 26736, 6388, 59616, 22661, 12301, 7433, 27555, 65211, 35427, 48311, 43875, 36251, 29282, 16744, 14115, 30595, 33701, 45973, 4890, 5019, 22759, 50338, 8249, 54690, 61808, 42326, 45683, 14342, 17953, 19031, 31019, 7227, 64657, 63853], [50249, 56521, 50441, 56790, 49673, 55770, 53773, 60806, 49428, 56795, 51723, 60889, 49557, 56516, 55682, 22741, 31861, 25829, 26729, 21670, 58848, 18453, 8229, 43670, 27265, 48555, 31329, 3241, 30033, 14658, 1829, 31007, 2159, 3194, 2409, 18603, 2410, 3113, 5148, 23961, 8933, 3492, 918, 15957, 30470, 38728, 13913, 31911, 23929, 28044], [39062, 22753, 26721, 39397, 25721, 26819, 43120, 23002, 35285, 55754, 38101, 52424, 34208, 55722, 56520, 54673, 56542, 17749, 40136, 43430, 40142, 38042, 40136, 39124, 40164, 60633, 61828, 44044, 37189, 48728, 20372, 23992, 31318, 47383, 46603, 44717, 2640, 48216, 45840, 1622, 6647, 59543, 24878, 21078, 38266, 45575, 17445, 14849, 36433, 20245], [39078, 23765, 43145, 44229, 51526, 56713, 54490, 60653, 55687, 51672, 38293, 40152, 44166, 44244, 39329, 39333, 60632, 43381, 42213, 6325, 17830, 53403, 52462, 51440, 60552, 41037, 27661, 14665, 48452, 44608, 36229, 4009, 32235, 64405, 40633, 20112, 31328, 19637, 10038, 38502, 19313, 29877, 39345, 15477, 3429, 32499, 52979, 55530, 43213, 29773], [35045, 22753, 43237, 23956, 58597, 44068, 22745, 42214, 44385, 26777, 39145, 17552, 55454, 38054, 43493, 23653, 38058, 39333, 43173, 47329, 43056, 18645, 26852, 39012, 42214, 27813, 39157, 58789, 59047, 34674, 48624, 9321, 3432, 12826, 13384, 14690, 15779, 3498, 5735, 14950, 13895, 31342, 34779, 23198, 45908, 4621, 794, 15059, 12938, 13080]], "recon_wavs": [[-0.0011008643778041005, -0.001460642903111875, -0.0013364834012463689, -0.0012342293048277497, -0.0016573331085965037, -0.0023596584796905518, -0.0025202888064086437, -0.0016399795422330499, -0.0014380980283021927, -0.0013638949021697044, -0.0008177136187441647, -0.00033787370193749666, 0.00015286594862118363, 0.0008170121000148356, 0.0013126268750056624, 0.0016154992626979947, 0.0019274774240329862, 0.0019568896386772394, 0.0015715231420472264, 0.0012249258579686284, 0.00037908912054263055, -0.0002922161656897515, -0.0012765169376507401, -0.0022736473474651575, -0.0030617560259997845, -0.0033180934842675924, -0.0028942336793988943, -0.0016975098988041282, -0.0006466208142228425, -0.0004274856473784894, 0.00018180676852352917, 0.00024370368919335306, 0.0004243181901983917, 0.00013699685223400593, -0.0005854793125763535, -0.0009038104326464236, -0.0011307818349450827, -0.0012690294533967972, -0.001159511273726821, -0.0013013124698773026, -0.0012913800310343504, -0.0006171377608552575, -0.000280333508271724, 5.6265213061124086e-05, 0.00040992829599417746, 0.0010330997174605727, 0.0011972620850428939, 0.0019873441196978092, 0.002585495123639703, 0.002360320882871747], [-0.0016607643337920308, -0.0016791214002296329, -0.0015427739126607776, -0.0015276115154847503, -0.001556021859869361, -0.0013398266164585948, -0.001550762914121151, -0.0014403339009732008, -0.0014644170878455043, -0.0015066087944433093, -0.00139694195240736, -0.0014410748844966292, -0.0012576949084177613, -0.0012177390744909644, -0.0013568775029852986, -0.0012781256809830666, -0.0012365460861474276, -0.0013506240211427212, -0.0012868946650996804, -0.0011238600127398968, -0.0011795497266575694, -0.0010923952795565128, -0.0010769360233098269, -0.0010513230226933956, -0.0011128043988719583, -0.0011728213867172599, -0.0012474383693188429, -0.0011557654943317175, -0.0011008945293724537, -0.0011928786989301443, -0.0012275803601369262, -0.0012453626841306686, -0.001151696196757257, -0.0012909501092508435, -0.0012360416585579515, -0.0011868906440213323, -0.0011757274623960257, -0.001244619837962091, -0.00118421227671206, -0.0011348960688337684, -0.0011484816204756498, -0.0010835109278559685, -0.0011126919416710734, -0.0010896507883444428, -0.0010282585863023996, -0.0010059188352897763, -0.0011189633514732122, -0.0010995542397722602, -0.0009034129325300455, -0.0007929924759082496], [-0.0012480972800403833, -0.0012651605065912008, -0.0010949854040518403, -0.0010546937119215727, -0.001078627654351294, -0.0009234032477252185, -0.0010382798500359058, -0.0009505563648417592, -0.0009531087125651538, -0.0009957934962585568, -0.0009083721088245511, -0.0009227182017639279, -0.0008061114349402487, -0.0007808126392774284, -0.0008537735557183623, -0.0007960521033965051, -0.0007304777973331511, -0.0007772567914798856, -0.0007459415937773883, -0.0005667995428666472, -0.0005742873181588948, -0.0005243733176030219, -0.0005098493420518935, -0.0005202587926760316, -0.0006425629835575819, -0.0007466219249181449, -0.0008316689054481685, -0.0007350316736847162, -0.0006660674698650837, -0.0007957375491969287, -0.0008297436870634556, -0.0008143999730236828, -0.0007190420874394476, -0.000801000976935029, -0.0007646504673175514, -0.0006494605331681669, -0.0006413368973881006, -0.0006751329055987298, -0.0006413113442249596, -0.0006223170785233378, -0.0006229524733498693, -0.0005909344181418419, -0.0006515766144730151, -0.0006640903884544969, -0.0006512465770356357, -0.0006502948817797005, -0.0007449680706486106, -0.0007000076002441347, -0.0004273657104931772, -0.00021398079115897417], [-0.0011066474253311753, -0.0011868970468640327, -0.0009630213025957346, -0.0008779973140917718, -0.0008443066035397351, -0.0007149658049456775, -0.0009070839732885361, -0.00045311579015105963, -0.0008019197266548872, -0.0010662920540198684, -0.000795503321569413, -0.001011745654977858, -0.0009578494355082512, -0.0006197167676873505, -0.0005287176463752985, -0.0003729389572981745, -0.0003080208844039589, -0.0005229912349022925, -0.00028249877505004406, 0.0001968767901416868, 5.971994687570259e-05, 0.0002598215942271054, 5.963111834716983e-05, -0.00029738256125710905, -0.0005823764367960393, -0.0007512072916142642, -0.0009913347894325852, -0.0006878262502141297, -0.0004208673781249672, -0.00069328339304775, -0.0006067726644687355, -0.0006956951692700386, -0.0005945245502516627, -0.0007078529451973736, -0.0005165179027244449, -0.00014967309834901243, -0.00017385809042025357, -0.0005303993239067495, -0.0005198210710659623, -0.0006569508695974946, -0.0006661764928139746, -0.0002722970093600452, -0.00036788778379559517, -0.000606390240136534, -0.0007828538655303419, -0.0007031478453427553, -0.0012643438531085849, -0.0008115124073810875, 0.0002588900679256767, 0.00044863042421638966], [-0.0010409698588773608, -0.0010965587571263313, -0.0008136100950650871, -0.0007525058463215828, -0.0008756787865422666, -0.0005220209714025259, -0.0009756999206729233, -0.0006955622229725122, -0.0008037487277761102, -0.0008529989863745868, -0.0005876251379959285, -0.0006758130039088428, -0.0005276572774164379, -0.00045754332677461207, -0.0006510093808174133, -0.0006367784226313233, -0.0005066347075626254, -0.0006434692186303437, -0.0006045284098945558, -0.0003542057820595801, -0.000507688382640481, -0.0004001189081463963, -0.0003605157253332436, -0.00044514931505545974, -0.0006045326590538025, -0.0005448149750009179, -0.0006299063097685575, -0.0004504048265516758, -0.0002886693109758198, -0.0004912835429422557, -0.0005427199648693204, -0.0005207248032093048, -0.00037977800820954144, -0.0006314199999906123, -0.00046551984269171953, -0.0003901926684193313, -0.00033286568941548467, -0.0003996526065748185, -0.00027388756279833615, -0.00022778211859986186, -0.0002465137804392725, -0.0001314862020080909, -0.00019224491552449763, -0.0001687967887846753, -9.850296919466928e-05, -3.4524957300163805e-05, -0.00012401226558722556, -1.5746762073831633e-05, 0.0001412936398992315, 0.0003545832587406039], [-0.002633909462019801, -0.002939558820798993, -0.0031623789109289646, -0.003717992454767227, -0.006213919259607792, -0.008839012123644352, -0.007897762581706047, -0.005105956923216581, -0.004325720947235823, -0.0027968466747552156, -0.0009356782538816333, -0.0005800615181215107, 0.0008326995884999633, 0.0036105173639953136, 0.004873625934123993, 0.004803325515240431, 0.004479749593883753, 0.004182993900030851, 0.0038449158892035484, 0.0031929451506584883, 0.0028485185466706753, 0.001997336046770215, -0.0015956751303747296, -0.004701278638094664, -0.005273113027215004, -0.00497988797724247, -0.003373801941052079, -0.0002530752681195736, 0.0008330975542776287, -8.96767305675894e-05, 0.0009636878967285156, 0.0010391121031716466, 0.0010382834589108825, 0.0004613919591065496, -0.0024286173284053802, -0.005377068649977446, -0.007031681481748819, -0.0069624497555196285, -0.006307982839643955, -0.005499339662492275, -0.0038761894684284925, -0.0013578786747530103, -0.00010939364437945187, 0.001178292790427804, 0.003179385093972087, 0.004486577119678259, 0.005581131670624018, 0.008361381478607655, 0.007654150482267141, 0.004194337874650955], [-0.0008620091830380261, -0.0011045760475099087, -0.0009484210750088096, -0.0009570972179062665, -0.0015024321619421244, -0.002290417905896902, -0.0025705681182444096, -0.0016868484672158957, -0.0013882213970646262, -0.0011444945121183991, -0.0004606058937497437, -0.0001916599867399782, 3.3370724850101396e-05, 0.0006069685332477093, 0.0010738879209384322, 0.001482853782363236, 0.00188724254257977, 0.0019310322823002934, 0.0015807341551408172, 0.0012787939049303532, 0.0005633485270664096, 1.0722690603870433e-05, -0.0012470768997445703, -0.0027314932085573673, -0.0036682202480733395, -0.0038946422282606363, -0.003534932155162096, -0.0023166751489043236, -0.0013255904195830226, -0.0008468437590636313, 0.00031998695340007544, 0.000814596249256283, 0.0009163859649561346, 0.0002684925275389105, -0.0005496987141668797, -0.0008152250666171312, -0.0011668122606351972, -0.0016995557816699147, -0.0018425117013975978, -0.0020621689036488533, -0.0018674272578209639, -0.0007466489332728088, -0.00029863984673283994, -0.00010105432738782838, 9.251692972611636e-05, 0.0006699811201542616, 0.0009415308595634997, 0.0019502851646393538, 0.0026856334879994392, 0.0023452339228242636], [-0.0013228993630036712, -0.001368498895317316, -0.0012006580363959074, -0.001171562122181058, -0.0012882830342277884, -0.0009248636779375374, -0.0013118889182806015, -0.0010485518723726273, -0.0010874145664274693, -0.0011479653185233474, -0.0009626307873986661, -0.0010687593603506684, -0.0008400334045290947, -0.0008171184454113245, -0.000988102168776095, -0.0009248615242540836, -0.0007497713668271899, -0.0008800484356470406, -0.0008597782580181956, -0.0006055162521079183, -0.0007618774543516338, -0.0007121867965906858, -0.0006305165588855743, -0.0006179334013722837, -0.0007921602227725089, -0.000744199613109231, -0.0008574029779992998, -0.0007292164955288172, -0.0006103485357016325, -0.0007879268960095942, -0.0008293346618302166, -0.0008602192392572761, -0.0006422612932510674, -0.0008748729596845806, -0.0008303745416924357, -0.0007639614050276577, -0.0006654548342339694, -0.00079479964915663, -0.0007037784671410918, -0.0006694573094137013, -0.0006846842588856816, -0.0006210155552253127, -0.0007122347014956176, -0.0006679666112177074, -0.0005909543251618743, -0.0005225487984716892, -0.0006808447069488466, -0.0006355906371027231, -0.0004188597376924008, -0.00024393535568378866], [-0.0013529746793210506, -0.0013792843092232943, -0.0011297621531412005, -0.0011308578541502357, -0.0012778122909367085, -0.0007907171384431422, -0.0012753637274727225, -0.0009693202446214855, -0.001065029064193368, -0.0011326945386826992, -0.0008853821200318635, -0.0009955521672964096, -0.0007609126623719931, -0.000740218732971698, -0.0009367227321490645, -0.0008644550107419491, -0.0006582390633411705, -0.0008376362384296954, -0.0008134669624269009, -0.0005164524191059172, -0.000744353630580008, -0.0006441245786845684, -0.0005446808645501733, -0.000596446159761399, -0.0007931703585200012, -0.0007509181159548461, -0.0008664063643664122, -0.0007010715780779719, -0.0005843734834343195, -0.0007837524171918631, -0.00081444694660604, -0.0008279732428491116, -0.000584459223318845, -0.0008842120878398418, -0.0008095946977846324, -0.0007284296443685889, -0.0006291552563197911, -0.0007373914122581482, -0.0006355564692057669, -0.0006152924033813179, -0.00066781957866624, -0.0005703764036297798, -0.0006367763853631914, -0.0006219468195922673, -0.0005837155040353537, -0.0005131169455125928, -0.0007188877207227051, -0.0006348349270410836, -0.0003458605788182467, -0.0001429567637387663], [-0.0013346676714718342, -0.0013752499362453818, -0.0012012998340651393, -0.001152540324255824, -0.0012275410117581487, -0.0008725171792320907, -0.0012797984527423978, -0.001026045880280435, -0.0011056632502004504, -0.0011657729046419263, -0.0009371027699671686, -0.0010767086641862988, -0.0008519586408510804, -0.0007408885285258293, -0.0009301523678004742, -0.0008571165963076055, -0.0007658027461729944, -0.000907114939764142, -0.0008677523583173752, -0.0006025144830346107, -0.0007183006964623928, -0.0005867090076208115, -0.000575666781514883, -0.000582298671361059, -0.0007442227215506136, -0.0007497555343434215, -0.0009016568656079471, -0.000738062895834446, -0.0006465379847213626, -0.0008259532623924315, -0.00083002052269876, -0.0009271397138945758, -0.0007199620013125241, -0.0009952518157660961, -0.0009738851804286242, -0.0008782949298620224, -0.0008461493416689336, -0.0009837368270382285, -0.000881065265275538, -0.0008730925619602203, -0.000861576700117439, -0.0007648588507436216, -0.0008628516807220876, -0.0008408075664192438, -0.0008214172557927668, -0.0007456291350536048, -0.0009528691880404949, -0.0009209910058416426, -0.0006382010760717094, -0.00046669793664477766]], "codec_errors": [0.00460360711440444, 0.005088453181087971, 0.004616959486156702, 0.004993683658540249, 0.0047010392881929874, 0.004666488617658615, 0.0047347950749099255, 0.004555338062345982, 0.00470463652163744, 0.004972124006599188]} diff --git a/tests/models/neucodec/__init__.py b/tests/models/neucodec/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/models/neucodec/test_feature_extraction_neucodec.py b/tests/models/neucodec/test_feature_extraction_neucodec.py new file mode 100644 index 000000000000..444eb0f7fc7c --- /dev/null +++ b/tests/models/neucodec/test_feature_extraction_neucodec.py @@ -0,0 +1,176 @@ +# 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. + +import itertools +import unittest + +import numpy as np + +from transformers import NeuCodecFeatureExtractor +from transformers.testing_utils import require_torch, require_torch_gpu, slow +from transformers.utils.import_utils import is_torch_available + +from ...test_processing_common import floats_list +from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin + + +if is_torch_available(): + import torch + + +@require_torch +class NeuCodecFeatureExtractionTester: + def __init__( + self, + parent, + batch_size=7, + min_seq_length=400, + max_seq_length=2000, + feature_size=80, # number of mel bins + sampling_rate=16000, + spec_hop_length=160, + hop_length=320, + ): + self.parent = parent + self.batch_size = batch_size + self.min_seq_length = min_seq_length + self.max_seq_length = max_seq_length + self.spec_hop_length = spec_hop_length + self.hop_length = hop_length + self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) + self.feature_size = feature_size + self.sampling_rate = sampling_rate + + def prepare_feat_extract_dict(self): + return { + "feature_size": self.feature_size, + "sampling_rate": self.sampling_rate, + "hop_length": self.hop_length, + "spec_hop_length": self.spec_hop_length, + "padding_value": 0.0, + } + + # Copied from transformers.tests.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTester.prepare_inputs_for_common + def prepare_inputs_for_common(self, equal_length=False, numpify=False): + def _flatten(list_of_lists): + return list(itertools.chain(*list_of_lists)) + + if equal_length: + speech_inputs = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)] + else: + # make sure that inputs increase in size + speech_inputs = [ + floats_list((x, self.feature_size)) + for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) + ] + if numpify: + speech_inputs = [np.asarray(x) for x in speech_inputs] + return speech_inputs + + +@require_torch +class NeuCodecFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase): + feature_extraction_class = NeuCodecFeatureExtractor + + def setUp(self): + self.feat_extract_tester = NeuCodecFeatureExtractionTester(self) + + def test_call(self): + TOL = 1e-6 + + # Tests that all call wrap to encode_plus and batch_encode_plus + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + # create three inputs of length 800, 1000, and 1200 + audio_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + np_audio_inputs = [np.asarray(audio_input) for audio_input in audio_inputs] + torch_audio_inputs = [torch.tensor(audio_input) for audio_input in audio_inputs] + + # Test not batched input + sampling_rate = self.feat_extract_tester.sampling_rate + encoded_sequences_1 = feat_extract(torch_audio_inputs[0], sampling_rate=sampling_rate, return_tensors="np") + encoded_sequences_2 = feat_extract(np_audio_inputs[0], sampling_rate=sampling_rate, return_tensors="np") + encoded_sequences_3 = feat_extract( + torch_audio_inputs[0], sampling_rate=sampling_rate, return_tensors="np", device="cpu" + ) + self.assertTrue(np.allclose(encoded_sequences_1.input_values, encoded_sequences_2.input_values, atol=TOL)) + self.assertTrue(np.allclose(encoded_sequences_1.input_features, encoded_sequences_2.input_features, atol=TOL)) + self.assertTrue(np.allclose(encoded_sequences_1.input_features, encoded_sequences_3.input_features, atol=TOL)) + + # Test batched + encoded_sequences_1 = feat_extract( + torch_audio_inputs, sampling_rate=sampling_rate, padding=True, return_tensors="np" + ) + encoded_sequences_2 = feat_extract( + np_audio_inputs, sampling_rate=sampling_rate, padding=True, return_tensors="np" + ) + encoded_sequences_3 = feat_extract( + torch_audio_inputs, + sampling_rate=sampling_rate, + padding=True, + return_tensors="np", + device="cpu", + ) + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1.input_values, encoded_sequences_2.input_values): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=TOL)) + for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1.input_features, encoded_sequences_2.input_features): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=TOL)) + for enc_seq_1, enc_seq_3 in zip(encoded_sequences_1.input_features, encoded_sequences_3.input_features): + self.assertTrue(np.allclose(enc_seq_1, enc_seq_3, atol=TOL)) + + @slow + @require_torch_gpu + def test_call_gpu(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + audio_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] + torch_audio_inputs = [torch.tensor(audio_input) for audio_input in audio_inputs] + sampling_rate = self.feat_extract_tester.sampling_rate + + # Single input: CPU vs GPU output should have same shape and dtype + encoded_sequences_cpu = feat_extract( + torch_audio_inputs[0], sampling_rate=sampling_rate, return_tensors="np", device="cpu" + ) + encoded_sequences_gpu = feat_extract( + torch_audio_inputs[0], sampling_rate=sampling_rate, return_tensors="np", device="cuda" + ) + self.assertEqual(encoded_sequences_cpu.input_values.shape, encoded_sequences_gpu.input_values.shape) + self.assertEqual(encoded_sequences_cpu.input_features.shape, encoded_sequences_gpu.input_features.shape) + self.assertEqual(encoded_sequences_cpu.input_values.dtype, encoded_sequences_gpu.input_values.dtype) + self.assertEqual(encoded_sequences_cpu.input_features.dtype, encoded_sequences_gpu.input_features.dtype) + + # Batched input: CPU vs GPU output should have same shape and dtype + encoded_sequences_cpu = feat_extract( + torch_audio_inputs, sampling_rate=sampling_rate, padding=True, return_tensors="np", device="cpu" + ) + encoded_sequences_gpu = feat_extract( + torch_audio_inputs, sampling_rate=sampling_rate, padding=True, return_tensors="np", device="cuda" + ) + self.assertEqual(encoded_sequences_cpu.input_values.shape, encoded_sequences_gpu.input_values.shape) + self.assertEqual(encoded_sequences_cpu.input_features.shape, encoded_sequences_gpu.input_features.shape) + self.assertEqual(encoded_sequences_cpu.input_values.dtype, encoded_sequences_gpu.input_values.dtype) + self.assertEqual(encoded_sequences_cpu.input_features.dtype, encoded_sequences_gpu.input_features.dtype) + + def test_double_precision_pad(self): + feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) + np_audio_inputs = np.random.rand(100, 32).astype(np.float64) + py_audio_inputs = np_audio_inputs.tolist() + + for inputs in [py_audio_inputs, np_audio_inputs]: + np_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="np") + self.assertTrue(np_processed.input_features.dtype == np.float32) + pt_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="pt") + self.assertTrue(pt_processed.input_features.dtype == torch.float32) + + @unittest.skip("NeuCodec doesn't support stereo input") + def test_integration_stereo(self): + pass diff --git a/tests/models/neucodec/test_modeling_neucodec.py b/tests/models/neucodec/test_modeling_neucodec.py new file mode 100644 index 000000000000..897b3cceb125 --- /dev/null +++ b/tests/models/neucodec/test_modeling_neucodec.py @@ -0,0 +1,333 @@ +# 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. + +import inspect +import json +import unittest +from pathlib import Path + +import numpy as np +from datasets import Audio, load_dataset + +from tests.test_configuration_common import ConfigTester +from tests.test_modeling_common import ModelTesterMixin, floats_tensor +from tests.utils.test_audio_utils import compute_rmse +from transformers import AutoFeatureExtractor, NeuCodecConfig, NeuCodecModel +from transformers.testing_utils import ( + is_torch_available, + require_torch, + slow, + torch_device, +) + + +if is_torch_available(): + import torch + + +@require_torch +class NeuCodecModelTester: + def __init__( + self, + parent, + batch_size=2, + num_channels=1, + input_sampling_rate=16000, + output_sampling_rate=24000, + num_mel_bins=80, + stride=2, + encoder_hidden_size=8, + downsampling_ratios=(2, 2, 4), + hidden_size=32, + num_attention_heads=2, + num_key_value_heads=2, + num_hidden_layers=2, + head_dim=8, + quantization_levels=(4, 4, 4, 4), + semantic_hidden_size=32, + semantic_num_hidden_layers=17, + semantic_num_attention_heads=4, + semantic_intermediate_size=64, + is_training=False, + ): + self.parent = parent + self.batch_size = batch_size + self.input_sampling_rate = input_sampling_rate + self.output_sampling_rate = output_sampling_rate + self.is_training = is_training + self.hop_length = int(np.prod(downsampling_ratios) * (output_sampling_rate / input_sampling_rate)) + self.num_samples = self.hop_length * 80 # feature extractor will pad to multiple of hop_length + self.num_channels = num_channels + self.num_mel_bins = num_mel_bins + self.stride = stride + self.mel_hop_length = int(np.prod(downsampling_ratios)) + self.encoder_hidden_size = encoder_hidden_size + self.downsampling_ratios = downsampling_ratios + self.hidden_size = hidden_size + self.num_attention_heads = num_attention_heads + self.num_key_value_heads = num_key_value_heads + self.num_hidden_layers = num_hidden_layers + self.head_dim = head_dim + self.quantization_levels = quantization_levels + self.semantic_hidden_size = semantic_hidden_size + self.semantic_num_hidden_layers = semantic_num_hidden_layers + self.semantic_num_attention_heads = semantic_num_attention_heads + self.semantic_intermediate_size = semantic_intermediate_size + + def prepare_config_and_inputs(self): + input_values = floats_tensor([self.batch_size, self.num_channels, self.num_samples], scale=1.0) + input_features = floats_tensor( + [self.batch_size, self.num_samples // self.mel_hop_length, self.num_mel_bins * self.stride], scale=1.0 + ) + config = self.get_config() + inputs_dict = {"input_values": input_values, "input_features": input_features} + return config, inputs_dict + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def prepare_config_and_inputs_for_model_class(self, model_class): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def get_config(self): + semantic_model_config = { + "model_type": "wav2vec2-bert", + "hidden_size": self.semantic_hidden_size, + "num_hidden_layers": self.semantic_num_hidden_layers, + "num_attention_heads": self.semantic_num_attention_heads, + "intermediate_size": self.semantic_intermediate_size, + "feature_projection_input_dim": self.num_mel_bins * self.stride, + "output_hidden_size": self.semantic_hidden_size, + } + + return NeuCodecConfig( + encoder_hidden_size=self.encoder_hidden_size, + downsampling_ratios=self.downsampling_ratios, + hidden_size=self.hidden_size, + semantic_model_config=semantic_model_config, + input_sampling_rate=self.input_sampling_rate, + output_sampling_rate=self.output_sampling_rate, + num_attention_heads=self.num_attention_heads, + num_key_value_heads=self.num_key_value_heads, + num_hidden_layers=self.num_hidden_layers, + head_dim=self.head_dim, + quantization_dim=self.hidden_size + self.semantic_hidden_size, + quantization_levels=self.quantization_levels, + audio_channels=self.num_channels, + ) + + def create_and_check_model_forward(self, config, inputs_dict): + model = NeuCodecModel(config=config).to(torch_device).eval() + input_values = inputs_dict["input_values"] + input_features = inputs_dict["input_features"] + result = model(input_values, input_features) + # output audio is resampled from `input_sampling_rate` (16kHz) to `output_sampling_rate` (24kHz) + expected_num_samples = int(self.num_samples * config.output_sampling_rate / config.input_sampling_rate) + self.parent.assertEqual( + result.audio_values.shape, + (self.batch_size, self.num_channels, expected_num_samples), + ) + + +@require_torch +class NeuCodecModelTest(ModelTesterMixin, unittest.TestCase): + all_model_classes = (NeuCodecModel,) if is_torch_available() else () + is_encoder_decoder = True + test_resize_embeddings = False + test_torch_exportable = False + pipeline_model_mapping = {"feature-extraction": NeuCodecModel} if is_torch_available() else {} + additional_model_inputs = ["input_features", "input_features_mask"] + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + # `forward` takes no `output_attentions` / `output_hidden_states` (see the skips below), so drop them + # from the inputs the common tests inject + inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) + inputs_dict.pop("output_attentions", None) + inputs_dict.pop("output_hidden_states", None) + return inputs_dict + + def setUp(self): + self.model_tester = NeuCodecModelTester(self) + self.config_tester = ConfigTester( + self, + config_class=NeuCodecConfig, + encoder_hidden_size=8, + hidden_size=32, + common_properties=[], + has_text_modality=False, + ) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_model_forward(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model_forward(*config_and_inputs) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["input_values", "input_features", "padding_mask"] + self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names) + + @unittest.skip("NeuCodecModel does not have `inputs_embeds` logics") + def test_model_get_set_embeddings(self): + pass + + # The three tests below need `output_attentions` / `output_hidden_states`, which a codec does not expose: + # `forward`, `encode` and `decode` take no such argument and `NeuCodecOutput` only carries `audio_values`, + # `audio_codes`, `latents` and `audio_codes_mask`. The inner Wav2Vec2-Bert semantic encoder and the decoder + # transformer do run real attention (so the sdpa/eager tests below still apply), but their intermediate + # states are not part of the codec's public output. Same as Dac/Encodec/Mimi/Xcodec2. + @unittest.skip(reason="NeuCodecOutput exposes neither `hidden_states` nor `attentions` to retain grads on") + def test_retain_grad_hidden_states_attentions(self): + pass + + @unittest.skip(reason="NeuCodecModel takes no `output_attentions`; NeuCodecOutput has no `attentions`") + def test_attention_outputs(self): + pass + + @unittest.skip(reason="NeuCodecModel takes no `output_hidden_states`; NeuCodecOutput has no `hidden_states`") + def test_hidden_states_output(self): + pass + + @unittest.skip( + reason="The Wav2Vec2Bert semantic encoder uses relative position embeddings that produce a dense attention bias incompatible with Flash Attention" + ) + def test_sdpa_can_dispatch_on_flash(self): + pass + + @staticmethod + def _prepare_config_headdim(config, requested_dim): + """ + Similar to Xcodec2: override to keep `quantization_dim` in sync with the encoder outputs. The quantizer + consumes the concatenation of the acoustic and semantic encoder outputs, i.e. `hidden_size + + semantic_model_config.hidden_size`, and both hidden sizes are scaled when adjusting the head dim. + """ + config = ModelTesterMixin._prepare_config_headdim(config, requested_dim) + config.quantization_dim = config.hidden_size + config.semantic_model_config.hidden_size + return config + + +@require_torch +class NeuCodecIntegrationTest(unittest.TestCase): + """ + reproducer: https://gist.github.com/ebezzam/becefc7002ba9030ad0defd93123e32b + """ + + def setUp(self): + self.fixtures_path = Path(__file__).parent.parent.parent / "fixtures/neucodec" + + @slow + def test_integration(self): + results_path = self.fixtures_path / "expected_results.json" + with open(results_path, "r") as f: + raw_data = json.load(f) + exp_code = torch.tensor(raw_data["audio_codes"][0]) + exp_recon = torch.tensor(raw_data["recon_wavs"][0]) + exp_codec_error = float(raw_data["codec_errors"][0]) + + model_id = "neuphonic/neucodec" + model = NeuCodecModel.from_pretrained(model_id, attn_implementation="eager").to(torch_device).eval() + feature_extractor = AutoFeatureExtractor.from_pretrained(model_id) + + dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate)) + audio = dataset[0]["audio"]["array"] + inputs = feature_extractor( + audio=audio, + sampling_rate=feature_extractor.sampling_rate, + return_tensors="pt", + ).to(torch_device) + + with torch.no_grad(): + audio_codes = model.encode(inputs["input_values"], inputs["input_features"], return_dict=False)[0] + n_codes = len(exp_code) + self.assertTrue(torch.equal(audio_codes.squeeze().cpu().to(exp_code.dtype)[:n_codes], exp_code)) + + dec = model.decode(audio_codes=audio_codes).audio_values + n_recon = len(exp_recon) + torch.testing.assert_close(dec.squeeze().cpu()[:n_recon], exp_recon, rtol=1e-6, atol=1e-6) + + # compare codec error + codec_error = compute_rmse(inputs["input_values"], dec).item() + torch.testing.assert_close(codec_error, exp_codec_error, rtol=1e-5, atol=1e-5) + + # make sure forward and decode gives same result + enc_dec = model(inputs["input_values"], inputs["input_features"]).audio_values + self.assertTrue(torch.equal(dec[..., : enc_dec.shape[-1]], enc_dec)) + + @slow + def test_batch_integration(self): + results_path = self.fixtures_path / "expected_results.json" + with open(results_path, "r") as f: + raw_data = json.load(f) + num_samples = len(raw_data["audio_codes"]) + exp_codes = [torch.tensor(c) for c in raw_data["audio_codes"]] + exp_recons = [torch.tensor(r) for r in raw_data["recon_wavs"]] + exp_codec_errors = raw_data["codec_errors"] + + model_id = "neuphonic/neucodec" + model = NeuCodecModel.from_pretrained(model_id, attn_implementation="eager").to(torch_device).eval() + feature_extractor = AutoFeatureExtractor.from_pretrained(model_id) + + dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + dataset = dataset.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate)) + # Fixed indices, chosen to keep audio lengths within a modest spread rather than the dataset's natural + # first-N order, which stresses padding-sensitive ops beyond what this test is meant to cover. + dataset_indices = raw_data["dataset_indices"] + audios = [dataset[i]["audio"]["array"] for i in dataset_indices] + + # Batched feature extraction + inference + inputs = feature_extractor( + audio=audios, + sampling_rate=feature_extractor.sampling_rate, + return_tensors="pt", + ).to(torch_device) + + with torch.no_grad(): + enc = model.encode( + inputs["input_values"], + inputs["input_features"], + padding_mask=inputs["padding_mask"], + input_features_mask=inputs.get("input_features_mask"), + return_dict=True, + ) + batch_codes = enc.audio_codes + batch_mask = enc.audio_codes_mask + dec = model.decode(audio_codes=batch_codes, audio_codes_mask=batch_mask).audio_values + + for i in range(num_samples): + valid_code_len = int(batch_mask[i].sum().item()) + n_codes = len(exp_codes[i]) + actual_codes = batch_codes[i, :, :valid_code_len].squeeze().cpu().to(exp_codes[i].dtype)[:n_codes] + self.assertTrue( + torch.equal(actual_codes, exp_codes[i]), + f"Sample {i}: codes mismatch", + ) + + n_recon = len(exp_recons[i]) + actual_recon = dec[i].squeeze().cpu()[:n_recon] + torch.testing.assert_close(actual_recon, exp_recons[i], rtol=1e-3, atol=1e-3) + + codec_error = compute_rmse(inputs["input_values"][i : i + 1], dec[i : i + 1]).item() + torch.testing.assert_close(codec_error, exp_codec_errors[i], rtol=1e-3, atol=1e-3) diff --git a/tests/models/xcodec2/test_modeling_xcodec2.py b/tests/models/xcodec2/test_modeling_xcodec2.py index a8a0c61eb8bc..684bea49f90e 100644 --- a/tests/models/xcodec2/test_modeling_xcodec2.py +++ b/tests/models/xcodec2/test_modeling_xcodec2.py @@ -144,6 +144,7 @@ class Xcodec2ModelTest(ModelTesterMixin, unittest.TestCase): all_model_classes = (Xcodec2Model,) if is_torch_available() else () is_encoder_decoder = True test_resize_embeddings = False + test_torch_exportable = False pipeline_model_mapping = {"feature-extraction": Xcodec2Model} if is_torch_available() else {} additional_model_inputs = ["input_features", "input_features_mask"] From 5c2ede900e36b7e92099c1f0e9ca65e24d0bb55b Mon Sep 17 00:00:00 2001 From: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com> Date: Wed, 2 Sep 2026 13:08:20 +0000 Subject: [PATCH 029/996] [`Qwen4 Exp`] Use partial to avoid skipping mask more easily (#48456) * cleaner * use proper layer mappings --- src/transformers/masking_utils.py | 3 +- .../models/qwen4_exp/modeling_qwen4_exp.py | 57 +------------------ .../models/qwen4_exp/modular_qwen4_exp.py | 56 +----------------- 3 files changed, 7 insertions(+), 109 deletions(-) diff --git a/src/transformers/masking_utils.py b/src/transformers/masking_utils.py index 0b6ea5e01945..1641bca80409 100644 --- a/src/transformers/masking_utils.py +++ b/src/transformers/masking_utils.py @@ -1514,7 +1514,8 @@ def create_recurrent_attention_mask( "minimax_m3_sparse": create_causal_mask, # DSA always needs to materialize the mask to account for causality (no SDPA `is_cauasal` shortcut) "deepseek_sparse_attention": partial(create_causal_mask, allow_is_causal_skip=False), - "qwen_sparse_attention": create_causal_mask, + # Force mask creation as needed in Qwen's DSA implementation + "qwen_sparse_attention": partial(create_causal_mask, allow_is_causal_skip=False), "linear_attention": create_recurrent_attention_mask, "conv": create_recurrent_attention_mask, "hybrid": {"full_attention": create_causal_mask, "linear_attention": create_recurrent_attention_mask}, diff --git a/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py b/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py index 4273886cc4ab..bf01c2fe356b 100644 --- a/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py +++ b/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py @@ -31,7 +31,6 @@ from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache -from ...configuration_utils import PreTrainedConfig from ...generation import GenerationMixin from ...integrations import ( use_experts_implementation, @@ -1474,7 +1473,7 @@ def forward( "allow_is_causal_skip": False, } causal_mask_mapping = { - "full_attention": create_causal_mask(**mask_kwargs), + "qwen_sparse_attention": create_causal_mask(**mask_kwargs), "linear_attention": create_recurrent_attention_mask(**mask_kwargs), } @@ -1493,7 +1492,7 @@ def forward( hidden_states = decoder_layer( hidden_states, position_embeddings=position_embeddings, - attention_mask=causal_mask_mapping["full_attention"], + attention_mask=causal_mask_mapping["qwen_sparse_attention"], conv_mask=conv_mask, past_key_values=past_key_values, ple_input_ids=ple_input_ids, @@ -1703,32 +1702,6 @@ def forward( router_logits=outputs.router_logits, ) - @staticmethod - def create_masks_for_generate( - config: PreTrainedConfig, - inputs_embeds: torch.Tensor, - attention_mask: torch.Tensor | None, - past_key_values: Cache | None, - position_ids: torch.Tensor | None, - **kwargs, - ) -> dict: - # We need to overwrite to add the `allow_is_causal_skip=False` condition - mask_kwargs = { - "config": config, - "inputs_embeds": inputs_embeds, - "attention_mask": attention_mask, - "past_key_values": past_key_values, - "position_ids": position_ids, - # Due to the indexer, we always want to create a mask to then simply overlay the indexer mask in each layer - otherwise - # we may have to recreate it in each layer if it gets skipped - "allow_is_causal_skip": False, - } - causal_mask_mapping = { - "full_attention": create_causal_mask(**mask_kwargs), - "linear_attention": create_recurrent_attention_mask(**mask_kwargs), - } - return causal_mask_mapping - class Qwen4ExpVisionRotaryEmbedding(nn.Module): def __init__(self, dim: int, theta: float = 10000.0) -> None: @@ -2718,32 +2691,6 @@ def _expand_dict_for_generation(dict_to_expand): return input_ids, model_kwargs - @staticmethod - def create_masks_for_generate( - config: PreTrainedConfig, - inputs_embeds: torch.Tensor, - attention_mask: torch.Tensor | None, - past_key_values: Cache | None, - position_ids: torch.Tensor | None, - **kwargs, - ) -> dict: - # We need to overwrite to add the `allow_is_causal_skip=False` condition - mask_kwargs = { - "config": config, - "inputs_embeds": inputs_embeds, - "attention_mask": attention_mask, - "past_key_values": past_key_values, - "position_ids": position_ids, - # Due to the indexer, we always want to create a mask to then simply overlay the indexer mask in each layer - otherwise - # we may have to recreate it in each layer if it gets skipped - "allow_is_causal_skip": False, - } - causal_mask_mapping = { - "full_attention": create_causal_mask(**mask_kwargs), - "linear_attention": create_recurrent_attention_mask(**mask_kwargs), - } - return causal_mask_mapping - __all__ = [ "Qwen4ExpVisionModel", diff --git a/src/transformers/models/qwen4_exp/modular_qwen4_exp.py b/src/transformers/models/qwen4_exp/modular_qwen4_exp.py index b87303e03f4c..2c1ec18ca6f2 100644 --- a/src/transformers/models/qwen4_exp/modular_qwen4_exp.py +++ b/src/transformers/models/qwen4_exp/modular_qwen4_exp.py @@ -996,7 +996,7 @@ def forward( "allow_is_causal_skip": False, } causal_mask_mapping = { - "full_attention": create_causal_mask(**mask_kwargs), + "qwen_sparse_attention": create_causal_mask(**mask_kwargs), "linear_attention": create_recurrent_attention_mask(**mask_kwargs), } @@ -1015,7 +1015,7 @@ def forward( hidden_states = decoder_layer( hidden_states, position_embeddings=position_embeddings, - attention_mask=causal_mask_mapping["full_attention"], + attention_mask=causal_mask_mapping["qwen_sparse_attention"], conv_mask=conv_mask, past_key_values=past_key_values, ple_input_ids=ple_input_ids, @@ -1033,32 +1033,6 @@ def forward( class Qwen4ExpForCausalLM(Qwen3_5MoeForCausalLM): config: Qwen4ExpTextConfig - @staticmethod - def create_masks_for_generate( - config: PreTrainedConfig, - inputs_embeds: torch.Tensor, - attention_mask: torch.Tensor | None, - past_key_values: Cache | None, - position_ids: torch.Tensor | None, - **kwargs, - ) -> dict: - # We need to overwrite to add the `allow_is_causal_skip=False` condition - mask_kwargs = { - "config": config, - "inputs_embeds": inputs_embeds, - "attention_mask": attention_mask, - "past_key_values": past_key_values, - "position_ids": position_ids, - # Due to the indexer, we always want to create a mask to then simply overlay the indexer mask in each layer - otherwise - # we may have to recreate it in each layer if it gets skipped - "allow_is_causal_skip": False, - } - causal_mask_mapping = { - "full_attention": create_causal_mask(**mask_kwargs), - "linear_attention": create_recurrent_attention_mask(**mask_kwargs), - } - return causal_mask_mapping - @auto_docstring class Qwen4ExpVisionModel(Qwen3_5MoeVisionModel): @@ -1146,31 +1120,7 @@ def forward( @auto_docstring class Qwen4ExpForConditionalGeneration(Qwen3_5MoeForConditionalGeneration): - @staticmethod - def create_masks_for_generate( - config: PreTrainedConfig, - inputs_embeds: torch.Tensor, - attention_mask: torch.Tensor | None, - past_key_values: Cache | None, - position_ids: torch.Tensor | None, - **kwargs, - ) -> dict: - # We need to overwrite to add the `allow_is_causal_skip=False` condition - mask_kwargs = { - "config": config, - "inputs_embeds": inputs_embeds, - "attention_mask": attention_mask, - "past_key_values": past_key_values, - "position_ids": position_ids, - # Due to the indexer, we always want to create a mask to then simply overlay the indexer mask in each layer - otherwise - # we may have to recreate it in each layer if it gets skipped - "allow_is_causal_skip": False, - } - causal_mask_mapping = { - "full_attention": create_causal_mask(**mask_kwargs), - "linear_attention": create_recurrent_attention_mask(**mask_kwargs), - } - return causal_mask_mapping + pass __all__ = [ From 4a2e450e601214024c8a37abdaca35df2a4a3ba3 Mon Sep 17 00:00:00 2001 From: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com> Date: Wed, 2 Sep 2026 13:28:29 +0000 Subject: [PATCH 030/996] [`Kernels`] Enable functions into kernels registry and allow non inheritance (#48443) * add features * add tests * style --- src/transformers/integrations/hub_kernels.py | 2 +- src/transformers/utils/kernel_config.py | 9 +++- tests/kernels/test_kernels.py | 44 ++++++++++++++++++++ 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/transformers/integrations/hub_kernels.py b/src/transformers/integrations/hub_kernels.py index b58adc35c063..55947e6ecfb8 100644 --- a/src/transformers/integrations/hub_kernels.py +++ b/src/transformers/integrations/hub_kernels.py @@ -793,7 +793,7 @@ def get_device(device_type): device = get_device(model.device.type) if model.kernel_config is not None: - inherit_mapping = not model.kernel_config.use_local_kernel + inherit_mapping = not model.kernel_config.use_local_kernel and model.kernel_config.inherit_mapping with use_kernel_mapping(model.kernel_config.kernel_mapping, inherit_mapping=inherit_mapping): _kernels_kernelize(model, device=device, mode=mode) else: diff --git a/src/transformers/utils/kernel_config.py b/src/transformers/utils/kernel_config.py index 0b469286f669..d3d62cc07585 100644 --- a/src/transformers/utils/kernel_config.py +++ b/src/transformers/utils/kernel_config.py @@ -101,10 +101,11 @@ class KernelConfig(PushToHubMixin): Kernel configuration class. This class is used to configure the kernel mapping for a model. """ - def __init__(self, kernel_mapping=None, use_local_kernel=False): + def __init__(self, kernel_mapping=None, use_local_kernel=False, inherit_mapping=True): self.kernel_mapping = kernel_mapping if kernel_mapping is not None else {} self.registered_layer_names = {} self.use_local_kernel = use_local_kernel + self.inherit_mapping = inherit_mapping def update_kernel( self, repo_id, registered_name, layer_name, device, mode, revision=None, version=1, trust_remote_code=False @@ -125,6 +126,12 @@ def update_kernel( def store_registered_layer_names(self, model): for name, module in model.named_modules(): + # converted functions + if getattr(module, "_kernel_funcs", None) is not None: + for kernel_layer_name in module._kernel_funcs.keys(): + self.registered_layer_names[name + f".{kernel_layer_name}"] = kernel_layer_name + + # converted modules if hasattr(module, "kernel_layer_name"): self.registered_layer_names[name] = module.kernel_layer_name diff --git a/tests/kernels/test_kernels.py b/tests/kernels/test_kernels.py index 507caf04f65e..bbe43d79e104 100644 --- a/tests/kernels/test_kernels.py +++ b/tests/kernels/test_kernels.py @@ -256,6 +256,50 @@ def test_kernels_mapping_explicit_version(self): del model + def test_kernels_mapping_functions_registration(self): + kernel_config = KernelConfig( + kernel_mapping={"rotary_pos_emb": ("kernels-community/rotary:apply_rotary_transformers", {"version": 2})} + ) + + # Functions would previously raise if not properly handled + model = AutoModelForCausalLM.from_pretrained( + "unsloth/Llama-3.2-1B-Instruct", use_kernels=True, device_map=torch_device, kernel_config=kernel_config + ) + + # Sanity checks making sure it is really been found / registered under the model + self.assertIn("rotary_pos_emb", model.kernel_config.registered_layer_names.values()) + self.assertTrue(any(name.endswith(".rotary_pos_emb") for name in model.kernel_config.registered_layer_names)) + + del model + + def test_kernels_mapping_no_inherit(self): + kernel_config = KernelConfig( + kernel_mapping={ + "RMSNorm": ( + "kernels-community/layer-norm:LlamaRMSNorm", + {"version": 1}, + ) + }, + # Force to only inherit the mapping ^ + inherit_mapping=False, + ) + + model = AutoModelForCausalLM.from_pretrained( + "unsloth/Llama-3.2-1B-Instruct", use_kernels=True, device_map=torch_device, kernel_config=kernel_config + ) + first_rms_norm = model.model.layers[0].input_layernorm + first_self_attn = model.model.layers[0].self_attn + + # RoPE should still be registered under attn + self.assertIn("rotary_pos_emb", getattr(first_self_attn, "_kernel_funcs", {})) + first_rope = first_self_attn._kernel_funcs["rotary_pos_emb"] + + # Check kernelization by fwd matching + self.assertIsNot(first_rms_norm.forward.__func__, type(first_rms_norm).forward) # exchanged + self.assertIs(first_rope.forward.__func__, type(first_rope).forward) # not exchanged + + del model + @require_torch_accelerator def test_kernel_fusion(self): model_id = "michaelbenayoun/qwen3-tiny-4kv-heads-4layers-random" From a85f3319abe2d40dd292a94810ad7818dad5f88c Mon Sep 17 00:00:00 2001 From: Steven Liu <59462357+stevhliu@users.noreply.github.com> Date: Wed, 2 Sep 2026 16:18:32 +0000 Subject: [PATCH 031/996] [docs] Kernel updates (#48465) * docs * feedback --- docs/source/en/kernel_doc/loading_kernels.md | 110 ++++++++++++------- docs/source/en/kernels.md | 2 +- 2 files changed, 74 insertions(+), 38 deletions(-) diff --git a/docs/source/en/kernel_doc/loading_kernels.md b/docs/source/en/kernel_doc/loading_kernels.md index cfa7edb1ada9..65a512ecc9d0 100644 --- a/docs/source/en/kernel_doc/loading_kernels.md +++ b/docs/source/en/kernel_doc/loading_kernels.md @@ -20,13 +20,10 @@ A kernel works as a drop-in replacement for standard PyTorch operations. It swap This guide shows how to load kernels to accelerate inference. -Install the kernels package. We recommend the latest version which provides the best performance and bug fixes. - -> [!NOTE] -> kernels >=0.11.0 is the minimum required version for working with Transformers. +Install Transformers with the supported version of the [kernels](https://github.com/huggingface/kernels) package. ```bash -pip install -U kernels +pip install -U "transformers[kernels]" ``` Set `use_kernels=True` in [`~PreTrainedModel.from_pretrained`] to load the most performant kernels available on the Hub for your device. This replaces supported PyTorch operations with the kernel implementation. @@ -41,7 +38,9 @@ model = AutoModelForCausalLM.from_pretrained( ) ``` -The default kernels differ by device type. The table below lists the Hub repository that supplies each operation's default kernel. When no default kernel is registered, the operation falls back to standard PyTorch. +The default mapping depends on the model, device, and execution mode. The table below lists common Hub repositories for +the devices shown. When no kernel is registered for a particular combination, the operation falls back to standard +PyTorch. | Operation | NVIDIA (CUDA) | AMD (ROCm) | Intel (XPU) | |---|---|---|---| @@ -54,6 +53,9 @@ The default kernels differ by device type. The table below lists the Hub reposit | Causal LM loss | `kernels-community/liger-kernels` | — | — | | Deformable attention | `kernels-community/deformable-detr` | — | — | +The table is not exhaustive. Models can register additional layers and functions, and some mappings are available only +for specific execution modes. + > [!NOTE] > AMD GPUs report their device type as `cuda` in PyTorch. Transformers detects ROCm at runtime and routes supported operations to the AMD kernels above, including [AITER](https://github.com/ROCm/aiter) builds such as `kernels-community/aiter-rope`. You don't need to set the device type yourself. @@ -171,19 +173,21 @@ kernelize(model, mode=Mode.TRAINING | Mode.TORCH_COMPILE) [`KernelConfig`] customizes which kernels are used in a model. -The `:` separator names a specific kernel entry inside the repository and maps it to a layer. +The `kernel_mapping` keys are names registered by the model. They can refer to a layer, such as `"RMSNorm"`, or a +registered function, such as `"rotary_pos_emb"`. The `:` separator names a specific kernel entry inside the repository +and maps it to that layer or function. ```py from transformers import AutoModelForCausalLM, KernelConfig kernel_config = KernelConfig( kernel_mapping={ - "RMSNorm": "kernels-community/liger_kernels:LigerRMSNorm", + "RMSNorm": "kernels-community/liger-kernels:LigerRMSNorm", } ) model = AutoModelForCausalLM.from_pretrained( "Qwen/Qwen3-0.6B", - attn_implementation="kernels-community/flash-attn2:FlashAttention2", + attn_implementation="kernels-community/flash-attn2", use_kernels=True, kernel_config=kernel_config, device_map="auto" @@ -198,15 +202,66 @@ from transformers import KernelConfig kernel_config = KernelConfig( kernel_mapping={ "RMSNorm": { - "cuda": "kernels-community/liger_kernels:LigerRMSNorm", - "rocm": "kernels-community/rocm-kernels:RocmRMSNorm", - "metal": "kernels-community/metal-kernels:MetalRMSNorm", - "xpu": "kernels-community/xpu-kernels:XpuRMSNorm" + "cuda": "kernels-community/liger-kernels:LigerRMSNorm", + "rocm": "kernels-community/liger-kernels:LigerRMSNorm", + "xpu": "kernels-community/rmsnorm:RMSNorm" } } ) ``` +### Kernel metadata + +Add a metadata dict to control which kernel build is loaded. + +| Option | Description | Default | +|---|---|---| +| `version` | Major version of the kernel repository. `2` loads the latest build on the repository's `v2` branch. | `1` | +| `revision` | Exact tag, branch, or commit to load instead of a version. | --- | +| `trust_remote_code` | Allows a repository outside the trusted `kernels-community` organization. Loading a kernel runs code from that repository on your machine. | `False` | + +```py +from transformers import KernelConfig + +kernel_config = KernelConfig( + kernel_mapping={ + "RMSNorm": ("kernels-community/liger-kernels:LigerRMSNorm", {"version": 3}), + } +) +``` + +Older branches of a kernel repository may not have builds for your PyTorch and CUDA versions. If a kernel fails to load, try a newer `version` before concluding your hardware is unsupported. + +### Inherited mappings + +A `KernelConfig` inherits the default Transformers kernel mapping for Hub kernels, and entries in `kernel_mapping` +override the default for the corresponding layers and functions. Set `inherit_mapping=False` to use only the entries in `kernel_mapping`. Everything you leave out falls back to standard PyTorch. This is useful when benchmarking a +specific kernel or testing a custom implementation without applying the other defaults. + +The configuration below maps the `rotary_pos_emb` function to a RoPE kernel and leaves every other operation on +PyTorch. The function name must be registered by the model. + +```py +from transformers import AutoModelForCausalLM, KernelConfig + +kernel_config = KernelConfig( + kernel_mapping={ + "rotary_pos_emb": ( + "kernels-community/rotary:apply_rotary_transformers", + {"version": 2}, + ), + }, + inherit_mapping=False, +) + +model = AutoModelForCausalLM.from_pretrained( + "Qwen/Qwen3-0.6B", + use_kernels=True, + kernel_config=kernel_config, + device_map="auto", +) +``` + ## Module fusion Fuse adjacent modules into a single kernel by passing a tuple of `(class_name, path_pattern)` pairs as the key in [`KernelConfig`]. All patterns must share the same parent module. `*` matches any single path segment. @@ -242,7 +297,7 @@ Local kernels use `/abs/path:layer_name` instead of the Hub format `org/repo:lay from transformers import KernelConfig, AutoModelForCausalLM kernel_mapping = { - "RMSNorm": "/path/to/liger_kernels:LigerRMSNorm", + "RMSNorm": "/path/to/liger-kernels:LigerRMSNorm", } kernel_config = KernelConfig(kernel_mapping, use_local_kernel=True) @@ -255,28 +310,9 @@ model = AutoModelForCausalLM.from_pretrained( ) ``` -## Disabling kernels - -Disable kernels for specific layers with an empty kernel mapping in [`KernelConfig`]. - -```py -from transformers import AutoModelForCausalLM, KernelConfig - -kernel_config = KernelConfig( - kernel_mapping={ - "RMSNorm": "", - } -) - -model = AutoModelForCausalLM.from_pretrained( - "Qwen/Qwen3-0.6B", - use_kernels=True, - kernel_config=kernel_config, - device_map="auto" -) -``` +## Disable kernels globally -Set the environment variable to disable kernels globally. +Set the `USE_HUB_KERNELS` environment variable to disable Hub kernels everywhere without changing your code. ```bash export USE_HUB_KERNELS=0 # or OFF or NO @@ -288,10 +324,10 @@ Kernel integration depends on hardware, drivers, and package versions working to ### Installation issues -Import errors indicate the kernels library isn't installed. +Import errors mean the kernels package is missing or its version falls outside the range Transformers supports. Reinstall through the extra to get a compatible version. ```bash -pip install -U kernels +pip install -U "transformers[kernels]" ``` ### Kernel loading failures diff --git a/docs/source/en/kernels.md b/docs/source/en/kernels.md index 4960365241c6..53a1896a11f6 100644 --- a/docs/source/en/kernels.md +++ b/docs/source/en/kernels.md @@ -27,7 +27,7 @@ from transformers import AutoModelForCausalLM, KernelConfig kernel_config = KernelConfig( kernel_mapping={ - "RMSNorm": "kernels-community/rmsnorm", + "RMSNorm": "kernels-community/liger-kernels:LigerRMSNorm", } ) model = AutoModelForCausalLM.from_pretrained( From dd35e077078d9aebbdbc8f64a138a5951aa79ffc Mon Sep 17 00:00:00 2001 From: Vimal Sahani Date: Wed, 2 Sep 2026 16:34:42 +0000 Subject: [PATCH 032/996] doc: fix syntax error and typos in VibeVoice documentation (#48489) --- docs/source/en/model_doc/vibevoice.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/source/en/model_doc/vibevoice.md b/docs/source/en/model_doc/vibevoice.md index 9f2eff5838a5..94dc3ade33ea 100644 --- a/docs/source/en/model_doc/vibevoice.md +++ b/docs/source/en/model_doc/vibevoice.md @@ -9,7 +9,7 @@ Unless required by applicable law or agreed to in writing, software distributed 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. -⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be +⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> @@ -27,7 +27,7 @@ rendered properly in your Markdown viewer. [VibeVoice](https://huggingface.co/papers/2508.19205) is a novel framework for synthesizing high-fidelity, long-form speech with multiple speakers by employing a next-token diffusion approach within a Large Language Model (LLM) structure. It's designed to capture the authentic conversational "vibe" and is particularly suited for generating audio content like podcasts and multi-participant audiobooks. -Two model checkpoint are available at: +Two model checkpoints are available at: - [vibevoice/VibeVoice-1.5B-hf](https://huggingface.co/vibevoice/VibeVoice-1.5B-hf) - [vibevoice/VibeVoice-7B-hf](https://huggingface.co/vibevoice/VibeVoice-7B-hf) @@ -41,7 +41,7 @@ This model was contributed by [Eric Bezzam](https://huggingface.co/bezzam). The VibeVoice framework integrates three key components: 1. **Continuous Speech Tokenizers:** Specialized [acoustic](./vibevoice_acoustic_tokenizer) and [semantic](./vibevoice_semantic_tokenizer) tokenizers, where the acoustic tokenizer uses a $\sigma$-VAE to achieve ultra-low compression (7.5 tokens/sec, 3200x) for scalability and fidelity, and the semantic tokenizer uses an ASR proxy task for content-centric feature extraction. -2. **Large Language Model (LLM):** Use Qwen2.5 (in 1.5B and 7B versions) as its core sequence model. +2. **Large Language Model (LLM):** Uses Qwen2.5 (in 1.5B and 7B versions) as its core sequence model. 3. **Token-Level Diffusion Head:** conditioned on the LLM's hidden state and responsible for predicting the continuous VAE features in a streaming fashion. The original VibeVoice-1.5B checkpoint is available under the [Microsoft](https://huggingface.co/microsoft/VibeVoice-1.5B) organization on Hugging Face. @@ -149,7 +149,7 @@ print(f"Saved output to {fn}") ### Generating a podcast from a script -Below is an example to generate a conversation between two speakers, whose voices are cloned by providing a refence audio for each unique role ID in the chat template. +Below is an example to generate a conversation between two speakers, whose voices are cloned by providing a reference audio for each unique role ID in the chat template. The example below also used the `monitor_progress` option to track the generation progress. @@ -470,7 +470,7 @@ inputs = processor.apply_chat_template( conversation, tokenize=True, return_dict=True, add_generation_prompt=True, ).to(model.device, model.dtype) -compile_config = CompileConfig(mode="default" dynamic=False) +compile_config = CompileConfig(mode="default", dynamic=False) generate_kwargs = dict( **inputs, From 64d071cca5ab762365d860cc78eedfd16c973e47 Mon Sep 17 00:00:00 2001 From: Steven Liu <59462357+stevhliu@users.noreply.github.com> Date: Wed, 2 Sep 2026 18:23:24 +0000 Subject: [PATCH 033/996] [docs] Partial checkpointing and group_by_length (#48463) * docs * feedback * offload --- docs/source/en/grad_checkpointing.md | 55 +++++++++++++++++++++++++++- docs/source/en/trainer_recipes.md | 20 ++++++++++ docs/source/en/training.md | 5 ++- 3 files changed, 77 insertions(+), 3 deletions(-) diff --git a/docs/source/en/grad_checkpointing.md b/docs/source/en/grad_checkpointing.md index 9ec9caf71e77..8e573e186df0 100644 --- a/docs/source/en/grad_checkpointing.md +++ b/docs/source/en/grad_checkpointing.md @@ -27,7 +27,8 @@ Gradient checkpointing: Backward: ←reaches L2, recomputes L2→L3 from scratch, uses it, discards it ``` -Training will be ~20% slower because some activations need to be recomputed, but it reduces activation memory. +Training is typically slower because the backward pass recomputes discarded activations, but checkpointing reduces +activation memory. Set `gradient_checkpointing=True` to enable. @@ -43,9 +44,59 @@ args = TrainingArguments( ) ``` +## Partial checkpointing + +Full gradient checkpointing recomputes every checkpointable layer. If your run has some memory headroom, checkpoint +fewer layers to trade some of the memory savings for speed. + +Pass `every_n_layers` to [`~PreTrainedModel.gradient_checkpointing_enable`] to choose the +checkpointing interval. + +```text +every_n_layers=2 + +Forward: input -> [L1] -> [L2] -> [L3] -> [L4] -> [L5] -> [L6] + CP keep CP keep CP keep + +Backward: output <- [L6] <- [L5] <- [L4] <- [L3] <- [L2] <- [L1] + keep rerun keep rerun keep rerun +``` + +With `every_n_layers=2`, the first layer and every second layer after it are checkpointed. Checkpointed layers discard +their activations during the forward pass and recompute them during the backward pass, while the other layers keep their +activations in memory. + +```py +model.gradient_checkpointing_enable(every_n_layers=2) +``` + +The default, `every_n_layers=1`, checkpoints every layer. Larger values checkpoint the first layer and then every `n` +layers after it, leaving the other layers' activations in memory. For example, `every_n_layers=2` checkpoints +layers 1, 3, 5, and so on. Only modules that inherit from [`GradientCheckpointingLayer`] are counted. Other modules +that support gradient checkpointing remain enabled. + +To use partial gradient checkpointing with [`Trainer`], set `every_n_layers` in `gradient_checkpointing_kwargs`. + +```py +from transformers import TrainingArguments + +args = TrainingArguments( + ..., + gradient_checkpointing=True, + gradient_checkpointing_kwargs={"every_n_layers": 4}, +) +``` + +
+ +
+ ## Offloading the saved activations -Gradient checkpointing still keeps one activation per checkpointed layer on the GPU, and at long sequence lengths that alone is large: `layers x sequence x hidden` bytes, so 36 layers of an 8B model at 128k tokens is 36 GB. Set `offload` to hold those in pinned host memory instead, and pay a device-to-host copy in the forward and a host-to-device copy in the backward for them. +Gradient checkpointing keeps one activation per checkpointed layer on the GPU. At long sequence lengths, this can +consume substantial memory (approximately `layers x sequence x hidden x bytes_per_element`). Set `offload` to hold +those activations in pinned host memory instead, at the cost of a device-to-host copy during the forward pass and a +host-to-device copy during the backward pass. ```py from transformers import TrainingArguments diff --git a/docs/source/en/trainer_recipes.md b/docs/source/en/trainer_recipes.md index db40ee691a72..29f624c8b4eb 100644 --- a/docs/source/en/trainer_recipes.md +++ b/docs/source/en/trainer_recipes.md @@ -157,6 +157,26 @@ args = TrainingArguments( ) ``` +## Group samples by length + +Use `train_sampling_strategy="group_by_length"` to batch examples with similar lengths and reduce padding. When you +don't provide precomputed lengths, [`Trainer`] infers them from the first model input in each dataset item. This also +works when processor-based multimodal datasets return [`BatchFeature`] objects, because they are mapping-like feature +containers. + +```py +from transformers import TrainingArguments + +training_args = TrainingArguments( + output_dir="qwen3-vl-finetuned", + train_sampling_strategy="group_by_length", +) +``` + +If a [`~datasets.Dataset`] already has a precomputed length column, [`Trainer`] uses that column instead. The default +column name is `length`. Set `length_column_name` when your dataset uses another name. This strategy requires a +dataset with a known length and is ignored for [`~datasets.IterableDataset`]. + ## Batch rebalance sampling On variable-length datasets, imbalance within a micro-batch and across devices causes devices to waste time on padding and to idle at gradient synchronization steps. diff --git a/docs/source/en/training.md b/docs/source/en/training.md index 30f5ffdc5fda..52eae902a48e 100644 --- a/docs/source/en/training.md +++ b/docs/source/en/training.md @@ -98,7 +98,9 @@ model = AutoModelForCausalLM.from_pretrained(model_name, dtype="auto") - Set `bf16=True` for fast mixed precision training if your hardware supports it (Ampere+ GPUs). Otherwise, fall back to `fp16=True` on older hardware. - `gradient_accumulation_steps` simulates a larger effective batch size by accumulating gradients over multiple forward passes before updating weights. -- `gradient_checkpointing` trades compute for memory by recomputing intermediate activations during the backward pass instead of storing them. +- `gradient_checkpointing` trades compute for memory by recomputing intermediate activations during the backward pass instead of storing them. For a compromise between memory and speed, see [partial checkpointing](./grad_checkpointing#partial-checkpointing). +- When `gradient_checkpointing=True`, set `gradient_checkpointing_kwargs={"offload": True}` to keep saved activations in pinned host memory and reduce GPU memory usage for long sequences. See [offloading the saved activations](./grad_checkpointing#offloading-the-saved-activations) for the trade-off. +- Set `train_sampling_strategy="group_by_length"` to batch examples with similar lengths and reduce padding. See [group samples by length](./trainer_recipes#group-samples-by-length) for processor-based multimodal datasets and precomputed lengths.
@@ -121,6 +123,7 @@ training_args = TrainingArguments( per_device_train_batch_size=2, gradient_accumulation_steps=8, gradient_checkpointing=True, + gradient_checkpointing_kwargs={"every_n_layers": 4}, bf16=True, learning_rate=2e-5, logging_steps=10, From 78fa17cb266f566f339d85acb8ecafc675d1119e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Quentin=20Gallou=C3=A9dec?= <45557362+qgallouedec@users.noreply.github.com> Date: Thu, 3 Sep 2026 01:01:46 +0000 Subject: [PATCH 034/996] Warn once when a hub-kernel function falls back to its reference PyTorch path (#48185) * Warn once when a hub-kernel function falls back to its reference PyTorch path * Name the pip distribution for causal_conv1d too * Keep the logger out of traced graphs, drop the distribution map * Trim the comments * Move the distribution name next to its only use * Say how much slower the reference path is * Reword the comment to say what the code does * Update src/transformers/integrations/hub_kernels.py Co-authored-by: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com> * Move the distribution alias next to the internal path mapping --------- Co-authored-by: q Co-authored-by: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com> --- src/transformers/integrations/hub_kernels.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/transformers/integrations/hub_kernels.py b/src/transformers/integrations/hub_kernels.py index 55947e6ecfb8..db53acb54073 100644 --- a/src/transformers/integrations/hub_kernels.py +++ b/src/transformers/integrations/hub_kernels.py @@ -33,6 +33,7 @@ is_kernels_available, is_rocm_platform, is_torch_available, + is_torchdynamo_compiling, is_torchdynamo_exporting, resolve_internal_import, ) @@ -75,6 +76,9 @@ "selective_scan_fn": "ops.selective_scan_interface", } +# Maps from import name to the distribution that ships it, where the two differ +_PACKAGE_TO_DISTRIBUTION = {"fla": "flash-linear-attention"} + if is_kernels_available(): from kernels import ( @@ -857,6 +861,18 @@ def wrapped(*args, **kwargs): if is_new_implementation and is_torchdynamo_exporting(): return torch_function(*args, **kwargs) + if not is_new_implementation and not is_torchdynamo_compiling(): + # These torch paths are readable references, not fast kernels, so their runtimes are + # significantly slower: for `chunk_gated_delta_rule` the gap is more than an order of + # magnitude on an H100. Warn the user when they end up on one. The logger is untraceable, + # hence the guard. + distribution = _PACKAGE_TO_DISTRIBUTION.get(package, package) + logger.warning_once( + f"`{func_name}` is falling back to its reference PyTorch implementation because " + f"`{distribution}` is not installed. This is correct but much slower; install " + f"`{distribution}` for the optimized kernel." + ) + kwargs = {k: v for k, v in kwargs.items() if k in applicable_params} return implementation(*args, **kwargs) From 8f542025728f98e8b3338b997fe569065b6204aa Mon Sep 17 00:00:00 2001 From: Cyril Vallez Date: Thu, 3 Sep 2026 11:08:56 +0900 Subject: [PATCH 035/996] Simplify and fix qwen4 tests (#48340) * start where i was * fix expected conv shapes * much cleaner * style * continue * fix * fix device placement --- src/transformers/core_model_loading.py | 5 + .../models/qwen4_exp/modeling_qwen4_exp.py | 8 +- .../models/qwen4_exp/modular_qwen4_exp.py | 8 +- .../qwen4_exp/test_modeling_qwen4_exp.py | 445 +++++++----------- tests/test_fsdp_mixin.py | 1 - 5 files changed, 189 insertions(+), 278 deletions(-) diff --git a/src/transformers/core_model_loading.py b/src/transformers/core_model_loading.py index 80cd1e027c53..580f46849c3c 100644 --- a/src/transformers/core_model_loading.py +++ b/src/transformers/core_model_loading.py @@ -1761,6 +1761,11 @@ def convert_and_load_state_dict_in_model( for target_name, param in realized_value.items(): param = param[0] if isinstance(param, list) else param param_device = get_device(device_map, target_name) + # Exception for params that are so huge that they need conversions on cpu no matter what - we put them back on + # the correct device now (if the device_map managed to make them fit on any device, as usually they will stay on + # cpu and this is a no-op) + if getattr(mapping, "force_cpu", False) and param_device != "disk": + param = param.to(param_device) # Offloading support if param_device == "disk" and (target_name not in model_buffers or offload_buffers): disk_offload_index = offload_and_maybe_resave_param( diff --git a/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py b/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py index bf01c2fe356b..03bad163f9ee 100644 --- a/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py +++ b/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py @@ -1182,8 +1182,12 @@ def forward(self, input_ids: torch.Tensor, past_key_values: Cache | None) -> tor blocks.append(ngram_ids + head_offsets.view(1, 1, -1)) ngram_ids = torch.cat(blocks, dim=-1)[:, -input_ids.shape[1] :] - # We need explicit device placement here, as the embedding may be skipped from device_map completely - return self.ngram_embedding(ngram_ids.to(self.ngram_embedding.weight.device)).to(ngram_ids.device).flatten(-2) + # We need explicit device placement here, as the embedding may be skipped from device_map completely (we just need to be + # careful in the case of offloading to disk) + execution_device = ( + self.ngram_embedding.weight.device if self.ngram_embedding.weight.device.type != "meta" else None + ) + return self.ngram_embedding(ngram_ids.to(execution_device)).to(ngram_ids.device).flatten(-2) class Qwen4ExpTextPLELayer(nn.Module): diff --git a/src/transformers/models/qwen4_exp/modular_qwen4_exp.py b/src/transformers/models/qwen4_exp/modular_qwen4_exp.py index 2c1ec18ca6f2..be83ff59c091 100644 --- a/src/transformers/models/qwen4_exp/modular_qwen4_exp.py +++ b/src/transformers/models/qwen4_exp/modular_qwen4_exp.py @@ -699,8 +699,12 @@ def forward(self, input_ids: torch.Tensor, past_key_values: Cache | None) -> tor blocks.append(ngram_ids + head_offsets.view(1, 1, -1)) ngram_ids = torch.cat(blocks, dim=-1)[:, -input_ids.shape[1] :] - # We need explicit device placement here, as the embedding may be skipped from device_map completely - return self.ngram_embedding(ngram_ids.to(self.ngram_embedding.weight.device)).to(ngram_ids.device).flatten(-2) + # We need explicit device placement here, as the embedding may be skipped from device_map completely (we just need to be + # careful in the case of offloading to disk) + execution_device = ( + self.ngram_embedding.weight.device if self.ngram_embedding.weight.device.type != "meta" else None + ) + return self.ngram_embedding(ngram_ids.to(execution_device)).to(ngram_ids.device).flatten(-2) class Qwen4ExpTextPLELayer(nn.Module): diff --git a/tests/models/qwen4_exp/test_modeling_qwen4_exp.py b/tests/models/qwen4_exp/test_modeling_qwen4_exp.py index b308989e1149..11144548c8fc 100644 --- a/tests/models/qwen4_exp/test_modeling_qwen4_exp.py +++ b/tests/models/qwen4_exp/test_modeling_qwen4_exp.py @@ -19,10 +19,9 @@ import unittest from huggingface_hub.errors import StrictDataclassClassValidationError -from parameterized import parameterized from transformers import is_torch_available -from transformers.testing_utils import is_fsdp_test, require_torch, require_torch_greater_or_equal, torch_device +from transformers.testing_utils import require_torch, torch_device from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester from ...test_modeling_common import floats_tensor @@ -68,7 +67,7 @@ def __init__(self, parent): self.linear_num_value_heads = 8 self.hc_count = 2 self.hc_lowrank = 8 - self.ple_layer_ids = [] + self.ple_layer_ids = [1] self.ple_embed_dim = 16 self.ple_conv_kernel_size = 2 self.ngram_size = 3 @@ -85,101 +84,50 @@ def __init__(self, parent): self.shared_expert_intermediate_size = 8 self.num_experts = 4 - def get_config(self, **overrides): - config = super().get_config() - if not overrides: - return config - - if "layer_types" in overrides: - overrides.setdefault("num_hidden_layers", len(overrides["layer_types"])) - config_dict = config.to_dict() - config_dict.pop("number_of_conv_states", None) - config_dict.update(overrides) - return self.config_class.from_dict(config_dict) - @require_torch class Qwen4ExpTextModelTest(CausalLMModelTest, unittest.TestCase): model_tester_class = Qwen4ExpTextModelTester model_split_percents = [0.5, 0.8, 0.9] - # QSA indexer parameters are trained through a separate objective rather than the causal-LM loss. test_all_params_have_gradient = False test_torch_exportable = False # QSA index selection has data-dependent control flow + def prepare_config_and_inputs_for_generate(self, batch_size=2): + config, inputs = super().prepare_config_and_inputs_for_generate(batch_size) + # Override as it's needed inside the model... But use a value way outside vocab to avoid using/generating it + config.eos_token_id = self.model_tester.vocab_size + 100000 + return config, inputs + def _get_conv_state_shape(self, batch_size: int, config): - intermediate_size = ( + intermediate_size_conv0 = ( 2 * config.linear_num_key_heads * config.linear_key_head_dim + config.linear_num_value_heads * config.linear_value_head_dim ) - return (batch_size, intermediate_size, config.linear_conv_kernel_dim) + shape_conv0 = (batch_size, intermediate_size_conv0, config.linear_conv_kernel_dim) - def _get_recurrent_state_shape(self, batch_size: int, config): - return ( - batch_size, - config.linear_num_value_heads, - config.linear_key_head_dim, - config.linear_value_head_dim, - ) + short_conv_state_len = (config.ple_conv_kernel_size - 1) * config.ngram_size + intermediate_size_conv1 = config.hidden_size * config.hc_count + shape_conv1 = (batch_size, intermediate_size_conv1, short_conv_state_len) - def _get_all_layer_types_config(self): - return self.model_tester.get_config( - ple_layer_ids=[2], - layer_types=[ - "linear_attention", - "linear_attention", - "qwen_sparse_attention", - ], - ) + shape_conv2 = (batch_size, config.ngram_size - 1) - def _get_tp_config(self, tie_word_embeddings=None): - config = self._get_all_layer_types_config() - remainder = config.vocab_size % self.tensor_parallel_size - if remainder: - config.vocab_size += self.tensor_parallel_size - remainder - if tie_word_embeddings is not None: - config.tie_word_embeddings = tie_word_embeddings - return config - - def _get_tiny_config(self): - config = self._get_all_layer_types_config() - config.vocab_size = 256 - return type(config), config.to_diff_dict() - - def _assert_cached_matches_full(self, model, input_ids, test_static=False): - split_idx = (input_ids.shape[1] + 1) // 2 - with torch.no_grad(): - expected = model(input_ids, use_cache=False).last_hidden_state - chunk_cache = DynamicCache(config=model.config) - actual_outputs = [ - torch.cat( - [ - model(input_ids[:, :split_idx], past_key_values=chunk_cache, use_cache=True).last_hidden_state, - model(input_ids[:, split_idx:], past_key_values=chunk_cache, use_cache=True).last_hidden_state, - ], - dim=1, - ) - ] - decode_caches = [DynamicCache(config=model.config)] - if test_static: - decode_caches.append(StaticCache(config=model.config, max_cache_len=input_ids.shape[1])) - for cache in decode_caches: - actual_outputs.append( - torch.cat( - [ - model( - input_ids[:, token_idx : token_idx + 1], - past_key_values=cache, - use_cache=True, - ).last_hidden_state - for token_idx in range(input_ids.shape[1]) - ], - dim=1, - ) - ) + return [shape_conv0, shape_conv1, shape_conv2] - for actual in actual_outputs: - torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-5) + def _get_recurrent_state_shape(self, batch_size: int, config): + return (batch_size, config.linear_num_value_heads, config.linear_key_head_dim, config.linear_value_head_dim) + + def _check_hidden_states_for_generate( + self, batch_size, hidden_states, prompt_length, output_length, config, use_cache=False + ): + self.assertIsInstance(hidden_states, tuple) + self.assertEqual(len(hidden_states), output_length - prompt_length) + hidden_sizes = [config.hc_count * config.hidden_size] * config.num_hidden_layers + [config.hidden_size] + + for generated_length, iteration_hidden_states in enumerate(hidden_states): + seq_len = 1 if use_cache and generated_length > 0 else prompt_length + generated_length + expected_shapes = [(batch_size, seq_len, hidden_size) for hidden_size in hidden_sizes] + self.assertListEqual([state.shape for state in iteration_hidden_states], expected_shapes) def test_attention_outputs(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() @@ -217,18 +165,6 @@ def test_hidden_states_output(self): hidden_states = model(**inputs_dict).hidden_states self.assertListEqual([state.shape for state in hidden_states], expected_shapes) - def _check_hidden_states_for_generate( - self, batch_size, hidden_states, prompt_length, output_length, config, use_cache=False - ): - self.assertIsInstance(hidden_states, tuple) - self.assertEqual(len(hidden_states), output_length - prompt_length) - hidden_sizes = [config.hc_count * config.hidden_size] * config.num_hidden_layers + [config.hidden_size] - - for generated_length, iteration_hidden_states in enumerate(hidden_states): - seq_len = 1 if use_cache and generated_length > 0 else prompt_length + generated_length - expected_shapes = [(batch_size, seq_len, hidden_size) for hidden_size in hidden_sizes] - self.assertListEqual([state.shape for state in iteration_hidden_states], expected_shapes) - @unittest.skip("QSA index selection has data-dependent control flow") def test_generate_compile_model_forward_fullgraph(self): pass @@ -237,24 +173,35 @@ def test_generate_compile_model_forward_fullgraph(self): def test_generate_compilation_all_outputs(self): pass - def test_tp_plan_matches_params(self): - self.model_tester.ple_layer_ids = [1] - try: - super().test_tp_plan_matches_params() - finally: - self.model_tester.ple_layer_ids = [] + @unittest.skip("The specific cache format cannot be instantiated from dp/ddp data.") + def test_multi_gpu_data_parallel_forward(self): + pass + + @unittest.skip("Qwen4-Exp hybrid linear-attention cache is not compatible with quantized cache yet.") + def test_generate_with_quant_cache(self): + pass + + @unittest.skip( + "Cannot generate from random embeds since the ple embedding needs to revert them if input_ids are not provided" + ) + def test_generate_from_random_inputs_embeds(self): + pass + + @unittest.skip("Qwen4 needs the eos token explicitly inside the modeling for the ple embedding") + def test_model_forward_default_config_values(self): + pass def test_ple_layers_must_use_linear_attention(self): with self.assertRaisesRegex( StrictDataclassClassValidationError, "PLE is only supported on linear_attention layers" ): - self.model_tester.get_config( + _ = Qwen4ExpTextConfig( ple_layer_ids=[2], layer_types=["linear_attention", "qwen_sparse_attention"], ) def test_finegrained_fp8_embedding_conversion(self): - config = self.model_tester.get_config(ple_layer_ids=[1], layer_types=["linear_attention"]) + config = self.model_tester.get_config() with torch.device("meta"): model = Qwen4ExpForCausalLM(config) @@ -267,15 +214,12 @@ def test_finegrained_fp8_embedding_conversion(self): def test_ple_padding_and_static_cache_match_unpadded_sequence(self): torch.manual_seed(0) - config = self.model_tester.get_config( - ple_layer_ids=[2], - layer_types=["qwen_sparse_attention", "linear_attention"], - ) + config = self.model_tester.get_config() config._attn_implementation = "sdpa" model = Qwen4ExpForCausalLM(config).to(torch_device).eval() with torch.no_grad(): - model.model.layers[1].ple.norm_conv.weight.fill_(1) - model.model.layers[1].ple.conv1d.weight.normal_(mean=0.0, std=0.2) + model.model.layers[0].ple.norm_conv.weight.fill_(1) + model.model.layers[0].ple.conv1d.weight.normal_(mean=0.0, std=0.2) padded_ids = torch.tensor([[config.pad_token_id, config.pad_token_id, 5, 6, 7]], device=torch_device) attention_mask = torch.tensor([[0, 0, 1, 1, 1]], device=torch_device) @@ -290,24 +234,19 @@ def test_ple_padding_and_static_cache_match_unpadded_sequence(self): with torch.no_grad(): expected = model(padded_ids[:, -3:], use_cache=False).logits outputs = [model(padded_ids, attention_mask=attention_mask, use_cache=False).logits[:, -3:]] - for cache in (DynamicCache(config=config), static_cache): - inputs = ( - static_inputs - if cache is static_cache - else { - "input_ids": padded_ids, - "attention_mask": attention_mask, - "past_key_values": cache, - } - ) - outputs.append(model(**inputs, use_cache=True).logits[:, -3:]) + static_output = model(**static_inputs).logits[:, -3:] + dynamic_output = model( + input_ids=padded_ids, attention_mask=attention_mask, past_key_values=DynamicCache(config=config) + ).logits[:, -3:] + outputs.append(static_output) + outputs.append(dynamic_output) for actual in outputs: torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-5) def test_all_layer_types_cached_forward_match_full_forward(self): torch.manual_seed(0) - config = self._get_all_layer_types_config() + config = self.model_tester.get_config() config._attn_implementation = "eager" model = Qwen4ExpTextModel(config).to(torch_device).eval() with torch.no_grad(): @@ -319,33 +258,42 @@ def test_all_layer_types_cached_forward_match_full_forward(self): [[5, 6, config.eos_token_id, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17]], device=torch_device, ) - self._assert_cached_matches_full(model, input_ids, test_static=True) - - def test_ple_beam_generation(self): - config = self.model_tester.get_config( - ple_layer_ids=[1], - layer_types=["linear_attention", "qwen_sparse_attention"], - ) - config._attn_implementation = "eager" - model = Qwen4ExpForCausalLM(config).to(torch_device).eval() - input_ids = torch.tensor([[5, 6, 7]], device=torch_device) - for cache_implementation in (None, "static"): - with self.subTest(cache_implementation=cache_implementation), torch.no_grad(): - output = model.generate( - input_ids, - max_new_tokens=3, - num_beams=2, - cache_implementation=cache_implementation, - disable_compile=True, - do_sample=False, - eos_token_id=None, + split_idx = (input_ids.shape[1] + 1) // 2 + with torch.no_grad(): + expected = model(input_ids, use_cache=False).last_hidden_state + chunk_cache = DynamicCache(config=model.config) + actual_outputs = [ + torch.cat( + [ + model(input_ids[:, :split_idx], past_key_values=chunk_cache, use_cache=True).last_hidden_state, + model(input_ids[:, split_idx:], past_key_values=chunk_cache, use_cache=True).last_hidden_state, + ], + dim=1, + ) + ] + decode_caches = [DynamicCache(config=model.config)] + decode_caches.append(StaticCache(config=model.config, max_cache_len=input_ids.shape[1])) + for cache in decode_caches: + actual_outputs.append( + torch.cat( + [ + model( + input_ids[:, token_idx : token_idx + 1], + past_key_values=cache, + use_cache=True, + ).last_hidden_state + for token_idx in range(input_ids.shape[1]) + ], + dim=1, + ) ) - self.assertEqual(output.shape, (1, input_ids.shape[1] + 3)) + for actual in actual_outputs: + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-5) def test_ple_sharded_checkpoint_loads_and_forwards(self): - config = self.model_tester.get_config(ple_layer_ids=[1], layer_types=["linear_attention"]) + config = self.model_tester.get_config() config.split_ngram_parts = 12 model = Qwen4ExpForCausalLM(config) state_dict = model.state_dict() @@ -376,7 +324,7 @@ def test_ple_sharded_checkpoint_loads_and_forwards(self): torch.testing.assert_close(actual, expected) def test_generate_with_ple_and_inputs_embeds(self): - config = self.model_tester.get_config(ple_layer_ids=[1]) + config = self.model_tester.get_config() model = Qwen4ExpForCausalLM(config).to(torch_device).eval() model.generation_config.eos_token_id = None input_ids = torch.tensor([[5, 6, 7]], device=torch_device) @@ -390,42 +338,6 @@ def test_generate_with_ple_and_inputs_embeds(self): ) torch.testing.assert_close(actual, expected[:, input_ids.shape[1] :]) - @unittest.skip("The specific cache format cannot be instantiated from dp/ddp data.") - def test_multi_gpu_data_parallel_forward(self): - pass - - @unittest.skip("Qwen4-Exp hybrid linear-attention cache is not compatible with quantized cache yet.") - def test_generate_with_quant_cache(self): - pass - - def test_reverse_loading_mapping(self, check_keys_were_modified=True): - self.model_tester.ple_layer_ids = [1] - self.model_tester.split_ngram_parts = 12 - try: - super().test_reverse_loading_mapping(check_keys_were_modified) - finally: - self.model_tester.ple_layer_ids = [] - self.model_tester.split_ngram_parts = 4 - - @require_torch_greater_or_equal("2.7") - @is_fsdp_test - @unittest.skip(reason="FIXME: Cyril or Ferdinand") - def test_fsdp2_save_load(self): - pass - - @require_torch_greater_or_equal("2.7") - @is_fsdp_test - @unittest.skip(reason="FIXME: Cyril or Ferdinand") - def test_fsdp2_save_load_dcp(self): - pass - - @parameterized.expand(["untied", "tied"]) - @require_torch_greater_or_equal("2.7") - @is_fsdp_test - @unittest.skip(reason="FIXME: Cyril or Ferdinand") - def test_fsdp2_plan_vs_ddp(self, label): - pass - class Qwen4ExpVisionText2TextModelTester(VLMModelTester): base_model_class = Qwen4ExpModel @@ -435,63 +347,64 @@ class Qwen4ExpVisionText2TextModelTester(VLMModelTester): conditional_generation_class = Qwen4ExpForConditionalGeneration def __init__(self, parent, **kwargs): - kwargs.setdefault("num_key_value_heads", 1) - kwargs.setdefault("head_dim", 24) - kwargs.setdefault("hidden_act", "silu") - kwargs.setdefault("layer_types", ["linear_attention", "qwen_sparse_attention"]) - kwargs.setdefault("linear_conv_kernel_dim", 2) - kwargs.setdefault("linear_key_head_dim", 16) - kwargs.setdefault("linear_value_head_dim", 16) - kwargs.setdefault("linear_num_key_heads", 4) - kwargs.setdefault("linear_num_value_heads", 8) - kwargs.setdefault("hc_count", 2) - kwargs.setdefault("hc_lowrank", 8) - kwargs.setdefault("ple_layer_ids", []) - kwargs.setdefault("ple_embed_dim", 16) - kwargs.setdefault("ple_conv_kernel_size", 2) - kwargs.setdefault("ngram_size", 3) - kwargs.setdefault("heads_per_ngram", 2) - kwargs.setdefault("ngram_vocab_size_base", 31) - kwargs.setdefault("make_ngram_vocab_size_divisible_by", 8) - kwargs.setdefault("split_ngram_parts", 4) - kwargs.setdefault("indexer_n_heads", 2) - kwargs.setdefault("indexer_kv_heads", 1) - kwargs.setdefault("indexer_head_dim", 8) - kwargs.setdefault("indexer_budget", 4) - kwargs.setdefault("indexer_compress_ratio", 2) - kwargs.setdefault("moe_intermediate_size", 8) - kwargs.setdefault("shared_expert_intermediate_size", 8) - kwargs.setdefault("num_experts", 4) - kwargs.setdefault("bos_token_id", 0) - kwargs.setdefault("eos_token_id", 1) - kwargs.setdefault("pad_token_id", 2) - kwargs.setdefault("video_token_id", 4) - kwargs.setdefault("vision_start_token_id", 5) - kwargs.setdefault("vision_end_token_id", 6) - kwargs.setdefault("image_size", 16) - kwargs.setdefault("patch_size", 16) - kwargs.setdefault("depth", 1) - kwargs.setdefault("vision_hidden_act", "gelu_pytorch_tanh") - kwargs.setdefault("num_heads", 4) - kwargs.setdefault("spatial_merge_size", 1) - kwargs.setdefault("temporal_patch_size", 2) - kwargs.setdefault("num_position_embeddings", 16) - kwargs.setdefault( - "rope_parameters", - { - "rope_type": "default", - "partial_rotary_factor": 0.25, - "mrope_section": [1, 1, 1], - "mrope_interleaved": True, - }, - ) super().__init__(parent, **kwargs) + self.num_key_value_heads = 1 + self.head_dim = 24 + self.hidden_act = "silu" + self.layer_types = ["linear_attention", "qwen_sparse_attention"] + self.linear_conv_kernel_dim = 2 + self.linear_key_head_dim = 16 + self.linear_value_head_dim = 16 + self.linear_num_key_heads = 4 + self.linear_num_value_heads = 8 + self.hc_count = 2 + self.hc_lowrank = 8 + self.ple_layer_ids = [1] + self.ple_embed_dim = 16 + self.ple_conv_kernel_size = 2 + self.ngram_size = 3 + self.heads_per_ngram = 2 + self.ngram_vocab_size_base = 31 + self.make_ngram_vocab_size_divisible_by = 8 + self.split_ngram_parts = 4 + self.indexer_n_heads = 2 + self.indexer_kv_heads = 1 + self.indexer_head_dim = 8 + self.indexer_budget = 4 + self.indexer_compress_ratio = 2 + self.moe_intermediate_size = 8 + self.shared_expert_intermediate_size = 8 + self.num_experts = 4 + self.bos_token_id = 0 + self.eos_token_id = 1 + self.pad_token_id = 2 + self.video_token_id = 4 + self.vision_start_token_id = 5 + self.vision_end_token_id = 6 + self.image_size = 16 + self.patch_size = 16 + self.depth = 1 + self.vision_hidden_act = "gelu_pytorch_tanh" + self.num_heads = 4 + self.spatial_merge_size = 1 + self.temporal_patch_size = 2 + self.num_position_embeddings = 16 + self.rope_parameters = { + "rope_type": "default", + "partial_rotary_factor": 0.25, + "mrope_section": [1, 1, 1], + "mrope_interleaved": True, + } self.in_channels = self.num_channels self.out_hidden_size = self.hidden_size self.vision_hidden_size = self.hidden_size self.vision_intermediate_size = self.hidden_size self.expected_num_hidden_layers = self.depth + 1 + @property + def _special_token_ids(self): + return super()._special_token_ids | {self.video_token_id, self.vision_start_token_id, self.vision_end_token_id} + def create_pixel_values(self): return floats_tensor( [ @@ -500,14 +413,6 @@ def create_pixel_values(self): ] ) - @property - def _special_token_ids(self): - return super()._special_token_ids | { - self.video_token_id, - self.vision_start_token_id, - self.vision_end_token_id, - } - def place_image_tokens(self, input_ids, config): input_ids = input_ids.clone() input_ids[:, -1] = self.pad_token_id @@ -523,46 +428,37 @@ def get_additional_inputs(self, config, input_ids, modality_inputs): "mm_token_type_ids": mm_token_type_ids, } - def get_config(self, ple_layer_ids=None): - text_config = self.get_text_config().to_dict() - text_config.pop("number_of_conv_states", None) - if ple_layer_ids is not None: - text_config["ple_layer_ids"] = ple_layer_ids - return Qwen4ExpConfig( - text_config=text_config, - vision_config=self.get_vision_config().to_dict(), - image_token_id=self.image_token_id, - video_token_id=self.video_token_id, - vision_start_token_id=self.vision_start_token_id, - vision_end_token_id=self.vision_end_token_id, - tie_word_embeddings=self.tie_word_embeddings, - pad_token_id=self.pad_token_id, - ) - @require_torch -class Qwen4ExpCompositeModelTest(VLMModelTest, unittest.TestCase): +class Qwen4ExpVisionText2TextModelTest(VLMModelTest, unittest.TestCase): model_tester_class = Qwen4ExpVisionText2TextModelTester + model_split_percents = [0.5, 0.8, 0.9] test_all_params_have_gradient = False test_torch_exportable = False # QSA index selection has data-dependent control flow - def get_config(self): - return self.model_tester.get_config(ple_layer_ids=[1]) + def prepare_config_and_inputs_for_generate(self, batch_size=2): + config, inputs = super().prepare_config_and_inputs_for_generate(batch_size) + # Override as it's needed inside the model... But use a value way outside vocab to avoid using/generating it + config.text_config.eos_token_id = self.model_tester.vocab_size + 100000 + return config, inputs def _get_conv_state_shape(self, batch_size: int, config): - intermediate_size = ( + intermediate_size_conv0 = ( 2 * config.linear_num_key_heads * config.linear_key_head_dim + config.linear_num_value_heads * config.linear_value_head_dim ) - return (batch_size, intermediate_size, config.linear_conv_kernel_dim) + shape_conv0 = (batch_size, intermediate_size_conv0, config.linear_conv_kernel_dim) + + short_conv_state_len = (config.ple_conv_kernel_size - 1) * config.ngram_size + intermediate_size_conv1 = config.hidden_size * config.hc_count + shape_conv1 = (batch_size, intermediate_size_conv1, short_conv_state_len) + + shape_conv2 = (batch_size, config.ngram_size - 1) + + return [shape_conv0, shape_conv1, shape_conv2] def _get_recurrent_state_shape(self, batch_size: int, config): - return ( - batch_size, - config.linear_num_value_heads, - config.linear_key_head_dim, - config.linear_value_head_dim, - ) + return (batch_size, config.linear_num_value_heads, config.linear_key_head_dim, config.linear_value_head_dim) def _check_hidden_states_for_generate( self, batch_size, hidden_states, prompt_length, output_length, config, use_cache=False @@ -664,21 +560,24 @@ def test_generate_with_quant_cache(self): def test_multi_gpu_data_parallel_forward(self): pass - def test_tp_plan_matches_params(self): - self.model_tester.ple_layer_ids = [1] - try: - super().test_tp_plan_matches_params() - finally: - self.model_tester.ple_layer_ids = [] + @unittest.skip( + "Cannot generate from random embeds since the ple embedding needs to revert them if input_ids are not provided" + ) + def test_generate_from_random_inputs_embeds(self): + pass + + @unittest.skip("Qwen4 needs the eos token explicitly inside the modeling for the ple embedding") + def test_model_forward_default_config_values(self): + pass def test_fsdp_plan_has_no_unused_rules(self): with torch.device("meta"): - model = Qwen4ExpForConditionalGeneration(self.get_config()) + model = Qwen4ExpForConditionalGeneration(self.model_tester.get_config()) with self.assertNoLogs("transformers.distributed.fsdp", level="WARNING"): verify_fsdp_plan([name for name, _ in model.named_modules()], model._fsdp_plan) def test_generate_with_ple_and_inputs_embeds(self): - config = self.get_config() + config = self.model_tester.get_config() model = Qwen4ExpForConditionalGeneration(config).to(torch_device).eval() model.generation_config.eos_token_id = None input_ids = torch.tensor([[7, 8, 9, 10]], device=torch_device) @@ -705,7 +604,7 @@ def test_video_forward(self): model(**inputs) def test_composite_checkpoint_loads_as_causal_lm(self): - config = self.get_config() + config = self.model_tester.get_config() composite_model = Qwen4ExpForConditionalGeneration(config).eval() with tempfile.TemporaryDirectory() as tmpdirname: @@ -725,7 +624,7 @@ def test_composite_checkpoint_loads_as_causal_lm(self): torch.testing.assert_close(actual, expected) def test_base_model_checkpoint_loads_as_conditional_generation(self): - config = self.get_config() + config = self.model_tester.get_config() base_model = Qwen4ExpModel(config).eval() with tempfile.TemporaryDirectory() as tmpdirname: diff --git a/tests/test_fsdp_mixin.py b/tests/test_fsdp_mixin.py index f305b8d14967..51dd0c7b20e5 100644 --- a/tests/test_fsdp_mixin.py +++ b/tests/test_fsdp_mixin.py @@ -77,7 +77,6 @@ "mixtral", "qwen3", "qwen3_moe", - "qwen4_exp_text", } From 774a675d827ed321b302a907941b4bee33efda03 Mon Sep 17 00:00:00 2001 From: Cyril Vallez Date: Thu, 3 Sep 2026 12:02:26 +0900 Subject: [PATCH 036/996] Fix Inkling inputs_embeds and add more tests (#47827) * fix * also on main model * use buffer as everywhere else * norm as well * set buffer to zeros in init as well * last small fix --- src/transformers/models/auto/modeling_auto.py | 1 + .../models/inkling/modeling_inkling.py | 21 +++++++++++-------- .../models/inkling/modular_inkling.py | 21 +++++++++++-------- tests/models/inkling/test_modeling_inkling.py | 17 ++++++++++++--- 4 files changed, 39 insertions(+), 21 deletions(-) diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index c6d153074b28..e6b27a561fed 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -269,6 +269,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin): ("imagegpt", "ImageGPTModel"), ("informer", "InformerModel"), ("inkling_mm_model", "InklingModel"), + ("inkling_text", "InklingTextModel"), ("instructblip", "InstructBlipModel"), ("instructblipvideo", "InstructBlipVideoModel"), ("internvl", "InternVLModel"), diff --git a/src/transformers/models/inkling/modeling_inkling.py b/src/transformers/models/inkling/modeling_inkling.py index 0bb061b3ea37..efcd8d6c205a 100644 --- a/src/transformers/models/inkling/modeling_inkling.py +++ b/src/transformers/models/inkling/modeling_inkling.py @@ -351,7 +351,7 @@ def __init__(self, config): self.weight = nn.Parameter(torch.empty(self.n_total_experts, config.hidden_size)) self.global_scale = nn.Parameter(torch.ones(1)) - self.e_score_correction_bias = nn.Parameter(torch.empty(self.num_experts)) + self.e_score_correction_bias = nn.Buffer(torch.zeros(self.num_experts)) def forward(self, hidden_states) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: flat = hidden_states.reshape(-1, self.hidden_dim) @@ -382,10 +382,9 @@ def __init__(self, config): super().__init__() self.n_shared_experts = config.n_shared_experts intermediate_dim = config.moe_intermediate_size - # TP loader cuts shards on the raw tensor but validates shapes on the target, so a Transpose - # conversion op breaks sharded loads. The runtime transpose(1, 2) is not a per-forward - # cost: it is a stride-metadata view, so the same - # matmul layout every nn.Linear runs + # TP loader cuts shards on the raw tensor but validates shapes on the target, so a Transpose conversion op breaks sharded + # loads. The runtime transpose(1, 2) is not a per-forward cost: it is a stride-metadata view, so the same matmul layout + # every nn.Linear runs self.gate_proj = nn.Parameter(torch.empty(config.n_shared_experts, intermediate_dim, config.hidden_size)) self.up_proj = nn.Parameter(torch.empty(config.n_shared_experts, intermediate_dim, config.hidden_size)) self.down_proj = nn.Parameter(torch.empty(config.n_shared_experts, config.hidden_size, intermediate_dim)) @@ -679,7 +678,9 @@ def forward( raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if inputs_embeds is None: - inputs_embeds = self.embed_norm(self.embed_tokens(input_ids)) + inputs_embeds = self.embed_tokens(input_ids) + # The norm needs to be outside the `if` in case `input_embeds` are given explicitly + inputs_embeds = self.embed_norm(inputs_embeds) if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config) @@ -1057,8 +1058,8 @@ def get_placeholder_mask( that the placeholder token count matches the length of `features`. If the lengths differ, an error is raised. """ if input_ids is None: - special_mask = inputs_embeds == self.get_input_embeddings()( - torch.tensor(token_id, dtype=torch.long, device=inputs_embeds.device) + special_mask = inputs_embeds == self.language_model.embed_norm( + self.get_input_embeddings()(torch.tensor(token_id, dtype=torch.long, device=inputs_embeds.device)) ) special_mask = special_mask.all(-1) else: @@ -1126,7 +1127,9 @@ def forward( raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if inputs_embeds is None: - inputs_embeds = self.language_model.embed_norm(self.get_input_embeddings()(input_ids)) + inputs_embeds = self.get_input_embeddings()(input_ids) + # The norm need to be outside the `if` in case `input_embeds` are given explicitly + inputs_embeds = self.language_model.embed_norm(inputs_embeds) # Merge text and images if pixel_values is not None: diff --git a/src/transformers/models/inkling/modular_inkling.py b/src/transformers/models/inkling/modular_inkling.py index 89276fa3128c..8e563ce92b61 100644 --- a/src/transformers/models/inkling/modular_inkling.py +++ b/src/transformers/models/inkling/modular_inkling.py @@ -530,7 +530,7 @@ def __init__(self, config): self.weight = nn.Parameter(torch.empty(self.n_total_experts, config.hidden_size)) self.global_scale = nn.Parameter(torch.ones(1)) - self.e_score_correction_bias = nn.Parameter(torch.empty(self.num_experts)) + self.e_score_correction_bias = nn.Buffer(torch.zeros(self.num_experts)) def forward(self, hidden_states) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: flat = hidden_states.reshape(-1, self.hidden_dim) @@ -561,10 +561,9 @@ def __init__(self, config): super().__init__() self.n_shared_experts = config.n_shared_experts intermediate_dim = config.moe_intermediate_size - # TP loader cuts shards on the raw tensor but validates shapes on the target, so a Transpose - # conversion op breaks sharded loads. The runtime transpose(1, 2) is not a per-forward - # cost: it is a stride-metadata view, so the same - # matmul layout every nn.Linear runs + # TP loader cuts shards on the raw tensor but validates shapes on the target, so a Transpose conversion op breaks sharded + # loads. The runtime transpose(1, 2) is not a per-forward cost: it is a stride-metadata view, so the same matmul layout + # every nn.Linear runs self.gate_proj = nn.Parameter(torch.empty(config.n_shared_experts, intermediate_dim, config.hidden_size)) self.up_proj = nn.Parameter(torch.empty(config.n_shared_experts, intermediate_dim, config.hidden_size)) self.down_proj = nn.Parameter(torch.empty(config.n_shared_experts, config.hidden_size, intermediate_dim)) @@ -803,7 +802,9 @@ def forward( raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if inputs_embeds is None: - inputs_embeds = self.embed_norm(self.embed_tokens(input_ids)) + inputs_embeds = self.embed_tokens(input_ids) + # The norm needs to be outside the `if` in case `input_embeds` are given explicitly + inputs_embeds = self.embed_norm(inputs_embeds) if use_cache and past_key_values is None: past_key_values = DynamicCache(config=self.config) @@ -1158,8 +1159,8 @@ def get_placeholder_mask( that the placeholder token count matches the length of `features`. If the lengths differ, an error is raised. """ if input_ids is None: - special_mask = inputs_embeds == self.get_input_embeddings()( - torch.tensor(token_id, dtype=torch.long, device=inputs_embeds.device) + special_mask = inputs_embeds == self.language_model.embed_norm( + self.get_input_embeddings()(torch.tensor(token_id, dtype=torch.long, device=inputs_embeds.device)) ) special_mask = special_mask.all(-1) else: @@ -1227,7 +1228,9 @@ def forward( raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if inputs_embeds is None: - inputs_embeds = self.language_model.embed_norm(self.get_input_embeddings()(input_ids)) + inputs_embeds = self.get_input_embeddings()(input_ids) + # The norm need to be outside the `if` in case `input_embeds` are given explicitly + inputs_embeds = self.language_model.embed_norm(inputs_embeds) # Merge text and images if pixel_values is not None: diff --git a/tests/models/inkling/test_modeling_inkling.py b/tests/models/inkling/test_modeling_inkling.py index aa31e7bab673..43947d351023 100644 --- a/tests/models/inkling/test_modeling_inkling.py +++ b/tests/models/inkling/test_modeling_inkling.py @@ -35,7 +35,7 @@ torch_device, ) -from ...causal_lm_tester import CausalLMModelTester +from ...causal_lm_tester import CausalLMModelTest, CausalLMModelTester from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor @@ -45,6 +45,7 @@ import torch from transformers import ( + InklingForCausalLM, InklingForConditionalGeneration, InklingModel, InklingTextModel, @@ -60,7 +61,7 @@ class InklingTextModelTester(CausalLMModelTester): if is_torch_available(): config_class = InklingTextConfig base_model_class = InklingTextModel - causal_lm_class = InklingForConditionalGeneration + causal_lm_class = InklingForCausalLM def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -73,8 +74,18 @@ def __init__(self, *args, **kwargs): self.swa_head_dim = self.head_dim # To activate moe blocks - self.enable_moe_block = True self.moe_intermediate_size = 16 + self.n_routed_experts = 16 + + +class InklingTextModelTests(CausalLMModelTest, unittest.TestCase): + model_tester_class = InklingTextModelTester + _torch_compile_train_cls = InklingForCausalLM if is_torch_available() else None + model_split_percents = [0.5, 0.8, 0.9] + + @unittest.skip("MoE routing on a tiny randomly-initialized model makes the overfit target unstable.") + def test_training_overfit(self): + pass class InklingAudio2TextModelTester: From e530c283bedb72abde10c937dcb1e38fcf862e24 Mon Sep 17 00:00:00 2001 From: Cyril Vallez Date: Thu, 3 Sep 2026 12:25:02 +0900 Subject: [PATCH 037/996] Update dev version (#48498) update --- setup.py | 2 +- src/transformers/__init__.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index fc24319b2b1e..76a1044e4506 100644 --- a/setup.py +++ b/setup.py @@ -326,7 +326,7 @@ def run(self): setup( name="transformers", - version="5.16.0.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots) + version="5.17.0.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots) author="The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)", author_email="transformers@huggingface.co", description="Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.", diff --git a/src/transformers/__init__.py b/src/transformers/__init__.py index 8990a72ff1c5..7751bdfceb53 100755 --- a/src/transformers/__init__.py +++ b/src/transformers/__init__.py @@ -18,7 +18,7 @@ # to defer the actual importing for when the objects are requested. This way `import transformers` provides the names # in the namespace without actually importing anything (and especially none of the backends). -__version__ = "5.16.0.dev0" +__version__ = "5.17.0.dev0" import importlib import sys From 23fbf2bb29aadbe837742103eed8b9ef821464c3 Mon Sep 17 00:00:00 2001 From: Cyril Vallez Date: Thu, 3 Sep 2026 12:45:07 +0900 Subject: [PATCH 038/996] Fix pre patch release utility (#48499) fix --- utils/release.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/utils/release.py b/utils/release.py index 0b2e83f46c91..2637b26b1550 100644 --- a/utils/release.py +++ b/utils/release.py @@ -188,9 +188,11 @@ def pre_release_work(patch: bool = False): print(f"Updating version to {version}.") global_version_update(version, patch=patch) - print("Deleting conversion and internal utils scripts.") - remove_conversion_scripts() - remove_internal_utils() + # If releasing a patch, all those files were already deleted on the branch when releasing the main version + if not patch: + print("Deleting conversion and internal utils scripts.") + remove_conversion_scripts() + remove_internal_utils() def post_release_work(): From c66311b576839fa9e241c0ab3fabf2ca13350b05 Mon Sep 17 00:00:00 2001 From: Yuvraj Singh Date: Thu, 3 Sep 2026 10:51:18 +0530 Subject: [PATCH 039/996] Fix Pix2StructTextAttention init using hidden_size instead of d_kv (#47558) --- src/transformers/models/pix2struct/modeling_pix2struct.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/transformers/models/pix2struct/modeling_pix2struct.py b/src/transformers/models/pix2struct/modeling_pix2struct.py index 6ea35aaf9a8e..1f8840d1f255 100644 --- a/src/transformers/models/pix2struct/modeling_pix2struct.py +++ b/src/transformers/models/pix2struct/modeling_pix2struct.py @@ -328,7 +328,7 @@ def _init_weights(self, module): else self.config.hidden_size ) key_value_proj_dim = ( - self.config.text_config.d_kv if isinstance(self.config, Pix2StructConfig) else self.config.hidden_size + self.config.text_config.d_kv if isinstance(self.config, Pix2StructConfig) else self.config.d_kv ) n_heads = ( self.config.text_config.num_heads From 2f70c41b05fb08c0aa75f0b2fa4364a23b526b36 Mon Sep 17 00:00:00 2001 From: bin xu <140522237+shenhuaqingshi@users.noreply.github.com> Date: Thu, 3 Sep 2026 13:35:54 +0800 Subject: [PATCH 040/996] [AfMoE] Standardize past_key_values argument naming across forward and generate (#48430) [AfMoE] Standardize past_key_values argument naming across forward and generate (#48310) --- src/transformers/models/afmoe/modeling_afmoe.py | 12 ++++++------ src/transformers/models/afmoe/modular_afmoe.py | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/transformers/models/afmoe/modeling_afmoe.py b/src/transformers/models/afmoe/modeling_afmoe.py index bf79f260355b..347a9b266d4b 100644 --- a/src/transformers/models/afmoe/modeling_afmoe.py +++ b/src/transformers/models/afmoe/modeling_afmoe.py @@ -352,7 +352,7 @@ def forward( hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: torch.Tensor | None, - past_key_value: Cache | None = None, + past_key_values: Cache | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor, torch.Tensor]: input_shape = hidden_states.shape[:-1] @@ -371,8 +371,8 @@ def forward( cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) - if past_key_value is not None: - key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx) + if past_key_values is not None: + key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, eager_attention_forward @@ -431,7 +431,7 @@ def forward( hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, - past_key_value: Cache | None = None, + past_key_values: Cache | None = None, use_cache: bool | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs: Unpack[TransformersKwargs], @@ -444,7 +444,7 @@ def forward( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, - past_key_value=past_key_value, + past_key_values=past_key_values, use_cache=use_cache, position_embeddings=position_embeddings, **kwargs, @@ -584,7 +584,7 @@ def forward( hidden_states, attention_mask=causal_mask_mapping[self.config.layer_types[i]], position_ids=position_ids, - past_key_value=past_key_values, + past_key_values=past_key_values, use_cache=use_cache, position_embeddings=position_embeddings, **kwargs, diff --git a/src/transformers/models/afmoe/modular_afmoe.py b/src/transformers/models/afmoe/modular_afmoe.py index c97e10ff758e..98739580cec0 100644 --- a/src/transformers/models/afmoe/modular_afmoe.py +++ b/src/transformers/models/afmoe/modular_afmoe.py @@ -146,7 +146,7 @@ def forward( hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: torch.Tensor | None, - past_key_value: Cache | None = None, + past_key_values: Cache | None = None, **kwargs: Unpack[TransformersKwargs], ) -> tuple[torch.Tensor, torch.Tensor]: input_shape = hidden_states.shape[:-1] @@ -165,8 +165,8 @@ def forward( cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) - if past_key_value is not None: - key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx) + if past_key_values is not None: + key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( self.config._attn_implementation, eager_attention_forward @@ -225,7 +225,7 @@ def forward( hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, - past_key_value: Cache | None = None, + past_key_values: Cache | None = None, use_cache: bool | None = None, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs: Unpack[TransformersKwargs], @@ -238,7 +238,7 @@ def forward( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, - past_key_value=past_key_value, + past_key_values=past_key_values, use_cache=use_cache, position_embeddings=position_embeddings, **kwargs, @@ -378,7 +378,7 @@ def forward( hidden_states, attention_mask=causal_mask_mapping[self.config.layer_types[i]], position_ids=position_ids, - past_key_value=past_key_values, + past_key_values=past_key_values, use_cache=use_cache, position_embeddings=position_embeddings, **kwargs, From a8d5f2c845471633cf744c86be66bf888b8d6a37 Mon Sep 17 00:00:00 2001 From: Cyril Vallez Date: Thu, 3 Sep 2026 14:51:46 +0900 Subject: [PATCH 041/996] Remove deprecation (#48500) remove deprec --- src/transformers/modeling_layers.py | 6 ------ tests/models/inkling/test_modeling_inkling.py | 16 +++------------- 2 files changed, 3 insertions(+), 19 deletions(-) diff --git a/src/transformers/modeling_layers.py b/src/transformers/modeling_layers.py index 485b66a584d4..4dc31ce058c9 100644 --- a/src/transformers/modeling_layers.py +++ b/src/transformers/modeling_layers.py @@ -90,12 +90,6 @@ def __call__(self, *args, **kwargs): if not self._can_checkpoint_with_cache: # different names for the same thing in different layers - # TODO cyril: this one without `S` can be removed after deprecation cycle - if "past_key_value" in kwargs and kwargs["past_key_value"] is not None: - kwargs["past_key_value"] = None - message += " `past_key_value=None`," - do_warn = True - if "past_key_values" in kwargs and kwargs["past_key_values"] is not None: kwargs["past_key_values"] = None message += " `past_key_values=None`," diff --git a/tests/models/inkling/test_modeling_inkling.py b/tests/models/inkling/test_modeling_inkling.py index 43947d351023..3d5492f14a02 100644 --- a/tests/models/inkling/test_modeling_inkling.py +++ b/tests/models/inkling/test_modeling_inkling.py @@ -44,17 +44,7 @@ if is_torch_available(): import torch - from transformers import ( - InklingForCausalLM, - InklingForConditionalGeneration, - InklingModel, - InklingTextModel, - ) - - -GEMMA4_RANDOM_MOE_FA2_SKIP_REASON = ( - "Randomly initialized Inkling MoE routers are too sensitive to tiny eager/FA2 input differences" -) + from transformers import InklingForCausalLM, InklingForConditionalGeneration, InklingModel, InklingTextModel class InklingTextModelTester(CausalLMModelTester): @@ -253,11 +243,11 @@ def test_disk_offload_bin(self): def test_disk_offload_safetensors(self): pass - @unittest.skip(GEMMA4_RANDOM_MOE_FA2_SKIP_REASON) + @unittest.skip("Randomly initialized Inkling MoE routers are too sensitive to tiny eager/FA2 input differences") def test_flash_attn_2_inference_equivalence(self): pass - @unittest.skip(GEMMA4_RANDOM_MOE_FA2_SKIP_REASON) + @unittest.skip("Randomly initialized Inkling MoE routers are too sensitive to tiny eager/FA2 input differences") def test_flash_attn_2_inference_equivalence_right_padding(self): pass From ea8f1f7461ff97fd00e163b0635d0db8ea79d8f1 Mon Sep 17 00:00:00 2001 From: Cyril Vallez Date: Thu, 3 Sep 2026 20:04:56 +0900 Subject: [PATCH 042/996] Fix some tests by removing the deprecation cycle (#48503) * remove * style --- .../integrations/finegrained_fp8.py | 5 ----- tests/kernels/test_deepgemm.py | 15 ------------- tests/kernels/test_finegrained_fp8.py | 21 ------------------- 3 files changed, 41 deletions(-) diff --git a/src/transformers/integrations/finegrained_fp8.py b/src/transformers/integrations/finegrained_fp8.py index 342abd9c35af..412fa42630e0 100644 --- a/src/transformers/integrations/finegrained_fp8.py +++ b/src/transformers/integrations/finegrained_fp8.py @@ -26,7 +26,6 @@ from ..core_model_loading import ConversionOps from ..quantizers.quantizers_utils import get_module_from_name, should_convert_module from ..utils import logging -from ..utils.deprecation import deprecate_kwarg from ..utils.import_utils import is_kernels_available from .deepgemm import ( deepgemm_fp8_fp4_experts_forward, @@ -177,7 +176,6 @@ def _alloc_expert_proj( return weight, sf -@deprecate_kwarg("output_dtype", version="v5.16") def finegrained_fp8_linear( input: torch.Tensor, weight: torch.Tensor, @@ -185,7 +183,6 @@ def finegrained_fp8_linear( block_size: list[int] | None = None, bias: torch.Tensor | None = None, activation_scale: torch.Tensor | None = None, - output_dtype: torch.dtype | None = None, ) -> torch.Tensor: """Triton FP8/FP4 linear: fused act-quant + matmul, then optional bias add. @@ -208,7 +205,6 @@ def finegrained_fp8_linear( return output -@deprecate_kwarg("output_dtype", version="v5.16") def fp8_linear( input: torch.Tensor, weight: torch.Tensor, @@ -216,7 +212,6 @@ def fp8_linear( block_size: list[int] | None = None, bias: torch.Tensor | None = None, activation_scale: torch.Tensor | None = None, - output_dtype: torch.dtype | None = None, allow_deepgemm: bool = True, ) -> torch.Tensor: """End-to-end FP8/FP4 linear used by `FP8Linear` and the eager `FP8Experts` loop. diff --git a/tests/kernels/test_deepgemm.py b/tests/kernels/test_deepgemm.py index 28ff68538916..3542cd4c20c7 100644 --- a/tests/kernels/test_deepgemm.py +++ b/tests/kernels/test_deepgemm.py @@ -453,21 +453,6 @@ def test_linear_rejects_float32_scales_on_sm100(self): deepgemm_fp8_fp4_linear(input, weight, weight_scale, block_size=(128, 128)) self.assertEqual(captured, {}) # raised before the kernel ran - def test_linear_adds_bias_and_ignores_deprecated_output_dtype(self): - input = torch.randn(4, 128, dtype=torch.bfloat16, device=torch_device) - weight = torch.randn(16, 128, device=torch_device).to(torch.float8_e4m3fn) - weight_scale = torch.ones(1, 1, dtype=torch.float32, device=torch_device) - bias = torch.randn(16, dtype=torch.bfloat16, device=torch_device) - with self._bundle(is_sm100=False): - with self.assertWarnsRegex(FutureWarning, "output_dtype"): - out = deepgemm_fp8_fp4_linear( - input, weight, weight_scale, bias=bias, block_size=(128, 128), output_dtype=torch.float32 - ) - # output_dtype is deprecated and ignored: output follows input.dtype, not the requested float32. - self.assertEqual(out.dtype, torch.bfloat16) - # The fake matmul zeros the output buffer, so the result is exactly the broadcast bias. - self.assertTrue(torch.equal(out, bias.expand(4, 16))) - # ── deepgemm_bf16_experts_forward ────────────────────────────────────────── def _bf16_hidden(self, experts, *, num_tokens=3, top_k=2): diff --git a/tests/kernels/test_finegrained_fp8.py b/tests/kernels/test_finegrained_fp8.py index 8cab88ad78c6..c2e59a29731e 100644 --- a/tests/kernels/test_finegrained_fp8.py +++ b/tests/kernels/test_finegrained_fp8.py @@ -209,27 +209,6 @@ def test_linear_marshals_args_and_defaults_output_dtype(self): self.assertIsNone(call["activation_scale"]) self.assertEqual(out.dtype, torch.bfloat16) - def test_linear_forwards_activation_scale_and_ignores_deprecated_output_dtype(self): - input = torch.randn(3, 8, dtype=torch.bfloat16, device=torch_device) - weight = torch.randn(16, 8, device=torch_device).to(torch.float8_e4m3fn) - weight_scale_inv = torch.randn(1, 1, dtype=torch.float32, device=torch_device) - activation_scale = torch.tensor(2.0, device=torch_device) - with self._mocked_kernel() as calls: - with self.assertWarnsRegex(FutureWarning, "output_dtype"): - out = finegrained_fp8_linear( - input, - weight, - weight_scale_inv, - block_size=None, - activation_scale=activation_scale, - output_dtype=torch.float32, # deprecated + ignored - ) - call = calls["matmul"][0] - self.assertIs(call["activation_scale"], activation_scale) - # output_dtype is deprecated and ignored: the kernel receives input.dtype, not the requested float32. - self.assertEqual(call["output_dtype"], torch.bfloat16) - self.assertEqual(out.dtype, torch.bfloat16) - def test_linear_adds_bias_in_place(self): input = torch.randn(3, 8, dtype=torch.bfloat16, device=torch_device) weight = torch.randn(16, 8, device=torch_device).to(torch.float8_e4m3fn) From 8ce59c1348cefb3df5c1315541a0773168e9ca44 Mon Sep 17 00:00:00 2001 From: "sergereview[bot]" <283583894+sergereview[bot]@users.noreply.github.com> Date: Thu, 3 Sep 2026 11:15:42 +0000 Subject: [PATCH 043/996] [serge] Fix 2 integration tests for model `fsmt` failing with `output_mismatch` (tensor values differ (2)) (#48496) * [serge] Fix 2 integration tests for model `fsmt` failing with `output_mismatch` (tensor values differ (2)) * use get_model across tests --------- Co-authored-by: serge[bot] Co-authored-by: Tarek Ziade --- tests/models/fsmt/test_modeling_fsmt.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/tests/models/fsmt/test_modeling_fsmt.py b/tests/models/fsmt/test_modeling_fsmt.py index 5470c56bd90d..6f139acc3b23 100644 --- a/tests/models/fsmt/test_modeling_fsmt.py +++ b/tests/models/fsmt/test_modeling_fsmt.py @@ -447,26 +447,25 @@ def get_tokenizer(self, mname): self.tokenizers_cache[mname] = FSMTTokenizer.from_pretrained(mname) return self.tokenizers_cache[mname] - def get_model(self, mname): - if mname not in self.models_cache: + def get_model(self, mname, model_class=FSMTForConditionalGeneration, half=True): + key = (mname, model_class, half) + if key not in self.models_cache: # The safetensors checkpoint on `facebook/wmt19-de-en` (and other repositories) has issues. # Hub PRs are opened, see https://huggingface.co/facebook/wmt19-de-en/discussions/6 # We have asked Meta to merge them but no response yet: # https://huggingface.slack.com/archives/C01NE71C4F7/p1749565278015529?thread_ts=1749031628.757929&cid=C01NE71C4F7 - # Below is what produced the Hub PRs that work (loading without safetensors, saving the reloading) - model = FSMTForConditionalGeneration.from_pretrained(mname, use_safetensors=False) - with tempfile.TemporaryDirectory() as tmpdir: - model.save_pretrained(tmpdir) - self.models_cache[mname] = FSMTForConditionalGeneration.from_pretrained(tmpdir).to(torch_device) - - if torch_device == "cuda": - self.models_cache[mname].half() - return self.models_cache[mname] + # Until they are merged, load the (correct) PyTorch weights instead. + model = model_class.from_pretrained(mname, use_safetensors=False).to(torch_device) + if half and torch_device == "cuda": + model.half() + self.models_cache[key] = model + return self.models_cache[key] @slow def test_inference_no_head(self): tokenizer = self.default_tokenizer - model = FSMTModel.from_pretrained(self.default_mname).to(torch_device) + # `half=False`: the expected slice below is fp32, the default fp16 on GPU is far outside TOLERANCE + model = self.get_model(self.default_mname, model_class=FSMTModel, half=False) src_text = "My friend computer will translate this for me" input_ids = tokenizer([src_text], return_tensors="pt")["input_ids"] From cfa309cfa34b5497a32fd50af49aa97aac94c054 Mon Sep 17 00:00:00 2001 From: Raushan Turganbay Date: Thu, 3 Sep 2026 12:35:34 +0000 Subject: [PATCH 044/996] Infinite loop in dependency search (#48393) * better error msg * add back comment --------- Co-authored-by: Cyril Vallez --- utils/create_dependency_mapping.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/utils/create_dependency_mapping.py b/utils/create_dependency_mapping.py index c67499fb4704..cccbaefa4f30 100644 --- a/utils/create_dependency_mapping.py +++ b/utils/create_dependency_mapping.py @@ -35,6 +35,11 @@ def topological_sort(dependencies: dict) -> list[list[str]]: while len(graph) > 0: # Find the nodes with 0 out-degree leaf_nodes = {node for node in graph if len(graph[node]) == 0} + # No node is free of dependencies, but graph isn't empty so it's necessarily a cyclic inter-dependency among the remaining nodes + if not leaf_nodes: + remaining = list(graph.keys()) + raise ValueError(f"Cyclic dependency detected among nodes: {remaining}") + # Add them to the list as next level sorting_list.append([name_mapping[node] for node in leaf_nodes]) # Remove the leaves from the graph (and from the deps of other nodes) From 92732e3752f41bc3d50eb4067e67c9445ae8ffef Mon Sep 17 00:00:00 2001 From: Anton Vlasjuk <73884904+vasqu@users.noreply.github.com> Date: Thu, 3 Sep 2026 17:31:02 +0200 Subject: [PATCH 045/996] [`Qwen 3.5 Moe`] Fix decorators (#48436) * fix * this way --- .../models/qwen3_5_moe/modeling_qwen3_5_moe.py | 4 ++++ .../models/qwen3_5_moe/modular_qwen3_5_moe.py | 10 ++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py b/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py index e538a653f210..7c5dd26beddc 100644 --- a/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py +++ b/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py @@ -35,6 +35,7 @@ use_experts_implementation, use_kernel_forward_from_hub, use_kernel_func_from_hub_with_fallback, + use_kernelized_func, ) from ...integrations.accelerate import force_accelerate_hooks from ...masking_utils import create_causal_mask, create_recurrent_attention_mask @@ -455,6 +456,9 @@ def torch_recurrent_gated_delta_rule( @use_kernel_forward_from_hub("Qwen3_5GatedDeltaNet") +@use_kernelized_func( + [torch_recurrent_gated_delta_rule, torch_chunk_gated_delta_rule, causal_conv1d_fn, causal_conv1d_update] +) class Qwen3_5MoeGatedDeltaNet(nn.Module): def __init__(self, config: Qwen3_5MoeConfig, layer_idx: int): super().__init__() diff --git a/src/transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py b/src/transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py index c9155ee22f05..a48c779802c5 100644 --- a/src/transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py +++ b/src/transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py @@ -17,7 +17,7 @@ from huggingface_hub.dataclasses import strict from ... import initialization as init -from ...integrations import use_kernel_forward_from_hub +from ...integrations import use_kernel_forward_from_hub, use_kernelized_func from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutputWithPooling from ...modeling_utils import PreTrainedModel @@ -31,6 +31,10 @@ Qwen3_5TextRotaryEmbedding, Qwen3_5VisionModel, Qwen3_5VisionRotaryEmbedding, + causal_conv1d_fn, + causal_conv1d_update, + torch_chunk_gated_delta_rule, + torch_recurrent_gated_delta_rule, ) from ..qwen3_next.configuration_qwen3_next import Qwen3NextConfig from ..qwen3_next.modeling_qwen3_next import ( @@ -161,8 +165,10 @@ class Qwen3_5MoeTextRotaryEmbedding(Qwen3_5TextRotaryEmbedding): pass -# Same GDN core as the dense variant, so it reuses the dense Hub kernel name. @use_kernel_forward_from_hub("Qwen3_5GatedDeltaNet") +@use_kernelized_func( + [torch_recurrent_gated_delta_rule, torch_chunk_gated_delta_rule, causal_conv1d_fn, causal_conv1d_update] +) class Qwen3_5MoeGatedDeltaNet(Qwen3_5GatedDeltaNet): pass From 904b5551c38a3c2c51d315a563ef26870b6ed0aa Mon Sep 17 00:00:00 2001 From: kaixuanliu Date: Thu, 3 Sep 2026 15:58:22 +0000 Subject: [PATCH 046/996] add xpu expectations for hunyuan_vl model tests (#48504) Signed-off-by: kaixuanliu --- .../hunyuan_vl/test_modeling_hunyuan_vl.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/models/hunyuan_vl/test_modeling_hunyuan_vl.py b/tests/models/hunyuan_vl/test_modeling_hunyuan_vl.py index a7b2f125b925..abe324bc39cb 100644 --- a/tests/models/hunyuan_vl/test_modeling_hunyuan_vl.py +++ b/tests/models/hunyuan_vl/test_modeling_hunyuan_vl.py @@ -446,6 +446,7 @@ def test_small_model_integration_test(self): expected_texts = Expectations( { ("cuda", None): "The image is a radar chart that compares the performance of four different models or methods across various benchmarks. The chart is labeled with the names of the benchmarks on the axes, and each model is represented by a different colored line. The models are labeled as BLIP-2, InstructBLIP, Qwen-VL", + ("xpu", 5): "To determine what is shown in the image, we analyze the visual elements: \n\n1. **Chart Type**: A radar chart (also called a spider chart) is used to compare multiple datasets. \n2. **Axes and Data**: The chart has 12 axes, each representing a dataset: *VQ", } ) # fmt: skip decoded_text = self._generate_trimmed_text(model, inputs, max_new_tokens=self.max_new_tokens)[0] @@ -465,6 +466,10 @@ def test_small_model_integration_test_batch(self): ("cuda", None): [ "The image is a radar chart that compares the performance of four different models or methods across various benchmarks. The chart is labeled with the names of the benchmarks on the axes, and each model is represented by a different colored line. The models are labeled as BLIP-2, InstructBLIP, Qwen-VL", "To determine the animal on the candy, observe the image: there are two candies—one teal and one orange. The teal candy has a black silhouette of a bird (a type of bird in the family **passerina**). The orange candy also has a black silhouette of a bird, but", + ], + ("xpu", 5): [ + "To determine what is shown in the image, we analyze the context of the radar chart. A radar chart is a graphical representation of multivariate data, where each axis represents a different variable (here, different models or tasks). \n\nIn the image, the axes are labeled with model names (e.g., VQAv", + "To determine the animal on the candy, observe the image: there are two green candies with black designs. The animal in the green candies is a **turtle** (a type of reptile with a shell and a tail).", ] } ) # fmt: skip @@ -479,6 +484,7 @@ def test_small_model_integration_test_multi_image(self): expected_texts = Expectations( { ("cuda", None): "To determine the answer, we analyze the radar chart: \n\n1. **First image**: The first image shows a hand with multiple colored candy beads. The top - most bead is teal, and the second bead from the top is green. The third bead from the top is orange. The fourth bead from the", + ("xpu", 5): "To determine the answers, let’s analyze the radar chart: \n\n1. **First Image**: The first image shows a radar chart with multiple colored candy beads. The first candy bead is a **green** one. The animal on this green bead is a **turtle** (a small aquatic creature with a", } ) # fmt: skip decoded_text = self._generate_trimmed_text(model, inputs, max_new_tokens=self.max_new_tokens)[0] @@ -500,6 +506,11 @@ def test_small_model_integration_test_multi_image_nested(self): "OCR (Optical Character Recognition) is a computer technology that uses **Optical Character Recognition (OCR)** to extract text from images or documents. It is a powerful tool for automating tasks like text extraction, image analysis, and document processing.\n\n### Brief Explanation:\n1. **Purpose**: OCR is used to recognize and extract", "To determine the answer, we analyze the radar chart: \n\n1. **First image**: The first image shows a hand with multiple colored candy beads. The top - most bead is teal, and the second bead from the top is green. The third bead from the top is orange. The fourth bead from the", "The image is a radar chart that compares the performance of four different models or methods across various benchmarks. The chart is labeled with the names of the benchmarks on the axes, and each model is represented by a different colored line. The models are labeled as BLIP-2, InstructBLIP, Qwen-VL", + ], + ("xpu", 5): [ + "It is a software tool that allows you to extract text from a document.", + "To determine what is shown in the first image and what animal is on the candy in the second image, we analyze the radar chart: \n\n1. **First Image**: The first radar chart has a green - colored region. The animal on this green region is a turtle. \n2. **Second Image**:", + "To determine what is shown in the image, we analyze the context of the radar chart. A radar chart is a graphical representation of multivariate data, where each axis represents a different variable (here, different models or tasks). \n\nIn the image, the axes are labeled with model names (e.g., VQAv", ] } ) # fmt: skip @@ -521,6 +532,10 @@ def test_small_model_integration_test_batch_different_resolutions(self): ("cuda", None): [ "STEALTH CAM 07:59 AM 09/01/15 69 F FRONT CBN", "To determine the animal on the candy, observe the image: there are two candies—one teal and one orange. The teal candy has a black silhouette of a bird (a type of bird in the family **passerina**). The orange candy also has a black silhouette of a bird, but", + ], + ("xpu", 5): [ + "STEALTH CAM\n07:59 AM 09/01/15 69 F \nFRONT CBN", + "To determine the animal on the candy, observe the image: there are two green candies with black designs. The animal in the green candies is a **turtle** (a type of reptile with a shell and a tail).", ] } ) # fmt: skip @@ -541,12 +556,17 @@ def test_small_model_integration_test_batch_matches_single(self): ("cuda", None): [ "STEALTH CAM 07:59 AM 09/01/15 69 F FRONT CBN", "To determine the animal on the candy, observe the image: there are two candies—one teal and one orange. The teal candy has a black silhouette of a bird (a type of bird in the family **passerina**). The orange candy also has a black silhouette of a bird, but", + ], + ("xpu", 5): [ + "STEALTH CAM\n07:59 AM 09/01/15 69 F \nFRONT CBN", + "To determine the animal on the candy, observe the image: there are two green candies with black designs. The animal in the green candies is a **turtle** (a type of reptile with a shell and a tail).", ] } ) # fmt: skip expected_texts_single = Expectations( { ("cuda", None): "STEALTH CAM 07:59 AM 09/01/15 69 F FRONT CBN", + ("xpu", 5): "STEALTH CAM\n07:59 AM 09/01/15 69 F \nFRONT CBN", } ) # fmt: skip From c119ec3cc37ab69642f39cca2de4187714002b08 Mon Sep 17 00:00:00 2001 From: DimensionSTP <65501090+DimensionSTP@users.noreply.github.com> Date: Fri, 4 Sep 2026 03:01:59 +0900 Subject: [PATCH 047/996] Support nested FLA kernel imports for fla-core (#48221) * fix: resolve nested optional kernel imports * test: clarify nested kernel fallback coverage --- src/transformers/integrations/hub_kernels.py | 9 +- tests/kernels/test_kernels.py | 105 +++++++++++++++++++ 2 files changed, 112 insertions(+), 2 deletions(-) diff --git a/src/transformers/integrations/hub_kernels.py b/src/transformers/integrations/hub_kernels.py index db53acb54073..c754ca051b02 100644 --- a/src/transformers/integrations/hub_kernels.py +++ b/src/transformers/integrations/hub_kernels.py @@ -838,13 +838,18 @@ def use_kernel_func_from_hub_with_fallback(func_name: str, package: str, interna # Allow internal path prefix if given to resolve non __init__ imports internal_path = _KERNELS_INTERNAL_PATH_MAPPINGS.get(func_name, internal_path) # defaults - full_path = func_name if internal_path is None else f"{internal_path}.{func_name}" + full_func_path = func_name if internal_path is None else f"{internal_path}.{func_name}" + full_module_path = package if internal_path is None else f"{package}.{internal_path}" def decorator(torch_function: Callable) -> Callable: implementation = None try: module = importlib.import_module(package) - implementation = resolve_internal_import(module, full_path) + implementation = resolve_internal_import(module, full_func_path) + # Some packages, such as FLA, do not expose nested modules from their package root. + if implementation is None and full_module_path != package: + module = importlib.import_module(full_module_path) + implementation = getattr(module, func_name, None) except Exception: implementation = torch_function finally: diff --git a/tests/kernels/test_kernels.py b/tests/kernels/test_kernels.py index bbe43d79e104..d19baef93852 100644 --- a/tests/kernels/test_kernels.py +++ b/tests/kernels/test_kernels.py @@ -24,6 +24,7 @@ import torch from huggingface_hub import snapshot_download +from parameterized import parameterized from transformers import AutoModelForCausalLM, AutoTokenizer, KernelConfig from transformers.integrations.hub_kernels import ( @@ -591,6 +592,110 @@ def forward(self, hidden_states, weight): exported = torch.export.export(Wrapper(), inputs) self.assertTrue(torch.equal(exported.module()(*inputs), torch_result)) + def test_fallback_resolves_function_from_package_root(self): + """The package-root implementation takes precedence over the nested-module fallback.""" + package = types.ModuleType("optional_backend") + optimized_function = MagicMock(return_value="optimized") + package.optimized_function = optimized_function + torch_function = MagicMock(return_value="torch") + + with ( + patch( + "transformers.integrations.hub_kernels.use_kernel_forward_from_hub", + return_value=lambda function: function, + ), + patch( + "transformers.integrations.hub_kernels.importlib.import_module", + return_value=package, + ) as import_module, + ): + wrapped = use_kernel_func_from_hub_with_fallback( + func_name="optimized_function", + package="optional_backend", + internal_path="ops.kernel", + )(torch_function) + + self.assertEqual(wrapped(), "optimized") + import_module.assert_called_once_with("optional_backend") + + @parameterized.expand( + [ + ( + "explicit_path", + "optimized_function", + "optional_backend", + "ops.kernel", + "optional_backend.ops.kernel", + ), + ( + "mapped_path", + "chunk_gated_delta_rule", + "fla", + None, + "fla.ops.gated_delta_rule", + ), + ] + ) + def test_fallback_imports_nested_module( + self, + case_name, + func_name, + package_name, + internal_path, + internal_module_name, + ): + """A nested implementation can be resolved from an explicit or registered module path.""" + package = types.ModuleType(package_name) + internal_module = types.ModuleType(internal_module_name) + optimized_function = MagicMock(return_value="optimized") + setattr(internal_module, func_name, optimized_function) + torch_function = MagicMock(return_value="torch") + + with ( + patch( + "transformers.integrations.hub_kernels.use_kernel_forward_from_hub", + return_value=lambda function: function, + ), + patch( + "transformers.integrations.hub_kernels.importlib.import_module", + side_effect=[package, internal_module], + ) as import_module, + ): + wrapped = use_kernel_func_from_hub_with_fallback( + func_name=func_name, + package=package_name, + internal_path=internal_path, + )(torch_function) + + self.assertEqual(wrapped(), "optimized") + self.assertEqual( + [call.args[0] for call in import_module.call_args_list], + [package_name, internal_module_name], + ) + + def test_fallback_uses_torch_when_nested_module_is_missing(self): + """The reference implementation remains available when the nested module cannot be imported.""" + package = types.ModuleType("optional_backend") + torch_function = MagicMock(return_value="torch") + + with ( + patch( + "transformers.integrations.hub_kernels.use_kernel_forward_from_hub", + return_value=lambda function: function, + ), + patch( + "transformers.integrations.hub_kernels.importlib.import_module", + side_effect=[package, ImportError], + ), + ): + wrapped = use_kernel_func_from_hub_with_fallback( + func_name="optimized_function", + package="optional_backend", + internal_path="ops.kernel", + )(torch_function) + + self.assertEqual(wrapped(), "torch") + @require_kernels class TestAttentionKernelRegistration(TestCasePlus): From c676202114bb929ba4377f90fc92c5a8fec72da6 Mon Sep 17 00:00:00 2001 From: jiqing-feng Date: Fri, 4 Sep 2026 08:19:57 +0000 Subject: [PATCH 048/996] Fix sliding-window mask `layer_idx` in Gemma3/Gemma4 `create_masks_for_vision_model` (#48482) * Fix sliding mask layer_idx in Gemma3/Gemma4 create_masks_for_vision_model `create_masks_for_vision_model` pads `block_sequence_ids` using the KV sizes of cache layer 0, but then calls `create_causal_mask` without `layer_idx`, which defaults to the first `full_attention` layer. On Gemma3/Gemma4 checkpoints layer 0 is a `sliding_attention` layer, so with a hybrid cache the two lengths differ: * DynamicCache: the sliding mask is built with the full layer's kv_length, so it no longer matches the sliding KV cache. * StaticCache: the full layer's kv_length is the padded `max_cache_len`, so `blockwise_overlay` indexes `block_sequence_ids` out of bounds. This raises an IndexError on CPU and triggers a device-side assert (crashing the process) on CUDA and XPU. Pin both the padding and the mask itself to the same `sliding_attention` layer. Also add a regression test covering a decode step with both a dynamic and a static hybrid cache. The existing `test_attention_mask_composition` only checks prefill with `past_key_values=None`, and the tester config places `full_attention` at layer 0, so neither exercised this path. * Cover the prefill path in the vision sliding mask regression test The crash actually happens on the first (prefill) forward: Gemma3's `prepare_inputs_for_generation` clears `token_type_ids` after the first step, so decode never reaches `create_masks_for_vision_model`. With an empty StaticCache the sliding layer reports `kv_length == q_len` while the full layer reports the padded `max_cache_len`, which is exactly the divergence that made `blockwise_overlay` read out of bounds. Rename the test accordingly and parameterize it over prefill/static, decode/static and decode/dynamic. * Cover the vision sliding mask regression on Gemma4 as well The Gemma4 checkpoints that reach create_masks_for_vision_model (use_bidirectional_attention="vision": the 31B and 26B-A4B variants) use layer_types starting with sliding_attention and sliding_window=1024, so they hit exactly the same layer_idx mismatch as Gemma3. Mirror the gemma3 test on Gemma4Vision2TextModelTest. Verified: 3 of the 4 parameterizations fail before the fix and all pass after. * Test the vision sliding mask regression through the model instead of the mask utility --- .../models/gemma3/modeling_gemma3.py | 10 ++++++- .../models/gemma3/modular_gemma3.py | 10 ++++++- .../models/gemma4/modeling_gemma4.py | 10 ++++++- .../models/gemma4/modular_gemma4.py | 10 ++++++- .../gemma4_unified/modeling_gemma4_unified.py | 10 ++++++- tests/models/gemma3/test_modeling_gemma3.py | 28 +++++++++++++++++++ tests/models/gemma4/test_modeling_gemma4.py | 25 +++++++++++++++++ 7 files changed, 98 insertions(+), 5 deletions(-) diff --git a/src/transformers/models/gemma3/modeling_gemma3.py b/src/transformers/models/gemma3/modeling_gemma3.py index e870ec1ad81a..f0fa3acb63b7 100644 --- a/src/transformers/models/gemma3/modeling_gemma3.py +++ b/src/transformers/models/gemma3/modeling_gemma3.py @@ -730,11 +730,18 @@ def create_masks_for_vision_model( # Full attention: OR(causal, blockwise) — use block_sequence_ids directly full_mask = create_causal_mask(**mask_kwargs, block_sequence_ids=block_sequence_ids) + # The sliding mask must be sized against a `sliding_attention` layer, but layer 0 may not be one + # and `create_causal_mask` defaults to the first `full_attention` layer, which has a different kv_length. + if getattr(past_key_values, "is_sliding", None) and True in past_key_values.is_sliding: + sliding_layer_idx = past_key_values.is_sliding.index(True) + else: + sliding_layer_idx = 0 + # We need to manually pad the sequence IDs for the sliding mask # as it's passed as an `or_mask_function` which bypasses internal padding. early_exit, _, _, _, kv_length, _, kv_offset = _preprocess_mask_arguments( **mask_kwargs, - layer_idx=0, + layer_idx=sliding_layer_idx, ) if early_exit: padded_block_sequence_ids = block_sequence_ids @@ -750,6 +757,7 @@ def create_masks_for_vision_model( **mask_kwargs, or_mask_function=blockwise_overlay(padded_block_sequence_ids), and_mask_function=sliding_window_overlay(config.sliding_window), + layer_idx=sliding_layer_idx, ) return { diff --git a/src/transformers/models/gemma3/modular_gemma3.py b/src/transformers/models/gemma3/modular_gemma3.py index 7ee7db711c27..b7ca600e17b4 100644 --- a/src/transformers/models/gemma3/modular_gemma3.py +++ b/src/transformers/models/gemma3/modular_gemma3.py @@ -639,11 +639,18 @@ def create_masks_for_vision_model( # Full attention: OR(causal, blockwise) — use block_sequence_ids directly full_mask = create_causal_mask(**mask_kwargs, block_sequence_ids=block_sequence_ids) + # The sliding mask must be sized against a `sliding_attention` layer, but layer 0 may not be one + # and `create_causal_mask` defaults to the first `full_attention` layer, which has a different kv_length. + if getattr(past_key_values, "is_sliding", None) and True in past_key_values.is_sliding: + sliding_layer_idx = past_key_values.is_sliding.index(True) + else: + sliding_layer_idx = 0 + # We need to manually pad the sequence IDs for the sliding mask # as it's passed as an `or_mask_function` which bypasses internal padding. early_exit, _, _, _, kv_length, _, kv_offset = _preprocess_mask_arguments( **mask_kwargs, - layer_idx=0, + layer_idx=sliding_layer_idx, ) if early_exit: padded_block_sequence_ids = block_sequence_ids @@ -659,6 +666,7 @@ def create_masks_for_vision_model( **mask_kwargs, or_mask_function=blockwise_overlay(padded_block_sequence_ids), and_mask_function=sliding_window_overlay(config.sliding_window), + layer_idx=sliding_layer_idx, ) return { diff --git a/src/transformers/models/gemma4/modeling_gemma4.py b/src/transformers/models/gemma4/modeling_gemma4.py index 79f626e86996..ab7e55acfb9e 100644 --- a/src/transformers/models/gemma4/modeling_gemma4.py +++ b/src/transformers/models/gemma4/modeling_gemma4.py @@ -2117,11 +2117,18 @@ def create_masks_for_vision_model( # Full attention: causal only — no bidirectional blockwise overlay. full_mask = create_causal_mask(**mask_kwargs) + # The sliding mask must be sized against a `sliding_attention` layer, but layer 0 may not be one + # and `create_causal_mask` defaults to the first `full_attention` layer, which has a different kv_length. + if getattr(past_key_values, "is_sliding", None) and True in past_key_values.is_sliding: + sliding_layer_idx = past_key_values.is_sliding.index(True) + else: + sliding_layer_idx = 0 + # We need to manually pad the sequence IDs for the sliding mask # as it's passed as an `or_mask_function` which bypasses internal padding. early_exit, _, _, _, kv_length, _, kv_offset = _preprocess_mask_arguments( **mask_kwargs, - layer_idx=0, + layer_idx=sliding_layer_idx, ) if early_exit: padded_block_sequence_ids = block_sequence_ids @@ -2137,6 +2144,7 @@ def create_masks_for_vision_model( **mask_kwargs, or_mask_function=blockwise_overlay(padded_block_sequence_ids), and_mask_function=sliding_window_overlay(config.sliding_window), + layer_idx=sliding_layer_idx, ) return { diff --git a/src/transformers/models/gemma4/modular_gemma4.py b/src/transformers/models/gemma4/modular_gemma4.py index 0c7e6df18d38..885b61625389 100644 --- a/src/transformers/models/gemma4/modular_gemma4.py +++ b/src/transformers/models/gemma4/modular_gemma4.py @@ -107,11 +107,18 @@ def create_masks_for_vision_model( # Full attention: causal only — no bidirectional blockwise overlay. full_mask = create_causal_mask(**mask_kwargs) + # The sliding mask must be sized against a `sliding_attention` layer, but layer 0 may not be one + # and `create_causal_mask` defaults to the first `full_attention` layer, which has a different kv_length. + if getattr(past_key_values, "is_sliding", None) and True in past_key_values.is_sliding: + sliding_layer_idx = past_key_values.is_sliding.index(True) + else: + sliding_layer_idx = 0 + # We need to manually pad the sequence IDs for the sliding mask # as it's passed as an `or_mask_function` which bypasses internal padding. early_exit, _, _, _, kv_length, _, kv_offset = _preprocess_mask_arguments( **mask_kwargs, - layer_idx=0, + layer_idx=sliding_layer_idx, ) if early_exit: padded_block_sequence_ids = block_sequence_ids @@ -127,6 +134,7 @@ def create_masks_for_vision_model( **mask_kwargs, or_mask_function=blockwise_overlay(padded_block_sequence_ids), and_mask_function=sliding_window_overlay(config.sliding_window), + layer_idx=sliding_layer_idx, ) return { diff --git a/src/transformers/models/gemma4_unified/modeling_gemma4_unified.py b/src/transformers/models/gemma4_unified/modeling_gemma4_unified.py index 9a897479a360..5ef121fcd4ca 100644 --- a/src/transformers/models/gemma4_unified/modeling_gemma4_unified.py +++ b/src/transformers/models/gemma4_unified/modeling_gemma4_unified.py @@ -1210,11 +1210,18 @@ def create_masks_for_vision_model( # Full attention: causal only — no bidirectional blockwise overlay. full_mask = create_causal_mask(**mask_kwargs) + # The sliding mask must be sized against a `sliding_attention` layer, but layer 0 may not be one + # and `create_causal_mask` defaults to the first `full_attention` layer, which has a different kv_length. + if getattr(past_key_values, "is_sliding", None) and True in past_key_values.is_sliding: + sliding_layer_idx = past_key_values.is_sliding.index(True) + else: + sliding_layer_idx = 0 + # We need to manually pad the sequence IDs for the sliding mask # as it's passed as an `or_mask_function` which bypasses internal padding. early_exit, _, _, _, kv_length, _, kv_offset = _preprocess_mask_arguments( **mask_kwargs, - layer_idx=0, + layer_idx=sliding_layer_idx, ) if early_exit: padded_block_sequence_ids = block_sequence_ids @@ -1230,6 +1237,7 @@ def create_masks_for_vision_model( **mask_kwargs, or_mask_function=blockwise_overlay(padded_block_sequence_ids), and_mask_function=sliding_window_overlay(config.sliding_window), + layer_idx=sliding_layer_idx, ) return { diff --git a/tests/models/gemma3/test_modeling_gemma3.py b/tests/models/gemma3/test_modeling_gemma3.py index e5be72867fe6..8b6b848d6fb1 100644 --- a/tests/models/gemma3/test_modeling_gemma3.py +++ b/tests/models/gemma3/test_modeling_gemma3.py @@ -62,6 +62,7 @@ Gemma3TextForSequenceClassification, Gemma3TextModel, ) + from transformers.cache_utils import StaticCache from transformers.models.gemma3.modeling_gemma3 import create_masks_for_vision_model from transformers.pytorch_utils import is_torch_greater_or_equal @@ -389,6 +390,33 @@ def test_attention_mask_composition(self): # Token 11 (image) looking ahead at Token 12 (text) -> MASKED self.assertLess(full_mask[0, 0, 11, 12].item(), -1000) + @parameterized.expand([(["sliding_attention", "full_attention"],), (["full_attention", "sliding_attention"],)]) + def test_vision_mask_with_cache_beyond_sliding_window(self, layer_types: list[str]): + """Regression test for a crash observed on real vision checkpoints such as ShieldGemma-2. + + Once the cache is longer than the sliding window, sliding and full attention layers report + different `kv_length`s. The vision mask has to be built for a sliding layer, otherwise the + sliding mask ends up sized against a full attention layer and the forward pass crashes. + """ + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.text_config._attn_implementation = "eager" + config.text_config.sliding_window = 4 + config.text_config.layer_types = layer_types + config.text_config.num_hidden_layers = len(layer_types) + + model = Gemma3ForConditionalGeneration(config).to(torch_device).eval() + batch_size, prompt_length = inputs_dict["input_ids"].shape + past_key_values = StaticCache( + config=config.get_text_config(), + max_batch_size=batch_size, + max_cache_len=prompt_length + 8, # longer than the sliding window + device=torch_device, + dtype=model.dtype, + ) + + with torch.no_grad(): + model(**inputs_dict, past_key_values=past_key_values, use_cache=True) + @slow @require_torch_accelerator diff --git a/tests/models/gemma4/test_modeling_gemma4.py b/tests/models/gemma4/test_modeling_gemma4.py index 6db3b45240b5..d5005d8d3060 100644 --- a/tests/models/gemma4/test_modeling_gemma4.py +++ b/tests/models/gemma4/test_modeling_gemma4.py @@ -58,6 +58,7 @@ Gemma4Processor, Gemma4TextModel, ) + from transformers.cache_utils import StaticCache from transformers.models.gemma4.modeling_gemma4 import create_masks_for_vision_model @@ -777,6 +778,30 @@ def test_attention_mask_composition(self): # Token 11 (image) looking ahead at Token 12 (text) -> MASKED self.assertLess(full_mask[0, 0, 11, 12].item(), -1000) + def test_vision_mask_with_cache_beyond_sliding_window(self): + """Regression test, see the Gemma 3 test of the same name. + + Once the cache is longer than the sliding window, sliding and full attention layers report + different `kv_length`s. The vision mask has to be built for a sliding layer, otherwise the + sliding mask ends up sized against a full attention layer and the forward pass crashes. + """ + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.text_config._attn_implementation = "eager" + config.text_config.sliding_window = 4 + + model = Gemma4ForConditionalGeneration(config).to(torch_device).eval() + batch_size, prompt_length = inputs_dict["input_ids"].shape + past_key_values = StaticCache( + config=config.get_text_config(), + max_batch_size=batch_size, + max_cache_len=prompt_length + 8, # longer than the sliding window + device=torch_device, + dtype=model.dtype, + ) + + with torch.no_grad(): + model(**inputs_dict, past_key_values=past_key_values, use_cache=True) + @slow @require_torch_accelerator From d3f494b047238a2b9d89e59c88e61d0a27f50849 Mon Sep 17 00:00:00 2001 From: Raushan Turganbay Date: Fri, 4 Sep 2026 09:10:47 +0000 Subject: [PATCH 049/996] Allow nested rope params for tiny models (#48435) . --- src/transformers/modeling_rope_utils.py | 4 ++-- tests/utils/test_modeling_rope_utils.py | 18 +++++++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/transformers/modeling_rope_utils.py b/src/transformers/modeling_rope_utils.py index 65ad358d4041..3312a7c5b8fb 100644 --- a/src/transformers/modeling_rope_utils.py +++ b/src/transformers/modeling_rope_utils.py @@ -781,7 +781,7 @@ def standardize_rope_params(self): logger.warning("`standardize_rope_params` was called but no RoPE parameters were found.") return # Case 1: RoPE param keys do not intersect with possible `layer_types` -> one global dict - elif layer_types is None or rope_parameters == {} or not set(rope_parameters.keys()).issubset(layer_types): + elif layer_types is None or rope_parameters == {} or set(rope_parameters.keys()).isdisjoint(layer_types): rope_parameters.setdefault("rope_type", rope_parameters.get("type", "default")) rope_parameters.setdefault("rope_theta", rope_theta) if partial_rotary_factor is not None: @@ -825,7 +825,7 @@ def validate_rope(self: "PreTrainedConfig"): if not rope_parameters_dict: return - if getattr(self, "layer_types", None) is not None and set(rope_parameters_dict.keys()).issubset( + if getattr(self, "layer_types", None) is not None and not set(rope_parameters_dict.keys()).isdisjoint( self.layer_types ): pass diff --git a/tests/utils/test_modeling_rope_utils.py b/tests/utils/test_modeling_rope_utils.py index 9f327da4f775..e65ceac4b6ad 100644 --- a/tests/utils/test_modeling_rope_utils.py +++ b/tests/utils/test_modeling_rope_utils.py @@ -20,7 +20,8 @@ from parameterized import parameterized from transformers import Gemma3TextConfig, LlamaConfig -from transformers.testing_utils import is_torch_available, require_torch, torch_device +from transformers.testing_utils import CaptureLogger, is_torch_available, require_torch, torch_device +from transformers.utils import logging as transformers_logging if is_torch_available(): @@ -78,6 +79,21 @@ def test_rope_validation(self, is_nested: bool, same_rope_per_layer: bool): ) config.validate_rope() + # If rope parameters are nested per layer type but only a single layer type is used, + # we don't raise a warning, As long as `cfg.rope_params.keys()` overlap with layer types + # we assume it is a nested RoPE and validate each sub-dict separately. See #48392 for more + if is_nested: + logger = transformers_logging.get_logger("transformers.modeling_rope_utils") + config = self.get_config_with_rope_parameters( + rope_params={"rope_type": "default", "rope_theta": 10000.0}, + is_nested=is_nested, + same_rope_per_layer=same_rope_per_layer, + ) + config.layer_types = ["full_attention"] + with CaptureLogger(logger) as cl: + config.validate_rope() + self.assertEqual("", cl.out) + # If we explicitly set the other (non-default) RoPE types with only rope_theta, # validation should fail because required keys are missing (e.g. factor, short_factor) for rope_type in all_rope_types: From 4177486a9f199bd7be520eff14431071d5d41ec5 Mon Sep 17 00:00:00 2001 From: Raushan Turganbay Date: Fri, 4 Sep 2026 09:44:37 +0000 Subject: [PATCH 050/996] :rotating_light: Vision (2d/3d) rotary embeddings (#48105) * delete * fix repo * . * add video processor docs * seems like this is expected * style * fix repo * i dont understand * ah this was not needed * add docstring back where needed * self reveiw * modular has no way to stop copying docstring... * comments * unpack kwargs * fix tests * oke, at least these are same, let's keep digging * . * second . * and like this * draft * maybe * commit before i break it * i think this is the last one from varity of ropes, now to update all models * vision-only rope qwen * run fix-repo * this will take soo long to fix every model * sooooo long * ! * one by one, hopefully i fix it all by eow * fix the rest * and left-out sam * fix repo most * and now fix repo for special omni models * a bit more of fix repo * new model was merged, ci wont run * suppress TRF, it comes from `main` * wording * . * gemma4, standardize 2D position IDs tmrw * fix repo * testers were working on pure luck, love it * fix repo * failing tests * a bit more * i suppose revert, why i changed it * fix style * lost type annotations * fix Sam copied incorrectly * qwen3 vl fix * move sam positions to buffer * modular convert * what? why CI never complained?! * forgot this * add the decorators where missing * ssome comments * more * axial rope type register separately * forgot * this is way too long * i am making bad decisions, revert * return dtype is fp32 in most models * ooops revert * bit more, rest comes tmrw * i broke smth and i dont know what * need to fix repo again * skip the test for vision rope for now, will add later more * example * Revert "i am making bad decisions, revert" This reverts commit 852a0c86fce3bb769a1ea77786bff09be187660d. * axial as type * fix repo * fix repo again * missing * gemma4 * fix * comments * new mrope with 2 sections only, no temporal! * fix repo --- src/transformers/modeling_rope_utils.py | 14 ++ src/transformers/modeling_utils.py | 12 +- .../configuration_cohere_compass.py | 3 + .../cohere_compass/modeling_cohere_compass.py | 157 ++++++++----- .../cohere_compass/modular_cohere_compass.py | 114 +++++++--- .../cosmos3_edge/modeling_cosmos3_edge.py | 19 -- .../models/dinov3_vit/modular_dinov3_vit.py | 20 +- .../configuration_edgetam_video.py | 28 ++- .../edgetam_video/modeling_edgetam_video.py | 134 +++++++---- .../edgetam_video/modular_edgetam_video.py | 81 ++++--- .../models/eomt_dinov3/modular_eomt_dinov3.py | 6 +- .../configuration_ernie4_5_vl_moe.py | 3 + .../modeling_ernie4_5_vl_moe.py | 90 ++++++-- .../modular_ernie4_5_vl_moe.py | 27 +-- .../exaone4_5/configuration_exaone4_5.py | 3 + .../models/exaone4_5/modeling_exaone4_5.py | 100 ++++++--- .../models/exaone4_5/modular_exaone4_5.py | 16 +- .../models/gemma4/configuration_gemma4.py | 7 +- .../models/gemma4/modeling_gemma4.py | 69 +++--- .../models/gemma4/modular_gemma4.py | 79 +++---- .../models/glm46v/modular_glm46v.py | 3 - .../models/glm4v/configuration_glm4v.py | 3 + .../models/glm4v/modeling_glm4v.py | 78 +++++-- .../models/glm4v/modular_glm4v.py | 23 +- .../glm4v_moe/configuration_glm4v_moe.py | 3 + .../models/glm4v_moe/modeling_glm4v_moe.py | 76 +++++-- .../models/glm4v_moe/modular_glm4v_moe.py | 7 - .../glm5_next/configuration_glm5_next.py | 3 + .../models/glm5_next/modeling_glm5_next.py | 90 ++++++-- .../models/glm5_next/modular_glm5_next.py | 3 - .../glm_image/configuration_glm_image.py | 2 + .../models/glm_image/modeling_glm_image.py | 4 +- .../models/glm_image/modular_glm_image.py | 4 +- .../models/glm_ocr/configuration_glm_ocr.py | 3 + .../models/glm_ocr/modeling_glm_ocr.py | 90 ++++++-- .../models/glm_ocr/modular_glm_ocr.py | 4 +- .../models/idefics/configuration_idefics.py | 2 + .../models/idefics/modeling_idefics.py | 110 +++++---- .../models/kimi_k25/configuration_kimi_k25.py | 4 +- .../models/kimi_k25/modeling_kimi_k25.py | 60 +++-- .../models/kimi_k25/modular_kimi_k25.py | 34 +-- .../models/llama4/modeling_llama4.py | 1 + .../configuration_minimax_m3_vl.py | 2 + .../minimax_m3_vl/modeling_minimax_m3_vl.py | 110 +++++---- .../minimax_m3_vl/modular_minimax_m3_vl.py | 73 ++---- .../models/mlcd/configuration_mlcd.py | 2 + src/transformers/models/mlcd/modeling_mlcd.py | 88 ++++++-- src/transformers/models/mlcd/modular_mlcd.py | 27 +-- .../configuration_muse_glimmer.py | 5 +- .../muse_glimmer/modeling_muse_glimmer.py | 50 +++-- .../muse_glimmer/modular_muse_glimmer.py | 29 +-- .../models/neomme/modeling_neomme.py | 32 ++- .../models/neomme/modular_neomme.py | 34 ++- .../configuration_paddleocr_vl.py | 2 + .../paddleocr_vl/modeling_paddleocr_vl.py | 132 ++++++----- .../paddleocr_vl/modular_paddleocr_vl.py | 18 +- .../models/pixtral/configuration_pixtral.py | 2 + .../models/pixtral/modeling_pixtral.py | 115 +++++----- .../modeling_pp_doclayout_v2.py | 2 +- .../modular_pp_doclayout_v2.py | 2 +- .../configuration_qwen2_5_omni.py | 3 + .../qwen2_5_omni/modeling_qwen2_5_omni.py | 210 ++++++++++-------- .../qwen2_5_omni/modular_qwen2_5_omni.py | 56 +++-- .../qwen2_5_vl/configuration_qwen2_5_vl.py | 3 + .../models/qwen2_5_vl/modeling_qwen2_5_vl.py | 152 ++++++++----- .../models/qwen2_5_vl/modular_qwen2_5_vl.py | 61 +++-- .../models/qwen2_vl/configuration_qwen2_vl.py | 3 + .../models/qwen2_vl/modeling_qwen2_vl.py | 139 +++++++----- .../models/qwen3_5/configuration_qwen3_5.py | 3 + .../models/qwen3_5/modeling_qwen3_5.py | 117 ++++++---- .../models/qwen3_5/modular_qwen3_5.py | 8 +- .../qwen3_5_moe/configuration_qwen3_5_moe.py | 3 + .../qwen3_5_moe/modeling_qwen3_5_moe.py | 117 ++++++---- .../models/qwen3_5_moe/modular_qwen3_5_moe.py | 3 - .../configuration_qwen3_omni_moe.py | 3 + .../qwen3_omni_moe/modeling_qwen3_omni_moe.py | 115 ++++++---- .../qwen3_omni_moe/modular_qwen3_omni_moe.py | 11 +- .../models/qwen3_vl/configuration_qwen3_vl.py | 3 + .../models/qwen3_vl/modeling_qwen3_vl.py | 121 ++++++---- .../models/qwen3_vl/modular_qwen3_vl.py | 82 ++----- .../configuration_qwen3_vl_moe.py | 3 + .../qwen3_vl_moe/modeling_qwen3_vl_moe.py | 117 ++++++---- .../qwen3_vl_moe/modular_qwen3_vl_moe.py | 3 - .../qwen4_exp/configuration_qwen4_exp.py | 3 + .../models/qwen4_exp/modeling_qwen4_exp.py | 117 ++++++---- .../models/qwen4_exp/modular_qwen4_exp.py | 3 - .../sam2_video/configuration_sam2_video.py | 27 ++- .../models/sam2_video/modeling_sam2_video.py | 117 +++++++--- .../models/sam2_video/modular_sam2_video.py | 107 +++++---- .../models/sam3/configuration_sam3.py | 8 +- src/transformers/models/sam3/modeling_sam3.py | 158 +++++++------ .../sam3_lite_text/modeling_sam3_lite_text.py | 1 - .../configuration_sam3_tracker_video.py | 28 ++- .../modeling_sam3_tracker_video.py | 112 +++++++--- .../modular_sam3_tracker_video.py | 31 ++- .../models/step3p7/configuration_step3p7.py | 1 + .../models/step3p7/modeling_step3p7.py | 47 ++-- .../models/step3p7/modular_step3p7.py | 17 +- .../configuration_video_llama_3.py | 2 + .../video_llama_3/modeling_video_llama_3.py | 83 +++++-- .../video_llama_3/modular_video_llama_3.py | 31 +-- .../test_modeling_cohere_compass.py | 6 +- .../test_modeling_cosmos3_omni.py | 4 +- .../test_modeling_ernie4_5_vl_moe.py | 4 +- tests/models/idefics/test_modeling_idefics.py | 5 + .../minicpmv4_6/test_modeling_minicpmv4_6.py | 5 +- tests/models/qwen3_5/test_modeling_qwen3_5.py | 18 +- .../qwen3_5_moe/test_modeling_qwen3_5_moe.py | 18 +- .../models/qwen3_vl/test_modeling_qwen3_vl.py | 62 +++++- .../test_modeling_qwen3_vl_moe.py | 6 +- .../qwen4_exp/test_modeling_qwen4_exp.py | 2 +- tests/multimodal_tester.py | 9 +- tests/test_modeling_common.py | 16 +- utils/create_dependency_mapping.py | 1 - 114 files changed, 2900 insertions(+), 1799 deletions(-) diff --git a/src/transformers/modeling_rope_utils.py b/src/transformers/modeling_rope_utils.py index 3312a7c5b8fb..513aea66bdc6 100644 --- a/src/transformers/modeling_rope_utils.py +++ b/src/transformers/modeling_rope_utils.py @@ -737,6 +737,7 @@ class RotaryEmbeddingConfigMixin: """ default_theta = 10_000.0 + default_rope_type = "default" # override only for axial models ignore_keys_at_rope_validation = set() def convert_rope_params_to_dict(self, **kwargs): @@ -787,6 +788,11 @@ def standardize_rope_params(self): if partial_rotary_factor is not None: rope_parameters["partial_rotary_factor"] = partial_rotary_factor + # Force set the default type to model's expected `default_rope`. For most models it's a no-op + # used only to keep BC with old ckpt that require axial rope type + if self.default_rope_type != "default" and rope_parameters["rope_type"] == "default": + rope_parameters["rope_type"] = self.default_rope_type + # Move pretraining-time maximum length to rope parameter dict for RoPE types with scaling if rope_parameters["rope_type"] in ["llama3", "yarn", "longrope"]: if hasattr(self, "original_max_position_embeddings"): @@ -813,6 +819,11 @@ def standardize_rope_params(self): "original_max_position_embeddings", self.max_position_embeddings ) + # Force set the default type to model's expected `default_rope`. For most models it's a no-op + # used only to keep BC with old ckpt that require axial rope type + if self.default_rope_type != "default" and rope_parameters[layer_type]["rope_type"] == "default": + rope_parameters[layer_type]["rope_type"] = self.default_rope_type + self.rope_parameters = rope_parameters def validate_rope(self: "PreTrainedConfig"): @@ -847,6 +858,9 @@ def validate_rope(self: "PreTrainedConfig"): f"Missing validation function in 'RotaryEmbeddingConfigMixin' for 'rope_type'='{rope_type}'" ) + def _validate_axial_rope_parameters(self, rope_parameters: dict, ignore_keys: set | None = None): + self._validate_default_rope_parameters(rope_parameters, ignore_keys=ignore_keys) + def _validate_default_rope_parameters(self, rope_parameters: dict, ignore_keys: set | None = None): required_keys = {"rope_type"} optional_keys = {"rope_theta"} diff --git a/src/transformers/modeling_utils.py b/src/transformers/modeling_utils.py index 3bbd2b3b46d5..02a27eff016e 100644 --- a/src/transformers/modeling_utils.py +++ b/src/transformers/modeling_utils.py @@ -2318,11 +2318,13 @@ def _init_weights(self, module): init.zeros_(module.num_batches_tracked) # This matches all the usual RotaryEmbeddings modules elif "RotaryEmbedding" in module.__class__.__name__ and hasattr(module, "original_inv_freq"): - rope_fn = ( - ROPE_INIT_FUNCTIONS[module.rope_type] - if module.rope_type != "default" - else module.compute_default_rope_parameters - ) + # Default and vision axial rope are defined in modeling files, only one can be defined at a time! + rope_init_fn_with_self = { + "axial": getattr(module, "compute_axial_rope_parameters", None), + "default": getattr(module, "compute_default_rope_parameters", None), + **ROPE_INIT_FUNCTIONS, + } + rope_fn = rope_init_fn_with_self[module.rope_type] buffer_value, _ = rope_fn(module.config) init.copy_(module.inv_freq, buffer_value) init.copy_(module.original_inv_freq, buffer_value) diff --git a/src/transformers/models/cohere_compass/configuration_cohere_compass.py b/src/transformers/models/cohere_compass/configuration_cohere_compass.py index 4ac771e7f0ae..9b3cc30eb68b 100644 --- a/src/transformers/models/cohere_compass/configuration_cohere_compass.py +++ b/src/transformers/models/cohere_compass/configuration_cohere_compass.py @@ -38,6 +38,8 @@ class CohereCompassVisionConfig(PreTrainedConfig): model_type = "cohere_compass_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 27 hidden_size: int = 1152 @@ -52,6 +54,7 @@ class CohereCompassVisionConfig(PreTrainedConfig): num_position_embeddings: int = 2304 deepstack_visual_indexes: list[int] | tuple[int, ...] = (8, 16, 24) initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="CohereLabs/North-Micro-Vision-Instruct") diff --git a/src/transformers/models/cohere_compass/modeling_cohere_compass.py b/src/transformers/models/cohere_compass/modeling_cohere_compass.py index 0f335150ae2a..8abaf88d11c2 100644 --- a/src/transformers/models/cohere_compass/modeling_cohere_compass.py +++ b/src/transformers/models/cohere_compass/modeling_cohere_compass.py @@ -68,22 +68,22 @@ class CohereCompassRotaryEmbedding(nn.Module): - """Gemma3 rotary embedding adapted to Compass's multi-axis position IDs.""" - @deprecate_kwarg("device", version="5.18") def __init__(self, config: CohereCompassTextConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.config = config - self.layer_types = sorted(set(config.layer_types)) + self.layer_types = list(set(config.layer_types)) self.rope_type = {} + self.mrope_section = {} for layer_type in self.layer_types: rope_params = self.config.rope_parameters[layer_type] if rope_params is None: continue self.rope_type[layer_type] = rope_params["rope_type"] + self.mrope_section[layer_type] = rope_params.get("mrope_section", [22, 22, 20]) rope_init_fn: Callable = self.compute_default_rope_parameters if self.rope_type[layer_type] != "default": rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]] @@ -110,54 +110,60 @@ def compute_default_rope_parameters( Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ - # For backward compatibility standardize the `rope_parameters_dict` if it uses old format base = config.rope_parameters[layer_type]["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads attention_factor = 1.0 # Unused in this type of RoPE + # Compute the inverse frequencies inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) - return inv_freq.to(device), attention_factor + + # Special to cohere-compass, we prerotate on the hw dim + mrope_section = config.rope_parameters[layer_type].get("mrope_section", [22, 22, 20]) + hw_dim = mrope_section[0] + mrope_section[1] + t_dim = mrope_section[2] + + inv_freq_3d = torch.empty_like(inv_freq) + # (Pre-)Rotate to avoid another rotation during the forward + inv_freq_3d[:hw_dim] = torch.cat([inv_freq[:-t_dim][0::2], inv_freq[:-t_dim][1::2]]) + inv_freq_3d[-t_dim:] = inv_freq[-t_dim:] + + return inv_freq_3d.to(device), attention_factor @torch.no_grad() - @dynamic_rope_update + @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids, layer_type=None): inv_freq = getattr(self, f"{layer_type}_inv_freq") attention_scaling = getattr(self, f"{layer_type}_attention_scaling") - # In contrast to other models, Cohere has different position ids for the grids - # So we expand the inv_freq to shape (3, ...) - inv_freq_expanded = inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device) + inv_freq_expanded = ( + inv_freq[None, None, :, None] + .expand(3, position_ids.shape[1], -1, 1) + .to(dtype=torch.float, device=x.device) + ) position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions) device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 - freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - mrope_section = self.config.rope_parameters[layer_type].get("mrope_section", [24, 20, 20]) - freqs = self.apply_interleaved_mrope(freqs, mrope_section) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * attention_scaling - sin = emb.sin() * attention_scaling + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(2, 3) + cos = freqs.cos() * attention_scaling + sin = freqs.sin() * attention_scaling + + sin = self.recomposition_frequencies(sin, layer_type) + cos = self.recomposition_frequencies(cos, layer_type) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) - # Copied from: Qwen3VLTextRotaryEmbedding.apply_interleaved_mrope - def apply_interleaved_mrope(self, freqs, mrope_section): - """Apply interleaved MRoPE to 3D rotary embeddings. - Reorganizes frequency layout from chunked [TTT...HHH...WWW] to - interleaved [THWTHWTHW...TT], preserving frequency continuity. - args: - x: (3, bs, seq_len, head_dim // 2) - mrope_section: (3,) - returns: - x_t: (bs, seq_len, head_dim // 2) + def recomposition_frequencies(self, freq, layer_type): + """ + Recompose the frequencies into the final spatial layout used per each grid. """ - freqs_t = freqs[0] # just overwrite the first dimension T - for dim, offset in enumerate((1, 2), start=1): # H, W - length = mrope_section[dim] * 3 - idx = slice(offset, length, 3) - freqs_t[..., idx] = freqs[dim, ..., idx] - return freqs_t + freq_h, freq_w, freq_t = ( + m[(i + 1) % 3] for i, m in enumerate(freq.split([*self.mrope_section[layer_type]], dim=-1)) + ) + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + freq_hwt = torch.cat([freq_hw, freq_t], dim=-1) + return torch.cat([freq_hwt, freq_hwt], dim=-1) class CohereCompassMLP(nn.Module): @@ -383,18 +389,6 @@ def forward( return hidden_states -class CohereCompassVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: - super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) - self.inv_freq = nn.Buffer(inv_freq, persistent=False) - - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) - - @auto_docstring class CohereCompassPreTrainedModel(PreTrainedModel): config: CohereCompassConfig @@ -418,9 +412,6 @@ class CohereCompassPreTrainedModel(PreTrainedModel): @torch.no_grad() def _init_weights(self, module): super()._init_weights(module) - if isinstance(module, CohereCompassVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) if isinstance(module, CohereCompassRotaryEmbedding): for layer_type in module.rope_type: rope_init_fn = module.compute_default_rope_parameters @@ -674,6 +665,72 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return hidden_states +class CohereCompassVisionRotaryEmbedding(nn.Module): + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: CohereCompassVisionConfig, device=None): + super().__init__() + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: CohereCompassVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) + + class CohereCompassVisionPatchMerger(nn.Module): def __init__(self, config: CohereCompassVisionConfig, use_postshuffle_norm=False) -> None: super().__init__() @@ -842,8 +899,7 @@ def __init__(self, config, *inputs, **kwargs) -> None: self.interpolation_align_corners = True self.interpolation_mode = "bilinear" - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = CohereCompassVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = CohereCompassVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([CohereCompassVisionBlock(config) for _ in range(config.depth)]) self.merger = CohereCompassVisionPatchMerger( @@ -895,13 +951,10 @@ def forward( hidden_states = self.patch_embed(hidden_states) pos_embeds = (self.pos_embed(interp_indices) * interp_weights[:, :, None]).sum(1) hidden_states = hidden_states + pos_embeds.to(hidden_states.dtype) - rotary_pos_emb = self.rotary_pos_emb(position_ids) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len, -1) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) deepstack_feature_lists = [] for layer_num, blk in enumerate(self.blocks): diff --git a/src/transformers/models/cohere_compass/modular_cohere_compass.py b/src/transformers/models/cohere_compass/modular_cohere_compass.py index 6ee08f232075..adebc0529b33 100644 --- a/src/transformers/models/cohere_compass/modular_cohere_compass.py +++ b/src/transformers/models/cohere_compass/modular_cohere_compass.py @@ -28,8 +28,8 @@ from ...modeling_flash_attention_utils import FlashAttentionKwargs from ...modeling_layers import GenericForSequenceClassification from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast -from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, RopeParameters, dynamic_rope_update -from ...modeling_utils import ALL_ATTENTION_FUNCTIONS +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, RopeParameters +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple from ...utils.generic import maybe_autocast @@ -160,49 +160,99 @@ def __init__(self, image_processor=None, tokenizer=None, video_processor=None, c self.vision_end_token = "<|VISION_END|>" +# Same mrope interleaving pattern as Qwen3VL but this model has layer-types class CohereCompassRotaryEmbedding(Gemma3RotaryEmbedding): - """Gemma3 rotary embedding adapted to Compass's multi-axis position IDs.""" + def __init__(self, config: CohereCompassTextConfig, device=None): + nn.Module.__init__() + self.max_seq_len_cached = config.max_position_embeddings + self.original_max_seq_len = config.max_position_embeddings + self.config = config + self.layer_types = list(set(config.layer_types)) + self.rope_type = {} + self.mrope_section = {} + for layer_type in self.layer_types: + rope_params = self.config.rope_parameters[layer_type] + if rope_params is None: + continue + + self.rope_type[layer_type] = rope_params["rope_type"] + self.mrope_section[layer_type] = rope_params.get("mrope_section", [22, 22, 20]) + rope_init_fn: Callable = self.compute_default_rope_parameters + if self.rope_type[layer_type] != "default": + rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]] + curr_inv_freq, curr_attention_scaling = rope_init_fn(self.config, device, layer_type=layer_type) + setattr(self, f"{layer_type}_inv_freq", nn.Buffer(curr_inv_freq, persistent=False)) + setattr(self, f"{layer_type}_original_inv_freq", nn.Buffer(curr_inv_freq.clone(), persistent=False)) + setattr(self, f"{layer_type}_attention_scaling", curr_attention_scaling) + + def compute_default_rope_parameters( + config: CohereCompassTextConfig, device=None, layer_type: str | None = None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + layer_type (`str`): + The current layer type if the model has different RoPE parameters per type. + Should not be used unless `config.layer_types is not None` + + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters[layer_type]["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + + attention_factor = 1.0 # Unused in this type of RoPE + + # Compute the inverse frequencies + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + + # Special to cohere-compass, we prerotate on the hw dim + mrope_section = config.rope_parameters[layer_type].get("mrope_section", [22, 22, 20]) + hw_dim = mrope_section[0] + mrope_section[1] + t_dim = mrope_section[2] + + inv_freq_3d = torch.empty_like(inv_freq) + # (Pre-)Rotate to avoid another rotation during the forward + inv_freq_3d[:hw_dim] = torch.cat([inv_freq[:-t_dim][0::2], inv_freq[:-t_dim][1::2]]) + inv_freq_3d[-t_dim:] = inv_freq[-t_dim:] + + return inv_freq_3d.to(device), attention_factor - # Copied from: Qwen3VLTextRotaryEmbedding.apply_interleaved_mrope, added supported for layer_types - @torch.no_grad() - @dynamic_rope_update def forward(self, x, position_ids, layer_type=None): inv_freq = getattr(self, f"{layer_type}_inv_freq") attention_scaling = getattr(self, f"{layer_type}_attention_scaling") - # In contrast to other models, Cohere has different position ids for the grids - # So we expand the inv_freq to shape (3, ...) - inv_freq_expanded = inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device) + inv_freq_expanded = ( + inv_freq[None, None, :, None] + .expand(3, position_ids.shape[1], -1, 1) + .to(dtype=torch.float, device=x.device) + ) position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions) device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 - freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - mrope_section = self.config.rope_parameters[layer_type].get("mrope_section", [24, 20, 20]) - freqs = self.apply_interleaved_mrope(freqs, mrope_section) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * attention_scaling - sin = emb.sin() * attention_scaling + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(2, 3) + cos = freqs.cos() * attention_scaling + sin = freqs.sin() * attention_scaling + + sin = self.recomposition_frequencies(sin, layer_type) + cos = self.recomposition_frequencies(cos, layer_type) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) - # Copied from: Qwen3VLTextRotaryEmbedding.apply_interleaved_mrope - def apply_interleaved_mrope(self, freqs, mrope_section): - """Apply interleaved MRoPE to 3D rotary embeddings. - Reorganizes frequency layout from chunked [TTT...HHH...WWW] to - interleaved [THWTHWTHW...TT], preserving frequency continuity. - args: - x: (3, bs, seq_len, head_dim // 2) - mrope_section: (3,) - returns: - x_t: (bs, seq_len, head_dim // 2) + def recomposition_frequencies(self, freq, layer_type): + """ + Recompose the frequencies into the final spatial layout used per each grid. """ - freqs_t = freqs[0] # just overwrite the first dimension T - for dim, offset in enumerate((1, 2), start=1): # H, W - length = mrope_section[dim] * 3 - idx = slice(offset, length, 3) - freqs_t[..., idx] = freqs[dim, ..., idx] - return freqs_t + freq_h, freq_w, freq_t = ( + m[(i + 1) % 3] for i, m in enumerate(freq.split([*self.mrope_section[layer_type]], dim=-1)) + ) + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + freq_hwt = torch.cat([freq_hw, freq_t], dim=-1) + return torch.cat([freq_hwt, freq_hwt], dim=-1) class CohereCompassMLP(Cohere2MLP): @@ -278,7 +328,7 @@ class CohereCompassPreTrainedModel(Qwen3VLPreTrainedModel): @torch.no_grad() def _init_weights(self, module): - super()._init_weights(module) + PreTrainedModel._init_weights(self, module) if isinstance(module, CohereCompassRotaryEmbedding): for layer_type in module.rope_type: rope_init_fn = module.compute_default_rope_parameters diff --git a/src/transformers/models/cosmos3_edge/modeling_cosmos3_edge.py b/src/transformers/models/cosmos3_edge/modeling_cosmos3_edge.py index c8489a76abb4..b53f6fbdbb47 100644 --- a/src/transformers/models/cosmos3_edge/modeling_cosmos3_edge.py +++ b/src/transformers/models/cosmos3_edge/modeling_cosmos3_edge.py @@ -25,7 +25,6 @@ import torch.nn as nn import torch.nn.functional as F -from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...generation import GenerationMixin @@ -589,18 +588,6 @@ def forward(self, inputs_embeds: torch.Tensor, grid_thw: torch.LongTensor, **kwa return hidden_states -class VisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: - super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) - self.inv_freq = nn.Buffer(inv_freq, persistent=False) - - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) - - _COSMOS3_EDGE_DROPPED_GENERATOR_KEYS = [ r"^(?:model\.language_model\.)?action_modality_embed$", r"^(?:model\.language_model\.)?action_proj_(?:in|out)\.(?:bias|fc)\.weight$", @@ -634,12 +621,6 @@ class Cosmos3EdgePreTrainedModel(PreTrainedModel): } _keys_to_ignore_on_load_unexpected = _COSMOS3_EDGE_DROPPED_GENERATOR_KEYS - def _init_weights(self, module): - super()._init_weights(module) - if isinstance(module, VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - @auto_docstring class Cosmos3EdgeTextModel(Cosmos3EdgePreTrainedModel): diff --git a/src/transformers/models/dinov3_vit/modular_dinov3_vit.py b/src/transformers/models/dinov3_vit/modular_dinov3_vit.py index 1af9b58d2d2e..93830cb3d29e 100644 --- a/src/transformers/models/dinov3_vit/modular_dinov3_vit.py +++ b/src/transformers/models/dinov3_vit/modular_dinov3_vit.py @@ -21,15 +21,6 @@ import torch from torch import nn -from transformers.models.arcee.modeling_arcee import ArceeMLP -from transformers.models.dinov2.modeling_dinov2 import ( - Dinov2LayerScale, - Dinov2PreTrainedModel, - eager_attention_forward, -) -from transformers.models.llama.modeling_llama import LlamaMLP -from transformers.models.pixtral.modeling_pixtral import PixtralAttention, rotate_half - from ... import initialization as init from ...backbone_utils import BackboneMixin, filter_output_hidden_states from ...modeling_layers import GradientCheckpointingLayer @@ -37,9 +28,17 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...pytorch_utils import compile_compatible_method_lru_cache -from ...utils import TransformersKwargs, auto_docstring, logging +from ...utils import TransformersKwargs, auto_docstring, logging, no_inherit_decorator from ...utils.generic import can_return_tuple, maybe_autocast, merge_with_config_defaults from ...utils.output_capturing import capture_outputs +from ..arcee.modeling_arcee import ArceeMLP +from ..dinov2.modeling_dinov2 import ( + Dinov2LayerScale, + Dinov2PreTrainedModel, + eager_attention_forward, +) +from ..llama.modeling_llama import LlamaMLP +from ..pixtral.modeling_pixtral import PixtralAttention, rotate_half from ..swin.modeling_swin import SwinDropPath from .configuration_dinov3_vit import DINOv3ViTConfig @@ -240,6 +239,7 @@ def apply_rotary_pos_emb( return q, k +@no_inherit_decorator class DINOv3ViTAttention(PixtralAttention): def __init__(self, config: DINOv3ViTConfig): super().__init__(config) diff --git a/src/transformers/models/edgetam_video/configuration_edgetam_video.py b/src/transformers/models/edgetam_video/configuration_edgetam_video.py index 8ce0582b9105..98b2dfd6b7c1 100644 --- a/src/transformers/models/edgetam_video/configuration_edgetam_video.py +++ b/src/transformers/models/edgetam_video/configuration_edgetam_video.py @@ -17,14 +17,16 @@ # 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. - from huggingface_hub.dataclasses import strict from ...configuration_utils import PreTrainedConfig -from ...utils import auto_docstring +from ...utils import auto_docstring, logging from ..auto import CONFIG_MAPPING, AutoConfig +logger = logging.get_logger(__name__) + + @auto_docstring(checkpoint="yonigozlan/EdgeTAM-hf") @strict class EdgeTamVideoPromptEncoderConfig(PreTrainedConfig): @@ -131,8 +133,6 @@ class EdgeTamVideoConfig(PreTrainedConfig): The non-linear activation function in the feedforward network in the memory attention module. memory_attention_dropout (`float`, *optional*, defaults to 0.1): The dropout rate for the memory attention module. - memory_attention_rope_theta (`float`, *optional*, defaults to 10000): - The Rope theta parameter. memory_attention_rope_feat_sizes (`Tuple[int, int]`, *optional*, defaults to `[64, 64]`): The feature sizes for the Rope positional encoding. memory_attention_rope_k_sizes (`List[int]`, *optional*, defaults to `[16, 16]`): @@ -219,6 +219,7 @@ class EdgeTamVideoConfig(PreTrainedConfig): ```""" model_type = "edgetam_video" + default_rope_type = "axial" sub_configs = { "vision_config": AutoConfig, "prompt_encoder_config": EdgeTamVideoPromptEncoderConfig, @@ -250,10 +251,10 @@ class EdgeTamVideoConfig(PreTrainedConfig): memory_attention_mlp_hidden_size: int = 2048 memory_attention_mlp_hidden_act: str = "relu" memory_attention_dropout: float | int = 0.1 - memory_attention_rope_theta: float | int = 10000 memory_attention_rope_feat_sizes: list | None = None memory_attention_rope_k_sizes: list | None = None memory_attention_rope_dropout: float | int = 0.1 + rope_parameters: dict | None = None # spatial perceiver resampler perceiver_resampler_num_latents: int = 256 @@ -308,7 +309,24 @@ def __post_init__(self, **kwargs): self.mask_decoder_config = EdgeTamVideoMaskDecoderConfig(**self.mask_decoder_config) elif self.mask_decoder_config is None: self.mask_decoder_config = EdgeTamVideoMaskDecoderConfig() + super().__post_init__(**kwargs) + @property + def memory_attention_rope_theta(self): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + return self.rope_parameters.get("rope_theta", 10_000) + + @memory_attention_rope_theta.setter + def memory_attention_rope_theta(self, value): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + self.rope_parameters["rope_theta"] = value + __all__ = ["EdgeTamVideoMaskDecoderConfig", "EdgeTamVideoPromptEncoderConfig", "EdgeTamVideoConfig"] diff --git a/src/transformers/models/edgetam_video/modeling_edgetam_video.py b/src/transformers/models/edgetam_video/modeling_edgetam_video.py index 1f0d063514aa..8fb591635599 100644 --- a/src/transformers/models/edgetam_video/modeling_edgetam_video.py +++ b/src/transformers/models/edgetam_video/modeling_edgetam_video.py @@ -17,7 +17,6 @@ # 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. - import math from collections import OrderedDict from collections.abc import Callable, Iterator @@ -40,7 +39,8 @@ from ...processing_utils import Unpack from ...pytorch_utils import compile_compatible_method_lru_cache from ...utils import ModelOutput, auto_docstring, can_return_tuple, logging -from ...utils.generic import TransformersKwargs, is_flash_attention_requested +from ...utils.deprecation import deprecate_kwarg +from ...utils.generic import TransformersKwargs, is_flash_attention_requested, maybe_autocast from ...utils.output_capturing import OutputRecorder from ..auto import AutoModel from .configuration_edgetam_video import ( @@ -136,44 +136,70 @@ class EdgeTamVideoVisionEncoderOutput(BaseModelOutputWithPooling): class EdgeTamVideoVisionRotaryEmbedding(nn.Module): """ - Vision Rotary Position Embedding for SAM2, following transformers library standards. - Supports 2D (axial) rotary embeddings for spatial dimensions. + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. """ - def __init__(self, config: EdgeTamVideoConfig, end_x: int | None = None, end_y: int | None = None): + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: EdgeTamVideoConfig, device=None): super().__init__() - self.dim = config.memory_attention_hidden_size // ( + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters(config: EdgeTamVideoConfig, device=None, **kwargs) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = config.memory_attention_hidden_size // ( config.memory_attention_downsample_rate * config.memory_attention_num_attention_heads ) - # Ensure even dimension for proper axial splitting - if self.dim % 4 != 0: - raise ValueError("Dimension must be divisible by 4 for axial RoPE") - self.end_x, self.end_y = config.memory_attention_rope_feat_sizes if end_x is None else (end_x, end_y) - self.memory_attention_rope_theta = config.memory_attention_rope_theta + spatial_dim = dim // 2 - # directly register the cos and sin embeddings as we have a fixed feature shape - inv_freq = self.create_inv_freq() - self.rope_embeddings_cos = nn.Buffer(inv_freq.cos(), persistent=False) - self.rope_embeddings_sin = nn.Buffer(inv_freq.sin(), persistent=False) + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor @torch.no_grad() - def forward(self) -> tuple[torch.Tensor, torch.Tensor]: - # As the feature map size is fixed, we can just return the pre-computed embeddings. - return self.rope_embeddings_cos, self.rope_embeddings_sin + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + # Ignore copy + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ - def create_inv_freq(self): - freqs = 1.0 / ( - self.memory_attention_rope_theta ** (torch.arange(0, self.dim, 4)[: (self.dim // 4)].float() / self.dim) - ) - # Generate 2D position indices for axial rotary embedding - flattened_indices = torch.arange(self.end_x * self.end_y, dtype=torch.long) - x_positions = flattened_indices % self.end_x - y_positions = torch.div(flattened_indices, self.end_x, rounding_mode="floor") - freqs_x = torch.outer(x_positions, freqs).float() - freqs_y = torch.outer(y_positions, freqs).float() - inv_freq = torch.cat([freqs_x, freqs_y], dim=-1) - inv_freq = inv_freq.repeat_interleave(2, dim=-1) - return inv_freq + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1)[None, ...] + return freq_hw.repeat_interleave(2, dim=-1) def eager_attention_forward( @@ -857,16 +883,14 @@ def _init_weights(self, module): if isinstance(module, EdgeTamVideoMemoryFuserCXBlock): if module.scale is not None: init.zeros_(module.scale) - elif isinstance(module, EdgeTamVideoVisionRotaryEmbedding): - inv_freq = module.create_inv_freq() - init.copy_(module.rope_embeddings_cos, inv_freq.cos()) - init.copy_(module.rope_embeddings_sin, inv_freq.sin()) elif isinstance(module, EdgeTamVideoPositionalEmbedding): init.normal_(module.positional_embedding, std=module.scale) - if isinstance(module, EdgeTamVideoVisionRotaryEmbedding): - inv_freq = module.create_inv_freq() - init.copy_(module.rope_embeddings_cos, inv_freq.cos()) - init.copy_(module.rope_embeddings_sin, inv_freq.sin()) + elif isinstance(module, EdgeTamVideoMemoryAttention): + position_ids = module.precompute_positions(module.config) + init.copy_(module.position_ids, position_ids) + if isinstance(module, EdgeTamVideoMemoryAttention): + position_ids_k = module.precompute_positions(module.config, is_key=True) + init.copy_(module.position_ids_k, position_ids_k) class EdgeTamVideoInferenceCache: @@ -1230,14 +1254,35 @@ def forward( class EdgeTamVideoMemoryAttention(nn.Module): def __init__(self, config: EdgeTamVideoConfig): super().__init__() + self.config = config self.layers = nn.ModuleList( [EdgeTamVideoMemoryAttentionLayer(config) for _ in range(config.memory_attention_num_layers)] ) self.layer_norm = nn.LayerNorm(config.memory_attention_hidden_size) self.rotary_emb = EdgeTamVideoVisionRotaryEmbedding(config=config) - self.rotary_emb_k = EdgeTamVideoVisionRotaryEmbedding( - config, end_x=config.memory_attention_rope_k_sizes[0], end_y=config.memory_attention_rope_k_sizes[1] - ) + + position_ids = self.precompute_positions(config) + self.position_ids = nn.Buffer(position_ids, persistent=False) + position_ids_k = self.precompute_positions(config, is_key=True) + self.position_ids_k = nn.Buffer(position_ids_k, persistent=False) + + @staticmethod + def precompute_positions(config: EdgeTamVideoConfig, is_key: bool = False): + "Precompute position IDs for query or key since they are different." + if not is_key: + hpos_ids, wpos_ids = torch.meshgrid( + torch.arange(config.memory_attention_rope_feat_sizes[1]), + torch.arange(config.memory_attention_rope_feat_sizes[0]), + indexing="ij", + ) + else: + hpos_ids, wpos_ids = torch.meshgrid( + torch.arange(config.memory_attention_rope_k_sizes[1]), + torch.arange(config.memory_attention_rope_k_sizes[0]), + indexing="ij", + ) + position_ids = torch.stack([wpos_ids.flatten(), hpos_ids.flatten()], dim=-1) + return position_ids def forward( self, @@ -1269,8 +1314,9 @@ def forward( output = output.transpose(0, 1) memory = memory.transpose(0, 1).unsqueeze(1) memory_posision_embeddings = memory_posision_embeddings.transpose(0, 1).unsqueeze(1) - rope_position_embeddings = self.rotary_emb() - rope_position_embeddings_k = self.rotary_emb_k() + + rope_position_embeddings = self.rotary_emb(output, self.position_ids) + rope_position_embeddings_k = self.rotary_emb(output, self.position_ids_k) for layer in self.layers: output = layer( queries=output.unsqueeze(1) if output.ndim == 3 else output, diff --git a/src/transformers/models/edgetam_video/modular_edgetam_video.py b/src/transformers/models/edgetam_video/modular_edgetam_video.py index 40390fefe6c9..2b5533189d3a 100644 --- a/src/transformers/models/edgetam_video/modular_edgetam_video.py +++ b/src/transformers/models/edgetam_video/modular_edgetam_video.py @@ -11,7 +11,6 @@ # 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. - import math from collections.abc import Callable from typing import Any @@ -29,7 +28,7 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS from ...processing_utils import Unpack from ...pytorch_utils import compile_compatible_method_lru_cache -from ...utils import auto_docstring +from ...utils import auto_docstring, logging from ...utils.output_capturing import OutputRecorder from ..auto import CONFIG_MAPPING, AutoConfig from ..sam2.modeling_sam2 import eager_attention_forward, window_partition @@ -57,6 +56,9 @@ ) +logger = logging.get_logger(__name__) + + @auto_docstring(checkpoint="yonigozlan/EdgeTAM-hf") @strict class EdgeTamVideoPromptEncoderConfig(Sam2VideoPromptEncoderConfig): @@ -113,8 +115,6 @@ class EdgeTamVideoConfig(PreTrainedConfig): The non-linear activation function in the feedforward network in the memory attention module. memory_attention_dropout (`float`, *optional*, defaults to 0.1): The dropout rate for the memory attention module. - memory_attention_rope_theta (`float`, *optional*, defaults to 10000): - The Rope theta parameter. memory_attention_rope_feat_sizes (`Tuple[int, int]`, *optional*, defaults to `[64, 64]`): The feature sizes for the Rope positional encoding. memory_attention_rope_k_sizes (`List[int]`, *optional*, defaults to `[16, 16]`): @@ -201,6 +201,7 @@ class EdgeTamVideoConfig(PreTrainedConfig): ```""" model_type = "edgetam_video" + default_rope_type = "axial" sub_configs = { "vision_config": AutoConfig, "prompt_encoder_config": EdgeTamVideoPromptEncoderConfig, @@ -232,10 +233,10 @@ class EdgeTamVideoConfig(PreTrainedConfig): memory_attention_mlp_hidden_size: int = 2048 memory_attention_mlp_hidden_act: str = "relu" memory_attention_dropout: float | int = 0.1 - memory_attention_rope_theta: float | int = 10000 memory_attention_rope_feat_sizes: list | None = None memory_attention_rope_k_sizes: list | None = None memory_attention_rope_dropout: float | int = 0.1 + rope_parameters: dict | None = None # spatial perceiver resampler perceiver_resampler_num_latents: int = 256 @@ -290,8 +291,25 @@ def __post_init__(self, **kwargs): self.mask_decoder_config = EdgeTamVideoMaskDecoderConfig(**self.mask_decoder_config) elif self.mask_decoder_config is None: self.mask_decoder_config = EdgeTamVideoMaskDecoderConfig() + super().__post_init__(**kwargs) + @property + def memory_attention_rope_theta(self): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + return self.rope_parameters.get("rope_theta", 10_000) + + @memory_attention_rope_theta.setter + def memory_attention_rope_theta(self, value): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + self.rope_parameters["rope_theta"] = value + class EdgeTamVideoLayerNorm(Sam2VideoLayerNorm): pass @@ -306,21 +324,7 @@ class EdgeTamVideoVisionEncoderOutput(Sam2VideoVisionEncoderOutput): class EdgeTamVideoVisionRotaryEmbedding(Sam2VideoVisionRotaryEmbedding): - def __init__(self, config: EdgeTamVideoConfig, end_x: int | None = None, end_y: int | None = None): - nn.Module.__init__() - self.dim = config.memory_attention_hidden_size // ( - config.memory_attention_downsample_rate * config.memory_attention_num_attention_heads - ) - # Ensure even dimension for proper axial splitting - if self.dim % 4 != 0: - raise ValueError("Dimension must be divisible by 4 for axial RoPE") - self.end_x, self.end_y = config.memory_attention_rope_feat_sizes if end_x is None else (end_x, end_y) - self.memory_attention_rope_theta = config.memory_attention_rope_theta - - # directly register the cos and sin embeddings as we have a fixed feature shape - inv_freq = self.create_inv_freq() - self.rope_embeddings_cos = nn.Buffer(inv_freq.cos(), persistent=False) - self.rope_embeddings_sin = nn.Buffer(inv_freq.sin(), persistent=False) + pass class EdgeTamVideoAttention(Sam2VideoAttention): @@ -590,11 +594,10 @@ class EdgeTamVideoFeedForward(Sam2VideoFeedForward): class EdgeTamVideoPreTrainedModel(Sam2VideoPreTrainedModel): def _init_weights(self, module): - super()._init_weights() - if isinstance(module, EdgeTamVideoVisionRotaryEmbedding): - inv_freq = module.create_inv_freq() - init.copy_(module.rope_embeddings_cos, inv_freq.cos()) - init.copy_(module.rope_embeddings_sin, inv_freq.sin()) + super()._init_weights(module) + if isinstance(module, EdgeTamVideoMemoryAttention): + position_ids_k = module.precompute_positions(module.config, is_key=True) + init.copy_(module.position_ids_k, position_ids_k) class EdgeTamVideoInferenceSession(Sam2VideoInferenceSession): @@ -670,9 +673,26 @@ def forward( class EdgeTamVideoMemoryAttention(Sam2VideoMemoryAttention): def __init__(self, config: EdgeTamVideoConfig): super().__init__() - self.rotary_emb_k = EdgeTamVideoVisionRotaryEmbedding( - config, end_x=config.memory_attention_rope_k_sizes[0], end_y=config.memory_attention_rope_k_sizes[1] - ) + position_ids_k = self.precompute_positions(config, is_key=True) + self.position_ids_k = nn.Buffer(position_ids_k, persistent=False) + + @staticmethod + def precompute_positions(config: EdgeTamVideoConfig, is_key: bool = False): + "Precompute position IDs for query or key since they are different." + if not is_key: + hpos_ids, wpos_ids = torch.meshgrid( + torch.arange(config.memory_attention_rope_feat_sizes[1]), + torch.arange(config.memory_attention_rope_feat_sizes[0]), + indexing="ij", + ) + else: + hpos_ids, wpos_ids = torch.meshgrid( + torch.arange(config.memory_attention_rope_k_sizes[1]), + torch.arange(config.memory_attention_rope_k_sizes[0]), + indexing="ij", + ) + position_ids = torch.stack([wpos_ids.flatten(), hpos_ids.flatten()], dim=-1) + return position_ids def forward( self, @@ -704,8 +724,9 @@ def forward( output = output.transpose(0, 1) memory = memory.transpose(0, 1).unsqueeze(1) memory_posision_embeddings = memory_posision_embeddings.transpose(0, 1).unsqueeze(1) - rope_position_embeddings = self.rotary_emb() - rope_position_embeddings_k = self.rotary_emb_k() + + rope_position_embeddings = self.rotary_emb(output, self.position_ids) + rope_position_embeddings_k = self.rotary_emb(output, self.position_ids_k) for layer in self.layers: output = layer( queries=output.unsqueeze(1) if output.ndim == 3 else output, diff --git a/src/transformers/models/eomt_dinov3/modular_eomt_dinov3.py b/src/transformers/models/eomt_dinov3/modular_eomt_dinov3.py index cd8972df5973..27a4a7e8bbf0 100644 --- a/src/transformers/models/eomt_dinov3/modular_eomt_dinov3.py +++ b/src/transformers/models/eomt_dinov3/modular_eomt_dinov3.py @@ -24,10 +24,7 @@ from ...modeling_rope_utils import RopeParameters from ...modeling_utils import PreTrainedModel from ...processing_utils import Unpack -from ...utils import ( - TransformersKwargs, - auto_docstring, -) +from ...utils import TransformersKwargs, auto_docstring from ...utils.deprecation import deprecate_kwarg from ...utils.generic import merge_with_config_defaults from ...utils.output_capturing import capture_outputs @@ -148,6 +145,7 @@ class EomtDinov3LayerScale(DINOv3ViTLayerScale): pass +# FIXME: this is simple axial rope, too much hassle to refactor - maybe some contrib stumbles upon it :) class EomtDinov3RotaryEmbedding(DINOv3ViTRopePositionEmbedding): inv_freq: Tensor diff --git a/src/transformers/models/ernie4_5_vl_moe/configuration_ernie4_5_vl_moe.py b/src/transformers/models/ernie4_5_vl_moe/configuration_ernie4_5_vl_moe.py index e93297a4eb5a..762b910ee666 100644 --- a/src/transformers/models/ernie4_5_vl_moe/configuration_ernie4_5_vl_moe.py +++ b/src/transformers/models/ernie4_5_vl_moe/configuration_ernie4_5_vl_moe.py @@ -37,6 +37,8 @@ class Ernie4_5_VLMoeVisionConfig(PreTrainedConfig): model_type = "ernie4_5_vl_moe_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 32 @@ -47,6 +49,7 @@ class Ernie4_5_VLMoeVisionConfig(PreTrainedConfig): patch_size: int | list[int] | tuple[int, int] = 14 spatial_merge_size: int = 2 initializer_range: float = 0.02 + rope_parameters: dict | None = None base_model_tp_plan = { "blocks.*.attn.qkv": "colwise", diff --git a/src/transformers/models/ernie4_5_vl_moe/modeling_ernie4_5_vl_moe.py b/src/transformers/models/ernie4_5_vl_moe/modeling_ernie4_5_vl_moe.py index c9decaad4383..14a083685a02 100644 --- a/src/transformers/models/ernie4_5_vl_moe/modeling_ernie4_5_vl_moe.py +++ b/src/transformers/models/ernie4_5_vl_moe/modeling_ernie4_5_vl_moe.py @@ -57,7 +57,7 @@ class Ernie4_5_VLMoeTextRotaryEmbedding(nn.Module): @deprecate_kwarg("device", version="5.18") - def __init__(self, config, device=None): + def __init__(self, config: Ernie4_5_VLMoeTextConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings @@ -70,7 +70,7 @@ def __init__(self, config, device=None): inv_freq, self.attention_scaling = rope_init_fn(self.config, device) self.inv_freq = nn.Buffer(inv_freq, persistent=False) - self.original_inv_freq = inv_freq + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) self.mrope_section = config.rope_parameters.get("mrope_section", [22, 22, 20]) @@ -124,12 +124,15 @@ def forward(self, x, position_ids): cos = freqs.cos() * self.attention_scaling sin = freqs.sin() * self.attention_scaling - sin = self.recomposition_to_3d(sin) - cos = self.recomposition_to_3d(cos) + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos, sin - def recomposition_to_3d(self, freq): + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ freq_h, freq_w, freq_t = (m[(i + 1) % 3] for i, m in enumerate(freq.split([*self.mrope_section], dim=-1))) freq_hw = torch.stack([freq_h, freq_w], dim=-1).flatten(-2) freq_hwt = torch.cat([freq_hw, freq_t], dim=-1) @@ -708,9 +711,6 @@ def _init_weights(self, module): elif isinstance(module, Ernie4_5_VLMoeMoeExperts): init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range) init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range) - elif isinstance(module, Ernie4_5_VLMoeVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) @auto_docstring @@ -843,15 +843,69 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: class Ernie4_5_VLMoeVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Ernie4_5_VLMoeVisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Ernie4_5_VLMoeVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) @auto_docstring @@ -876,9 +930,7 @@ def __init__(self, config) -> None: embed_dim=config.hidden_size, ) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Ernie4_5_VLMoeVisionRotaryEmbedding(head_dim // 2) - + self.rotary_pos_emb = Ernie4_5_VLMoeVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Ernie4_5_VLMoeVisionBlock(config) for _ in range(config.depth)]) self.gradient_checkpointing = False @@ -899,9 +951,7 @@ def forward( cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs) hidden_states = self.patch_embed(hidden_states) - rotary_pos_emb = self.rotary_pos_emb(position_ids) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) for block in self.blocks: hidden_states = block( diff --git a/src/transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py b/src/transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py index 96ed23d89340..0d8db16cf5e3 100644 --- a/src/transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py +++ b/src/transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py @@ -61,10 +61,10 @@ from ..mixtral.modeling_mixtral import load_balancing_loss_func from ..qwen2_5_vl.modeling_qwen2_5_vl import ( Qwen2_5_VisionPatchEmbed, - Qwen2_5_VisionRotaryEmbedding, Qwen2_5_VLPreTrainedModel, Qwen2_5_VLVisionAttention, Qwen2_5_VLVisionBlock, + Qwen2_5_VLVisionRotaryEmbedding, ) from ..qwen2_vl.configuration_qwen2_vl import Qwen2VLVisionConfig from ..qwen2_vl.image_processing_pil_qwen2_vl import Qwen2VLImageProcessorPil @@ -218,7 +218,7 @@ def __post_init__(self, **kwargs): class Ernie4_5_VLMoeTextRotaryEmbedding(nn.Module): @deprecate_kwarg("device", version="5.18") - def __init__(self, config, device=None): + def __init__(self, config: Ernie4_5_VLMoeTextConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings @@ -231,7 +231,7 @@ def __init__(self, config, device=None): inv_freq, self.attention_scaling = rope_init_fn(self.config, device) self.inv_freq = nn.Buffer(inv_freq, persistent=False) - self.original_inv_freq = inv_freq + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) self.mrope_section = config.rope_parameters.get("mrope_section", [22, 22, 20]) @@ -285,12 +285,15 @@ def forward(self, x, position_ids): cos = freqs.cos() * self.attention_scaling sin = freqs.sin() * self.attention_scaling - sin = self.recomposition_to_3d(sin) - cos = self.recomposition_to_3d(cos) + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos, sin - def recomposition_to_3d(self, freq): + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ freq_h, freq_w, freq_t = (m[(i + 1) % 3] for i, m in enumerate(freq.split([*self.mrope_section], dim=-1))) freq_hw = torch.stack([freq_h, freq_w], dim=-1).flatten(-2) freq_hwt = torch.cat([freq_hw, freq_t], dim=-1) @@ -536,9 +539,6 @@ def _init_weights(self, module): elif isinstance(module, Ernie4_5_VLMoeMoeExperts): init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range) init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range) - elif isinstance(module, Ernie4_5_VLMoeVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class Ernie4_5_VLMoeTextModel(Ernie4_5_MoeModel): @@ -650,7 +650,7 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return self.proj(hidden_states.to(target_dtype)) -class Ernie4_5_VLMoeVisionRotaryEmbedding(Qwen2_5_VisionRotaryEmbedding): +class Ernie4_5_VLMoeVisionRotaryEmbedding(Qwen2_5_VLVisionRotaryEmbedding): pass @@ -672,8 +672,7 @@ def __init__(self, config) -> None: embed_dim=config.hidden_size, ) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Ernie4_5_VLMoeVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Ernie4_5_VLMoeVisionRotaryEmbedding(config) self.ln = nn.LayerNorm(config.hidden_size, eps=config.rms_norm_eps) @@ -692,9 +691,7 @@ def forward( cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs) hidden_states = self.patch_embed(hidden_states) - rotary_pos_emb = self.rotary_pos_emb(position_ids) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) for block in self.blocks: hidden_states = block( diff --git a/src/transformers/models/exaone4_5/configuration_exaone4_5.py b/src/transformers/models/exaone4_5/configuration_exaone4_5.py index 29519897e8ed..168e49999bde 100644 --- a/src/transformers/models/exaone4_5/configuration_exaone4_5.py +++ b/src/transformers/models/exaone4_5/configuration_exaone4_5.py @@ -39,6 +39,8 @@ class Exaone4_5_VisionConfig(PreTrainedConfig): model_type = "exaone4_5_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 32 hidden_size: int = 3584 @@ -53,6 +55,7 @@ class Exaone4_5_VisionConfig(PreTrainedConfig): out_hidden_size: int = 3584 fullatt_block_indexes: list[int] | tuple[int, ...] = (7, 15, 23, 31) initializer_range: float = 0.02 + rope_parameters: dict | None = None num_key_value_heads: int = 8 diff --git a/src/transformers/models/exaone4_5/modeling_exaone4_5.py b/src/transformers/models/exaone4_5/modeling_exaone4_5.py index 312076f07b18..fd639af538fb 100644 --- a/src/transformers/models/exaone4_5/modeling_exaone4_5.py +++ b/src/transformers/models/exaone4_5/modeling_exaone4_5.py @@ -25,7 +25,6 @@ import torch from torch import nn -from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache from ...generation import GenerationMixin @@ -35,10 +34,12 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check +from ...utils.deprecation import deprecate_kwarg from ...utils.generic import ( accepts_precomputed_kwargs, get_max_seqlen, is_flash_attention_requested, + maybe_autocast, merge_with_config_defaults, ) from ...utils.output_capturing import capture_outputs @@ -74,15 +75,69 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: class Exaone4_5_VisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Exaone4_5_VisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Exaone4_5_VisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) @use_kernel_forward_from_hub("RMSNorm") @@ -474,12 +529,6 @@ class Exaone4_5_PreTrainedModel(PreTrainedModel): config_class = Exaone4_5_Config _keys_to_ignore_on_load_unexpected = [r"mtp.*"] - def _init_weights(self, module): - super()._init_weights(module) - if isinstance(module, Exaone4_5_VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - class Exaone4_5_VisionModel(Exaone4_5_PreTrainedModel): config: Exaone4_5_VisionConfig @@ -504,8 +553,7 @@ def __init__(self, config: Exaone4_5_VisionConfig, *inputs, **kwargs) -> None: in_channels=config.in_channels, embed_dim=config.hidden_size, ) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Exaone4_5_VisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Exaone4_5_VisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Exaone4_5_VisionBlock(config) for _ in range(config.depth)]) self.merger = Exaone4_5_PatchMerger( dim=config.out_hidden_size, @@ -516,6 +564,12 @@ def __init__(self, config: Exaone4_5_VisionConfig, *inputs, **kwargs) -> None: self.post_init() + def permute_input_for_window_attn(self, input_tensor: torch.Tensor, window_index: torch.Tensor, seq_len: int): + input_tensor = input_tensor.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) + input_tensor = input_tensor[window_index, :, :] + input_tensor = input_tensor.reshape(seq_len, -1) + return input_tensor + @merge_with_config_defaults @capture_outputs def forward( @@ -547,16 +601,12 @@ def forward( hidden_states = self.patch_embed(hidden_states) seq_len, _ = hidden_states.size() - hidden_states = hidden_states.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) - hidden_states = hidden_states[window_index, :, :] - hidden_states = hidden_states.reshape(seq_len, -1) - - rotary_pos_emb = self.rotary_pos_emb(position_ids) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) - rotary_pos_emb = rotary_pos_emb[window_index, :, :] - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + hidden_states = self.permute_input_for_window_attn(hidden_states, window_index, seq_len=seq_len) + + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) + position_embeddings = tuple( + self.permute_input_for_window_attn(freq, window_index, seq_len=seq_len) for freq in position_embeddings + ) for layer_num, blk in enumerate(self.blocks): if layer_num in self.fullatt_block_indexes: diff --git a/src/transformers/models/exaone4_5/modular_exaone4_5.py b/src/transformers/models/exaone4_5/modular_exaone4_5.py index 0d6e97b085b8..f31741b71f19 100644 --- a/src/transformers/models/exaone4_5/modular_exaone4_5.py +++ b/src/transformers/models/exaone4_5/modular_exaone4_5.py @@ -20,11 +20,10 @@ from huggingface_hub.dataclasses import strict from torch import nn -from ... import initialization as init from ...cache_utils import Cache from ...configuration_utils import PreTrainedConfig from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast -from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS from ...processing_utils import ProcessingKwargs, Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple from ...utils.generic import get_max_seqlen, is_flash_attention_requested @@ -33,13 +32,13 @@ from ..qwen2_5_vl.configuration_qwen2_5_vl import Qwen2_5_VLVisionConfig from ..qwen2_5_vl.modeling_qwen2_5_vl import ( Qwen2_5_VisionPatchEmbed, - Qwen2_5_VisionRotaryEmbedding, Qwen2_5_VisionTransformerPretrainedModel, Qwen2_5_VLForConditionalGeneration, Qwen2_5_VLMLP, Qwen2_5_VLPatchMerger, Qwen2_5_VLVisionAttention, Qwen2_5_VLVisionBlock, + Qwen2_5_VLVisionRotaryEmbedding, ) from ..qwen2_vl.modeling_qwen2_vl import ( Qwen2VLModel, @@ -103,7 +102,7 @@ class Exaone4_5_PatchEmbed(Qwen2_5_VisionPatchEmbed): pass -class Exaone4_5_VisionRotaryEmbedding(Qwen2_5_VisionRotaryEmbedding): +class Exaone4_5_VisionRotaryEmbedding(Qwen2_5_VLVisionRotaryEmbedding): pass @@ -206,12 +205,6 @@ class Exaone4_5_PreTrainedModel(Exaone4PreTrainedModel): _no_split_modules = ["Exaone4_5_VisionBlock", "Exaone4_5_DecoderLayer"] _keys_to_ignore_on_load_unexpected = [r"mtp.*"] - def _init_weights(self, module): - PreTrainedModel._init_weights(module) - if isinstance(module, Exaone4_5_VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - class Exaone4_5_VisionModel(Exaone4_5_PreTrainedModel, Qwen2_5_VisionTransformerPretrainedModel): config_class = Exaone4_5_VisionConfig @@ -224,8 +217,7 @@ def __init__(self, config: Exaone4_5_VisionConfig, *inputs, **kwargs): in_channels=config.in_channels, embed_dim=config.hidden_size, ) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Exaone4_5_VisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Exaone4_5_VisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Exaone4_5_VisionBlock(config) for _ in range(config.depth)]) self.merger = Exaone4_5_PatchMerger( dim=config.out_hidden_size, diff --git a/src/transformers/models/gemma4/configuration_gemma4.py b/src/transformers/models/gemma4/configuration_gemma4.py index ff970b4c7ef5..88b6ebec1208 100644 --- a/src/transformers/models/gemma4/configuration_gemma4.py +++ b/src/transformers/models/gemma4/configuration_gemma4.py @@ -268,6 +268,7 @@ class Gemma4VisionConfig(PreTrainedConfig): } default_theta = 100.0 + default_rope_type = "axial" hidden_size: int = 768 intermediate_size: int = 3072 @@ -288,12 +289,6 @@ class Gemma4VisionConfig(PreTrainedConfig): standardize: bool = False initializer_range: float = 0.02 - def __post_init__(self, **kwargs): - if self.rope_parameters is None: - self.rope_parameters = {"rope_type": "default", "rope_theta": 100.0} - - super().__post_init__(**kwargs) - @auto_docstring(checkpoint="google/gemma-4-e2b-it") @strict diff --git a/src/transformers/models/gemma4/modeling_gemma4.py b/src/transformers/models/gemma4/modeling_gemma4.py index ab7e55acfb9e..7e08ab82ec73 100644 --- a/src/transformers/models/gemma4/modeling_gemma4.py +++ b/src/transformers/models/gemma4/modeling_gemma4.py @@ -705,18 +705,21 @@ def forward(self, x): class Gemma4VisionRotaryEmbedding(nn.Module): + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + @deprecate_kwarg("device", version="5.18") def __init__(self, config: Gemma4VisionConfig, device=None): super().__init__() - self.max_seq_len_cached = config.max_position_embeddings - self.original_max_seq_len = config.max_position_embeddings - self.config = config self.rope_type = self.config.rope_parameters["rope_type"] - rope_init_fn: Callable = self.compute_default_rope_parameters - if self.rope_type != "default": - rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") inv_freq, self.attention_scaling = rope_init_fn(self.config, device) self.inv_freq = nn.Buffer(inv_freq, persistent=False) @@ -724,9 +727,7 @@ def __init__(self, config: Gemma4VisionConfig, device=None): @staticmethod @deprecate_kwarg("device", version="5.18") - def compute_default_rope_parameters( - config: Gemma4VisionConfig, device=None, **kwargs - ) -> tuple[torch.Tensor, float]: + def compute_axial_rope_parameters(config: Gemma4VisionConfig, device=None, **kwargs) -> tuple[torch.Tensor, float]: """ Computes the inverse frequencies according to the original RoPE implementation Args: @@ -738,11 +739,6 @@ def compute_default_rope_parameters( """ base = config.rope_parameters["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads - - # The reference implementation computes RoPE frequencies INDEPENDENTLY - # for each spatial dimension using the partitioned head_dim (head_dim // ndim), - # so both x and y dimensions get identical frequency ranges. - # This is different from splitting the global inv_freq between dimensions. spatial_dim = dim // 2 attention_factor = 1.0 # Unused in this type of RoPE @@ -750,28 +746,28 @@ def compute_default_rope_parameters( return inv_freq.to(device), attention_factor @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): - inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) - device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + inv_freq_expanded = self.inv_freq[None, ...].float() + position_ids_expanded = position_ids[..., None].float() - # Multidimensional positions: [batch, num_patches, ndim]. Apply rotations to each spatial dim separately - all_cos, all_sin = [], [] - for i in range(2): - dim_position_ids = position_ids[:, :, i] - dim_position_ids_expanded = dim_position_ids[:, None, :].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded @ inv_freq_expanded + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling - with maybe_autocast(device_type=device_type, enabled=False): # Force float32 - freqs = (inv_freq_expanded.float() @ dim_position_ids_expanded.float()).transpose(1, 2) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling - all_cos.append(cos) - all_sin.append(sin) + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos.to(x.dtype), sin.to(x.dtype) - cos = torch.cat(all_cos, dim=-1).to(dtype=x.dtype) - sin = torch.cat(all_sin, dim=-1).to(dtype=x.dtype) - return cos, sin + # Ignore copy + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + # in contrast to other 2D rope modules, interleave grids as H-H-W-W + freq_h, freq_w = freq[:, :, 0], freq[:, :, 1] + return torch.cat([freq_h, freq_h, freq_w, freq_w], dim=-1) def rotate_half(x): @@ -1501,15 +1497,6 @@ def _init_weights(self, module): curr_inv_freq, _ = rope_init_fn(rope_config, layer_type=layer_type) init.copy_(getattr(module, f"{layer_type}_inv_freq"), curr_inv_freq) init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), curr_inv_freq) - elif isinstance(module, Gemma4VisionRotaryEmbedding): - rope_fn = ( - ROPE_INIT_FUNCTIONS[module.rope_type] - if module.rope_type != "default" - else module.compute_default_rope_parameters - ) - buffer_value, _ = rope_fn(module.config) - init.copy_(module.inv_freq, buffer_value) - init.copy_(module.original_inv_freq, buffer_value) elif isinstance(module, Gemma4TextScaledWordEmbedding): init.constant_(module.embed_scale, module.scalar_embed_scale) elif isinstance(module, Gemma4TextRouter): diff --git a/src/transformers/models/gemma4/modular_gemma4.py b/src/transformers/models/gemma4/modular_gemma4.py index 885b61625389..ac4e8fb4f737 100644 --- a/src/transformers/models/gemma4/modular_gemma4.py +++ b/src/transformers/models/gemma4/modular_gemma4.py @@ -38,7 +38,7 @@ ) from ...modeling_flash_attention_utils import FlashAttentionKwargs from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling -from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import ( @@ -71,9 +71,9 @@ apply_rotary_pos_emb, eager_attention_forward, ) -from ..llama.modeling_llama import LlamaRotaryEmbedding from ..mixtral.modeling_mixtral import MixtralExperts from ..moonshine_streaming.modeling_moonshine_streaming import sliding_window_mask_function +from ..sam3.modeling_sam3 import Sam3ViTRotaryEmbedding from .configuration_gemma4 import Gemma4AudioConfig, Gemma4Config, Gemma4TextConfig, Gemma4VisionConfig @@ -784,55 +784,35 @@ def apply_multidimensional_rope( return torch.cat(y_parts, dim=-1) -class Gemma4VisionRotaryEmbedding(LlamaRotaryEmbedding): - def compute_default_rope_parameters( - config: Gemma4VisionConfig, device=None, **kwargs - ) -> tuple[torch.Tensor, float]: - """ - Computes the inverse frequencies according to the original RoPE implementation - Args: - config ([`~transformers.PreTrainedConfig`]): - The model configuration. - Returns: - Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the - post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). - """ - base = config.rope_parameters["rope_theta"] - dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads - - # The reference implementation computes RoPE frequencies INDEPENDENTLY - # for each spatial dimension using the partitioned head_dim (head_dim // ndim), - # so both x and y dimensions get identical frequency ranges. - # This is different from splitting the global inv_freq between dimensions. - spatial_dim = dim // 2 +# override -- Gemma4 doesn't pack inputs for attention and thus needs a proper batch dim +class Gemma4VisionRotaryEmbedding(Sam3ViTRotaryEmbedding): + def __init__(self, config: Gemma4VisionConfig, device=None): + super().__init__(config, device) - attention_factor = 1.0 # Unused in this type of RoPE - inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) - return inv_freq.to(device), attention_factor + def compute_axial_rope_parameters(config: Gemma4VisionConfig, device=None, **kwargs) -> tuple[torch.Tensor, float]: + return super().compute_axial_rope_parameters(config, device, **kwargs) - @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): - inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) - device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + inv_freq_expanded = self.inv_freq[None, ...].float() + position_ids_expanded = position_ids[..., None].float() - # Multidimensional positions: [batch, num_patches, ndim]. Apply rotations to each spatial dim separately - all_cos, all_sin = [], [] - for i in range(2): - dim_position_ids = position_ids[:, :, i] - dim_position_ids_expanded = dim_position_ids[:, None, :].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded @ inv_freq_expanded + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling - with maybe_autocast(device_type=device_type, enabled=False): # Force float32 - freqs = (inv_freq_expanded.float() @ dim_position_ids_expanded.float()).transpose(1, 2) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling - all_cos.append(cos) - all_sin.append(sin) + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos.to(x.dtype), sin.to(x.dtype) - cos = torch.cat(all_cos, dim=-1).to(dtype=x.dtype) - sin = torch.cat(all_sin, dim=-1).to(dtype=x.dtype) - return cos, sin + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + # in contrast to other 2D rope modules, interleave grids as H-H-W-W + freq_h, freq_w = freq[:, :, 0], freq[:, :, 1] + return torch.cat([freq_h, freq_h, freq_w, freq_w], dim=-1) @no_inherit_decorator @@ -1305,15 +1285,6 @@ def _init_weights(self, module): curr_inv_freq, _ = rope_init_fn(rope_config, layer_type=layer_type) init.copy_(getattr(module, f"{layer_type}_inv_freq"), curr_inv_freq) init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), curr_inv_freq) - elif isinstance(module, Gemma4VisionRotaryEmbedding): - rope_fn = ( - ROPE_INIT_FUNCTIONS[module.rope_type] - if module.rope_type != "default" - else module.compute_default_rope_parameters - ) - buffer_value, _ = rope_fn(module.config) - init.copy_(module.inv_freq, buffer_value) - init.copy_(module.original_inv_freq, buffer_value) elif isinstance(module, Gemma4TextScaledWordEmbedding): init.constant_(module.embed_scale, module.scalar_embed_scale) elif isinstance(module, Gemma4TextRouter): diff --git a/src/transformers/models/glm46v/modular_glm46v.py b/src/transformers/models/glm46v/modular_glm46v.py index 3d239161f738..ff2a0e694815 100644 --- a/src/transformers/models/glm46v/modular_glm46v.py +++ b/src/transformers/models/glm46v/modular_glm46v.py @@ -87,9 +87,6 @@ class Glm46VPreTrainedModel(Glm4vPreTrainedModel): _can_record_outputs = None _no_split_modules = None - def _init_weights(self, module): - raise AttributeError("Not needed") - class Glm46VModel(Glm4vModel): _no_split_modules = None diff --git a/src/transformers/models/glm4v/configuration_glm4v.py b/src/transformers/models/glm4v/configuration_glm4v.py index 21ef4a4d9bfa..23f15e5e23dd 100644 --- a/src/transformers/models/glm4v/configuration_glm4v.py +++ b/src/transformers/models/glm4v/configuration_glm4v.py @@ -48,6 +48,8 @@ class Glm4vVisionConfig(PreTrainedConfig): model_type = "glm4v_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 24 hidden_size: int = 1536 @@ -64,6 +66,7 @@ class Glm4vVisionConfig(PreTrainedConfig): out_hidden_size: int = 4096 intermediate_size: int = 13696 initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="zai-org/GLM-4.1V-9B-Thinking") diff --git a/src/transformers/models/glm4v/modeling_glm4v.py b/src/transformers/models/glm4v/modeling_glm4v.py index 3175e96035d1..8c778e4026a0 100644 --- a/src/transformers/models/glm4v/modeling_glm4v.py +++ b/src/transformers/models/glm4v/modeling_glm4v.py @@ -27,7 +27,6 @@ import torch.nn.functional as F from torch.nn import LayerNorm -from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...generation import GenerationMixin @@ -109,15 +108,67 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: class Glm4vVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Glm4vVisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters(config: Glm4vVisionConfig, device=None, **kwargs) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) class Glm4vVisionPatchMerger(nn.Module): @@ -659,12 +710,6 @@ class Glm4vPreTrainedModel(PreTrainedModel): _can_compile_fullgraph = True _supports_attention_backend = True - def _init_weights(self, module): - super()._init_weights(module) - if isinstance(module, Glm4vVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - class Glm4vVisionModel(Glm4vPreTrainedModel): config: Glm4vVisionConfig @@ -683,8 +728,7 @@ def __init__(self, config) -> None: self.embeddings = Glm4vVisionEmbeddings(config) self.patch_embed = Glm4vVisionPatchEmbed(config) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Glm4vVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Glm4vVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Glm4vVisionBlock(config) for _ in range(config.depth)]) self.merger = Glm4vVisionPatchMerger( @@ -723,9 +767,7 @@ def forward( hidden_states = self.patch_embed(hidden_states) hidden_states = self.post_conv_layernorm(hidden_states) - rotary_emb = self.rotary_pos_emb(position_ids) - emb = torch.cat((rotary_emb, rotary_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seqlens = cu_seqlens[1:] - cu_seqlens[:-1] hidden_states = self.embeddings( diff --git a/src/transformers/models/glm4v/modular_glm4v.py b/src/transformers/models/glm4v/modular_glm4v.py index 29f75ed09e50..3e4be49a16a9 100644 --- a/src/transformers/models/glm4v/modular_glm4v.py +++ b/src/transformers/models/glm4v/modular_glm4v.py @@ -20,7 +20,6 @@ from huggingface_hub.dataclasses import strict from torch.nn import LayerNorm -from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...configuration_utils import PreTrainedConfig @@ -29,7 +28,7 @@ from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling from ...modeling_rope_utils import RopeParameters -from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS from ...processing_utils import Unpack from ...utils import ( TransformersKwargs, @@ -49,7 +48,6 @@ from ..glm4.modeling_glm4 import Glm4MLP, Glm4RMSNorm, Glm4RotaryEmbedding, eager_attention_forward from ..qwen2_5_vl.modeling_qwen2_5_vl import ( Qwen2_5_VisionPatchEmbed, - Qwen2_5_VisionRotaryEmbedding, Qwen2_5_VLCausalLMOutputWithPast, Qwen2_5_VLForConditionalGeneration, Qwen2_5_VLMLP, @@ -58,6 +56,7 @@ Qwen2_5_VLTextModel, Qwen2_5_VLVisionAttention, Qwen2_5_VLVisionBlock, + Qwen2_5_VLVisionRotaryEmbedding, ) from ..qwen2_vl.modeling_qwen2_vl import Qwen2VLModel from ..qwen2_vl.processing_qwen2_vl import ( @@ -93,6 +92,8 @@ class Glm4vVisionConfig(PreTrainedConfig): model_type = "glm4v_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 24 hidden_size: int = 1536 @@ -109,6 +110,7 @@ class Glm4vVisionConfig(PreTrainedConfig): out_hidden_size: int = 4096 intermediate_size: int = 13696 initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="zai-org/GLM-4.1V-9B-Thinking") @@ -254,7 +256,7 @@ def __init__(self, config: Glm4vVisionConfig) -> None: self.proj = nn.Conv3d(self.in_channels, self.embed_dim, kernel_size=kernel_size, stride=kernel_size) -class Glm4vVisionRotaryEmbedding(Qwen2_5_VisionRotaryEmbedding): +class Glm4vVisionRotaryEmbedding(Qwen2_5_VLVisionRotaryEmbedding): pass @@ -573,12 +575,6 @@ class Glm4vModelOutputWithPast(Qwen2_5_VLModelOutputWithPast): class Glm4vPreTrainedModel(Qwen2_5_VLPreTrainedModel): _no_split_modules = ["Glm4vTextDecoderLayer", "Glm4vVisionBlock"] - def _init_weights(self, module): - PreTrainedModel._init_weights(self, module) - if isinstance(module, Glm4vVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - class Glm4vVisionModel(Glm4vPreTrainedModel): config: Glm4vVisionConfig @@ -597,8 +593,7 @@ def __init__(self, config) -> None: self.embeddings = Glm4vVisionEmbeddings(config) self.patch_embed = Glm4vVisionPatchEmbed(config) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Glm4vVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Glm4vVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Glm4vVisionBlock(config) for _ in range(config.depth)]) self.merger = Glm4vVisionPatchMerger( @@ -637,9 +632,7 @@ def forward( hidden_states = self.patch_embed(hidden_states) hidden_states = self.post_conv_layernorm(hidden_states) - rotary_emb = self.rotary_pos_emb(position_ids) - emb = torch.cat((rotary_emb, rotary_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seqlens = cu_seqlens[1:] - cu_seqlens[:-1] hidden_states = self.embeddings( diff --git a/src/transformers/models/glm4v_moe/configuration_glm4v_moe.py b/src/transformers/models/glm4v_moe/configuration_glm4v_moe.py index 110db28d6001..1cfb69cf24b1 100644 --- a/src/transformers/models/glm4v_moe/configuration_glm4v_moe.py +++ b/src/transformers/models/glm4v_moe/configuration_glm4v_moe.py @@ -136,6 +136,8 @@ class Glm4vMoeVisionConfig(PreTrainedConfig): model_type = "glm4v_moe_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 24 hidden_size: int = 1536 @@ -152,6 +154,7 @@ class Glm4vMoeVisionConfig(PreTrainedConfig): out_hidden_size: int = 4096 intermediate_size: int = 13696 initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="zai-org/GLM-4.5V") diff --git a/src/transformers/models/glm4v_moe/modeling_glm4v_moe.py b/src/transformers/models/glm4v_moe/modeling_glm4v_moe.py index 8f1c1577b4e8..4210fa834660 100644 --- a/src/transformers/models/glm4v_moe/modeling_glm4v_moe.py +++ b/src/transformers/models/glm4v_moe/modeling_glm4v_moe.py @@ -425,9 +425,6 @@ def _init_weights(self, module): elif isinstance(module, Glm4vMoeTextExperts): init.normal_(module.gate_up_proj, mean=0.0, std=self.config.initializer_range) init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range) - if isinstance(module, Glm4vMoeVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) @auto_docstring @@ -445,15 +442,69 @@ class Glm4vMoeCausalLMOutputWithPast(CausalLMOutputWithPast): class Glm4vMoeVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Glm4vMoeVisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Glm4vMoeVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) @use_kernel_forward_from_hub("RMSNorm") @@ -747,8 +798,7 @@ def __init__(self, config) -> None: self.embeddings = Glm4vMoeVisionEmbeddings(config) self.patch_embed = Glm4vMoeVisionPatchEmbed(config) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Glm4vMoeVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Glm4vMoeVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Glm4vMoeVisionBlock(config) for _ in range(config.depth)]) self.merger = Glm4vMoeVisionPatchMerger( @@ -787,9 +837,7 @@ def forward( hidden_states = self.patch_embed(hidden_states) hidden_states = self.post_conv_layernorm(hidden_states) - rotary_emb = self.rotary_pos_emb(position_ids) - emb = torch.cat((rotary_emb, rotary_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seqlens = cu_seqlens[1:] - cu_seqlens[:-1] hidden_states = self.embeddings( diff --git a/src/transformers/models/glm4v_moe/modular_glm4v_moe.py b/src/transformers/models/glm4v_moe/modular_glm4v_moe.py index 47db82c3c26c..d90e33397527 100644 --- a/src/transformers/models/glm4v_moe/modular_glm4v_moe.py +++ b/src/transformers/models/glm4v_moe/modular_glm4v_moe.py @@ -17,7 +17,6 @@ import torch.nn as nn from huggingface_hub.dataclasses import strict -from ... import initialization as init from ...cache_utils import Cache, DynamicCache from ...masking_utils import create_causal_mask from ...modeling_flash_attention_utils import FlashAttentionKwargs @@ -229,12 +228,6 @@ class Glm4vMoePreTrainedModel(Glm4MoePreTrainedModel): _skip_keys_device_placement = ["past_key_values"] _can_record_outputs = {} - def _init_weights(self, module): - super()._init_weights(module) - if isinstance(module, Glm4vMoeVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - class Glm4vMoeCausalLMOutputWithPast(Qwen3VLMoeCausalLMOutputWithPast): pass diff --git a/src/transformers/models/glm5_next/configuration_glm5_next.py b/src/transformers/models/glm5_next/configuration_glm5_next.py index 21b57bb5cc68..f9fcace029c0 100644 --- a/src/transformers/models/glm5_next/configuration_glm5_next.py +++ b/src/transformers/models/glm5_next/configuration_glm5_next.py @@ -242,6 +242,8 @@ class Glm5NextVisionConfig(PreTrainedConfig): model_type = "glm5_next_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 24 hidden_size: int = 1024 @@ -258,6 +260,7 @@ class Glm5NextVisionConfig(PreTrainedConfig): out_hidden_size: int = 1536 intermediate_size: int = 4096 initializer_range: float = 0.02 + rope_parameters: dict | None = None projection_intermediate_size: int = 10240 swiglu_limit: float = 10.0 diff --git a/src/transformers/models/glm5_next/modeling_glm5_next.py b/src/transformers/models/glm5_next/modeling_glm5_next.py index ba0551f62ad8..9ba825abc4cf 100644 --- a/src/transformers/models/glm5_next/modeling_glm5_next.py +++ b/src/transformers/models/glm5_next/modeling_glm5_next.py @@ -50,10 +50,12 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check +from ...utils.deprecation import deprecate_kwarg from ...utils.generic import ( accepts_precomputed_kwargs, get_max_seqlen, is_flash_attention_requested, + maybe_autocast, merge_with_config_defaults, ) from ...utils.output_capturing import OutputRecorder, capture_outputs @@ -1399,9 +1401,6 @@ def _init_weights(self, module): elif isinstance(module, Glm5NextTextIndexer): init.zeros_(module.index_kpool_compress_ape) init.ones_(module.index_kpool_compress_gate) - elif isinstance(module, Glm5NextVisionRotaryEmbedding): # noqa: F821 - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) # Do not inherit from DSv4 as it messes modular prefixes up for the PreTrainedModel @@ -1697,18 +1696,6 @@ def forward( return hidden_states -class Glm5NextVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: - super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) - self.inv_freq = nn.Buffer(inv_freq, persistent=False) - - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) - - class Glm5NextVisionPatchEmbed(nn.Module): def __init__(self, config: Glm5NextVisionConfig) -> None: super().__init__() @@ -1729,6 +1716,72 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return hidden_states +class Glm5NextVisionRotaryEmbedding(nn.Module): + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Glm5NextVisionConfig, device=None): + super().__init__() + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Glm5NextVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) + + @auto_docstring class Glm5NextVisionModel(Glm5NextPreTrainedModel): config: Glm5NextVisionConfig @@ -1745,8 +1798,7 @@ def __init__(self, config) -> None: self.patch_size = config.patch_size self.patch_embed = Glm5NextVisionPatchEmbed(config) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Glm5NextVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Glm5NextVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Glm5NextVisionBlock(config) for _ in range(config.depth)]) self.merger = Glm5NextVisionPatchMerger( dim=config.out_hidden_size, @@ -1787,9 +1839,7 @@ def forward( cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs) hidden_states = self.patch_embed(hidden_states) - rotary_emb = self.rotary_pos_emb(position_ids) - emb = torch.cat((rotary_emb, rotary_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) for blk in self.blocks: hidden_states = blk( diff --git a/src/transformers/models/glm5_next/modular_glm5_next.py b/src/transformers/models/glm5_next/modular_glm5_next.py index 96067aa59feb..1214d52c275a 100644 --- a/src/transformers/models/glm5_next/modular_glm5_next.py +++ b/src/transformers/models/glm5_next/modular_glm5_next.py @@ -1275,9 +1275,6 @@ def _init_weights(self, module): elif isinstance(module, Glm5NextTextIndexer): init.zeros_(module.index_kpool_compress_ape) init.ones_(module.index_kpool_compress_gate) - elif isinstance(module, Glm5NextVisionRotaryEmbedding): # noqa: F821 - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) # Do not inherit from DSv4 as it messes modular prefixes up for the PreTrainedModel diff --git a/src/transformers/models/glm_image/configuration_glm_image.py b/src/transformers/models/glm_image/configuration_glm_image.py index fcd302e35560..911e42a791a4 100644 --- a/src/transformers/models/glm_image/configuration_glm_image.py +++ b/src/transformers/models/glm_image/configuration_glm_image.py @@ -59,6 +59,8 @@ class GlmImageVisionConfig(PreTrainedConfig): model_type = "glm_image_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 40 hidden_size: int = 1536 diff --git a/src/transformers/models/glm_image/modeling_glm_image.py b/src/transformers/models/glm_image/modeling_glm_image.py index 3f5b5dd0407b..e15c727783ee 100644 --- a/src/transformers/models/glm_image/modeling_glm_image.py +++ b/src/transformers/models/glm_image/modeling_glm_image.py @@ -572,11 +572,11 @@ def __init__(self, config: GlmImageVisionConfig) -> None: self.embeddings = GlmImageVisionEmbeddings(config) self.patch_embed = GlmImageVisionPatchEmbed(config) - head_dim = config.hidden_size // config.num_heads - self.blocks = nn.ModuleList([GlmImageVisionBlock(config) for _ in range(config.depth)]) self.gradient_checkpointing = False + + head_dim = config.hidden_size // config.num_heads self.head_dim = head_dim self.post_init() diff --git a/src/transformers/models/glm_image/modular_glm_image.py b/src/transformers/models/glm_image/modular_glm_image.py index 4ab82395a292..a6d276aadda5 100644 --- a/src/transformers/models/glm_image/modular_glm_image.py +++ b/src/transformers/models/glm_image/modular_glm_image.py @@ -111,6 +111,7 @@ class GlmImageVisionConfig(Glm4vVisionConfig): out_hidden_size = AttributeError() rms_norm_eps = AttributeError() temporal_patch_size = AttributeError() + rope_parameters = AttributeError() @auto_docstring(checkpoint="zai-org/GLM-Image") @@ -341,9 +342,6 @@ class GlmImagePreTrainedModel(Glm4vPreTrainedModel): config: GlmImageConfig input_modalities = ("image", "text") - def _init_weights(self, module): - raise AttributeError("Normal super call") - class GlmImageModelOutputWithPast(Glm4vModelOutputWithPast): pass diff --git a/src/transformers/models/glm_ocr/configuration_glm_ocr.py b/src/transformers/models/glm_ocr/configuration_glm_ocr.py index e88d98b86964..52bc0d827d50 100644 --- a/src/transformers/models/glm_ocr/configuration_glm_ocr.py +++ b/src/transformers/models/glm_ocr/configuration_glm_ocr.py @@ -49,6 +49,8 @@ class GlmOcrVisionConfig(PreTrainedConfig): model_type = "glm_ocr_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 24 hidden_size: int = 1024 @@ -65,6 +67,7 @@ class GlmOcrVisionConfig(PreTrainedConfig): out_hidden_size: int = 1536 intermediate_size: int = 4096 initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="zai-org/GLM-OCR") diff --git a/src/transformers/models/glm_ocr/modeling_glm_ocr.py b/src/transformers/models/glm_ocr/modeling_glm_ocr.py index 65d239d60b77..5807b36ae46b 100644 --- a/src/transformers/models/glm_ocr/modeling_glm_ocr.py +++ b/src/transformers/models/glm_ocr/modeling_glm_ocr.py @@ -27,7 +27,6 @@ import torch.nn as nn from torch.nn import LayerNorm -from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...generation import GenerationMixin @@ -309,18 +308,6 @@ def forward( return hidden_states -class GlmOcrVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: - super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) - self.inv_freq = nn.Buffer(inv_freq, persistent=False) - - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) - - @auto_docstring class GlmOcrPreTrainedModel(PreTrainedModel): config: GlmOcrConfig @@ -336,12 +323,6 @@ class GlmOcrPreTrainedModel(PreTrainedModel): _supports_attention_backend = True _keys_to_ignore_on_load_unexpected = [r"model\.language_model\.layers\.16.*"] - def _init_weights(self, module): - super()._init_weights(module) - if isinstance(module, GlmOcrVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - @auto_docstring @dataclass @@ -531,6 +512,70 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return hidden_states +class GlmOcrVisionRotaryEmbedding(nn.Module): + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: GlmOcrVisionConfig, device=None): + super().__init__() + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters(config: GlmOcrVisionConfig, device=None, **kwargs) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) + + class GlmOcrVisionModel(GlmOcrPreTrainedModel): config: GlmOcrVisionConfig input_modalities = ("image", "video") @@ -546,8 +591,7 @@ def __init__(self, config) -> None: self.patch_size = config.patch_size self.patch_embed = GlmOcrVisionPatchEmbed(config) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = GlmOcrVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = GlmOcrVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([GlmOcrVisionBlock(config) for _ in range(config.depth)]) self.merger = GlmOcrVisionPatchMerger( @@ -588,9 +632,7 @@ def forward( cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs) hidden_states = self.patch_embed(hidden_states) - rotary_emb = self.rotary_pos_emb(position_ids) - emb = torch.cat((rotary_emb, rotary_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) for blk in self.blocks: hidden_states = blk( diff --git a/src/transformers/models/glm_ocr/modular_glm_ocr.py b/src/transformers/models/glm_ocr/modular_glm_ocr.py index 3c5a7b4134bd..cfb7506a6188 100644 --- a/src/transformers/models/glm_ocr/modular_glm_ocr.py +++ b/src/transformers/models/glm_ocr/modular_glm_ocr.py @@ -266,9 +266,7 @@ def forward( cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs) hidden_states = self.patch_embed(hidden_states) - rotary_emb = self.rotary_pos_emb(position_ids) - emb = torch.cat((rotary_emb, rotary_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) for blk in self.blocks: hidden_states = blk( diff --git a/src/transformers/models/idefics/configuration_idefics.py b/src/transformers/models/idefics/configuration_idefics.py index d95ee8dd1fa7..3a224673955d 100644 --- a/src/transformers/models/idefics/configuration_idefics.py +++ b/src/transformers/models/idefics/configuration_idefics.py @@ -150,7 +150,9 @@ class IdeficsConfig(PreTrainedConfig): freeze_vision_module_exceptions: list | tuple = () use_resampler: bool = False vision_config: dict | PreTrainedConfig | None = None + max_position_embeddings: int = 2048 perceiver_config: dict | PreTrainedConfig | None = None + rope_parameters: dict | None = None def __post_init__(self, **kwargs): if self.perceiver_config is None: diff --git a/src/transformers/models/idefics/modeling_idefics.py b/src/transformers/models/idefics/modeling_idefics.py index a1726d916a53..d02a4dc12883 100644 --- a/src/transformers/models/idefics/modeling_idefics.py +++ b/src/transformers/models/idefics/modeling_idefics.py @@ -30,13 +30,16 @@ from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...generation import GenerationMixin +from ...integrations import use_kernel_forward_from_hub from ...masking_utils import create_causal_mask from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import ModelOutput +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedConfig, PreTrainedModel from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging -from ...utils.generic import merge_with_config_defaults +from ...utils.deprecation import deprecate_kwarg +from ...utils.generic import maybe_autocast, merge_with_config_defaults from ...utils.output_capturing import OutputRecorder, capture_outputs from .configuration_idefics import IdeficsConfig from .perceiver import IdeficsPerceiverResampler @@ -353,46 +356,65 @@ def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" -# this was adapted from LlamaRotaryEmbedding -class IdeficsEmbedding(torch.nn.Module): - def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): +# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Idefics +class IdeficsRotaryEmbedding(nn.Module): + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: IdeficsConfig, device=None): super().__init__() + self.max_seq_len_cached = config.max_position_embeddings + self.original_max_seq_len = config.max_position_embeddings - self.dim = dim - self.max_position_embeddings = max_position_embeddings - self.base = base - inv_freq = 1.0 / ( - self.base - ** (torch.arange(0, self.dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / self.dim) - ) - self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.config = config - # Build here to make `torch.jit.trace` work. - self._set_cos_sin_cache( - seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype() - ) + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_default_rope_parameters + if self.rope_type != "default": + rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) - def _set_cos_sin_cache(self, seq_len, device, dtype): - self.max_seq_len_cached = seq_len - t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) - freqs = torch.einsum("i,j->ij", t, self.inv_freq) - # Different from paper, but it uses a different permutation in order to obtain the same calculation - emb = torch.cat((freqs, freqs), dim=-1) - self.cos_cached = nn.Buffer(emb.cos().to(dtype), persistent=False) - self.sin_cached = nn.Buffer(emb.sin().to(dtype), persistent=False) + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_default_rope_parameters(config: IdeficsConfig, device=None, **kwargs) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads - def forward(self, x, seq_len=None): - # x: [bs, num_attention_heads, seq_len, head_size] - if seq_len > self.max_seq_len_cached: - self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype) + attention_factor = 1.0 # Unused in this type of RoPE + # Compute the inverse frequencies + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + return inv_freq.to(device), attention_factor - return ( - self.cos_cached[:seq_len].to(dtype=x.dtype), - self.sin_cached[:seq_len].to(dtype=x.dtype), + @torch.no_grad() + @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) + def forward(self, x, position_ids): + inv_freq_expanded = ( + self.inv_freq[None, :, None].expand(position_ids.shape[0], -1, 1).to(dtype=torch.float, device=x.device) ) + position_ids_expanded = position_ids[:, None, :].float() + + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + # Disable any outside autocast context if any, to really force fp32 + with maybe_autocast(device_type=device_type, enabled=False): + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2) + emb = torch.cat((freqs, freqs), dim=-1) + cos = emb.cos() * self.attention_scaling + sin = emb.sin() * self.attention_scaling + + return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) +# Copied from transformers.models.llama.modeling_llama.rotate_half def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] @@ -400,7 +422,9 @@ def rotate_half(x): return torch.cat((-x2, x1), dim=-1) -def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): +@use_kernel_forward_from_hub("rotary_pos_emb") +# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb +def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: @@ -408,9 +432,6 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. - position_ids (`torch.Tensor`): - The position indices of the tokens corresponding to the query and key tensors. For example, this can be - used to pass offsetted position ids when working with a KV-cache. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note @@ -421,8 +442,8 @@ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ - cos = cos[position_ids].unsqueeze(unsqueeze_dim) - sin = sin[position_ids].unsqueeze(unsqueeze_dim) + cos = cos.unsqueeze(unsqueeze_dim) + sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed @@ -548,7 +569,7 @@ def __init__( hidden_size, bias=False, ) - self.rotary_emb = IdeficsEmbedding(self.head_dim) + self.rotary_emb = IdeficsRotaryEmbedding(config) # trf-ignore: TRF050 self.qk_layer_norms = qk_layer_norms if self.qk_layer_norms: @@ -588,8 +609,8 @@ def forward( kv_seq_len += past_key_values.get_seq_length() if not is_cross_attention: - cos, sin = self.rotary_emb(value_states, seq_len=max(kv_seq_len, q_len)) - query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + cos, sin = self.rotary_emb(value_states, position_ids) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) # [bsz, nh, t, hd] if past_key_values is not None: @@ -841,15 +862,6 @@ def _init_weights(self, module): init.normal_(module.alpha_dense, mean=0.0, std=self.config.alphas_initializer_range) elif isinstance(module, IdeficsPerceiverResampler): init.normal_(module.latents) - elif isinstance(module, IdeficsEmbedding): - inv_freq = 1.0 / (module.base ** (torch.arange(0, module.dim, 2) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - t = torch.arange(module.max_position_embeddings).type_as(inv_freq) - freqs = torch.einsum("i,j->ij", t, inv_freq) - # Different from paper, but it uses a different permutation in order to obtain the same calculation - emb = torch.cat((freqs, freqs), dim=-1) - init.copy_(module.cos_cached, emb.cos()) - init.copy_(module.sin_cached, emb.sin()) @auto_docstring diff --git a/src/transformers/models/kimi_k25/configuration_kimi_k25.py b/src/transformers/models/kimi_k25/configuration_kimi_k25.py index 28be752ce4c9..d8eb9a37333a 100644 --- a/src/transformers/models/kimi_k25/configuration_kimi_k25.py +++ b/src/transformers/models/kimi_k25/configuration_kimi_k25.py @@ -39,6 +39,7 @@ class Kimi_K25VisionConfig(PreTrainedConfig): """ model_type = "kimi_k25_vision" + default_rope_type = "axial" patch_size: int = 14 pos_emb_height: int = 64 @@ -50,8 +51,7 @@ class Kimi_K25VisionConfig(PreTrainedConfig): intermediate_size: int = 4304 hidden_act: str = "gelu_pytorch_tanh" merge_kernel_size: tuple[int, int] | list[int] = (2, 2) - rope_parameters: dict | None = None # defaults set by `RopeConfigMixin` - max_position_embeddings: int | None = None + rope_parameters: dict | None = None @auto_docstring(checkpoint="moonshotai/Kimi-K2.6") diff --git a/src/transformers/models/kimi_k25/modeling_kimi_k25.py b/src/transformers/models/kimi_k25/modeling_kimi_k25.py index ab774e31357a..55f847d9c161 100644 --- a/src/transformers/models/kimi_k25/modeling_kimi_k25.py +++ b/src/transformers/models/kimi_k25/modeling_kimi_k25.py @@ -29,17 +29,10 @@ from ...cache_utils import Cache from ...generation import GenerationMixin from ...modeling_layers import GradientCheckpointingLayer -from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling -from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, ModelOutput from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack -from ...utils import ( - ModelOutput, - TransformersKwargs, - auto_docstring, - can_return_tuple, - torch_compilable_check, -) +from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check from ...utils.deprecation import deprecate_kwarg from ...utils.generic import get_max_seqlen, is_flash_attention_requested, maybe_autocast from ...utils.output_capturing import capture_outputs @@ -183,18 +176,21 @@ def forward(self, pixel_values: torch.Tensor, grid_thw: torch.Tensor, **kwargs) class Kimi_K25VisionRotaryEmbedding(nn.Module): + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + @deprecate_kwarg("device", version="5.18") def __init__(self, config: Kimi_K25VisionConfig, device=None): super().__init__() - self.max_seq_len_cached = config.max_position_embeddings - self.original_max_seq_len = config.max_position_embeddings - self.config = config self.rope_type = self.config.rope_parameters["rope_type"] - rope_init_fn: Callable = self.compute_default_rope_parameters - if self.rope_type != "default": - rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") inv_freq, self.attention_scaling = rope_init_fn(self.config, device) self.inv_freq = nn.Buffer(inv_freq, persistent=False) @@ -202,7 +198,7 @@ def __init__(self, config: Kimi_K25VisionConfig, device=None): @staticmethod @deprecate_kwarg("device", version="5.18") - def compute_default_rope_parameters( + def compute_axial_rope_parameters( config: Kimi_K25VisionConfig, device=None, **kwargs ) -> tuple[torch.Tensor, float]: """ @@ -216,11 +212,6 @@ def compute_default_rope_parameters( """ base = config.rope_parameters["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads - - # The reference implementation computes RoPE frequencies INDEPENDENTLY - # for each spatial dimension using the partitioned head_dim (head_dim // ndim), - # so both x and y dimensions get identical frequency ranges. - # This is different from splitting the global inv_freq between dimensions. spatial_dim = dim // 2 attention_factor = 1.0 # Unused in this type of RoPE @@ -228,22 +219,27 @@ def compute_default_rope_parameters( return inv_freq.to(device), attention_factor @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): - position_ids_expanded = position_ids.transpose(0, 1)[..., None].float() # (positions, 2, 1) - inv_freq_expanded = ( - self.inv_freq[None, None, :].float().expand(position_ids_expanded.shape[0], 2, -1).to(x.device) - ) # (positions, 2, freq_dim) - + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" - with maybe_autocast(device_type=device_type, enabled=False): # Force float32 - freqs = (inv_freq_expanded.float() * position_ids_expanded.float()).transpose(1, 2).flatten(1) - emb = torch.cat([freqs, freqs], dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) return cos, sin + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + # interleave within the head dim for HW + freq_hw = freq.permute(1, 2, 0).flatten(1) + return torch.cat([freq_hw, freq_hw], dim=-1) + class Kimi_K25VisionMLP(nn.Module): def __init__(self, dim: int, hidden_dim: int, hidden_act: str) -> None: diff --git a/src/transformers/models/kimi_k25/modular_kimi_k25.py b/src/transformers/models/kimi_k25/modular_kimi_k25.py index fe63367febc5..f21cb376075c 100644 --- a/src/transformers/models/kimi_k25/modular_kimi_k25.py +++ b/src/transformers/models/kimi_k25/modular_kimi_k25.py @@ -33,7 +33,7 @@ logging, torch_compilable_check, ) -from ...utils.generic import get_max_seqlen, is_flash_attention_requested, maybe_autocast +from ...utils.generic import get_max_seqlen, is_flash_attention_requested from ...utils.output_capturing import capture_outputs from ...vision_utils import ( get_vision_attention_seqlens, @@ -41,8 +41,7 @@ get_vision_position_ids, ) from ..auto import CONFIG_MAPPING, AutoConfig, AutoModel -from ..gemma4.modeling_gemma4 import Gemma4VisionRotaryEmbedding -from ..glm4v.modeling_glm4v import Glm4vForConditionalGeneration +from ..glm4v.modeling_glm4v import Glm4vForConditionalGeneration, Glm4vVisionRotaryEmbedding from ..llava.modeling_llava import LlavaCausalLMOutputWithPast, LlavaModelOutputWithPast from ..qwen2_vl.modeling_qwen2_vl import ( Qwen2VLPreTrainedModel, @@ -119,6 +118,7 @@ class Kimi_K25VisionConfig(PreTrainedConfig): """ model_type = "kimi_k25_vision" + default_rope_type = "axial" patch_size: int = 14 pos_emb_height: int = 64 @@ -130,8 +130,7 @@ class Kimi_K25VisionConfig(PreTrainedConfig): intermediate_size: int = 4304 hidden_act: str = "gelu_pytorch_tanh" merge_kernel_size: tuple[int, int] | list[int] = (2, 2) - rope_parameters: dict | None = None # defaults set by `RopeConfigMixin` - max_position_embeddings: int | None = None + rope_parameters: dict | None = None @auto_docstring(checkpoint="moonshotai/Kimi-K2.6") @@ -246,23 +245,14 @@ def forward(self, pixel_values: torch.Tensor, grid_thw: torch.Tensor, **kwargs) return hidden_states -# Similarly to gemma4, applies the same freq to H and W grids -# The difference is that gemma4 stacks H/W embeds on `dim`, while Kimi interleaves them -class Kimi_K25VisionRotaryEmbedding(Gemma4VisionRotaryEmbedding): - def forward(self, x, position_ids): - position_ids_expanded = position_ids.transpose(0, 1)[..., None].float() # (positions, 2, 1) - inv_freq_expanded = ( - self.inv_freq[None, None, :].float().expand(position_ids_expanded.shape[0], 2, -1).to(x.device) - ) # (positions, 2, freq_dim) - - device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" - with maybe_autocast(device_type=device_type, enabled=False): # Force float32 - freqs = (inv_freq_expanded.float() * position_ids_expanded.float()).transpose(1, 2).flatten(1) - emb = torch.cat([freqs, freqs], dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling - - return cos, sin +class Kimi_K25VisionRotaryEmbedding(Glm4vVisionRotaryEmbedding): + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + # interleave within the head dim for HW + freq_hw = freq.permute(1, 2, 0).flatten(1) + return torch.cat([freq_hw, freq_hw], dim=-1) class Kimi_K25VisionMLP(VisionMlp): diff --git a/src/transformers/models/llama4/modeling_llama4.py b/src/transformers/models/llama4/modeling_llama4.py index 59a18f56c4d4..dbd3818f47ff 100644 --- a/src/transformers/models/llama4/modeling_llama4.py +++ b/src/transformers/models/llama4/modeling_llama4.py @@ -987,6 +987,7 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return hidden_states +# note: this is same axial rope as in Pixtral class Llama4VisionRotaryEmbedding(nn.Module): def __init__(self, config: Llama4VisionConfig): super().__init__() diff --git a/src/transformers/models/minimax_m3_vl/configuration_minimax_m3_vl.py b/src/transformers/models/minimax_m3_vl/configuration_minimax_m3_vl.py index d7493ad811b0..536d2c87d0fa 100644 --- a/src/transformers/models/minimax_m3_vl/configuration_minimax_m3_vl.py +++ b/src/transformers/models/minimax_m3_vl/configuration_minimax_m3_vl.py @@ -154,6 +154,7 @@ def __post_init__(self, **kwargs): self.mlp_layer_types = ["sparse"] * self.num_hidden_layers +# NOTE: can copy from qwen vision config! @auto_docstring(checkpoint="MiniMaxAI/MiniMax-M3") @strict class MiniMaxM3VLVisionConfig(PreTrainedConfig): @@ -164,6 +165,7 @@ class MiniMaxM3VLVisionConfig(PreTrainedConfig): model_type = "minimax_m3_vl_vision" base_config_key = "vision_config" + default_rope_type = "axial" default_theta = 10000.0 hidden_size: int = 1280 diff --git a/src/transformers/models/minimax_m3_vl/modeling_minimax_m3_vl.py b/src/transformers/models/minimax_m3_vl/modeling_minimax_m3_vl.py index 75e39fa9f6c2..37ab0ef46bcf 100644 --- a/src/transformers/models/minimax_m3_vl/modeling_minimax_m3_vl.py +++ b/src/transformers/models/minimax_m3_vl/modeling_minimax_m3_vl.py @@ -992,48 +992,70 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return hidden_states -class MiniMaxM3VL3DRotaryEmbedding(nn.Module): - r"""3D RoPE for the vision tower: each patch is rotated by its `(T, H, W)` grid position. +class MiniMaxM3VLVisionRotaryEmbedding(nn.Module): + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ - `2 * (head_dim // 2)` rotary dims are split evenly across the three axes (each rounded - down to a multiple of 2), giving `axis_dim` dims per axis and `axis_dim // 2` frequencies:: + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: MiniMaxM3VLVisionConfig, device=None): + super().__init__() + self.config = config - |<------------------ rotated (3 * axis_dim) ------------------>|<- pass ->| - +--------------------+--------------------+--------------------+----------+ - | T (frames) | H (rows) | W (cols) | | - | axis_dim | axis_dim | axis_dim | | - +--------------------+--------------------+--------------------+----------+ + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) - Each axis' coordinate scales its own band of frequencies; the bands are concatenated as - `T|H|W` and duplicated via `cat([f, f])` to pair with the half-rotation in - `apply_rotary_pos_emb_vision`. Any head dims past `3 * axis_dim` are left unrotated. - """ + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) - def __init__(self, head_dim: int, theta: float = 10000.0, spatial_merge_size: int = 1): - super().__init__() - # `2 * (head_dim // 2)` rotary dims are split evenly across T/H/W, each axis rounded - # down to a multiple of 2. With head_dim=80 that is 26 dims/axis (39 freqs total); the - # remaining `head_dim - 3 * axis_dim` dims are never rotated (they pass through). - rope_dims = 2 * (head_dim // 2) - self.axis_dim = 2 * ((rope_dims // 3) // 2) - self.spatial_merge_size = spatial_merge_size - self.theta = theta + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: MiniMaxM3VLVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 - def forward( - self, - grid_thw: torch.Tensor, - device: torch.device, - dtype: torch.dtype, - kwargs: dict | None = None, - ) -> tuple[torch.Tensor, torch.Tensor]: - coords = get_vision_position_ids(grid_thw, self.spatial_merge_size, include_temporal=True, kwargs=kwargs) - coords = coords.to(device=device, dtype=torch.float32) - inv_freq = 1.0 / ( - self.theta ** (torch.arange(0, self.axis_dim, 2, dtype=torch.float32, device=device) / self.axis_dim) - ) - freqs = (coords.unsqueeze(-1) * inv_freq).reshape(coords.shape[0], -1) - emb = torch.cat([freqs, freqs], dim=-1) - return emb.cos().to(dtype), emb.sin().to(dtype) + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos.to(x.dtype), sin.to(x.dtype) + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) def apply_rotary_pos_emb_vision( @@ -1172,10 +1194,7 @@ def __init__(self, config: MiniMaxM3VLVisionConfig): self.embeddings = MiniMaxM3VLVisionEmbeddings(config) self.pre_layrnorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.layers = nn.ModuleList([MiniMaxM3VLVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)]) - head_dim = config.hidden_size // config.num_attention_heads - self.rotary_emb = MiniMaxM3VL3DRotaryEmbedding( - head_dim, theta=config.rope_parameters["rope_theta"], spatial_merge_size=config.spatial_merge_size - ) + self.rotary_emb = MiniMaxM3VLVisionRotaryEmbedding(config) self.post_init() @merge_with_config_defaults @@ -1190,10 +1209,15 @@ def forward( The temporal, height and width of feature shape of each image. """ embeds = self.embeddings(pixel_values).to(self.pre_layrnorm.weight.dtype) - cos, sin = self.rotary_emb(grid_thw, device=embeds.device, dtype=embeds.dtype, kwargs=kwargs) + position_ids = get_vision_position_ids( + grid_thw, self.config.spatial_merge_size, include_temporal=True, kwargs=kwargs + ) + position_embeddings = self.rotary_emb(embeds, position_ids) hidden_states = self.pre_layrnorm(embeds).unsqueeze(0) for layer in self.layers: - hidden_states = layer(hidden_states, attention_mask=None, position_embeddings=(cos, sin), **kwargs) + hidden_states = layer( + hidden_states, attention_mask=None, position_embeddings=position_embeddings, **kwargs + ) return BaseModelOutputWithPooling(last_hidden_state=hidden_states, pooler_output=hidden_states[:, 0]) diff --git a/src/transformers/models/minimax_m3_vl/modular_minimax_m3_vl.py b/src/transformers/models/minimax_m3_vl/modular_minimax_m3_vl.py index b18f41dde2d2..fe42d0eb75fa 100644 --- a/src/transformers/models/minimax_m3_vl/modular_minimax_m3_vl.py +++ b/src/transformers/models/minimax_m3_vl/modular_minimax_m3_vl.py @@ -32,7 +32,7 @@ from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, logging, torch_compilable_check from ...utils.deprecation import deprecate_kwarg -from ...utils.generic import can_return_tuple, merge_with_config_defaults +from ...utils.generic import can_return_tuple, maybe_autocast, merge_with_config_defaults from ...utils.import_utils import is_torchdynamo_compiling from ...utils.output_capturing import capture_outputs from ...vision_utils import get_vision_position_ids @@ -59,7 +59,7 @@ apply_rotary_pos_emb, ) from ..mixtral.modeling_mixtral import MixtralDecoderLayer -from ..qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VisionPatchEmbed +from ..qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VisionPatchEmbed, Qwen2_5_VLVisionRotaryEmbedding from ..qwen2_vl.image_processing_qwen2_vl import Qwen2VLImageProcessor, Qwen2VLImageProcessorKwargs from ..qwen2_vl.processing_qwen2_vl import Qwen2VLProcessor, Qwen2VLProcessorKwargs @@ -163,6 +163,7 @@ def __post_init__(self, **kwargs): self.mlp_layer_types = ["sparse"] * self.num_hidden_layers +# NOTE: can copy from qwen vision config! @auto_docstring(checkpoint="MiniMaxAI/MiniMax-M3") @strict class MiniMaxM3VLVisionConfig(PreTrainedConfig): @@ -173,6 +174,7 @@ class MiniMaxM3VLVisionConfig(PreTrainedConfig): model_type = "minimax_m3_vl_vision" base_config_key = "vision_config" + default_rope_type = "axial" default_theta = 10000.0 hidden_size: int = 1280 @@ -745,48 +747,19 @@ def __init__(self, config) -> None: ) -class MiniMaxM3VL3DRotaryEmbedding(nn.Module): - r"""3D RoPE for the vision tower: each patch is rotated by its `(T, H, W)` grid position. +class MiniMaxM3VLVisionRotaryEmbedding(Qwen2_5_VLVisionRotaryEmbedding): + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling - `2 * (head_dim // 2)` rotary dims are split evenly across the three axes (each rounded - down to a multiple of 2), giving `axis_dim` dims per axis and `axis_dim // 2` frequencies:: - - |<------------------ rotated (3 * axis_dim) ------------------>|<- pass ->| - +--------------------+--------------------+--------------------+----------+ - | T (frames) | H (rows) | W (cols) | | - | axis_dim | axis_dim | axis_dim | | - +--------------------+--------------------+--------------------+----------+ - - Each axis' coordinate scales its own band of frequencies; the bands are concatenated as - `T|H|W` and duplicated via `cat([f, f])` to pair with the half-rotation in - `apply_rotary_pos_emb_vision`. Any head dims past `3 * axis_dim` are left unrotated. - """ - - def __init__(self, head_dim: int, theta: float = 10000.0, spatial_merge_size: int = 1): - super().__init__() - # `2 * (head_dim // 2)` rotary dims are split evenly across T/H/W, each axis rounded - # down to a multiple of 2. With head_dim=80 that is 26 dims/axis (39 freqs total); the - # remaining `head_dim - 3 * axis_dim` dims are never rotated (they pass through). - rope_dims = 2 * (head_dim // 2) - self.axis_dim = 2 * ((rope_dims // 3) // 2) - self.spatial_merge_size = spatial_merge_size - self.theta = theta - - def forward( - self, - grid_thw: torch.Tensor, - device: torch.device, - dtype: torch.dtype, - kwargs: dict | None = None, - ) -> tuple[torch.Tensor, torch.Tensor]: - coords = get_vision_position_ids(grid_thw, self.spatial_merge_size, include_temporal=True, kwargs=kwargs) - coords = coords.to(device=device, dtype=torch.float32) - inv_freq = 1.0 / ( - self.theta ** (torch.arange(0, self.axis_dim, 2, dtype=torch.float32, device=device) / self.axis_dim) - ) - freqs = (coords.unsqueeze(-1) * inv_freq).reshape(coords.shape[0], -1) - emb = torch.cat([freqs, freqs], dim=-1) - return emb.cos().to(dtype), emb.sin().to(dtype) + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos.to(x.dtype), sin.to(x.dtype) def rotate_half(x): @@ -883,10 +856,7 @@ def __init__(self, config: MiniMaxM3VLVisionConfig): self.embeddings = MiniMaxM3VLVisionEmbeddings(config) self.pre_layrnorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.layers = nn.ModuleList([MiniMaxM3VLVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)]) - head_dim = config.hidden_size // config.num_attention_heads - self.rotary_emb = MiniMaxM3VL3DRotaryEmbedding( - head_dim, theta=config.rope_parameters["rope_theta"], spatial_merge_size=config.spatial_merge_size - ) + self.rotary_emb = MiniMaxM3VLVisionRotaryEmbedding(config) self.post_init() @merge_with_config_defaults @@ -901,10 +871,15 @@ def forward( The temporal, height and width of feature shape of each image. """ embeds = self.embeddings(pixel_values).to(self.pre_layrnorm.weight.dtype) - cos, sin = self.rotary_emb(grid_thw, device=embeds.device, dtype=embeds.dtype, kwargs=kwargs) + position_ids = get_vision_position_ids( + grid_thw, self.config.spatial_merge_size, include_temporal=True, kwargs=kwargs + ) + position_embeddings = self.rotary_emb(embeds, position_ids) hidden_states = self.pre_layrnorm(embeds).unsqueeze(0) for layer in self.layers: - hidden_states = layer(hidden_states, attention_mask=None, position_embeddings=(cos, sin), **kwargs) + hidden_states = layer( + hidden_states, attention_mask=None, position_embeddings=position_embeddings, **kwargs + ) return BaseModelOutputWithPooling(last_hidden_state=hidden_states, pooler_output=hidden_states[:, 0]) diff --git a/src/transformers/models/mlcd/configuration_mlcd.py b/src/transformers/models/mlcd/configuration_mlcd.py index 9bfdc3c9ea03..35025b840240 100644 --- a/src/transformers/models/mlcd/configuration_mlcd.py +++ b/src/transformers/models/mlcd/configuration_mlcd.py @@ -47,6 +47,7 @@ class MLCDVisionConfig(PreTrainedConfig): model_type = "mlcd_vision_model" base_config_key = "vision_config" + default_rope_type = "axial" hidden_size: int = 1664 intermediate_size: int = 8192 @@ -61,6 +62,7 @@ class MLCDVisionConfig(PreTrainedConfig): attention_dropout: float | int = 0.0 initializer_range: float = 0.02 initializer_factor: float = 1.0 + rope_parameters: dict | None = None __all__ = ["MLCDVisionConfig"] diff --git a/src/transformers/models/mlcd/modeling_mlcd.py b/src/transformers/models/mlcd/modeling_mlcd.py index f8cf406dbe93..3ddb8cac1fc7 100644 --- a/src/transformers/models/mlcd/modeling_mlcd.py +++ b/src/transformers/models/mlcd/modeling_mlcd.py @@ -29,7 +29,8 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, torch_int -from ...utils.generic import merge_with_config_defaults +from ...utils.deprecation import deprecate_kwarg +from ...utils.generic import maybe_autocast, merge_with_config_defaults from ...utils.output_capturing import capture_outputs from .configuration_mlcd import MLCDVisionConfig @@ -50,15 +51,67 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: class MLCDRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: MLCDVisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters(config: MLCDVisionConfig, device=None, **kwargs) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) class MLCDVisionEmbeddings(nn.Module): @@ -409,9 +462,6 @@ def _init_weights(self, module): factor = self.config.initializer_factor pos_emb_std = (module.config.hidden_size // module.config.num_attention_heads // 2) ** -0.5 * factor init.normal_(module.class_pos_emb, mean=0.0, std=pos_emb_std) - elif isinstance(module, MLCDRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) @auto_docstring( @@ -433,7 +483,7 @@ def __init__(self, config: MLCDVisionConfig): self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) self.encoder = MLCDEncoder(config) self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) - self.vision_rotary_embedding = MLCDRotaryEmbedding(config.hidden_size // config.num_attention_heads // 2) + self.vision_rotary_embedding = MLCDRotaryEmbedding(config) self.class_pos_emb = nn.Parameter(torch.randn(1, config.hidden_size // config.num_attention_heads // 2)) self.post_init() @@ -472,6 +522,9 @@ def forward( if pixel_values is None: raise ValueError("You have to specify pixel_values") + hidden_states = self.embeddings(pixel_values) + hidden_states = self.pre_layrnorm(hidden_states) + num_patches_height = pixel_values.shape[-2] // self.config.patch_size num_patches_width = pixel_values.shape[-1] // self.config.patch_size hpos_ids = ( @@ -481,13 +534,12 @@ def forward( torch.arange(num_patches_width, device=pixel_values.device).unsqueeze(0).expand(num_patches_height, -1) ) pos_ids = torch.stack([hpos_ids.flatten(), wpos_ids.flatten()], dim=-1) - rotary_pos_emb = self.vision_rotary_embedding(pos_ids) - rotary_pos_emb = torch.cat([self.class_pos_emb, rotary_pos_emb], dim=0) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) - - hidden_states = self.embeddings(pixel_values) - hidden_states = self.pre_layrnorm(hidden_states) + position_embeddings = self.vision_rotary_embedding(hidden_states, pos_ids) + class_pos_emb = torch.cat([self.class_pos_emb, self.class_pos_emb], dim=-1) + position_embeddings = [ + torch.cat([class_pos_emb.cos(), position_embeddings[0]], dim=0), + torch.cat([class_pos_emb.sin(), position_embeddings[1]], dim=0), + ] encoder_outputs = self.encoder( inputs_embeds=hidden_states, diff --git a/src/transformers/models/mlcd/modular_mlcd.py b/src/transformers/models/mlcd/modular_mlcd.py index 99102f3b2a6a..a7a5f32f62d1 100644 --- a/src/transformers/models/mlcd/modular_mlcd.py +++ b/src/transformers/models/mlcd/modular_mlcd.py @@ -32,7 +32,7 @@ CLIPVisionModel, ) from ..llama.modeling_llama import eager_attention_forward -from ..qwen2_vl.modeling_qwen2_vl import VisionRotaryEmbedding, apply_rotary_pos_emb_vision +from ..qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLVisionRotaryEmbedding, apply_rotary_pos_emb_vision logger = logging.get_logger(__name__) @@ -62,6 +62,7 @@ class MLCDVisionConfig(PreTrainedConfig): model_type = "mlcd_vision_model" base_config_key = "vision_config" + default_rope_type = "axial" hidden_size: int = 1664 intermediate_size: int = 8192 @@ -76,13 +77,14 @@ class MLCDVisionConfig(PreTrainedConfig): attention_dropout: float | int = 0.0 initializer_range: float = 0.02 initializer_factor: float = 1.0 + rope_parameters: dict | None = None class MLCDMLP(CLIPMLP): pass -class MLCDRotaryEmbedding(VisionRotaryEmbedding): +class MLCDRotaryEmbedding(Qwen2_5_VLVisionRotaryEmbedding): pass @@ -299,15 +301,12 @@ def _init_weights(self, module): factor = self.config.initializer_factor pos_emb_std = (module.config.hidden_size // module.config.num_attention_heads // 2) ** -0.5 * factor init.normal_(module.class_pos_emb, mean=0.0, std=pos_emb_std) - elif isinstance(module, MLCDRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class MLCDVisionModel(CLIPVisionModel): def __init__(self, config: MLCDVisionConfig): super().__init__(config) - self.vision_rotary_embedding = MLCDRotaryEmbedding(config.hidden_size // config.num_attention_heads // 2) + self.vision_rotary_embedding = MLCDRotaryEmbedding(config) self.class_pos_emb = nn.Parameter(torch.randn(1, config.hidden_size // config.num_attention_heads // 2)) def forward( @@ -342,6 +341,9 @@ def forward( if pixel_values is None: raise ValueError("You have to specify pixel_values") + hidden_states = self.embeddings(pixel_values) + hidden_states = self.pre_layrnorm(hidden_states) + num_patches_height = pixel_values.shape[-2] // self.config.patch_size num_patches_width = pixel_values.shape[-1] // self.config.patch_size hpos_ids = ( @@ -351,13 +353,12 @@ def forward( torch.arange(num_patches_width, device=pixel_values.device).unsqueeze(0).expand(num_patches_height, -1) ) pos_ids = torch.stack([hpos_ids.flatten(), wpos_ids.flatten()], dim=-1) - rotary_pos_emb = self.vision_rotary_embedding(pos_ids) - rotary_pos_emb = torch.cat([self.class_pos_emb, rotary_pos_emb], dim=0) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) - - hidden_states = self.embeddings(pixel_values) - hidden_states = self.pre_layrnorm(hidden_states) + position_embeddings = self.vision_rotary_embedding(hidden_states, pos_ids) + class_pos_emb = torch.cat([self.class_pos_emb, self.class_pos_emb], dim=-1) + position_embeddings = [ + torch.cat([class_pos_emb.cos(), position_embeddings[0]], dim=0), + torch.cat([class_pos_emb.sin(), position_embeddings[1]], dim=0), + ] encoder_outputs = self.encoder( inputs_embeds=hidden_states, diff --git a/src/transformers/models/muse_glimmer/configuration_muse_glimmer.py b/src/transformers/models/muse_glimmer/configuration_muse_glimmer.py index 597d1253a2a0..94070f2c3aaa 100644 --- a/src/transformers/models/muse_glimmer/configuration_muse_glimmer.py +++ b/src/transformers/models/muse_glimmer/configuration_muse_glimmer.py @@ -42,6 +42,7 @@ class MuseGlimmerVisionConfig(PreTrainedConfig): """ model_type = "muse_glimmer_vision" + default_rope_type = "axial" patch_size: int = 14 pos_emb_height: int = 32 @@ -52,8 +53,7 @@ class MuseGlimmerVisionConfig(PreTrainedConfig): hidden_size: int = 1536 intermediate_size: int = 8960 hidden_act: str = "gelu" - rope_parameters: dict | None = None # defaults set by `RopeConfigMixin` - max_position_embeddings: int = 32 * 32 # == `pos_h * pos_w` + rope_parameters: dict | None = None base_model_tp_plan = { "patch_embedder.patch_embedding": "colwise_gather_output", "layers.*.attn.q_proj": "colwise", @@ -65,6 +65,7 @@ class MuseGlimmerVisionConfig(PreTrainedConfig): } patch_temporal: int = 2 merge_size: int = 2 + max_position_embeddings: int = 32 * 32 # == `pos_h * pos_w` layer_norm_eps: float = 1e-05 layer_types: list[str] | None = None diff --git a/src/transformers/models/muse_glimmer/modeling_muse_glimmer.py b/src/transformers/models/muse_glimmer/modeling_muse_glimmer.py index 453ec247ff10..bbe097d2720d 100644 --- a/src/transformers/models/muse_glimmer/modeling_muse_glimmer.py +++ b/src/transformers/models/muse_glimmer/modeling_muse_glimmer.py @@ -720,18 +720,21 @@ def forward( class MuseGlimmerVisionRotaryEmbedding(nn.Module): + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + @deprecate_kwarg("device", version="5.18") def __init__(self, config: MuseGlimmerVisionConfig, device=None): super().__init__() - self.max_seq_len_cached = config.max_position_embeddings - self.original_max_seq_len = config.max_position_embeddings - self.config = config self.rope_type = self.config.rope_parameters["rope_type"] - rope_init_fn: Callable = self.compute_default_rope_parameters - if self.rope_type != "default": - rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") inv_freq, self.attention_scaling = rope_init_fn(self.config, device) self.inv_freq = nn.Buffer(inv_freq, persistent=False) @@ -739,7 +742,7 @@ def __init__(self, config: MuseGlimmerVisionConfig, device=None): @staticmethod @deprecate_kwarg("device", version="5.18") - def compute_default_rope_parameters( + def compute_axial_rope_parameters( config: MuseGlimmerVisionConfig, device=None, **kwargs ) -> tuple[torch.Tensor, float]: """ @@ -753,11 +756,6 @@ def compute_default_rope_parameters( """ base = config.rope_parameters["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads - - # The reference implementation computes RoPE frequencies INDEPENDENTLY - # for each spatial dimension using the partitioned head_dim (head_dim // ndim), - # so both x and y dimensions get identical frequency ranges. - # This is different from splitting the global inv_freq between dimensions. spatial_dim = dim // 2 attention_factor = 1.0 # Unused in this type of RoPE @@ -765,22 +763,26 @@ def compute_default_rope_parameters( return inv_freq.to(device), attention_factor @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): - # We interleave as `[freq_w, freq_h, freq_w, freq_h]` in MuseGlimmer - inv_freq = self.inv_freq.to(device=x.device, dtype=torch.float32) - w_ids = position_ids[:, 0].float() # position_ids: (seq, 2), unbatched - h_ids = position_ids[:, 1].float() - + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): - freq_w = w_ids[:, None] * inv_freq[None, :] - freq_h = h_ids[:, None] * inv_freq[None, :] - freq = torch.cat([freq_w, freq_h, freq_w, freq_h], dim=-1) - cos = freq.cos() * self.attention_scaling - sin = freq.sin() * self.attention_scaling + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling - return cos.to(x.dtype), sin.to(x.dtype) + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) def get_vision_pixel_shuffle_index( diff --git a/src/transformers/models/muse_glimmer/modular_muse_glimmer.py b/src/transformers/models/muse_glimmer/modular_muse_glimmer.py index b5973eb2d19c..e6db2f0737c9 100644 --- a/src/transformers/models/muse_glimmer/modular_muse_glimmer.py +++ b/src/transformers/models/muse_glimmer/modular_muse_glimmer.py @@ -35,10 +35,7 @@ from ...processing_utils import Unpack, VideosKwargs from ...utils import TensorType, TransformersKwargs, auto_docstring, logging from ...utils.constants import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD -from ...utils.generic import ( - maybe_autocast, - merge_with_config_defaults, -) +from ...utils.generic import maybe_autocast, merge_with_config_defaults from ...utils.output_capturing import capture_outputs from ...video_processing_utils import BaseVideoProcessor from ...video_utils import VideoMetadata, group_videos_by_shape, reorder_videos @@ -60,7 +57,7 @@ apply_rotary_pos_emb, ) from ..gemma3.modeling_gemma3 import Gemma3CausalLMOutputWithPast, Gemma3ModelOutputWithPast -from ..gemma4.modeling_gemma4 import Gemma4RMSNorm, Gemma4VisionRotaryEmbedding +from ..gemma4.modeling_gemma4 import Gemma4RMSNorm from ..glm4v.image_processing_glm4v import Glm4vImageProcessor, Glm4vImageProcessorKwargs from ..kimi_k25.configuration_kimi_k25 import Kimi_K25VisionConfig from ..kimi_k25.modeling_kimi_k25 import ( @@ -72,6 +69,7 @@ ) from ..llama.modeling_llama import eager_attention_forward from ..paddleocr_vl.modeling_paddleocr_vl import PaddleOCRVisionEmbeddings +from ..qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLVisionRotaryEmbedding logger = logging.get_logger(__name__) @@ -946,22 +944,19 @@ def forward( return embeddings -class MuseGlimmerVisionRotaryEmbedding(Gemma4VisionRotaryEmbedding): +class MuseGlimmerVisionRotaryEmbedding(Qwen2_5_VLVisionRotaryEmbedding): def forward(self, x, position_ids): - # We interleave as `[freq_w, freq_h, freq_w, freq_h]` in MuseGlimmer - inv_freq = self.inv_freq.to(device=x.device, dtype=torch.float32) - w_ids = position_ids[:, 0].float() # position_ids: (seq, 2), unbatched - h_ids = position_ids[:, 1].float() - + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): - freq_w = w_ids[:, None] * inv_freq[None, :] - freq_h = h_ids[:, None] * inv_freq[None, :] - freq = torch.cat([freq_w, freq_h, freq_w, freq_h], dim=-1) - cos = freq.cos() * self.attention_scaling - sin = freq.sin() * self.attention_scaling + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling - return cos.to(x.dtype), sin.to(x.dtype) + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) def get_vision_pixel_shuffle_index( diff --git a/src/transformers/models/neomme/modeling_neomme.py b/src/transformers/models/neomme/modeling_neomme.py index 0eaf5ebb1feb..34afdeea2d6e 100644 --- a/src/transformers/models/neomme/modeling_neomme.py +++ b/src/transformers/models/neomme/modeling_neomme.py @@ -143,24 +143,36 @@ def compute_default_rope_parameters( return inv_freq.to(device), attention_factor @torch.no_grad() - @dynamic_rope_update + @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward( self, x: torch.Tensor, position_ids: torch.LongTensor, layer_type: str | None = None ) -> tuple[torch.Tensor, torch.Tensor]: - """Build cos/sin from two-axis `position_ids` of shape `(2, batch, seq_len)`.""" - # Same axias 2D rope as in Qwen-VIT models, all will be standardized by @raushan - inv_freq = getattr(self, f"{layer_type}_inv_freq") # (rotary_dim // 2,) + inv_freq = getattr(self, f"{layer_type}_inv_freq") attention_scaling = getattr(self, f"{layer_type}_attention_scaling") + inv_freq_expanded = inv_freq[None, None, :, None].float().expand(2, position_ids.shape[1], -1, 1) + position_ids_expanded = position_ids[:, :, None, :].float() # (2, batch, 1, seq_len) + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): - row_angles = position_ids[0].float().unsqueeze(-1) * inv_freq[0::2] - column_angles = position_ids[1].float().unsqueeze(-1) * inv_freq[1::2] + # (2, batch, seq_len, rotary_dim // 2) + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(2, 3) + cos = freqs.cos() * attention_scaling + sin = freqs.sin() * attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos.to(x.dtype), sin.to(x.dtype) - angles = torch.stack([row_angles, column_angles], dim=-1).flatten(-2) - cos = (angles.cos() * attention_scaling).to(x.dtype) - sin = (angles.sin() * attention_scaling).to(x.dtype) - return torch.cat([cos, cos], dim=-1), torch.cat([sin, sin], dim=-1) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + # in contrast to the H-H-W-W layout, row/col here interleave as row0-col0-row1-col1 + # i.e. `mrope_section = [head_dim//4, head_dim//4]` + freq_row, freq_col = freq[0][..., 0::2], freq[1][..., 1::2] + angles = torch.stack([freq_row, freq_col], dim=-1).flatten(-2) + return torch.cat([angles, angles], dim=-1) def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: diff --git a/src/transformers/models/neomme/modular_neomme.py b/src/transformers/models/neomme/modular_neomme.py index 015bb769785f..407ebc731968 100644 --- a/src/transformers/models/neomme/modular_neomme.py +++ b/src/transformers/models/neomme/modular_neomme.py @@ -30,7 +30,7 @@ from ...masking_utils import create_bidirectional_mask, create_bidirectional_sliding_window_mask from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, MaskedLMOutput -from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import ImagesKwargs, Unpack from ...utils import ( @@ -283,25 +283,35 @@ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor: class NeoMMERotaryEmbedding(LagunaRotaryEmbedding): """Two-axis interleaved M-RoPE with per-layer-type frequency spectra.""" - @torch.no_grad() - @dynamic_rope_update def forward( self, x: torch.Tensor, position_ids: torch.LongTensor, layer_type: str | None = None ) -> tuple[torch.Tensor, torch.Tensor]: - """Build cos/sin from two-axis `position_ids` of shape `(2, batch, seq_len)`.""" - # Same axias 2D rope as in Qwen-VIT models, all will be standardized by @raushan - inv_freq = getattr(self, f"{layer_type}_inv_freq") # (rotary_dim // 2,) + inv_freq = getattr(self, f"{layer_type}_inv_freq") attention_scaling = getattr(self, f"{layer_type}_attention_scaling") + inv_freq_expanded = inv_freq[None, None, :, None].float().expand(2, position_ids.shape[1], -1, 1) + position_ids_expanded = position_ids[:, :, None, :].float() # (2, batch, 1, seq_len) + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): - row_angles = position_ids[0].float().unsqueeze(-1) * inv_freq[0::2] - column_angles = position_ids[1].float().unsqueeze(-1) * inv_freq[1::2] + # (2, batch, seq_len, rotary_dim // 2) + freqs = (inv_freq_expanded @ position_ids_expanded).transpose(2, 3) + cos = freqs.cos() * attention_scaling + sin = freqs.sin() * attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos.to(x.dtype), sin.to(x.dtype) - angles = torch.stack([row_angles, column_angles], dim=-1).flatten(-2) - cos = (angles.cos() * attention_scaling).to(x.dtype) - sin = (angles.sin() * attention_scaling).to(x.dtype) - return torch.cat([cos, cos], dim=-1), torch.cat([sin, sin], dim=-1) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + # in contrast to the H-H-W-W layout, row/col here interleave as row0-col0-row1-col1 + # i.e. `mrope_section = [head_dim//4, head_dim//4]` + freq_row, freq_col = freq[0][..., 0::2], freq[1][..., 1::2] + angles = torch.stack([freq_row, freq_col], dim=-1).flatten(-2) + return torch.cat([angles, angles], dim=-1) class NeoMMEExclusiveSelfAttention(nn.Module): diff --git a/src/transformers/models/paddleocr_vl/configuration_paddleocr_vl.py b/src/transformers/models/paddleocr_vl/configuration_paddleocr_vl.py index c5f95b799e34..defc0ee3b172 100644 --- a/src/transformers/models/paddleocr_vl/configuration_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/configuration_paddleocr_vl.py @@ -65,7 +65,9 @@ class PaddleOCRVisionConfig(PreTrainedConfig): hidden_act: str = "gelu_pytorch_tanh" layer_norm_eps: float = 1e-6 attention_dropout: float | int = 0.0 + default_rope_type = "axial" spatial_merge_size: int = 2 + rope_parameters: dict | None = None @auto_docstring(checkpoint="PaddlePaddle/PaddleOCR-VL") diff --git a/src/transformers/models/paddleocr_vl/modeling_paddleocr_vl.py b/src/transformers/models/paddleocr_vl/modeling_paddleocr_vl.py index 50109e0c6dcd..df432b358aa0 100644 --- a/src/transformers/models/paddleocr_vl/modeling_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/modeling_paddleocr_vl.py @@ -35,7 +35,7 @@ from ...activations import ACT2FN, GELUActivation from ...cache_utils import Cache, DynamicCache from ...generation import GenerationMixin -from ...integrations import use_kernel_forward_from_hub +from ...integrations import use_kernel_forward_from_hub, use_kernelized_func from ...masking_utils import create_bidirectional_mask, create_causal_mask from ...modeling_flash_attention_utils import FlashAttentionKwargs from ...modeling_layers import GradientCheckpointingLayer @@ -106,15 +106,69 @@ def forward(self, image_features: torch.Tensor, image_grid_thw: torch.Tensor) -> class PaddleOCRVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: PaddleOCRVisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: PaddleOCRVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) class PaddleOCRRotaryEmbedding(nn.Module): @@ -134,6 +188,7 @@ def __init__(self, config: PaddleOCRVLConfig, device=None): self.inv_freq = nn.Buffer(inv_freq, persistent=False) self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + self.mrope_section = config.rope_parameters.get("mrope_section", [16, 24, 24]) @staticmethod @deprecate_kwarg("device", version="5.18") @@ -157,7 +212,6 @@ def compute_default_rope_parameters( inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq.to(device), attention_factor - # Ignore copy def forward(self, x, position_ids): # In contrast to other models, PaddleOCR has different position ids for the grids # So we expand the inv_freq to shape (3, ...) @@ -167,12 +221,20 @@ def forward(self, x, position_ids): device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq = torch.cat([m[i % 3] for i, m in enumerate(freq.split(self.mrope_section, dim=-1))], dim=-1) + return torch.cat((freq, freq), dim=-1) + class PaddleOCRMLP(nn.Module): def __init__(self, config: PaddleOCRTextConfig): @@ -235,28 +297,15 @@ def rotate_half(x): return torch.cat((-x2, x1), dim=-1) -def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1): - """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/). - - Explanation: - Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding - sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For - vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately. - Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding. - For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal, - height and width) of text embedding is always the same, so the text embedding rotary position embedding has no - difference with modern LLMs. +@use_kernel_forward_from_hub("rotary_pos_emb") +def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. - position_ids (`torch.Tensor`): - The position indices of the tokens corresponding to the query and key tensors. For example, this can be - used to pass offsetted position ids when working with a KV-cache. - mrope_section(`List(int)`): - Multimodal rope section is for channel dimension of temporal, height and width in rope calculation. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note @@ -267,19 +316,14 @@ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ - mrope_section = mrope_section * 2 - cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze( - unsqueeze_dim - ) - sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze( - unsqueeze_dim - ) - + cos = cos.unsqueeze(unsqueeze_dim) + sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed +@use_kernelized_func(apply_rotary_pos_emb) class PaddleOCRAttention(nn.Module): """ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer @@ -320,8 +364,6 @@ def forward( attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, - output_attentions: bool = False, - use_cache: bool = False, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]: @@ -336,9 +378,7 @@ def forward( value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) cos, sin = position_embeddings - query_states, key_states = apply_multimodal_rotary_pos_emb( - query_states, key_states, cos, sin, self.config.rope_parameters["mrope_section"] - ) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) @@ -452,9 +492,6 @@ def _init_weights(self, module): super()._init_weights(module) if isinstance(module, PaddleOCRVisionEmbeddings): init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1))) - elif isinstance(module, PaddleOCRVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) @auto_docstring @@ -789,10 +826,7 @@ def __init__(self, config: PaddleOCRVisionConfig): self.config = config self.layers = nn.ModuleList([PaddleOCRVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False - embed_dim = config.hidden_size - num_heads = config.num_attention_heads - head_dim = embed_dim // num_heads - self.rotary_pos_emb = PaddleOCRVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = PaddleOCRVisionRotaryEmbedding(config) # Ignore copy @can_return_tuple @@ -825,9 +859,7 @@ def forward( inputs_embeds=inputs_embeds, attention_mask=attention_mask, ) - rotary_embeddings = self.rotary_pos_emb(position_ids) - rotary_embeddings = rotary_embeddings.repeat(1, 2) - position_embeddings = (rotary_embeddings.cos(), rotary_embeddings.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) for encoder_layer in self.layers: hidden_states = encoder_layer( diff --git a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py index 50f0eaee3f7f..27798ff27549 100644 --- a/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py +++ b/src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py @@ -61,6 +61,7 @@ from ..qwen2_5_omni.modeling_qwen2_5_omni import ( Qwen2_5OmniAttention, ) +from ..qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLVisionRotaryEmbedding from ..qwen2_vl.configuration_qwen2_vl import Qwen2VLConfig from ..qwen2_vl.modeling_qwen2_vl import ( Qwen2VLCausalLMOutputWithPast, @@ -68,7 +69,6 @@ Qwen2VLModel, Qwen2VLModelOutputWithPast, Qwen2VLRotaryEmbedding, - VisionRotaryEmbedding, ) from ..siglip.configuration_siglip import SiglipVisionConfig from ..siglip.modeling_siglip import ( @@ -273,6 +273,7 @@ class PaddleOCRVisionConfig(SiglipVisionConfig): model_type = "paddleocr_vl_vision" base_config_key = "vision_config" + default_rope_type = "axial" hidden_size: int = 1152 intermediate_size: int = 4304 @@ -281,6 +282,7 @@ class PaddleOCRVisionConfig(SiglipVisionConfig): image_size: int = 384 patch_size: int = 14 spatial_merge_size: int = 2 + rope_parameters: dict | None = None @auto_docstring(checkpoint="PaddlePaddle/PaddleOCR-VL") @@ -353,7 +355,7 @@ def forward(self, image_features: torch.Tensor, image_grid_thw: torch.Tensor) -> return torch.cat(processed_features, dim=0) -class PaddleOCRVisionRotaryEmbedding(VisionRotaryEmbedding): +class PaddleOCRVisionRotaryEmbedding(Qwen2_5_VLVisionRotaryEmbedding): pass @@ -409,9 +411,6 @@ def _init_weights(self, module): super()._init_weights(module) if isinstance(module, PaddleOCRVisionEmbeddings): init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1))) - elif isinstance(module, PaddleOCRVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class PaddleOCRTextModel(PaddleOCRVLPreTrainedModel, Ernie4_5Model): @@ -545,10 +544,7 @@ def __init__(self, config: PaddleOCRVisionConfig): class PaddleOCRVisionEncoder(VideoLlama3VisionEncoder): def __init__(self, config: PaddleOCRVisionConfig): super().__init__() - embed_dim = config.hidden_size - num_heads = config.num_attention_heads - head_dim = embed_dim // num_heads - self.rotary_pos_emb = PaddleOCRVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = PaddleOCRVisionRotaryEmbedding(config) @can_return_tuple @auto_docstring @@ -580,9 +576,7 @@ def forward( inputs_embeds=inputs_embeds, attention_mask=attention_mask, ) - rotary_embeddings = self.rotary_pos_emb(position_ids) - rotary_embeddings = rotary_embeddings.repeat(1, 2) - position_embeddings = (rotary_embeddings.cos(), rotary_embeddings.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) for encoder_layer in self.layers: hidden_states = encoder_layer( diff --git a/src/transformers/models/pixtral/configuration_pixtral.py b/src/transformers/models/pixtral/configuration_pixtral.py index 095425e4054b..07055411cfc5 100644 --- a/src/transformers/models/pixtral/configuration_pixtral.py +++ b/src/transformers/models/pixtral/configuration_pixtral.py @@ -56,5 +56,7 @@ def __post_init__(self, **kwargs): self.head_dim = self.hidden_size // self.num_attention_heads super().__post_init__(**kwargs) + default_rope_type = "axial" + __all__ = ["PixtralVisionConfig"] diff --git a/src/transformers/models/pixtral/modeling_pixtral.py b/src/transformers/models/pixtral/modeling_pixtral.py index 2b9d70ed55ba..9fa025b67591 100644 --- a/src/transformers/models/pixtral/modeling_pixtral.py +++ b/src/transformers/models/pixtral/modeling_pixtral.py @@ -19,9 +19,9 @@ from torch import nn from ...activations import ACT2FN +from ...integrations import use_kernel_forward_from_hub, use_kernelized_func from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutput -from ...modeling_rope_utils import dynamic_rope_update from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, logging @@ -34,52 +34,35 @@ logger = logging.get_logger(__name__) -def position_ids_in_meshgrid(patch_embeds_list, max_width): - positions = [] - for patch in patch_embeds_list: - height, width = patch.shape[-2:] - mesh = torch.meshgrid(torch.arange(height), torch.arange(width), indexing="ij") - h_grid, v_grid = torch.stack(mesh, dim=-1).reshape(-1, 2).chunk(2, -1) - ids = h_grid * max_width + v_grid - positions.append(ids[:, 0]) - return torch.cat(positions) - - -class PixtralRotaryEmbedding(nn.Module): +# Adapted from transformers.models.gemma4.modeling_gemma4.Gemma4VisionRotaryEmbedding with interleaved freqs +class PixtralVisionRotaryEmbedding(nn.Module): """ - The key with pixtral embedding is just that you have a frequency for each pixel positions. - If you have height x width pixels (or embedding pixels), then the frequency used for ROPE - is given by indexing the pre_computed frequency on the width and height. - - What you output is of dimension (batch, height * width, dim) with dim the embed dim. - - This simply means that for each image hidden state, you are going to add - a corresponding positional embedding, based on its index in the grid. + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. """ @deprecate_kwarg("device", version="5.18") def __init__(self, config: PixtralVisionConfig, device=None): super().__init__() - self.config = config + self.rope_type = self.config.rope_parameters["rope_type"] - rope_init_fn: Callable = self.compute_default_rope_parameters - if self.rope_type != "default": - raise ValueError( - f"{self.__class__.__name__} does not support non-default RoPE, but got `rope_type={self.rope_type}`" - ) + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) - inv_freq, attention_scaling = rope_init_fn(self.config, device) self.inv_freq = nn.Buffer(inv_freq, persistent=False) self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) @staticmethod @deprecate_kwarg("device", version="5.18") - def compute_default_rope_parameters( + def compute_axial_rope_parameters( config: PixtralVisionConfig, device=None, **kwargs ) -> tuple[torch.Tensor, float]: """ - Computes the inverse frequencies according to the original RoPE implementation + Computes the inverse frequencies according to the axial RoPE implementation Args: config ([`~transformers.PreTrainedConfig`]): The model configuration. @@ -92,38 +75,34 @@ def compute_default_rope_parameters( attention_factor = 1.0 # Unused in this type of RoPE - # Here is the diff from Llama RoPE - max_patches_per_side = config.image_size // config.patch_size - h = torch.arange(max_patches_per_side) - w = torch.arange(max_patches_per_side) - - freqs = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim)) - freqs_h = torch.outer(h, freqs[::2]).float() - freqs_w = torch.outer(w, freqs[1::2]).float() - inv_freq = torch.cat( - [ - freqs_h[:, None, :].repeat(1, max_patches_per_side, 1), - freqs_w[None, :, :].repeat(max_patches_per_side, 1, 1), - ], - dim=-1, - ).reshape(-1, dim // 2) # we reshape to only index on the position indexes, not tuple of indexes - # Different from paper, but it uses a different permutation in order to obtain the same calculation - - # TODO maybe make it torch compatible later on. We can also just slice - inv_freq = torch.cat((inv_freq, inv_freq), dim=-1) - return inv_freq.to(device), attention_factor + inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + inv_freq_2d = torch.cat([inv_freq[0::2], inv_freq[1::2]]) + + return inv_freq_2d.to(device), attention_factor @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): - freqs = self.inv_freq[position_ids] + inv_freq_expanded = self.inv_freq[None, ...].float() + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" - with maybe_autocast(device_type=device_type, enabled=False): # Force float32 - emb = freqs - cos = emb.cos() - sin = emb.sin() + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded @ inv_freq_expanded + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos.to(x.dtype), sin.to(x.dtype) - return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + # block-concat grids as H-W-H-W + freq_h, freq_w = (m[:, i % 2] for i, m in enumerate(freq.chunk(2, dim=-1))) + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) # Copied from transformers.models.llama.modeling_llama.rotate_half @@ -134,6 +113,8 @@ def rotate_half(x): return torch.cat((-x2, x1), dim=-1) +@use_kernel_forward_from_hub("rotary_pos_emb") +# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. @@ -183,6 +164,7 @@ def eager_attention_forward( return attn_output, attn_weights +@use_kernelized_func(apply_rotary_pos_emb) class PixtralAttention(nn.Module): """ Multi-headed attention compatible with ALL_ATTENTION_FUNCTIONS. @@ -419,7 +401,7 @@ def __init__(self, config): self.patch_size = config.patch_size self.ln_pre = PixtralRMSNorm(config.hidden_size, eps=1e-5) self.transformer = PixtralTransformer(config) - self.patch_positional_embedding = PixtralRotaryEmbedding(config) + self.patch_positional_embedding = PixtralVisionRotaryEmbedding(config) self.post_init() @@ -451,12 +433,16 @@ def forward( patch_embeds = torch.cat([p.flatten(1).T for p in patch_embeds_list], dim=0).unsqueeze(0) patch_embeds = self.ln_pre(patch_embeds) - # positional embeddings - position_ids = position_ids_in_meshgrid( - patch_embeds_list, max_width=self.config.image_size // self.config.patch_size - ) - kwargs["position_ids"] = position_ids.unsqueeze(0).to(patch_embeds.device, non_blocking=True) - + # Create 2D positions for axial rotations + position_ids = [] + for patch in patch_embeds_list: + hpos_ids, wpos_ids = torch.meshgrid( + torch.arange(patch.shape[-2], device=patch.device), + torch.arange(patch.shape[-1], device=patch.device), + indexing="ij", + ) + position_ids.append(torch.stack([hpos_ids.flatten(), wpos_ids.flatten()], dim=-1)) + position_ids = torch.cat(position_ids, dim=0) position_embeddings = self.patch_positional_embedding(patch_embeds, position_ids) if is_flash_attention_requested(self.config): @@ -471,6 +457,7 @@ def forward( patch_embeds, attention_mask=attention_mask, position_embeddings=position_embeddings, + position_ids=position_ids, **kwargs, ) diff --git a/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py b/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py index 1d0e460b9fd0..a83a3721b347 100644 --- a/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py +++ b/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py @@ -76,7 +76,7 @@ class PPDocLayoutV2PositionRelationEmbedding(nn.Module): inv_freq: torch.Tensor @deprecate_kwarg("device", version="5.18") - def __init__(self, config, device=None): + def __init__(self, config: PPDocLayoutV2Config, device=None): super().__init__() self.config = config self.embed_dim = config.relation_bias_embed_dim diff --git a/src/transformers/models/pp_doclayout_v2/modular_pp_doclayout_v2.py b/src/transformers/models/pp_doclayout_v2/modular_pp_doclayout_v2.py index 802a82d98040..5366546ce1d2 100644 --- a/src/transformers/models/pp_doclayout_v2/modular_pp_doclayout_v2.py +++ b/src/transformers/models/pp_doclayout_v2/modular_pp_doclayout_v2.py @@ -383,7 +383,7 @@ class PPDocLayoutV2PositionRelationEmbedding(nn.Module): inv_freq: torch.Tensor @deprecate_kwarg("device", version="5.18") - def __init__(self, config, device=None): + def __init__(self, config: PPDocLayoutV2Config, device=None): super().__init__() self.config = config self.embed_dim = config.relation_bias_embed_dim diff --git a/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py b/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py index 081823bf222f..b33e7ec1de31 100644 --- a/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py +++ b/src/transformers/models/qwen2_5_omni/configuration_qwen2_5_omni.py @@ -56,6 +56,8 @@ class Qwen2_5OmniVisionEncoderConfig(PreTrainedConfig): model_type = "qwen2_5_omni_vision_encoder" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 32 hidden_size: int = 3584 @@ -70,6 +72,7 @@ class Qwen2_5OmniVisionEncoderConfig(PreTrainedConfig): out_hidden_size: int = 3584 fullatt_block_indexes: list[int] | tuple[int, ...] = (7, 15, 23, 31) initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="Qwen/Qwen2.5-Omni-7B") diff --git a/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py b/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py index 6b74915c8bae..0ddf66222dfa 100644 --- a/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py +++ b/src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py @@ -34,7 +34,7 @@ from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...generation import GenerationMixin -from ...integrations import use_kernel_forward_from_hub +from ...integrations import use_kernel_forward_from_hub, use_kernelized_func from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask from ...modeling_flash_attention_utils import FlashAttentionKwargs from ...modeling_layers import GradientCheckpointingLayer @@ -152,9 +152,6 @@ def _init_weights(self, module): elif isinstance(module, Qwen2_5OmniDownSample1d): filter_tensor = kaiser_sinc_filter1d(module.cutoff, module.half_width, module.kernel_size) init.copy_(module.filter, filter_tensor) - elif isinstance(module, Qwen2_5_VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class Qwen2_5OmniPreTrainedModelForConditionalGeneration(Qwen2_5OmniPreTrainedModel): @@ -930,6 +927,72 @@ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor): return input_lengths, output_lengths +class Qwen2_5OmniVisionRotaryEmbedding(nn.Module): + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Qwen2_5OmniVisionEncoderConfig, device=None): + super().__init__() + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Qwen2_5OmniVisionEncoderConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) + + def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] @@ -937,16 +1000,18 @@ def rotate_half(x): return torch.cat((-x2, x1), dim=-1) -def apply_rotary_pos_emb_vision(tensor: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor: - orig_dtype = tensor.dtype - tensor = tensor.float() - cos = freqs.cos() - sin = freqs.sin() - cos = cos.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float() - sin = sin.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float() - output = (tensor * cos) + (rotate_half(tensor) * sin) - output = output.to(orig_dtype) - return output +def apply_rotary_pos_emb_vision( + q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor +) -> tuple[torch.Tensor, torch.Tensor]: + orig_q_dtype = q.dtype + orig_k_dtype = k.dtype + q, k = q.float(), k.float() + cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float() + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + q_embed = q_embed.to(orig_q_dtype) + k_embed = k_embed.to(orig_k_dtype) + return q_embed, k_embed class Qwen2_5OmniVisionAttention(nn.Module): @@ -979,8 +1044,8 @@ def forward( key_states = self.k(hidden_states).reshape(seq_length, self.num_heads, -1) value_states = self.v(hidden_states).reshape(seq_length, self.num_heads, -1) - query_states = apply_rotary_pos_emb_vision(query_states.unsqueeze(0), position_embeddings).squeeze(0) - key_states = apply_rotary_pos_emb_vision(key_states.unsqueeze(0), position_embeddings).squeeze(0) + cos, sin = position_embeddings + query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin) query_states = query_states.transpose(0, 1).unsqueeze(0) key_states = key_states.transpose(0, 1).unsqueeze(0) @@ -1101,18 +1166,6 @@ def forward( return hidden_states -class Qwen2_5_VisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: - super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) - self.inv_freq = nn.Buffer(inv_freq, persistent=False) - - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) - - class Qwen2_5_VisionPatchEmbed(nn.Module): def __init__( self, @@ -1180,8 +1233,7 @@ def __init__(self, config: Qwen2_5OmniVisionEncoderConfig, *inputs, **kwargs) -> embed_dim=config.hidden_size, ) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Qwen2_5_VisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Qwen2_5OmniVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Qwen2_5OmniVisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen2_5OmniPatchMerger( dim=config.out_hidden_size, @@ -1192,6 +1244,12 @@ def __init__(self, config: Qwen2_5OmniVisionEncoderConfig, *inputs, **kwargs) -> self.post_init() + def permute_input_for_window_attn(self, input_tensor: torch.Tensor, window_index: torch.Tensor, seq_len: int): + input_tensor = input_tensor.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) + input_tensor = input_tensor[window_index, :, :] + input_tensor = input_tensor.reshape(seq_len, -1) + return input_tensor + @merge_with_config_defaults @capture_outputs def forward( @@ -1222,16 +1280,14 @@ def forward( hidden_states = self.patch_embed(hidden_states) - seq_len, _ = hidden_states.size() reverse_indices = torch.argsort(window_index) - hidden_states = hidden_states.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) - hidden_states = hidden_states[window_index, :, :] - hidden_states = hidden_states.reshape(seq_len, -1) + seq_len, _ = hidden_states.size() + hidden_states = self.permute_input_for_window_attn(hidden_states, window_index, seq_len=seq_len) - rotary_pos_emb = self.rotary_pos_emb(position_ids) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) - rotary_pos_emb = rotary_pos_emb[window_index, :, :] - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) + position_embeddings = tuple( + self.permute_input_for_window_attn(freq, window_index, seq_len=seq_len) for freq in position_embeddings + ) # Modification here for layer_num, blk in enumerate(self.blocks): @@ -1246,7 +1302,7 @@ def forward( hidden_states, cu_seqlens=cu_seqlens_now, max_seqlen=max_seqlen_now, - position_embeddings=rotary_pos_emb, + position_embeddings=position_embeddings, **kwargs, ) @@ -1276,6 +1332,7 @@ def __init__(self, config: Qwen2_5OmniConfig, device=None): self.inv_freq = nn.Buffer(inv_freq, persistent=False) self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + self.mrope_section = config.rope_parameters.get("mrope_section", [16, 24, 24]) @staticmethod @deprecate_kwarg("device", version="5.18") @@ -1299,7 +1356,6 @@ def compute_default_rope_parameters( inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq.to(device), attention_factor - # Ignore copy def forward(self, x, position_ids): # In contrast to other models, Qwen2_5Omni has different position ids for the grids # So we expand the inv_freq to shape (3, ...) @@ -1309,35 +1365,30 @@ def forward(self, x, position_ids): device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq = torch.cat([m[i % 3] for i, m in enumerate(freq.split(self.mrope_section, dim=-1))], dim=-1) + return torch.cat((freq, freq), dim=-1) -def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1): - """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/). - Explanation: - Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding - sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For - vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately. - Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding. - For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal, - height and width) of text embedding is always the same, so the text embedding rotary position embedding has no - difference with modern LLMs. +@use_kernel_forward_from_hub("rotary_pos_emb") +def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. - position_ids (`torch.Tensor`): - The position indices of the tokens corresponding to the query and key tensors. For example, this can be - used to pass offsetted position ids when working with a KV-cache. - mrope_section(`List(int)`): - Multimodal rope section is for channel dimension of temporal, height and width in rope calculation. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note @@ -1348,19 +1399,14 @@ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ - mrope_section = mrope_section * 2 - cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze( - unsqueeze_dim - ) - sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze( - unsqueeze_dim - ) - + cos = cos.unsqueeze(unsqueeze_dim) + sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed +@use_kernelized_func(apply_rotary_pos_emb) class Qwen2_5OmniAttention(nn.Module): """ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer @@ -1401,8 +1447,6 @@ def forward( attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, - output_attentions: bool = False, - use_cache: bool = False, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]: @@ -1417,9 +1461,7 @@ def forward( value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) cos, sin = position_embeddings - query_states, key_states = apply_multimodal_rotary_pos_emb( - query_states, key_states, cos, sin, self.config.rope_parameters["mrope_section"] - ) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) @@ -2844,32 +2886,6 @@ def forward(self, hidden_states): return hidden_states -@use_kernel_forward_from_hub("rotary_pos_emb") -def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): - """Applies Rotary Position Embedding to the query and key tensors. - - Args: - q (`torch.Tensor`): The query tensor. - k (`torch.Tensor`): The key tensor. - cos (`torch.Tensor`): The cosine part of the rotary embedding. - sin (`torch.Tensor`): The sine part of the rotary embedding. - unsqueeze_dim (`int`, *optional*, defaults to 1): - The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and - sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note - that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and - k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes - cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have - the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. - Returns: - `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. - """ - cos = cos.unsqueeze(unsqueeze_dim) - sin = sin.unsqueeze(unsqueeze_dim) - q_embed = (q * cos) + (rotate_half(q) * sin) - k_embed = (k * cos) + (rotate_half(k) * sin) - return q_embed, k_embed - - def deinterleave_head_dim(x: torch.Tensor) -> torch.Tensor: """Reorder the head dim from interleaved RoPE layout `(x0, x1, x2, x3, ...)` to the standard half-split layout `(x0, x2, ..., x1, x3, ...)` so the kernelized `apply_rotary_pos_emb` can be used. diff --git a/src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py b/src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py index 9d65d3d7c034..92c6d5b649a3 100644 --- a/src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py +++ b/src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py @@ -56,16 +56,17 @@ get_vision_position_ids, get_vision_window_index, ) -from ..llama.modeling_llama import LlamaRotaryEmbedding, apply_rotary_pos_emb, rotate_half +from ..llama.modeling_llama import LlamaRotaryEmbedding, apply_rotary_pos_emb from ..qwen2_5_vl.configuration_qwen2_5_vl import Qwen2_5_VLVisionConfig from ..qwen2_5_vl.modeling_qwen2_5_vl import ( - Qwen2_5_VisionRotaryEmbedding, Qwen2_5_VisionTransformerPretrainedModel, Qwen2_5_VLAttention, Qwen2_5_VLMLP, Qwen2_5_VLPreTrainedModel, Qwen2_5_VLTextModel, Qwen2_5_VLVisionBlock, + Qwen2_5_VLVisionRotaryEmbedding, + apply_rotary_pos_emb_vision, eager_attention_forward, ) from ..qwen2_audio.configuration_qwen2_audio import Qwen2AudioEncoderConfig @@ -776,9 +777,6 @@ def _init_weights(self, module): elif isinstance(module, Qwen2_5OmniDownSample1d): filter_tensor = kaiser_sinc_filter1d(module.cutoff, module.half_width, module.kernel_size) init.copy_(module.filter, filter_tensor) - elif isinstance(module, Qwen2_5_VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class Qwen2_5OmniPreTrainedModelForConditionalGeneration(Qwen2_5OmniPreTrainedModel): @@ -1410,16 +1408,14 @@ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor): return input_lengths, output_lengths -def apply_rotary_pos_emb_vision(tensor: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor: - orig_dtype = tensor.dtype - tensor = tensor.float() - cos = freqs.cos() - sin = freqs.sin() - cos = cos.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float() - sin = sin.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float() - output = (tensor * cos) + (rotate_half(tensor) * sin) - output = output.to(orig_dtype) - return output +class Qwen2_5OmniVisionRotaryEmbedding(Qwen2_5_VLVisionRotaryEmbedding): + def __init__(self, config: Qwen2_5OmniVisionEncoderConfig, device=None): + super().__init__(config, device=device) + + def compute_axial_rope_parameters( + config: Qwen2_5OmniVisionEncoderConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + return super().compute_axial_rope_parameters(config, device=device, *kwargs) class Qwen2_5OmniVisionAttention(nn.Module): @@ -1452,8 +1448,8 @@ def forward( key_states = self.k(hidden_states).reshape(seq_length, self.num_heads, -1) value_states = self.v(hidden_states).reshape(seq_length, self.num_heads, -1) - query_states = apply_rotary_pos_emb_vision(query_states.unsqueeze(0), position_embeddings).squeeze(0) - key_states = apply_rotary_pos_emb_vision(key_states.unsqueeze(0), position_embeddings).squeeze(0) + cos, sin = position_embeddings + query_states, key_states = apply_rotary_pos_emb_vision(query_states, key_states, cos, sin) query_states = query_states.transpose(0, 1).unsqueeze(0) key_states = key_states.transpose(0, 1).unsqueeze(0) @@ -1532,10 +1528,6 @@ def forward( return hidden_states -class Qwen2_5_VisionRotaryEmbedding(Qwen2_5_VisionRotaryEmbedding): - pass - - class Qwen2_5OmniVisionEncoder(Qwen2_5_VisionTransformerPretrainedModel): config: Qwen2_5OmniVisionEncoderConfig input_modalities = ("image", "video") @@ -1550,6 +1542,12 @@ def __init__(self, config: Qwen2_5OmniVisionEncoderConfig, *inputs, **kwargs) -> super().__init__(config, *inputs, **kwargs) self.blocks = nn.ModuleList([Qwen2_5OmniVisionBlock(config) for _ in range(config.depth)]) + def permute_input_for_window_attn(self, input_tensor: torch.Tensor, window_index: torch.Tensor, seq_len: int): + input_tensor = input_tensor.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) + input_tensor = input_tensor[window_index, :, :] + input_tensor = input_tensor.reshape(seq_len, -1) + return input_tensor + @merge_with_config_defaults @capture_outputs def forward( @@ -1580,16 +1578,14 @@ def forward( hidden_states = self.patch_embed(hidden_states) - seq_len, _ = hidden_states.size() reverse_indices = torch.argsort(window_index) - hidden_states = hidden_states.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) - hidden_states = hidden_states[window_index, :, :] - hidden_states = hidden_states.reshape(seq_len, -1) + seq_len, _ = hidden_states.size() + hidden_states = self.permute_input_for_window_attn(hidden_states, window_index, seq_len=seq_len) - rotary_pos_emb = self.rotary_pos_emb(position_ids) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) - rotary_pos_emb = rotary_pos_emb[window_index, :, :] - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) + position_embeddings = tuple( + self.permute_input_for_window_attn(freq, window_index, seq_len=seq_len) for freq in position_embeddings + ) # Modification here for layer_num, blk in enumerate(self.blocks): @@ -1604,7 +1600,7 @@ def forward( hidden_states, cu_seqlens=cu_seqlens_now, max_seqlen=max_seqlen_now, - position_embeddings=rotary_pos_emb, + position_embeddings=position_embeddings, **kwargs, ) diff --git a/src/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py b/src/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py index 16fec33739e6..2aeae3a6ebef 100644 --- a/src/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py +++ b/src/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py @@ -47,6 +47,8 @@ class Qwen2_5_VLVisionConfig(PreTrainedConfig): model_type = "qwen2_5_vl_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 32 hidden_size: int = 3584 @@ -62,6 +64,7 @@ class Qwen2_5_VLVisionConfig(PreTrainedConfig): out_hidden_size: int = 3584 fullatt_block_indexes: list[int] | tuple[int, ...] = (7, 15, 23, 31) initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="Qwen/Qwen2-VL-7B-Instruct") diff --git a/src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py b/src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py index 4557b08f217e..8267ffe8b746 100644 --- a/src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +++ b/src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py @@ -31,11 +31,10 @@ import torch import torch.nn as nn -from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...generation import GenerationMixin -from ...integrations import use_kernel_forward_from_hub +from ...integrations import use_kernel_forward_from_hub, use_kernelized_func from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask from ...modeling_flash_attention_utils import FlashAttentionKwargs from ...modeling_layers import GradientCheckpointingLayer @@ -121,16 +120,70 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: return hidden_states -class Qwen2_5_VisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: +class Qwen2_5_VLVisionRotaryEmbedding(nn.Module): + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Qwen2_5_VLVisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Qwen2_5_VLVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) class Qwen2_5_VLPatchMerger(nn.Module): @@ -334,12 +387,6 @@ class Qwen2_5_VLPreTrainedModel(PreTrainedModel): _can_compile_fullgraph = True _supports_attention_backend = True - def _init_weights(self, module): - super()._init_weights(module) - if isinstance(module, Qwen2_5_VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - class Qwen2_5_VisionTransformerPretrainedModel(Qwen2_5_VLPreTrainedModel): config: Qwen2_5_VLVisionConfig @@ -365,8 +412,7 @@ def __init__(self, config, *inputs, **kwargs) -> None: embed_dim=config.hidden_size, ) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Qwen2_5_VisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Qwen2_5_VLVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Qwen2_5_VLVisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen2_5_VLPatchMerger( @@ -378,6 +424,12 @@ def __init__(self, config, *inputs, **kwargs) -> None: self.post_init() + def permute_input_for_window_attn(self, input_tensor: torch.Tensor, window_index: torch.Tensor, seq_len: int): + input_tensor = input_tensor.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) + input_tensor = input_tensor[window_index, :, :] + input_tensor = input_tensor.reshape(seq_len, -1) + return input_tensor + @merge_with_config_defaults @capture_outputs def forward( @@ -409,16 +461,12 @@ def forward( hidden_states = self.patch_embed(hidden_states) seq_len, _ = hidden_states.size() - hidden_states = hidden_states.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) - hidden_states = hidden_states[window_index, :, :] - hidden_states = hidden_states.reshape(seq_len, -1) + hidden_states = self.permute_input_for_window_attn(hidden_states, window_index, seq_len=seq_len) - rotary_pos_emb = self.rotary_pos_emb(position_ids) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) - rotary_pos_emb = rotary_pos_emb[window_index, :, :] - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) + position_embeddings = tuple( + self.permute_input_for_window_attn(freq, window_index, seq_len=seq_len) for freq in position_embeddings + ) for layer_num, blk in enumerate(self.blocks): if layer_num in self.fullatt_block_indexes: @@ -475,6 +523,7 @@ def __init__(self, config: Qwen2_5_VLConfig, device=None): self.inv_freq = nn.Buffer(inv_freq, persistent=False) self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + self.mrope_section = config.rope_parameters.get("mrope_section", [16, 24, 24]) @staticmethod @deprecate_kwarg("device", version="5.18") @@ -496,7 +545,6 @@ def compute_default_rope_parameters(config: Qwen2_5_VLConfig, device=None, **kwa inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq.to(device), attention_factor - # Ignore copy def forward(self, x, position_ids): # In contrast to other models, Qwen2_5_VL has different position ids for the grids # So we expand the inv_freq to shape (3, ...) @@ -506,12 +554,20 @@ def forward(self, x, position_ids): device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq = torch.cat([m[i % 3] for i, m in enumerate(freq.split(self.mrope_section, dim=-1))], dim=-1) + return torch.cat((freq, freq), dim=-1) + class Qwen2MLP(nn.Module): def __init__(self, config): @@ -529,28 +585,15 @@ def forward(self, x): return down_proj -def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1): - """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/). - - Explanation: - Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding - sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For - vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately. - Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding. - For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal, - height and width) of text embedding is always the same, so the text embedding rotary position embedding has no - difference with modern LLMs. +@use_kernel_forward_from_hub("rotary_pos_emb") +def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. - position_ids (`torch.Tensor`): - The position indices of the tokens corresponding to the query and key tensors. For example, this can be - used to pass offsetted position ids when working with a KV-cache. - mrope_section(`List(int)`): - Multimodal rope section is for channel dimension of temporal, height and width in rope calculation. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note @@ -561,19 +604,14 @@ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ - mrope_section = mrope_section * 2 - cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze( - unsqueeze_dim - ) - sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze( - unsqueeze_dim - ) - + cos = cos.unsqueeze(unsqueeze_dim) + sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed +@use_kernelized_func(apply_rotary_pos_emb) class Qwen2_5_VLAttention(nn.Module): """ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer @@ -619,8 +657,6 @@ def forward( attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, - output_attentions: bool = False, - use_cache: bool = False, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]: @@ -635,9 +671,7 @@ def forward( value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) cos, sin = position_embeddings - query_states, key_states = apply_multimodal_rotary_pos_emb( - query_states, key_states, cos, sin, self.config.rope_parameters["mrope_section"] - ) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) diff --git a/src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py b/src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py index 54489d981b4d..b041d83f8c99 100644 --- a/src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py +++ b/src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py @@ -24,13 +24,11 @@ import torch.nn as nn from huggingface_hub.dataclasses import strict -from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache from ...configuration_utils import PreTrainedConfig from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutputWithPooling -from ...modeling_utils import PreTrainedModel from ...processing_utils import ProcessingKwargs, Unpack from ...utils import auto_docstring, logging from ...utils.generic import get_max_seqlen, merge_with_config_defaults @@ -51,9 +49,9 @@ Qwen2VLModel, Qwen2VLModelOutputWithPast, Qwen2VLPreTrainedModel, + Qwen2VLVisionRotaryEmbedding, TransformersKwargs, VisionAttention, - VisionRotaryEmbedding, ) from ..qwen2_vl.processing_qwen2_vl import Qwen2VLProcessor @@ -77,6 +75,8 @@ class Qwen2_5_VLVisionConfig(PreTrainedConfig): model_type = "qwen2_5_vl_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 32 hidden_size: int = 3584 @@ -92,6 +92,7 @@ class Qwen2_5_VLVisionConfig(PreTrainedConfig): out_hidden_size: int = 3584 fullatt_block_indexes: list[int] | tuple[int, ...] = (7, 15, 23, 31) initializer_range: float = 0.02 + rope_parameters: dict | None = None class Qwen2_5_VLTextConfig(Qwen2VLTextConfig): @@ -124,8 +125,27 @@ class Qwen2_5_VisionPatchEmbed(PatchEmbed): pass -class Qwen2_5_VisionRotaryEmbedding(VisionRotaryEmbedding): - pass +class Qwen2_5_VLVisionRotaryEmbedding(Qwen2VLVisionRotaryEmbedding): + # override: this model uses standard config names (`hidden_size`) opposed to `embed_dim` + def compute_axial_rope_parameters( + config: Qwen2_5_VLVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor class Qwen2_5_VLPatchMerger(PatchMerger): @@ -171,11 +191,7 @@ def forward( class Qwen2_5_VLPreTrainedModel(Qwen2VLPreTrainedModel): - def _init_weights(self, module): - PreTrainedModel._init_weights(self, module) - if isinstance(module, Qwen2_5_VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) + pass class Qwen2_5_VisionTransformerPretrainedModel(Qwen2_5_VLPreTrainedModel): @@ -202,8 +218,7 @@ def __init__(self, config, *inputs, **kwargs) -> None: embed_dim=config.hidden_size, ) - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Qwen2_5_VisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Qwen2_5_VLVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Qwen2_5_VLVisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen2_5_VLPatchMerger( @@ -215,6 +230,12 @@ def __init__(self, config, *inputs, **kwargs) -> None: self.post_init() + def permute_input_for_window_attn(self, input_tensor: torch.Tensor, window_index: torch.Tensor, seq_len: int): + input_tensor = input_tensor.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) + input_tensor = input_tensor[window_index, :, :] + input_tensor = input_tensor.reshape(seq_len, -1) + return input_tensor + @merge_with_config_defaults @capture_outputs def forward( @@ -246,16 +267,12 @@ def forward( hidden_states = self.patch_embed(hidden_states) seq_len, _ = hidden_states.size() - hidden_states = hidden_states.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) - hidden_states = hidden_states[window_index, :, :] - hidden_states = hidden_states.reshape(seq_len, -1) - - rotary_pos_emb = self.rotary_pos_emb(position_ids) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len // self.spatial_merge_unit, self.spatial_merge_unit, -1) - rotary_pos_emb = rotary_pos_emb[window_index, :, :] - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + hidden_states = self.permute_input_for_window_attn(hidden_states, window_index, seq_len=seq_len) + + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) + position_embeddings = tuple( + self.permute_input_for_window_attn(freq, window_index, seq_len=seq_len) for freq in position_embeddings + ) for layer_num, blk in enumerate(self.blocks): if layer_num in self.fullatt_block_indexes: diff --git a/src/transformers/models/qwen2_vl/configuration_qwen2_vl.py b/src/transformers/models/qwen2_vl/configuration_qwen2_vl.py index f9d57f2515f3..bf95e6390be9 100644 --- a/src/transformers/models/qwen2_vl/configuration_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/configuration_qwen2_vl.py @@ -27,6 +27,8 @@ class Qwen2VLVisionConfig(PreTrainedConfig): model_type = "qwen2_vl_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 32 embed_dim: int = 1280 @@ -39,6 +41,7 @@ class Qwen2VLVisionConfig(PreTrainedConfig): spatial_merge_size: int = 2 temporal_patch_size: int | list[int] | tuple[int, int] = 2 initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="Qwen/Qwen2-VL-7B-Instruct") diff --git a/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py b/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py index 1193f899694d..8aee185c579d 100644 --- a/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py +++ b/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py @@ -27,11 +27,10 @@ import torch.nn as nn from torch.nn import LayerNorm -from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...generation import GenerationMixin -from ...integrations import use_kernel_forward_from_hub +from ...integrations import use_kernel_forward_from_hub, use_kernelized_func from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask from ...modeling_flash_attention_utils import FlashAttentionKwargs from ...modeling_layers import GradientCheckpointingLayer @@ -112,7 +111,6 @@ def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" -# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Qwen2VL class Qwen2VLRotaryEmbedding(nn.Module): @deprecate_kwarg("device", version="5.18") def __init__(self, config: Qwen2VLConfig, device=None): @@ -130,6 +128,7 @@ def __init__(self, config: Qwen2VLConfig, device=None): self.inv_freq = nn.Buffer(inv_freq, persistent=False) self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + self.mrope_section = config.rope_parameters.get("mrope_section", [16, 24, 24]) @staticmethod @deprecate_kwarg("device", version="5.18") @@ -151,7 +150,6 @@ def compute_default_rope_parameters(config: Qwen2VLConfig, device=None, **kwargs inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq.to(device), attention_factor - # Ignore copy def forward(self, x, position_ids): # In contrast to other models, Qwen2_VL has different position ids for the grids # So we expand the inv_freq to shape (3, ...) @@ -161,12 +159,20 @@ def forward(self, x, position_ids): device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq = torch.cat([m[i % 3] for i, m in enumerate(freq.split(self.mrope_section, dim=-1))], dim=-1) + return torch.cat((freq, freq), dim=-1) + # Copied from transformers.models.llama.modeling_llama.rotate_half def rotate_half(x): @@ -176,28 +182,16 @@ def rotate_half(x): return torch.cat((-x2, x1), dim=-1) -def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1): - """Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/). - - Explanation: - Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding - sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For - vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately. - Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding. - For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal, - height and width) of text embedding is always the same, so the text embedding rotary position embedding has no - difference with modern LLMs. +@use_kernel_forward_from_hub("rotary_pos_emb") +# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb +def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. - position_ids (`torch.Tensor`): - The position indices of the tokens corresponding to the query and key tensors. For example, this can be - used to pass offsetted position ids when working with a KV-cache. - mrope_section(`List(int)`): - Multimodal rope section is for channel dimension of temporal, height and width in rope calculation. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note @@ -208,14 +202,8 @@ def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ - mrope_section = mrope_section * 2 - cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze( - unsqueeze_dim - ) - sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze( - unsqueeze_dim - ) - + cos = cos.unsqueeze(unsqueeze_dim) + sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed @@ -235,16 +223,70 @@ def apply_rotary_pos_emb_vision( return q_embed, k_embed -class VisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: +class Qwen2VLVisionRotaryEmbedding(nn.Module): + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Qwen2VLVisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Qwen2VLVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the axial RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.embed_dim // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) class PatchEmbed(nn.Module): @@ -465,6 +507,7 @@ def forward(self, x): return down_proj +@use_kernelized_func(apply_rotary_pos_emb) class Qwen2VLAttention(nn.Module): """ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer @@ -510,8 +553,6 @@ def forward( attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, - output_attentions: bool = False, - use_cache: bool = False, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]: @@ -526,9 +567,7 @@ def forward( value_states = value_states.view(bsz, q_len, -1, self.head_dim).transpose(1, 2) cos, sin = position_embeddings - query_states, key_states = apply_multimodal_rotary_pos_emb( - query_states, key_states, cos, sin, self.config.rope_parameters["mrope_section"] - ) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) @@ -637,12 +676,6 @@ class Qwen2VLPreTrainedModel(PreTrainedModel): _can_compile_fullgraph = True _supports_attention_backend = True - def _init_weights(self, module): - super()._init_weights(module) - if isinstance(module, VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - @auto_docstring class Qwen2VisionTransformerPretrainedModel(Qwen2VLPreTrainedModel): @@ -666,9 +699,7 @@ def __init__(self, config) -> None: embed_dim=config.embed_dim, ) - head_dim = config.embed_dim // config.num_heads - self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2) - + self.rotary_pos_emb = Qwen2VLVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Qwen2VLVisionBlock(config) for _ in range(config.depth)]) self.merger = PatchMerger( dim=config.hidden_size, context_dim=config.embed_dim, spatial_merge_size=config.spatial_merge_size @@ -697,9 +728,7 @@ def forward( cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs) hidden_states = self.patch_embed(hidden_states) - rotary_pos_emb = self.rotary_pos_emb(position_ids) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) for blk in self.blocks: hidden_states = blk( diff --git a/src/transformers/models/qwen3_5/configuration_qwen3_5.py b/src/transformers/models/qwen3_5/configuration_qwen3_5.py index c33663287cea..e0ca67f850e5 100644 --- a/src/transformers/models/qwen3_5/configuration_qwen3_5.py +++ b/src/transformers/models/qwen3_5/configuration_qwen3_5.py @@ -133,6 +133,8 @@ class Qwen3_5VisionConfig(PreTrainedConfig): model_type = "qwen3_5_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 27 hidden_size: int = 1152 @@ -146,6 +148,7 @@ class Qwen3_5VisionConfig(PreTrainedConfig): out_hidden_size: int = 3584 num_position_embeddings: int = 2304 initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="Qwen/Qwen3.5-27B") diff --git a/src/transformers/models/qwen3_5/modeling_qwen3_5.py b/src/transformers/models/qwen3_5/modeling_qwen3_5.py index 06c19237c170..6915fa30cadf 100644 --- a/src/transformers/models/qwen3_5/modeling_qwen3_5.py +++ b/src/transformers/models/qwen3_5/modeling_qwen3_5.py @@ -46,7 +46,7 @@ CausalLMOutputWithPast, SequenceClassifierOutputWithPast, ) -from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import ( @@ -75,15 +75,69 @@ class Qwen3_5VisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Qwen3_5VisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Qwen3_5VisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) class Qwen3_5TextRotaryEmbedding(nn.Module): @@ -129,44 +183,32 @@ def compute_default_rope_parameters( inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq.to(device), attention_factor - @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): - # In contrast to other models, Qwen3_5 has different position ids for the grids + # In contrast to other models, Qwen3_5Text has different position ids for the grids # So we expand the inv_freq to shape (3, ...) - if position_ids.ndim == 2: - position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1) - inv_freq_expanded = ( - self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device) - ) + inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1) position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions) device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - freqs = self.apply_interleaved_mrope(freqs, self.mrope_section) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) - def apply_interleaved_mrope(self, freqs, mrope_section): - """Apply interleaved MRoPE to 3D rotary embeddings. - Reorganizes frequency layout from chunked [TTT...HHH...WWW] to - interleaved [THWTHWTHW...TT], preserving frequency continuity. - args: - x: (3, bs, seq_len, head_dim // 2) - mrope_section: (3,) - returns: - x_t: (bs, seq_len, head_dim // 2) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. """ - freqs_t = freqs[0] # just overwrite the first dimension T + freqs_thw = freq[0] # just overwrite the first dimension T for dim, offset in enumerate((1, 2), start=1): # H, W - length = mrope_section[dim] * 3 + length = self.mrope_section[dim] * 3 idx = slice(offset, length, 3) - freqs_t[..., idx] = freqs[dim, ..., idx] - return freqs_t + freqs_thw[..., idx] = freq[dim, ..., idx] + return torch.cat((freqs_thw, freqs_thw), dim=-1) # NOTE: the FLA package does not re-cast to `input_dtype` in its implementation, maybe we should do the same @@ -898,9 +940,6 @@ def _init_weights(self, module): # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight) elif isinstance(module, Qwen3_5RMSNorm): init.zeros_(module.weight) - elif isinstance(module, Qwen3_5VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class Qwen3_5VisionMLP(nn.Module): @@ -1104,8 +1143,7 @@ def __init__(self, config, *inputs, **kwargs) -> None: self.interpolation_align_corners = True self.interpolation_mode = "bilinear" - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Qwen3_5VisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Qwen3_5VisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Qwen3_5VisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen3_5VisionPatchMerger( @@ -1144,13 +1182,10 @@ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) hidden_states = self.patch_embed(hidden_states) pos_embeds = (self.pos_embed(interp_indices) * interp_weights[:, :, None]).sum(1) hidden_states = hidden_states + pos_embeds.to(hidden_states.dtype) - rotary_pos_emb = self.rotary_pos_emb(position_ids) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len, -1) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) for blk in self.blocks: hidden_states = blk( diff --git a/src/transformers/models/qwen3_5/modular_qwen3_5.py b/src/transformers/models/qwen3_5/modular_qwen3_5.py index 5ed733c1be4c..c75ae33e1431 100644 --- a/src/transformers/models/qwen3_5/modular_qwen3_5.py +++ b/src/transformers/models/qwen3_5/modular_qwen3_5.py @@ -428,9 +428,6 @@ def _init_weights(self, module): # We initialize with 0s to be 1 centered as the RMSNorm here does (1 + weight) elif isinstance(module, Qwen3_5RMSNorm): init.zeros_(module.weight) - elif isinstance(module, Qwen3_5VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class Qwen3_5VisionModel(Qwen3VLVisionModel): @@ -469,13 +466,10 @@ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) hidden_states = self.patch_embed(hidden_states) pos_embeds = (self.pos_embed(interp_indices) * interp_weights[:, :, None]).sum(1) hidden_states = hidden_states + pos_embeds.to(hidden_states.dtype) - rotary_pos_emb = self.rotary_pos_emb(position_ids) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len, -1) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) for blk in self.blocks: hidden_states = blk( diff --git a/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py b/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py index a60a3989a374..5a10240e98b8 100644 --- a/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py +++ b/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py @@ -146,6 +146,8 @@ class Qwen3_5MoeVisionConfig(PreTrainedConfig): model_type = "qwen3_5_moe_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 27 hidden_size: int = 1152 @@ -159,6 +161,7 @@ class Qwen3_5MoeVisionConfig(PreTrainedConfig): out_hidden_size: int = 3584 num_position_embeddings: int = 2304 initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="Qwen/Qwen3.5-35B-A3B") diff --git a/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py b/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py index 7c5dd26beddc..b9773fdc5b7c 100644 --- a/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py +++ b/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py @@ -48,7 +48,7 @@ MoeCausalLMOutputWithPast, MoeModelOutputWithPast, ) -from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import ( @@ -77,15 +77,69 @@ class Qwen3_5MoeVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Qwen3_5MoeVisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Qwen3_5MoeVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) class Qwen3_5MoeTextRotaryEmbedding(nn.Module): @@ -131,44 +185,32 @@ def compute_default_rope_parameters( inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq.to(device), attention_factor - @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): - # In contrast to other models, Qwen3_5Moe has different position ids for the grids + # In contrast to other models, Qwen3_5MoeText has different position ids for the grids # So we expand the inv_freq to shape (3, ...) - if position_ids.ndim == 2: - position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1) - inv_freq_expanded = ( - self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device) - ) + inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1) position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions) device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - freqs = self.apply_interleaved_mrope(freqs, self.mrope_section) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) - def apply_interleaved_mrope(self, freqs, mrope_section): - """Apply interleaved MRoPE to 3D rotary embeddings. - Reorganizes frequency layout from chunked [TTT...HHH...WWW] to - interleaved [THWTHWTHW...TT], preserving frequency continuity. - args: - x: (3, bs, seq_len, head_dim // 2) - mrope_section: (3,) - returns: - x_t: (bs, seq_len, head_dim // 2) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. """ - freqs_t = freqs[0] # just overwrite the first dimension T + freqs_thw = freq[0] # just overwrite the first dimension T for dim, offset in enumerate((1, 2), start=1): # H, W - length = mrope_section[dim] * 3 + length = self.mrope_section[dim] * 3 idx = slice(offset, length, 3) - freqs_t[..., idx] = freqs[dim, ..., idx] - return freqs_t + freqs_thw[..., idx] = freq[dim, ..., idx] + return torch.cat((freqs_thw, freqs_thw), dim=-1) # NOTE: the FLA package does not re-cast to `input_dtype` in its implementation, maybe we should do the same @@ -992,9 +1034,6 @@ def _init_weights(self, module): init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range) elif isinstance(module, Qwen3_5MoeSparseMoeBlock): init.normal_(module.gate.weight, mean=0.0, std=self.config.initializer_range) - elif isinstance(module, Qwen3_5MoeVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class Qwen3_5MoeVisionMLP(nn.Module): @@ -1198,8 +1237,7 @@ def __init__(self, config, *inputs, **kwargs) -> None: self.interpolation_align_corners = True self.interpolation_mode = "bilinear" - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Qwen3_5MoeVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Qwen3_5MoeVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Qwen3_5MoeVisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen3_5MoeVisionPatchMerger( @@ -1238,13 +1276,10 @@ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) hidden_states = self.patch_embed(hidden_states) pos_embeds = (self.pos_embed(interp_indices) * interp_weights[:, :, None]).sum(1) hidden_states = hidden_states + pos_embeds.to(hidden_states.dtype) - rotary_pos_emb = self.rotary_pos_emb(position_ids) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len, -1) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) for blk in self.blocks: hidden_states = blk( diff --git a/src/transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py b/src/transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py index a48c779802c5..3a79c40d57db 100644 --- a/src/transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py +++ b/src/transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py @@ -232,9 +232,6 @@ def _init_weights(self, module): init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range) elif isinstance(module, Qwen3_5MoeSparseMoeBlock): init.normal_(module.gate.weight, mean=0.0, std=self.config.initializer_range) - elif isinstance(module, Qwen3_5MoeVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class Qwen3_5MoeVisionModel(Qwen3_5VisionModel): diff --git a/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py b/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py index 6a81cef420f3..41d44aedb7d5 100644 --- a/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py +++ b/src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py @@ -88,6 +88,8 @@ class Qwen3OmniMoeVisionEncoderConfig(PreTrainedConfig): model_type = "qwen3_omni_moe_vision_encoder" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 27 hidden_size: int = 1152 @@ -102,6 +104,7 @@ class Qwen3OmniMoeVisionEncoderConfig(PreTrainedConfig): num_position_embeddings: int = 2304 deepstack_visual_indexes: list[int] | tuple[int, ...] = (8, 16, 24) initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="Qwen/Qwen3-Omni-30B-A3B-Instruct") diff --git a/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py b/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py index 6ec317e1debd..b7dde7dae48f 100644 --- a/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py +++ b/src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py @@ -147,9 +147,6 @@ def _init_weights(self, module): elif isinstance(module, SinusoidsPositionEmbedding): position_embeddings = module.compute_default_singular_positional_embedding() init.copy_(module.positional_embedding, position_embeddings) - elif isinstance(module, Qwen3OmniMoeVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) def _get_feat_extract_output_lengths(input_lengths, n_window=50): @@ -985,15 +982,69 @@ def forward(self, hidden: torch.Tensor) -> torch.Tensor: class Qwen3OmniMoeVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Qwen3OmniMoeVisionEncoderConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Qwen3OmniMoeVisionEncoderConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) class Qwen3OmniMoeTextTopKRouter(nn.Module): @@ -1112,8 +1163,7 @@ def __init__(self, config, *inputs, **kwargs) -> None: self.interpolation_align_corners = True self.interpolation_mode = "bilinear" - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Qwen3OmniMoeVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Qwen3OmniMoeVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Qwen3OmniMoeVisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen3OmniMoeVisionPatchMerger( @@ -1156,13 +1206,10 @@ def forward( hidden_states = self.patch_embed(hidden_states) pos_embeds = (self.pos_embed(interp_indices) * interp_weights[:, :, None]).sum(1) hidden_states = hidden_states + pos_embeds.to(hidden_states.dtype) - rotary_pos_emb = self.rotary_pos_emb(position_ids) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len, -1) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) deepstack_feature_lists = [] for layer_num, blk in enumerate(self.blocks): @@ -1233,44 +1280,32 @@ def compute_default_rope_parameters( inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq.to(device), attention_factor - @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): - # In contrast to other models, Qwen3OmniMoeThinker has different position ids for the grids + # In contrast to other models, Qwen3OmniMoeThinkerText has different position ids for the grids # So we expand the inv_freq to shape (3, ...) - if position_ids.ndim == 2: - position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1) - inv_freq_expanded = ( - self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device) - ) + inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1) position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions) device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - freqs = self.apply_interleaved_mrope(freqs, self.mrope_section) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) - def apply_interleaved_mrope(self, freqs, mrope_section): - """Apply interleaved MRoPE to 3D rotary embeddings. - Reorganizes frequency layout from chunked [TTT...HHH...WWW] to - interleaved [THWTHWTHW...TT], preserving frequency continuity. - args: - x: (3, bs, seq_len, head_dim // 2) - mrope_section: (3,) - returns: - x_t: (bs, seq_len, head_dim // 2) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. """ - freqs_t = freqs[0] # just overwrite the first dimension T + freqs_thw = freq[0] # just overwrite the first dimension T for dim, offset in enumerate((1, 2), start=1): # H, W - length = mrope_section[dim] * 3 + length = self.mrope_section[dim] * 3 idx = slice(offset, length, 3) - freqs_t[..., idx] = freqs[dim, ..., idx] - return freqs_t + freqs_thw[..., idx] = freq[dim, ..., idx] + return torch.cat((freqs_thw, freqs_thw), dim=-1) @use_experts_implementation diff --git a/src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py b/src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py index eecce4c80a23..966d5ecb7490 100644 --- a/src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py +++ b/src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py @@ -709,9 +709,6 @@ def _init_weights(self, module): elif isinstance(module, SinusoidsPositionEmbedding): position_embeddings = module.compute_default_singular_positional_embedding() init.copy_(module.positional_embedding, position_embeddings) - elif isinstance(module, Qwen3OmniMoeVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class Qwen3OmniMoePreTrainedModelForConditionalGeneration(Qwen2_5OmniPreTrainedModelForConditionalGeneration): @@ -1099,7 +1096,13 @@ def forward(self, hidden: torch.Tensor) -> torch.Tensor: class Qwen3OmniMoeVisionRotaryEmbedding(Qwen3VLMoeVisionRotaryEmbedding): - pass + def __init__(self, config: Qwen3OmniMoeVisionEncoderConfig, device=None): + super().__init__(config, device=device) + + def compute_axial_rope_parameters( + config: Qwen3OmniMoeVisionEncoderConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + return super().compute_axial_rope_parameters(config, device=device, **kwargs) class Qwen3OmniMoeVisionEncoder(Qwen3VLMoeVisionModel): diff --git a/src/transformers/models/qwen3_vl/configuration_qwen3_vl.py b/src/transformers/models/qwen3_vl/configuration_qwen3_vl.py index be6f3992500e..1146b876734d 100644 --- a/src/transformers/models/qwen3_vl/configuration_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/configuration_qwen3_vl.py @@ -38,6 +38,8 @@ class Qwen3VLVisionConfig(PreTrainedConfig): model_type = "qwen3_vl_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 27 hidden_size: int = 1152 @@ -52,6 +54,7 @@ class Qwen3VLVisionConfig(PreTrainedConfig): num_position_embeddings: int = 2304 deepstack_visual_indexes: list[int] | tuple[int, ...] = (8, 16, 24) initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="Qwen/Qwen3-VL-4B-Instruct") diff --git a/src/transformers/models/qwen3_vl/modeling_qwen3_vl.py b/src/transformers/models/qwen3_vl/modeling_qwen3_vl.py index 7d964d080792..f144a57115bb 100644 --- a/src/transformers/models/qwen3_vl/modeling_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/modeling_qwen3_vl.py @@ -26,7 +26,6 @@ import torch import torch.nn as nn -from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...generation import GenerationMixin @@ -35,7 +34,7 @@ from ...modeling_flash_attention_utils import FlashAttentionKwargs from ...modeling_layers import GradientCheckpointingLayer from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, CausalLMOutputWithPast -from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import ( @@ -107,15 +106,69 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: class Qwen3VLVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Qwen3VLVisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Qwen3VLVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) class Qwen3VLVisionPatchMerger(nn.Module): @@ -346,44 +399,32 @@ def compute_default_rope_parameters( inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq.to(device), attention_factor - @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): - # In contrast to other models, Qwen3VL has different position ids for the grids + # In contrast to other models, Qwen3VLText has different position ids for the grids # So we expand the inv_freq to shape (3, ...) - if position_ids.ndim == 2: - position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1) - inv_freq_expanded = ( - self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device) - ) + inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1) position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions) device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - freqs = self.apply_interleaved_mrope(freqs, self.mrope_section) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) - def apply_interleaved_mrope(self, freqs, mrope_section): - """Apply interleaved MRoPE to 3D rotary embeddings. - Reorganizes frequency layout from chunked [TTT...HHH...WWW] to - interleaved [THWTHWTHW...TT], preserving frequency continuity. - args: - x: (3, bs, seq_len, head_dim // 2) - mrope_section: (3,) - returns: - x_t: (bs, seq_len, head_dim // 2) + def recomposition_frequencies(self, freq): """ - freqs_t = freqs[0] # just overwrite the first dimension T + Recompose the frequencies into the final spatial layout used per each grid. + """ + freqs_thw = freq[0] # just overwrite the first dimension T for dim, offset in enumerate((1, 2), start=1): # H, W - length = mrope_section[dim] * 3 + length = self.mrope_section[dim] * 3 idx = slice(offset, length, 3) - freqs_t[..., idx] = freqs[dim, ..., idx] - return freqs_t + freqs_thw[..., idx] = freq[dim, ..., idx] + return torch.cat((freqs_thw, freqs_thw), dim=-1) @use_kernel_forward_from_hub("RMSNorm") @@ -595,12 +636,6 @@ class Qwen3VLPreTrainedModel(PreTrainedModel): "attentions": Qwen3VLTextAttention, } - def _init_weights(self, module): - super()._init_weights(module) - if isinstance(module, Qwen3VLVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - class Qwen3VLVisionModel(Qwen3VLPreTrainedModel): config: Qwen3VLVisionConfig @@ -626,8 +661,7 @@ def __init__(self, config, *inputs, **kwargs) -> None: self.interpolation_align_corners = True self.interpolation_mode = "bilinear" - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Qwen3VLVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Qwen3VLVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Qwen3VLVisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen3VLVisionPatchMerger( @@ -679,13 +713,10 @@ def forward( hidden_states = self.patch_embed(hidden_states) pos_embeds = (self.pos_embed(interp_indices) * interp_weights[:, :, None]).sum(1) hidden_states = hidden_states + pos_embeds.to(hidden_states.dtype) - rotary_pos_emb = self.rotary_pos_emb(position_ids) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len, -1) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) deepstack_feature_lists = [] for layer_num, blk in enumerate(self.blocks): diff --git a/src/transformers/models/qwen3_vl/modular_qwen3_vl.py b/src/transformers/models/qwen3_vl/modular_qwen3_vl.py index 7aaa2f785141..ebdb21273b13 100644 --- a/src/transformers/models/qwen3_vl/modular_qwen3_vl.py +++ b/src/transformers/models/qwen3_vl/modular_qwen3_vl.py @@ -22,7 +22,6 @@ import torch.nn as nn from huggingface_hub.dataclasses import strict -from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache, DynamicCache from ...configuration_utils import PreTrainedConfig @@ -30,13 +29,11 @@ from ...masking_utils import create_causal_mask from ...modeling_flash_attention_utils import FlashAttentionKwargs from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling -from ...modeling_rope_utils import RopeParameters, dynamic_rope_update -from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from ...modeling_rope_utils import RopeParameters +from ...modeling_utils import ALL_ATTENTION_FUNCTIONS from ...processing_utils import ProcessingKwargs, Unpack, VideosKwargs from ...utils import auto_docstring, can_return_tuple, is_torchvision_available, logging -from ...utils.deprecation import deprecate_kwarg from ...utils.generic import ( - maybe_autocast, merge_with_config_defaults, ) from ...utils.output_capturing import capture_outputs @@ -49,11 +46,12 @@ ) from ..auto.modeling_auto import AutoModel from ..glm4v.video_processing_glm4v import smart_resize -from ..llama.modeling_llama import LlamaRotaryEmbedding from ..qwen2_5_vl.modeling_qwen2_5_vl import ( Qwen2_5_VLCausalLMOutputWithPast, Qwen2_5_VLForConditionalGeneration, + Qwen2_5_VLRotaryEmbedding, Qwen2_5_VLVisionBlock, + Qwen2_5_VLVisionRotaryEmbedding, ) from ..qwen2_vl.modeling_qwen2_vl import ( PatchEmbed, @@ -62,7 +60,6 @@ Qwen2VLPreTrainedModel, TransformersKwargs, VisionAttention, - VisionRotaryEmbedding, ) from ..qwen2_vl.processing_qwen2_vl import Qwen2VLProcessor from ..qwen2_vl.video_processing_qwen2_vl import Qwen2VLVideoProcessor @@ -107,6 +104,8 @@ class Qwen3VLVisionConfig(PreTrainedConfig): model_type = "qwen3_vl_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 27 hidden_size: int = 1152 @@ -121,6 +120,7 @@ class Qwen3VLVisionConfig(PreTrainedConfig): num_position_embeddings: int = 2304 deepstack_visual_indexes: list[int] | tuple[int, ...] = (8, 16, 24) initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="Qwen/Qwen3-VL-4B-Instruct") @@ -244,7 +244,7 @@ def __init__(self, config) -> None: self.proj = nn.Conv3d(self.in_channels, self.embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=True) -class Qwen3VLVisionRotaryEmbedding(VisionRotaryEmbedding): +class Qwen3VLVisionRotaryEmbedding(Qwen2_5_VLVisionRotaryEmbedding): pass @@ -279,50 +279,26 @@ def __init__(self, config, attn_implementation: str = "sdpa") -> None: self.mlp = Qwen3VLVisionMLP(config=config) -class Qwen3VLTextRotaryEmbedding(LlamaRotaryEmbedding): - @deprecate_kwarg("device", version="5.18") +class Qwen3VLTextRotaryEmbedding(Qwen2_5_VLRotaryEmbedding): def __init__(self, config: Qwen3VLTextConfig, device=None): - super().__init__(config) + super().__init__() self.mrope_section = config.rope_parameters.get("mrope_section", [24, 20, 20]) - def apply_interleaved_mrope(self, freqs, mrope_section): - """Apply interleaved MRoPE to 3D rotary embeddings. - Reorganizes frequency layout from chunked [TTT...HHH...WWW] to - interleaved [THWTHWTHW...TT], preserving frequency continuity. - args: - x: (3, bs, seq_len, head_dim // 2) - mrope_section: (3,) - returns: - x_t: (bs, seq_len, head_dim // 2) + def compute_default_rope_parameters( + config: Qwen3VLTextConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + return super().compute_default_rope_parameters(config, device, **kwargs) + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. """ - freqs_t = freqs[0] # just overwrite the first dimension T + freqs_thw = freq[0] # just overwrite the first dimension T for dim, offset in enumerate((1, 2), start=1): # H, W - length = mrope_section[dim] * 3 + length = self.mrope_section[dim] * 3 idx = slice(offset, length, 3) - freqs_t[..., idx] = freqs[dim, ..., idx] - return freqs_t - - @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) - def forward(self, x, position_ids): - # In contrast to other models, Qwen3VL has different position ids for the grids - # So we expand the inv_freq to shape (3, ...) - if position_ids.ndim == 2: - position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1) - inv_freq_expanded = ( - self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device) - ) - position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions) - - device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" - with maybe_autocast(device_type=device_type, enabled=False): # Force float32 - freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - freqs = self.apply_interleaved_mrope(freqs, self.mrope_section) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling - - return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) + freqs_thw[..., idx] = freq[dim, ..., idx] + return torch.cat((freqs_thw, freqs_thw), dim=-1) class Qwen3VLTextAttention(Qwen3Attention): @@ -409,12 +385,6 @@ class Qwen3VLPreTrainedModel(Qwen2VLPreTrainedModel): "attentions": Qwen3VLTextAttention, } - def _init_weights(self, module): - PreTrainedModel._init_weights(self, module) - if isinstance(module, Qwen3VLVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - class Qwen3VLVisionModel(Qwen3VLPreTrainedModel): config: Qwen3VLVisionConfig @@ -440,8 +410,7 @@ def __init__(self, config, *inputs, **kwargs) -> None: self.interpolation_align_corners = True self.interpolation_mode = "bilinear" - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Qwen3VLVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Qwen3VLVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Qwen3VLVisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen3VLVisionPatchMerger( @@ -493,13 +462,10 @@ def forward( hidden_states = self.patch_embed(hidden_states) pos_embeds = (self.pos_embed(interp_indices) * interp_weights[:, :, None]).sum(1) hidden_states = hidden_states + pos_embeds.to(hidden_states.dtype) - rotary_pos_emb = self.rotary_pos_emb(position_ids) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len, -1) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) deepstack_feature_lists = [] for layer_num, blk in enumerate(self.blocks): diff --git a/src/transformers/models/qwen3_vl_moe/configuration_qwen3_vl_moe.py b/src/transformers/models/qwen3_vl_moe/configuration_qwen3_vl_moe.py index aaa6b2e52ef8..06b0c0a2a848 100644 --- a/src/transformers/models/qwen3_vl_moe/configuration_qwen3_vl_moe.py +++ b/src/transformers/models/qwen3_vl_moe/configuration_qwen3_vl_moe.py @@ -130,6 +130,8 @@ class Qwen3VLMoeVisionConfig(PreTrainedConfig): model_type = "qwen3_vl_moe_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 27 hidden_size: int = 1152 @@ -144,6 +146,7 @@ class Qwen3VLMoeVisionConfig(PreTrainedConfig): num_position_embeddings: int = 2304 deepstack_visual_indexes: list[int] | tuple[int, ...] = (8, 16, 24) initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="Qwen/Qwen3-VL-30B-A3B-Instruct") diff --git a/src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py b/src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py index 42bb1d65346b..e1823c92261c 100644 --- a/src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py +++ b/src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py @@ -41,7 +41,7 @@ CausalLMOutputWithPast, MoeModelOutputWithPast, ) -from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check @@ -397,21 +397,72 @@ def _init_weights(self, module): init.normal_(module.down_proj, mean=0.0, std=std) elif isinstance(module, Qwen3VLMoeTextTopKRouter): init.normal_(module.weight, mean=0.0, std=std) - elif isinstance(module, Qwen3VLMoeVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class Qwen3VLMoeVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Qwen3VLMoeVisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Qwen3VLMoeVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) def apply_rotary_pos_emb_vision( @@ -626,8 +677,7 @@ def __init__(self, config, *inputs, **kwargs) -> None: self.interpolation_align_corners = True self.interpolation_mode = "bilinear" - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Qwen3VLMoeVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Qwen3VLMoeVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Qwen3VLMoeVisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen3VLMoeVisionPatchMerger( @@ -679,13 +729,10 @@ def forward( hidden_states = self.patch_embed(hidden_states) pos_embeds = (self.pos_embed(interp_indices) * interp_weights[:, :, None]).sum(1) hidden_states = hidden_states + pos_embeds.to(hidden_states.dtype) - rotary_pos_emb = self.rotary_pos_emb(position_ids) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len, -1) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) deepstack_feature_lists = [] for layer_num, blk in enumerate(self.blocks): @@ -752,44 +799,32 @@ def compute_default_rope_parameters( inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq.to(device), attention_factor - @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): - # In contrast to other models, Qwen3VLMoe has different position ids for the grids + # In contrast to other models, Qwen3VLMoeText has different position ids for the grids # So we expand the inv_freq to shape (3, ...) - if position_ids.ndim == 2: - position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1) - inv_freq_expanded = ( - self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device) - ) + inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1) position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions) device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - freqs = self.apply_interleaved_mrope(freqs, self.mrope_section) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) - def apply_interleaved_mrope(self, freqs, mrope_section): - """Apply interleaved MRoPE to 3D rotary embeddings. - Reorganizes frequency layout from chunked [TTT...HHH...WWW] to - interleaved [THWTHWTHW...TT], preserving frequency continuity. - args: - x: (3, bs, seq_len, head_dim // 2) - mrope_section: (3,) - returns: - x_t: (bs, seq_len, head_dim // 2) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. """ - freqs_t = freqs[0] # just overwrite the first dimension T + freqs_thw = freq[0] # just overwrite the first dimension T for dim, offset in enumerate((1, 2), start=1): # H, W - length = mrope_section[dim] * 3 + length = self.mrope_section[dim] * 3 idx = slice(offset, length, 3) - freqs_t[..., idx] = freqs[dim, ..., idx] - return freqs_t + freqs_thw[..., idx] = freq[dim, ..., idx] + return torch.cat((freqs_thw, freqs_thw), dim=-1) @auto_docstring( diff --git a/src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py b/src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py index b7bce365191c..8b4e96324611 100644 --- a/src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py +++ b/src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py @@ -215,9 +215,6 @@ def _init_weights(self, module): init.normal_(module.down_proj, mean=0.0, std=std) elif isinstance(module, Qwen3VLMoeTextTopKRouter): init.normal_(module.weight, mean=0.0, std=std) - elif isinstance(module, Qwen3VLMoeVisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) class Qwen3VLMoeVisionRotaryEmbedding(Qwen3VLVisionRotaryEmbedding): diff --git a/src/transformers/models/qwen4_exp/configuration_qwen4_exp.py b/src/transformers/models/qwen4_exp/configuration_qwen4_exp.py index 3dd586b84458..16617898d2c3 100644 --- a/src/transformers/models/qwen4_exp/configuration_qwen4_exp.py +++ b/src/transformers/models/qwen4_exp/configuration_qwen4_exp.py @@ -269,6 +269,8 @@ class Qwen4ExpVisionConfig(PreTrainedConfig): model_type = "qwen4_exp_vision" base_config_key = "vision_config" + default_rope_type = "axial" + attribute_map = {"num_attention_heads": "num_heads"} depth: int = 27 hidden_size: int = 1152 @@ -282,6 +284,7 @@ class Qwen4ExpVisionConfig(PreTrainedConfig): out_hidden_size: int = 3584 num_position_embeddings: int = 2304 initializer_range: float = 0.02 + rope_parameters: dict | None = None base_model_fsdp_plan = None diff --git a/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py b/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py index 03bad163f9ee..99f6eca1656f 100644 --- a/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py +++ b/src/transformers/models/qwen4_exp/modeling_qwen4_exp.py @@ -48,7 +48,7 @@ MoeCausalLMOutputWithPast, MoeModelOutputWithPast, ) -from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import ( @@ -119,44 +119,32 @@ def compute_default_rope_parameters( inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) return inv_freq.to(device), attention_factor - @torch.no_grad() - @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): - # In contrast to other models, Qwen4Exp has different position ids for the grids + # In contrast to other models, Qwen4ExpText has different position ids for the grids # So we expand the inv_freq to shape (3, ...) - if position_ids.ndim == 2: - position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1) - inv_freq_expanded = ( - self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1).to(x.device) - ) + inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1) position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions) device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) - freqs = self.apply_interleaved_mrope(freqs, self.mrope_section) - emb = torch.cat((freqs, freqs), dim=-1) - cos = emb.cos() * self.attention_scaling - sin = emb.sin() * self.attention_scaling + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + sin = self.recomposition_frequencies(sin) + cos = self.recomposition_frequencies(cos) return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) - def apply_interleaved_mrope(self, freqs, mrope_section): - """Apply interleaved MRoPE to 3D rotary embeddings. - Reorganizes frequency layout from chunked [TTT...HHH...WWW] to - interleaved [THWTHWTHW...TT], preserving frequency continuity. - args: - x: (3, bs, seq_len, head_dim // 2) - mrope_section: (3,) - returns: - x_t: (bs, seq_len, head_dim // 2) + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. """ - freqs_t = freqs[0] # just overwrite the first dimension T + freqs_thw = freq[0] # just overwrite the first dimension T for dim, offset in enumerate((1, 2), start=1): # H, W - length = mrope_section[dim] * 3 + length = self.mrope_section[dim] * 3 idx = slice(offset, length, 3) - freqs_t[..., idx] = freqs[dim, ..., idx] - return freqs_t + freqs_thw[..., idx] = freq[dim, ..., idx] + return torch.cat((freqs_thw, freqs_thw), dim=-1) class Qwen4ExpTextRMSNorm(nn.Module): @@ -1357,9 +1345,6 @@ def _init_weights(self, module): init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range) elif isinstance(module, Qwen4ExpTextSparseMoeBlock): init.normal_(module.gate.weight, mean=0.0, std=self.config.initializer_range) - elif module.__class__.__name__ == "Qwen4ExpVisionRotaryEmbedding": - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) if isinstance(module, Qwen4ExpTextNGramEmbedding): init.copy_( module.layer_multipliers, @@ -1708,15 +1693,69 @@ def forward( class Qwen4ExpVisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Qwen4ExpVisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Qwen4ExpVisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) class Qwen4ExpVisionMLP(nn.Module): @@ -1921,8 +1960,7 @@ def __init__(self, config, *inputs, **kwargs) -> None: self.interpolation_align_corners = True self.interpolation_mode = "bilinear" - head_dim = config.hidden_size // config.num_heads - self.rotary_pos_emb = Qwen4ExpVisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = Qwen4ExpVisionRotaryEmbedding(config) self.blocks = nn.ModuleList([Qwen4ExpVisionBlock(config) for _ in range(config.depth)]) self.merger = Qwen4ExpVisionPatchMerger( @@ -1961,13 +1999,10 @@ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, **kwargs) hidden_states = self.patch_embed(hidden_states) pos_embeds = (self.pos_embed(interp_indices) * interp_weights[:, :, None]).sum(1) hidden_states = hidden_states + pos_embeds.to(hidden_states.dtype) - rotary_pos_emb = self.rotary_pos_emb(position_ids) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) seq_len, _ = hidden_states.size() hidden_states = hidden_states.reshape(seq_len, -1) - rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) for blk in self.blocks: hidden_states = blk( diff --git a/src/transformers/models/qwen4_exp/modular_qwen4_exp.py b/src/transformers/models/qwen4_exp/modular_qwen4_exp.py index be83ff59c091..23bde6d818c5 100644 --- a/src/transformers/models/qwen4_exp/modular_qwen4_exp.py +++ b/src/transformers/models/qwen4_exp/modular_qwen4_exp.py @@ -868,9 +868,6 @@ def _init_weights(self, module): init.normal_(module.down_proj, mean=0.0, std=self.config.initializer_range) elif isinstance(module, Qwen4ExpTextSparseMoeBlock): init.normal_(module.gate.weight, mean=0.0, std=self.config.initializer_range) - elif module.__class__.__name__ == "Qwen4ExpVisionRotaryEmbedding": - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) if isinstance(module, Qwen4ExpTextNGramEmbedding): init.copy_( module.layer_multipliers, diff --git a/src/transformers/models/sam2_video/configuration_sam2_video.py b/src/transformers/models/sam2_video/configuration_sam2_video.py index e8a77087a60c..8409a8ab1bd4 100644 --- a/src/transformers/models/sam2_video/configuration_sam2_video.py +++ b/src/transformers/models/sam2_video/configuration_sam2_video.py @@ -20,10 +20,13 @@ from huggingface_hub.dataclasses import strict from ...configuration_utils import PreTrainedConfig -from ...utils import auto_docstring +from ...utils import auto_docstring, logging from ..auto import CONFIG_MAPPING, AutoConfig +logger = logging.get_logger(__name__) + + @auto_docstring(checkpoint="facebook/sam2_video.1-hiera-tiny") @strict class Sam2VideoPromptEncoderConfig(PreTrainedConfig): @@ -132,8 +135,6 @@ class Sam2VideoConfig(PreTrainedConfig): The non-linear activation function in the feedforward network in the memory attention module. memory_attention_dropout (`float`, *optional*, defaults to 0.1): The dropout rate for the memory attention module. - memory_attention_rope_theta (`float`, *optional*, defaults to 10000): - The Rope theta parameter. memory_attention_rope_feat_sizes (`list[int]`, *optional*, defaults to `[64, 64]`): The feature sizes for the Rope positional encoding. memory_attention_rope_dropout (`float`, *optional*, defaults to 0.1): @@ -199,6 +200,7 @@ class Sam2VideoConfig(PreTrainedConfig): ```""" model_type = "sam2_video" + default_rope_type = "axial" sub_configs = { "vision_config": AutoConfig, "prompt_encoder_config": Sam2VideoPromptEncoderConfig, @@ -228,11 +230,12 @@ class Sam2VideoConfig(PreTrainedConfig): memory_attention_feed_forward_hidden_size: int = 2048 memory_attention_feed_forward_hidden_act: str = "relu" memory_attention_dropout: float | int = 0.1 - memory_attention_rope_theta: int = 10000 memory_attention_rope_feat_sizes: list[int] | None = None memory_attention_rope_dropout: float | int = 0.1 memory_encoder_hidden_size: int = 256 memory_encoder_output_channels: int = 64 + rope_parameters: dict | None = None + mask_downsampler_embed_dim: int = 256 mask_downsampler_kernel_size: int = 3 mask_downsampler_stride: int = 2 @@ -270,5 +273,21 @@ def __post_init__(self, **kwargs): super().__post_init__(**kwargs) + @property + def memory_attention_rope_theta(self): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + return self.rope_parameters.get("rope_theta", 10_000) + + @memory_attention_rope_theta.setter + def memory_attention_rope_theta(self, value): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + self.rope_parameters["rope_theta"] = value + __all__ = ["Sam2VideoMaskDecoderConfig", "Sam2VideoPromptEncoderConfig", "Sam2VideoConfig"] diff --git a/src/transformers/models/sam2_video/modeling_sam2_video.py b/src/transformers/models/sam2_video/modeling_sam2_video.py index 8e804afae009..deadd9ef5b1b 100644 --- a/src/transformers/models/sam2_video/modeling_sam2_video.py +++ b/src/transformers/models/sam2_video/modeling_sam2_video.py @@ -39,8 +39,14 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...pytorch_utils import compile_compatible_method_lru_cache -from ...utils import ModelOutput, auto_docstring, can_return_tuple, logging -from ...utils.generic import TransformersKwargs, is_flash_attention_requested +from ...utils import ( + ModelOutput, + auto_docstring, + can_return_tuple, + logging, +) +from ...utils.deprecation import deprecate_kwarg +from ...utils.generic import TransformersKwargs, is_flash_attention_requested, maybe_autocast from ...utils.output_capturing import OutputRecorder from ..auto import AutoModel from .configuration_sam2_video import Sam2VideoConfig, Sam2VideoMaskDecoderConfig, Sam2VideoPromptEncoderConfig @@ -730,54 +736,79 @@ def _init_weights(self, module): if isinstance(module, Sam2VideoMemoryFuserCXBlock): if module.scale is not None: init.zeros_(module.scale) - elif isinstance(module, Sam2VideoVisionRotaryEmbedding): - inv_freq = module.create_inv_freq() - init.copy_(module.rope_embeddings_cos, inv_freq.cos()) - init.copy_(module.rope_embeddings_sin, inv_freq.sin()) elif isinstance(module, Sam2VideoPositionalEmbedding): init.normal_(module.positional_embedding, std=module.scale) + elif isinstance(module, Sam2VideoMemoryAttention): + position_ids = module.precompute_positions(module.config) + init.copy_(module.position_ids, position_ids) class Sam2VideoVisionRotaryEmbedding(nn.Module): """ - Vision Rotary Position Embedding for SAM2, following transformers library standards. - Supports 2D (axial) rotary embeddings for spatial dimensions. + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. """ - def __init__(self, config: Sam2VideoConfig): + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Sam2VideoConfig, device=None): super().__init__() - self.dim = config.memory_attention_hidden_size // ( + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters(config: Sam2VideoConfig, device=None, **kwargs) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = config.memory_attention_hidden_size // ( config.memory_attention_downsample_rate * config.memory_attention_num_attention_heads ) - # Ensure even dimension for proper axial splitting - if self.dim % 4 != 0: - raise ValueError("Dimension must be divisible by 4 for axial RoPE") - self.end_x, self.end_y = config.memory_attention_rope_feat_sizes - self.memory_attention_rope_theta = config.memory_attention_rope_theta + spatial_dim = dim // 2 - # directly register the cos and sin embeddings as we have a fixed feature shape - inv_freq = self.create_inv_freq() - self.rope_embeddings_cos = nn.Buffer(inv_freq.cos(), persistent=False) - self.rope_embeddings_sin = nn.Buffer(inv_freq.sin(), persistent=False) + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor @torch.no_grad() - def forward(self) -> tuple[torch.Tensor, torch.Tensor]: - # As the feature map size is fixed, we can just return the pre-computed embeddings. - return self.rope_embeddings_cos, self.rope_embeddings_sin + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + # Ignore copy + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ - def create_inv_freq(self): - freqs = 1.0 / ( - self.memory_attention_rope_theta ** (torch.arange(0, self.dim, 4)[: (self.dim // 4)].float() / self.dim) - ) - # Generate 2D position indices for axial rotary embedding - flattened_indices = torch.arange(self.end_x * self.end_y, dtype=torch.long) - x_positions = flattened_indices % self.end_x - y_positions = torch.div(flattened_indices, self.end_x, rounding_mode="floor") - freqs_x = torch.outer(x_positions, freqs).float() - freqs_y = torch.outer(y_positions, freqs).float() - inv_freq = torch.cat([freqs_x, freqs_y], dim=-1) - inv_freq = inv_freq.repeat_interleave(2, dim=-1) - return inv_freq + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1)[None, ...] + return freq_hw.repeat_interleave(2, dim=-1) def rotate_pairwise(x): @@ -973,12 +1004,26 @@ def forward( class Sam2VideoMemoryAttention(nn.Module): def __init__(self, config: Sam2VideoConfig): super().__init__() + self.config = config self.layers = nn.ModuleList( [Sam2VideoMemoryAttentionLayer(config) for _ in range(config.memory_attention_num_layers)] ) self.layer_norm = nn.LayerNorm(config.memory_attention_hidden_size) self.rotary_emb = Sam2VideoVisionRotaryEmbedding(config=config) + position_ids = self.precompute_positions(config) + self.position_ids = nn.Buffer(position_ids, persistent=False) + + @staticmethod + def precompute_positions(config: Sam2VideoConfig): + hpos_ids, wpos_ids = torch.meshgrid( + torch.arange(config.memory_attention_rope_feat_sizes[1]), + torch.arange(config.memory_attention_rope_feat_sizes[0]), + indexing="ij", + ) + position_ids = torch.stack([wpos_ids.flatten(), hpos_ids.flatten()], dim=-1) + return position_ids + def forward( self, current_vision_features: torch.Tensor, @@ -1008,7 +1053,7 @@ def forward( output = output.transpose(0, 1) memory = memory.transpose(0, 1).unsqueeze(1) memory_posision_embeddings = memory_posision_embeddings.transpose(0, 1).unsqueeze(1) - rope_position_embeddings = self.rotary_emb() + rope_position_embeddings = self.rotary_emb(output, self.position_ids) for layer in self.layers: output = layer( queries=output.unsqueeze(1) if output.ndim == 3 else output, diff --git a/src/transformers/models/sam2_video/modular_sam2_video.py b/src/transformers/models/sam2_video/modular_sam2_video.py index 0bcaa1164f10..b8d2430eedd0 100644 --- a/src/transformers/models/sam2_video/modular_sam2_video.py +++ b/src/transformers/models/sam2_video/modular_sam2_video.py @@ -34,11 +34,7 @@ from ...modeling_layers import GradientCheckpointingLayer from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import ProcessorMixin, Unpack -from ...utils import ( - ModelOutput, - auto_docstring, - logging, -) +from ...utils import ModelOutput, auto_docstring, logging from ...utils.generic import TransformersKwargs from ...utils.output_capturing import OutputRecorder from ...video_utils import VideoInput @@ -58,6 +54,7 @@ eager_attention_forward, ) from ..sam2.processing_sam2 import Sam2Processor +from ..sam3.modeling_sam3 import Sam3ViTRotaryEmbedding logger = logging.get_logger(__name__) @@ -117,8 +114,6 @@ class Sam2VideoConfig(PreTrainedConfig): The non-linear activation function in the feedforward network in the memory attention module. memory_attention_dropout (`float`, *optional*, defaults to 0.1): The dropout rate for the memory attention module. - memory_attention_rope_theta (`float`, *optional*, defaults to 10000): - The Rope theta parameter. memory_attention_rope_feat_sizes (`list[int]`, *optional*, defaults to `[64, 64]`): The feature sizes for the Rope positional encoding. memory_attention_rope_dropout (`float`, *optional*, defaults to 0.1): @@ -184,6 +179,7 @@ class Sam2VideoConfig(PreTrainedConfig): ```""" model_type = "sam2_video" + default_rope_type = "axial" sub_configs = { "vision_config": AutoConfig, "prompt_encoder_config": Sam2VideoPromptEncoderConfig, @@ -213,11 +209,12 @@ class Sam2VideoConfig(PreTrainedConfig): memory_attention_feed_forward_hidden_size: int = 2048 memory_attention_feed_forward_hidden_act: str = "relu" memory_attention_dropout: float | int = 0.1 - memory_attention_rope_theta: int = 10000 memory_attention_rope_feat_sizes: list[int] | None = None memory_attention_rope_dropout: float | int = 0.1 memory_encoder_hidden_size: int = 256 memory_encoder_output_channels: int = 64 + rope_parameters: dict | None = None + mask_downsampler_embed_dim: int = 256 mask_downsampler_kernel_size: int = 3 mask_downsampler_stride: int = 2 @@ -255,6 +252,22 @@ def __post_init__(self, **kwargs): super().__post_init__(**kwargs) + @property + def memory_attention_rope_theta(self): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + return self.rope_parameters.get("rope_theta", 10_000) + + @memory_attention_rope_theta.setter + def memory_attention_rope_theta(self, value): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + self.rope_parameters["rope_theta"] = value + class Sam2VideoInferenceCache: """Cache for vision features and model constants.""" @@ -937,54 +950,36 @@ def _init_weights(self, module): if isinstance(module, Sam2VideoMemoryFuserCXBlock): if module.scale is not None: init.zeros_(module.scale) - elif isinstance(module, Sam2VideoVisionRotaryEmbedding): - inv_freq = module.create_inv_freq() - init.copy_(module.rope_embeddings_cos, inv_freq.cos()) - init.copy_(module.rope_embeddings_sin, inv_freq.sin()) elif isinstance(module, Sam2VideoPositionalEmbedding): init.normal_(module.positional_embedding, std=module.scale) + elif isinstance(module, Sam2VideoMemoryAttention): + position_ids = module.precompute_positions(module.config) + init.copy_(module.position_ids, position_ids) -class Sam2VideoVisionRotaryEmbedding(nn.Module): - """ - Vision Rotary Position Embedding for SAM2, following transformers library standards. - Supports 2D (axial) rotary embeddings for spatial dimensions. - """ +class Sam2VideoVisionRotaryEmbedding(Sam3ViTRotaryEmbedding): + def __init__(self, config: Sam2VideoConfig, device=None): + super().__init__(config, device=device) - def __init__(self, config: Sam2VideoConfig): - super().__init__() - self.dim = config.memory_attention_hidden_size // ( + def compute_axial_rope_parameters(config: Sam2VideoConfig, device=None, **kwargs) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = config.memory_attention_hidden_size // ( config.memory_attention_downsample_rate * config.memory_attention_num_attention_heads ) - # Ensure even dimension for proper axial splitting - if self.dim % 4 != 0: - raise ValueError("Dimension must be divisible by 4 for axial RoPE") - self.end_x, self.end_y = config.memory_attention_rope_feat_sizes - self.memory_attention_rope_theta = config.memory_attention_rope_theta + spatial_dim = dim // 2 - # directly register the cos and sin embeddings as we have a fixed feature shape - inv_freq = self.create_inv_freq() - self.rope_embeddings_cos = nn.Buffer(inv_freq.cos(), persistent=False) - self.rope_embeddings_sin = nn.Buffer(inv_freq.sin(), persistent=False) - - @torch.no_grad() - def forward(self) -> tuple[torch.Tensor, torch.Tensor]: - # As the feature map size is fixed, we can just return the pre-computed embeddings. - return self.rope_embeddings_cos, self.rope_embeddings_sin - - def create_inv_freq(self): - freqs = 1.0 / ( - self.memory_attention_rope_theta ** (torch.arange(0, self.dim, 4)[: (self.dim // 4)].float() / self.dim) - ) - # Generate 2D position indices for axial rotary embedding - flattened_indices = torch.arange(self.end_x * self.end_y, dtype=torch.long) - x_positions = flattened_indices % self.end_x - y_positions = torch.div(flattened_indices, self.end_x, rounding_mode="floor") - freqs_x = torch.outer(x_positions, freqs).float() - freqs_y = torch.outer(y_positions, freqs).float() - inv_freq = torch.cat([freqs_x, freqs_y], dim=-1) - inv_freq = inv_freq.repeat_interleave(2, dim=-1) - return inv_freq + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor def rotate_pairwise(x): @@ -1180,12 +1175,26 @@ def forward( class Sam2VideoMemoryAttention(nn.Module): def __init__(self, config: Sam2VideoConfig): super().__init__() + self.config = config self.layers = nn.ModuleList( [Sam2VideoMemoryAttentionLayer(config) for _ in range(config.memory_attention_num_layers)] ) self.layer_norm = nn.LayerNorm(config.memory_attention_hidden_size) self.rotary_emb = Sam2VideoVisionRotaryEmbedding(config=config) + position_ids = self.precompute_positions(config) + self.position_ids = nn.Buffer(position_ids, persistent=False) + + @staticmethod + def precompute_positions(config: Sam2VideoConfig): + hpos_ids, wpos_ids = torch.meshgrid( + torch.arange(config.memory_attention_rope_feat_sizes[1]), + torch.arange(config.memory_attention_rope_feat_sizes[0]), + indexing="ij", + ) + position_ids = torch.stack([wpos_ids.flatten(), hpos_ids.flatten()], dim=-1) + return position_ids + def forward( self, current_vision_features: torch.Tensor, @@ -1215,7 +1224,7 @@ def forward( output = output.transpose(0, 1) memory = memory.transpose(0, 1).unsqueeze(1) memory_posision_embeddings = memory_posision_embeddings.transpose(0, 1).unsqueeze(1) - rope_position_embeddings = self.rotary_emb() + rope_position_embeddings = self.rotary_emb(output, self.position_ids) for layer in self.layers: output = layer( queries=output.unsqueeze(1) if output.ndim == 3 else output, diff --git a/src/transformers/models/sam3/configuration_sam3.py b/src/transformers/models/sam3/configuration_sam3.py index a933b1ff794d..5cb044969d29 100644 --- a/src/transformers/models/sam3/configuration_sam3.py +++ b/src/transformers/models/sam3/configuration_sam3.py @@ -24,8 +24,6 @@ @strict class Sam3ViTConfig(PreTrainedConfig): r""" - rope_theta (`float`, *optional*, defaults to 10000.0): - Base frequency for RoPE. window_size (`int`, *optional*, defaults to 24): Window size for windowed attention. global_attn_indexes (`list[int]`, *optional*, defaults to `[7, 15, 23, 31]`): @@ -38,6 +36,7 @@ class Sam3ViTConfig(PreTrainedConfig): base_config_key = "backbone_config" model_type = "sam3_vit_model" + default_rope_type = "axial" hidden_size: int = 1024 intermediate_size: int = 4736 @@ -49,19 +48,20 @@ class Sam3ViTConfig(PreTrainedConfig): hidden_act: str = "gelu" layer_norm_eps: float = 1e-6 attention_dropout: float | int = 0.0 - rope_theta: float = 10000.0 window_size: int = 24 global_attn_indexes: list[int] | None = None layer_scale_init_value: float | None = None pretrain_image_size: int | list[int] | tuple[int, int] = 336 hidden_dropout: float | int = 0.0 initializer_range: float = 0.02 + rope_parameters: dict | None = None def __post_init__(self, **kwargs): - super().__post_init__(**kwargs) if self.global_attn_indexes is None: self.global_attn_indexes = [7, 15, 23, 31] + super().__post_init__(**kwargs) + @auto_docstring(checkpoint="facebook/sam3") @strict diff --git a/src/transformers/models/sam3/modeling_sam3.py b/src/transformers/models/sam3/modeling_sam3.py index f5474eee203f..e0754ac4bf92 100644 --- a/src/transformers/models/sam3/modeling_sam3.py +++ b/src/transformers/models/sam3/modeling_sam3.py @@ -22,14 +22,6 @@ import torch.nn.functional as F from torch import Tensor -from ...utils import is_torchvision_available - - -if is_torchvision_available(): - import torchvision - -from transformers import CLIPTextModelWithProjection - from ... import initialization as init from ...activations import ACT2FN from ...masking_utils import create_bidirectional_mask @@ -42,15 +34,18 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...pytorch_utils import compile_compatible_method_lru_cache -from ...utils import auto_docstring, can_return_tuple, logging +from ...utils import auto_docstring, can_return_tuple, is_torchvision_available, logging +from ...utils.deprecation import deprecate_kwarg from ...utils.generic import ( TransformersKwargs, is_flash_attention_requested, + maybe_autocast, merge_with_config_defaults, ) from ...utils.import_utils import requires from ...utils.output_capturing import capture_outputs from ..auto import AutoModel +from ..clip import CLIPTextModelWithProjection # trf-ignore: TRF009 from .configuration_sam3 import ( Sam3Config, Sam3DETRDecoderConfig, @@ -62,6 +57,9 @@ ) +if is_torchvision_available(): + import torchvision + logger = logging.get_logger(__name__) @@ -406,39 +404,71 @@ def forward( return attn_output, attn_weights +# Copied from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl.Qwen2_5_VLVisionRotaryEmbedding with Qwen2_5_VLVision->Sam3ViT class Sam3ViTRotaryEmbedding(nn.Module): """ - Vision Rotary Position Embedding for SAM3, following transformers library standards. - Supports 2D (axial) rotary embeddings for spatial dimensions. + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. """ - def __init__(self, config: Sam3ViTConfig, end_x: int, end_y: int, scale: float = 1.0): + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Sam3ViTConfig, device=None): super().__init__() - dim = config.hidden_size // config.num_attention_heads - # Ensure even dimension for proper axial splitting - if dim % 4 != 0: - raise ValueError("Dimension must be divisible by 4 for axial RoPE") - self.end_x, self.end_y = end_x, end_y - self.dim = dim - self.rope_theta = config.rope_theta - self.scale = scale - freqs = 1.0 / (config.rope_theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim)) - - flattened_indices = torch.arange(end_x * end_y, dtype=torch.long) - x_positions = (flattened_indices % end_x) * scale - y_positions = torch.div(flattened_indices, end_x, rounding_mode="floor") * scale - freqs_x = torch.outer(x_positions, freqs).float() - freqs_y = torch.outer(y_positions, freqs).float() - inv_freq = torch.cat([freqs_x, freqs_y], dim=-1) - inv_freq = inv_freq.repeat_interleave(2, dim=-1) - # directly register the cos and sin embeddings as we have a fixed feature shape - self.rope_embeddings_cos = nn.Buffer(inv_freq.cos(), persistent=False) - self.rope_embeddings_sin = nn.Buffer(inv_freq.sin(), persistent=False) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters(config: Sam3ViTConfig, device=None, **kwargs) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor @torch.no_grad() - def forward(self) -> tuple[torch.Tensor, torch.Tensor]: - # As the feature map size is fixed for each stage, we can just return the pre-computed embeddings. - return self.rope_embeddings_cos, self.rope_embeddings_sin + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + # Ignore copy + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1)[None, ...] + return freq_hw.repeat_interleave(2, dim=-1) def rotate_pairwise(x): @@ -715,27 +745,41 @@ class Sam3ViTLayer(GradientCheckpointingLayer): def __init__(self, config: Sam3ViTConfig, window_size: int = 0) -> None: super().__init__() + self.config = config hidden_size = config.hidden_size - image_size = config.image_size - image_size = image_size if isinstance(image_size, (list, tuple)) else (image_size, image_size) - - patch_size = config.patch_size - patch_size = patch_size if isinstance(patch_size, (list, tuple)) else (patch_size, patch_size) - - input_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1]) self.layer_norm1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps) - rotary_input_size = input_size if window_size == 0 else (window_size, window_size) - rotary_scale = config.window_size / rotary_input_size[0] - self.rotary_emb = Sam3ViTRotaryEmbedding( - config, end_x=rotary_input_size[0], end_y=rotary_input_size[1], scale=rotary_scale - ) + self.rotary_emb = Sam3ViTRotaryEmbedding(config) self.attention = Sam3ViTRoPEAttention(config) self.layer_norm2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps) self.mlp = Sam3MLP(config) self.dropout = nn.Dropout(config.hidden_dropout) - self.window_size = window_size + position_ids = self.precompute_positions(config, window_size) + self.position_ids = nn.Buffer(position_ids, persistent=False) + + @staticmethod + def precompute_positions(config: Sam3ViTConfig, window_size: int): + if window_size > 0: + hw_grid = (window_size, window_size) + else: + image_size = config.image_size + image_size = image_size if isinstance(image_size, (list, tuple)) else (image_size, image_size) + + patch_size = config.patch_size + patch_size = patch_size if isinstance(patch_size, (list, tuple)) else (patch_size, patch_size) + + hw_grid = (image_size[1] // patch_size[1], image_size[0] // patch_size[0]) + + hpos_ids, wpos_ids = torch.meshgrid( + torch.arange(hw_grid[0]), + torch.arange(hw_grid[1]), + indexing="ij", + ) + position_ids = torch.stack([wpos_ids.flatten(), hpos_ids.flatten()], dim=-1) + position_ids = position_ids * (config.window_size / hw_grid[1]) + return position_ids + def forward( self, hidden_states: torch.Tensor, @@ -750,7 +794,7 @@ def forward( # Partition into non-overlapping windows for efficient attention hidden_states, pad_height_width = window_partition(hidden_states, self.window_size) - position_embeddings = self.rotary_emb() + position_embeddings = self.rotary_emb(hidden_states, self.position_ids) hidden_states, _ = self.attention(hidden_states, position_embeddings, **kwargs) if self.window_size > 0: @@ -782,19 +826,9 @@ def _init_weights(self, module): super()._init_weights(module) if isinstance(module, Sam3ViTEmbeddings): init.normal_(module.position_embeddings, mean=0.0, std=self.config.initializer_range) - elif isinstance(module, Sam3ViTRotaryEmbedding): - end_x, end_y = module.end_x, module.end_y - dim = module.dim - freqs = 1.0 / (module.rope_theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim)) - flattened_indices = torch.arange(end_x * end_y, dtype=torch.long) - x_positions = (flattened_indices % end_x) * module.scale - y_positions = torch.div(flattened_indices, end_x, rounding_mode="floor") * module.scale - freqs_x = torch.outer(x_positions, freqs).float() - freqs_y = torch.outer(y_positions, freqs).float() - inv_freq = torch.cat([freqs_x, freqs_y], dim=-1) - inv_freq = inv_freq.repeat_interleave(2, dim=-1) - init.copy_(module.rope_embeddings_cos, inv_freq.cos()) - init.copy_(module.rope_embeddings_sin, inv_freq.sin()) + elif isinstance(module, Sam3ViTLayer): + position_ids = module.precompute_positions(module.config, module.window_size) + init.copy_(module.position_ids, position_ids) @auto_docstring diff --git a/src/transformers/models/sam3_lite_text/modeling_sam3_lite_text.py b/src/transformers/models/sam3_lite_text/modeling_sam3_lite_text.py index 9f92f7f311de..eccee813e11e 100644 --- a/src/transformers/models/sam3_lite_text/modeling_sam3_lite_text.py +++ b/src/transformers/models/sam3_lite_text/modeling_sam3_lite_text.py @@ -53,7 +53,6 @@ if is_torchvision_available(): import torchvision - logger = logging.get_logger(__name__) diff --git a/src/transformers/models/sam3_tracker_video/configuration_sam3_tracker_video.py b/src/transformers/models/sam3_tracker_video/configuration_sam3_tracker_video.py index 99359da979d2..fe6853a54d8f 100644 --- a/src/transformers/models/sam3_tracker_video/configuration_sam3_tracker_video.py +++ b/src/transformers/models/sam3_tracker_video/configuration_sam3_tracker_video.py @@ -22,10 +22,13 @@ from huggingface_hub.dataclasses import strict from ...configuration_utils import PreTrainedConfig -from ...utils import auto_docstring +from ...utils import auto_docstring, logging from ..auto import CONFIG_MAPPING, AutoConfig +logger = logging.get_logger(__name__) + + @auto_docstring(checkpoint="facebook/sam3") @strict class Sam3TrackerVideoPromptEncoderConfig(PreTrainedConfig): @@ -135,8 +138,6 @@ class Sam3TrackerVideoConfig(PreTrainedConfig): The non-linear activation function in the feedforward network in the memory attention module. memory_attention_dropout (`float`, *optional*, defaults to 0.1): The dropout rate for the memory attention module. - memory_attention_rope_theta (`float`, *optional*, defaults to 10000): - The Rope theta parameter. memory_attention_rope_feat_sizes (`list[int]`, *optional*, defaults to `[72, 72]`): The feature sizes for the Rope positional encoding. memory_attention_rope_dropout (`float`, *optional*, defaults to 0.1): @@ -202,6 +203,7 @@ class Sam3TrackerVideoConfig(PreTrainedConfig): ```""" model_type = "sam3_tracker_video" + default_rope_type = "axial" sub_configs = { "vision_config": AutoConfig, "prompt_encoder_config": Sam3TrackerVideoPromptEncoderConfig, @@ -230,11 +232,12 @@ class Sam3TrackerVideoConfig(PreTrainedConfig): memory_attention_feed_forward_hidden_size: int = 2048 memory_attention_feed_forward_hidden_act: str = "relu" memory_attention_dropout: float | int = 0.1 - memory_attention_rope_theta: int = 10000 memory_attention_rope_feat_sizes: list | None = None memory_attention_rope_dropout: float | int = 0.1 memory_encoder_hidden_size: int = 256 memory_encoder_output_channels: int = 64 + rope_parameters: dict | None = None + mask_downsampler_embed_dim: int = 256 mask_downsampler_kernel_size: int = 3 mask_downsampler_stride: int = 2 @@ -273,8 +276,25 @@ def __post_init__(self, **kwargs): self.mask_decoder_config = Sam3TrackerVideoMaskDecoderConfig() self.image_size = kwargs.pop("image_size", 1008) + super().__post_init__(**kwargs) + @property + def memory_attention_rope_theta(self): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + return self.rope_parameters.get("rope_theta", 10_000) + + @memory_attention_rope_theta.setter + def memory_attention_rope_theta(self, value): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + self.rope_parameters["rope_theta"] = value + @property def image_size(self): """Image size for the tracker video model.""" diff --git a/src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py b/src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py index d6f76c9354d8..b10370237ab7 100644 --- a/src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py +++ b/src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py @@ -41,7 +41,8 @@ from ...processing_utils import Unpack from ...pytorch_utils import compile_compatible_method_lru_cache from ...utils import ModelOutput, TransformersKwargs, auto_docstring, can_return_tuple, logging -from ...utils.generic import is_flash_attention_requested +from ...utils.deprecation import deprecate_kwarg +from ...utils.generic import is_flash_attention_requested, maybe_autocast from ...utils.output_capturing import OutputRecorder from ..auto import AutoModel from .configuration_sam3_tracker_video import ( @@ -735,54 +736,81 @@ def _init_weights(self, module): if isinstance(module, Sam3TrackerVideoMemoryFuserCXBlock): if module.scale is not None: init.zeros_(module.scale) - elif isinstance(module, Sam3TrackerVideoVisionRotaryEmbedding): - inv_freq = module.create_inv_freq() - init.copy_(module.rope_embeddings_cos, inv_freq.cos()) - init.copy_(module.rope_embeddings_sin, inv_freq.sin()) elif isinstance(module, Sam3TrackerVideoPositionalEmbedding): init.normal_(module.positional_embedding, std=module.scale) + elif isinstance(module, Sam3TrackerVideoMemoryAttention): + position_ids = module.precompute_positions(module.config) + init.copy_(module.position_ids, position_ids) class Sam3TrackerVideoVisionRotaryEmbedding(nn.Module): """ - Vision Rotary Position Embedding for SAM2, following transformers library standards. - Supports 2D (axial) rotary embeddings for spatial dimensions. + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. """ - def __init__(self, config: Sam3TrackerVideoConfig): + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: Sam3TrackerVideoConfig, device=None): super().__init__() - self.dim = config.memory_attention_hidden_size // ( + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) + + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: Sam3TrackerVideoConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = config.memory_attention_hidden_size // ( config.memory_attention_downsample_rate * config.memory_attention_num_attention_heads ) - # Ensure even dimension for proper axial splitting - if self.dim % 4 != 0: - raise ValueError("Dimension must be divisible by 4 for axial RoPE") - self.end_x, self.end_y = config.memory_attention_rope_feat_sizes - self.memory_attention_rope_theta = config.memory_attention_rope_theta + spatial_dim = dim // 2 - # directly register the cos and sin embeddings as we have a fixed feature shape - inv_freq = self.create_inv_freq() - self.rope_embeddings_cos = nn.Buffer(inv_freq.cos(), persistent=False) - self.rope_embeddings_sin = nn.Buffer(inv_freq.sin(), persistent=False) + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor @torch.no_grad() - def forward(self) -> tuple[torch.Tensor, torch.Tensor]: - # As the feature map size is fixed, we can just return the pre-computed embeddings. - return self.rope_embeddings_cos, self.rope_embeddings_sin + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + # Ignore copy + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ - def create_inv_freq(self): - freqs = 1.0 / ( - self.memory_attention_rope_theta ** (torch.arange(0, self.dim, 4)[: (self.dim // 4)].float() / self.dim) - ) - # Generate 2D position indices for axial rotary embedding - flattened_indices = torch.arange(self.end_x * self.end_y, dtype=torch.long) - x_positions = flattened_indices % self.end_x - y_positions = torch.div(flattened_indices, self.end_x, rounding_mode="floor") - freqs_x = torch.outer(x_positions, freqs).float() - freqs_y = torch.outer(y_positions, freqs).float() - inv_freq = torch.cat([freqs_x, freqs_y], dim=-1) - inv_freq = inv_freq.repeat_interleave(2, dim=-1) - return inv_freq + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1)[None, ...] + return freq_hw.repeat_interleave(2, dim=-1) def rotate_pairwise(x): @@ -978,12 +1006,26 @@ def forward( class Sam3TrackerVideoMemoryAttention(nn.Module): def __init__(self, config: Sam3TrackerVideoConfig): super().__init__() + self.config = config self.layers = nn.ModuleList( [Sam3TrackerVideoMemoryAttentionLayer(config) for _ in range(config.memory_attention_num_layers)] ) self.layer_norm = nn.LayerNorm(config.memory_attention_hidden_size) self.rotary_emb = Sam3TrackerVideoVisionRotaryEmbedding(config=config) + position_ids = self.precompute_positions(config) + self.position_ids = nn.Buffer(position_ids, persistent=False) + + @staticmethod + def precompute_positions(config: Sam3TrackerVideoConfig): + hpos_ids, wpos_ids = torch.meshgrid( + torch.arange(config.memory_attention_rope_feat_sizes[1]), + torch.arange(config.memory_attention_rope_feat_sizes[0]), + indexing="ij", + ) + position_ids = torch.stack([wpos_ids.flatten(), hpos_ids.flatten()], dim=-1) + return position_ids + def forward( self, current_vision_features: torch.Tensor, @@ -1013,7 +1055,7 @@ def forward( output = output.transpose(0, 1) memory = memory.transpose(0, 1).unsqueeze(1) memory_posision_embeddings = memory_posision_embeddings.transpose(0, 1).unsqueeze(1) - rope_position_embeddings = self.rotary_emb() + rope_position_embeddings = self.rotary_emb(output, self.position_ids) for layer in self.layers: output = layer( queries=output.unsqueeze(1) if output.ndim == 3 else output, diff --git a/src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py b/src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py index e214448b6399..015b2d941455 100644 --- a/src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py +++ b/src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py @@ -18,7 +18,7 @@ from ...configuration_utils import PreTrainedConfig from ...processing_utils import Unpack -from ...utils import TransformersKwargs, auto_docstring, can_return_tuple +from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging from ..auto import CONFIG_MAPPING, AutoConfig, AutoModel from ..sam2_video.configuration_sam2_video import Sam2VideoMaskDecoderConfig, Sam2VideoPromptEncoderConfig from ..sam2_video.modeling_sam2_video import ( @@ -52,6 +52,9 @@ from ..sam2_video.processing_sam2_video import Sam2VideoProcessor +logger = logging.get_logger(__name__) + + @auto_docstring(checkpoint="facebook/sam3") @strict class Sam3TrackerVideoPromptEncoderConfig(Sam2VideoPromptEncoderConfig): @@ -126,8 +129,6 @@ class Sam3TrackerVideoConfig(PreTrainedConfig): The non-linear activation function in the feedforward network in the memory attention module. memory_attention_dropout (`float`, *optional*, defaults to 0.1): The dropout rate for the memory attention module. - memory_attention_rope_theta (`float`, *optional*, defaults to 10000): - The Rope theta parameter. memory_attention_rope_feat_sizes (`list[int]`, *optional*, defaults to `[72, 72]`): The feature sizes for the Rope positional encoding. memory_attention_rope_dropout (`float`, *optional*, defaults to 0.1): @@ -193,6 +194,7 @@ class Sam3TrackerVideoConfig(PreTrainedConfig): ```""" model_type = "sam3_tracker_video" + default_rope_type = "axial" sub_configs = { "vision_config": AutoConfig, "prompt_encoder_config": Sam3TrackerVideoPromptEncoderConfig, @@ -221,11 +223,12 @@ class Sam3TrackerVideoConfig(PreTrainedConfig): memory_attention_feed_forward_hidden_size: int = 2048 memory_attention_feed_forward_hidden_act: str = "relu" memory_attention_dropout: float | int = 0.1 - memory_attention_rope_theta: int = 10000 memory_attention_rope_feat_sizes: list | None = None memory_attention_rope_dropout: float | int = 0.1 memory_encoder_hidden_size: int = 256 memory_encoder_output_channels: int = 64 + rope_parameters: dict | None = None + mask_downsampler_embed_dim: int = 256 mask_downsampler_kernel_size: int = 3 mask_downsampler_stride: int = 2 @@ -264,8 +267,25 @@ def __post_init__(self, **kwargs): self.mask_decoder_config = Sam3TrackerVideoMaskDecoderConfig() self.image_size = kwargs.pop("image_size", 1008) + super().__post_init__(**kwargs) + @property + def memory_attention_rope_theta(self): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + return self.rope_parameters.get("rope_theta", 10_000) + + @memory_attention_rope_theta.setter + def memory_attention_rope_theta(self, value): + logger.warning_once( + "`memory_attention_rope_theta` is deprecated and will be removed in v5.0. " + "Use `rope_parameters['rope_theta']` instead." + ) + self.rope_parameters["rope_theta"] = value + @property def image_size(self): """Image size for the tracker video model.""" @@ -333,7 +353,8 @@ class Sam3TrackerVideoPreTrainedModel(Sam2VideoPreTrainedModel): class Sam3TrackerVideoVisionRotaryEmbedding(Sam2VideoVisionRotaryEmbedding): - pass + def __init__(self, config: Sam3TrackerVideoConfig, device=None): + super().__init__(config, device=device) class Sam3TrackerVideoRoPEAttention(Sam2VideoRoPEAttention): diff --git a/src/transformers/models/step3p7/configuration_step3p7.py b/src/transformers/models/step3p7/configuration_step3p7.py index 04bdb10ed6aa..d96f4fb31798 100644 --- a/src/transformers/models/step3p7/configuration_step3p7.py +++ b/src/transformers/models/step3p7/configuration_step3p7.py @@ -58,6 +58,7 @@ class Step3p7VisionConfig(PreTrainedConfig): hidden_act: str = "quick_gelu" layer_norm_eps: float = 1e-5 attention_dropout: float | int = 0.0 + default_rope_type = "axial" # New fields mlp_ratio: float = 8960 / 1536 layer_scale_init_value: float = 0.1 diff --git a/src/transformers/models/step3p7/modeling_step3p7.py b/src/transformers/models/step3p7/modeling_step3p7.py index 9fe25214ebec..8d74b5f1a761 100644 --- a/src/transformers/models/step3p7/modeling_step3p7.py +++ b/src/transformers/models/step3p7/modeling_step3p7.py @@ -50,18 +50,21 @@ class Step3p7VisionRotaryEmbedding(nn.Module): + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + @deprecate_kwarg("device", version="5.18") def __init__(self, config: Step3p7VisionConfig, device=None): super().__init__() - self.max_seq_len_cached = config.max_position_embeddings - self.original_max_seq_len = config.max_position_embeddings - self.config = config self.rope_type = self.config.rope_parameters["rope_type"] - rope_init_fn: Callable = self.compute_default_rope_parameters - if self.rope_type != "default": - rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") inv_freq, self.attention_scaling = rope_init_fn(self.config, device) self.inv_freq = nn.Buffer(inv_freq, persistent=False) @@ -69,7 +72,7 @@ def __init__(self, config: Step3p7VisionConfig, device=None): @staticmethod @deprecate_kwarg("device", version="5.18") - def compute_default_rope_parameters( + def compute_axial_rope_parameters( config: Step3p7VisionConfig, device=None, **kwargs ) -> tuple[torch.Tensor, float]: """ @@ -83,11 +86,6 @@ def compute_default_rope_parameters( """ base = config.rope_parameters["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads - - # The reference implementation computes RoPE frequencies INDEPENDENTLY - # for each spatial dimension using the partitioned head_dim (head_dim // ndim), - # so both x and y dimensions get identical frequency ranges. - # This is different from splitting the global inv_freq between dimensions. spatial_dim = dim // 2 attention_factor = 1.0 # Unused in this type of RoPE @@ -95,14 +93,27 @@ def compute_default_rope_parameters( return inv_freq.to(device), attention_factor @torch.no_grad() - def forward(self, x: torch.Tensor, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + def forward(self, x, position_ids): + inv_freq_expanded = self.inv_freq[None, ...].float() + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with maybe_autocast(device_type=device_type, enabled=False): - freqs = (position_ids[..., None].float() * self.inv_freq.to(x.device)).flatten(-2) - emb = torch.cat((freqs, freqs), dim=-1) - cos = (emb.cos() * self.attention_scaling).to(dtype=x.dtype) - sin = (emb.sin() * self.attention_scaling).to(dtype=x.dtype) - return cos, sin + freqs = position_ids_expanded @ inv_freq_expanded + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos.to(x.dtype), sin.to(x.dtype) + + # Ignore copy + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq = freq.flatten(-2) + return torch.cat((freq, freq), dim=-1) class Step3p7VisionMLP(nn.Module): diff --git a/src/transformers/models/step3p7/modular_step3p7.py b/src/transformers/models/step3p7/modular_step3p7.py index 3c714f671b03..43e91a56b9a5 100644 --- a/src/transformers/models/step3p7/modular_step3p7.py +++ b/src/transformers/models/step3p7/modular_step3p7.py @@ -39,7 +39,6 @@ no_inherit_decorator, torch_int, ) -from ...utils.generic import maybe_autocast from ...utils.output_capturing import capture_outputs from ...vision_utils import get_vision_position_ids from ..deepseek_ocr2.modeling_deepseek_ocr2 import DeepseekOcr2ForConditionalGeneration, DeepseekOcr2Model @@ -91,6 +90,7 @@ class Step3p7VisionConfig(SiglipVisionConfig): model_type = "step3p5_vision" base_config_key = "vision_config" + default_rope_type = "axial" # SiGLIP field overrides hidden_size: int = 1536 @@ -589,15 +589,12 @@ def preprocess(self, images: ImageInput, **kwargs: Unpack[Step3p7ImageProcessorK class Step3p7VisionRotaryEmbedding(Gemma4VisionRotaryEmbedding): - @torch.no_grad() - def forward(self, x: torch.Tensor, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" - with maybe_autocast(device_type=device_type, enabled=False): - freqs = (position_ids[..., None].float() * self.inv_freq.to(x.device)).flatten(-2) - emb = torch.cat((freqs, freqs), dim=-1) - cos = (emb.cos() * self.attention_scaling).to(dtype=x.dtype) - sin = (emb.sin() * self.attention_scaling).to(dtype=x.dtype) - return cos, sin + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq = freq.flatten(-2) + return torch.cat((freq, freq), dim=-1) class Step3p7VisionMLP(MiniMaxM3VLVisionMLP): diff --git a/src/transformers/models/video_llama_3/configuration_video_llama_3.py b/src/transformers/models/video_llama_3/configuration_video_llama_3.py index 55230680d477..4e63a95e2cf6 100644 --- a/src/transformers/models/video_llama_3/configuration_video_llama_3.py +++ b/src/transformers/models/video_llama_3/configuration_video_llama_3.py @@ -55,7 +55,9 @@ class VideoLlama3VisionConfig(PreTrainedConfig): hidden_act: str = "gelu_pytorch_tanh" layer_norm_eps: float = 1e-6 attention_dropout: float | int = 0.0 + default_rope_type = "axial" initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="lkhl/VideoLLaMA3-2B-Image-HF") diff --git a/src/transformers/models/video_llama_3/modeling_video_llama_3.py b/src/transformers/models/video_llama_3/modeling_video_llama_3.py index f43d9ff15d73..90d3a5de2bc4 100644 --- a/src/transformers/models/video_llama_3/modeling_video_llama_3.py +++ b/src/transformers/models/video_llama_3/modeling_video_llama_3.py @@ -25,7 +25,6 @@ import torch.nn as nn from torch.nn import LayerNorm -from ... import initialization as init from ...activations import ACT2FN from ...cache_utils import Cache from ...generation import GenerationMixin @@ -34,10 +33,12 @@ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel from ...processing_utils import Unpack from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check +from ...utils.deprecation import deprecate_kwarg from ...utils.generic import ( accepts_precomputed_kwargs, get_max_seqlen, is_flash_attention_requested, + maybe_autocast, merge_with_config_defaults, ) from ...utils.output_capturing import capture_outputs @@ -47,15 +48,69 @@ class VideoLlama3VisionRotaryEmbedding(nn.Module): - def __init__(self, dim: int, theta: float = 10000.0) -> None: + """ + Simple axial 2D rope with same freqs used for H and W grids. The freqs are + pre-computed using `head-dim//4` which is later used to concat H and W positions. + The final angles rotate over the whole head dim, no partial rotation involved. + """ + + @deprecate_kwarg("device", version="5.18") + def __init__(self, config: VideoLlama3VisionConfig, device=None): super().__init__() - self.dim = dim - self.theta = theta - inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_axial_rope_parameters + if self.rope_type != "axial": + raise ValueError(f"{self.__class__.__name__} supports only axial rope, but requested {self.rope_type}") + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.inv_freq = nn.Buffer(inv_freq, persistent=False) + self.original_inv_freq = nn.Buffer(inv_freq.clone(), persistent=False) - def forward(self, position_ids: torch.Tensor) -> torch.Tensor: - return (position_ids.unsqueeze(-1) * self.inv_freq).flatten(1) + @staticmethod + @deprecate_kwarg("device", version="5.18") + def compute_axial_rope_parameters( + config: VideoLlama3VisionConfig, device=None, **kwargs + ) -> tuple[torch.Tensor, float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + spatial_dim = dim // 2 + + attention_factor = 1.0 # Unused in this type of RoPE + inv_freq = 1.0 / (base ** (torch.arange(0, spatial_dim, 2, dtype=torch.float) / spatial_dim)) + return inv_freq.to(device), attention_factor + + @torch.no_grad() + def forward(self, x, position_ids): + # position_ids: (2, N) — row 0 = h coords, row 1 = w coords + position_ids_expanded = position_ids[..., None].float() + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): + freqs = position_ids_expanded * self.inv_freq.float() + cos = freqs.cos() * self.attention_scaling + sin = freqs.sin() * self.attention_scaling + + cos = self.recomposition_frequencies(cos) + sin = self.recomposition_frequencies(sin) + return cos, sin + + def recomposition_frequencies(self, freq): + """ + Recompose the frequencies into the final spatial layout used per each grid. + """ + freq_h, freq_w = freq[:, 0], freq[:, 1] + freq_hw = torch.cat([freq_h, freq_w], dim=-1) + return torch.cat([freq_hw, freq_hw], dim=-1) class VideoLlama3VisionEmbeddings(nn.Module): @@ -357,12 +412,6 @@ class VideoLlama3PreTrainedModel(PreTrainedModel): _can_compile_fullgraph = True _supports_attention_backend = True - def _init_weights(self, module): - super()._init_weights(module) - if isinstance(module, VideoLlama3VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - class VideoLlama3VisionModel(VideoLlama3PreTrainedModel): config: VideoLlama3VisionConfig @@ -375,9 +424,7 @@ class VideoLlama3VisionModel(VideoLlama3PreTrainedModel): def __init__(self, config: VideoLlama3VisionConfig): super().__init__(config) - head_dim = config.hidden_size // config.num_attention_heads - - self.rotary_pos_emb = VideoLlama3VisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = VideoLlama3VisionRotaryEmbedding(config) self.embeddings = VideoLlama3VisionEmbeddings(config) self.encoder = VideoLlama3VisionEncoder(config) self.post_layernorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps) @@ -430,9 +477,7 @@ def forward( cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs) hidden_states = self.embeddings(pixel_values.type(self.dtype)) - rotary_pos_emb = self.rotary_pos_emb(position_ids) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) encoder_outputs: BaseModelOutput = self.encoder( hidden_states, diff --git a/src/transformers/models/video_llama_3/modular_video_llama_3.py b/src/transformers/models/video_llama_3/modular_video_llama_3.py index da56df084608..2780bb24583b 100644 --- a/src/transformers/models/video_llama_3/modular_video_llama_3.py +++ b/src/transformers/models/video_llama_3/modular_video_llama_3.py @@ -22,7 +22,6 @@ from huggingface_hub.dataclasses import strict from torch.nn import LayerNorm -from ... import initialization as init from ...cache_utils import Cache from ...configuration_utils import PreTrainedConfig from ...feature_extraction_utils import BatchFeature @@ -44,13 +43,11 @@ ) from ...utils.output_capturing import capture_outputs from ...video_processing_utils import BaseVideoProcessor -from ...video_utils import ( - group_videos_by_shape, - reorder_videos, -) +from ...video_utils import group_videos_by_shape, reorder_videos from ...vision_utils import get_vision_attention_seqlens, get_vision_position_ids from ..auto import CONFIG_MAPPING, AutoConfig from ..auto.modeling_auto import AutoModel +from ..qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLVisionRotaryEmbedding from ..qwen2_vl.image_processing_pil_qwen2_vl import Qwen2VLImageProcessorPil from ..qwen2_vl.image_processing_qwen2_vl import Qwen2VLImageProcessor, Qwen2VLImageProcessorKwargs, smart_resize from ..qwen2_vl.modeling_qwen2_vl import ( @@ -58,13 +55,10 @@ Qwen2VLModel, Qwen2VLPreTrainedModel, TransformersKwargs, - VisionRotaryEmbedding, apply_rotary_pos_emb_vision, eager_attention_forward, ) -from ..qwen2_vl.processing_qwen2_vl import ( - Qwen2VLProcessorKwargs, -) +from ..qwen2_vl.processing_qwen2_vl import Qwen2VLProcessorKwargs from ..qwen2_vl.video_processing_qwen2_vl import Qwen2VLVideoProcessor from ..qwen3_vl.processing_qwen3_vl import Qwen3VLProcessor from ..siglip.configuration_siglip import SiglipVisionConfig @@ -84,8 +78,11 @@ class VideoLlama3VisionConfig(SiglipVisionConfig): model_type = "video_llama_3_vision" base_config_key = "vision_config" + default_rope_type = "axial" + image_size = AttributeError() initializer_range: float = 0.02 + rope_parameters: dict | None = None @auto_docstring(checkpoint="lkhl/VideoLLaMA3-2B-Image-HF") @@ -121,7 +118,7 @@ def __post_init__(self, **kwargs): super().__post_init__(**kwargs) -class VideoLlama3VisionRotaryEmbedding(VisionRotaryEmbedding): +class VideoLlama3VisionRotaryEmbedding(Qwen2_5_VLVisionRotaryEmbedding): pass @@ -315,12 +312,6 @@ class VideoLlama3PreTrainedModel(Qwen2VLPreTrainedModel): config: VideoLlama3Config _no_split_modules = ["VideoLlama3VisionEncoderLayer"] - def _init_weights(self, module): - PreTrainedModel._init_weights(self, module) - if isinstance(module, VideoLlama3VisionRotaryEmbedding): - inv_freq = 1.0 / (module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)) - init.copy_(module.inv_freq, inv_freq) - class VideoLlama3VisionModel(VideoLlama3PreTrainedModel): config: VideoLlama3VisionConfig @@ -333,9 +324,7 @@ class VideoLlama3VisionModel(VideoLlama3PreTrainedModel): def __init__(self, config: VideoLlama3VisionConfig): super().__init__(config) - head_dim = config.hidden_size // config.num_attention_heads - - self.rotary_pos_emb = VideoLlama3VisionRotaryEmbedding(head_dim // 2) + self.rotary_pos_emb = VideoLlama3VisionRotaryEmbedding(config) self.embeddings = VideoLlama3VisionEmbeddings(config) self.encoder = VideoLlama3VisionEncoder(config) self.post_layernorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps) @@ -388,9 +377,7 @@ def forward( cu_seqlens, max_seqlen = get_vision_attention_seqlens(grid_thw, self.config, kwargs=kwargs) hidden_states = self.embeddings(pixel_values.type(self.dtype)) - rotary_pos_emb = self.rotary_pos_emb(position_ids) - emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) - position_embeddings = (emb.cos(), emb.sin()) + position_embeddings = self.rotary_pos_emb(hidden_states, position_ids) encoder_outputs: BaseModelOutput = self.encoder( hidden_states, diff --git a/tests/models/cohere_compass/test_modeling_cohere_compass.py b/tests/models/cohere_compass/test_modeling_cohere_compass.py index 3d64abff76ff..430a5adad2d1 100644 --- a/tests/models/cohere_compass/test_modeling_cohere_compass.py +++ b/tests/models/cohere_compass/test_modeling_cohere_compass.py @@ -90,8 +90,8 @@ def test_rope_parameters_are_per_layer_type(self): **config, "layer_types": ["full_attention", "sliding_attention"], "rope_parameters": { - "full_attention": {"rope_type": "default", "rope_theta": 20_000}, - "sliding_attention": {"rope_type": "default", "rope_theta": 10_000}, + "full_attention": {"rope_type": "default", "rope_theta": 20_000, "mrope_section": [1, 1, 2]}, + "sliding_attention": {"rope_type": "default", "rope_theta": 10_000, "mrope_section": [1, 1, 2]}, }, } ) @@ -115,7 +115,7 @@ def test_null_rope_parameters_disable_position_embeddings(self): "sliding_window": 4, "rope_parameters": { "full_attention": None, - "sliding_attention": {"rope_type": "default", "rope_theta": 10_000}, + "sliding_attention": {"rope_type": "default", "rope_theta": 10_000, "mrope_section": [1, 1, 2]}, }, } ) diff --git a/tests/models/cosmos3_omni/test_modeling_cosmos3_omni.py b/tests/models/cosmos3_omni/test_modeling_cosmos3_omni.py index ed5c0a15e35b..3d8863a41e9e 100644 --- a/tests/models/cosmos3_omni/test_modeling_cosmos3_omni.py +++ b/tests/models/cosmos3_omni/test_modeling_cosmos3_omni.py @@ -74,7 +74,7 @@ def __init__(self, parent, **kwargs): kwargs.setdefault("hidden_act", "silu") kwargs.setdefault("num_attention_heads", 4) kwargs.setdefault("num_key_value_heads", 2) - kwargs.setdefault("head_dim", 8) + kwargs.setdefault("head_dim", 16) kwargs.setdefault("depth", 2) kwargs.setdefault("vision_hidden_act", "gelu_pytorch_tanh") kwargs.setdefault("num_heads", 4) @@ -86,7 +86,7 @@ def __init__(self, parent, **kwargs): "rope_parameters", { "rope_type": "default", - "mrope_section": [16, 8, 8], + "mrope_section": [2, 3, 3], "mrope_interleaved": True, "rope_theta": 10000, }, diff --git a/tests/models/ernie4_5_vl_moe/test_modeling_ernie4_5_vl_moe.py b/tests/models/ernie4_5_vl_moe/test_modeling_ernie4_5_vl_moe.py index 70f757d8a9a9..b9d00c7d8140 100644 --- a/tests/models/ernie4_5_vl_moe/test_modeling_ernie4_5_vl_moe.py +++ b/tests/models/ernie4_5_vl_moe/test_modeling_ernie4_5_vl_moe.py @@ -94,7 +94,7 @@ def __init__( if text_config is None: self.text_config = { "vocab_size": 99, - "hidden_size": 16, + "hidden_size": 32, "intermediate_size": 32, "num_hidden_layers": 2, "num_attention_heads": 2, @@ -102,7 +102,7 @@ def __init__( "hidden_act": "silu", "max_position_embeddings": 512, "tie_word_embeddings": True, - "rope_parameters": {"type": "default", "rope_theta": 500_000.0, "mrope_section": [1, 1, 2]}, + "rope_parameters": {"type": "default", "rope_theta": 500_000.0, "mrope_section": [3, 3, 2]}, "mlp_layer_types": ["dense", "sparse"], "moe_intermediate_size": [32, 32], "moe_k": 2, diff --git a/tests/models/idefics/test_modeling_idefics.py b/tests/models/idefics/test_modeling_idefics.py index c0f185168e99..928055fcc7c7 100644 --- a/tests/models/idefics/test_modeling_idefics.py +++ b/tests/models/idefics/test_modeling_idefics.py @@ -349,6 +349,11 @@ def test_eager_matches_sdpa_inference( ): pass + @parameterized.expand([("linear",), ("dynamic",), ("yarn",)]) + @unittest.skip("Idefics requires both text and image inputs which is currently not done in this test.") + def test_model_rope_scaling_from_config(self, scaling_type): + pass + def test_model_outputs_equivalence(self): try: orig = self.all_model_classes diff --git a/tests/models/minicpmv4_6/test_modeling_minicpmv4_6.py b/tests/models/minicpmv4_6/test_modeling_minicpmv4_6.py index 9f73270c3ce1..84a721a8d681 100644 --- a/tests/models/minicpmv4_6/test_modeling_minicpmv4_6.py +++ b/tests/models/minicpmv4_6/test_modeling_minicpmv4_6.py @@ -64,10 +64,10 @@ def __init__(self, parent, **kwargs): kwargs.setdefault("num_hidden_layers", 2) kwargs.setdefault("num_attention_heads", 4) kwargs.setdefault("num_key_value_heads", 2) - kwargs.setdefault("head_dim", 16) + kwargs.setdefault("head_dim", 32) kwargs.setdefault("hidden_act", "silu") kwargs.setdefault("max_position_embeddings", 512) - kwargs.setdefault("rope_parameters", {"rope_type": "default"}) + kwargs.setdefault("rope_parameters", {"type": "default", "rope_theta": 10_000, "mrope_section": [2, 1, 1]}) kwargs.setdefault("tie_word_embeddings", True) kwargs.setdefault("bos_token_id", 0) kwargs.setdefault("eos_token_id", 1) @@ -118,7 +118,6 @@ def get_config(self): "num_key_value_heads": self.num_key_value_heads, "hidden_act": "silu", "max_position_embeddings": self.max_position_embeddings, - "rope_theta": 10000, "rope_parameters": self.rope_parameters, "tie_word_embeddings": self.tie_word_embeddings, "bos_token_id": self.bos_token_id, diff --git a/tests/models/qwen3_5/test_modeling_qwen3_5.py b/tests/models/qwen3_5/test_modeling_qwen3_5.py index 487451ceae0d..3614c19dac3f 100644 --- a/tests/models/qwen3_5/test_modeling_qwen3_5.py +++ b/tests/models/qwen3_5/test_modeling_qwen3_5.py @@ -69,6 +69,13 @@ def __init__(self, parent): super().__init__(parent=parent) self.hidden_act = "silu" self.layer_types = ["full_attention", "linear_attention"] + self.rope_parameters = { + "rope_type": "default", + "rope_theta": 10_000, + "mrope_section": [2, 1, 1], + "mrope_interleaved": True, + } + self.head_dim = 32 self.linear_conv_kernel_dim = 2 self.linear_key_head_dim = 16 self.linear_value_head_dim = 16 @@ -255,7 +262,7 @@ def __init__( "eos_token_id": 1, "pad_token_id": 2, "hidden_act": "silu", - "head_dim": 8, + "head_dim": 32, "hidden_size": 32, "vocab_size": 99, "intermediate_size": 37, @@ -265,9 +272,13 @@ def __init__( "num_hidden_layers": 2, "layer_types": ["full_attention", "linear_attention"], "num_key_value_heads": 2, - "rope_theta": 10000, "tie_word_embeddings": True, - "rope_parameters": {"rope_type": "default", "mrope_section": [16, 8, 8], "mrope_interleaved": True}, + "rope_parameters": { + "rope_type": "default", + "rope_theta": 10_000, + "mrope_section": [2, 1, 1], + "mrope_interleaved": True, + }, "linear_conv_kernel_dim": 2, "linear_key_head_dim": 16, "linear_value_head_dim": 16, @@ -311,7 +322,6 @@ def __init__( self.num_hidden_layers = text_config["num_hidden_layers"] self.num_attention_heads = text_config["num_attention_heads"] self.num_key_value_heads = text_config["num_key_value_heads"] - self.rope_theta = text_config["rope_theta"] self.rope_parameters = text_config["rope_parameters"] self.hidden_act = text_config["hidden_act"] self.max_position_embeddings = text_config["max_position_embeddings"] diff --git a/tests/models/qwen3_5_moe/test_modeling_qwen3_5_moe.py b/tests/models/qwen3_5_moe/test_modeling_qwen3_5_moe.py index 81ef25d64669..ce342b0a1b57 100644 --- a/tests/models/qwen3_5_moe/test_modeling_qwen3_5_moe.py +++ b/tests/models/qwen3_5_moe/test_modeling_qwen3_5_moe.py @@ -67,6 +67,13 @@ def __init__(self, parent): self.linear_value_head_dim = 16 self.linear_num_key_heads = 4 self.linear_num_value_heads = 8 + self.rope_parameters = { + "rope_type": "default", + "rope_theta": 10_000, + "mrope_section": [2, 1, 1], + "mrope_interleaved": True, + } + self.head_dim = 32 @require_torch @@ -207,7 +214,7 @@ def __init__( "eos_token_id": 1, "pad_token_id": 2, "hidden_act": "silu", - "head_dim": 8, + "head_dim": 32, "hidden_size": 32, "vocab_size": 99, "intermediate_size": 37, @@ -217,9 +224,13 @@ def __init__( "num_hidden_layers": 2, "layer_types": ["full_attention", "linear_attention"], "num_key_value_heads": 2, - "rope_theta": 10000, "tie_word_embeddings": True, - "rope_parameters": {"rope_type": "default", "mrope_section": [16, 8, 8], "mrope_interleaved": True}, + "rope_parameters": { + "rope_type": "default", + "rope_theta": 10_000, + "mrope_section": [2, 1, 1], + "mrope_interleaved": True, + }, "linear_conv_kernel_dim": 2, "linear_key_head_dim": 16, "linear_value_head_dim": 16, @@ -267,7 +278,6 @@ def __init__( self.num_hidden_layers = text_config["num_hidden_layers"] self.num_attention_heads = text_config["num_attention_heads"] self.num_key_value_heads = text_config["num_key_value_heads"] - self.rope_theta = text_config["rope_theta"] self.rope_parameters = text_config["rope_parameters"] self.hidden_act = text_config["hidden_act"] self.max_position_embeddings = text_config["max_position_embeddings"] diff --git a/tests/models/qwen3_vl/test_modeling_qwen3_vl.py b/tests/models/qwen3_vl/test_modeling_qwen3_vl.py index 1b11a224d7f0..be5989c6aa9d 100644 --- a/tests/models/qwen3_vl/test_modeling_qwen3_vl.py +++ b/tests/models/qwen3_vl/test_modeling_qwen3_vl.py @@ -14,11 +14,13 @@ """Testing suite for the PyTorch Qwen3-VL model.""" import copy +import gc import unittest import pytest from transformers import ( + AutoProcessor, Qwen3VLConfig, Qwen3VLForConditionalGeneration, Qwen3VLModel, @@ -26,7 +28,10 @@ ) from transformers.models.qwen3_vl.configuration_qwen3_vl import Qwen3VLTextConfig, Qwen3VLVisionConfig from transformers.testing_utils import ( + Expectations, + backend_empty_cache, require_torch, + slow, torch_device, ) @@ -61,10 +66,10 @@ def __init__(self, parent, **kwargs): kwargs.setdefault("hidden_act", "silu") kwargs.setdefault("num_attention_heads", 4) kwargs.setdefault("num_key_value_heads", 2) - kwargs.setdefault("head_dim", 8) + kwargs.setdefault("head_dim", 16) kwargs.setdefault("depth", 2) kwargs.setdefault("vision_hidden_act", "gelu_pytorch_tanh") - kwargs.setdefault("num_heads", 4) + kwargs.setdefault("num_heads", 2) kwargs.setdefault("spatial_merge_size", 1) kwargs.setdefault("temporal_patch_size", 2) kwargs.setdefault("num_position_embeddings", 16) @@ -73,7 +78,7 @@ def __init__(self, parent, **kwargs): "rope_parameters", { "rope_type": "default", - "mrope_section": [16, 8, 8], + "mrope_section": [2, 3, 3], "mrope_interleaved": True, "rope_theta": 10000, }, @@ -405,10 +410,10 @@ def get_text_config(self): num_hidden_layers=2, num_attention_heads=4, num_key_value_heads=2, - head_dim=8, + head_dim=16, hidden_act="silu", max_position_embeddings=512, - rope_parameters={"rope_type": "default", "mrope_section": [16, 8, 8], "mrope_interleaved": True}, + rope_parameters={"rope_type": "default", "mrope_section": [2, 3, 3], "mrope_interleaved": True}, ) def _make_vision_position_ids(self, batch_size, seq_len): @@ -491,3 +496,50 @@ def test_2d_position_ids_forward(self): output = model(input_ids=input_ids, position_ids=position_ids_2d, use_cache=False) self.assertEqual(output.last_hidden_state.shape, (batch_size, seq_len, config.hidden_size)) self.assertTrue(torch.isfinite(output.last_hidden_state).all()) + + +@slow +@require_torch +class Qwen3VLIntegrationTest(unittest.TestCase): + def setUp(self): + self.processor = AutoProcessor.from_pretrained("Qwen/Qwen3-VL-4B-Instruct") + self.messages = [ + { + "role": "user", + "content": [ + { + "type": "image", + "url": "https://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen2-VL/demo_small.jpg", + }, + {"type": "text", "text": "What kind of dog is this?"}, + ], + } + ] + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + + def test_small_model_integration_test(self): + model = Qwen3VLForConditionalGeneration.from_pretrained("Qwen/Qwen3-VL-4B-Instruct", device_map="auto") + expected_texts = Expectations( + { + ("cuda", None): "user\nWhat kind of dog is this?\nassistant\nBased on the image, this appears to be a **Labrador Retriever**.\n\nHere’s why:\n\n- **Build and Size**: The dog has a large, muscular, and sturdy build, which is characteristic of Labradors.\n- **", + } + ) # fmt: skip + EXPECTED_TEXT = expected_texts.get_expectation() + + inputs = self.processor.apply_chat_template( + self.messages, + tokenize=True, + return_dict=True, + add_generation_prompt=True, + return_tensors="pt", + ).to(torch_device, dtype=model.dtype) + + output = model.generate(**inputs, max_new_tokens=50, do_sample=False) + + self.assertEqual( + self.processor.decode(output[0], skip_special_tokens=True), + EXPECTED_TEXT, + ) diff --git a/tests/models/qwen3_vl_moe/test_modeling_qwen3_vl_moe.py b/tests/models/qwen3_vl_moe/test_modeling_qwen3_vl_moe.py index b77626a5b4c9..f5a705f2cbc4 100644 --- a/tests/models/qwen3_vl_moe/test_modeling_qwen3_vl_moe.py +++ b/tests/models/qwen3_vl_moe/test_modeling_qwen3_vl_moe.py @@ -62,19 +62,19 @@ def __init__(self, parent, **kwargs): kwargs.setdefault("hidden_act", "silu") kwargs.setdefault("num_attention_heads", 4) kwargs.setdefault("num_key_value_heads", 2) - kwargs.setdefault("head_dim", 8) + kwargs.setdefault("head_dim", 16) kwargs.setdefault("moe_intermediate_size", 16) kwargs.setdefault("num_experts_per_tok", 4) kwargs.setdefault("num_experts", 8) kwargs.setdefault("depth", 2) kwargs.setdefault("vision_hidden_act", "gelu_pytorch_tanh") - kwargs.setdefault("num_heads", 4) + kwargs.setdefault("num_heads", 2) kwargs.setdefault("spatial_merge_size", 1) kwargs.setdefault("temporal_patch_size", 2) kwargs.setdefault("num_position_embeddings", 16) kwargs.setdefault("deepstack_visual_indexes", [0, 1]) kwargs.setdefault( - "rope_parameters", {"rope_type": "default", "mrope_section": [16, 8, 8], "mrope_interleaved": True} + "rope_parameters", {"rope_type": "default", "mrope_section": [2, 3, 3], "mrope_interleaved": True} ) kwargs.setdefault("decoder_sparse_step", 1) super().__init__(parent, **kwargs) diff --git a/tests/models/qwen4_exp/test_modeling_qwen4_exp.py b/tests/models/qwen4_exp/test_modeling_qwen4_exp.py index 11144548c8fc..2d14c2c127f9 100644 --- a/tests/models/qwen4_exp/test_modeling_qwen4_exp.py +++ b/tests/models/qwen4_exp/test_modeling_qwen4_exp.py @@ -58,7 +58,7 @@ class Qwen4ExpTextModelTester(CausalLMModelTester): def __init__(self, parent): super().__init__(parent=parent) self.hidden_act = "silu" - self.rope_parameters = {"rope_type": "default", "partial_rotary_factor": 0.25} + self.rope_parameters = {"rope_type": "default", "partial_rotary_factor": 0.25, "mrope_section": [1, 1, 1]} self.layer_types = ["linear_attention", "qwen_sparse_attention"] self.linear_conv_kernel_dim = 2 self.linear_key_head_dim = 16 diff --git a/tests/multimodal_tester.py b/tests/multimodal_tester.py index 7edb74bf293b..524a770b081e 100644 --- a/tests/multimodal_tester.py +++ b/tests/multimodal_tester.py @@ -11,6 +11,7 @@ # 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. +from copy import deepcopy from inspect import signature from transformers.testing_utils import _TEXT_MODEL_TESTER_DEFAULTS @@ -182,10 +183,14 @@ def _collect_kwargs(self, sig_keys, config_class): model_name_to_common_name = {v: k for k, v in attribute_map.items()} kwargs = {} for k in sig_keys: + # Deepcopy each value to prevent common fields in each subconfig + # from pointing to the same object. For ex: both might share the "same" + # `rope_params` and overriding the value for text config causes an override + # for all other subconfig, messing up with test settings if hasattr(self, k) and k != "self": - kwargs[k] = getattr(self, k) + kwargs[k] = deepcopy(getattr(self, k)) elif k in model_name_to_common_name and hasattr(self, model_name_to_common_name[k]): - kwargs[k] = getattr(self, model_name_to_common_name[k]) + kwargs[k] = deepcopy(getattr(self, model_name_to_common_name[k])) return kwargs def get_config(self): diff --git a/tests/test_modeling_common.py b/tests/test_modeling_common.py index b9e52733facc..62b1453d967a 100644 --- a/tests/test_modeling_common.py +++ b/tests/test_modeling_common.py @@ -5893,6 +5893,7 @@ def test_model_rope_scaling_from_config(self, scaling_type): """ Tests that we can initialize a model with RoPE scaling in the config, that it can run a forward pass, and that a few basic model output properties are honored. + Note that we test only text backbone's rope module since multimodal rope can be special. """ config, _ = self.model_tester.prepare_config_and_inputs_for_common() text_config = config.get_text_config(decoder=True) @@ -5978,7 +5979,10 @@ def test_model_rope_scaling_from_config(self, scaling_type): self.assertFalse(torch.allclose(original_long_output, scaled_long_output, atol=1e-5)) def test_model_rope_scaling_frequencies(self): - """Tests the frequency properties of the different RoPE scaling types on the model RoPE layer.""" + """ + Tests the frequency properties of the different RoPE scaling types on the model RoPE layer. + Note that we test only text backbone's rope module since multimodal rope can be special. + """ config, _ = self.model_tester.prepare_config_and_inputs_for_common() text_config = config.get_text_config(decoder=True) base_model_class = None @@ -6273,8 +6277,14 @@ def _config_supports_rope_scaling(config: PreTrainedConfig) -> bool: """Returns whether a certain model config supports RoPE scaling parameterization.""" # Has rope_scaling -> model was designed with rope scaling in mind # Has rope_theta (and no rope_scaling) -> probably an older model, but should support rope scaling as well - main_config_has_rope = hasattr(config, "rope_parameters") - return main_config_has_rope + main_config_scales_rope = hasattr(config, "rope_parameters") + + # Axial rope doesn't scale as images usually have a pre-defined length + # so the config will have no `max_position_embeddings` field defined + # FIXME: add non-scaling rope tests for vision models @raushan + if not hasattr(config, "max_position_embeddings"): + main_config_scales_rope = False + return main_config_scales_rope def _set_config_rope_params(config: PreTrainedConfig, rope_params: dict) -> bool: diff --git a/utils/create_dependency_mapping.py b/utils/create_dependency_mapping.py index cccbaefa4f30..b74e19b07435 100644 --- a/utils/create_dependency_mapping.py +++ b/utils/create_dependency_mapping.py @@ -44,7 +44,6 @@ def topological_sort(dependencies: dict) -> list[list[str]]: sorting_list.append([name_mapping[node] for node in leaf_nodes]) # Remove the leaves from the graph (and from the deps of other nodes) graph = {node: deps - leaf_nodes for node, deps in graph.items() if node not in leaf_nodes} - return sorting_list From 03a4d7b91e06cccdd0b2c68eb5c282a048f5dfb0 Mon Sep 17 00:00:00 2001 From: Tarek Ziade Date: Fri, 4 Sep 2026 10:00:02 +0000 Subject: [PATCH 051/996] QA: Add noisy comment checker (#48484) * noisy comment checker * tweaks * sort by size * ignore top of files * restrict to class/functions * added progress bar, cache and cut off date * tweaks * fix the 7 occurences and added to make style --- .gitignore | 1 + Makefile | 2 +- .../neucodec/feature_extraction_neucodec.py | 11 +- .../models/neucodec/modular_neucodec.py | 11 +- src/transformers/trainer_pt_utils.py | 12 +- tests/models/zamba2/test_modeling_zamba2.py | 11 +- tests/repo_utils/test_check_noisy_comments.py | 786 ++++++++++++++++ utils/check_noisy_comments.py | 866 ++++++++++++++++++ utils/get_previous_daily_ci.py | 17 +- 9 files changed, 1679 insertions(+), 38 deletions(-) create mode 100644 tests/repo_utils/test_check_noisy_comments.py create mode 100644 utils/check_noisy_comments.py diff --git a/.gitignore b/.gitignore index e78abcb9dc5c..fe287f9f71a1 100644 --- a/.gitignore +++ b/.gitignore @@ -173,6 +173,7 @@ tags # checkers cache utils/.checkers_cache.json utils/.checkers_requirements.json +utils/.noisy_comments_cache.json mlinter-findings.json # modular conversion diff --git a/Makefile b/Makefile index 52cece1f36aa..08dbb61cb1eb 100644 --- a/Makefile +++ b/Makefile @@ -10,7 +10,7 @@ export PYTHONPATH = src # so they can never drift out of sync (e.g. silently dropping `auto_mappings` # from CI, as happened in #45018 → fixed in #45774). -STYLE_CHECKERS := ruff_check, ruff_format, init_isort, sort_auto_mappings +STYLE_CHECKERS := ruff_check, ruff_format, init_isort, sort_auto_mappings, noisy_comments TYPING_CHECKERS := types, modeling_structure CODE_QUALITY_CHECKERS := $(TYPING_CHECKERS), $(STYLE_CHECKERS) diff --git a/src/transformers/models/neucodec/feature_extraction_neucodec.py b/src/transformers/models/neucodec/feature_extraction_neucodec.py index c8e21a207f36..78fab005b857 100644 --- a/src/transformers/models/neucodec/feature_extraction_neucodec.py +++ b/src/transformers/models/neucodec/feature_extraction_neucodec.py @@ -167,12 +167,11 @@ def __call__( padding_mask = padded_inputs.pop("attention_mask") padded_audio = padded_inputs["audio"][:, None, :] - # 2) Semantic encoder feature extraction (mel spectrogram). Unlike Xcodec2FeatureExtractor, NeuCodec's - # reference implementation feeds the acoustic-padded waveform directly into the mel computation, with no extra - # "valid_len" trimming or symmetric hop-sized padding: https://github.com/neuphonic/neucodec/blob/ed3e6cd1bdc374ce14a21355e5eee66a777149ce/neucodec/model.py#L128 - # Padded per-sample (not via the batch-collated `padded_audio`): the CMVN normalization below is computed - # over the whole padded signal, so batch-padding a short sample to the batch's longest would skew it. - # TODO (ebezzam): can batch processing be done without regression from expected outputs? + # 2) Semantic encoder features (mel spectrogram). Unlike Xcodec2FeatureExtractor, the NeuCodec + # reference feeds the acoustic-padded waveform straight into the mel computation, with no + # valid_len trimming or hop-sized padding: https://github.com/neuphonic/neucodec/blob/ed3e6cd1bdc374ce14a21355e5eee66a777149ce/neucodec/model.py#L128 + # Padded per-sample, not via the batch-collated `padded_audio`: CMVN below runs over the + # whole padded signal, so padding to the batch's longest would skew a short one. mel_features = [] for i in range(batch_size): single_padded_audio = self.acoustic_encoder_padder.pad( diff --git a/src/transformers/models/neucodec/modular_neucodec.py b/src/transformers/models/neucodec/modular_neucodec.py index 90e07b982e21..79ea3aca1e22 100644 --- a/src/transformers/models/neucodec/modular_neucodec.py +++ b/src/transformers/models/neucodec/modular_neucodec.py @@ -374,12 +374,11 @@ def __call__( padding_mask = padded_inputs.pop("attention_mask") padded_audio = padded_inputs["audio"][:, None, :] - # 2) Semantic encoder feature extraction (mel spectrogram). Unlike Xcodec2FeatureExtractor, NeuCodec's - # reference implementation feeds the acoustic-padded waveform directly into the mel computation, with no extra - # "valid_len" trimming or symmetric hop-sized padding: https://github.com/neuphonic/neucodec/blob/ed3e6cd1bdc374ce14a21355e5eee66a777149ce/neucodec/model.py#L128 - # Padded per-sample (not via the batch-collated `padded_audio`): the CMVN normalization below is computed - # over the whole padded signal, so batch-padding a short sample to the batch's longest would skew it. - # TODO (ebezzam): can batch processing be done without regression from expected outputs? + # 2) Semantic encoder features (mel spectrogram). Unlike Xcodec2FeatureExtractor, the NeuCodec + # reference feeds the acoustic-padded waveform straight into the mel computation, with no + # valid_len trimming or hop-sized padding: https://github.com/neuphonic/neucodec/blob/ed3e6cd1bdc374ce14a21355e5eee66a777149ce/neucodec/model.py#L128 + # Padded per-sample, not via the batch-collated `padded_audio`: CMVN below runs over the + # whole padded signal, so padding to the batch's longest would skew a short one. mel_features = [] for i in range(batch_size): single_padded_audio = self.acoustic_encoder_padder.pad( diff --git a/src/transformers/trainer_pt_utils.py b/src/transformers/trainer_pt_utils.py index 0eb2e789385f..f99ce38a938d 100644 --- a/src/transformers/trainer_pt_utils.py +++ b/src/transformers/trainer_pt_utils.py @@ -858,13 +858,11 @@ def compute_groups_costs(cts): best_spread = float("inf") best_counts = list(counts) - # Each iteration moves exactly one sample between groups, so worst-case - # convergence is O(n). `effective_batch_size` (= n) covers the move-dominated - # regime (large batch, small K) that a fixed `K * 30` cap could cut off - # prematurely; `K * 30` stays as a floor for the detection-dominated regime - # (tiny batch, n ~= K) where convergence is reached via `spread == 0` / `seen` - # rather than the move budget. `best_counts` is tracked below, so hitting the - # cap only degrades the result gracefully (no samples are dropped). + # Each iteration moves one sample between groups, so worst-case convergence is O(n). + # `effective_batch_size` (= n) covers the move-dominated regime (large batch, small K) that a + # fixed `K * 30` cap could cut off; `K * 30` stays a floor for the detection-dominated regime + # (tiny batch, n ~= K), where convergence comes from `spread == 0` / `seen` instead. Hitting + # the cap only degrades the result: `best_counts` is tracked below, so nothing is dropped. for _ in range(max(K * 30, self.effective_batch_size)): key = tuple(counts) if key in seen: diff --git a/tests/models/zamba2/test_modeling_zamba2.py b/tests/models/zamba2/test_modeling_zamba2.py index 4700b9aa2b9f..41b4d449466d 100644 --- a/tests/models/zamba2/test_modeling_zamba2.py +++ b/tests/models/zamba2/test_modeling_zamba2.py @@ -664,12 +664,11 @@ def test_simple_batched_generate_with_padding(self, device): @slow def test_num_mem_blocks_2_official_checkpoint(self): - # Regression test for #47994: every published `num_mem_blocks=2` checkpoint (the Zamba2-2.7B - # and Zamba2-7B families) raised at construction, before any weight was read, because - # `block_id` followed the global layer index while the weight-tie cycle follows hybrid-layer - # order. The layout is what makes this checkpoint the right one to test: its hybrid layers - # `[6, 12, 18, 24, 30, 36, 42, 47, 51]` are not all congruent modulo `num_mem_blocks`, and an - # evenly spaced layout constructs fine even without the fix. + # Regression test for #47994: every published `num_mem_blocks=2` checkpoint (Zamba2-2.7B and + # Zamba2-7B) raised at construction, before any weight was read, because `block_id` followed + # the global layer index while the weight-tie cycle follows hybrid-layer order. This checkpoint + # is the one to test because its hybrid layers `[6, 12, 18, 24, 30, 36, 42, 47, 51]` are not + # all congruent modulo `num_mem_blocks`; an evenly spaced layout constructs fine without the fix. model_id = "Zyphra/Zamba2-2.7B-instruct" model, loading_info = Zamba2ForCausalLM.from_pretrained( model_id, dtype=torch.bfloat16, output_loading_info=True diff --git a/tests/repo_utils/test_check_noisy_comments.py b/tests/repo_utils/test_check_noisy_comments.py new file mode 100644 index 000000000000..9dddc21308a6 --- /dev/null +++ b/tests/repo_utils/test_check_noisy_comments.py @@ -0,0 +1,786 @@ +# Copyright 2026 The HuggingFace 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. + +import io +import os +import sys +import tempfile +import unittest +from contextlib import redirect_stdout +from datetime import date +from pathlib import Path +from unittest.mock import patch + + +git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +utils_path = os.path.join(git_repo_path, "utils") +if utils_path not in sys.path: + sys.path.append(utils_path) + +import check_noisy_comments # noqa: E402 + + +LICENSE_HEADER = """# Copyright 2026 The HuggingFace 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. +""" + + +NOISY_SOURCE = """def foo(): + # This is a long agent-style explanation that goes on and on. + # It restates the code below in prose. + # And keeps going with more detail. + # Still going, adding nothing new. + # One more line for good measure. + # And a sixth line to push it over the limit. + return 1 +""" + + +class _StubOwners: + """Stands in for `FileOwners`, so ownership tests do not need the reviewer resolver installed.""" + + def __init__(self, logins): + self.logins = logins + + def logins_for(self, path): + return self.logins + + +class _StubResolver: + CODEOWNERS_PATH = "codeowners" + + def __init__(self, source, owners): + self.source = source + self.owners = owners + + def resolution_source(self, file_path, codeowners_lines): + return self.source + + def owners_for_file(self, file_path, codeowners_lines): + return self.owners + + +class NoisyCommentsTest(unittest.TestCase): + def _write_file(self, repo_root: Path, content: str) -> Path: + path = repo_root / "sample.py" + path.write_text(content, encoding="utf-8") + return path + + def _blame(self, commit_date: date, author_email: str = "someone@example.com") -> check_noisy_comments.LineBlame: + return check_noisy_comments.LineBlame(commit_date=commit_date, author_email=author_email) + + def _finding(self, path: Path, line: int = 2, end_line: int = 2) -> check_noisy_comments.Finding: + return check_noisy_comments.Finding( + path=path, line=line, end_line=end_line, code="NC001", message="", text="", score=1 + ) + + def test_ignores_standard_license_header(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file(repo_root, LICENSE_HEADER + "\nvalue = 1\n") + + with patch.object(check_noisy_comments, "ROOT", repo_root): + findings = check_noisy_comments.check_file(path, max_block_lines=5, max_block_chars=500) + + self.assertEqual(findings, []) + + def test_ignores_leading_comments_before_first_code(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file( + repo_root, + "\n".join( + [ + "#!/usr/bin/env python3", + "", + "# coding=utf-8", + "# Copyright 2020 The HuggingFace Inc. team.", + "#", + '# 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.", + "", + "# this script dumps information about the environment", + "", + "import sys", + ] + ), + ) + + with patch.object(check_noisy_comments, "ROOT", repo_root): + findings = check_noisy_comments.check_file(path, max_block_lines=5, max_block_chars=500) + + self.assertEqual(findings, []) + + def test_flags_long_comment_block(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file( + repo_root, + "\n".join( + [ + "def foo():", + " value = 1", + " # This is a multi-line note.", + " # It keeps going.", + " # And going.", + " # And going.", + " # And going.", + " # And going.", + " return value", + ] + ), + ) + + with patch.object(check_noisy_comments, "ROOT", repo_root): + findings = check_noisy_comments.check_file(path, max_block_lines=5, max_block_chars=500) + + self.assertEqual([finding.code for finding in findings], ["NC001"]) + + def test_ignores_module_level_comment_blocks(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file( + repo_root, + "\n".join( + [ + "value = 1", + "# This is a module-level note.", + "# It keeps going.", + "# And going.", + "# And going.", + "# And going.", + "# And going.", + ] + ), + ) + + with patch.object(check_noisy_comments, "ROOT", repo_root): + findings = check_noisy_comments.check_file(path, max_block_lines=5, max_block_chars=500) + + self.assertEqual(findings, []) + + def test_ignores_inline_script_metadata_block(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file( + repo_root, + "\n".join( + [ + "# /// script", + "# dependencies = [", + '# "torch",', + '# "torchaudio",', + "# ]", + "# ///", + "value = 1", + ] + ), + ) + + with patch.object(check_noisy_comments, "ROOT", repo_root): + findings = check_noisy_comments.check_file(path, max_block_lines=5, max_block_chars=500) + + self.assertEqual(findings, []) + + def test_skips_autogenerated_modular_outputs(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + model_dir = repo_root / "src" / "transformers" / "models" / "demo" + model_dir.mkdir(parents=True) + generated_file = model_dir / "modeling_demo.py" + generated_file.write_text( + "\n".join( + [ + "# coding=utf-8", + "# This file was automatically generated from src/transformers/models/demo/modular_demo.py.", + "# Do not edit this file manually.", + "def foo():", + " # one", + " # two", + " # three", + " # four", + " # five", + " # six", + ] + ), + encoding="utf-8", + ) + modular_file = model_dir / "modular_demo.py" + modular_file.write_text( + NOISY_SOURCE, + encoding="utf-8", + ) + + with patch.object(check_noisy_comments, "ROOT", repo_root): + findings = check_noisy_comments.check_comments(targets=["src"], max_block_lines=5) + + self.assertEqual([finding.path for finding in findings], [modular_file]) + + def test_thresholds_are_configurable(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file( + repo_root, "def foo():\n # This comment is deliberately not short.\n return 1\n" + ) + + with patch.object(check_noisy_comments, "ROOT", repo_root): + strict = check_noisy_comments.check_file(path, max_block_lines=5, max_block_chars=10) + relaxed = check_noisy_comments.check_file(path, max_block_lines=5, max_block_chars=100) + + self.assertEqual([finding.code for finding in strict], ["NC002"]) + self.assertEqual(relaxed, []) + + def test_cli_reports_without_failing_by_default(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file(repo_root, NOISY_SOURCE) + stdout = io.StringIO() + + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_running_in_pr", return_value=False), + patch.object(sys, "argv", ["check_noisy_comments.py", str(path), "--no-cache", "--progress", "never"]), + redirect_stdout(stdout), + ): + exit_code = check_noisy_comments.main() + + self.assertEqual(exit_code, 0) + self.assertIn("Reporting only; not blocking.", stdout.getvalue()) + + def test_cli_path_option_checks_specific_directory(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + checked_dir = repo_root / "checked" + ignored_dir = repo_root / "ignored" + checked_dir.mkdir() + ignored_dir.mkdir() + checked_file = checked_dir / "sample.py" + checked_file.write_text(NOISY_SOURCE, encoding="utf-8") + ignored_file = ignored_dir / "sample.py" + ignored_file.write_text( + "def foo():\n # This comment is deliberately not short.\n return 1\n", encoding="utf-8" + ) + stdout = io.StringIO() + + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_running_in_pr", return_value=False), + patch.object( + sys, "argv", ["check_noisy_comments.py", "--path", "checked", "--no-cache", "--progress", "never"] + ), + redirect_stdout(stdout), + ): + exit_code = check_noisy_comments.main() + + self.assertEqual(exit_code, 0) + self.assertIn("checked/sample.py", stdout.getvalue()) + self.assertNotIn("ignored/sample.py", stdout.getvalue()) + + def test_collect_findings_uses_persistent_cache(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + cache_path = repo_root / "utils" / ".noisy_comments_cache.json" + cache_path.parent.mkdir() + path = self._write_file(repo_root, NOISY_SOURCE) + + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "CACHE_PATH", cache_path), + patch.object(check_noisy_comments, "_file_line_blames", return_value={}), + ): + first = check_noisy_comments.collect_findings(targets=[str(path)], use_cache=True) + with patch.object(check_noisy_comments, "check_file", side_effect=AssertionError("cache miss")): + second = check_noisy_comments.collect_findings(targets=[str(path)], use_cache=True) + + self.assertEqual([finding.code for finding in first], ["NC001"]) + self.assertEqual([finding.code for finding in second], ["NC001"]) + self.assertTrue(cache_path.exists()) + + def test_collect_findings_shows_progress(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file(repo_root, NOISY_SOURCE) + stdout = io.StringIO() + + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_file_line_blames", return_value={}), + redirect_stdout(stdout), + ): + check_noisy_comments.collect_findings(targets=[str(path)], use_cache=False, progress=True) + + self.assertIn("\rScanning [", stdout.getvalue()) + self.assertIn("Scanned [", stdout.getvalue()) + self.assertIn("] 1/1", stdout.getvalue()) + self.assertEqual(stdout.getvalue().count("\n"), 1) + + def test_pr_scope_filters_to_changed_python_files(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + changed_file = repo_root / "changed.py" + changed_file.write_text(NOISY_SOURCE, encoding="utf-8") + unchanged_file = repo_root / "unchanged.py" + unchanged_file.write_text(NOISY_SOURCE, encoding="utf-8") + + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_patch_added_lines", return_value={changed_file: {2}}), + patch.object(check_noisy_comments, "_file_line_blames", return_value={}), + ): + findings = check_noisy_comments.collect_findings( + targets=[str(repo_root)], use_cache=False, diff_only=True + ) + + self.assertEqual([finding.path for finding in findings], [changed_file]) + + def test_cli_orders_biggest_offenders_first(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + large_file = repo_root / "large.py" + large_file.write_text("def foo():\n # " + "a" * 600 + "\n return 1\n", encoding="utf-8") + small_file = repo_root / "small.py" + small_file.write_text(NOISY_SOURCE, encoding="utf-8") + stdout = io.StringIO() + + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_running_in_pr", return_value=False), + patch.object( + sys, + "argv", + ["check_noisy_comments.py", "--path", str(repo_root), "--no-cache", "--progress", "never"], + ), + redirect_stdout(stdout), + ): + exit_code = check_noisy_comments.main() + + self.assertEqual(exit_code, 0) + self.assertLess(stdout.getvalue().index("large.py"), stdout.getvalue().index("small.py")) + + def test_cli_filters_by_rule(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + # Tall enough for NC001 and long enough for NC002, so `--rule` has something to pick from. + block = "\n".join(f" # {'detail ' * 15}" for _ in range(6)) + path = self._write_file(repo_root, f"def foo():\n{block}\n return 1\n") + stdout = io.StringIO() + + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_running_in_pr", return_value=False), + patch.object( + sys, + "argv", + [ + "check_noisy_comments.py", + "--path", + str(path), + "--rule", + "NC002", + "--no-cache", + "--progress", + "never", + ], + ), + redirect_stdout(stdout), + ): + exit_code = check_noisy_comments.main() + + self.assertEqual(exit_code, 0) + self.assertIn("NC002", stdout.getvalue()) + self.assertNotIn("NC001", stdout.getvalue()) + + def test_cutoff_filter_ignores_old_findings(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file(repo_root, NOISY_SOURCE) + finding = check_noisy_comments.Finding( + path=path, + line=2, + end_line=2, + code="NC001", + message="", + text="", + score=1, + ) + + blames = {2: self._blame(date(2024, 12, 31))} + with patch.object(check_noisy_comments, "_file_line_blames", return_value=blames): + findings = check_noisy_comments._filter_findings_by_cutoff([finding], date(2025, 1, 1)) + + self.assertEqual(findings, []) + + def test_cutoff_filter_keeps_findings_on_cutoff_date(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file(repo_root, NOISY_SOURCE) + finding = check_noisy_comments.Finding( + path=path, + line=2, + end_line=2, + code="NC001", + message="", + text="", + score=1, + ) + + blames = {2: self._blame(date(2025, 1, 1))} + with patch.object(check_noisy_comments, "_file_line_blames", return_value=blames): + findings = check_noisy_comments._filter_findings_by_cutoff([finding], date(2025, 1, 1)) + + self.assertEqual(findings, [finding]) + + def _filter_by_ownership(self, findings, owner_logins, blames): + owners = _StubOwners(owner_logins) + with patch.object(check_noisy_comments, "_file_line_blames", return_value=blames): + return check_noisy_comments._filter_findings_by_ownership(findings, owners) + + def test_ownership_filter_ignores_comments_from_the_files_owner(self): + with tempfile.TemporaryDirectory() as tmpdir: + path = self._write_file(Path(tmpdir), NOISY_SOURCE) + finding = self._finding(path) + + blames = {2: self._blame(date(2026, 6, 1), "cyril.vallez@huggingface.co")} + findings = self._filter_by_ownership([finding], {"cyrilvallez"}, blames) + + self.assertEqual(findings, []) + + def test_ownership_filter_keeps_comments_from_a_non_owner(self): + with tempfile.TemporaryDirectory() as tmpdir: + path = self._write_file(Path(tmpdir), NOISY_SOURCE) + finding = self._finding(path) + + blames = {2: self._blame(date(2026, 6, 1), "someone@example.com")} + findings = self._filter_by_ownership([finding], {"cyrilvallez"}, blames) + + self.assertEqual(findings, [finding]) + + def test_ownership_filter_keeps_comments_from_an_owner_of_another_area(self): + with tempfile.TemporaryDirectory() as tmpdir: + path = self._write_file(Path(tmpdir), NOISY_SOURCE) + finding = self._finding(path) + + # Owning `generation/` does not make a comment in someone else's file deliberate. + blames = {2: self._blame(date(2026, 6, 1), "cyril.vallez@huggingface.co")} + findings = self._filter_by_ownership([finding], {"sunmarc"}, blames) + + self.assertEqual(findings, [finding]) + + def test_ownership_filter_keeps_blocks_with_a_non_owner_line(self): + with tempfile.TemporaryDirectory() as tmpdir: + path = self._write_file(Path(tmpdir), "def foo():\n # one\n # two\n return 1\n") + finding = self._finding(path, line=2, end_line=3) + + blames = { + 2: self._blame(date(2026, 6, 1), "cyril.vallez@huggingface.co"), + 3: self._blame(date(2026, 6, 2), "someone@example.com"), + } + findings = self._filter_by_ownership([finding], {"cyrilvallez"}, blames) + + self.assertEqual(findings, [finding]) + + def test_ownership_filter_keeps_findings_in_unowned_files(self): + with tempfile.TemporaryDirectory() as tmpdir: + path = self._write_file(Path(tmpdir), NOISY_SOURCE) + finding = self._finding(path) + + blames = {2: self._blame(date(2026, 6, 1), "cyril.vallez@huggingface.co")} + findings = self._filter_by_ownership([finding], set(), blames) + + self.assertEqual(findings, [finding]) + + def test_ownership_filter_keeps_findings_without_blame(self): + with tempfile.TemporaryDirectory() as tmpdir: + path = self._write_file(Path(tmpdir), NOISY_SOURCE) + finding = self._finding(path) + + findings = self._filter_by_ownership([finding], {"cyrilvallez"}, {}) + + self.assertEqual(findings, [finding]) + + def test_author_logins_derives_logins_from_commit_email(self): + self.assertIn( + "arthurzucker", check_noisy_comments._author_logins("48595927+ArthurZucker@users.noreply.github.com") + ) + self.assertIn("cyrilvallez", check_noisy_comments._author_logins("cyril.vallez@huggingface.co")) + self.assertIn("rocketknight1", check_noisy_comments._author_logins("rocketknight1@gmail.com")) + # An owner whose commit address resembles neither their login nor their name needs an alias. + self.assertIn("zucchininlp", check_noisy_comments._author_logins("raushan@huggingface.co")) + self.assertEqual(check_noisy_comments._author_logins(""), set()) + + def test_author_logins_does_not_match_lookalike_contributors(self): + # Both of these are real contributors in this history; neither is the owner they resemble. + self.assertNotIn("cyrilvallez", check_noisy_comments._author_logins("cyrile.ufr.orsay@gmail.com")) + self.assertNotIn("vasqu", check_noisy_comments._author_logins("lmvasque@users.noreply.github.com")) + + def test_file_owners_reads_the_resolver_and_ignores_the_catch_all(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + codeowners = repo_root / "codeowners" + codeowners.write_text("/src/ @Someone\n", encoding="utf-8") + owned = self._write_file(repo_root, "value = 1\n") + + resolver = _StubResolver(source="rule", owners=["@SomeOne", "@other"]) + lines = codeowners.read_text(encoding="utf-8").splitlines(keepends=True) + with patch.object(check_noisy_comments, "ROOT", repo_root): + owners = check_noisy_comments.FileOwners(resolver, lines) + self.assertEqual(owners.logins_for(owned), {"someone", "other"}) + + resolver.source = "catch-all" + self.assertEqual(check_noisy_comments.FileOwners(resolver, lines).logins_for(owned), set()) + + def test_blame_parsing_reads_author_email_and_date(self): + porcelain = ( + "abc123 1 1 1\n" + "author Cyril Vallez\n" + "author-mail \n" + "author-time 1767225600\n" + "\tdef foo():\n" + "def456 2 2 1\n" + "author Someone Else\n" + "author-mail \n" + "author-time 1767312000\n" + "\t return 1\n" + ) + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file(repo_root, "def foo():\n return 1\n") + + completed = type("Completed", (), {"returncode": 0, "stdout": porcelain})() + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_FILE_LINE_BLAME_CACHE", {}), + patch.object(check_noisy_comments.subprocess, "run", return_value=completed), + ): + blames = check_noisy_comments._file_line_blames(path) + + self.assertEqual(blames[1].author_email, "cyril.vallez@huggingface.co") + self.assertEqual(blames[2].author_email, "someone@example.com") + self.assertEqual(blames[1].commit_date, date(2026, 1, 1)) + + def test_noqa_marker_suppresses_only_the_named_rule(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + block = "\n".join(f" # line {index}" for index in range(6)) + path = self._write_file(repo_root, f"def foo():\n{block}\n # noqa: NC001\n return 1\n") + + with patch.object(check_noisy_comments, "ROOT", repo_root): + findings = check_noisy_comments.check_file(path, max_block_lines=5, max_block_chars=500) + + self.assertEqual([finding.code for finding in findings], []) + + # The same block trips NC001 and NC002; the marker names one code, not all of them. + block = "\n".join(f" # {'detail ' * 15}" for _ in range(6)) + path = self._write_file(repo_root, f"def foo():\n{block}\n # noqa: NC001\n return 1\n") + with patch.object(check_noisy_comments, "ROOT", repo_root): + findings = check_noisy_comments.check_file(path, max_block_lines=5, max_block_chars=500) + + self.assertEqual([finding.code for finding in findings], ["NC002"]) + + def test_patch_added_lines_parses_diff_hunks(self): + diff = "\n".join( + [ + "diff --git a/kept.py b/kept.py", + "--- a/kept.py", + "+++ b/kept.py", + "@@ -10,0 +11,3 @@ def foo():", + "+ # one", + "+ # two", + "+ # three", + "@@ -40 +43 @@ def bar():", + "+ # single", + "diff --git a/notes.md b/notes.md", + "--- a/notes.md", + "+++ b/notes.md", + "@@ -1,0 +2,1 @@", + "+text", + ] + ) + with ( + patch.object(check_noisy_comments, "_PATCH_ADDED_LINES_CACHE", {}), + patch.object(check_noisy_comments, "_git_output", side_effect=["abc123", diff]), + ): + added = check_noisy_comments._patch_added_lines() + + self.assertEqual(added, {check_noisy_comments.ROOT / "kept.py": {11, 12, 13, 43}}) + + def test_patch_scope_keeps_only_findings_overlapping_added_lines(self): + with tempfile.TemporaryDirectory() as tmpdir: + path = self._write_file(Path(tmpdir), "def foo():\n # one\n # two\n return 1\n") + touched = self._finding(path, line=2, end_line=3) + untouched = self._finding(path, line=20, end_line=20) + + # A block the patch only extends still counts: the patch is what pushed it over the limit. + with patch.object(check_noisy_comments, "_patch_added_lines", return_value={path: {3}}): + findings = check_noisy_comments._filter_findings_to_patch([touched, untouched]) + + self.assertEqual(findings, [touched]) + + def test_patch_scope_keeps_everything_when_the_diff_is_unavailable(self): + with tempfile.TemporaryDirectory() as tmpdir: + path = self._write_file(Path(tmpdir), "def foo():\n # one\n return 1\n") + finding = self._finding(path) + + with patch.object(check_noisy_comments, "_patch_added_lines", return_value=None): + self.assertEqual(check_noisy_comments._filter_findings_to_patch([finding]), [finding]) + + def test_cli_blocks_on_findings_a_patch_adds(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file(repo_root, NOISY_SOURCE) + argv = [ + "check_noisy_comments.py", + str(path), + "--no-cache", + "--no-owner-filter", + "--no-date-filter", + "--progress", + "never", + ] + + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_running_in_pr", return_value=True), + patch.object(check_noisy_comments, "_patch_added_lines", return_value={path: {2}}), + patch.object(sys, "argv", argv), + redirect_stdout(io.StringIO()) as stdout, + ): + exit_code = check_noisy_comments.main() + + self.assertEqual(exit_code, 1) + self.assertIn("on lines this patch adds. Blocking.", stdout.getvalue()) + self.assertIn("# noqa:", stdout.getvalue()) + + def test_cli_ignores_findings_a_patch_did_not_add(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file(repo_root, NOISY_SOURCE) + argv = [ + "check_noisy_comments.py", + str(path), + "--no-cache", + "--no-owner-filter", + "--no-date-filter", + "--progress", + "never", + ] + + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_running_in_pr", return_value=True), + patch.object(check_noisy_comments, "_patch_added_lines", return_value={path: {8}}), + patch.object(sys, "argv", argv), + redirect_stdout(io.StringIO()), + ): + exit_code = check_noisy_comments.main() + + self.assertEqual(exit_code, 0) + + def test_cli_can_be_told_not_to_fail_in_pr_ci(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file(repo_root, NOISY_SOURCE) + argv = [ + "check_noisy_comments.py", + str(path), + "--no-cache", + "--no-owner-filter", + "--no-date-filter", + "--no-fail-on-findings", + "--progress", + "never", + ] + + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_running_in_pr", return_value=True), + patch.object(check_noisy_comments, "_patch_added_lines", return_value={path: {2}}), + patch.object(sys, "argv", argv), + redirect_stdout(io.StringIO()) as stdout, + ): + exit_code = check_noisy_comments.main() + + self.assertEqual(exit_code, 0) + self.assertIn("Reporting only; not blocking.", stdout.getvalue()) + + def test_cli_does_not_block_when_the_diff_cannot_be_resolved(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file(repo_root, NOISY_SOURCE) + argv = [ + "check_noisy_comments.py", + str(path), + "--no-cache", + "--no-owner-filter", + "--no-date-filter", + "--progress", + "never", + ] + + # No merge base (a CI checkout without `origin/main`): the scan covers the whole tree, so + # blocking would fail PRs for comments they never touched. + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_running_in_pr", return_value=True), + patch.object(check_noisy_comments, "_patch_added_lines", return_value=None), + patch.object(sys, "argv", argv), + redirect_stdout(io.StringIO()) as stdout, + ): + exit_code = check_noisy_comments.main() + + self.assertEqual(exit_code, 0) + self.assertIn("Reporting only; not blocking.", stdout.getvalue()) + + def test_cli_can_fail_on_findings(self): + with tempfile.TemporaryDirectory() as tmpdir: + repo_root = Path(tmpdir) + path = self._write_file(repo_root, NOISY_SOURCE) + + with ( + patch.object(check_noisy_comments, "ROOT", repo_root), + patch.object(check_noisy_comments, "_running_in_pr", return_value=False), + patch.object( + sys, + "argv", + ["check_noisy_comments.py", str(path), "--fail-on-findings", "--no-cache", "--progress", "never"], + ), + redirect_stdout(io.StringIO()), + ): + exit_code = check_noisy_comments.main() + + self.assertEqual(exit_code, 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/check_noisy_comments.py b/utils/check_noisy_comments.py new file mode 100644 index 000000000000..aa6751398734 --- /dev/null +++ b/utils/check_noisy_comments.py @@ -0,0 +1,866 @@ +# Copyright 2026 The HuggingFace 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. +"""Flag comment blocks that are long enough to read as verbose, low-signal AI output. + +Blocking on what a patch adds in PR CI; reporting only on a full scan. +""" + +import argparse +import ast +import datetime +import hashlib +import io +import json +import os +import re +import subprocess +import sys +import tokenize +from dataclasses import dataclass +from pathlib import Path + + +CHECKER_CONFIG = { + "name": "noisy_comments", + "label": "Noisy comments", + # Matches the library/code-quality surface instead of only model implementation files. + # Approximate: excludes are applied by the checker at runtime. + "cache_globs": [ + "tests/**/*.py", + "src/**/*.py", + "utils/**/*.py", + "scripts/**/*.py", + ".circleci/create_circleci_config.py", + "benchmark/**/*.py", + "benchmark_v2/**/*.py", + "setup.py", + "conftest.py", + ".github/scripts/codeowners_for_review_action", + ], + "check_args": [], + # Nothing here is auto-fixable, but `make style` should still surface findings while you are + # writing the comment, so this runs in --fix mode instead of being skipped as check-only. + "fix_args": [], + # For the reviewer resolver, which supplies the file ownership used to skip owners' own comments. + "needs_requirements": True, +} + +ROOT = Path(__file__).resolve().parent.parent +CACHE_PATH = ROOT / "utils" / ".noisy_comments_cache.json" +CACHE_VERSION = 4 +DEFAULT_TARGETS = [ + "tests", + "src", + "utils", + "scripts", + ".circleci/create_circleci_config.py", + "benchmark", + "benchmark_v2", + "setup.py", + "conftest.py", +] +DEFAULT_EXCLUDES = { + ".git", + ".mypy_cache", + ".pytest_cache", + ".ruff_cache", + "__pycache__", + "build", + "dist", + "node_modules", +} +DIRECTIVE_PREFIXES = ( + "#!", + "# -*-", + "# coding", + "# fmt:", + "# isort:", + "# noqa", + "# pyright:", + "# ruff:", + "# type:", +) +NOQA_RE = re.compile(r"noqa:\s*(NC[0-9]{3}(?:\s*,\s*NC[0-9]{3})*)", re.IGNORECASE) +AUTOGENERATED_MODULAR_HEADER = "This file was automatically generated from" +# A comment left by the owner of the file it sits in is deliberate, so it is not reported. Ownership comes +# from `.github/scripts/codeowners_for_review_action` -- the same data the `Assign PR Reviewers` workflow uses +# -- so this follows the reviewer map instead of duplicating a list of names that would go stale. +# +# Bridging the two takes one step: `git blame` reports commit emails, the codeowners file names GitHub logins. +# `_author_logins` derives the login from the email, which works for every owner in that file except one whose +# commit address resembles neither their login nor their name. +LOGIN_EMAIL_ALIASES = { + "zucchininlp": {"raushan@huggingface.co", "raushan.turganbay@alumni.nu.edu.kz"}, +} +GITHUB_NOREPLY_RE = re.compile(r"(?:\d+\+)?(?P[A-Za-z0-9-]+)@users\.noreply\.github\.com") +DIFF_HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(?P\d+)(?:,(?P\d+))? @@") +INSTALL_RESOLVER = "pip install -r utils/checkers-requirements.txt" +_FILE_LINE_BLAME_CACHE = {} +_PATCH_ADDED_LINES_CACHE = {} + + +@dataclass(frozen=True) +class Comment: + line: int + column: int + text: str + physical_line: str + + +@dataclass(frozen=True) +class LineBlame: + commit_date: datetime.date + author_email: str + + +@dataclass(frozen=True) +class Finding: + path: Path + line: int + end_line: int + code: str + message: str + text: str + score: int + + +class CommentCache: + def __init__(self, path: Path | None = None): + self.path = CACHE_PATH if path is None else path + self.data = self._load() + + def _load(self) -> dict: + try: + data = json.loads(self.path.read_text(encoding="utf-8")) + except (FileNotFoundError, json.JSONDecodeError, OSError): + return {"version": CACHE_VERSION, "files": {}} + if data.get("version") != CACHE_VERSION: + return {"version": CACHE_VERSION, "files": {}} + data.setdefault("files", {}) + return data + + def save(self) -> None: + try: + self.path.write_text(json.dumps(self.data, sort_keys=True, indent=2) + "\n", encoding="utf-8") + except OSError: + pass + + def get(self, path: Path, key: str) -> tuple[list[Finding], dict[int, LineBlame]] | None: + entry = self.data["files"].get(_display_path(path)) + if entry is None or entry.get("key") != key: + return None + findings = [Finding(path=path, **finding) for finding in entry.get("findings", [])] + line_blames = { + int(line): LineBlame( + commit_date=datetime.date.fromisoformat(blame["commit_date"]), + author_email=blame.get("author_email", ""), + ) + for line, blame in entry.get("line_blames", {}).items() + } + return findings, line_blames + + def set(self, path: Path, key: str, findings: list[Finding], line_blames: dict[int, LineBlame]) -> None: + self.data["files"][_display_path(path)] = { + "key": key, + "findings": [ + { + "line": finding.line, + "end_line": finding.end_line, + "code": finding.code, + "message": finding.message, + "text": finding.text, + "score": finding.score, + } + for finding in findings + ], + "line_blames": { + str(line): {"commit_date": blame.commit_date.isoformat(), "author_email": blame.author_email} + for line, blame in line_blames.items() + }, + } + + def prune_missing_files(self) -> None: + self.data["files"] = {path: entry for path, entry in self.data["files"].items() if (ROOT / path).exists()} + + +def _display_path(path: Path) -> str: + try: + return str(path.relative_to(ROOT)) + except ValueError: + return str(path) + + +def _comment_body(text: str) -> str: + return text[1:].strip() + + +def _is_full_line_comment(comment: Comment) -> bool: + return comment.physical_line[: comment.column].strip() == "" + + +def _is_directive(comment: Comment) -> bool: + text = comment.text.strip() + lower_text = text.lower() + return lower_text.startswith(DIRECTIVE_PREFIXES) + + +def _is_structured_metadata_block(block: list[Comment]) -> bool: + bodies = [_comment_body(comment.text) for comment in block] + return any(body == "/// script" for body in bodies) and any(body == "///" for body in bodies) + + +def _is_autogenerated_modular_file(path: Path) -> bool: + try: + with path.open(encoding="utf-8") as f: + header = "".join(next(f, "") for _ in range(5)) + except UnicodeDecodeError: + with path.open(encoding="latin-1") as f: + header = "".join(next(f, "") for _ in range(5)) + except OSError: + # A path named by the diff that is not in the working tree. Nothing to scan either way. + return False + + return AUTOGENERATED_MODULAR_HEADER in header and "/modular_" in header.replace("\\", "/") + + +def _parse_cutoff_date(value: str) -> datetime.date: + try: + return datetime.date.fromisoformat(value) + except ValueError as error: + raise argparse.ArgumentTypeError("Expected date in YYYY-MM-DD format.") from error + + +def _read_source(path: Path) -> str: + try: + return path.read_text(encoding="utf-8") + except UnicodeDecodeError: + return path.read_text(encoding="latin-1") + + +def _source_cache_key(source: str, max_block_lines: int, max_block_chars: int) -> str: + payload = "\0".join([source, str(max_block_lines), str(max_block_chars)]) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +def _lines_inside_class_or_function(source: str, path: Path) -> set[int]: + try: + tree = ast.parse(source, filename=str(path)) + except SyntaxError as error: + raise ValueError(f"Could not parse {_display_path(path)}: {error}") from error + + lines = set() + for node in ast.walk(tree): + if isinstance(node, ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef): + end_lineno = getattr(node, "end_lineno", node.lineno) + lines.update(range(node.lineno, end_lineno + 1)) + return lines + + +def _iter_python_files(targets: list[str], excludes: set[str]) -> list[Path]: + files = set() + for target in targets: + path = ROOT / target + if path.is_file() and path.suffix == ".py": + if not _is_autogenerated_modular_file(path): + files.add(path) + continue + if not path.is_dir(): + continue + for candidate in path.rglob("*.py"): + if excludes.intersection(candidate.relative_to(ROOT).parts): + continue + if _is_autogenerated_modular_file(candidate): + continue + files.add(candidate) + return sorted(files) + + +def _git_output(args: list[str]) -> str | None: + result = subprocess.run(["git", "-C", str(ROOT), *args], capture_output=True, text=True) + if result.returncode != 0: + return None + return result.stdout.strip() + + +def _running_in_pr() -> bool: + return ( + os.environ.get("GITHUB_EVENT_NAME") in {"pull_request", "pull_request_target", "issue_comment"} + or bool(os.environ.get("CIRCLE_PULL_REQUEST")) + or bool(os.environ.get("CI_PULL_REQUEST")) + ) + + +def _diff_base_ref() -> str: + base_ref = os.environ.get("GITHUB_BASE_REF") + if base_ref: + return f"origin/{base_ref}" + return "origin/main" + + +def _patch_added_lines() -> dict[Path, set[int]] | None: + """Line numbers this patch adds, per Python file, or None when the diff cannot be resolved. + + The unit a blocking check has to work in. Scoping to changed *files* would fail a PR for comments + it never touched -- every pre-existing finding in a file it happens to edit. Scoping to added + *lines* fails it only for what it wrote. + """ + if _PATCH_ADDED_LINES_CACHE: + return _PATCH_ADDED_LINES_CACHE["value"] + + added = _resolve_patch_added_lines() + _PATCH_ADDED_LINES_CACHE["value"] = added + return added + + +def _resolve_patch_added_lines() -> dict[Path, set[int]] | None: + merge_base = _git_output(["merge-base", "HEAD", _diff_base_ref()]) + if not merge_base: + merge_base = _git_output(["merge-base", "HEAD", "main"]) + if not merge_base: + return None + + output = _git_output(["diff", "--unified=0", "--diff-filter=ACMR", f"{merge_base}...HEAD"]) + if output is None: + return None + + added = {} + path = None + for line in output.splitlines(): + if line.startswith("+++ "): + target = line[4:].strip() + path = None + if target.startswith("b/") and target.endswith(".py"): + candidate = ROOT / target[2:] + if not _is_autogenerated_modular_file(candidate): + path = candidate + added.setdefault(path, set()) + continue + if path is None: + continue + hunk = DIFF_HUNK_RE.match(line) + if hunk is not None: + start = int(hunk.group("start")) + count = 1 if hunk.group("count") is None else int(hunk.group("count")) + added[path].update(range(start, start + count)) + return added + + +def _filter_files_to_patch(files: list[Path]) -> list[Path]: + added = _patch_added_lines() + if added is None: + print("Could not determine PR changed files; scanning selected targets.") + return files + return [path for path in files if path in added] + + +def _filter_findings_to_patch(findings: list[Finding]) -> list[Finding]: + """Findings that overlap a line this patch adds.""" + added = _patch_added_lines() + if added is None: + return findings + return [ + finding + for finding in findings + if added.get(finding.path, set()).intersection(range(finding.line, finding.end_line + 1)) + ] + + +def _should_show_progress(progress: str) -> bool: + if progress == "always": + return True + if progress == "never": + return False + return sys.stdout.isatty() or os.environ.get("GITHUB_ACTIONS") == "true" or os.environ.get("CIRCLECI") == "true" + + +def _show_progress(done: int, total: int, path: Path | None = None) -> None: + width = 24 + filled = width if total == 0 else int(width * done / total) + bar = "#" * filled + "-" * (width - filled) + status = "Scanning" if done < total else "Scanned" + suffix = "" if path is None else f" {_display_path(path)}" + line = f"\r{status} [{bar}] {done}/{total}{suffix}\033[K" + sys.stdout.write(line[:160]) + sys.stdout.flush() + + +def _finish_progress() -> None: + sys.stdout.write("\n") + sys.stdout.flush() + + +def _should_update_progress(done: int, total: int) -> bool: + return done == total or done % 100 == 0 + + +def _tokenize_comments(source: str, path: Path) -> list[Comment]: + comments = [] + try: + tokens = tokenize.generate_tokens(io.StringIO(source).readline) + for token in tokens: + if token.type == tokenize.COMMENT: + line, column = token.start + comment = Comment(line=line, column=column, text=token.string, physical_line=token.line) + comments.append(comment) + except tokenize.TokenError as error: + raise ValueError(f"Could not tokenize {_display_path(path)}: {error}") from error + return comments + + +def _file_line_blames(path: Path) -> dict[int, LineBlame]: + if path in _FILE_LINE_BLAME_CACHE: + return _FILE_LINE_BLAME_CACHE[path] + + try: + relative_path = path.relative_to(ROOT) + except ValueError: + return {} + + result = subprocess.run( + [ + "git", + "-C", + str(ROOT), + "blame", + "--line-porcelain", + "--", + str(relative_path), + ], + capture_output=True, + text=True, + ) + if result.returncode != 0: + return {} + + blames = {} + current_line = 1 + commit_date = None + author_email = "" + for line in result.stdout.splitlines(): + if line.startswith("author-time "): + timestamp = int(line.split()[1]) + commit_date = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc).date() + elif line.startswith("author-mail "): + author_email = _normalize_email(line.split(" ", 1)[1]) + elif line.startswith("\t"): + if commit_date is not None: + blames[current_line] = LineBlame(commit_date=commit_date, author_email=author_email) + current_line += 1 + commit_date = None + author_email = "" + _FILE_LINE_BLAME_CACHE[path] = blames + return blames + + +def _normalize_email(value: str) -> str: + return value.strip().strip("<>").strip().lower() + + +def _github_noreply_login(email: str) -> str | None: + match = GITHUB_NOREPLY_RE.fullmatch(email) + return None if match is None else match.group("login").lower() + + +def _author_logins(email: str) -> set[str]: + """The GitHub logins a commit email could belong to. + + `git blame` reports an email, `codeowners_for_review_action` names GitHub logins, and nothing in a + clone maps one to the other. Three derivations cover every owner in that file but one: the login + inside a `users.noreply.github.com` address, the email's local part, and `LOGIN_EMAIL_ALIASES` for + an owner whose commit address resembles neither. + """ + if not email: + return set() + + logins = {alias for alias, emails in LOGIN_EMAIL_ALIASES.items() if email in emails} + noreply_login = _github_noreply_login(email) + if noreply_login is not None: + logins.add(noreply_login) + else: + logins.add(_normalize_login(email.split("@")[0])) + return {login for login in logins if login} + + +def _normalize_login(value: str) -> str: + return re.sub(r"[^a-z0-9]", "", value.lower()) + + +def _load_file_owners() -> tuple["FileOwners | None", str]: + """File ownership, or None and the reason it is unavailable. + + The resolver is the same optional dependency as in `utils/check_reviewers.py`: pinned in + `utils/checkers-requirements.txt`, not in `setup.py`. When either it or the codeowners file is + missing, ownership is unknown and every finding is reported -- a checker should not hide findings + based on data it could not read. + """ + try: + from transformersci.reviewers import resolver + except ImportError: + return None, f"the reviewer resolver is not installed ({INSTALL_RESOLVER})" + + try: + codeowners_lines = (ROOT / resolver.CODEOWNERS_PATH).read_text(encoding="utf-8").splitlines(keepends=True) + except OSError: + return None, f"{resolver.CODEOWNERS_PATH} could not be read" + + return FileOwners(resolver, codeowners_lines), "" + + +class FileOwners: + """Owner logins per file, read from `codeowners_for_review_action` through the shared resolver.""" + + def __init__(self, resolver, codeowners_lines: list[str]): + self.resolver = resolver + self.codeowners_lines = codeowners_lines + self._cache = {} + + def logins_for(self, path: Path) -> set[str]: + display_path = _display_path(path) + if display_path not in self._cache: + self._cache[display_path] = self._resolve(display_path) + return self._cache[display_path] + + def _resolve(self, display_path: str) -> set[str]: + # The catch-all exists so that every PR reaches *somebody*; it is dispatch, not ownership, and + # treating it as ownership would make its owners the owners of the whole repository. + if self.resolver.resolution_source(display_path, self.codeowners_lines) == "catch-all": + return set() + owners = self.resolver.owners_for_file(display_path, self.codeowners_lines) + return {_normalize_login(owner.lstrip("@")) for owner in owners} + + +def _blames_for_finding(finding: Finding) -> dict[int, LineBlame] | None: + """Blame entries covering every line of `finding`, or None when blame is incomplete.""" + line_blames = _file_line_blames(finding.path) + if not line_blames: + return None + + expected_lines = set(range(finding.line, finding.end_line + 1)) + if not expected_lines.issubset(line_blames): + return None + + return {line: line_blames[line] for line in expected_lines} + + +def _finding_is_before_cutoff(finding: Finding, cutoff_date: datetime.date) -> bool: + blames = _blames_for_finding(finding) + if blames is None: + return False + + return all(blame.commit_date < cutoff_date for blame in blames.values()) + + +def _finding_is_owned(finding: Finding, owners: FileOwners) -> bool: + """Whether every line of `finding` was last touched by an owner of the file it sits in.""" + owner_logins = owners.logins_for(finding.path) + if not owner_logins: + return False + + blames = _blames_for_finding(finding) + if blames is None: + return False + + return all(_author_logins(blame.author_email) & owner_logins for blame in blames.values()) + + +def _filter_findings_by_cutoff(findings: list[Finding], cutoff_date: datetime.date | None) -> list[Finding]: + if cutoff_date is None: + return findings + return [finding for finding in findings if not _finding_is_before_cutoff(finding, cutoff_date)] + + +def _filter_findings_by_ownership(findings: list[Finding], owners: FileOwners | None) -> list[Finding]: + if owners is None: + return findings + return [finding for finding in findings if not _finding_is_owned(finding, owners)] + + +def _comment_blocks(comments: list[Comment]) -> list[list[Comment]]: + blocks = [] + current = [] + previous_line = None + for comment in comments: + if not _is_full_line_comment(comment): + continue + if previous_line is None or comment.line == previous_line + 1: + current.append(comment) + else: + if current: + blocks.append(current) + current = [comment] + previous_line = comment.line + if current: + blocks.append(current) + return blocks + + +def _suppressed_codes(comments: list[Comment]) -> set[str]: + """Rule codes silenced by a `# noqa: NC00x` marker on any of `comments`. + + The escape hatch for a comment that is long on purpose. The code is required: a bare `# noqa` + belongs to ruff, and should not silence this checker by accident. + """ + codes = set() + for comment in comments: + for match in NOQA_RE.finditer(comment.text): + codes.update(code.strip().upper() for code in match.group(1).split(",")) + return codes + + +def check_file(path: Path, max_block_lines: int, max_block_chars: int) -> list[Finding]: + findings = [] + source = _read_source(path) + scope_lines = _lines_inside_class_or_function(source, path) + comments = _tokenize_comments(source, path) + + for block in _comment_blocks(comments): + if ( + not all(comment.line in scope_lines for comment in block) + or _is_structured_metadata_block(block) + or all(_is_directive(comment) for comment in block) + ): + continue + + suppressed = _suppressed_codes(block) + body_chars = sum(len(_comment_body(comment.text)) for comment in block) + if len(block) > max_block_lines and "NC001" not in suppressed: + findings.append( + Finding( + path=path, + line=block[0].line, + end_line=block[-1].line, + code="NC001", + message=f"comment block has {len(block)} lines (limit: {max_block_lines})", + text=block[0].text.strip(), + score=len(block), + ) + ) + if body_chars > max_block_chars and "NC002" not in suppressed: + findings.append( + Finding( + path=path, + line=block[0].line, + end_line=block[-1].line, + code="NC002", + message=f"comment block has {body_chars} characters (limit: {max_block_chars})", + text=block[0].text.strip(), + score=body_chars, + ) + ) + + return findings + + +def check_comments( + targets: list[str] | None = None, + excludes: set[str] | None = None, + max_block_lines: int = 5, + max_block_chars: int = 500, +) -> list[Finding]: + return collect_findings( + targets=targets, + excludes=excludes, + max_block_lines=max_block_lines, + max_block_chars=max_block_chars, + use_cache=False, + diff_only=False, + progress=False, + ) + + +def collect_findings( + targets: list[str] | None = None, + excludes: set[str] | None = None, + max_block_lines: int = 5, + max_block_chars: int = 500, + use_cache: bool = True, + diff_only: bool = False, + progress: bool = False, +) -> list[Finding]: + targets = DEFAULT_TARGETS if targets is None else targets + excludes = DEFAULT_EXCLUDES if excludes is None else excludes + + files = _iter_python_files(targets, excludes) + if diff_only: + files = _filter_files_to_patch(files) + print(f"Restricting noisy comment scan to {len(files)} Python file(s) changed in this patch.", flush=True) + + if progress: + _show_progress(0, len(files)) + + cache = CommentCache() if use_cache else None + if cache is not None: + cache.prune_missing_files() + + findings = [] + for index, path in enumerate(files, start=1): + source = _read_source(path) + key = _source_cache_key(source, max_block_lines, max_block_chars) + cached = cache.get(path, key) if cache is not None else None + if cached is None: + _FILE_LINE_BLAME_CACHE.pop(path, None) + file_findings = check_file(path, max_block_lines, max_block_chars) + line_blames = _file_line_blames(path) if file_findings else {} + if cache is not None: + cache.set(path, key, file_findings, line_blames) + else: + file_findings, line_blames = cached + _FILE_LINE_BLAME_CACHE[path] = line_blames + findings.extend(file_findings) + if progress and _should_update_progress(index, len(files)): + _show_progress(index, len(files), path) + + if progress: + _finish_progress() + + if cache is not None: + cache.save() + return findings + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "targets", + nargs="*", + help="Files or directories to check. Defaults to the library-wide checker surface.", + ) + parser.add_argument( + "--path", + action="append", + default=[], + help="File or directory to check; can be repeated. Overrides the default checker surface.", + ) + parser.add_argument("--max-block-lines", type=int, default=5, help="Maximum contiguous full-line comment lines.") + parser.add_argument("--max-block-chars", type=int, default=500, help="Maximum characters in a comment block.") + parser.add_argument("--exclude", action="append", default=[], help="Path component to exclude; can be repeated.") + parser.add_argument("--max-findings", type=int, default=50, help="Maximum findings to print before truncating.") + parser.add_argument( + "--ignore-before-date", + type=_parse_cutoff_date, + default=datetime.date(2026, 8, 27), + help="Ignore findings where every reported line was last committed before this YYYY-MM-DD date.", + ) + parser.add_argument( + "--no-date-filter", + action="store_true", + help="Report findings regardless of the last commit date for their comment lines.", + ) + parser.add_argument( + "--no-owner-filter", + action="store_true", + help="Report findings even when the file's owner is the one who last committed their comment lines.", + ) + parser.add_argument( + "--no-cache", + action="store_true", + help=f"Ignore the per-file noisy comment cache at {_display_path(CACHE_PATH)}.", + ) + parser.add_argument( + "--all-files", + action="store_true", + help="Scan all selected files even in PR CI. By default, PR CI scans only changed Python files.", + ) + parser.add_argument( + "--progress", + choices=["auto", "always", "never"], + default="auto", + help="Show scan progress. Defaults to auto, enabled for TTY and CI output.", + ) + parser.add_argument( + "--rule", + action="append", + default=[], + choices=["NC001", "NC002"], + help="Only report this rule code; can be repeated.", + ) + parser.add_argument( + "--fail-on-findings", + action="store_true", + help="Exit non-zero when noisy comments are found. On by default when scanning a patch in PR CI.", + ) + parser.add_argument( + "--no-fail-on-findings", + action="store_true", + help="Report findings without failing, even in PR CI.", + ) + args = parser.parse_args() + + excludes = DEFAULT_EXCLUDES.union(args.exclude) + targets = args.path or args.targets or DEFAULT_TARGETS + diff_only = _running_in_pr() and not args.all_files + findings = collect_findings( + targets=targets, + excludes=excludes, + max_block_lines=args.max_block_lines, + max_block_chars=args.max_block_chars, + use_cache=not args.no_cache, + diff_only=diff_only, + progress=_should_show_progress(args.progress), + ) + if args.rule: + rules = set(args.rule) + findings = [finding for finding in findings if finding.code in rules] + # Blocking requires a resolved diff. Without one -- `origin/main` missing from a CI checkout, say -- + # the scan covers the whole tree, and failing on comments the patch never touched would break every + # PR, so an unresolved diff degrades to reporting instead. + patch_is_resolved = diff_only and _patch_added_lines() is not None + if patch_is_resolved: + findings = _filter_findings_to_patch(findings) + cutoff_date = None if args.no_date_filter else args.ignore_before_date + findings = _filter_findings_by_cutoff(findings, cutoff_date) + + owners = None + if not args.no_owner_filter: + owners, unavailable = _load_file_owners() + if unavailable: + print(f"Reporting owners' own comments too: {unavailable}.") + findings = _filter_findings_by_ownership(findings, owners) + + # Blocking on a patch, reporting on a full scan. A full scan sees comments the caller did not + # write, and failing on those would make the check impossible to act on -- see `_patch_added_lines`. + blocking = args.fail_on_findings or (patch_is_resolved and not args.no_fail_on_findings) + + if not findings: + print("No noisy comments found.") + return 0 + + findings = sorted( + findings, key=lambda finding: (-finding.score, finding.code, _display_path(finding.path), finding.line) + ) + scope = "on lines this patch adds" if patch_is_resolved else "in the scanned files" + mode = "Blocking." if blocking else "Reporting only; not blocking." + print(f"Found {len(findings)} noisy comment finding(s) {scope}. {mode}") + for finding in findings[: args.max_findings]: + print(f"{_display_path(finding.path)}:{finding.line}: {finding.code} {finding.message}") + print(f" {finding.text[:160]}") + + remaining = len(findings) - args.max_findings + if remaining > 0: + print(f"... and {remaining} more finding(s).") + if blocking: + print("Shorten these comments, or add `# noqa: ` to one that is long on purpose.") + else: + print("Tune thresholds with --max-block-lines and --max-block-chars.") + if cutoff_date is not None: + print(f"Ignored findings last committed before {cutoff_date.isoformat()}.") + if owners is not None: + print("Ignored findings whose every line was last committed by an owner of the file.") + print(f"Found {len(findings)} noisy comment finding(s).") + + return 1 if blocking else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/utils/get_previous_daily_ci.py b/utils/get_previous_daily_ci.py index fb0f5f6b9db6..440011da056b 100644 --- a/utils/get_previous_daily_ci.py +++ b/utils/get_previous_daily_ci.py @@ -39,18 +39,11 @@ def get_daily_ci_runs(token, num_runs=7, workflow_id=None): url = f"https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs" url += f"?branch=main&exclude_pull_requests=true&per_page={num_runs}" - # The GitHub Actions search index (used for event=/branch= filters) can lag badly: - # the same URL has returned total_count values of 190, 238, 311, and 413 within minutes - # from different backend nodes (PR #48374). We detect a stale response by checking - # that GITHUB_RUN_ID appears in the results; if absent we retry. - # - # Stale-check is only active when querying the *same* workflow as the current run AND - # the current run is schedule-triggered (so GITHUB_RUN_ID is guaranteed to be in the - # results when the API is fresh). The two remaining uncovered paths are left for a - # follow-up PR once this path is confirmed stable: - # • AMD CI querying its own history → falls into the event=workflow_run fallback below - # (AMD CI is triggered via workflow_run, not schedule). - # • AMD CI querying the matching Nvidia run (different workflow_id) → stale_check=False. + # The GitHub Actions search index (event=/branch= filters) lags: the same URL returned + # total_count 190, 238, 311 and 413 within minutes from different backend nodes (PR #48374). + # A response without GITHUB_RUN_ID is stale, so retry. Only checkable for the current run's own + # workflow on a schedule trigger, which guarantees the run is in a fresh response. AMD CI, which + # runs via workflow_run or queries another workflow_id, stays uncovered pending a follow-up PR. stale_check = ( current_workflow_id is not None and int(workflow_id) == int(current_workflow_id) From 976e7a41c6615559f7a2ccb79fd5212c378b2c95 Mon Sep 17 00:00:00 2001 From: Raushan Turganbay Date: Fri, 4 Sep 2026 11:19:56 +0000 Subject: [PATCH 052/996] Processing tests [part 2] (#47922) * . * draft it * fix some * maybe * . * chat template in qwen style * draft sth for video sampling tests * fix * . * fix last * move around * draft * . * renamed those * fix repo deleted one line in all files * fix * the rest * merge this * typo * when will this end? * fix? * save coz now i will break stuff * rename it all, except for xx_token_id * missed these renames * fix last * revert * comments * less small private helpers * more comments * last failing tests, and i stop adding more stuff * typo * forgot about this one * why i cannot get green CI * move around to skip more tests * few more * fix * new model * here it is, opened PR on the hub * forgot modular... --- .../models/clipseg/processing_clipseg.py | 14 +- .../configuration_cohere_compass.py | 5 + .../cohere_compass/modular_cohere_compass.py | 5 + src/transformers/models/csm/processing_csm.py | 2 + .../gemma4/feature_extraction_gemma4.py | 1 - .../models/glm46v/configuration_glm46v.py | 1 - .../models/glm46v/image_processing_glm46v.py | 1 - .../glm46v/image_processing_pil_glm46v.py | 1 - .../models/glm46v/modeling_glm46v.py | 1 - .../models/glm46v/modular_glm46v.py | 3 +- .../models/glm46v/processing_glm46v.py | 1 - .../models/glm46v/video_processing_glm46v.py | 3 +- .../models/glm4v/video_processing_glm4v.py | 4 +- .../models/glm5_next/modular_glm5_next.py | 2 +- .../glm5_next/video_processing_glm5_next.py | 2 +- .../models/glmga/modular_glmga.py | 2 +- .../models/glmga/video_processing_glmga.py | 2 +- .../hunyuan_vl/processing_hunyuan_vl.py | 2 +- .../muse_glimmer/modular_muse_glimmer.py | 2 + .../video_processing_muse_glimmer.py | 2 + .../models/owlv2/processing_owlv2.py | 2 + .../qwen2_5_omni/processing_qwen2_5_omni.py | 3 +- .../qwen3_omni_moe/modular_qwen3_omni_moe.py | 8 +- .../processing_qwen3_omni_moe.py | 10 +- tests/models/aria/test_processing_aria.py | 2 +- .../test_processing_audioflamingo3.py | 2 + .../aya_vision/test_processing_aya_vision.py | 22 - .../test_processing_bridgetower.py | 148 +- .../chameleon/test_processing_chameleon.py | 4 +- .../models/clipseg/test_processing_clipseg.py | 6 +- .../test_processing_cohere_compass.py | 82 +- .../test_processing_colmodernvbert.py | 147 +- .../models/colpali/test_processing_colpali.py | 114 +- .../colqwen2/test_processing_colqwen2.py | 126 +- .../test_processing_cosmos3_edge.py | 232 +--- tests/models/csm/test_processing_csm.py | 58 +- .../test_processing_deepseek_ocr2.py | 4 - tests/models/emu3/test_processing_emu3.py | 6 +- .../test_processing_ernie4_5_vl_moe.py | 276 +--- tests/models/evolla/test_processing_evolla.py | 6 + .../florence2/test_processing_florence2.py | 4 - tests/models/fuyu/test_processing_fuyu.py | 170 +-- tests/models/gemma3/test_processing_gemma3.py | 24 +- .../test_feature_extraction_gemma3n.py | 4 - .../models/gemma3n/test_processing_gemma3n.py | 4 +- tests/models/gemma4/test_processing_gemma4.py | 28 +- .../test_processing_gemma4_unified.py | 28 +- tests/models/glm46v/test_processing_glm46v.py | 220 +-- tests/models/glm4v/test_processing_glm4v.py | 225 +--- .../glm_image/test_processing_glm_image.py | 131 +- tests/models/glmasr/test_processing_glmasr.py | 2 + .../got_ocr2/test_processing_got_ocr2.py | 58 +- .../test_processing_granite4_vision.py | 6 +- .../test_processing_granite_speech5.py | 3 + .../test_processing_grounding_dino.py | 10 +- .../hunyuan_vl/test_processing_hunyuan_vl.py | 74 +- .../models/idefics/test_processing_idefics.py | 23 +- .../idefics3/test_processing_idefics3.py | 8 +- .../models/inkling/test_processing_inkling.py | 127 +- .../test_processing_instructblip.py | 4 +- .../test_processing_instructblipvideo.py | 9 +- .../internvl/test_processing_internvl.py | 99 +- tests/models/janus/test_processing_janus.py | 2 +- .../kimi_k25/test_processing_kimi_k25.py | 198 +-- .../models/kosmos2/test_processing_kosmos2.py | 163 +-- .../kosmos2_5/test_processing_kosmos2_5.py | 157 +-- .../layoutlmv2/test_processing_layoutlmv2.py | 8 +- .../layoutlmv3/test_processing_layoutlmv3.py | 8 +- .../models/lfm2_vl/test_processing_lfm2_vl.py | 9 +- .../test_processing_lighton_ocr.py | 10 +- tests/models/llava/test_processing_llava.py | 2 +- .../test_processing_llava_next_video.py | 3 +- .../test_processing_llava_onevision.py | 78 +- .../models/mgp_str/test_processing_mgp_str.py | 6 +- .../test_processing_minicpmv4_6.py | 129 +- .../mistral3/test_processing_mistral3.py | 4 +- tests/models/mllama/test_processing_mllama.py | 21 +- .../test_processing_muse_glimmer.py | 46 +- .../test_processing_musicflamingo.py | 2 + tests/models/neomme/test_processing_neomme.py | 151 +-- .../oneformer/test_processing_oneformer.py | 10 +- tests/models/ovis2/test_processing_ovis2.py | 4 +- tests/models/owlvit/test_processing_owlvit.py | 4 +- .../paligemma/test_processing_paligemma.py | 7 +- .../test_processing_phi4_multimodal.py | 18 +- tests/models/pi0/test_processing_pi0.py | 18 +- .../pix2struct/test_processing_pix2struct.py | 152 +-- .../test_processing_pp_chart2table.py | 7 +- .../test_processing_pp_formulanet.py | 27 +- .../test_processing_qianfan_ocr.py | 129 +- .../test_processing_qwen2_5_omni.py | 306 +---- .../qwen2_5_vl/test_processing_qwen2_5_vl.py | 237 +--- .../test_processing_qwen2_audio.py | 2 + .../qwen2_vl/test_processing_qwen2_vl.py | 232 +--- .../test_processing_qwen3_omni_moe.py | 297 +--- .../qwen3_vl/test_processing_qwen3_vl.py | 227 +--- tests/models/sam/test_processing_sam.py | 16 +- tests/models/sam2/test_processing_sam2.py | 9 +- .../sam2_video/test_processing_sam2_video.py | 9 +- tests/models/sam3/test_processing_sam3.py | 13 +- tests/models/sam_hq/test_processing_sam_hq.py | 40 +- .../test_processing_shieldgemma2.py | 51 +- .../models/smolvlm/test_processing_smolvlm.py | 83 +- tests/models/tipsv2/test_processing_tipsv2.py | 6 +- tests/models/trocr/test_processing_trocr.py | 2 +- tests/models/udop/test_processing_udop.py | 4 + .../vibevoice/test_processing_vibevoice.py | 6 +- .../test_processing_video_llama_3.py | 260 +--- .../videoprism/test_processing_videoprism.py | 2 +- .../test_processing_voxtral_realtime.py | 24 +- tests/test_processing_common.py | 1198 ++++++----------- 111 files changed, 1483 insertions(+), 5489 deletions(-) diff --git a/src/transformers/models/clipseg/processing_clipseg.py b/src/transformers/models/clipseg/processing_clipseg.py index 9d2e0538401a..57b364de6a50 100644 --- a/src/transformers/models/clipseg/processing_clipseg.py +++ b/src/transformers/models/clipseg/processing_clipseg.py @@ -26,7 +26,7 @@ def __init__(self, image_processor=None, tokenizer=None, **kwargs): super().__init__(image_processor, tokenizer) @auto_docstring - def __call__(self, text=None, images=None, visual_prompt=None, return_tensors=None, **kwargs): + def __call__(self, text=None, images=None, visual_prompt=None, **kwargs): r""" visual_prompt (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`): The visual prompt image or batch of images to be prepared. Each visual prompt image can be a PIL image, @@ -53,17 +53,13 @@ def __call__(self, text=None, images=None, visual_prompt=None, return_tensors=No ) if text is not None: - encoding = self.tokenizer(text, return_tensors=return_tensors, **output_kwargs["text_kwargs"]) + encoding = self.tokenizer(text, **output_kwargs["text_kwargs"]) if visual_prompt is not None: - prompt_features = self.image_processor( - visual_prompt, return_tensors=return_tensors, **output_kwargs["images_kwargs"] - ) + prompt_features = self.image_processor(visual_prompt, **output_kwargs["images_kwargs"]) if images is not None: - image_features = self.image_processor( - images, return_tensors=return_tensors, **output_kwargs["images_kwargs"] - ) + image_features = self.image_processor(images, **output_kwargs["images_kwargs"]) if visual_prompt is not None and images is not None: encoding = { @@ -82,7 +78,7 @@ def __call__(self, text=None, images=None, visual_prompt=None, return_tensors=No } return encoding else: - return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors) + return BatchEncoding(data=dict(**image_features)) __all__ = ["CLIPSegProcessor"] diff --git a/src/transformers/models/cohere_compass/configuration_cohere_compass.py b/src/transformers/models/cohere_compass/configuration_cohere_compass.py index 9b3cc30eb68b..a999abefce3f 100644 --- a/src/transformers/models/cohere_compass/configuration_cohere_compass.py +++ b/src/transformers/models/cohere_compass/configuration_cohere_compass.py @@ -133,6 +133,11 @@ def __post_init__(self, **kwargs): def convert_rope_params_to_dict(self, **kwargs): # allow per layer rope with optional NoPE layers self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else {} + # workaround until the hub config is fixed, dangling entries were saved that fire on validation + # ref: https://huggingface.co/CohereLabs/North-Micro-Vision-Instruct/discussions/3 + if self.layer_types is not None and not set(self.rope_parameters.keys()).isdisjoint(self.layer_types): + self.rope_parameters.pop("rope_theta", None) + self.rope_parameters.pop("rope_type", None) self.standardize_rope_params() return kwargs diff --git a/src/transformers/models/cohere_compass/modular_cohere_compass.py b/src/transformers/models/cohere_compass/modular_cohere_compass.py index adebc0529b33..c9b4b16beba0 100644 --- a/src/transformers/models/cohere_compass/modular_cohere_compass.py +++ b/src/transformers/models/cohere_compass/modular_cohere_compass.py @@ -93,6 +93,11 @@ def __post_init__(self, **kwargs): def convert_rope_params_to_dict(self, **kwargs): # allow per layer rope with optional NoPE layers self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else {} + # workaround until the hub config is fixed, dangling entries were saved that fire on validation + # ref: https://huggingface.co/CohereLabs/North-Micro-Vision-Instruct/discussions/3 + if self.layer_types is not None and not set(self.rope_parameters.keys()).isdisjoint(self.layer_types): + self.rope_parameters.pop("rope_theta", None) + self.rope_parameters.pop("rope_type", None) self.standardize_rope_params() return kwargs diff --git a/src/transformers/models/csm/processing_csm.py b/src/transformers/models/csm/processing_csm.py index 8b47adc41796..2fcc12f0cc8a 100644 --- a/src/transformers/models/csm/processing_csm.py +++ b/src/transformers/models/csm/processing_csm.py @@ -70,6 +70,8 @@ class CsmProcessorKwargs(ProcessingKwargs, total=False): @requires(backends=("torch",)) @auto_docstring class CsmProcessor(ProcessorMixin): + valid_processor_kwargs = CsmProcessorKwargs + def __init__( self, feature_extractor, diff --git a/src/transformers/models/gemma4/feature_extraction_gemma4.py b/src/transformers/models/gemma4/feature_extraction_gemma4.py index 38382e8a85cb..e1259fea2cc9 100644 --- a/src/transformers/models/gemma4/feature_extraction_gemma4.py +++ b/src/transformers/models/gemma4/feature_extraction_gemma4.py @@ -167,7 +167,6 @@ def __init__( self.per_bin_stddev = None def _extract_spectrogram(self, waveform: np.ndarray, attention_mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: - """""" if waveform.ndim == 1: # If single waveform, add batch dimension waveform = np.expand_dims(waveform, axis=0) diff --git a/src/transformers/models/glm46v/configuration_glm46v.py b/src/transformers/models/glm46v/configuration_glm46v.py index 95c62c7c9979..2e621a59ab0a 100644 --- a/src/transformers/models/glm46v/configuration_glm46v.py +++ b/src/transformers/models/glm46v/configuration_glm46v.py @@ -18,7 +18,6 @@ # See the License for the specific language governing permissions and # limitations under the License. - from huggingface_hub.dataclasses import strict from ...configuration_utils import PreTrainedConfig diff --git a/src/transformers/models/glm46v/image_processing_glm46v.py b/src/transformers/models/glm46v/image_processing_glm46v.py index 9b51615e6b0c..3ddb2961eb05 100644 --- a/src/transformers/models/glm46v/image_processing_glm46v.py +++ b/src/transformers/models/glm46v/image_processing_glm46v.py @@ -18,7 +18,6 @@ # See the License for the specific language governing permissions and # limitations under the License. - import math import torch diff --git a/src/transformers/models/glm46v/image_processing_pil_glm46v.py b/src/transformers/models/glm46v/image_processing_pil_glm46v.py index 2b3caa1c3103..67110c4df92b 100644 --- a/src/transformers/models/glm46v/image_processing_pil_glm46v.py +++ b/src/transformers/models/glm46v/image_processing_pil_glm46v.py @@ -18,7 +18,6 @@ # See the License for the specific language governing permissions and # limitations under the License. - import math import numpy as np diff --git a/src/transformers/models/glm46v/modeling_glm46v.py b/src/transformers/models/glm46v/modeling_glm46v.py index 4bc77cada67d..54028b97126c 100644 --- a/src/transformers/models/glm46v/modeling_glm46v.py +++ b/src/transformers/models/glm46v/modeling_glm46v.py @@ -18,7 +18,6 @@ # See the License for the specific language governing permissions and # limitations under the License. - import itertools from dataclasses import dataclass from typing import Any diff --git a/src/transformers/models/glm46v/modular_glm46v.py b/src/transformers/models/glm46v/modular_glm46v.py index ff2a0e694815..e18b9aca5bd7 100644 --- a/src/transformers/models/glm46v/modular_glm46v.py +++ b/src/transformers/models/glm46v/modular_glm46v.py @@ -12,7 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. - import numpy as np from huggingface_hub.dataclasses import strict @@ -179,7 +178,7 @@ def sample_frames( if len(uniq) & 1: uniq.append(uniq[-1]) - return np.array(uniq) + return np.array(uniq, dtype=int) __all__ = [ diff --git a/src/transformers/models/glm46v/processing_glm46v.py b/src/transformers/models/glm46v/processing_glm46v.py index 87fbd53509b0..3b0a18c26460 100644 --- a/src/transformers/models/glm46v/processing_glm46v.py +++ b/src/transformers/models/glm46v/processing_glm46v.py @@ -18,7 +18,6 @@ # See the License for the specific language governing permissions and # limitations under the License. - import numpy as np from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin diff --git a/src/transformers/models/glm46v/video_processing_glm46v.py b/src/transformers/models/glm46v/video_processing_glm46v.py index 361a19fb2a34..c64adf728253 100644 --- a/src/transformers/models/glm46v/video_processing_glm46v.py +++ b/src/transformers/models/glm46v/video_processing_glm46v.py @@ -18,7 +18,6 @@ # See the License for the specific language governing permissions and # limitations under the License. - import math import numpy as np @@ -189,7 +188,7 @@ def sample_frames( if len(uniq) & 1: uniq.append(uniq[-1]) - return np.array(uniq) + return np.array(uniq, dtype=int) def resize( self, diff --git a/src/transformers/models/glm4v/video_processing_glm4v.py b/src/transformers/models/glm4v/video_processing_glm4v.py index 9c9b17e4cea6..b7886d636442 100644 --- a/src/transformers/models/glm4v/video_processing_glm4v.py +++ b/src/transformers/models/glm4v/video_processing_glm4v.py @@ -147,7 +147,7 @@ def sample_frames( duration = metadata.duration or round(max_frame_idx / metadata.fps) + 1 if duration <= self.max_duration: - n = int(math.floor(duration * requested_fps)) + n = max(int(math.floor(duration * requested_fps)), 1) # sample at least 1 frame frame_indices = [min(max_frame_idx, int(math.ceil(i * metadata.fps / requested_fps))) for i in range(n)] else: num_samples = int(self.max_duration * requested_fps) @@ -166,7 +166,7 @@ def sample_frames( if len(uniq) & 1: uniq.append(uniq[-1]) - return np.array(uniq) + return np.array(uniq, dtype=int) def resize( self, diff --git a/src/transformers/models/glm5_next/modular_glm5_next.py b/src/transformers/models/glm5_next/modular_glm5_next.py index 1214d52c275a..6cb6bca776c0 100644 --- a/src/transformers/models/glm5_next/modular_glm5_next.py +++ b/src/transformers/models/glm5_next/modular_glm5_next.py @@ -2187,7 +2187,7 @@ def sample_frames( if len(uniq) & 1: uniq.append(uniq[-1]) - return np.array(uniq) + return np.array(uniq, dtype=int) def _preprocess( self, diff --git a/src/transformers/models/glm5_next/video_processing_glm5_next.py b/src/transformers/models/glm5_next/video_processing_glm5_next.py index 04a2acdf18e0..e28a85089c78 100644 --- a/src/transformers/models/glm5_next/video_processing_glm5_next.py +++ b/src/transformers/models/glm5_next/video_processing_glm5_next.py @@ -234,7 +234,7 @@ def sample_frames( if len(uniq) & 1: uniq.append(uniq[-1]) - return np.array(uniq) + return np.array(uniq, dtype=int) def resize( self, diff --git a/src/transformers/models/glmga/modular_glmga.py b/src/transformers/models/glmga/modular_glmga.py index c1da4e955a66..f354fefed303 100644 --- a/src/transformers/models/glmga/modular_glmga.py +++ b/src/transformers/models/glmga/modular_glmga.py @@ -311,7 +311,7 @@ def sample_frames( if len(uniq) & 1: uniq.append(uniq[-1]) - return np.array(uniq) + return np.array(uniq, dtype=int) def _preprocess( self, diff --git a/src/transformers/models/glmga/video_processing_glmga.py b/src/transformers/models/glmga/video_processing_glmga.py index 3d530fd8ee32..11da53d4270a 100644 --- a/src/transformers/models/glmga/video_processing_glmga.py +++ b/src/transformers/models/glmga/video_processing_glmga.py @@ -191,7 +191,7 @@ def sample_frames( if len(uniq) & 1: uniq.append(uniq[-1]) - return np.array(uniq) + return np.array(uniq, dtype=int) def resize( self, diff --git a/src/transformers/models/hunyuan_vl/processing_hunyuan_vl.py b/src/transformers/models/hunyuan_vl/processing_hunyuan_vl.py index 7675c22d0f98..39e994cc5a05 100644 --- a/src/transformers/models/hunyuan_vl/processing_hunyuan_vl.py +++ b/src/transformers/models/hunyuan_vl/processing_hunyuan_vl.py @@ -136,7 +136,7 @@ def validate_inputs( ): raise ValueError( f"HunYuanVL image placeholders must be formatted as " - f"{self.image_start_token}{self.image_token}{self.image_end_token}. " + f"{self.image_start_token}{self.image_token}{self.image_end_token} but got {prompt}. " "Please format prompts with the processor chat template or include the image start/end " "tokens explicitly." ) diff --git a/src/transformers/models/muse_glimmer/modular_muse_glimmer.py b/src/transformers/models/muse_glimmer/modular_muse_glimmer.py index e6db2f0737c9..b881d44b81e2 100644 --- a/src/transformers/models/muse_glimmer/modular_muse_glimmer.py +++ b/src/transformers/models/muse_glimmer/modular_muse_glimmer.py @@ -425,6 +425,8 @@ def sample_frames( np.ndarray: Indices to sample video frames. """ + fps = fps if fps is not None else self.fps + num_frames = num_frames if num_frames is not None else self.num_frames if metadata.fps is None: logger.warning_once( "The `fps` of the input video could not be inferred. Defaulting to `fps=24`. " diff --git a/src/transformers/models/muse_glimmer/video_processing_muse_glimmer.py b/src/transformers/models/muse_glimmer/video_processing_muse_glimmer.py index 8b12cd168e7f..f938a5dc433e 100644 --- a/src/transformers/models/muse_glimmer/video_processing_muse_glimmer.py +++ b/src/transformers/models/muse_glimmer/video_processing_muse_glimmer.py @@ -210,6 +210,8 @@ def sample_frames( np.ndarray: Indices to sample video frames. """ + fps = fps if fps is not None else self.fps + num_frames = num_frames if num_frames is not None else self.num_frames if metadata.fps is None: logger.warning_once( "The `fps` of the input video could not be inferred. Defaulting to `fps=24`. " diff --git a/src/transformers/models/owlv2/processing_owlv2.py b/src/transformers/models/owlv2/processing_owlv2.py index 39c8623937ea..b4620c338452 100644 --- a/src/transformers/models/owlv2/processing_owlv2.py +++ b/src/transformers/models/owlv2/processing_owlv2.py @@ -60,6 +60,8 @@ class Owlv2ProcessorKwargs(ProcessingKwargs, total=False): @auto_docstring class Owlv2Processor(ProcessorMixin): + valid_processor_kwargs = Owlv2ProcessorKwargs + def __init__(self, image_processor, tokenizer, **kwargs): super().__init__(image_processor, tokenizer) diff --git a/src/transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py b/src/transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py index 47b9734d247d..a14604cc1bfc 100644 --- a/src/transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py +++ b/src/transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py @@ -164,7 +164,8 @@ def __call__( if videos is not None: videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"]) - fps = output_kwargs["videos_kwargs"].get("fps", 2.0) + fps = output_kwargs["videos_kwargs"].get("fps") + fps = fps if fps is not None else 2.0 # default fps not saved in official ckpt, hardcode video_grid_thw = videos_inputs["video_grid_thw"] second_per_grid_ts = [self.video_processor.temporal_patch_size / fps] * len(video_grid_thw) videos_inputs["video_second_per_grid"] = second_per_grid_ts diff --git a/src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py b/src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py index 966d5ecb7490..d6830caa4f9f 100644 --- a/src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py +++ b/src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py @@ -52,7 +52,7 @@ merge_with_config_defaults, ) from ...utils.output_capturing import OutputRecorder, capture_outputs -from ...video_utils import VideoInput, make_batched_videos +from ...video_utils import VideoInput from ..mimi.modeling_mimi import MimiLayerScale from ..qwen2_5_omni.configuration_qwen2_5_omni import ( Qwen2_5OmniAudioEncoderConfig, @@ -2724,7 +2724,7 @@ def __call__( images: ImageInput | None = None, videos: VideoInput | None = None, audio: AudioInput | None = None, - **kwargs, + **kwargs: Unpack[Qwen3OmniMoeProcessorKwargs], ): if text is None: raise ValueError("You need to specify either a `text` input to process.") @@ -2739,6 +2739,7 @@ def __call__( position_id_per_seconds = output_kwargs["videos_kwargs"].pop("position_id_per_seconds") use_audio_in_video = output_kwargs["videos_kwargs"].pop("use_audio_in_video") fps = output_kwargs["videos_kwargs"].get("fps", 1.0) + fps = fps if fps is not None else 1.0 n_window = output_kwargs["audio_kwargs"].pop("n_window", 50) if audio is not None: @@ -2764,9 +2765,8 @@ def __call__( image_grid_thw = iter([]) if videos is not None: - videos = make_batched_videos(videos) videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"]) - fps = [fps] * len(videos) + fps = [fps] * len(videos_inputs["video_grid_thw"]) videos_inputs["video_second_per_grid"] = [ self.video_processor.temporal_patch_size / fps[i] for i in range(len(fps)) ] diff --git a/src/transformers/models/qwen3_omni_moe/processing_qwen3_omni_moe.py b/src/transformers/models/qwen3_omni_moe/processing_qwen3_omni_moe.py index d417b4ed29d1..a9b40122d6e4 100644 --- a/src/transformers/models/qwen3_omni_moe/processing_qwen3_omni_moe.py +++ b/src/transformers/models/qwen3_omni_moe/processing_qwen3_omni_moe.py @@ -25,10 +25,10 @@ from ...audio_utils import AudioInput from ...feature_extraction_utils import BatchFeature from ...image_utils import ImageInput -from ...processing_utils import ProcessingKwargs, ProcessorMixin, VideosKwargs +from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack, VideosKwargs from ...tokenization_utils_base import TextInput from ...utils import auto_docstring -from ...video_utils import VideoInput, make_batched_videos +from ...video_utils import VideoInput # Redefine kwargs for videos because Qwen-Omni uses some kwargs for processing omni @@ -138,7 +138,7 @@ def __call__( images: ImageInput | None = None, videos: VideoInput | None = None, audio: AudioInput | None = None, - **kwargs, + **kwargs: Unpack[Qwen3OmniMoeProcessorKwargs], ) -> BatchFeature: if text is None: raise ValueError("You need to specify either a `text` input to process.") @@ -153,6 +153,7 @@ def __call__( position_id_per_seconds = output_kwargs["videos_kwargs"].pop("position_id_per_seconds") use_audio_in_video = output_kwargs["videos_kwargs"].pop("use_audio_in_video") fps = output_kwargs["videos_kwargs"].get("fps", 1.0) + fps = fps if fps is not None else 1.0 n_window = output_kwargs["audio_kwargs"].pop("n_window", 50) if audio is not None: @@ -178,9 +179,8 @@ def __call__( image_grid_thw = iter([]) if videos is not None: - videos = make_batched_videos(videos) videos_inputs = self.video_processor(videos=videos, **output_kwargs["videos_kwargs"]) - fps = [fps] * len(videos) + fps = [fps] * len(videos_inputs["video_grid_thw"]) videos_inputs["video_second_per_grid"] = [ self.video_processor.temporal_patch_size / fps[i] for i in range(len(fps)) ] diff --git a/tests/models/aria/test_processing_aria.py b/tests/models/aria/test_processing_aria.py index c05528410ba1..afe491a559a8 100644 --- a/tests/models/aria/test_processing_aria.py +++ b/tests/models/aria/test_processing_aria.py @@ -280,7 +280,7 @@ def test_special_mm_token_truncation(self): processor = self.get_processor() input_str = self.prepare_text_inputs(batch_size=2, modalities="image") - image_input = self.prepare_image_inputs(batch_size=2) + image_input = self.prepare_images_inputs(batch_size=2) _ = processor( text=input_str, diff --git a/tests/models/audioflamingo3/test_processing_audioflamingo3.py b/tests/models/audioflamingo3/test_processing_audioflamingo3.py index 5b1299730ca7..f801353b371b 100644 --- a/tests/models/audioflamingo3/test_processing_audioflamingo3.py +++ b/tests/models/audioflamingo3/test_processing_audioflamingo3.py @@ -36,6 +36,8 @@ class AudioFlamingo3ProcessorTest(ProcessorTesterMixin, unittest.TestCase): tiny_model_id = "hf-internal-testing/tiny-processor-audioflamingo3" checkpoint = "nvidia/audio-flamingo-3-hf" + audio_unstructured_max_length = 201 + @classmethod @require_torch def setUpClass(cls): diff --git a/tests/models/aya_vision/test_processing_aya_vision.py b/tests/models/aya_vision/test_processing_aya_vision.py index e2bc4e19ad8f..6f148e52fefb 100644 --- a/tests/models/aya_vision/test_processing_aya_vision.py +++ b/tests/models/aya_vision/test_processing_aya_vision.py @@ -142,25 +142,3 @@ def test_process_interleaved_images_videos(self): ], ) images_patches_index += inputs["pixel_values"].shape[0] - - def test_image_processor_defaults(self): - # AyaVisionProcessor has a default value `crop_to_patches=True` but the image processor's - # default is different. Override and pass the arg explicitly - - image_processor = self.get_component("image_processor") - - # Get all required components for processor - components = {} - for attribute in self.processor_class.get_attributes(): - components[attribute] = self.get_component(attribute) - - processor = self.processor_class(**components) - image_input = self.prepare_image_inputs() - - input_image_proc = image_processor(image_input, crop_to_patches=False, return_tensors="pt") - input_processor = processor(images=image_input, crop_to_patches=False, return_tensors="pt") - - # Verify outputs match - for key in input_image_proc: - if key in processor.model_input_names: - torch.testing.assert_close(input_image_proc[key], input_processor[key]) diff --git a/tests/models/bridgetower/test_processing_bridgetower.py b/tests/models/bridgetower/test_processing_bridgetower.py index b8019b3e3fb1..b65fe4f8e25d 100644 --- a/tests/models/bridgetower/test_processing_bridgetower.py +++ b/tests/models/bridgetower/test_processing_bridgetower.py @@ -13,7 +13,7 @@ # limitations under the License. import unittest -from transformers.testing_utils import require_torch, require_vision +from transformers.testing_utils import require_vision from transformers.utils import is_vision_available from ...test_processing_common import ProcessorTesterMixin @@ -33,149 +33,3 @@ class BridgeTowerProcessorTest(ProcessorTesterMixin, unittest.TestCase): def _setup_tokenizer(cls): tokenizer_class = cls._get_component_class_from_processor("tokenizer") return tokenizer_class.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc") - - @require_torch - @require_vision - def test_image_processor_defaults_preserved_by_image_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component( - "image_processor", - crop_size={"shortest_edge": 234, "longest_edge": 234}, - ) - tokenizer = self.get_component("tokenizer", max_length=117, padding="max_length") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = "lower newer" - image_input = self.prepare_image_inputs() - - inputs = processor(text=input_str, images=image_input) - self.assertEqual(len(inputs["pixel_values"][0][0]), 234) - - @require_torch - @require_vision - def test_structured_kwargs_nested_from_dict(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - input_str = "lower newer" - image_input = self.prepare_image_inputs() - - # Define the kwargs for each modality - all_kwargs = { - "common_kwargs": {"return_tensors": "pt"}, - "images_kwargs": { - "crop_size": {"shortest_edge": 214}, - }, - "text_kwargs": {"padding": "max_length", "max_length": 76}, - } - - inputs = processor(text=input_str, images=image_input, **all_kwargs) - self.assertEqual(inputs["pixel_values"].shape[2], 214) - - self.assertEqual(len(inputs["input_ids"][0]), 76) - - @require_torch - @require_vision - def test_kwargs_overrides_default_image_processor_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor", crop_size={"shortest_edge": 234}) - tokenizer = self.get_component("tokenizer", max_length=117) - if not tokenizer.pad_token: - tokenizer.pad_token = "[TEST_PAD]" - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = "lower newer" - image_input = self.prepare_image_inputs() - inputs = processor(text=input_str, images=image_input, crop_size={"shortest_edge": 224}) - self.assertEqual(len(inputs["pixel_values"][0][0]), 224) - - @require_torch - @require_vision - def test_unstructured_kwargs_batched(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - if not tokenizer.pad_token: - tokenizer.pad_token = "[TEST_PAD]" - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = ["lower newer", "upper older longer string"] - image_input = self.prepare_image_inputs(batch_size=2) - inputs = processor( - text=input_str, - images=image_input, - return_tensors="pt", - crop_size={"shortest_edge": 214}, - padding="longest", - max_length=76, - ) - self.assertEqual(inputs["pixel_values"].shape[2], 214) - - self.assertEqual(len(inputs["input_ids"][0]), 6) - - @require_torch - @require_vision - def test_unstructured_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - if not tokenizer.pad_token: - tokenizer.pad_token = "[TEST_PAD]" - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = "lower newer" - image_input = self.prepare_image_inputs() - inputs = processor( - text=input_str, - images=image_input, - return_tensors="pt", - crop_size={"shortest_edge": 214}, - padding="max_length", - max_length=76, - ) - - self.assertEqual(inputs["pixel_values"].shape[2], 214) - self.assertEqual(len(inputs["input_ids"][0]), 76) - - @require_torch - @require_vision - def test_structured_kwargs_nested(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - if not tokenizer.pad_token: - tokenizer.pad_token = "[TEST_PAD]" - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = "lower newer" - image_input = self.prepare_image_inputs() - - # Define the kwargs for each modality - all_kwargs = { - "common_kwargs": {"return_tensors": "pt"}, - "images_kwargs": {"crop_size": {"shortest_edge": 214}}, - "text_kwargs": {"padding": "max_length", "max_length": 76}, - } - - inputs = processor(text=input_str, images=image_input, **all_kwargs) - self.skip_processor_without_typed_kwargs(processor) - - self.assertEqual(inputs["pixel_values"].shape[2], 214) - - self.assertEqual(len(inputs["input_ids"][0]), 76) diff --git a/tests/models/chameleon/test_processing_chameleon.py b/tests/models/chameleon/test_processing_chameleon.py index 75b97210b3fd..c5ec55a019a5 100644 --- a/tests/models/chameleon/test_processing_chameleon.py +++ b/tests/models/chameleon/test_processing_chameleon.py @@ -42,7 +42,7 @@ def _setup_tokenizer(cls): return tokenizer @unittest.skip("Chameleon processor add a sep_token at the end of each sample") - def test_tokenizer_defaults(self): + def test_subprocessor_defaults_0_text(self): pass def test_special_mm_token_truncation(self): @@ -51,7 +51,7 @@ def test_special_mm_token_truncation(self): processor = self.get_processor() input_str = self.prepare_text_inputs(batch_size=2, modalities="image") - image_input = self.prepare_image_inputs(batch_size=2) + image_input = self.prepare_images_inputs(batch_size=2) _ = processor( text=input_str, diff --git a/tests/models/clipseg/test_processing_clipseg.py b/tests/models/clipseg/test_processing_clipseg.py index 73d0e8d74c3f..8c82fd121074 100644 --- a/tests/models/clipseg/test_processing_clipseg.py +++ b/tests/models/clipseg/test_processing_clipseg.py @@ -66,7 +66,7 @@ def test_processor_text(self): processor = self.get_processor() input_str = "lower newer" - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor(text=input_str, images=image_input) @@ -79,8 +79,8 @@ def test_processor_text(self): def test_processor_visual_prompt(self): processor = self.get_processor() - image_input = self.prepare_image_inputs() - visual_prompt_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() + visual_prompt_input = self.prepare_images_inputs() inputs = processor(images=image_input, visual_prompt=visual_prompt_input) diff --git a/tests/models/cohere_compass/test_processing_cohere_compass.py b/tests/models/cohere_compass/test_processing_cohere_compass.py index 5227be3c3cee..272c5990352a 100644 --- a/tests/models/cohere_compass/test_processing_cohere_compass.py +++ b/tests/models/cohere_compass/test_processing_cohere_compass.py @@ -16,10 +16,10 @@ import numpy as np from transformers import ( + AutoTokenizer, CohereCompassImageProcessor, CohereCompassProcessor, CohereCompassVideoProcessor, - PreTrainedTokenizerFast, ) from transformers.testing_utils import require_torch, require_vision @@ -30,48 +30,10 @@ @require_vision class CohereCompassProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = CohereCompassProcessor - video_unstructured_max_length = 870 - video_text_kwargs_max_length = 870 - video_text_kwargs_override_max_length = 870 - - @classmethod - def _setup_tokenizer(cls): - from tokenizers import Tokenizer - from tokenizers.models import WordLevel - from tokenizers.pre_tokenizers import Whitespace - - tokenizer = Tokenizer( - WordLevel( - { - "": 0, - "": 1, - "": 2, - "": 3, - "<|IMAGE_PAD|>": 4, - "<|VISION_START|>": 5, - "<|VISION_END|>": 6, - "<|VIDEO_PAD|>": 7, - "describe": 8, - "this": 9, - "image": 10, - }, - unk_token="", - ) - ) - tokenizer.pre_tokenizer = Whitespace() - return PreTrainedTokenizerFast( - tokenizer_object=tokenizer, - bos_token="", - eos_token="", - pad_token="", - unk_token="", - additional_special_tokens=[ - "<|IMAGE_PAD|>", - "<|VIDEO_PAD|>", - "<|VISION_START|>", - "<|VISION_END|>", - ], - ) + videos_unstructured_max_length = 870 + videos_text_kwargs_max_length = 870 + videos_text_kwargs_override_max_length = 870 + model_id = "CohereLabs/North-Micro-Vision-Instruct" @classmethod def _setup_image_processor(cls): @@ -85,18 +47,34 @@ def _setup_image_processor(cls): def _setup_video_processor(cls): return CohereCompassVideoProcessor(patch_size=16) + @classmethod + def _setup_tokenizer(cls): + # For some reason the tokenizer has saved image processing fields, unset it all! + tokenizer = AutoTokenizer.from_pretrained(cls.model_id) + return tokenizer + + @property + def video_sampling_expectations(self): + return [ + {"num_frames": 3, "fps": None, "expected_dim": 0, "output_length": 640}, + {"num_frames": None, "fps": 2, "expected_dim": 0, "output_length": 640}, + {"do_sample_frames": False, "fps": 10, "expected_dim": 0, "output_length": 1512}, + {"do_sample_frames": False, "expected_dim": 0, "output_length": 1512}, + {"expected_dim": 0, "output_length": 640}, + ] + def _image(self, height=56, width=56): from PIL import Image return Image.fromarray(np.full((height, width, 3), 127, dtype=np.uint8)) - def prepare_image_inputs(self, batch_size=None, nested=False): + def prepare_images_inputs(self, batch_size=None, nested=False): if batch_size is None: return self._image(64, 64) images = [self._image(64, 64) for _ in range(batch_size)] return [[image] for image in images] if nested else images - def prepare_video_inputs(self, batch_size=None): + def prepare_videos_inputs(self, batch_size=None): video = np.random.randint(255, size=(8, 3, 64, 64), dtype=np.uint8) return video if batch_size is None else [video] * batch_size @@ -129,17 +107,3 @@ def test_get_num_multimodal_tokens(self): output = processor._get_num_multimodal_tokens(image_sizes=[(56, 56), (56, 112)]) self.assertEqual(output["num_image_patches"], [4, 8]) self.assertEqual(output["num_image_tokens"], [1, 2]) - - def test_get_num_multimodal_tokens_matches_processor_call(self): - processor = self.get_processor() - image_sizes = [(64, 64), (64, 128), (128, 64)] - images = [np.random.randint(255, size=(*size, 3), dtype=np.uint8) for size in image_sizes] - output = processor( - text=[processor.image_token] * len(images), - images=images, - padding=True, - return_tensors="pt", - ) - expected = processor._get_num_multimodal_tokens(image_sizes=image_sizes)["num_image_tokens"] - actual = (output.input_ids == processor.image_token_id).sum(dim=1).tolist() - self.assertEqual(actual, expected) diff --git a/tests/models/colmodernvbert/test_processing_colmodernvbert.py b/tests/models/colmodernvbert/test_processing_colmodernvbert.py index f831d9d0fbee..72499b4a7f52 100755 --- a/tests/models/colmodernvbert/test_processing_colmodernvbert.py +++ b/tests/models/colmodernvbert/test_processing_colmodernvbert.py @@ -18,7 +18,6 @@ import unittest import torch -from parameterized import parameterized from transformers.models.colmodernvbert.processing_colmodernvbert import ColModernVBertProcessor from transformers.testing_utils import get_tests_dir, require_torch, require_vision @@ -53,7 +52,7 @@ def tearDownClass(cls): @require_vision def test_process_images(self): # Processor configuration - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() image_processor = self.get_component("image_processor") tokenizer = self.get_component("tokenizer", max_length=112, padding="max_length") @@ -103,26 +102,11 @@ def test_process_queries(self): # The following tests override the parent tests because ColModernVBertProcessor can only take one of images or text as input at a time. - def test_tokenizer_defaults_preserved_by_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - processor_components = self.prepare_components() - processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") + @unittest.skip("Model doesn't take images+text as input") + def test_replacement_offsets(self): + pass - processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - inputs = processor(text=input_str, return_tensors="pt") - self.assertEqual(inputs[self.text_input_name].shape[-1], 117) - - def test_image_processor_defaults_preserved_by_image_kwargs(self): - """ - We use do_rescale=True, rescale_factor=-1.0 to ensure that image_processor kwargs are preserved in the processor. - We then check that the mean of the pixel_values is less than or equal to 0 after processing. - Since the original pixel_values are in [0, 255], this is a good indicator that the rescale_factor is indeed applied. - """ - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_modality_processor_defaults_preserved_by_modality_kwargs(self, modality): processor_components = self.prepare_components() processor_components["image_processor"] = self.get_component( "image_processor", do_rescale=True, rescale_factor=-1.0 @@ -130,48 +114,36 @@ def test_image_processor_defaults_preserved_by_image_kwargs(self): processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor(images=image_input, return_tensors="pt") self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) - def test_kwargs_overrides_default_tokenizer_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - processor_components = self.prepare_components() - processor_components["tokenizer"] = self.get_component("tokenizer", padding="longest") - - processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - inputs = processor(text=input_str, return_tensors="pt", max_length=112, padding="max_length") - self.assertEqual(inputs[self.text_input_name].shape[-1], 112) - - def test_kwargs_overrides_default_image_processor_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_kwargs_overrides_default_modality_processor_kwargs(self, modality): processor_components = self.prepare_components() processor_components["image_processor"] = self.get_component( "image_processor", do_rescale=True, rescale_factor=1 ) - processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") + processor_components["tokenizer"] = self.get_component("tokenizer", padding=None) processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() - inputs = processor(images=image_input, do_rescale=True, rescale_factor=-1.0, return_tensors="pt") + inputs = processor( + images=image_input, + do_rescale=True, + rescale_factor=-1.0, + max_length=117, + padding="max_length", + return_tensors="pt", + ) self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) - def test_unstructured_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_unstructured_kwargs(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) input_str = self.prepare_text_inputs() inputs = processor( @@ -185,14 +157,11 @@ def test_unstructured_kwargs(self): self.assertEqual(inputs[self.text_input_name].shape[-1], 76) - def test_unstructured_kwargs_batched(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_unstructured_kwargs_batched(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs(batch_size=2) + image_input = self.prepare_images_inputs(batch_size=2) inputs = processor( images=image_input, return_tensors="pt", @@ -204,14 +173,11 @@ def test_unstructured_kwargs_batched(self): self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) - def test_doubly_passed_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_doubly_passed_kwargs(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() with self.assertRaises(ValueError): _ = processor( images=image_input, @@ -220,39 +186,17 @@ def test_doubly_passed_kwargs(self): return_tensors="pt", ) - def test_structured_kwargs_nested(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_structured_kwargs_nested_from_dict(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs() - - # Define the kwargs for each modality - all_kwargs = { - "common_kwargs": {"return_tensors": "pt"}, - "images_kwargs": {"do_rescale": True, "rescale_factor": -1.0}, - "text_kwargs": {"padding": "max_length", "max_length": 15, "truncation": True}, - } - - inputs = processor(text=input_str, **all_kwargs) - self.skip_processor_without_typed_kwargs(processor) - self.assertEqual(inputs[self.text_input_name].shape[-1], 15) - - def test_structured_kwargs_nested_from_dict(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - processor_components = self.prepare_components() - processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() # Define the kwargs for each modality all_kwargs = { "common_kwargs": {"return_tensors": "pt"}, "images_kwargs": {"do_rescale": True, "rescale_factor": -1.0}, + "text_kwargs": {"padding": "max_length", "max_length": 76}, } inputs = processor(images=image_input, **all_kwargs) @@ -261,15 +205,11 @@ def test_structured_kwargs_nested_from_dict(self): # Can process only text or images at a time def test_model_input_names(self): processor = self.get_processor() - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor(images=image_input) # When only images are provided, pixel_values must be present self.assertIn("pixel_values", inputs) - @unittest.skip(reason="ColModernVBert is meant to be used through `process_queries` or `process_images`.") - def test_tokenizer_defaults(self): - pass - @unittest.skip("ColModernVBert can't process text+image inputs at the same time") def test_processor_text_has_no_visual(self): pass @@ -286,39 +226,6 @@ def test_get_num_multimodal_tokens_matches_processor_call(self): def test_flat_kwarg_applied_when_modality_dict_lacks_it(self): pass - @unittest.skip("ColModernVBert does not have a chat template") + @unittest.skip("ColModernVBert has no chat template, force-set to None at runtime") def test_chat_template_save_loading(self): pass - - @unittest.skip("ColModernVBert does not have a chat template") - def test_apply_chat_template_audio(self): - pass - - @unittest.skip("ColModernVBert does not have a chat template") - def test_apply_chat_template_decoded_video(self): - pass - - @unittest.skip("ColModernVBert does not have a chat template") - def test_apply_chat_template_video(self): - pass - - @parameterized.expand([(1, "pt"), (2, "pt")]) - @unittest.skip("ColModernVBert does not have a chat template") - def test_apply_chat_template_image(self, batch_size, return_tensors): - pass - - @unittest.skip("ColModernVBert does not have a chat template") - def test_apply_chat_template_video_frame_sampling(self): - pass - - @unittest.skip("ColModernVBert does not have a chat template") - def test_chat_template_audio_from_video(self): - pass - - @unittest.skip("ColModernVBert does not have a chat template") - def test_chat_template_jinja_kwargs(self): - pass - - @unittest.skip("ColModernVBert does not have a chat template") - def test_apply_chat_template_assistant_mask(self): - pass diff --git a/tests/models/colpali/test_processing_colpali.py b/tests/models/colpali/test_processing_colpali.py index f9a261a6b989..2978c93ac9d4 100644 --- a/tests/models/colpali/test_processing_colpali.py +++ b/tests/models/colpali/test_processing_colpali.py @@ -46,12 +46,16 @@ def _setup_image_processor(cls): image_processor.image_seq_length = 0 return image_processor + @unittest.skip("Model doesn't take images+text as input") + def test_replacement_offsets(self): + pass + @unittest.skip("ColpaliProcessor can only process one of text or images at a time") def test_processor_with_multiple_inputs(self): pass - @unittest.skip("ColpaliProcessor adds a prefix and suffix to the text") - def test_tokenizer_defaults(self): + @unittest.skip("Processor adds query tokens and BOS to text") + def test_subprocessor_defaults_0_text(self): pass def test_get_num_vision_tokens(self): @@ -70,7 +74,7 @@ def test_get_num_vision_tokens(self): @require_vision def test_process_images(self): # Processor configuration - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() image_processor = self.get_component("image_processor") tokenizer = self.get_component("tokenizer", max_length=112, padding="max_length") image_processor.image_seq_length = 14 @@ -118,26 +122,7 @@ def test_process_queries(self): # The following tests override the parent tests because ColPaliProcessor can only take one of images or text as input at a time. - def test_tokenizer_defaults_preserved_by_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - processor_components = self.prepare_components() - processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") - - processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - inputs = processor(text=input_str, return_tensors="pt") - self.assertEqual(inputs[self.text_input_name].shape[-1], 117) - - def test_image_processor_defaults_preserved_by_image_kwargs(self): - """ - We use do_rescale=True, rescale_factor=-1.0 to ensure that image_processor kwargs are preserved in the processor. - We then check that the mean of the pixel_values is less than or equal to 0 after processing. - Since the original pixel_values are in [0, 255], this is a good indicator that the rescale_factor is indeed applied. - """ - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_modality_processor_defaults_preserved_by_modality_kwargs(self, modality): processor_components = self.prepare_components() processor_components["image_processor"] = self.get_component( "image_processor", do_rescale=True, rescale_factor=-1.0 @@ -145,48 +130,36 @@ def test_image_processor_defaults_preserved_by_image_kwargs(self): processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor(images=image_input, return_tensors="pt") self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) - def test_kwargs_overrides_default_tokenizer_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - processor_components = self.prepare_components() - processor_components["tokenizer"] = self.get_component("tokenizer", padding="longest") - - processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - inputs = processor(text=input_str, return_tensors="pt", max_length=112, padding="max_length") - self.assertEqual(inputs[self.text_input_name].shape[-1], 112) - - def test_kwargs_overrides_default_image_processor_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_kwargs_overrides_default_modality_processor_kwargs(self, modality): processor_components = self.prepare_components() processor_components["image_processor"] = self.get_component( "image_processor", do_rescale=True, rescale_factor=1 ) - processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") + processor_components["tokenizer"] = self.get_component("tokenizer", padding=None) processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() - inputs = processor(images=image_input, do_rescale=True, rescale_factor=-1.0, return_tensors="pt") + inputs = processor( + images=image_input, + do_rescale=True, + rescale_factor=-1.0, + max_length=117, + padding="max_length", + return_tensors="pt", + ) self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) - def test_unstructured_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_unstructured_kwargs(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) input_str = self.prepare_text_inputs() inputs = processor( @@ -200,14 +173,11 @@ def test_unstructured_kwargs(self): self.assertEqual(inputs[self.text_input_name].shape[-1], 76) - def test_unstructured_kwargs_batched(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_unstructured_kwargs_batched(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs(batch_size=2) + image_input = self.prepare_images_inputs(batch_size=2) inputs = processor( images=image_input, return_tensors="pt", @@ -219,14 +189,11 @@ def test_unstructured_kwargs_batched(self): self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) - def test_doubly_passed_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_doubly_passed_kwargs(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() with self.assertRaises(ValueError): _ = processor( images=image_input, @@ -235,34 +202,11 @@ def test_doubly_passed_kwargs(self): return_tensors="pt", ) - def test_structured_kwargs_nested(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_structured_kwargs_nested_from_dict(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs() - - # Define the kwargs for each modality - all_kwargs = { - "common_kwargs": {"return_tensors": "pt"}, - "images_kwargs": {"do_rescale": True, "rescale_factor": -1.0}, - "text_kwargs": {"padding": "max_length", "max_length": 76}, - } - inputs = processor(text=input_str, **all_kwargs) - self.skip_processor_without_typed_kwargs(processor) - - self.assertEqual(inputs[self.text_input_name].shape[-1], 76) - - def test_structured_kwargs_nested_from_dict(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - processor_components = self.prepare_components() - processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() # Define the kwargs for each modality all_kwargs = { @@ -272,12 +216,12 @@ def test_structured_kwargs_nested_from_dict(self): } inputs = processor(images=image_input, **all_kwargs) - self.assertEqual(inputs[self.text_input_name].shape[-1], 76) + self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) # Can process only text or images at a time def test_model_input_names(self): processor = self.get_processor() - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor(images=image_input) self.assertSetEqual(set(inputs.keys()), set(processor.model_input_names)) diff --git a/tests/models/colqwen2/test_processing_colqwen2.py b/tests/models/colqwen2/test_processing_colqwen2.py index 765bf8f25f78..ad736096a75d 100644 --- a/tests/models/colqwen2/test_processing_colqwen2.py +++ b/tests/models/colqwen2/test_processing_colqwen2.py @@ -49,8 +49,20 @@ def test_apply_chat_template_image(self, batch_size, return_tensors): def test_processor_with_multiple_inputs(self): pass - @unittest.skip("ColQwen2Processor adds a prefix and suffix to the text") - def test_tokenizer_defaults(self): + @unittest.skip("Model doesn't take images+text as input") + def test_replacement_offsets(self): + pass + + @parameterized.expand( + [ + ("text",), + ("images",), + ("videos",), + ("audio",), + ] + ) + @unittest.skip("Processor changes the input content/shape which subprocessor doesn't") + def test_subprocessor_defaults(self, modality): pass def test_get_num_vision_tokens(self): @@ -67,7 +79,7 @@ def test_get_num_vision_tokens(self): def test_process_images(self): # Processor configuration - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() image_processor = self.get_component("image_processor") tokenizer = self.get_component("tokenizer", max_length=112, padding="max_length") image_processor.image_seq_length = 14 @@ -113,26 +125,7 @@ def test_process_queries(self): # The following tests override the parent tests because ColQwen2Processor can only take one of images or text as input at a time. - def test_tokenizer_defaults_preserved_by_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - processor_components = self.prepare_components() - processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") - - processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - inputs = processor(text=input_str, return_tensors="pt") - self.assertEqual(inputs[self.text_input_name].shape[-1], 117) - - def test_image_processor_defaults_preserved_by_image_kwargs(self): - """ - We use do_rescale=True, rescale_factor=-1.0 to ensure that image_processor kwargs are preserved in the processor. - We then check that the mean of the pixel_values is less than or equal to 0 after processing. - Since the original pixel_values are in [0, 255], this is a good indicator that the rescale_factor is indeed applied. - """ - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_modality_processor_defaults_preserved_by_modality_kwargs(self, modality): processor_components = self.prepare_components() processor_components["image_processor"] = self.get_component( "image_processor", do_rescale=True, rescale_factor=-1.0 @@ -140,48 +133,36 @@ def test_image_processor_defaults_preserved_by_image_kwargs(self): processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor(images=image_input, return_tensors="pt") self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) - def test_kwargs_overrides_default_tokenizer_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - processor_components = self.prepare_components() - processor_components["tokenizer"] = self.get_component("tokenizer", padding="longest") - - processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - inputs = processor(text=input_str, return_tensors="pt", max_length=112, padding="max_length") - self.assertEqual(inputs[self.text_input_name].shape[-1], 112) - - def test_kwargs_overrides_default_image_processor_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_kwargs_overrides_default_modality_processor_kwargs(self, modality): processor_components = self.prepare_components() processor_components["image_processor"] = self.get_component( "image_processor", do_rescale=True, rescale_factor=1 ) - processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") + processor_components["tokenizer"] = self.get_component("tokenizer", padding=None) processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() - inputs = processor(images=image_input, do_rescale=True, rescale_factor=-1.0, return_tensors="pt") + inputs = processor( + images=image_input, + do_rescale=True, + rescale_factor=-1.0, + max_length=117, + padding="max_length", + return_tensors="pt", + ) self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) - def test_unstructured_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_unstructured_kwargs(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) input_str = self.prepare_text_inputs() inputs = processor( @@ -195,14 +176,11 @@ def test_unstructured_kwargs(self): self.assertEqual(inputs[self.text_input_name].shape[-1], 76) - def test_unstructured_kwargs_batched(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_unstructured_kwargs_batched(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs(batch_size=2) + image_input = self.prepare_images_inputs(batch_size=2) inputs = processor( images=image_input, return_tensors="pt", @@ -214,14 +192,11 @@ def test_unstructured_kwargs_batched(self): self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) - def test_doubly_passed_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_doubly_passed_kwargs(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() with self.assertRaises(ValueError): _ = processor( images=image_input, @@ -230,34 +205,11 @@ def test_doubly_passed_kwargs(self): return_tensors="pt", ) - def test_structured_kwargs_nested(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") + def _test_structured_kwargs_nested_from_dict(self, modality): processor_components = self.prepare_components() processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs() - - # Define the kwargs for each modality - all_kwargs = { - "common_kwargs": {"return_tensors": "pt"}, - "images_kwargs": {"do_rescale": True, "rescale_factor": -1.0}, - "text_kwargs": {"padding": "max_length", "max_length": 76}, - } - - inputs = processor(text=input_str, **all_kwargs) - self.skip_processor_without_typed_kwargs(processor) - self.assertEqual(inputs[self.text_input_name].shape[-1], 76) - - def test_structured_kwargs_nested_from_dict(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - processor_components = self.prepare_components() - processor = self.processor_class(**processor_components) - self.skip_processor_without_typed_kwargs(processor) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() # Define the kwargs for each modality all_kwargs = { @@ -267,12 +219,12 @@ def test_structured_kwargs_nested_from_dict(self): } inputs = processor(images=image_input, **all_kwargs) - self.assertEqual(inputs[self.text_input_name].shape[-1], 76) + self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) # Can process only text or images at a time def test_model_input_names(self): processor = self.get_processor() - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor(images=image_input) self.assertSetEqual(set(inputs.keys()), set(processor.model_input_names)) @@ -281,10 +233,6 @@ def test_model_input_names(self): def test_processor_text_has_no_visual(self): pass - @unittest.skip("ColQwen2Processor adds a batch dimension to the pixel_values") - def test_image_processor_defaults(self): - pass - @unittest.skip("ColQwen2Processor can't process text+image inputs at the same time") def test_get_num_multimodal_tokens_matches_processor_call(self): pass diff --git a/tests/models/cosmos3_edge/test_processing_cosmos3_edge.py b/tests/models/cosmos3_edge/test_processing_cosmos3_edge.py index f944df772b95..e411ab1da3b5 100644 --- a/tests/models/cosmos3_edge/test_processing_cosmos3_edge.py +++ b/tests/models/cosmos3_edge/test_processing_cosmos3_edge.py @@ -26,23 +26,17 @@ ) from transformers.testing_utils import ( require_torch, - require_torchcodec, require_torchvision, require_vision, ) from transformers.utils import ( - is_torch_available, - is_torchcodec_available, is_vision_available, ) from transformers.video_utils import VideoMetadata -from ...test_processing_common import ProcessorTesterMixin, url_to_local_path +from ...test_processing_common import ProcessorTesterMixin -if is_torch_available(): - import torch - if is_vision_available(): from PIL import Image @@ -54,7 +48,17 @@ class Cosmos3EdgeProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = Cosmos3EdgeProcessor tiny_model_id = "hf-internal-testing/tiny-processor-cosmos3-edge" - def prepare_image_inputs(self, batch_size: int | None = None, nested: bool = False): + @property + def video_sampling_expectations(self): + return [ + {"num_frames": 2, "fps": None, "expected_dim": 0, "output_length": 240}, + {"num_frames": None, "fps": 1, "expected_dim": 0, "output_length": 192}, + {"do_sample_frames": False, "fps": 10, "expected_dim": 0, "output_length": 176}, + {"do_sample_frames": False, "expected_dim": 0, "output_length": 176}, + {"expected_dim": 0, "output_length": 176}, + ] + + def prepare_images_inputs(self, batch_size: int | None = None, nested: bool = False): """Create small 64x96 inputs aligned to patch_size * merge_size (32). The fixed size keeps the processor tests lightweight and valid for patch @@ -67,7 +71,7 @@ def prepare_image_inputs(self, batch_size: int | None = None, nested: bool = Fal return [[image] for _ in range(batch_size)] return [image] * batch_size - def prepare_video_inputs(self, batch_size: int | None = None): + def prepare_videos_inputs(self, batch_size: int | None = None): """Create four 64x96 frames aligned to patch_size * merge_size (32). The fixed shape keeps frame-wise packing tests lightweight and valid; it @@ -78,212 +82,6 @@ def prepare_video_inputs(self, batch_size: int | None = None): return video return [video] * batch_size - @require_torch - def _test_apply_chat_template( - self, - modality: str, - batch_size: int, - return_tensors: str, - input_name: str, - processor_name: str, - input_data: list, - ): - """Adapt shared chat-template coverage to Edge's packed patch outputs.""" - if modality == "video" and any(isinstance(item, str) for item in input_data[:batch_size]): - if not is_torchcodec_available(): - self.skipTest("torchcodec is required to decode video URLs") - - processor = self.get_processor() - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - if processor_name not in self.processor_class.get_attributes(): - self.skipTest(f"{processor_name} attribute not present in {self.processor_class}") - - batch_messages = [ - [ - {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]}, - {"role": "user", "content": [{"type": "text", "text": "Describe this."}]}, - ] - for _ in range(batch_size) - ] - - formatted_prompt = processor.apply_chat_template(batch_messages, add_generation_prompt=True, tokenize=False) - self.assertEqual(len(formatted_prompt), batch_size) - - formatted_prompt_tokenized = processor.apply_chat_template( - batch_messages, add_generation_prompt=True, tokenize=True, return_tensors=return_tensors - ) - tokenized_prompt = processor.tokenizer(formatted_prompt, return_tensors=return_tensors) - self.assertListEqual(tokenized_prompt.input_ids.tolist(), formatted_prompt_tokenized.tolist()) - - tokenized_prompt_max_length = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_tensors=return_tensors, - processor_kwargs={ - "padding": "max_length", - "truncation": True, - "max_length": self.chat_template_max_length, - }, - ) - self.assertEqual(len(tokenized_prompt_max_length[0]), self.chat_template_max_length) - - out_dict_text = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - ) - self.assertTrue(all(key in out_dict_text for key in ["input_ids", "attention_mask"])) - self.assertEqual(len(out_dict_text["input_ids"]), batch_size) - self.assertEqual(len(out_dict_text["attention_mask"]), batch_size) - - for index, item in enumerate(input_data[:batch_size]): - batch_messages[index][1]["content"] = [ - batch_messages[index][1]["content"][0], - {"type": modality, "url": item}, - ] - - processor_kwargs = {"num_frames": 2, "fps": None} if modality == "video" else None - out_dict = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - processor_kwargs=processor_kwargs, - ) - input_name = getattr(self, input_name) - grid_name = "video_grid_thw" if modality == "video" else "image_grid_thw" - expected_num_patches = int(out_dict[grid_name].prod(dim=-1).sum()) - - self.assertIn(input_name, out_dict) - self.assertEqual(len(out_dict["input_ids"]), batch_size) - self.assertEqual(len(out_dict["attention_mask"]), batch_size) - self.assertEqual(len(out_dict[input_name]), expected_num_patches) - - return_tensor_to_type = {"pt": torch.Tensor, "np": np.ndarray, None: list} - for value in out_dict.values(): - self.assertIsInstance(value, return_tensor_to_type[return_tensors]) - - assistant_message = { - "role": "assistant", - "content": [{"type": "text", "text": "It is the sound of"}], - } - for index in range(batch_size): - batch_messages[index] = batch_messages[index] + [assistant_message] - continue_prompt = processor.apply_chat_template(batch_messages, continue_final_message=True, tokenize=False) - for prompt in continue_prompt: - self.assertTrue(prompt.endswith("It is the sound of")) - - @require_torchcodec - def test_apply_chat_template_video_frame_sampling(self): - """Adapt the shared frame-sampling assertions to Edge's packed video patches.""" - processor = self.get_processor() - - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - - messages = [ - [ - { - "role": "user", - "content": [ - { - "type": "video", - "url": url_to_local_path( - "https://huggingface.co/datasets/hf-internal-testing/test-videos/resolve/main/tiny_video_320x240.mp4" - ), - }, - {"type": "text", "text": "What is shown in this video?"}, - ], - }, - ] - ] - - def assert_packed_video(output, expected_num_frames): - self.assertIn(self.videos_input_name, output) - self.assertEqual(tuple(output["video_grid_thw"].shape), (1, 3)) - self.assertEqual(output["video_grid_thw"][0, 0].item(), expected_num_frames) - expected_num_patches = int(output["video_grid_thw"].prod(dim=-1).sum()) - self.assertEqual(len(output[self.videos_input_name]), expected_num_patches) - self.assertEqual( - output[self.videos_input_name].shape[-1], - len(processor.video_processor.image_mean) * processor.video_processor.patch_size**2, - ) - - num_frames = 3 - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors="pt", - processor_kwargs={"num_frames": num_frames, "fps": None, "do_sample_frames": True}, - ) - assert_packed_video(out_dict_with_video, expected_num_frames=num_frames) - - # The fixture would yield three frames at 10 FPS, which Edge clamps to its four-frame minimum. - fps = 10 - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors="pt", - processor_kwargs={"fps": fps, "num_frames": None, "do_sample_frames": True}, - ) - assert_packed_video(out_dict_with_video, expected_num_frames=processor.video_processor.min_frames) - - # Disabling sampling retains all eleven frames in the fixture even when an FPS is supplied. - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - processor_kwargs={"do_sample_frames": False, "fps": fps, "return_tensors": "pt"}, - ) - assert_packed_video(out_dict_with_video, expected_num_frames=11) - - with self.assertRaises(ValueError): - processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - processor_kwargs={"fps": fps, "num_frames": num_frames, "do_sample_frames": True}, - ) - - def test_video_processor_defaults(self): - """Compare processor outputs while preserving Edge's timestamp metadata.""" - video_processor = self.get_component("video_processor") - processor = self.processor_class(**self.prepare_components()) - video_input = self.prepare_video_inputs() - video_metadata = [VideoMetadata(total_num_frames=4, fps=2, duration=2.0, frames_indices=[0, 1, 2, 3])] - - video_processor_output = video_processor( - video_input, - video_metadata=video_metadata, - do_sample_frames=False, - return_metadata=True, - return_tensors="pt", - ) - processor_output = processor( - videos=video_input, - video_metadata=video_metadata, - do_sample_frames=False, - return_metadata=True, - return_tensors="pt", - ) - - for key in video_processor_output: - if key == "video_metadata": - self.assertEqual(video_processor_output[key], processor_output[key]) - else: - torch.testing.assert_close(video_processor_output[key], processor_output[key]) - def test_image_processor_uses_projector_block_major_patch_order(self): """Protect the checkpoint's block-major patches and HWC values within each patch.""" image = np.arange(4 * 4 * 3, dtype=np.uint8).reshape(4, 4, 3) @@ -390,3 +188,7 @@ def test_video_replacement_consumes_the_template_vision_wrapper_as_one_unit(self self.assertEqual(text, [f"before{replacement}after"]) self.assertEqual(replacement_offsets[0][0]["text"], "<|vision_start|><|video_pad|><|vision_end|>") + + @unittest.skip("Model needs real tokenizer and isn't worth testing, as it's used in diffusers pipe") + def test_replacement_offsets(self): + pass diff --git a/tests/models/csm/test_processing_csm.py b/tests/models/csm/test_processing_csm.py index 2955f9ac7092..b0e717196e1e 100644 --- a/tests/models/csm/test_processing_csm.py +++ b/tests/models/csm/test_processing_csm.py @@ -17,12 +17,13 @@ import jinja2 import numpy as np +from parameterized import parameterized from transformers import CsmProcessor from transformers.testing_utils import require_torch from transformers.utils import is_torch_available -from ...test_processing_common import ProcessorTesterMixin +from ...test_processing_common import MODALITY_TEST_SPECS, ProcessorTesterMixin if is_torch_available(): @@ -43,10 +44,6 @@ def _setup_test_attributes(cls, processor): cls.pad_token_id = processor.tokenizer.pad_token_id cls.bos_token_id = processor.tokenizer.bos_token_id - @unittest.skip("CsmProcessor modifies the tokenizer inputs") - def test_tokenizer_defaults(self): - pass - @staticmethod def prepare_processor_dict(): return {"chat_template": "\n{%- for message in messages %}\n {#-- Validate role is a stringified integer --#}\n {%- if not message['role'] is string or not message['role'].isdigit() %}\n {{- raise_exception(\"The role must be an integer or a stringified integer (e.g. '0') designating the speaker id\") }}\n {%- endif %}\n\n {#-- Validate content is a list --#}\n {%- set content = message['content'] %}\n {%- if content is not iterable or content is string %}\n {{- raise_exception(\"The content must be a list\") }}\n {%- endif %}\n\n {#-- Collect content types --#}\n {%- set content_types = content | map(attribute='type') | list %}\n {%- set is_last = loop.last %}\n\n {#-- Last message validation --#}\n {%- if is_last %}\n {%- if 'text' not in content_types %}\n {{- raise_exception(\"The last message must include one item of type 'text'\") }}\n {%- elif (content_types | select('equalto', 'text') | list | length > 1) or (content_types | select('equalto', 'audio') | list | length > 1) %}\n {{- raise_exception(\"At most two items are allowed in the last message: one 'text' and one 'audio'\") }}\n {%- endif %}\n\n {#-- All other messages validation --#}\n {%- else %}\n {%- if content_types | select('equalto', 'text') | list | length != 1\n or content_types | select('equalto', 'audio') | list | length != 1 %}\n {{- raise_exception(\"Each message (except the last) must contain exactly one 'text' and one 'audio' item\") }}\n {%- elif content_types | reject('in', ['text', 'audio']) | list | length > 0 %}\n {{- raise_exception(\"Only 'text' and 'audio' types are allowed in content\") }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n\n{%- for message in messages %}\n {{- bos_token }}\n {{- '[' + message['role'] + ']' }}\n {{- message['content'][0]['text'] }}\n {{- eos_token }}\n {%- if message['content']|length > 1 %}\n {{- '<|AUDIO|><|audio_eos|>' }}\n {%- endif %}\n{%- endfor %}\n"} # fmt: skip @@ -62,7 +59,55 @@ def test_chat_template_is_saved(self): processor_dict = self.prepare_processor_dict() self.assertTrue(processor_loaded.chat_template == processor_dict.get("chat_template", None)) - @require_torch + @parameterized.expand( + [ + ("text",), + ("images",), + ("videos",), + ("audio",), + ] + ) + def test_subprocessor_defaults(self, modality): + # override - drop unused kwargs for `subprocessor` + + parameterized_config = MODALITY_TEST_SPECS[modality] + attributes = self.processor_class.get_attributes() + component_key = self.get_subprocessor_name(modality, attributes) + + if component_key not in attributes: + self.skipTest(f"{component_key} attribute not present in {self.processor_class}") + + subprocessor = self.get_component(component_key) + + # Get all other required components for processor + components = {} + for attribute in self.processor_class.get_attributes(): + components[attribute] = self.get_component(attribute) + + processor = self.processor_class(**components, **self.prepare_processor_dict()) + modality_input = self._prepare_modality_input(modality) + + # merge processor defaults when calling a subprocessor + kwargs = parameterized_config["call_time_kwargs"] + merged_kwargs = processor._merge_kwargs( + processor.valid_processor_kwargs, + tokenizer_init_kwargs=processor.tokenizer.init_kwargs if hasattr(processor, "tokenizer") else {}, + **kwargs, + ) + kwargs = merged_kwargs[f"{modality}_kwargs"] + kwargs.pop("encoded_length_kwargs", None) + + input_subproc = subprocessor(modality_input, **kwargs) + try: + input_processor = processor(**{modality: modality_input, **kwargs}) + except Exception: + input_processor = {} + + # Verify outputs match + for key in input_subproc: + if input_processor and key in processor.model_input_names: + torch.testing.assert_close(input_subproc[key], input_processor[key]) + def _test_apply_chat_template( self, modality: str, @@ -245,7 +290,6 @@ def test_apply_chat_template(self): ) torch.testing.assert_close(input_ids, expected_ids) - @require_torch @unittest.skip("CSM doesn't need assistant masks as an audio generation model") def test_apply_chat_template_assistant_mask(self): pass diff --git a/tests/models/deepseek_ocr2/test_processing_deepseek_ocr2.py b/tests/models/deepseek_ocr2/test_processing_deepseek_ocr2.py index dfb805d38e35..09ccdc346c22 100644 --- a/tests/models/deepseek_ocr2/test_processing_deepseek_ocr2.py +++ b/tests/models/deepseek_ocr2/test_processing_deepseek_ocr2.py @@ -42,10 +42,6 @@ def _setup_image_processor(cls): def _setup_test_attributes(cls, processor): cls.image_token = processor.image_token - @unittest.skip("DeepseekOcr2Processor pops the image processor output 'num_local_patches'") - def test_image_processor_defaults(self): - pass - def test_image_token_expansion_small_image(self): """Small image (< tile_size) should produce no local patches → 257 image tokens.""" processor = self.get_processor() diff --git a/tests/models/emu3/test_processing_emu3.py b/tests/models/emu3/test_processing_emu3.py index 0cbb2cf0a5e3..9bc91326a137 100644 --- a/tests/models/emu3/test_processing_emu3.py +++ b/tests/models/emu3/test_processing_emu3.py @@ -62,7 +62,7 @@ def test_processor_for_generation(self): # we don't need an image as input because the model will generate one input_str = "lower newer" - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor(text=input_str, return_for_image_generation=True, return_tensors="pt") self.assertListEqual(list(inputs.keys()), ["input_ids", "attention_mask", "image_sizes"]) self.assertEqual(inputs[self.text_input_name].shape[-1], 8) @@ -78,7 +78,7 @@ def test_processor_postprocess(self): processor = self.processor_class(**processor_components) input_str = "lower newer" - orig_image_input = self.prepare_image_inputs() + orig_image_input = self.prepare_images_inputs() orig_image = np.array(orig_image_input).transpose(2, 0, 1) inputs = processor(text=input_str, images=orig_image, do_resize=False, return_tensors="pt") @@ -102,7 +102,7 @@ def test_get_num_vision_tokens(self): self.assertEqual(len(output["num_image_patches"]), 3) @unittest.skip("Processor adds BOS manually to the input text") - def test_tokenizer_defaults(self): + def test_subprocessor_defaults_0_text(self): pass @parameterized.expand([(1, "pt"), (2, "pt")]) diff --git a/tests/models/ernie4_5_vl_moe/test_processing_ernie4_5_vl_moe.py b/tests/models/ernie4_5_vl_moe/test_processing_ernie4_5_vl_moe.py index 6f93c5ab40ef..3f75fb4a2873 100644 --- a/tests/models/ernie4_5_vl_moe/test_processing_ernie4_5_vl_moe.py +++ b/tests/models/ernie4_5_vl_moe/test_processing_ernie4_5_vl_moe.py @@ -12,15 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. -import inspect import unittest -import numpy as np import pytest from transformers import AutoProcessor, TokenizersBackend -from transformers.testing_utils import require_av, require_torch, require_torchvision, require_vision -from transformers.utils import is_torch_available, is_vision_available +from transformers.testing_utils import require_torch, require_torchvision, require_vision +from transformers.utils import is_vision_available from ...test_processing_common import ProcessorTesterMixin @@ -28,9 +26,6 @@ if is_vision_available(): from transformers import Ernie4_5_VLMoeImageProcessor, Ernie4_5_VLMoeProcessor -if is_torch_available(): - import torch - @require_vision @require_torch @@ -41,17 +36,19 @@ class Ernie4_5_VLMoeProcessorTest(ProcessorTesterMixin, unittest.TestCase): # Tiny processor created with make_tiny_processor.py from "hf-internal-testing/Ernie-VL-Moe-Small" tiny_model_id = "hf-internal-testing/tiny-processor-ernie4_5_vl_moe" - def get_tokenizer(self, **kwargs): - return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer - - def get_image_processor(self, **kwargs): - return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor - - def get_video_processor(self, **kwargs): - return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).video_processor - - def get_processor(self, **kwargs): - return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs) + @classmethod + def _setup_video_processor(cls): + component = AutoProcessor.from_pretrained(cls.tiny_model_id, min_frames=1).video_processor + return component + + @property + def video_sampling_expectations(self): + return [ + {"num_frames": None, "fps": 3, "expected_dim": 0, "output_length": 384}, + {"do_sample_frames": False, "fps": 10, "expected_dim": 0, "output_length": 2304}, + {"do_sample_frames": False, "expected_dim": 0, "output_length": 2304}, + {"expected_dim": 0, "output_length": 2304}, + ] # Copied from tests.models.llava.test_processing_llava.LlavaProcessorTest.test_get_num_vision_tokens def test_get_num_vision_tokens(self): @@ -67,9 +64,9 @@ def test_get_num_vision_tokens(self): self.assertEqual(len(output["num_image_patches"]), 3) def test_save_load_pretrained_default(self): - tokenizer = self.get_tokenizer() - image_processor = self.get_image_processor() - video_processor = self.get_video_processor() + tokenizer = self.get_component("tokenizer") + image_processor = self.get_component("image_processor") + video_processor = self.get_component("video_processor") processor = Ernie4_5_VLMoeProcessor( tokenizer=tokenizer, image_processor=image_processor, video_processor=video_processor @@ -83,15 +80,15 @@ def test_save_load_pretrained_default(self): self.assertIsInstance(processor.image_processor, Ernie4_5_VLMoeImageProcessor) def test_image_processor(self): - image_processor = self.get_image_processor() - tokenizer = self.get_tokenizer() - video_processor = self.get_video_processor() + image_processor = self.get_component("image_processor") + tokenizer = self.get_component("tokenizer") + video_processor = self.get_component("video_processor") processor = Ernie4_5_VLMoeProcessor( tokenizer=tokenizer, image_processor=image_processor, video_processor=video_processor ) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() input_image_proc = image_processor(image_input, return_tensors="pt") input_processor = processor(images=image_input, text="dummy", return_tensors="pt") @@ -100,16 +97,16 @@ def test_image_processor(self): self.assertAlmostEqual(input_image_proc[key].sum(), input_processor[key].sum(), delta=1e-2) def test_processor(self): - image_processor = self.get_image_processor() - tokenizer = self.get_tokenizer() - video_processor = self.get_video_processor() + image_processor = self.get_component("image_processor") + tokenizer = self.get_component("tokenizer") + video_processor = self.get_component("video_processor") processor = Ernie4_5_VLMoeProcessor( tokenizer=tokenizer, image_processor=image_processor, video_processor=video_processor ) input_str = "lower newer" - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor(text=input_str, images=image_input) self.assertListEqual( @@ -132,230 +129,11 @@ def test_processor(self): with pytest.raises(KeyError): processor(images=image_input) - @require_torch - @require_av - def _test_apply_chat_template( - self, - modality: str, - batch_size: int, - return_tensors: str, - input_name: str, - processor_name: str, - input_data: list[str], - ): - processor = self.get_processor() - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - - if processor_name not in self.processor_class.get_attributes(): - self.skipTest(f"{processor_name} attribute not present in {self.processor_class}") - - batch_messages = [ - [ - { - "role": "user", - "content": [{"type": "text", "text": "Describe this."}], - }, - ] - ] * batch_size - - # Test that jinja can be applied - formatted_prompt = processor.apply_chat_template(batch_messages, add_generation_prompt=True, tokenize=False) - self.assertEqual(len(formatted_prompt), batch_size) - - # Test that tokenizing with template and directly with `self.tokenizer` gives same output - formatted_prompt_tokenized = processor.apply_chat_template( - batch_messages, add_generation_prompt=True, tokenize=True, return_tensors=return_tensors - ) - add_special_tokens = True - if processor.tokenizer.bos_token is not None and formatted_prompt[0].startswith(processor.tokenizer.bos_token): - add_special_tokens = False - tok_output = processor.tokenizer( - formatted_prompt, return_tensors=return_tensors, add_special_tokens=add_special_tokens - ) - expected_output = tok_output.input_ids - self.assertListEqual(expected_output.tolist(), formatted_prompt_tokenized.tolist()) - - # Test that kwargs passed to processor's `__call__` are actually used - tokenized_prompt_100 = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - padding="max_length", - truncation=True, - return_tensors=return_tensors, - max_length=100, - ) - self.assertEqual(len(tokenized_prompt_100[0]), 100) - - # Test that `return_dict=True` returns text related inputs in the dict - out_dict_text = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - ) - self.assertTrue( - all( - key in out_dict_text - for key in ["input_ids", "attention_mask", "mm_token_type_ids", "moe_mm_token_type_ids"] - ) - ) - self.assertEqual(len(out_dict_text["input_ids"]), batch_size) - self.assertEqual(len(out_dict_text["attention_mask"]), batch_size) - self.assertEqual(len(out_dict_text["mm_token_type_ids"]), batch_size) - self.assertEqual(len(out_dict_text["moe_mm_token_type_ids"]), batch_size) - - # Test that with modality URLs and `return_dict=True`, we get modality inputs in the dict - for idx, url in enumerate(input_data[:batch_size]): - batch_messages[idx][0]["content"] = [batch_messages[idx][0]["content"][0], {"type": modality, "url": url}] - - out_dict = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - max_frames=2, # by default no more than 2 frames, otherwise too slow - ) - input_name = getattr(self, input_name) - self.assertTrue(input_name in out_dict) - self.assertEqual(len(out_dict["input_ids"]), batch_size) - self.assertEqual(len(out_dict["attention_mask"]), batch_size) - self.assertEqual(len(out_dict["mm_token_type_ids"]), batch_size) - self.assertEqual(len(out_dict["moe_mm_token_type_ids"]), batch_size) - - if modality == "video": - # qwen pixels don't scale with bs same way as other models, calculate expected video token count based on video_grid_thw - expected_video_token_count = 0 - for thw in out_dict["video_grid_thw"]: - expected_video_token_count += thw[0] * thw[1] * thw[2] - mm_len = expected_video_token_count - else: - # Calculate expected image token count based on image_grid_thw - expected_image_token_count = 0 - for thw in out_dict["image_grid_thw"]: - expected_image_token_count += thw[0] * thw[1] * thw[2] - mm_len = expected_image_token_count - self.assertEqual(len(out_dict[input_name]), mm_len) - - return_tensor_to_type = {"pt": torch.Tensor, "np": np.ndarray, None: list} - for k in out_dict: - self.assertIsInstance(out_dict[k], return_tensor_to_type[return_tensors]) - - @require_av - def test_apply_chat_template_video_frame_sampling(self): - processor = self.get_processor() - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - - signature = inspect.signature(processor.__call__) - if "videos" not in {*signature.parameters.keys()} or ( - signature.parameters.get("videos") is not None - and signature.parameters["videos"].annotation == inspect._empty - ): - self.skipTest("Processor doesn't accept videos at input") - - messages = [ - [ - { - "role": "user", - "content": [ - {"type": "video"}, - {"type": "text", "text": "What is shown in this video?"}, - ], - }, - ] - ] - - formatted_prompt = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) - self.assertEqual(len(formatted_prompt), 1) - - formatted_prompt_tokenized = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True) - expected_output = processor.tokenizer(formatted_prompt, return_tensors=None).input_ids - self.assertListEqual(expected_output, formatted_prompt_tokenized) - - out_dict = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True) - self.assertListEqual( - list(out_dict.keys()), ["input_ids", "attention_mask", "mm_token_type_ids", "moe_mm_token_type_ids"] - ) - - # Add video URL for return dict and load with `num_frames` arg - messages[0][0]["content"][0] = { - "type": "video", - "url": "https://huggingface.co/datasets/hf-internal-testing/test-videos/resolve/main/tiny_video_320x240.mp4", - } - num_frames = 3 - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - num_frames=num_frames, - min_frames=3, # default is 16 - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 768) - - # Load with `fps` arg - fps = 1 - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - fps=fps, - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 2304) - - # Load with `fps` and `num_frames` args, should raise an error - with self.assertRaises(ValueError): - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - fps=fps, - num_frames=num_frames, - ) - - # Load without any arg should load the whole video - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 2304) - - # Load video as a list of frames (i.e. images). NOTE: each frame should have same size - # because we assume they come from one video - messages[0][0]["content"][0] = { - "type": "video", - "url": [ - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg", - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg", - ], - } - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - do_sample_frames=False, - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 320) - def test_kwargs_overrides_custom_image_processor_kwargs(self): processor = self.get_processor() - self.skip_processor_without_typed_kwargs(processor) input_str = self.prepare_text_inputs() - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() size = {"shortest_edge": processor.image_processor.size["shortest_edge"], "longest_edge": 56 * 56 * 4} inputs = processor(text=input_str, images=image_input, size=size, return_tensors="pt") diff --git a/tests/models/evolla/test_processing_evolla.py b/tests/models/evolla/test_processing_evolla.py index 1f3ca2135da0..8f42938b1b93 100644 --- a/tests/models/evolla/test_processing_evolla.py +++ b/tests/models/evolla/test_processing_evolla.py @@ -43,6 +43,12 @@ class EvollaProcessorTest(ProcessorTesterMixin, unittest.TestCase): def test_processor_with_multiple_inputs(self): pass + def test_flat_kwarg_applied_when_modality_dict_lacks_it(self): + self.skipTest("EvollaProcessor requires `messages_list` and `proteins` inputs.") + + def maybe_skip_typed_test_for_modality(self, modality: str, attributes: list): + self.skipTest("EvollaProcessor requires `messages_list` and `proteins` inputs.") + def prepare_input_and_expected_output(self): amino_acid_sequence = "AAAA" foldseek_sequence = "dddd" diff --git a/tests/models/florence2/test_processing_florence2.py b/tests/models/florence2/test_processing_florence2.py index 0457de8d3a55..8aba8585fc5c 100644 --- a/tests/models/florence2/test_processing_florence2.py +++ b/tests/models/florence2/test_processing_florence2.py @@ -48,10 +48,6 @@ def _setup_test_attributes(cls, processor): # override: Florence shouldn't have any image-token in input text pass - @unittest.skip("Florence2Processor adds prefix and suffix tokens to the text") - def test_tokenizer_defaults(self): - pass - @staticmethod def prepare_processor_dict(): return { diff --git a/tests/models/fuyu/test_processing_fuyu.py b/tests/models/fuyu/test_processing_fuyu.py index a5161fd755ad..8ccec2bde669 100644 --- a/tests/models/fuyu/test_processing_fuyu.py +++ b/tests/models/fuyu/test_processing_fuyu.py @@ -24,7 +24,7 @@ from transformers.image_utils import load_image from transformers.testing_utils import require_torch, require_vision -from ...test_processing_common import ProcessorTesterMixin, url_to_local_path +from ...test_processing_common import MODALITY_TEST_SPECS, ProcessorTesterMixin, url_to_local_path if is_torch_available(): @@ -39,6 +39,11 @@ class FuyuProcessingTest(ProcessorTesterMixin, unittest.TestCase): # Fuyu uses a tokenizer with a very large vocabulary (~262K tokens), making tests slow and # memory-intensive. tiny_model_id points to a trimmed tokenizer repo to keep tests lightweight. tiny_model_id = "hf-internal-testing/tiny-processor-fuyu" + images_input_name = "image_patches" + + images_text_kwargs_max_length = 22 + images_text_kwargs_override_max_length = 22 + images_unstructured_max_length = 22 @classmethod def _setup_test_attributes(cls, processor): @@ -48,10 +53,6 @@ def _setup_test_attributes(cls, processor): ) cls.bus_image_pil = load_image(bus_image_url) - @unittest.skip("FuyuProcessor doesn't return typical pixel values for images") - def test_image_processor_defaults(self): - pass - @unittest.skip("FuyuProcessor doesn't return typical pixel values for images") def test_processor_with_multiple_inputs(self): pass @@ -135,159 +136,38 @@ def test_fuyu_processing_multiple_image_sample(self): self.assertTrue((processor_outputs["input_ids"] == expected_padded_unpacked_token_inputs).all()) # Rewrite as Fuyu supports tokenizer kwargs only when image is None. - @require_vision - @require_torch - def test_kwargs_overrides_default_tokenizer_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer", max_length=117) - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - # Fuyu uses tokenizer kwargs only when image is None. - image_input = None - - inputs = processor( - text=input_str, images=image_input, return_tensors="pt", max_length=112, padding="max_length" - ) - self.assertEqual(len(inputs["input_ids"][0]), 112) - - @unittest.skip("Fuyu processor does not support image_processor kwargs") - def test_image_processor_defaults_preserved_by_image_kwargs(self): - pass - - @unittest.skip("Fuyu processor does not support image_processor kwargs") - def test_kwargs_overrides_default_image_processor_kwargs(self): - pass - - # Rewrite as Fuyu supports tokenizer kwargs only when image is None. - @require_vision - @require_torch - def test_tokenizer_defaults_preserved_by_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer", max_length=117, padding="max_length") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - # Fuyu uses tokenizer kwargs only when image is None. - image_input = None - - inputs = processor(text=input_str, images=image_input, return_tensors="pt") - self.assertEqual(len(inputs["input_ids"][0]), 117) - - # Rewrite as Fuyu image processor does not return pixel values - @require_torch - @require_vision - def test_structured_kwargs_nested(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs() - # Fuyu uses tokenizer kwargs only when image is None. - image_input = None - - # Define the kwargs for each modality - all_kwargs = { - "common_kwargs": {"return_tensors": "pt"}, - "text_kwargs": {"padding": "max_length", "max_length": 76}, - } - - inputs = processor(text=input_str, images=image_input, **all_kwargs) - self.skip_processor_without_typed_kwargs(processor) - - self.assertEqual(len(inputs["input_ids"][0]), 76) - - # Rewrite as Fuyu image processor does not return pixel values - @require_torch - @require_vision - def test_structured_kwargs_nested_from_dict(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - # Fuyu uses tokenizer kwargs only when image is None. - image_input = None - - # Define the kwargs for each modality - all_kwargs = { - "common_kwargs": {"return_tensors": "pt"}, - "text_kwargs": {"padding": "max_length", "max_length": 76}, - } - - inputs = processor(text=input_str, images=image_input, **all_kwargs) - - self.assertEqual(len(inputs["input_ids"][0]), 76) - - # Rewrite as Fuyu supports tokenizer kwargs only when image is None. - @require_torch - @require_vision - def test_unstructured_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs() - # Fuyu uses tokenizer kwargs only when image is None. - image_input = None - inputs = processor( - text=input_str, - images=image_input, - return_tensors="pt", - padding="max_length", - max_length=76, - ) + def _test_unstructured_kwargs_batched(self, modality): + attributes = self.processor_class.get_attributes() + processor = self.get_processor() + self.maybe_skip_typed_test_for_modality(modality, attributes) - self.assertEqual(len(inputs["input_ids"][0]), 76) + input_str = self.prepare_text_inputs(batch_size=2, modalities="image") + modal_input = self._prepare_modality_input(modality, batch_size=2) + max_length = 76 # just hardcode + init_time_kwargs = MODALITY_TEST_SPECS[modality]["init_time_kwargs"] + call_kwargs = MODALITY_TEST_SPECS[modality]["call_time_kwargs"] - # Rewrite as Fuyu supports tokenizer kwargs only when image is None. - @require_torch - @require_vision - def test_unstructured_kwargs_batched(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor", use_tiny_ckpt=False) - tokenizer = self.get_component("tokenizer", use_tiny_ckpt=False) - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs(batch_size=2) - # Fuyu uses tokenizer kwargs only when image is None. - image_input = None inputs = processor( text=input_str, - images=image_input, - return_tensors="pt", + max_length=max_length, padding="longest", - max_length=76, + images=modal_input, + **call_kwargs, + **init_time_kwargs, ) - self.assertEqual(len(inputs["input_ids"][0]), 7) + self._check_modality_outputs(inputs, modality) + self.assertTrue( + len(inputs[self.text_input_name][0]) == len(inputs[self.text_input_name][1]) + and len(inputs[self.text_input_name][1]) < max_length + ) def test_processor_text_has_no_visual(self): # Overwritten: Fuyu has a complicated processing so we don't check id values processor = self.get_processor() text = self.prepare_text_inputs(batch_size=3, modalities="image") - image_inputs = self.prepare_image_inputs(batch_size=3) + image_inputs = self.prepare_images_inputs(batch_size=3) processing_kwargs = {"return_tensors": "pt", "padding": True, "multi_page": True} # Call with nested list of vision inputs diff --git a/tests/models/gemma3/test_processing_gemma3.py b/tests/models/gemma3/test_processing_gemma3.py index db3079161193..d45cca4657ec 100644 --- a/tests/models/gemma3/test_processing_gemma3.py +++ b/tests/models/gemma3/test_processing_gemma3.py @@ -28,6 +28,7 @@ @require_vision class Gemma3ProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = Gemma3Processor + model_id = "hf-internal-testing/tiny-gemma3" @classmethod def _setup_test_attributes(cls, processor): @@ -44,19 +45,6 @@ def _setup_image_processor(cls): } return image_processor_class(**gemma3_image_processor_kwargs) - @classmethod - def _setup_tokenizer(cls): - tokenizer_class = cls._get_component_class_from_processor("tokenizer") - extra_special_tokens = { - "image_token": "", - "boi_token": "", - "eoi_token": "", - } - tokenizer = tokenizer_class.from_pretrained( - SAMPLE_VOCAB, keep_accents=True, extra_special_tokens=extra_special_tokens - ) - return tokenizer - def test_get_num_vision_tokens(self): "Tests general functionality of the helper used internally in vLLM" @@ -76,9 +64,9 @@ def prepare_processor_dict(): } # fmt: skip # Override as Gemma3 needs images to be an explicitly nested batch - def prepare_image_inputs(self, batch_size: int | None = None): + def prepare_images_inputs(self, batch_size: int | None = None): """This function prepares a list of PIL images for testing""" - images = super().prepare_image_inputs(batch_size) + images = super().prepare_images_inputs(batch_size) if isinstance(images, (list, tuple)): images = [[image] for image in images] return images @@ -92,7 +80,7 @@ def test_text_with_image_tokens(self): text_single_image = f"{processor.boi_token}Dummy text!" text_no_image = "Dummy text!" - image = self.prepare_image_inputs() + image = self.prepare_images_inputs() # If text has no image tokens, image should be `None` with self.assertRaises(ValueError): @@ -117,7 +105,7 @@ def test_pan_and_scan(self): processor = self.processor_class(**processor_components, **processor_kwargs) input_str = self.prepare_text_inputs(modalities="image") - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor( text=input_str, images=image_input, @@ -145,7 +133,7 @@ def test_special_mm_token_truncation(self): processor = self.get_processor() input_str = self.prepare_text_inputs(batch_size=2, modalities="image") - image_input = self.prepare_image_inputs(batch_size=2) + image_input = self.prepare_images_inputs(batch_size=2) _ = processor( text=input_str, images=image_input, diff --git a/tests/models/gemma3n/test_feature_extraction_gemma3n.py b/tests/models/gemma3n/test_feature_extraction_gemma3n.py index 12512d0c081a..4581956c3350 100644 --- a/tests/models/gemma3n/test_feature_extraction_gemma3n.py +++ b/tests/models/gemma3n/test_feature_extraction_gemma3n.py @@ -27,15 +27,11 @@ check_json_file_has_correct_format, require_torch, ) -from transformers.utils.import_utils import is_torch_available from ...test_processing_common import floats_list from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin -if is_torch_available(): - pass - MAX_LENGTH_FOR_TESTING = 512 diff --git a/tests/models/gemma3n/test_processing_gemma3n.py b/tests/models/gemma3n/test_processing_gemma3n.py index 73119084a52d..b79a44f7dd79 100644 --- a/tests/models/gemma3n/test_processing_gemma3n.py +++ b/tests/models/gemma3n/test_processing_gemma3n.py @@ -36,8 +36,8 @@ class Gemma3nProcessorTest(ProcessorTesterMixin, unittest.TestCase): # Tiny processor created with make_tiny_processor.py from "hf-internal-testing/namespace-google-repo_name-gemma-3n-E4B-it" tiny_model_id = "hf-internal-testing/tiny-processor-gemma3n" - def prepare_image_inputs(self, batch_size: int | None = None, nested: bool = False): - return super().prepare_image_inputs(batch_size=batch_size, nested=True) + def prepare_images_inputs(self, batch_size: int | None = None, nested: bool = False): + return super().prepare_images_inputs(batch_size=batch_size, nested=True) @classmethod def _setup_test_attributes(cls, processor): diff --git a/tests/models/gemma4/test_processing_gemma4.py b/tests/models/gemma4/test_processing_gemma4.py index 7c42be086bc2..a5a1a56a3e53 100644 --- a/tests/models/gemma4/test_processing_gemma4.py +++ b/tests/models/gemma4/test_processing_gemma4.py @@ -33,9 +33,9 @@ @require_vision class Gemma4ProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = Gemma4Processor - video_unstructured_max_length = 570 - video_text_kwargs_max_length = 570 - video_text_kwargs_override_max_length = 570 + videos_unstructured_max_length = 570 + videos_text_kwargs_max_length = 570 + videos_text_kwargs_override_max_length = 570 @classmethod def _setup_test_attributes(cls, processor): @@ -87,6 +87,16 @@ def _setup_tokenizer(cls): tokenizer.pad_token_id = tokenizer.eos_token_id return tokenizer + @property + def video_sampling_expectations(self): + return [ + {"num_frames": 3, "fps": None, "expected_dim": 1, "output_length": 3}, + {"num_frames": None, "fps": 18, "expected_dim": 1, "output_length": 2}, + {"do_sample_frames": False, "fps": 2, "expected_dim": 1, "output_length": 11}, + {"do_sample_frames": False, "expected_dim": 1, "output_length": 11}, + {"expected_dim": 1, "output_length": 2}, + ] + # Copied from tests.models.llava.test_processing_llava.LlavaProcessorTest.test_get_num_vision_tokens def test_get_num_vision_tokens(self): "Tests general functionality of the helper used internally in vLLM" @@ -111,9 +121,9 @@ def prepare_processor_dict(): } # fmt: skip # Override as Gemma4 needs images to be an explicitly nested batch - def prepare_image_inputs(self, batch_size: int | None = None): + def prepare_images_inputs(self, batch_size: int | None = None): """This function prepares a list of PIL images for testing""" - images = super().prepare_image_inputs(batch_size) + images = super().prepare_images_inputs(batch_size) if isinstance(images, (list, tuple)): images = [[image] for image in images] return images @@ -133,7 +143,7 @@ def test_text_with_image_tokens(self): text_multi_images = f"{processor.image_token}{processor.image_token}Dummy text!" text_single_image = f"{processor.image_token}Dummy text!" - image = self.prepare_image_inputs() + image = self.prepare_images_inputs() # We can't be sure what is users intention: if user wants one image per text OR two images for first text and no image for second text with self.assertRaises(ValueError): @@ -154,7 +164,7 @@ def test_special_mm_token_truncation(self): processor = self.get_processor() input_str = self.prepare_text_inputs(batch_size=2, modalities="image") - image_input = self.prepare_image_inputs(batch_size=2) + image_input = self.prepare_images_inputs(batch_size=2) _ = processor( text=input_str, images=image_input, @@ -230,7 +240,3 @@ def test_get_num_audio_tokens(self): audio_lengths = list(expected_num_tokens) num_from_helper = processor._get_num_multimodal_tokens(audio_lengths=audio_lengths)["num_audio_tokens"] self.assertListEqual(num_from_helper, list(expected_num_tokens.values())) - - @unittest.skip("This test seems to be loading a different video, check for all models and fix") - def test_apply_chat_template_video_frame_sampling(self): - pass diff --git a/tests/models/gemma4_unified/test_processing_gemma4_unified.py b/tests/models/gemma4_unified/test_processing_gemma4_unified.py index 99575f7ff439..6a065ffaa589 100644 --- a/tests/models/gemma4_unified/test_processing_gemma4_unified.py +++ b/tests/models/gemma4_unified/test_processing_gemma4_unified.py @@ -33,9 +33,9 @@ @require_vision class Gemma4UnifiedProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = Gemma4UnifiedProcessor - video_unstructured_max_length = 570 - video_text_kwargs_max_length = 570 - video_text_kwargs_override_max_length = 570 + videos_unstructured_max_length = 570 + videos_text_kwargs_max_length = 570 + videos_text_kwargs_override_max_length = 570 @classmethod def _setup_test_attributes(cls, processor): @@ -86,6 +86,16 @@ def _setup_tokenizer(cls): tokenizer.pad_token_id = tokenizer.eos_token_id return tokenizer + @property + def video_sampling_expectations(self): + return [ + {"num_frames": 3, "fps": None, "expected_dim": 1, "output_length": 3}, + {"num_frames": None, "fps": 18, "expected_dim": 1, "output_length": 2}, + {"do_sample_frames": False, "fps": 2, "expected_dim": 1, "output_length": 11}, + {"do_sample_frames": False, "expected_dim": 1, "output_length": 11}, + {"expected_dim": 1, "output_length": 2}, + ] + # Copied from tests.models.llava.test_processing_llava.LlavaProcessorTest.test_get_num_vision_tokens def test_get_num_vision_tokens(self): "Tests general functionality of the helper used internally in vLLM" @@ -110,9 +120,9 @@ def prepare_processor_dict(): } # fmt: skip # Override as Gemma4Unified needs images to be an explicitly nested batch - def prepare_image_inputs(self, batch_size: int | None = None): + def prepare_images_inputs(self, batch_size: int | None = None): """This function prepares a list of PIL images for testing""" - images = super().prepare_image_inputs(batch_size) + images = super().prepare_images_inputs(batch_size) if isinstance(images, (list, tuple)): images = [[image] for image in images] return images @@ -132,7 +142,7 @@ def test_text_with_image_tokens(self): text_multi_images = f"{processor.image_token}{processor.image_token}Dummy text!" text_single_image = f"{processor.image_token}Dummy text!" - image = self.prepare_image_inputs() + image = self.prepare_images_inputs() # We can't be sure what is users intention: if user wants one image per text OR two images for first text and no image for second text with self.assertRaises(ValueError): @@ -153,7 +163,7 @@ def test_special_mm_token_truncation(self): processor = self.get_processor() input_str = self.prepare_text_inputs(batch_size=2, modalities="image") - image_input = self.prepare_image_inputs(batch_size=2) + image_input = self.prepare_images_inputs(batch_size=2) _ = processor( text=input_str, images=image_input, @@ -200,7 +210,3 @@ def test_get_num_multimodal_tokens_matches_processor_call(self): num_image_tokens_from_call = inputs.mm_token_type_ids.sum(-1).tolist() num_image_tokens_from_helper = processor._get_num_multimodal_tokens(image_sizes=image_sizes) self.assertListEqual(num_image_tokens_from_call, num_image_tokens_from_helper["num_image_tokens"]) - - @unittest.skip("This test seems to be loading a different video, check for all models and fix") - def test_apply_chat_template_video_frame_sampling(self): - pass diff --git a/tests/models/glm46v/test_processing_glm46v.py b/tests/models/glm46v/test_processing_glm46v.py index 94c7ccb8cf30..362a4a2f0163 100644 --- a/tests/models/glm46v/test_processing_glm46v.py +++ b/tests/models/glm46v/test_processing_glm46v.py @@ -12,23 +12,19 @@ # See the License for the specific language governing permissions and # limitations under the License. -import inspect import unittest -import numpy as np +from parameterized import parameterized -from transformers.testing_utils import require_av, require_torch, require_vision -from transformers.utils import is_torch_available, is_vision_available +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_vision_available -from ...test_processing_common import ProcessorTesterMixin, url_to_local_path +from ...test_processing_common import ProcessorTesterMixin if is_vision_available(): from transformers import Glm46VProcessor -if is_torch_available(): - import torch - @require_vision @require_torch @@ -51,207 +47,27 @@ def _setup_from_pretrained(cls, model_id, **kwargs): **kwargs, ) - @require_torch - @require_av - def _test_apply_chat_template( - self, - modality: str, - batch_size: int, - return_tensors: str, - input_name: str, - processor_name: str, - input_data: list[str], - ): - processor = self.get_processor() - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - - if processor_name not in self.processor_class.get_attributes(): - self.skipTest(f"{processor_name} attribute not present in {self.processor_class}") - - batch_messages = [ - [ - { - "role": "user", - "content": [{"type": "text", "text": "Describe this."}], - }, - ] - ] * batch_size - - # Test that jinja can be applied - formatted_prompt = processor.apply_chat_template(batch_messages, add_generation_prompt=True, tokenize=False) - self.assertEqual(len(formatted_prompt), batch_size) - - # Test that tokenizing with template and directly with `self.tokenizer` gives same output - formatted_prompt_tokenized = processor.apply_chat_template( - batch_messages, add_generation_prompt=True, tokenize=True, return_tensors=return_tensors - ) - add_special_tokens = True - if processor.tokenizer.bos_token is not None and formatted_prompt[0].startswith(processor.tokenizer.bos_token): - add_special_tokens = False - tok_output = processor.tokenizer( - formatted_prompt, return_tensors=return_tensors, add_special_tokens=add_special_tokens - ) - expected_output = tok_output.input_ids - self.assertListEqual(expected_output.tolist(), formatted_prompt_tokenized.tolist()) - - # Test that kwargs passed to processor's `__call__` are actually used - tokenized_prompt_100 = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - padding="max_length", - truncation=True, - return_tensors=return_tensors, - max_length=100, - ) - self.assertEqual(len(tokenized_prompt_100[0]), 100) - - # Test that `return_dict=True` returns text related inputs in the dict - out_dict_text = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - ) - self.assertTrue(all(key in out_dict_text for key in ["input_ids", "attention_mask"])) - self.assertEqual(len(out_dict_text["input_ids"]), batch_size) - self.assertEqual(len(out_dict_text["attention_mask"]), batch_size) - - # Test that with modality URLs and `return_dict=True`, we get modality inputs in the dict - for idx, url in enumerate(input_data[:batch_size]): - batch_messages[idx][0]["content"] = [batch_messages[idx][0]["content"][0], {"type": modality, "url": url}] - - out_dict = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - fps=2 - if isinstance(input_data[0], str) - else None, # by default no more than 2 frames per second, otherwise too slow - do_sample_frames=bool(isinstance(input_data[0], str)), # don't sample frames if decoded video is used - ) - input_name = getattr(self, input_name) - self.assertTrue(input_name in out_dict) - self.assertEqual(len(out_dict["input_ids"]), batch_size) - self.assertEqual(len(out_dict["attention_mask"]), batch_size) - - if modality == "video": - # qwen pixels don't scale with bs same way as other models, calculate expected video token count based on video_grid_thw - expected_video_token_count = 0 - for thw in out_dict["video_grid_thw"]: - expected_video_token_count += thw[0] * thw[1] * thw[2] - mm_len = expected_video_token_count - else: - mm_len = batch_size * 4 - self.assertEqual(len(out_dict[input_name]), mm_len) - - return_tensor_to_type = {"pt": torch.Tensor, "np": np.ndarray, None: list} - for k in out_dict: - self.assertIsInstance(out_dict[k], return_tensor_to_type[return_tensors]) - - @require_av - def test_apply_chat_template_video_frame_sampling(self): - processor = self.get_processor() - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - - signature = inspect.signature(processor.__call__) - if "videos" not in {*signature.parameters.keys()} or ( - signature.parameters.get("videos") is not None - and signature.parameters["videos"].annotation == inspect._empty - ): - self.skipTest("Processor doesn't accept videos at input") - - messages = [ - [ - { - "role": "user", - "content": [ - { - "type": "video", - "url": url_to_local_path( - "https://huggingface.co/datasets/hf-internal-testing/test-videos/resolve/main/tiny_video_320x240.mp4" - ), - }, - {"type": "text", "text": "What is shown in this video?"}, - ], - }, - ] + @property + def video_sampling_expectations(self): + return [ + {"num_frames": 3, "fps": None, "expected_dim": 0, "output_length": 4}, + {"num_frames": None, "fps": 16, "expected_dim": 0, "output_length": 12}, + {"do_sample_frames": False, "fps": 2, "expected_dim": 0, "output_length": 24}, + {"do_sample_frames": False, "expected_dim": 0, "output_length": 24}, ] - formatted_prompt = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) - self.assertEqual(len(formatted_prompt), 1) - - # Load with `video_fps` arg - video_fps = 10 - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - fps=video_fps, - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 8) - - # Load the whole video - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - do_sample_frames=False, - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 24) - - # Load video as a list of frames (i.e. images). NOTE: each frame should have same size - # because we assume they come from one video - messages[0][0]["content"][0] = { - "type": "video", - "url": [ - url_to_local_path( - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" - ), - url_to_local_path( - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" - ), - ], - } - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - do_sample_frames=False, - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 4) - - # When the inputs are frame URLs/paths we expect that those are already - # sampled and will raise an error is asked to sample again. - with self.assertRaisesRegex( - ValueError, "Sampling frames from a list of images is not supported! Set `do_sample_frames=False`" - ): - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - do_sample_frames=True, - ) - def test_model_input_names(self): processor = self.get_processor() text = self.prepare_text_inputs(modalities=["image", "video"]) - image_input = self.prepare_image_inputs() - video_inputs = self.prepare_video_inputs() + image_input = self.prepare_images_inputs() + video_inputs = self.prepare_videos_inputs() inputs_dict = {"text": text, "images": image_input, "videos": video_inputs} inputs = processor(**inputs_dict, return_tensors="pt", do_sample_frames=False) self.assertSetEqual(set(inputs.keys()), set(processor.model_input_names)) + + @parameterized.expand([(1, "pt")]) + @unittest.skip("Mode requires metadata to be always passed by users") + def test_apply_chat_template_decoded_video(self, batch_size: int, return_tensors: str): + pass diff --git a/tests/models/glm4v/test_processing_glm4v.py b/tests/models/glm4v/test_processing_glm4v.py index 530b8ae035e7..4cf019e958bc 100644 --- a/tests/models/glm4v/test_processing_glm4v.py +++ b/tests/models/glm4v/test_processing_glm4v.py @@ -14,20 +14,17 @@ import unittest -import numpy as np +from parameterized import parameterized -from transformers.testing_utils import require_av, require_torch, require_vision -from transformers.utils import is_torch_available, is_vision_available +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_vision_available -from ...test_processing_common import ProcessorTesterMixin, url_to_local_path +from ...test_processing_common import ProcessorTesterMixin if is_vision_available(): from transformers import Glm4vProcessor -if is_torch_available(): - import torch - @require_vision @require_torch @@ -41,206 +38,16 @@ class Glm4vProcessorTest(ProcessorTesterMixin, unittest.TestCase): def _setup_test_attributes(cls, processor): cls.image_token = processor.image_token - @require_torch - @require_av - def _test_apply_chat_template( - self, - modality: str, - batch_size: int, - return_tensors: str, - input_name: str, - processor_name: str, - input_data: list[str], - ): - processor = self.get_processor() - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - - if processor_name not in self.processor_class.get_attributes(): - self.skipTest(f"{processor_name} attribute not present in {self.processor_class}") - - batch_messages = [ - [ - { - "role": "user", - "content": [{"type": "text", "text": "Describe this."}], - }, - ] - ] * batch_size - - # Test that jinja can be applied - formatted_prompt = processor.apply_chat_template(batch_messages, add_generation_prompt=True, tokenize=False) - self.assertEqual(len(formatted_prompt), batch_size) - - # Test that tokenizing with template and directly with `self.tokenizer` gives same output - formatted_prompt_tokenized = processor.apply_chat_template( - batch_messages, add_generation_prompt=True, tokenize=True, return_tensors=return_tensors - ) - add_special_tokens = True - if processor.tokenizer.bos_token is not None and formatted_prompt[0].startswith(processor.tokenizer.bos_token): - add_special_tokens = False - tok_output = processor.tokenizer( - formatted_prompt, return_tensors=return_tensors, add_special_tokens=add_special_tokens - ) - expected_output = tok_output.input_ids - self.assertListEqual(expected_output.tolist(), formatted_prompt_tokenized.tolist()) - - # Test that kwargs passed to processor's `__call__` are actually used - tokenized_prompt_100 = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - padding="max_length", - truncation=True, - return_tensors=return_tensors, - max_length=100, - ) - self.assertEqual(len(tokenized_prompt_100[0]), 100) - - # Test that `return_dict=True` returns text related inputs in the dict - out_dict_text = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - ) - self.assertTrue(all(key in out_dict_text for key in ["input_ids", "attention_mask"])) - self.assertEqual(len(out_dict_text["input_ids"]), batch_size) - self.assertEqual(len(out_dict_text["attention_mask"]), batch_size) - - # Test that with modality URLs and `return_dict=True`, we get modality inputs in the dict - for idx, url in enumerate(input_data[:batch_size]): - batch_messages[idx][0]["content"] = [batch_messages[idx][0]["content"][0], {"type": modality, "url": url}] - - out_dict = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - fps=2 - if isinstance(input_data[0], str) - else None, # by default no more than 2 frames per second, otherwise too slow - do_sample_frames=bool(isinstance(input_data[0], str)), # don't sample frames if decoded video is used - ) - input_name = getattr(self, input_name) - self.assertTrue(input_name in out_dict) - self.assertEqual(len(out_dict["input_ids"]), batch_size) - self.assertEqual(len(out_dict["attention_mask"]), batch_size) - - if modality == "video": - # qwen pixels don't scale with bs same way as other models, calculate expected video token count based on video_grid_thw - expected_video_token_count = 0 - for thw in out_dict["video_grid_thw"]: - expected_video_token_count += thw[0] * thw[1] * thw[2] - mm_len = expected_video_token_count - else: - mm_len = batch_size * 4 - self.assertEqual(len(out_dict[input_name]), mm_len) - - return_tensor_to_type = {"pt": torch.Tensor, "np": np.ndarray, None: list} - for k in out_dict: - self.assertIsInstance(out_dict[k], return_tensor_to_type[return_tensors]) - - @require_av - def test_apply_chat_template_video_frame_sampling(self): - processor = self.get_processor() - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - - if "video_processor" not in self.processor_class.get_attributes(): - self.skipTest("Processor doesn't accept videos at input") - - messages = [ - [ - { - "role": "user", - "content": [ - {"type": "video"}, - {"type": "text", "text": "What is shown in this video?"}, - ], - }, - ] + @parameterized.expand([(1, "pt")]) + @unittest.skip("Mode requires metadata to be always passed by users") + def test_apply_chat_template_decoded_video(self, batch_size: int, return_tensors: str): + pass + + @property + def video_sampling_expectations(self): + return [ + {"num_frames": 3, "fps": None, "expected_dim": 0, "output_length": 4}, + {"num_frames": None, "fps": 3, "expected_dim": 0, "output_length": 4}, + {"do_sample_frames": False, "fps": 10, "expected_dim": 0, "output_length": 24}, + {"do_sample_frames": False, "expected_dim": 0, "output_length": 24}, ] - - formatted_prompt = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) - self.assertEqual(len(formatted_prompt), 1) - - # Add video URL for return dict and load with `num_frames` arg - messages[0][0]["content"][0] = { - "type": "video", - "url": url_to_local_path( - "https://huggingface.co/datasets/hf-internal-testing/test-videos/resolve/main/tiny_video_320x240.mp4" - ), - } - - # Load with `video_fps` arg - video_fps = 10 - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - fps=video_fps, - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 8) - - # Load the whole video - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - do_sample_frames=False, - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 24) - - # Load video as a list of frames (i.e. images). NOTE: each frame should have same size - # because we assume they come from one video - messages[0][0]["content"][0] = { - "type": "video", - "url": [ - url_to_local_path( - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" - ), - url_to_local_path( - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" - ), - ], - } - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - do_sample_frames=False, - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 4) - - # When the inputs are frame URLs/paths we expect that those are already - # sampled and will raise an error is asked to sample again. - with self.assertRaisesRegex( - ValueError, "Sampling frames from a list of images is not supported! Set `do_sample_frames=False`" - ): - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - do_sample_frames=True, - ) - - # def test_model_input_names(self): - # processor = self.get_processor() - - # text = self.prepare_text_inputs(modalities=["image", "video"]) - # image_input = self.prepare_image_inputs() - # video_inputs = self.prepare_video_inputs() - # inputs_dict = {"text": text, "images": image_input, "videos": video_inputs} - # inputs = processor(**inputs_dict, return_tensors="pt", do_sample_frames=False) - - # self.assertSetEqual(set(inputs.keys()), set(processor.model_input_names)) diff --git a/tests/models/glm_image/test_processing_glm_image.py b/tests/models/glm_image/test_processing_glm_image.py index 2cca925101b8..d314a1ab4e69 100644 --- a/tests/models/glm_image/test_processing_glm_image.py +++ b/tests/models/glm_image/test_processing_glm_image.py @@ -15,10 +15,11 @@ import unittest import numpy as np +from parameterized import parameterized from PIL import Image -from transformers.testing_utils import require_av, require_torch, require_vision -from transformers.utils import is_torch_available, is_vision_available +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_vision_available from ...test_processing_common import ProcessorTesterMixin @@ -26,9 +27,6 @@ if is_vision_available(): from transformers import GlmImageProcessor -if is_torch_available(): - import torch - @require_vision @require_torch @@ -41,7 +39,7 @@ class GlmImageProcessorTest(ProcessorTesterMixin, unittest.TestCase): def _setup_test_attributes(cls, processor): cls.image_token = processor.image_token - def prepare_image_inputs(self, batch_size: int | None = None, nested: bool = False): + def prepare_images_inputs(self, batch_size: int | None = None, nested: bool = False): """Override to create images with valid aspect ratio (< 4) for GLM-Image.""" # GLM-Image requires aspect ratio < 4, so use near-square images image_inputs = [Image.fromarray(np.random.randint(0, 255, (256, 256, 3), dtype=np.uint8))] @@ -51,121 +49,28 @@ def prepare_image_inputs(self, batch_size: int | None = None, nested: bool = Fal return [image_inputs] * batch_size return image_inputs * batch_size - @require_torch - @require_av - def _test_apply_chat_template( - self, - modality: str, - batch_size: int, - return_tensors: str, - input_name: str, - processor_name: str, - input_data: list[str], - ): - # Skip image modality tests for GLM-Image because the processor expands image tokens - # based on image size, making the tokenized output differ from direct tokenizer call - if modality == "image": - self.skipTest( - "GLM-Image processor expands image tokens based on image size, " - "making tokenized output differ from direct tokenizer call" - ) - - processor = self.get_processor() - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - - if processor_name not in self.processor_class.get_attributes(): - self.skipTest(f"{processor_name} attribute not present in {self.processor_class}") - - batch_messages = [ - [ - { - "role": "user", - "content": [{"type": "text", "text": "Describe this."}], - }, - ] - ] * batch_size - - # Test that jinja can be applied - formatted_prompt = processor.apply_chat_template(batch_messages, add_generation_prompt=True, tokenize=False) - self.assertEqual(len(formatted_prompt), batch_size) - - # Test that tokenizing with template and directly with `self.tokenizer` gives same output - formatted_prompt_tokenized = processor.apply_chat_template( - batch_messages, add_generation_prompt=True, tokenize=True, return_tensors=return_tensors - ) - add_special_tokens = True - if processor.tokenizer.bos_token is not None and formatted_prompt[0].startswith(processor.tokenizer.bos_token): - add_special_tokens = False - tok_output = processor.tokenizer( - formatted_prompt, return_tensors=return_tensors, add_special_tokens=add_special_tokens - ) - expected_output = tok_output.input_ids - self.assertListEqual(expected_output.tolist(), formatted_prompt_tokenized.tolist()) - - # Test that kwargs passed to processor's `__call__` are actually used - tokenized_prompt_100 = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - padding="max_length", - truncation=True, - return_tensors=return_tensors, - max_length=100, - ) - self.assertEqual(len(tokenized_prompt_100[0]), 100) - - # Test that `return_dict=True` returns text related inputs in the dict - out_dict_text = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - ) - self.assertTrue(all(key in out_dict_text for key in ["input_ids", "attention_mask"])) - self.assertEqual(len(out_dict_text["input_ids"]), batch_size) - self.assertEqual(len(out_dict_text["attention_mask"]), batch_size) - - # Test that with modality URLs and `return_dict=True`, we get modality inputs in the dict - for idx, url in enumerate(input_data[:batch_size]): - batch_messages[idx][0]["content"] = [batch_messages[idx][0]["content"][0], {"type": modality, "url": url}] - - out_dict = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - fps=2 - if isinstance(input_data[0], str) - else None, # by default no more than 2 frames per second, otherwise too slow - ) - input_name = getattr(self, input_name) - self.assertTrue(input_name in out_dict) - self.assertEqual(len(out_dict["input_ids"]), batch_size) - self.assertEqual(len(out_dict["attention_mask"]), batch_size) - - mm_len = batch_size * 4 - self.assertEqual(len(out_dict[input_name]), mm_len) - - return_tensor_to_type = {"pt": torch.Tensor, "np": np.ndarray, None: list} - for k in out_dict: - self.assertIsInstance(out_dict[k], return_tensor_to_type[return_tensors]) - def test_model_input_names(self): processor = self.get_processor() text = self.prepare_text_inputs(modalities=["image"]) - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs_dict = {"text": text, "images": image_input} inputs = processor(**inputs_dict, return_tensors="pt") self.assertSetEqual(set(inputs.keys()), set(processor.model_input_names)) - @unittest.skip( - "GlmImageProcessor injects additional special/control tokens around plain text inputs, so " - "`processor(text=X)` is not equivalent to `tokenizer(X)` for this model." + @unittest.skip("tiny model has too little tokens and collapses everything to UNK which is not defined") + def test_replacement_offsets(self): + pass + + @parameterized.expand( + [ + ("text",), + ("images",), + ("videos",), + ("audio",), + ] ) - def test_tokenizer_defaults(self): + @unittest.skip("Model changes input content as it is used by diffusers and thus is special") + def test_subprocessor_defaults(self, modality): pass diff --git a/tests/models/glmasr/test_processing_glmasr.py b/tests/models/glmasr/test_processing_glmasr.py index 95d1dba6e9d7..c5d069a87a32 100644 --- a/tests/models/glmasr/test_processing_glmasr.py +++ b/tests/models/glmasr/test_processing_glmasr.py @@ -34,6 +34,8 @@ class GlmAsrProcessorTest(ProcessorTesterMixin, unittest.TestCase): # Tiny processor created with make_tiny_processor.py from "zai-org/GLM-ASR-Nano-2512" tiny_model_id = "hf-internal-testing/tiny-processor-glmasr" + audio_unstructured_max_length = 201 + @classmethod @require_torch def setUpClass(cls): diff --git a/tests/models/got_ocr2/test_processing_got_ocr2.py b/tests/models/got_ocr2/test_processing_got_ocr2.py index f15037880f12..f46b719f2431 100644 --- a/tests/models/got_ocr2/test_processing_got_ocr2.py +++ b/tests/models/got_ocr2/test_processing_got_ocr2.py @@ -15,9 +15,13 @@ import unittest from transformers import GotOcr2Processor -from transformers.testing_utils import require_vision +from transformers.testing_utils import is_torch_available, require_vision -from ...test_processing_common import ProcessorTesterMixin +from ...test_processing_common import MODALITY_TEST_SPECS, ProcessorTesterMixin + + +if is_torch_available(): + import torch @require_vision @@ -25,9 +29,9 @@ class GotOcr2ProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = GotOcr2Processor # `num_image_tokens` is controlled via kwargs, tho overriding each testcase is overkill # just use higher `max_length` in tests - image_unstructured_max_length = 300 - image_text_kwargs_max_length = 300 - image_text_kwargs_override_max_length = 300 + images_unstructured_max_length = 300 + images_text_kwargs_max_length = 300 + images_text_kwargs_override_max_length = 300 # Tiny processor created with make_tiny_processor.py from "stepfun-ai/GOT-OCR-2.0-hf" tiny_model_id = "hf-internal-testing/tiny-processor-got_ocr2" @@ -38,13 +42,9 @@ def _setup_image_processor(cls): image_processor_class = cls._get_component_class_from_processor("image_processor") return image_processor_class() - @unittest.skip("GotOcr2Processor pop the image processor output 'num_patches'") - def test_image_processor_defaults(self): - pass - def test_ocr_queries(self): processor = self.get_processor() - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor(image_input, return_tensors="pt") self.assertEqual(inputs["input_ids"].shape, (1, 324)) self.assertEqual(inputs["pixel_values"].shape, (1, 3, 384, 384)) @@ -74,7 +74,7 @@ def test_processor_text_has_no_visual(self): processor = self.get_processor() text = self.prepare_text_inputs(batch_size=3, modalities="image") - image_inputs = self.prepare_image_inputs(batch_size=3) + image_inputs = self.prepare_images_inputs(batch_size=3) processing_kwargs = {"return_tensors": "pt", "padding": True, "multi_page": True} # Call with nested list of vision inputs @@ -92,3 +92,39 @@ def test_processor_text_has_no_visual(self): self.assertListEqual( inputs[self.text_input_name][1:].tolist(), inputs_nested[self.text_input_name][1:].tolist() ) + + def test_subprocessor_defaults_1_images(self): + # overriden - pop certina keys from `merged_kwargs` which are used only by processor + parameterized_config = MODALITY_TEST_SPECS["images"] + subprocessor = self.get_component(parameterized_config["component_key"]) + + # Get all other required components for processor + components = {} + for attribute in self.processor_class.get_attributes(): + components[attribute] = self.get_component(attribute) + + processor = self.processor_class(**components, **self.prepare_processor_dict()) + modality_input = self._prepare_modality_input("images") + + # merge processor defaults when calling a subprocessor + kwargs = parameterized_config["call_time_kwargs"] + kwargs["return_tensors"] = "pt" + merged_kwargs = processor._merge_kwargs( + processor.valid_processor_kwargs, + tokenizer_init_kwargs=None, + **kwargs, + ) + kwargs = merged_kwargs["images_kwargs"] + kwargs.pop("num_image_tokens") + kwargs.pop("multi_page") + + input_subproc = subprocessor(modality_input, **kwargs) + try: + input_processor = processor(images=modality_input, **kwargs) + except Exception: + input_processor = {} + + # Verify outputs match + for key in input_subproc: + if input_processor and key in processor.model_input_names: + torch.testing.assert_close(input_subproc[key], input_processor[key]) diff --git a/tests/models/granite4_vision/test_processing_granite4_vision.py b/tests/models/granite4_vision/test_processing_granite4_vision.py index 810c16fb50e1..96dc6803aac4 100644 --- a/tests/models/granite4_vision/test_processing_granite4_vision.py +++ b/tests/models/granite4_vision/test_processing_granite4_vision.py @@ -29,9 +29,9 @@ class Granite4VisionProcessorTest(ProcessorTesterMixin, unittest.TestCase): # Tiny processor created with make_tiny_processor.py from "ibm-granite/granite-vision-4.1-4b" tiny_model_id = "hf-internal-testing/tiny-processor-granite4_vision" # Image token expansion with downsample_rate="1/2" produces more tokens than the defaults - image_text_kwargs_max_length = 300 - image_text_kwargs_override_max_length = 280 - image_unstructured_max_length = 260 + images_text_kwargs_max_length = 300 + images_text_kwargs_override_max_length = 280 + images_unstructured_max_length = 260 @classmethod def _setup_image_processor(cls): diff --git a/tests/models/granite_speech5/test_processing_granite_speech5.py b/tests/models/granite_speech5/test_processing_granite_speech5.py index 39f11fc91280..e7bc4a9f8f67 100644 --- a/tests/models/granite_speech5/test_processing_granite_speech5.py +++ b/tests/models/granite_speech5/test_processing_granite_speech5.py @@ -26,6 +26,9 @@ class GraniteSpeech5ProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = GraniteSpeech5Processor text_input_name = "labels" + audio_text_kwargs_max_length = 1001 + audio_unstructured_max_length = 1001 + @classmethod def _setup_tokenizer(cls): from tokenizers import Tokenizer diff --git a/tests/models/grounding_dino/test_processing_grounding_dino.py b/tests/models/grounding_dino/test_processing_grounding_dino.py index f8c60bb345d1..bf5bc70f869b 100644 --- a/tests/models/grounding_dino/test_processing_grounding_dino.py +++ b/tests/models/grounding_dino/test_processing_grounding_dino.py @@ -63,10 +63,6 @@ def _setup_tokenizer(cls): vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) return tokenizer_class.from_pretrained(cls.tmpdirname) - @unittest.skip("GroundingDinoProcessor merges candidate labels text") - def test_tokenizer_defaults(self): - pass - def prepare_text_inputs(self, batch_size: int | None = None, **kwargs): labels = ["a cat", "remote control"] labels_longer = ["a person", "a car", "a dog", "a cat"] @@ -139,7 +135,7 @@ def test_processor_text_has_no_visual(self): processor = self.get_processor() text = self.prepare_text_inputs(batch_size=3, modalities="image") - image_inputs = self.prepare_image_inputs(batch_size=3) + image_inputs = self.prepare_images_inputs(batch_size=3) processing_kwargs = {"return_tensors": "pt", "padding": True} # Call with nested list of vision inputs @@ -160,3 +156,7 @@ def test_processor_text_has_no_visual(self): self.assertListEqual( inputs[self.text_input_name][1:].tolist(), inputs_nested[self.text_input_name][1:].tolist() ) + + @unittest.skip("Processor changes input text by adding dots before anf after") + def test_subprocessor_defaults_0_text(self): + pass diff --git a/tests/models/hunyuan_vl/test_processing_hunyuan_vl.py b/tests/models/hunyuan_vl/test_processing_hunyuan_vl.py index 0eb67a144cd5..d3ea810afddd 100644 --- a/tests/models/hunyuan_vl/test_processing_hunyuan_vl.py +++ b/tests/models/hunyuan_vl/test_processing_hunyuan_vl.py @@ -16,10 +16,8 @@ import numpy as np -from transformers import PreTrainedTokenizerFast from transformers.testing_utils import require_tokenizers, require_torch, require_torchvision, require_vision from transformers.utils import ( - is_tokenizers_available, is_torch_available, is_torchvision_available, is_vision_available, @@ -31,11 +29,6 @@ if is_torch_available(): import torch -if is_tokenizers_available(): - from tokenizers import Tokenizer - from tokenizers.models import WordLevel - from tokenizers.pre_tokenizers import Whitespace - if is_vision_available(): from PIL import Image @@ -51,6 +44,7 @@ @require_tokenizers class HunYuanVLProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = HunYuanVLProcessor + model_id = "tencent/HunyuanOCR" @classmethod def _setup_test_attributes(cls, processor): @@ -63,8 +57,11 @@ def prepare_text_inputs(self, batch_size: int | None = None, modalities: str | l modalities = [modalities] special_token_to_add = "" - if modalities is not None and "image" in modalities: - special_token_to_add += f"{self.image_start_token}{self.image_token}{self.image_end_token}" + if modalities is not None: + for modality in modalities: + # we hae non-uniform naming conventions for image/videos + if modality in ["images", "image"]: + special_token_to_add += f"{self.image_start_token}{self.image_token}{self.image_end_token}" if batch_size is None: return f"lower newer {special_token_to_add}" @@ -78,53 +75,6 @@ def prepare_text_inputs(self, batch_size: int | None = None, modalities: str | l f"lower newer {special_token_to_add}" ] * (batch_size - 2) - @classmethod - def _setup_tokenizer(cls): - vocab = { - "": 0, - "": 1, - "": 2, - "": 3, - "": 4, - "": 5, - "": 6, - "hello": 7, - "": 8, - "": 9, - "lower": 10, - "newer": 11, - "upper": 12, - "older": 13, - "longer": 14, - "string": 15, - "Describe": 16, - "this.": 17, - } - tokenizer = Tokenizer(WordLevel(vocab=vocab, unk_token="")) - tokenizer.pre_tokenizer = Whitespace() - fast_tokenizer = PreTrainedTokenizerFast( - tokenizer_object=tokenizer, - unk_token="", - pad_token="", - bos_token="", - eos_token="", - extra_special_tokens={ - "image_start_token": "", - "image_token": "", - "image_end_token": "", - }, - ) - fast_tokenizer.chat_template = ( - "{% for message in messages %}" - "{% for content in message['content'] %}" - "{% if content['type'] == 'image' %}" - "{% elif content['type'] == 'text' %}{{ content['text'] }}" - "{% endif %}" - "{% endfor %}" - "{% endfor %}" - ) - return fast_tokenizer - @classmethod def _setup_image_processor(cls): return HunYuanVLImageProcessor( @@ -140,7 +90,10 @@ def test_processor_outputs_image_only_inputs(self): image = Image.new("RGB", (32, 32), color="white") inputs = processor( - text=[" hello"], images=[image], padding=True, return_tensors="pt" + text=[f"{processor.image_start_token}{self.image_token}{processor.image_end_token} hello"], + images=[image], + padding=True, + return_tensors="pt", ) self.assertSetEqual( @@ -163,7 +116,10 @@ def test_processor_uses_named_special_token_ids(self): image = Image.new("RGB", (32, 32), color="white") inputs = processor( - text=[" hello"], images=[image], padding=True, return_tensors="pt" + text=[f"{processor.image_start_token}{self.image_token}{processor.image_end_token} hello"], + images=[image], + padding=True, + return_tensors="pt", ) input_ids = inputs["input_ids"][0].tolist() @@ -177,7 +133,7 @@ def test_processor_rejects_bare_image_tokens(self): processor = self.get_processor() image = Image.new("RGB", (32, 32), color="white") - with self.assertRaisesRegex(ValueError, "image placeholders must be formatted"): + with self.assertRaisesRegex(ValueError, r"tokens in text \(0\) does not match the number of images"): processor(text=[" hello"], images=[image], padding=True, return_tensors="pt") def test_apply_chat_template_keeps_wrapped_image_tokens_single_wrapped(self): diff --git a/tests/models/idefics/test_processing_idefics.py b/tests/models/idefics/test_processing_idefics.py index f49942a4a4d8..c988dbdb7c3a 100644 --- a/tests/models/idefics/test_processing_idefics.py +++ b/tests/models/idefics/test_processing_idefics.py @@ -20,14 +20,11 @@ IdeficsProcessor, ) from transformers.testing_utils import require_torch, require_vision -from transformers.utils import is_torch_available, is_vision_available +from transformers.utils import is_vision_available from ...test_processing_common import ProcessorTesterMixin -if is_torch_available(): - pass - if is_vision_available(): from PIL import Image @@ -156,18 +153,6 @@ def test_tokenizer_left_padding(self): self.assertListEqual(max_length["attention_mask"][-1].tolist(), predicted_attention_masks[1]) self.assertListEqual(longest["attention_mask"][-1].tolist(), predicted_attention_masks[0]) - def test_tokenizer_defaults(self): - # Override to account for the processor prefixing the BOS token to prompts. - components = {attribute: self.get_component(attribute) for attribute in self.processor_class.get_attributes()} - processor = self.processor_class(**components) - tokenizer = components["tokenizer"] - - input_str = ["lower newer"] - encoded_processor = processor(text=input_str, padding=False, return_tensors="pt") - encoded_tok = tokenizer( - [f"{tokenizer.bos_token}{input_str[0]}"], padding=False, add_special_tokens=False, return_tensors="pt" - ) - - for key in encoded_tok: - if key in encoded_processor: - self.assertListEqual(encoded_tok[key].tolist(), encoded_processor[key].tolist()) + @unittest.skip("processor artifically adds BOS token to text") + def test_subprocessor_defaults_0_text(self): + pass diff --git a/tests/models/idefics3/test_processing_idefics3.py b/tests/models/idefics3/test_processing_idefics3.py index cbef4fb7fa55..8271bbb1ebea 100644 --- a/tests/models/idefics3/test_processing_idefics3.py +++ b/tests/models/idefics3/test_processing_idefics3.py @@ -29,13 +29,15 @@ class Idefics3ProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = Idefics3Processor # Tiny processor created with make_tiny_processor.py from "HuggingFaceM4/Idefics3-8B-Llama3" tiny_model_id = "hf-internal-testing/tiny-processor-idefics3" + model_id = "HuggingFaceM4/Idefics3-8B-Llama3" # Default 76 is too small: idefics3 with the tiny tokenizer expands to ~78 tokens, then with # surrounding text tokens we exceed 76, truncation cuts through image tokens, and _check_special_mm_tokens # raises a mismatch error. - image_unstructured_max_length = 100 + images_unstructured_max_length = 100 - def get_processor(self): - processor = self.processor_class.from_pretrained(self.tmpdirname) + def get_processor(self, use_tiny_ckpt: bool = True): + load_dir = self.model_id if not use_tiny_ckpt else self.tmpdirname + processor = self.processor_class.from_pretrained(load_dir) processor.tokenizer.add_bos_token = True processor.tokenizer.add_eos_token = False return processor diff --git a/tests/models/inkling/test_processing_inkling.py b/tests/models/inkling/test_processing_inkling.py index 866600b2cfd3..10bfbc031159 100644 --- a/tests/models/inkling/test_processing_inkling.py +++ b/tests/models/inkling/test_processing_inkling.py @@ -98,9 +98,9 @@ def prepare_processor_dict(): } # fmt: skip # Override as Inkling needs images to be an explicitly nested batch - def prepare_image_inputs(self, batch_size: int | None = None): + def prepare_images_inputs(self, batch_size: int | None = None): """This function prepares a list of PIL images for testing""" - images = super().prepare_image_inputs(batch_size) + images = super().prepare_images_inputs(batch_size) if isinstance(images, (list, tuple)): images = [[image] for image in images] return images @@ -111,7 +111,7 @@ def test_special_mm_token_truncation(self): processor = self.get_processor() input_str = self.prepare_text_inputs(batch_size=2, modalities="image") - image_input = self.prepare_image_inputs(batch_size=2) + image_input = self.prepare_images_inputs(batch_size=2) _ = processor( text=input_str, images=image_input, @@ -188,10 +188,6 @@ def test_get_num_audio_tokens(self): num_from_helper = processor._get_num_multimodal_tokens(audio_lengths=audio_lengths)["num_audio_tokens"] self.assertListEqual(num_from_helper, list(expected_num_tokens.values())) - @unittest.skip("This test seems to be loading a different video, check for all models and fix") - def test_apply_chat_template_video_frame_sampling(self): - pass - @require_librosa @parameterized.expand([(1, "np"), (1, "pt"), (2, "np"), (2, "pt")]) def test_apply_chat_template_audio(self, batch_size: int, return_tensors: str): @@ -201,19 +197,118 @@ def test_apply_chat_template_audio(self, batch_size: int, return_tensors: str): "audio", batch_size, return_tensors, "audio_input_name", "feature_extractor", MODALITY_INPUT_DATA["audio"] ) - @parameterized.expand([(1, "np"), (1, "pt"), (2, "np"), (2, "pt")]) - @unittest.skip("Inkling packs image patches across the batch instead of keeping one tensor per image") - def test_apply_chat_template_image(self, batch_size: int, return_tensors: str): - pass - - @unittest.skip("Inkling quantizes input features into discrete audio input IDs") - def test_feature_extractor_defaults(self): - pass - @unittest.skip("The test fixture passes image_seq_length, which is not an InklingProcessor attribute") def test_processor_to_json_string(self): pass + def _test_apply_chat_template( + self, + modality: str, + batch_size: int, + return_tensors: str, + input_name: str, + processor_name: str, + input_data: list[str], + ): + processor = self.get_processor() + if processor.chat_template is None: + self.skipTest("Processor has no chat template") + + if processor_name not in self.processor_class.get_attributes(): + self.skipTest(f"{processor_name} attribute not present in {self.processor_class}") + + # some models have only Fast image processor + if getattr(processor, processor_name).__class__.__name__.endswith("Fast"): + return_tensors = "pt" + + batch_messages = [ + [ + {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]}, + {"role": "user", "content": [{"type": "text", "text": "Describe this."}]}, + ] + ] * batch_size + + # Test that jinja can be applied + formatted_prompt = processor.apply_chat_template(batch_messages, add_generation_prompt=True, tokenize=False) + self.assertEqual(len(formatted_prompt), batch_size) + + # Test that tokenizing with template and directly with `self.tokenizer` gives same output + formatted_prompt_tokenized = processor.apply_chat_template( + batch_messages, add_generation_prompt=True, tokenize=True, return_tensors=return_tensors + ) + add_special_tokens = True + if processor.tokenizer.bos_token is not None and formatted_prompt[0].startswith(processor.tokenizer.bos_token): + add_special_tokens = False + tok_output = processor.tokenizer( + formatted_prompt, return_tensors=return_tensors, add_special_tokens=add_special_tokens + ) + expected_output = tok_output.input_ids + self.assertListEqual(expected_output.tolist(), formatted_prompt_tokenized.tolist()) + + # Test that kwargs passed to processor's `__call__` are actually used + tokenized_prompt_100 = processor.apply_chat_template( + batch_messages, + add_generation_prompt=True, + tokenize=True, + return_tensors=return_tensors, + processor_kwargs={ + "padding": "max_length", + "truncation": True, + "max_length": self.chat_template_max_length, + }, + ) + self.assertEqual(len(tokenized_prompt_100[0]), self.chat_template_max_length) + + # Test that `return_dict=True` returns text related inputs in the dict + out_dict_text = processor.apply_chat_template( + batch_messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors=return_tensors, + ) + self.assertTrue(all(key in out_dict_text for key in ["input_ids", "attention_mask"])) + self.assertEqual(len(out_dict_text["input_ids"]), batch_size) + self.assertEqual(len(out_dict_text["attention_mask"]), batch_size) + + # Test that with modality URLs and `return_dict=True`, we get modality inputs in the dict + for idx, url in enumerate(input_data[:batch_size]): + batch_messages[idx][1]["content"] = [batch_messages[idx][1]["content"][0], {"type": modality, "url": url}] + + out_dict = processor.apply_chat_template( + batch_messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors=return_tensors, + processor_kwargs={"num_frames": 2, "fps": None}, # no more than 2 frames, otherwise too slow + ) + input_name = getattr(self, input_name) + self.assertTrue(input_name in out_dict) + self.assertEqual(len(out_dict["input_ids"]), batch_size) + self.assertEqual(len(out_dict["attention_mask"]), batch_size) + + if modality == "image": + mm_len = 204 * batch_size # hardcode, the model uses patches as input + else: + mm_len = batch_size + self.assertEqual(len(out_dict[input_name]), mm_len) + + return_tensor_to_type = {"pt": torch.Tensor, "np": np.ndarray, None: list} + for k in out_dict: + self.assertIsInstance(out_dict[k], return_tensor_to_type[return_tensors]) + + # Test continue from final message + assistant_message = { + "role": "assistant", + "content": [{"type": "text", "text": "It is the sound of"}], + } + for idx, url in enumerate(input_data[:batch_size]): + batch_messages[idx] = batch_messages[idx] + [assistant_message] + continue_prompt = processor.apply_chat_template(batch_messages, continue_final_message=True, tokenize=False) + for prompt in continue_prompt: + self.assertTrue(prompt.endswith("It is the sound of")) # no `eos` token at the end + @slow @require_torch_accelerator diff --git a/tests/models/instructblip/test_processing_instructblip.py b/tests/models/instructblip/test_processing_instructblip.py index ba5c13e24545..9d7566e97e7d 100644 --- a/tests/models/instructblip/test_processing_instructblip.py +++ b/tests/models/instructblip/test_processing_instructblip.py @@ -32,7 +32,9 @@ class InstructBlipProcessorTest(ProcessorTesterMixin, unittest.TestCase): @classmethod def _setup_tokenizer(cls): tokenizer_class = cls._get_component_class_from_processor("tokenizer") - return tokenizer_class.from_pretrained("hf-internal-testing/tiny-random-GPT2Model") + tokenizer = tokenizer_class.from_pretrained("hf-internal-testing/tiny-random-GPT2Model") + tokenizer.pad_token_id = tokenizer.eos_token_id + return tokenizer @classmethod def _setup_qformer_tokenizer(cls): diff --git a/tests/models/instructblipvideo/test_processing_instructblipvideo.py b/tests/models/instructblipvideo/test_processing_instructblipvideo.py index 88f2d1d2501d..5f4d514b7bab 100644 --- a/tests/models/instructblipvideo/test_processing_instructblipvideo.py +++ b/tests/models/instructblipvideo/test_processing_instructblipvideo.py @@ -14,18 +14,13 @@ import unittest from transformers.testing_utils import require_torch, require_vision -from transformers.utils import is_torchvision_available, is_vision_available +from transformers.utils import is_vision_available from ...test_processing_common import ProcessorTesterMixin if is_vision_available(): - from transformers import ( - InstructBlipVideoProcessor, - ) - - if is_torchvision_available(): - pass + from transformers import InstructBlipVideoProcessor @require_vision diff --git a/tests/models/internvl/test_processing_internvl.py b/tests/models/internvl/test_processing_internvl.py index 474eed76b53e..3c7838a5a7b9 100644 --- a/tests/models/internvl/test_processing_internvl.py +++ b/tests/models/internvl/test_processing_internvl.py @@ -12,13 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. -import inspect import unittest from parameterized import parameterized from transformers import InternVLProcessor -from transformers.testing_utils import require_av, require_torch, require_vision +from transformers.testing_utils import require_torch, require_torchcodec, require_vision from transformers.utils import is_torch_available from ...test_processing_common import ProcessorTesterMixin, url_to_local_path @@ -64,14 +63,20 @@ def _setup_video_processor(cls): do_convert_rgb=True, ) - @unittest.skip("InternVL requires text") - def test_video_processor_defaults(self): - pass - @staticmethod def prepare_processor_dict(): return {"image_seq_length": 2} + @property + def video_sampling_expectations(self): + return [ + {"num_frames": 3, "fps": None, "expected_dim": 0, "output_length": 3}, + {"num_frames": None, "fps": 16, "expected_dim": 0, "output_length": 5}, + {"do_sample_frames": False, "fps": 2, "expected_dim": 0, "output_length": 11}, + {"do_sample_frames": False, "expected_dim": 0, "output_length": 11}, + {"expected_dim": 0, "output_length": 11}, + ] + # Copied from tests.models.llava.test_processing_llava.LlavaProcessorTest.test_get_num_vision_tokens def test_get_num_vision_tokens(self): "Tests general functionality of the helper used internally in vLLM" @@ -85,7 +90,7 @@ def test_get_num_vision_tokens(self): self.assertTrue("num_image_patches" in output) self.assertEqual(len(output["num_image_patches"]), 3) - @require_av + @require_torchcodec @require_torch def test_process_interleaved_images_videos(self): processor = self.get_processor() @@ -175,86 +180,6 @@ def test_process_interleaved_images_videos(self): ) images_patches_index += inputs["pixel_values"].shape[0] - @require_torch - @require_av - def test_apply_chat_template_video_frame_sampling(self): - processor = self.get_processor() - - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - - signature = inspect.signature(processor.__call__) - if "videos" not in {*signature.parameters.keys()} or ( - signature.parameters.get("videos") is not None - and signature.parameters["videos"].annotation == inspect._empty - ): - self.skipTest("Processor doesn't accept videos at input") - - messages = [ - [ - { - "role": "user", - "content": [ - { - "type": "video", - "url": url_to_local_path( - "https://huggingface.co/datasets/hf-internal-testing/test-videos/resolve/main/tiny_video_320x240.mp4" - ), - }, - {"type": "text", "text": "What is shown in this video?"}, - ], - }, - ] - ] - - num_frames = 3 - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - num_frames=num_frames, - return_tensors="pt", - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), num_frames) - - # Load with `fps` arg is not possible with InternVL (skip) - - # Load without any arg should use the default loading method - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors="pt", - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 11) - - # Load video as a list of frames (i.e. images). NOTE: each frame should have same size - # because we assume they come from one video - messages[0][0]["content"][0] = { - "type": "video", - "url": [ - url_to_local_path( - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" - ), - url_to_local_path( - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" - ), - ], - } - out_dict_with_video = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors="pt", - ) - self.assertTrue(self.videos_input_name in out_dict_with_video) - self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 2) - @require_torch def _test_apply_chat_template( self, diff --git a/tests/models/janus/test_processing_janus.py b/tests/models/janus/test_processing_janus.py index a8eef34b155f..b78b31a0121f 100644 --- a/tests/models/janus/test_processing_janus.py +++ b/tests/models/janus/test_processing_janus.py @@ -420,7 +420,7 @@ def test_processor_postprocess(self): processor = self.processor_class(**processor_components) input_str = "lower newer" - orig_image_input = self.prepare_image_inputs() + orig_image_input = self.prepare_images_inputs() orig_image = np.array(orig_image_input).transpose(2, 0, 1) inputs = processor(text=input_str, images=orig_image, do_resize=False, do_pad=False, return_tensors="pt") diff --git a/tests/models/kimi_k25/test_processing_kimi_k25.py b/tests/models/kimi_k25/test_processing_kimi_k25.py index a35c03504005..5830b30c4d58 100644 --- a/tests/models/kimi_k25/test_processing_kimi_k25.py +++ b/tests/models/kimi_k25/test_processing_kimi_k25.py @@ -12,24 +12,19 @@ # See the License for the specific language governing permissions and # limitations under the License. -import inspect import unittest -import numpy as np from parameterized import parameterized -from transformers.testing_utils import require_av, require_torch, require_torchvision, require_vision -from transformers.utils import is_torch_available, is_vision_available +from transformers.testing_utils import require_torch, require_torchvision, require_vision +from transformers.utils import is_vision_available -from ...test_processing_common import ProcessorTesterMixin, url_to_local_path +from ...test_processing_common import ProcessorTesterMixin if is_vision_available(): from transformers import Kimi_K25Processor -if is_torch_available(): - import torch - @require_vision @require_torch @@ -69,187 +64,20 @@ def _setup_test_attributes(cls, processor): cls.image_token = processor.image_token cls.video_token = processor.video_token - @require_torch - @require_av - def _test_apply_chat_template( - self, - modality: str, - batch_size: int, - return_tensors: str, - input_name: str, - processor_name: str, - input_data: list[str], - ): - processor = self.get_processor() - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - - if processor_name not in self.processor_class.get_attributes(): - self.skipTest(f"{processor_name} attribute not present in {self.processor_class}") - - batch_messages = [ - [ - { - "role": "user", - "content": [{"type": "text", "text": "Describe this."}], - }, - ] - ] * batch_size - - # Test that jinja can be applied - formatted_prompt = processor.apply_chat_template(batch_messages, add_generation_prompt=True, tokenize=False) - self.assertEqual(len(formatted_prompt), batch_size) - - # Test that tokenizing with template and directly with `self.tokenizer` gives same output - formatted_prompt_tokenized = processor.apply_chat_template( - batch_messages, add_generation_prompt=True, tokenize=True, return_tensors=return_tensors - ) - add_special_tokens = True - if processor.tokenizer.bos_token is not None and formatted_prompt[0].startswith(processor.tokenizer.bos_token): - add_special_tokens = False - tok_output = processor.tokenizer( - formatted_prompt, return_tensors=return_tensors, add_special_tokens=add_special_tokens - ) - expected_output = tok_output.input_ids - self.assertListEqual(expected_output.tolist(), formatted_prompt_tokenized.tolist()) - - # Test that kwargs passed to processor's `__call__` are actually used - tokenized_prompt_100 = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - padding="max_length", - truncation=True, - return_tensors=return_tensors, - max_length=100, - ) - self.assertEqual(len(tokenized_prompt_100[0]), 100) - - # Test that `return_dict=True` returns text related inputs in the dict - out_dict_text = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - ) - self.assertTrue(all(key in out_dict_text for key in ["input_ids", "attention_mask"])) - self.assertEqual(len(out_dict_text["input_ids"]), batch_size) - self.assertEqual(len(out_dict_text["attention_mask"]), batch_size) - - # Test that with modality URLs and `return_dict=True`, we get modality inputs in the dict - for idx, url in enumerate(input_data[:batch_size]): - batch_messages[idx][0]["content"] = [batch_messages[idx][0]["content"][0], {"type": modality, "url": url}] - - out_dict = processor.apply_chat_template( - batch_messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - return_tensors=return_tensors, - fps=1, # by default no more than 1 fps, otherwise too slow - ) - input_name = getattr(self, input_name) - self.assertTrue(input_name in out_dict) - self.assertEqual(len(out_dict["input_ids"]), batch_size) - self.assertEqual(len(out_dict["attention_mask"]), batch_size) - if modality == "video": - expected_video_token_count = 0 - for thw in out_dict["video_grid_thw"]: - expected_video_token_count += thw[0] * thw[1] * thw[2] - mm_len = expected_video_token_count - else: - mm_len = batch_size * 616 - self.assertEqual(len(out_dict[input_name]), mm_len) - - return_tensor_to_type = {"pt": torch.Tensor, "np": np.ndarray, None: list} - for k in out_dict: - self.assertIsInstance(out_dict[k], return_tensor_to_type[return_tensors]) - - @require_av - def test_apply_chat_template_video_frame_sampling(self): - processor = self.get_processor() - if processor.chat_template is None: - self.skipTest("Processor has no chat template") - - signature = inspect.signature(processor.__call__) - if "videos" not in {*signature.parameters.keys()} or ( - signature.parameters.get("videos") is not None - and signature.parameters["videos"].annotation == inspect._empty - ): - self.skipTest("Processor doesn't accept videos at input") - - messages = [ - [ - { - "role": "user", - "content": [ - {"type": "video"}, - {"type": "text", "text": "What is shown in this video?"}, - ], - }, - ] + @property + def video_sampling_expectations(self): + return [ + {"num_frames": 3, "fps": None, "expected_dim": 0, "output_length": 1848}, + {"num_frames": None, "fps": 16, "expected_dim": 0, "output_length": 3080}, + {"do_sample_frames": False, "fps": 2, "expected_dim": 0, "output_length": 6776}, + {"do_sample_frames": False, "expected_dim": 0, "output_length": 6776}, ] - formatted_prompt = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) - self.assertEqual(len(formatted_prompt), 1) - - formatted_prompt_tokenized = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True) - expected_output = processor.tokenizer(formatted_prompt, return_tensors=None).input_ids - self.assertListEqual(expected_output, formatted_prompt_tokenized) - - # Add video URL for return dict and load with `num_frames` arg - messages[0][0]["content"][0] = { - "type": "video", - "url": url_to_local_path( - "https://huggingface.co/datasets/hf-internal-testing/test-videos/resolve/main/tiny_video_320x240.mp4" - ), - } - num_frames = 3 - out_dict_num_frames = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - num_frames=num_frames, - fps=None, - ) - self.assertTrue(self.videos_input_name in out_dict_num_frames) - expected_num_frames_len = sum(thw[0] * thw[1] * thw[2] for thw in out_dict_num_frames["video_grid_thw"]) - self.assertEqual(len(out_dict_num_frames[self.videos_input_name]), expected_num_frames_len) - - # Load with `fps` arg - fps = 3 - out_dict_fps = processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - fps=fps, - ) - self.assertTrue(self.videos_input_name in out_dict_fps) - expected_fps_len = sum(thw[0] * thw[1] * thw[2] for thw in out_dict_fps["video_grid_thw"]) - self.assertEqual(len(out_dict_fps[self.videos_input_name]), expected_fps_len) - # num_frames and fps sampling should produce different token counts - self.assertNotEqual(expected_num_frames_len, expected_fps_len) - - # Load with `fps` and `num_frames` args, should raise an error - with self.assertRaises(ValueError): - processor.apply_chat_template( - messages, - add_generation_prompt=True, - tokenize=True, - return_dict=True, - fps=fps, - num_frames=num_frames, - ) - def test_kwargs_overrides_custom_image_processor_kwargs(self): processor = self.get_processor() - self.skip_processor_without_typed_kwargs(processor) input_str = self.prepare_text_inputs() - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() inputs = processor(text=input_str, images=image_input, return_tensors="pt") self.assertEqual(inputs[self.images_input_name].shape[0], 56) inputs = processor( @@ -260,10 +88,6 @@ def test_kwargs_overrides_custom_image_processor_kwargs(self): ) self.assertEqual(inputs[self.images_input_name].shape[0], 800) - @unittest.skip("Kimi pops some keys before returning in a processor") - def test_video_processor_defaults(self): - pass - @parameterized.expand([(1, "pt")]) @unittest.skip("Kimi sampels with FPS by default which is not compatible with this test") def test_apply_chat_template_decoded_video(self, batch_size: int, return_tensors: str): diff --git a/tests/models/kosmos2/test_processing_kosmos2.py b/tests/models/kosmos2/test_processing_kosmos2.py index abb42e4e02e4..a4ff476e666a 100644 --- a/tests/models/kosmos2/test_processing_kosmos2.py +++ b/tests/models/kosmos2/test_processing_kosmos2.py @@ -18,6 +18,7 @@ import numpy as np import pytest +from parameterized import parameterized from transformers.image_utils import load_image from transformers.testing_utils import ( @@ -30,7 +31,7 @@ from transformers.tokenization_utils_sentencepiece import SentencePieceExtractor from transformers.utils import is_vision_available -from ...test_processing_common import ProcessorTesterMixin, url_to_local_path +from ...test_processing_common import MODALITY_TEST_SPECS, ProcessorTesterMixin, url_to_local_path if is_vision_available(): @@ -52,6 +53,9 @@ @require_vision class Kosmos2ProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = Kosmos2Processor + images_text_kwargs_max_length = 72 + images_text_kwargs_override_max_length = 72 + images_unstructured_max_length = 72 @classmethod def _setup_tokenizer(cls): @@ -71,8 +75,9 @@ def _setup_image_processor(cls): image_processor_class = cls._get_component_class_from_processor("image_processor") return image_processor_class(do_center_crop=False) + @parameterized.expand(["text", "images"]) @unittest.skip("Kosmos2Processor adds special tokens to the text") - def test_tokenizer_defaults(self): + def test_subprocessor_defaults(self, modality): pass def test_image_processor_load_save_reload(self): @@ -370,145 +375,27 @@ def check(texts, bboxes, expected_input_ids): self.assertListEqual(outputs.image_embeds_position_mask.numpy().tolist()[-1], EXPECTED_IMG_POS_MASK_BATCH[-1]) # Rewrite as Kosmos-2 supports custom padding only when image is None. - @require_vision - @require_torch - def test_kwargs_overrides_default_tokenizer_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer", max_length=117) - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - # set image input to None - image_input = None - - inputs = processor( - text=input_str, - images=image_input, - return_tensors="pt", - max_length=112, - padding="max_length", - ) - - self.assertEqual(len(inputs["input_ids"][0]), 112) - - # Rewrite to test only image_processor kwargs - @require_torch - @require_vision - def test_structured_kwargs_nested(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs() - image_input = self.prepare_image_inputs() - - # Define the kwargs for each modality - all_kwargs = { - "common_kwargs": {"return_tensors": "pt"}, - "images_kwargs": {"size": {"height": 214, "width": 214}}, - } - - inputs = processor(text=input_str, images=image_input, **all_kwargs) - self.skip_processor_without_typed_kwargs(processor) - - self.assertEqual(inputs["pixel_values"].shape[2], 214) - - # Rewrite to test only image_processor kwargs - @require_torch - @require_vision - def test_structured_kwargs_nested_from_dict(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - image_input = self.prepare_image_inputs() - - # Define the kwargs for each modality - all_kwargs = { - "common_kwargs": {"return_tensors": "pt"}, - "images_kwargs": {"size": {"height": 214, "width": 214}}, - } + def _test_unstructured_kwargs_batched(self, modality): + attributes = self.processor_class.get_attributes() + processor = self.get_processor() + self.maybe_skip_typed_test_for_modality(modality, attributes) - inputs = processor(text=input_str, images=image_input, **all_kwargs) - self.assertEqual(inputs["pixel_values"].shape[2], 214) + input_str = self.prepare_text_inputs(batch_size=2, modalities=modality) + modal_input = self._prepare_modality_input(modality, batch_size=2) + max_length = getattr(self, "images_unstructured_max_length") + init_time_kwargs = MODALITY_TEST_SPECS[modality]["init_time_kwargs"] + call_kwargs = MODALITY_TEST_SPECS[modality]["call_time_kwargs"] - # Rewrite as Kosmos-2 supports custom padding only when image is None. - @require_vision - @require_torch - def test_tokenizer_defaults_preserved_by_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer", max_length=117, padding="max_length") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - # set image input to None - image_input = None - - inputs = processor(text=input_str, images=image_input, return_tensors="pt") - self.assertEqual(len(inputs["input_ids"][0]), 117) - - # Rewrite as Kosmos-2 supports custom padding only when image is None. - @require_torch - @require_vision - def test_unstructured_kwargs(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs() - # set image input to None - image_input = None - inputs = processor( - text=input_str, - images=image_input, - return_tensors="pt", - padding="max_length", - max_length=76, - ) - - self.assertEqual(len(inputs["input_ids"][0]), 76) - - # Rewrite as Kosmos-2 supports custom padding only when image is None. - @require_torch - @require_vision - def test_unstructured_kwargs_batched(self): - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs(batch_size=2) - # set image input to None - image_input = None inputs = processor( text=input_str, - images=image_input, - return_tensors="pt", - size={"height": 214, "width": 214}, + max_length=max_length, padding="longest", - max_length=76, + images=modal_input, + **call_kwargs, + **init_time_kwargs, + ) + self._check_modality_outputs(inputs, modality) + self.assertTrue( + len(inputs[self.text_input_name][0]) == len(inputs[self.text_input_name][1]) + and len(inputs[self.text_input_name][1]) == 76 ) - - self.assertEqual(len(inputs["input_ids"][0]), 10) diff --git a/tests/models/kosmos2_5/test_processing_kosmos2_5.py b/tests/models/kosmos2_5/test_processing_kosmos2_5.py index 0658a49c4be1..3504af73055b 100644 --- a/tests/models/kosmos2_5/test_processing_kosmos2_5.py +++ b/tests/models/kosmos2_5/test_processing_kosmos2_5.py @@ -47,8 +47,12 @@ class Kosmos2_5ProcessorTest(ProcessorTesterMixin, unittest.TestCase): # Tiny processor created with make_tiny_processor.py from "microsoft/kosmos-2.5" tiny_model_id = "hf-internal-testing/tiny-processor-kosmos2_5" + @staticmethod + def prepare_processor_dict(): + return {"num_image_tokens": 5} + @unittest.skip("Kosmos2_5Processor removes 'rows' and 'cols' from the output") - def test_image_processor_defaults(self): + def test_subprocessor_defaults_1_images(self): pass def test_image_procesor_load_save_reload(self): @@ -73,7 +77,7 @@ def test_model_input_names(self): processor = Kosmos2_5Processor(tokenizer=tokenizer, image_processor=image_processor) input_str = "This is a test" - image_input = self.prepare_image_inputs() + image_input = self.prepare_images_inputs() # both image and text inputs = processor(text=input_str, images=image_input) @@ -92,150 +96,11 @@ def test_model_input_names(self): with pytest.raises(ValueError): processor() - @require_torch - @require_vision - def test_image_processor_defaults_preserved_by_image_kwargs(self): - # Rewrite as KOSMOS-2.5 processor return "flattened_patches" and not "pixel_values" - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor", max_patches=1024, patch_size={"height": 8, "width": 8}) - tokenizer = self.get_component("tokenizer", max_length=117, padding="max_length") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs() - image_input = self.prepare_image_inputs() - - inputs = processor(text=input_str, images=image_input) - self.assertEqual(len(inputs["flattened_patches"][0][0]), 194) - - @require_torch - @require_vision - def test_kwargs_overrides_default_image_processor_kwargs(self): - # Rewrite as KOSMOS-2.5 processor return "flattened_patches" and not "pixel_values" - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor", max_patches=4096) - tokenizer = self.get_component("tokenizer", max_length=117, padding="max_length") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs() - image_input = self.prepare_image_inputs() - - inputs = processor(text=input_str, images=image_input, max_patches=1024) - self.assertEqual(len(inputs["flattened_patches"][0]), 1024) - - @require_torch - @require_vision - def test_unstructured_kwargs(self): - # Rewrite as KOSMOS-2.5 processor doesn't use `rescale_factor` - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs() - image_input = self.prepare_image_inputs() - inputs = processor( - text=input_str, - images=image_input, - return_tensors="pt", - max_patches=1024, - padding="max_length", - max_length=76, - ) - - self.assertEqual(inputs["flattened_patches"].shape[1], 1024) - self.assertEqual(len(inputs["input_ids"][0]), 76) - - @require_torch - @require_vision - def test_unstructured_kwargs_batched(self): - # Rewrite as KOSMOS-2.5 processor doesn't use `rescale_factor` - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs(batch_size=2) - image_input = self.prepare_image_inputs(batch_size=2) - inputs = processor( - text=input_str, - images=image_input, - return_tensors="pt", - max_patches=1024, - padding="longest", - max_length=76, - ) - - self.assertEqual(inputs["flattened_patches"].shape[1], 1024) - - self.assertEqual(len(inputs["input_ids"][0]), 76) - - @require_torch - @require_vision - def test_structured_kwargs_nested(self): - # Rewrite as KOSMOS-2.5 processor doesn't use `rescale_factor` - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - - input_str = self.prepare_text_inputs() - image_input = self.prepare_image_inputs() - - # Define the kwargs for each modality - all_kwargs = { - "common_kwargs": {"return_tensors": "pt"}, - "images_kwargs": {"max_patches": 1024}, - "text_kwargs": {"padding": "max_length", "max_length": 76}, - } - - inputs = processor(text=input_str, images=image_input, **all_kwargs) - self.skip_processor_without_typed_kwargs(processor) - - self.assertEqual(inputs["flattened_patches"].shape[1], 1024) - - self.assertEqual(len(inputs["input_ids"][0]), 76) - - @require_torch - @require_vision - def test_structured_kwargs_nested_from_dict(self): - # Rewrite as KOSMOS-2.5 processor doesn't use `rescale_factor` - if "image_processor" not in self.processor_class.get_attributes(): - self.skipTest(f"image_processor attribute not present in {self.processor_class}") - - image_processor = self.get_component("image_processor") - tokenizer = self.get_component("tokenizer") - - processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) - self.skip_processor_without_typed_kwargs(processor) - input_str = self.prepare_text_inputs() - image_input = self.prepare_image_inputs() - - # Define the kwargs for each modality - all_kwargs = { - "common_kwargs": {"return_tensors": "pt"}, - "images_kwargs": {"max_patches": 1024}, - "text_kwargs": {"padding": "max_length", "max_length": 76}, - } - - inputs = processor(text=input_str, images=image_input, **all_kwargs) - self.assertEqual(inputs["flattened_patches"].shape[1], 1024) - - self.assertEqual(len(inputs["input_ids"][0]), 76) + # Rewrite as KOSMOS-2.5 processor applies custom normalization and we can't check `out.mean()` + def _check_modality_outputs(self, inputs: dict, modality: str): + input_key = getattr(self, f"{modality}_input_name") + if modality in ["image"]: + self.assertEqual(len(inputs[input_key][0]), 4096) @require_torch def test_full_processor(self): diff --git a/tests/models/layoutlmv2/test_processing_layoutlmv2.py b/tests/models/layoutlmv2/test_processing_layoutlmv2.py index eaa213d3c0b1..0c9fca4e8e00 100644 --- a/tests/models/layoutlmv2/test_processing_layoutlmv2.py +++ b/tests/models/layoutlmv2/test_processing_layoutlmv2.py @@ -69,8 +69,8 @@ def _setup_tokenizer(cls): vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) return LayoutLMv2Tokenizer.from_pretrained(cls.tmpdirname) - @unittest.skip("LayoutLMv2Processor doesn't use pixel_values") - def test_image_processor_defaults(self): + @unittest.skip("LayoutLMv2Processor can't process string text, requires pre-tokenized words") + def test_subprocessor_defaults_0_text(self): pass @unittest.skip("LayoutLMv2Processor doesn't use pixel_values") @@ -142,6 +142,10 @@ def preprocess_data(examples): self.assertEqual(len(train_data["image"]), len(train_data["input_ids"])) + @unittest.skip("Processor doesn't accept typed kwargs!") + def test_flat_kwarg_applied_when_modality_dict_lacks_it(self): + pass + # different use cases tests @require_torch diff --git a/tests/models/layoutlmv3/test_processing_layoutlmv3.py b/tests/models/layoutlmv3/test_processing_layoutlmv3.py index 9385c55c8f30..6d3c1de69880 100644 --- a/tests/models/layoutlmv3/test_processing_layoutlmv3.py +++ b/tests/models/layoutlmv3/test_processing_layoutlmv3.py @@ -60,8 +60,12 @@ def _setup_tokenizer(cls): return tokenizer_class.from_pretrained(cls.tmpdirname, unk_token="") - @unittest.skip("LayoutLMv3 Image Processor doesn't return image tensors") - def test_image_processor_defaults(self): + @unittest.skip("LayoutLMv3Processor can't process string text, requires pre-tokenized words") + def test_subprocessor_defaults_0_text(self): + pass + + @unittest.skip("Processor doesn't accept typed kwargs!") + def test_flat_kwarg_applied_when_modality_dict_lacks_it(self): pass diff --git a/tests/models/lfm2_vl/test_processing_lfm2_vl.py b/tests/models/lfm2_vl/test_processing_lfm2_vl.py index f264e693cd03..f734eb8c7bcc 100755 --- a/tests/models/lfm2_vl/test_processing_lfm2_vl.py +++ b/tests/models/lfm2_vl/test_processing_lfm2_vl.py @@ -37,6 +37,7 @@ class Lfm2VlProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = Lfm2VlProcessor # Tiny processor created with make_tiny_processor.py from "LiquidAI/LFM2-VL-1.6B" tiny_model_id = "hf-internal-testing/tiny-processor-lfm2_vl" + model_id = "LiquidAI/LFM2-VL-1.6B" @classmethod def _setup_image_processor(cls): @@ -91,14 +92,10 @@ def prepare_processor_dict(): ) return {"chat_template": chat_template} - @unittest.skip("Lfm2VlProcessor adds special tokens to the text") - def test_tokenizer_defaults(self): - pass - # Override as Lfm2VL needs images/video to be an explicitly nested batch - def prepare_image_inputs(self, batch_size=None): + def prepare_images_inputs(self, batch_size=None): """This function prepares a list of PIL images for testing""" - images = super().prepare_image_inputs(batch_size) + images = super().prepare_images_inputs(batch_size) if isinstance(images, (list, tuple)): images = [[image] for image in images] return images diff --git a/tests/models/lighton_ocr/test_processing_lighton_ocr.py b/tests/models/lighton_ocr/test_processing_lighton_ocr.py index aac794740d3e..c00409b8283c 100644 --- a/tests/models/lighton_ocr/test_processing_lighton_ocr.py +++ b/tests/models/lighton_ocr/test_processing_lighton_ocr.py @@ -45,7 +45,7 @@ def setUp(self): processor = self.get_processor() self.image_token = processor.image_token - def prepare_image_inputs(self, batch_size=None): + def prepare_images_inputs(self, batch_size=None): """Prepare small dummy image inputs.""" image = Image.new("RGB", (112, 112), color="red") if batch_size is None: @@ -73,7 +73,7 @@ def test_processor_with_text_only(self): def test_processor_with_image_and_text(self): """Test processor with both image and text inputs.""" processor = self.get_processor() - image = self.prepare_image_inputs() + image = self.prepare_images_inputs() text = f"{self.image_token} Extract text from this image." inputs = processor(images=image, text=text, return_tensors="pt") @@ -91,7 +91,7 @@ def test_processor_with_image_and_text(self): def test_processor_image_token_expansion(self): """Test that image token is properly expanded based on image size.""" processor = self.get_processor() - image = self.prepare_image_inputs() + image = self.prepare_images_inputs() text = f"{self.image_token} Describe this image." inputs = processor(images=image, text=text, return_tensors="pt") @@ -107,7 +107,7 @@ def test_processor_image_token_expansion(self): def test_processor_batch_processing(self): """Test processor with batch of inputs.""" processor = self.get_processor() - images = self.prepare_image_inputs(batch_size=2) + images = self.prepare_images_inputs(batch_size=2) texts = [f"{self.image_token} Extract text." for _ in range(2)] inputs = processor(images=images, text=texts, return_tensors="pt", padding=True) @@ -155,7 +155,7 @@ def test_processor_special_tokens(self): def test_processor_return_types(self): """Test different return types (pt, np, list).""" processor = self.get_processor() - image = self.prepare_image_inputs() + image = self.prepare_images_inputs() text_with_image = f"{self.image_token} Test image." text_only = "Test without image." diff --git a/tests/models/llava/test_processing_llava.py b/tests/models/llava/test_processing_llava.py index 76a3749cf678..ba635444d7ce 100644 --- a/tests/models/llava/test_processing_llava.py +++ b/tests/models/llava/test_processing_llava.py @@ -78,7 +78,7 @@ def test_special_mm_token_truncation(self): processor = LlavaProcessor.from_pretrained("hf-internal-testing/tiny-processor-llava") input_str = self.prepare_text_inputs(batch_size=2, modalities="image") - image_input = self.prepare_image_inputs(batch_size=2) + image_input = self.prepare_images_inputs(batch_size=2) _ = processor( text=input_str, diff --git a/tests/models/llava_next_video/test_processing_llava_next_video.py b/tests/models/llava_next_video/test_processing_llava_next_video.py index e2324190b6ce..0895530ace38 100644 --- a/tests/models/llava_next_video/test_processing_llava_next_video.py +++ b/tests/models/llava_next_video/test_processing_llava_next_video.py @@ -35,6 +35,7 @@ class LlavaNextVideoProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = LlavaNextVideoProcessor # Tiny processor created with make_tiny_processor.py from "llava-hf/LLaVA-NeXT-Video-7B-hf" tiny_model_id = "hf-internal-testing/tiny-processor-llava_next_video" + model_id = "llava-hf/LLaVA-NeXT-Video-7B-hf" @classmethod def prepare_processor_dict(cls): @@ -45,7 +46,7 @@ def prepare_processor_dict(cls): "vision_feature_select_strategy": "default", } - def prepare_video_inputs(self, batch_size=None): + def prepare_videos_inputs(self, batch_size=None): """Use tiny frames to keep test_processor_text_has_no_visual memory-efficient.""" video_input = [np.random.randint(255, size=(3, 8, 8), dtype=np.uint8)] * 2 video_input = np.array(video_input) diff --git a/tests/models/llava_onevision/test_processing_llava_onevision.py b/tests/models/llava_onevision/test_processing_llava_onevision.py index a09a616c1ec5..80036b0755d6 100644 --- a/tests/models/llava_onevision/test_processing_llava_onevision.py +++ b/tests/models/llava_onevision/test_processing_llava_onevision.py @@ -20,7 +20,7 @@ from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_vision_available -from ...test_processing_common import ProcessorTesterMixin, url_to_local_path +from ...test_processing_common import ProcessorTesterMixin if is_vision_available(): @@ -31,26 +31,7 @@ @require_torch class LlavaOnevisionProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = LlavaOnevisionProcessor - - @classmethod - def _setup_tokenizer(cls): - tokenizer_class = cls._get_component_class_from_processor("tokenizer") - vocab_tokens = [ - ("", 0.0), - ("", 0.0), - ("", 0.0), - ("[PAD]", 0.0), - ("", 0.0), - ("