# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # This file was automatically generated from src/transformers/models/musicflamingo/modular_musicflamingo.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_musicflamingo.py file directly. One of our CI enforces this. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # Copyright 2026 NVIDIA CORPORATION and 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 ...audio_utils import AudioInput from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack from ...tokenization_utils_base import TextInput from ...utils import auto_docstring, is_torch_available, logging from ...utils.import_utils import requires if is_torch_available(): import torch logger = logging.get_logger(__name__) class MusicFlamingoProcessorKwargs(ProcessingKwargs, total=False): _defaults = { "text_kwargs": { "padding": True, }, "audio_kwargs": { "sampling_rate": 16000, "return_attention_mask": True, "padding": "max_length", }, "common_kwargs": { "return_tensors": "pt", "padding_side": "left", }, } @requires(backends=("torch",)) @auto_docstring class MusicFlamingoProcessor(ProcessorMixin): valid_processor_kwargs = MusicFlamingoProcessorKwargs def __init__( self, feature_extractor, tokenizer, chat_template=None, audio_token="", audio_bos_token="<|sound_bos|>", audio_eos_token="<|sound_eos|>", max_audio_len=1200, ): r""" audio_token (`Optional[str]`, *optional*, defaults to `""`): Special token used to represent audio inputs in the chat template. audio_bos_token (`Optional[str]`, *optional*, defaults to `"<|sound_bos|>"`): Special token used to represent the beginning of audio. audio_eos_token (`Optional[str]`, *optional*, defaults to `"<|sound_eos|>"`): Special token used to represent the end of audio. max_audio_len (`int`, *optional*, defaults to 1200): Maximum length of audio sequences in seconds. Audio longer than this will be truncated. """ self.audio_token = audio_token self.audio_token_id = tokenizer.convert_tokens_to_ids(audio_token) self.max_audio_len = max_audio_len super().__init__(feature_extractor, tokenizer, chat_template=chat_template) self.audio_bos_token = audio_bos_token self.audio_eos_token = audio_eos_token self.audio_bos_token_id = tokenizer.convert_tokens_to_ids(audio_bos_token) self.audio_eos_token_id = tokenizer.convert_tokens_to_ids(audio_eos_token) @auto_docstring def __call__( self, text: TextInput | list[TextInput], audio: AudioInput | None = None, output_labels: bool | None = False, **kwargs: Unpack[MusicFlamingoProcessorKwargs], ) -> BatchFeature: r""" output_labels (bool, *optional*, default=False): Whether to return labels for training. Returns: [`BatchFeature`]: A dictionary with tokenized text (`input_ids`, `attention_mask`) and audio features (`input_features`, `input_features_mask`). """ # Check only if passed explicitly as another value since by default we'll use `pt` if "return_tensors" in kwargs and kwargs["return_tensors"] != "pt": raise ValueError(f"{self.__class__.__name__} only supports `return_tensors='pt'`.") if output_labels: kwargs["return_mm_token_type_ids"] = True model_inputs = super().__call__(audio=audio, text=text, **kwargs) if output_labels: mm_token_type_ids = model_inputs.pop("mm_token_type_ids") labels = model_inputs["input_ids"].clone() labels[mm_token_type_ids != 0] = -100 # audio positions labels[labels == self.tokenizer.pad_token_id] = -100 model_inputs["labels"] = labels return BatchFeature(data=model_inputs, tensor_type="pt") def validate_inputs( self, audio: AudioInput | None = None, text: TextInput | list[TextInput] | None = None, **kwargs: Unpack[ProcessingKwargs], ): super().validate_inputs(audio=audio, text=text, **kwargs) if text is not None and audio is not None and len(text) != len(audio): raise ValueError(f"Got {len(text)} text but {len(audio)} audios; they must match 1:1.") def _get_audio_token_length(self, audio_lengths): conv_output_lengths = (audio_lengths - 1) // 2 + 1 # After conv2 downsampling audio_tokens_lengths = (conv_output_lengths - 2) // 2 + 1 # After avg pooling return audio_tokens_lengths def _process_audio(self, audio: AudioInput, **kwargs): # Determine number of chunks per sample, and flatten window_size = int(kwargs["sampling_rate"] * self.feature_extractor.chunk_length) max_windows = int(self.max_audio_len // self.feature_extractor.chunk_length) per_sample_windows: list[int] = [] flat_chunks: list[np.ndarray] = [] for audio_el in audio: n_samples = int(audio_el.shape[0]) n_win = max(1, (n_samples + window_size - 1) // window_size) if n_win > max_windows: logger.warning( f"Audio duration ({n_samples / kwargs['sampling_rate']:.1f}s) exceeds {self.max_audio_len}s; truncating to first {self.max_audio_len}s." ) n_win = max_windows per_sample_windows.append(n_win) time_cap = min(n_samples, n_win * window_size) for i in range(n_win): start = i * window_size end = min((i + 1) * window_size, time_cap) flat_chunks.append(audio_el[start:end]) audio = self.feature_extractor.fetch_audio(audio) audio_inputs = self.feature_extractor(flat_chunks, **kwargs) audio_inputs["input_features_mask"] = audio_inputs.pop("attention_mask") # AudioFlamingo doesn't have its own feature extractor and crops audio into # chunks here. Save the number of tokens based on crops/padding in analogy # with some vision processors audio_lengths = torch.stack( [s.sum() for s in torch.split(audio_inputs["input_features_mask"].sum(-1), per_sample_windows)] ) audio_inputs["num_audio_tokens"] = self._get_audio_token_length(audio_lengths) audio_replacements = [] for idx in range(len(audio)): replacement_text = self.replace_audio_token(audio_inputs, audio_idx=idx) audio_replacements.append(replacement_text) return audio_inputs, audio_replacements def replace_audio_token(self, audio_inputs: dict, audio_idx: int, **kwargs) -> str: num_audio_tokens = audio_inputs["num_audio_tokens"][audio_idx] return self.audio_bos_token + self.audio_token * num_audio_tokens + self.audio_eos_token @property def model_input_names(self) -> list[str]: return super().model_input_names + ["input_features_mask"] @property def unused_input_names(self) -> list[str]: "Input names returned always by subprocessors but not used in model's `forward`" return ["num_audio_tokens"] @property def audio_token_ids(self): return [self.audio_token_id, self.audio_bos_token_id, self.audio_eos_token_id] # Alias for BC @property def audio_ids(self): """Deprecated alias for `audio_token_ids`; will be removed in a future release.""" logger.warning_once("`audio_ids` is deprecated; please use `audio_token_ids` instead.") return self.audio_token_ids __all__ = ["MusicFlamingoProcessor"]