Upload 5 files
Browse files- processor_config.json +1 -1
 - ultravox_config.py +48 -9
 - ultravox_model.py +433 -68
 - ultravox_processing.py +263 -61
 
    	
        processor_config.json
    CHANGED
    
    | 
         @@ -5,7 +5,7 @@ 
     | 
|
| 5 | 
         
             
              "auto_map": {
         
     | 
| 6 | 
         
             
                "AutoProcessor": "ultravox_processing.UltravoxProcessor"
         
     | 
| 7 | 
         
             
              },
         
     | 
| 8 | 
         
            -
              "encoder_ds_factor":  
     | 
| 9 | 
         
             
              "processor_class": "UltravoxProcessor",
         
     | 
| 10 | 
         
             
              "stack_factor": 8
         
     | 
| 11 | 
         
             
            }
         
     | 
| 
         | 
|
| 5 | 
         
             
              "auto_map": {
         
     | 
| 6 | 
         
             
                "AutoProcessor": "ultravox_processing.UltravoxProcessor"
         
     | 
| 7 | 
         
             
              },
         
     | 
| 8 | 
         
            +
              "encoder_ds_factor": 2,
         
     | 
| 9 | 
         
             
              "processor_class": "UltravoxProcessor",
         
     | 
| 10 | 
         
             
              "stack_factor": 8
         
     | 
| 11 | 
         
             
            }
         
     | 
    	
        ultravox_config.py
    CHANGED
    
    | 
         @@ -1,4 +1,5 @@ 
     | 
|
| 1 | 
         
             
            import dataclasses
         
     | 
| 
         | 
|
| 2 | 
         
             
            from typing import Any, Dict, List, Optional
         
     | 
| 3 | 
         | 
| 4 | 
         
             
            import transformers
         
     | 
| 
         @@ -18,6 +19,25 @@ class LoraConfigSimplified: 
     | 
|
| 18 | 
         
             
                target_modules: Optional[List[str]] = dataclasses.field(
         
     | 
| 19 | 
         
             
                    default_factory=lambda: ["k_proj", "q_proj", "linear_k", "linear_q"]
         
     | 
| 20 | 
         
             
                )
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 21 | 
         | 
| 22 | 
         | 
| 23 | 
         
             
            class UltravoxConfig(transformers.PretrainedConfig):
         
     | 
| 
         @@ -29,7 +49,7 @@ class UltravoxConfig(transformers.PretrainedConfig): 
     | 
|
| 29 | 
         
             
                documentation from [`PretrainedConfig`] for more information.
         
     | 
| 30 | 
         | 
| 31 | 
         
             
                Args:
         
     | 
| 32 | 
         
            -
                    audio_config (` 
     | 
| 33 | 
         
             
                        Custom audio config or dict
         
     | 
| 34 | 
         
             
                    text_config (`Union[AutoConfig, dict]`, *optional*):
         
     | 
| 35 | 
         
             
                        The config object of the text backbone. Can be any of `LlamaConfig` or `MistralConfig`.
         
     | 
| 
         @@ -47,15 +67,17 @@ class UltravoxConfig(transformers.PretrainedConfig): 
     | 
|
| 47 | 
         
             
                        The LoRA configuration for finetuning the text model.
         
     | 
| 48 | 
         
             
                    audio_model_lora_config (`LoraConfigSimplified`, *optional*):
         
     | 
| 49 | 
         
             
                        The LoRA configuration for finetuning the audio model.
         
     | 
| 
         | 
|
| 
         | 
|
| 50 | 
         | 
| 51 | 
         | 
| 52 | 
         
             
                Example:
         
     | 
| 53 | 
         | 
| 54 | 
         
             
                ```python
         
     | 
| 55 | 
         
            -
                >>> from transformers import  
     | 
| 56 | 
         | 
| 57 | 
         
             
                >>> # Initializing an audio encoder config
         
     | 
| 58 | 
         
            -
                >>> audio_config =  
     | 
| 59 | 
         | 
| 60 | 
         
             
                >>> # Initializing a Llama config
         
     | 
| 61 | 
         
             
                >>> text_config = LlamaConfig()
         
     | 
| 
         @@ -64,13 +86,13 @@ class UltravoxConfig(transformers.PretrainedConfig): 
     | 
|
| 64 | 
         
             
                >>> configuration = UltravoxConfig(audio_config, text_config)
         
     | 
| 65 | 
         | 
| 66 | 
         
             
                >>> # Initializing a completely untrained model from the configuration
         
     | 
| 67 | 
         
            -
                >>> model =  
     | 
| 68 | 
         | 
| 69 | 
         
             
                >>> # Accessing the model configuration
         
     | 
| 70 | 
         
             
                >>> configuration = model.config
         
     | 
| 71 | 
         | 
| 72 | 
         
             
                >>> # Initialize a model from pretrained checkpoints and random projector weights
         
     | 
| 73 | 
         
            -
                >>> config = UltravoxConfig(audio_model_id=" 
     | 
| 74 | 
         
             
                ```"""
         
     | 
| 75 | 
         | 
| 76 | 
         
             
                model_type = "ultravox"
         
     | 
| 
         @@ -83,26 +105,26 @@ class UltravoxConfig(transformers.PretrainedConfig): 
     | 
|
| 83 | 
         
             
                    audio_model_id: Optional[str] = None,
         
     | 
| 84 | 
         
             
                    text_model_id: Optional[str] = None,
         
     | 
| 85 | 
         
             
                    ignore_index: int = -100,
         
     | 
| 86 | 
         
            -
                    audio_token_index: int = 32000,
         
     | 
| 87 | 
         
             
                    hidden_size: int = 4096,
         
     | 
| 88 | 
         
             
                    stack_factor: int = 8,
         
     | 
| 89 | 
         
             
                    norm_init: float = 0.4,
         
     | 
| 90 | 
         
             
                    projector_act: str = "swiglu",
         
     | 
| 
         | 
|
| 91 | 
         
             
                    text_model_lora_config: Optional[LoraConfigSimplified] = None,
         
     | 
| 92 | 
         
             
                    audio_model_lora_config: Optional[LoraConfigSimplified] = None,
         
     | 
| 
         | 
|
| 93 | 
         
             
                    **kwargs,
         
     | 
| 94 | 
         
             
                ):
         
     | 
| 95 | 
         
             
                    self.ignore_index = ignore_index
         
     | 
| 96 | 
         | 
| 97 | 
         
             
                    self.audio_model_id = audio_model_id
         
     | 
| 98 | 
         
             
                    self.text_model_id = text_model_id
         
     | 
| 99 | 
         
            -
                    self.audio_token_index = audio_token_index
         
     | 
| 100 | 
         | 
| 101 | 
         
             
                    self.hidden_size = hidden_size
         
     | 
| 102 | 
         
             
                    self.stack_factor = stack_factor
         
     | 
| 103 | 
         
             
                    self.norm_init = norm_init
         
     | 
| 104 | 
         
             
                    self.projector_act = projector_act
         
     | 
| 105 | 
         
            -
             
     | 
| 106 | 
         
             
                    if text_model_id is not None:
         
     | 
| 107 | 
         
             
                        self.text_config: transformers.LlamaConfig = (
         
     | 
| 108 | 
         
             
                            transformers.AutoConfig.from_pretrained(text_model_id)
         
     | 
| 
         @@ -120,7 +142,7 @@ class UltravoxConfig(transformers.PretrainedConfig): 
     | 
|
| 120 | 
         
             
                    else:
         
     | 
| 121 | 
         
             
                        audio_config = audio_config or {}
         
     | 
| 122 | 
         
             
                        self.audio_config = transformers.CONFIG_MAPPING[
         
     | 
| 123 | 
         
            -
                            audio_config.get("model_type", " 
     | 
| 124 | 
         
             
                        ](**audio_config)
         
     | 
| 125 | 
         | 
| 126 | 
         
             
                    self.text_model_lora_config = (
         
     | 
| 
         @@ -133,9 +155,26 @@ class UltravoxConfig(transformers.PretrainedConfig): 
     | 
|
| 133 | 
         
             
                        if isinstance(audio_model_lora_config, dict)
         
     | 
| 134 | 
         
             
                        else dataclasses.asdict(audio_model_lora_config or LoraConfigSimplified())
         
     | 
| 135 | 
         
             
                    )
         
     | 
| 
         | 
|
| 136 | 
         | 
| 137 | 
         
             
                    self.vocab_size = self.text_config.vocab_size
         
     | 
| 138 | 
         | 
| 139 | 
         
             
                    self.initializer_range = self.text_config.initializer_range
         
     | 
| 140 | 
         | 
| 141 | 
         
             
                    super().__init__(**kwargs)
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
| 
         | 
|
| 1 | 
         
             
            import dataclasses
         
     | 
| 2 | 
         
            +
            from enum import Enum
         
     | 
| 3 | 
         
             
            from typing import Any, Dict, List, Optional
         
     | 
| 4 | 
         | 
| 5 | 
         
             
            import transformers
         
     | 
| 
         | 
|
| 19 | 
         
             
                target_modules: Optional[List[str]] = dataclasses.field(
         
     | 
| 20 | 
         
             
                    default_factory=lambda: ["k_proj", "q_proj", "linear_k", "linear_q"]
         
     | 
| 21 | 
         
             
                )
         
     | 
| 22 | 
         
            +
                # A list of module names regex patterns to unfreeze. Only used if r == 0.
         
     | 
| 23 | 
         
            +
                unfreeze_layers: Optional[List[str]] = None
         
     | 
| 24 | 
         
            +
             
     | 
| 25 | 
         
            +
             
     | 
| 26 | 
         
            +
            class LossFunction(str, Enum):
         
     | 
| 27 | 
         
            +
                CrossEntropy = "ce"
         
     | 
| 28 | 
         
            +
                KL_Divergence = "kl"
         
     | 
| 29 | 
         
            +
             
     | 
| 30 | 
         
            +
             
     | 
| 31 | 
         
            +
            @dataclasses.dataclass
         
     | 
| 32 | 
         
            +
            class LossConfig:
         
     | 
| 33 | 
         
            +
                loss_function: LossFunction = LossFunction.CrossEntropy
         
     | 
| 34 | 
         
            +
                kl_temperature: float = 2.0
         
     | 
| 35 | 
         
            +
                # Number of tokens to ignore from the beginning of the sequence. Only used in LSM
         
     | 
| 36 | 
         
            +
                initial_tokens_to_ignore: int = 0
         
     | 
| 37 | 
         
            +
             
     | 
| 38 | 
         
            +
                @property
         
     | 
| 39 | 
         
            +
                def requires_alt_fields(self):
         
     | 
| 40 | 
         
            +
                    return self.loss_function == LossFunction.KL_Divergence
         
     | 
| 41 | 
         | 
| 42 | 
         | 
| 43 | 
         
             
            class UltravoxConfig(transformers.PretrainedConfig):
         
     | 
| 
         | 
|
| 49 | 
         
             
                documentation from [`PretrainedConfig`] for more information.
         
     | 
| 50 | 
         | 
| 51 | 
         
             
                Args:
         
     | 
| 52 | 
         
            +
                    audio_config (`WhisperConfig`,  *optional*):
         
     | 
| 53 | 
         
             
                        Custom audio config or dict
         
     | 
| 54 | 
         
             
                    text_config (`Union[AutoConfig, dict]`, *optional*):
         
     | 
| 55 | 
         
             
                        The config object of the text backbone. Can be any of `LlamaConfig` or `MistralConfig`.
         
     | 
| 
         | 
|
| 67 | 
         
             
                        The LoRA configuration for finetuning the text model.
         
     | 
| 68 | 
         
             
                    audio_model_lora_config (`LoraConfigSimplified`, *optional*):
         
     | 
| 69 | 
         
             
                        The LoRA configuration for finetuning the audio model.
         
     | 
| 70 | 
         
            +
                    audio_latency_block_size (`int`, *optional*, defaults to `None`):
         
     | 
| 71 | 
         
            +
                        The latency block size for simulating audio streaming.
         
     | 
| 72 | 
         | 
| 73 | 
         | 
| 74 | 
         
             
                Example:
         
     | 
| 75 | 
         | 
| 76 | 
         
             
                ```python
         
     | 
| 77 | 
         
            +
                >>> from transformers import UltravoxModel, WhisperConfig, UltravoxConfig, LlamaConfig
         
     | 
| 78 | 
         | 
| 79 | 
         
             
                >>> # Initializing an audio encoder config
         
     | 
| 80 | 
         
            +
                >>> audio_config = WhisperConfig()
         
     | 
| 81 | 
         | 
| 82 | 
         
             
                >>> # Initializing a Llama config
         
     | 
| 83 | 
         
             
                >>> text_config = LlamaConfig()
         
     | 
| 
         | 
|
| 86 | 
         
             
                >>> configuration = UltravoxConfig(audio_config, text_config)
         
     | 
| 87 | 
         | 
| 88 | 
         
             
                >>> # Initializing a completely untrained model from the configuration
         
     | 
| 89 | 
         
            +
                >>> model = UltravoxModel(configuration)
         
     | 
| 90 | 
         | 
| 91 | 
         
             
                >>> # Accessing the model configuration
         
     | 
| 92 | 
         
             
                >>> configuration = model.config
         
     | 
| 93 | 
         | 
| 94 | 
         
             
                >>> # Initialize a model from pretrained checkpoints and random projector weights
         
     | 
| 95 | 
         
            +
                >>> config = UltravoxConfig(audio_model_id="openai/whisper-tiny", text_model_id="meta-llama/Llama-2-7b-chat-hf")
         
     | 
| 96 | 
         
             
                ```"""
         
     | 
| 97 | 
         | 
| 98 | 
         
             
                model_type = "ultravox"
         
     | 
| 
         | 
|
| 105 | 
         
             
                    audio_model_id: Optional[str] = None,
         
     | 
| 106 | 
         
             
                    text_model_id: Optional[str] = None,
         
     | 
| 107 | 
         
             
                    ignore_index: int = -100,
         
     | 
| 
         | 
|
| 108 | 
         
             
                    hidden_size: int = 4096,
         
     | 
| 109 | 
         
             
                    stack_factor: int = 8,
         
     | 
| 110 | 
         
             
                    norm_init: float = 0.4,
         
     | 
| 111 | 
         
             
                    projector_act: str = "swiglu",
         
     | 
| 112 | 
         
            +
                    projector_ln_mid: bool = False,  # defaults to False for compatibility with v0.4.1 and below
         
     | 
| 113 | 
         
             
                    text_model_lora_config: Optional[LoraConfigSimplified] = None,
         
     | 
| 114 | 
         
             
                    audio_model_lora_config: Optional[LoraConfigSimplified] = None,
         
     | 
| 115 | 
         
            +
                    audio_latency_block_size: Optional[int] = None,
         
     | 
| 116 | 
         
             
                    **kwargs,
         
     | 
| 117 | 
         
             
                ):
         
     | 
| 118 | 
         
             
                    self.ignore_index = ignore_index
         
     | 
| 119 | 
         | 
| 120 | 
         
             
                    self.audio_model_id = audio_model_id
         
     | 
| 121 | 
         
             
                    self.text_model_id = text_model_id
         
     | 
| 
         | 
|
| 122 | 
         | 
| 123 | 
         
             
                    self.hidden_size = hidden_size
         
     | 
| 124 | 
         
             
                    self.stack_factor = stack_factor
         
     | 
| 125 | 
         
             
                    self.norm_init = norm_init
         
     | 
| 126 | 
         
             
                    self.projector_act = projector_act
         
     | 
| 127 | 
         
            +
                    self.projector_ln_mid = projector_ln_mid
         
     | 
| 128 | 
         
             
                    if text_model_id is not None:
         
     | 
| 129 | 
         
             
                        self.text_config: transformers.LlamaConfig = (
         
     | 
| 130 | 
         
             
                            transformers.AutoConfig.from_pretrained(text_model_id)
         
     | 
| 
         | 
|
| 142 | 
         
             
                    else:
         
     | 
| 143 | 
         
             
                        audio_config = audio_config or {}
         
     | 
| 144 | 
         
             
                        self.audio_config = transformers.CONFIG_MAPPING[
         
     | 
| 145 | 
         
            +
                            audio_config.get("model_type", "whisper")
         
     | 
| 146 | 
         
             
                        ](**audio_config)
         
     | 
| 147 | 
         | 
| 148 | 
         
             
                    self.text_model_lora_config = (
         
     | 
| 
         | 
|
| 155 | 
         
             
                        if isinstance(audio_model_lora_config, dict)
         
     | 
| 156 | 
         
             
                        else dataclasses.asdict(audio_model_lora_config or LoraConfigSimplified())
         
     | 
| 157 | 
         
             
                    )
         
     | 
| 158 | 
         
            +
                    self.audio_latency_block_size = audio_latency_block_size
         
     | 
| 159 | 
         | 
| 160 | 
         
             
                    self.vocab_size = self.text_config.vocab_size
         
     | 
| 161 | 
         | 
| 162 | 
         
             
                    self.initializer_range = self.text_config.initializer_range
         
     | 
| 163 | 
         | 
| 164 | 
         
             
                    super().__init__(**kwargs)
         
     | 
| 165 | 
         
            +
             
     | 
| 166 | 
         
            +
                def to_diff_dict(self) -> Dict[str, Any]:
         
     | 
| 167 | 
         
            +
                    diff_dict = super().to_diff_dict()
         
     | 
| 168 | 
         
            +
             
     | 
| 169 | 
         
            +
                    # remove text_config and audio_config if text_model_id and audio_model_id are present
         
     | 
| 170 | 
         
            +
                    if self.text_model_id is not None:
         
     | 
| 171 | 
         
            +
                        diff_dict.pop("text_config", None)
         
     | 
| 172 | 
         
            +
                    elif "text_config" in diff_dict:
         
     | 
| 173 | 
         
            +
                        diff_dict["text_config"].pop("_attn_implementation_autoset", None)
         
     | 
| 174 | 
         
            +
             
     | 
| 175 | 
         
            +
                    if self.audio_model_id is not None:
         
     | 
| 176 | 
         
            +
                        diff_dict.pop("audio_config", None)
         
     | 
| 177 | 
         
            +
                    elif "audio_config" in diff_dict:
         
     | 
| 178 | 
         
            +
                        diff_dict["audio_config"].pop("_attn_implementation_autoset", None)
         
     | 
| 179 | 
         
            +
             
     | 
| 180 | 
         
            +
                    return diff_dict
         
     | 
    	
        ultravox_model.py
    CHANGED
    
    | 
         @@ -1,5 +1,6 @@ 
     | 
|
| 1 | 
         
             
            import logging
         
     | 
| 2 | 
         
            -
             
     | 
| 
         | 
|
| 3 | 
         | 
| 4 | 
         
             
            import peft
         
     | 
| 5 | 
         
             
            import torch
         
     | 
| 
         @@ -9,14 +10,17 @@ import transformers 
     | 
|
| 9 | 
         
             
            import transformers.activations
         
     | 
| 10 | 
         
             
            import transformers.modeling_outputs
         
     | 
| 11 | 
         
             
            import transformers.models
         
     | 
| 
         | 
|
| 
         | 
|
| 12 | 
         | 
| 13 | 
         
             
            # We must use relative import in this directory to allow uploading to HF Hub
         
     | 
| 14 | 
         
             
            # Even "from . import X" pattern doesn't work (undocumented and unclear why)
         
     | 
| 
         | 
|
| 
         | 
|
| 15 | 
         
             
            from .ultravox_config import UltravoxConfig
         
     | 
| 16 | 
         
            -
            from .whisper_model_modified import WhisperEncoder as ModifiedWhisperEncoder
         
     | 
| 17 | 
         | 
| 18 | 
         | 
| 19 | 
         
            -
            class UltravoxModel(transformers.LlamaPreTrainedModel):
         
     | 
| 20 | 
         
             
                """
         
     | 
| 21 | 
         
             
                The Ultravox model which consists of an audio encoder and a language model.
         
     | 
| 22 | 
         | 
| 
         @@ -32,20 +36,32 @@ class UltravoxModel(transformers.LlamaPreTrainedModel): 
     | 
|
| 32 | 
         | 
| 33 | 
         
             
                config_class = UltravoxConfig
         
     | 
| 34 | 
         
             
                config: UltravoxConfig  # for type hinting
         
     | 
| 35 | 
         
            -
                 
     | 
| 36 | 
         
            -
                _keys_to_ignore_on_load_missing = ["audio_tower.*"]
         
     | 
| 37 | 
         
            -
                 
     | 
| 
         | 
|
| 
         | 
|
| 38 | 
         | 
| 39 | 
         
             
                def __init__(self, config: UltravoxConfig):
         
     | 
| 40 | 
         
             
                    super().__init__(config)
         
     | 
| 
         | 
|
| 41 | 
         | 
| 42 | 
         
             
                    self.keep_params: Set[str] = set()
         
     | 
| 43 | 
         
             
                    self.vocab_size = config.vocab_size
         
     | 
| 44 | 
         | 
| 45 | 
         
             
                    self.audio_tower = self._create_audio_tower(config)
         
     | 
| 46 | 
         
            -
                    self. 
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 47 | 
         
             
                    self.language_model = self._create_language_model(config)
         
     | 
| 48 | 
         | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 49 | 
         
             
                    self.post_init()
         
     | 
| 50 | 
         | 
| 51 | 
         
             
                def get_input_embeddings(self):
         
     | 
| 
         @@ -69,6 +85,9 @@ class UltravoxModel(transformers.LlamaPreTrainedModel): 
     | 
|
| 69 | 
         
             
                def tie_weights(self):
         
     | 
| 70 | 
         
             
                    return self.language_model.tie_weights()
         
     | 
| 71 | 
         | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 72 | 
         
             
                def _setup_cache(
         
     | 
| 73 | 
         
             
                    self, cache_cls, max_batch_size: int, max_cache_len: Optional[int] = None
         
     | 
| 74 | 
         
             
                ):
         
     | 
| 
         @@ -91,6 +110,60 @@ class UltravoxModel(transformers.LlamaPreTrainedModel): 
     | 
|
| 91 | 
         
             
                    self.vocab_size = model_embeds.num_embeddings
         
     | 
| 92 | 
         
             
                    return model_embeds
         
     | 
| 93 | 
         | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 94 | 
         
             
                def forward(
         
     | 
| 95 | 
         
             
                    self,
         
     | 
| 96 | 
         
             
                    input_ids: torch.Tensor,
         
     | 
| 
         @@ -99,8 +172,14 @@ class UltravoxModel(transformers.LlamaPreTrainedModel): 
     | 
|
| 99 | 
         
             
                    labels: Optional[torch.Tensor] = None,
         
     | 
| 100 | 
         
             
                    attention_mask: Optional[torch.Tensor] = None,
         
     | 
| 101 | 
         
             
                    audio_token_start_idx: Optional[torch.Tensor] = None,
         
     | 
| 
         | 
|
| 102 | 
         
             
                    audio_token_len: Optional[torch.Tensor] = None,
         
     | 
| 
         | 
|
| 103 | 
         
             
                    past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 104 | 
         
             
                    **kwargs,
         
     | 
| 105 | 
         
             
                ) -> Union[Tuple, transformers.modeling_outputs.CausalLMOutputWithPast]:
         
     | 
| 106 | 
         
             
                    """
         
     | 
| 
         @@ -126,28 +205,37 @@ class UltravoxModel(transformers.LlamaPreTrainedModel): 
     | 
|
| 126 | 
         
             
                        # B x T  ->  B x T x D
         
     | 
| 127 | 
         
             
                        inputs_embeds = self.get_input_embeddings().forward(input_ids)
         
     | 
| 128 | 
         | 
| 129 | 
         
            -
                    if audio_values is not None:
         
     | 
| 130 | 
         
             
                        assert (
         
     | 
| 131 | 
         
            -
                            audio_token_start_idx is not None 
     | 
| 132 | 
         
            -
             
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 133 | 
         
             
                        assert (
         
     | 
| 134 | 
         
            -
                            len(audio_token_start_idx) 
     | 
| 135 | 
         
            -
             
     | 
| 136 | 
         
            -
             
     | 
| 137 | 
         
            -
             
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 138 | 
         
             
                        audio_tower_output = self.audio_tower.forward(
         
     | 
| 139 | 
         
            -
                            audio_values
         
     | 
| 
         | 
|
| 140 | 
         
             
                        ).last_hidden_state
         
     | 
| 141 | 
         
             
                        audio_tower_output = audio_tower_output.to(inputs_embeds.dtype)
         
     | 
| 142 | 
         
            -
             
     | 
| 143 | 
         
             
                        audio_embeds = self.multi_modal_projector.forward(audio_tower_output)
         
     | 
| 144 | 
         | 
| 145 | 
         
             
                        # combine audio and text embeddings
         
     | 
| 146 | 
         
            -
                        for  
     | 
| 147 | 
         
            -
                             
     | 
| 148 | 
         
            -
             
     | 
| 149 | 
         
            -
                             
     | 
| 150 | 
         
            -
                            inputs_embeds[ 
     | 
| 151 | 
         | 
| 152 | 
         
             
                    lm_output = self.language_model.forward(
         
     | 
| 153 | 
         
             
                        inputs_embeds=inputs_embeds,
         
     | 
| 
         @@ -156,8 +244,25 @@ class UltravoxModel(transformers.LlamaPreTrainedModel): 
     | 
|
| 156 | 
         
             
                        past_key_values=past_key_values,
         
     | 
| 157 | 
         
             
                        **kwargs,
         
     | 
| 158 | 
         
             
                    )
         
     | 
| 159 | 
         
            -
             
     | 
| 160 | 
         
            -
             
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 161 | 
         | 
| 162 | 
         
             
                def prepare_inputs_for_generation(
         
     | 
| 163 | 
         
             
                    self,
         
     | 
| 
         @@ -165,9 +270,12 @@ class UltravoxModel(transformers.LlamaPreTrainedModel): 
     | 
|
| 165 | 
         
             
                    audio_values: Optional[torch.FloatTensor] = None,
         
     | 
| 166 | 
         
             
                    audio_token_start_idx: Optional[torch.Tensor] = None,
         
     | 
| 167 | 
         
             
                    audio_token_len: Optional[torch.Tensor] = None,
         
     | 
| 
         | 
|
| 
         | 
|
| 168 | 
         
             
                    past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
         
     | 
| 169 | 
         
             
                    attention_mask: Optional[torch.Tensor] = None,
         
     | 
| 170 | 
         
             
                    inputs_embeds: Optional[torch.Tensor] = None,
         
     | 
| 
         | 
|
| 171 | 
         
             
                    **kwargs,
         
     | 
| 172 | 
         
             
                ) -> Dict[str, Any]:
         
     | 
| 173 | 
         
             
                    model_input = self.language_model.prepare_inputs_for_generation(
         
     | 
| 
         @@ -175,35 +283,73 @@ class UltravoxModel(transformers.LlamaPreTrainedModel): 
     | 
|
| 175 | 
         
             
                        past_key_values=past_key_values,
         
     | 
| 176 | 
         
             
                        attention_mask=attention_mask,
         
     | 
| 177 | 
         
             
                        inputs_embeds=inputs_embeds,
         
     | 
| 
         | 
|
| 178 | 
         
             
                        **kwargs,
         
     | 
| 179 | 
         
             
                    )
         
     | 
| 180 | 
         | 
| 181 | 
         
            -
                     
     | 
| 182 | 
         
            -
             
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 183 | 
         
             
                        model_input["audio_values"] = audio_values
         
     | 
| 184 | 
         
            -
                        model_input["audio_token_start_idx"] =  
     | 
| 
         | 
|
| 
         | 
|
| 185 | 
         
             
                        model_input["audio_token_len"] = audio_token_len
         
     | 
| 
         | 
|
| 
         | 
|
| 186 | 
         | 
| 187 | 
         
             
                    return model_input
         
     | 
| 188 | 
         | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 189 | 
         
             
                @classmethod
         
     | 
| 190 | 
         
             
                def _create_audio_tower(
         
     | 
| 191 | 
         
             
                    cls, config: UltravoxConfig
         
     | 
| 192 | 
         
            -
                ) -> Union[transformers.Wav2Vec2Model, ModifiedWhisperEncoder]:
         
     | 
| 193 | 
         
             
                    if config.audio_model_id is not None:
         
     | 
| 194 | 
         
            -
                        if "whisper" in config.audio_model_id 
     | 
| 195 | 
         
             
                            audio_tower = ModifiedWhisperEncoder.from_pretrained(
         
     | 
| 196 | 
         
            -
                                config.audio_model_id
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 197 | 
         
             
                            )
         
     | 
| 198 | 
         
             
                        else:
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 199 | 
         
             
                            audio_tower = transformers.AutoModel.from_pretrained(
         
     | 
| 200 | 
         
            -
                                config.audio_model_id
         
     | 
| 201 | 
         
             
                            )
         
     | 
| 202 | 
         
             
                    else:
         
     | 
| 203 | 
         
            -
                        if "whisper" in config.audio_config._name_or_path:
         
     | 
| 204 | 
         
             
                            audio_tower = ModifiedWhisperEncoder(config.audio_config)
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 205 | 
         
             
                        else:
         
     | 
| 206 | 
         
            -
                             
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 207 | 
         | 
| 208 | 
         
             
                    if isinstance(
         
     | 
| 209 | 
         
             
                        audio_tower,
         
     | 
| 
         @@ -223,12 +369,19 @@ class UltravoxModel(transformers.LlamaPreTrainedModel): 
     | 
|
| 223 | 
         
             
                ) -> transformers.LlamaForCausalLM:
         
     | 
| 224 | 
         
             
                    if config.text_model_id is not None:
         
     | 
| 225 | 
         
             
                        language_model = transformers.AutoModelForCausalLM.from_pretrained(
         
     | 
| 226 | 
         
            -
                            config.text_model_id, 
     | 
| 
         | 
|
| 
         | 
|
| 227 | 
         
             
                        )
         
     | 
| 228 | 
         
             
                    else:
         
     | 
| 229 | 
         
            -
                         
     | 
| 230 | 
         
            -
                             
     | 
| 231 | 
         
            -
             
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 232 | 
         | 
| 233 | 
         
             
                    language_model = apply_lora(language_model, config.text_model_lora_config)
         
     | 
| 234 | 
         
             
                    return language_model
         
     | 
| 
         @@ -266,29 +419,38 @@ class UltravoxModel(transformers.LlamaPreTrainedModel): 
     | 
|
| 266 | 
         | 
| 267 | 
         
             
                def push_to_hub(self, *args, **kwargs):
         
     | 
| 268 | 
         
             
                    self.merge_and_unload()
         
     | 
| 269 | 
         
            -
                    self.to(self.language_model.dtype)
         
     | 
| 270 | 
         
             
                    return super().push_to_hub(*args, **kwargs)
         
     | 
| 271 | 
         | 
| 272 | 
         
            -
                def  
     | 
| 273 | 
         
            -
                     
     | 
| 274 | 
         
            -
             
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 275 | 
         | 
| 276 | 
         
             
                    state_dict = {
         
     | 
| 277 | 
         
             
                        k: v
         
     | 
| 278 | 
         
             
                        for k, v in state_dict.items()
         
     | 
| 279 | 
         
            -
                        if k in self.keep_params
         
     | 
| 280 | 
         
            -
                        or (k in named_params and named_params[k].requires_grad)
         
     | 
| 281 | 
         
             
                    }
         
     | 
| 
         | 
|
| 282 | 
         
             
                    return state_dict
         
     | 
| 283 | 
         | 
| 284 | 
         
            -
                def  
     | 
| 285 | 
         
            -
                    self,
         
     | 
| 286 | 
         
            -
                    state_dict: Dict[str, Any],
         
     | 
| 287 | 
         
            -
                    *args,
         
     | 
| 288 | 
         
            -
                    **kwargs,
         
     | 
| 289 | 
         
             
                ):
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 290 | 
         
             
                    self.keep_params.update(set(state_dict.keys()))
         
     | 
| 291 | 
         
            -
                    return super().load_state_dict(state_dict, *args, **kwargs)
         
     | 
| 292 | 
         | 
| 293 | 
         
             
                def print_trainable_parameters(self):
         
     | 
| 294 | 
         
             
                    """
         
     | 
| 
         @@ -319,8 +481,9 @@ class UltravoxModel(transformers.LlamaPreTrainedModel): 
     | 
|
| 319 | 
         
             
                    )
         
     | 
| 320 | 
         | 
| 321 | 
         | 
| 
         | 
|
| 322 | 
         
             
            def is_cache_empty(
         
     | 
| 323 | 
         
            -
                past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]]
         
     | 
| 324 | 
         
             
            ) -> bool:
         
     | 
| 325 | 
         
             
                """
         
     | 
| 326 | 
         
             
                Check if the cache is empty.
         
     | 
| 
         @@ -336,12 +499,18 @@ def apply_lora(model: torch.nn.Module, lora_config: dict) -> torch.nn.Module: 
     | 
|
| 336 | 
         
             
                """
         
     | 
| 337 | 
         
             
                Applies LoRA finetuning to the model. If the `r` parameter is set to 0, the model is frozen instead.
         
     | 
| 338 | 
         
             
                """
         
     | 
| 
         | 
|
| 339 | 
         
             
                lora_config = peft.LoraConfig(**lora_config or {})
         
     | 
| 340 | 
         | 
| 341 | 
         
             
                if lora_config.r == 0:
         
     | 
| 342 | 
         
            -
                    # freeze the model entirely
         
     | 
| 343 | 
         
            -
                    for param in model. 
     | 
| 344 | 
         
            -
                         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 345 | 
         
             
                else:
         
     | 
| 346 | 
         
             
                    model = peft.get_peft_model(model, lora_config)
         
     | 
| 347 | 
         | 
| 
         @@ -350,12 +519,8 @@ def apply_lora(model: torch.nn.Module, lora_config: dict) -> torch.nn.Module: 
     | 
|
| 350 | 
         | 
| 351 | 
         
             
            class StackAudioFrames(nn.Module):
         
     | 
| 352 | 
         
             
                """
         
     | 
| 353 | 
         
            -
                Stack the audio embedding frames to reduce the sequence length by a factor 
     | 
| 354 | 
         
            -
             
     | 
| 355 | 
         
            -
                The number of output frames will be `ceil(T / stack_factor) + 1` where `T` is the number of input frames.
         
     | 
| 356 | 
         
            -
                NOTE: the extra +1 is intentional: in case the number of audio tokens are over-estimated by the processor,
         
     | 
| 357 | 
         
            -
                we want to make sure `processor.audio_token_replacement` (i.e. EOS) doesn't get leaked into the middle of embeddings.
         
     | 
| 358 | 
         
            -
                In most cases this extra padding will get removed in the model's forward function so it has no effect.
         
     | 
| 359 | 
         
             
                """
         
     | 
| 360 | 
         | 
| 361 | 
         
             
                def __init__(self, stack_factor: int = 8):
         
     | 
| 
         @@ -365,7 +530,7 @@ class StackAudioFrames(nn.Module): 
     | 
|
| 365 | 
         
             
                def forward(self, audio_embeds: torch.Tensor) -> torch.Tensor:
         
     | 
| 366 | 
         
             
                    B, T, C = audio_embeds.shape
         
     | 
| 367 | 
         
             
                    T_pad = (T + self.stack_factor - 1) // self.stack_factor * self.stack_factor
         
     | 
| 368 | 
         
            -
                    audio_embeds = F.pad(audio_embeds, (0, 0, 0, T_pad - T 
     | 
| 369 | 
         
             
                    B, T, C = audio_embeds.shape
         
     | 
| 370 | 
         
             
                    audio_embeds = audio_embeds.view(
         
     | 
| 371 | 
         
             
                        B, T // self.stack_factor, C * self.stack_factor
         
     | 
| 
         @@ -385,35 +550,235 @@ class SwiGLU(nn.Module): 
     | 
|
| 385 | 
         
             
                    return F.silu(gate) * x
         
     | 
| 386 | 
         | 
| 387 | 
         | 
| 388 | 
         
            -
            class UltravoxProjector(nn. 
     | 
| 389 | 
         
             
                def __init__(self, config: UltravoxConfig):
         
     | 
| 390 | 
         
             
                    super().__init__()
         
     | 
| 391 | 
         
             
                    self.hidden_dim = config.hidden_size
         
     | 
| 392 | 
         
             
                    self._pad_and_stack = StackAudioFrames(config.stack_factor)
         
     | 
| 393 | 
         
            -
                     
     | 
| 394 | 
         
            -
                    self.ln_pre = RMSNorm( 
     | 
| 395 | 
         
            -
                    self.linear_1 = nn.Linear( 
     | 
| 396 | 
         
            -
                     
     | 
| 397 | 
         
             
                    self.act = transformers.activations.get_activation(config.projector_act)
         
     | 
| 398 | 
         
            -
                     
     | 
| 399 | 
         
            -
                     
     | 
| 400 | 
         
            -
                    self. 
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 401 | 
         | 
| 402 | 
         
             
                def forward(self, audio_features: torch.Tensor) -> torch.Tensor:
         
     | 
| 403 | 
         
             
                    audio_features = self._pad_and_stack(audio_features)
         
     | 
| 404 | 
         
             
                    audio_features = self.ln_pre(audio_features)
         
     | 
| 405 | 
         
             
                    hidden_states = self.linear_1(audio_features)
         
     | 
| 406 | 
         
             
                    hidden_states = self.act(hidden_states)
         
     | 
| 
         | 
|
| 407 | 
         
             
                    hidden_states = self.linear_2(hidden_states)
         
     | 
| 408 | 
         
             
                    hidden_states = self.ln_post(hidden_states)
         
     | 
| 409 | 
         
             
                    return hidden_states
         
     | 
| 410 | 
         | 
| 411 | 
         | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 412 | 
         
             
            UltravoxConfig.register_for_auto_class()
         
     | 
| 413 | 
         
             
            UltravoxModel.register_for_auto_class()
         
     | 
| 414 | 
         | 
| 415 | 
         
             
            transformers.AutoConfig.register("ultravox", UltravoxConfig)
         
     | 
| 416 | 
         
             
            transformers.AutoModel.register(UltravoxConfig, UltravoxModel)
         
     | 
| 417 | 
         
            -
            # transformers.AutoProcessor.register(UltravoxConfig, UltravoxProcessor)  # TODO: make processor work standalone
         
     | 
| 418 | 
         | 
| 419 | 
         
             
            transformers.activations.ACT2FN["swiglu"] = SwiGLU
         
     | 
| 
         | 
|
| 1 | 
         
             
            import logging
         
     | 
| 2 | 
         
            +
            import re
         
     | 
| 3 | 
         
            +
            from typing import Any, Dict, Generator, Optional, Set, Tuple, Union
         
     | 
| 4 | 
         | 
| 5 | 
         
             
            import peft
         
     | 
| 6 | 
         
             
            import torch
         
     | 
| 
         | 
|
| 10 | 
         
             
            import transformers.activations
         
     | 
| 11 | 
         
             
            import transformers.modeling_outputs
         
     | 
| 12 | 
         
             
            import transformers.models
         
     | 
| 13 | 
         
            +
            from transformers.generation.utils import GenerationMixin
         
     | 
| 14 | 
         
            +
            from transformers.models.whisper import modeling_whisper as whisper
         
     | 
| 15 | 
         | 
| 16 | 
         
             
            # We must use relative import in this directory to allow uploading to HF Hub
         
     | 
| 17 | 
         
             
            # Even "from . import X" pattern doesn't work (undocumented and unclear why)
         
     | 
| 18 | 
         
            +
            from .ultravox_config import LossConfig
         
     | 
| 19 | 
         
            +
            from .ultravox_config import LossFunction
         
     | 
| 20 | 
         
             
            from .ultravox_config import UltravoxConfig
         
     | 
| 
         | 
|
| 21 | 
         | 
| 22 | 
         | 
| 23 | 
         
            +
            class UltravoxModel(transformers.LlamaPreTrainedModel, GenerationMixin):
         
     | 
| 24 | 
         
             
                """
         
     | 
| 25 | 
         
             
                The Ultravox model which consists of an audio encoder and a language model.
         
     | 
| 26 | 
         | 
| 
         | 
|
| 36 | 
         | 
| 37 | 
         
             
                config_class = UltravoxConfig
         
     | 
| 38 | 
         
             
                config: UltravoxConfig  # for type hinting
         
     | 
| 39 | 
         
            +
                # Usually we load encoder and LLM weights from a pretrained model separately, so they are allowed to be missing
         
     | 
| 40 | 
         
            +
                _keys_to_ignore_on_load_missing = ["audio_tower.*", "language_model.*"]
         
     | 
| 41 | 
         
            +
                # Since we have kwargs in forward, we need to set this to False, otherwise grad_accum_steps will cause incorrect train loss to be reported
         
     | 
| 42 | 
         
            +
                # see https://github.com/huggingface/transformers/issues/35856 and https://github.com/huggingface/trl/pull/2615/files
         
     | 
| 43 | 
         
            +
                accepts_loss_kwargs = False
         
     | 
| 44 | 
         | 
| 45 | 
         
             
                def __init__(self, config: UltravoxConfig):
         
     | 
| 46 | 
         
             
                    super().__init__(config)
         
     | 
| 47 | 
         
            +
                    self._register_load_state_dict_pre_hook(self._pre_load_state_dict_hook)
         
     | 
| 48 | 
         | 
| 49 | 
         
             
                    self.keep_params: Set[str] = set()
         
     | 
| 50 | 
         
             
                    self.vocab_size = config.vocab_size
         
     | 
| 51 | 
         | 
| 52 | 
         
             
                    self.audio_tower = self._create_audio_tower(config)
         
     | 
| 53 | 
         
            +
                    self.audio_tower_context_length: Optional[int] = None
         
     | 
| 54 | 
         
            +
                    self.audio_tower_context_length = self.audio_tower.max_context_length
         
     | 
| 55 | 
         
            +
             
     | 
| 56 | 
         
            +
                    self.multi_modal_projector = self._create_multi_modal_projector(config)
         
     | 
| 57 | 
         
             
                    self.language_model = self._create_language_model(config)
         
     | 
| 58 | 
         | 
| 59 | 
         
            +
                    # Determine no_split_modules dynamically to use with FSDP auto_wrap policy.
         
     | 
| 60 | 
         
            +
                    # FSDP throws an error if some of the layer types are not found in the model.
         
     | 
| 61 | 
         
            +
                    # This would be something like ["LlamaDecoderLayer"] as we don't split audio encoder layers.
         
     | 
| 62 | 
         
            +
                    self._no_split_modules = self.language_model._no_split_modules
         
     | 
| 63 | 
         
            +
             
     | 
| 64 | 
         
            +
                    self.loss_config = LossConfig()
         
     | 
| 65 | 
         
             
                    self.post_init()
         
     | 
| 66 | 
         | 
| 67 | 
         
             
                def get_input_embeddings(self):
         
     | 
| 
         | 
|
| 85 | 
         
             
                def tie_weights(self):
         
     | 
| 86 | 
         
             
                    return self.language_model.tie_weights()
         
     | 
| 87 | 
         | 
| 88 | 
         
            +
                def set_loss_config(self, loss_config: LossConfig):
         
     | 
| 89 | 
         
            +
                    self.loss_config = loss_config
         
     | 
| 90 | 
         
            +
             
     | 
| 91 | 
         
             
                def _setup_cache(
         
     | 
| 92 | 
         
             
                    self, cache_cls, max_batch_size: int, max_cache_len: Optional[int] = None
         
     | 
| 93 | 
         
             
                ):
         
     | 
| 
         | 
|
| 110 | 
         
             
                    self.vocab_size = model_embeds.num_embeddings
         
     | 
| 111 | 
         
             
                    return model_embeds
         
     | 
| 112 | 
         | 
| 113 | 
         
            +
                def _compute_kl_loss(
         
     | 
| 114 | 
         
            +
                    self,
         
     | 
| 115 | 
         
            +
                    lm_output: transformers.modeling_outputs.CausalLMOutputWithPast,
         
     | 
| 116 | 
         
            +
                    labels: Optional[torch.Tensor] = None,
         
     | 
| 117 | 
         
            +
                    past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
         
     | 
| 118 | 
         
            +
                    alt_input_ids: Optional[torch.Tensor] = None,
         
     | 
| 119 | 
         
            +
                    alt_attention_mask: Optional[torch.Tensor] = None,
         
     | 
| 120 | 
         
            +
                    alt_labels: Optional[torch.Tensor] = None,
         
     | 
| 121 | 
         
            +
                    **kwargs,
         
     | 
| 122 | 
         
            +
                ):
         
     | 
| 123 | 
         
            +
                    # disable gradient computation for the teacher model
         
     | 
| 124 | 
         
            +
                    with torch.no_grad():
         
     | 
| 125 | 
         
            +
                        # compute the teacher (text-only) model's distribution
         
     | 
| 126 | 
         
            +
                        alt_inputs_embeds = self.get_input_embeddings().forward(alt_input_ids)
         
     | 
| 127 | 
         
            +
                        alt_lm_output = self.language_model.forward(
         
     | 
| 128 | 
         
            +
                            inputs_embeds=alt_inputs_embeds,
         
     | 
| 129 | 
         
            +
                            labels=alt_labels,
         
     | 
| 130 | 
         
            +
                            attention_mask=alt_attention_mask,
         
     | 
| 131 | 
         
            +
                            past_key_values=past_key_values,
         
     | 
| 132 | 
         
            +
                            **kwargs,
         
     | 
| 133 | 
         
            +
                        )
         
     | 
| 134 | 
         
            +
                    # compute the KL divergence loss between the two models
         
     | 
| 135 | 
         
            +
                    kl_loss = F.kl_div(
         
     | 
| 136 | 
         
            +
                        F.log_softmax(
         
     | 
| 137 | 
         
            +
                            lm_output.logits[labels != -100] / self.loss_config.kl_temperature,
         
     | 
| 138 | 
         
            +
                            dim=-1,
         
     | 
| 139 | 
         
            +
                        ),
         
     | 
| 140 | 
         
            +
                        F.softmax(
         
     | 
| 141 | 
         
            +
                            alt_lm_output.logits[alt_labels != -100]
         
     | 
| 142 | 
         
            +
                            / self.loss_config.kl_temperature,
         
     | 
| 143 | 
         
            +
                            dim=-1,
         
     | 
| 144 | 
         
            +
                        ),
         
     | 
| 145 | 
         
            +
                        reduction="batchmean",
         
     | 
| 146 | 
         
            +
                    )
         
     | 
| 147 | 
         
            +
                    return {"loss": kl_loss}
         
     | 
| 148 | 
         
            +
             
     | 
| 149 | 
         
            +
                def _audio_iter(
         
     | 
| 150 | 
         
            +
                    self, audio_batch_size: torch.Tensor
         
     | 
| 151 | 
         
            +
                ) -> Generator[Tuple[int, int], None, None]:
         
     | 
| 152 | 
         
            +
                    """
         
     | 
| 153 | 
         
            +
                    Iterate over the audio batch size and yield the batch index and audio index of each audio item.
         
     | 
| 154 | 
         
            +
             
     | 
| 155 | 
         
            +
                    Args:
         
     | 
| 156 | 
         
            +
                        audio_batch_size: A tensor of shape (B,) where B is the batch size.
         
     | 
| 157 | 
         
            +
             
     | 
| 158 | 
         
            +
                    Returns:
         
     | 
| 159 | 
         
            +
                        A generator that yields a tuple of (start index, length) for each audio item.
         
     | 
| 160 | 
         
            +
                    """
         
     | 
| 161 | 
         
            +
                    audio_index = 0
         
     | 
| 162 | 
         
            +
                    for i_b, batch_count in enumerate(audio_batch_size):
         
     | 
| 163 | 
         
            +
                        for _ in range(batch_count):
         
     | 
| 164 | 
         
            +
                            yield i_b, audio_index
         
     | 
| 165 | 
         
            +
                            audio_index += 1
         
     | 
| 166 | 
         
            +
             
     | 
| 167 | 
         
             
                def forward(
         
     | 
| 168 | 
         
             
                    self,
         
     | 
| 169 | 
         
             
                    input_ids: torch.Tensor,
         
     | 
| 
         | 
|
| 172 | 
         
             
                    labels: Optional[torch.Tensor] = None,
         
     | 
| 173 | 
         
             
                    attention_mask: Optional[torch.Tensor] = None,
         
     | 
| 174 | 
         
             
                    audio_token_start_idx: Optional[torch.Tensor] = None,
         
     | 
| 175 | 
         
            +
                    audio_lens: Optional[torch.Tensor] = None,
         
     | 
| 176 | 
         
             
                    audio_token_len: Optional[torch.Tensor] = None,
         
     | 
| 177 | 
         
            +
                    audio_batch_size: Optional[torch.Tensor] = None,
         
     | 
| 178 | 
         
             
                    past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
         
     | 
| 179 | 
         
            +
                    # the alt_* fields are needed for KL divergence loss
         
     | 
| 180 | 
         
            +
                    alt_input_ids: Optional[torch.Tensor] = None,
         
     | 
| 181 | 
         
            +
                    alt_attention_mask: Optional[torch.Tensor] = None,
         
     | 
| 182 | 
         
            +
                    alt_labels: Optional[torch.Tensor] = None,
         
     | 
| 183 | 
         
             
                    **kwargs,
         
     | 
| 184 | 
         
             
                ) -> Union[Tuple, transformers.modeling_outputs.CausalLMOutputWithPast]:
         
     | 
| 185 | 
         
             
                    """
         
     | 
| 
         | 
|
| 205 | 
         
             
                        # B x T  ->  B x T x D
         
     | 
| 206 | 
         
             
                        inputs_embeds = self.get_input_embeddings().forward(input_ids)
         
     | 
| 207 | 
         | 
| 208 | 
         
            +
                    if audio_values is not None and len(audio_values) > 0:
         
     | 
| 209 | 
         
             
                        assert (
         
     | 
| 210 | 
         
            +
                            audio_token_start_idx is not None
         
     | 
| 211 | 
         
            +
                            and audio_token_len is not None
         
     | 
| 212 | 
         
            +
                            and audio_lens is not None
         
     | 
| 213 | 
         
            +
                            and audio_batch_size is not None
         
     | 
| 214 | 
         
            +
                        ), "audio_token_start_idx/audio_token_len/audio_lens must be provided if audio_values are provided."
         
     | 
| 215 | 
         
             
                        assert (
         
     | 
| 216 | 
         
            +
                            len(audio_token_start_idx)
         
     | 
| 217 | 
         
            +
                            == len(audio_token_len)
         
     | 
| 218 | 
         
            +
                            == len(audio_lens)
         
     | 
| 219 | 
         
            +
                            == len(audio_values)
         
     | 
| 220 | 
         
            +
                        ), "audio_token_start_idx/audio_token_len/audio_lens/audio_values must have the same batch size."
         
     | 
| 221 | 
         
            +
                        assert len(audio_batch_size) == len(
         
     | 
| 222 | 
         
            +
                            inputs_embeds
         
     | 
| 223 | 
         
            +
                        ), "audio_batch_size and inputs_embeds must have the same batch size."
         
     | 
| 224 | 
         
            +
             
     | 
| 225 | 
         
            +
                        # B x A/3200 x (D=max-audio-length-in-batch)
         
     | 
| 226 | 
         
             
                        audio_tower_output = self.audio_tower.forward(
         
     | 
| 227 | 
         
            +
                            audio_values.to(self.audio_tower.dtype),
         
     | 
| 228 | 
         
            +
                            audio_len=audio_lens,
         
     | 
| 229 | 
         
             
                        ).last_hidden_state
         
     | 
| 230 | 
         
             
                        audio_tower_output = audio_tower_output.to(inputs_embeds.dtype)
         
     | 
| 
         | 
|
| 231 | 
         
             
                        audio_embeds = self.multi_modal_projector.forward(audio_tower_output)
         
     | 
| 232 | 
         | 
| 233 | 
         
             
                        # combine audio and text embeddings
         
     | 
| 234 | 
         
            +
                        for i_b, i_a in self._audio_iter(audio_batch_size):
         
     | 
| 235 | 
         
            +
                            start_idx = audio_token_start_idx[i_a]
         
     | 
| 236 | 
         
            +
                            token_len = audio_token_len[i_a]
         
     | 
| 237 | 
         
            +
                            item_embedding = audio_embeds[i_a][:token_len]
         
     | 
| 238 | 
         
            +
                            inputs_embeds[i_b][start_idx : start_idx + token_len] = item_embedding
         
     | 
| 239 | 
         | 
| 240 | 
         
             
                    lm_output = self.language_model.forward(
         
     | 
| 241 | 
         
             
                        inputs_embeds=inputs_embeds,
         
     | 
| 
         | 
|
| 244 | 
         
             
                        past_key_values=past_key_values,
         
     | 
| 245 | 
         
             
                        **kwargs,
         
     | 
| 246 | 
         
             
                    )
         
     | 
| 247 | 
         
            +
                    if self.training:
         
     | 
| 248 | 
         
            +
                        if self.loss_config.loss_function == LossFunction.CrossEntropy:
         
     | 
| 249 | 
         
            +
                            return lm_output
         
     | 
| 250 | 
         
            +
                        elif self.loss_config.loss_function == LossFunction.KL_Divergence:
         
     | 
| 251 | 
         
            +
                            return self._compute_kl_loss(
         
     | 
| 252 | 
         
            +
                                lm_output=lm_output,
         
     | 
| 253 | 
         
            +
                                labels=labels,
         
     | 
| 254 | 
         
            +
                                past_key_values=past_key_values,
         
     | 
| 255 | 
         
            +
                                alt_input_ids=alt_input_ids,
         
     | 
| 256 | 
         
            +
                                alt_attention_mask=alt_attention_mask,
         
     | 
| 257 | 
         
            +
                                alt_labels=alt_labels,
         
     | 
| 258 | 
         
            +
                                **kwargs,
         
     | 
| 259 | 
         
            +
                            )
         
     | 
| 260 | 
         
            +
                        else:
         
     | 
| 261 | 
         
            +
                            raise ValueError(
         
     | 
| 262 | 
         
            +
                                f"Unsupported loss function: {self.loss_config.loss_function}"
         
     | 
| 263 | 
         
            +
                            )
         
     | 
| 264 | 
         
            +
                    else:
         
     | 
| 265 | 
         
            +
                        return lm_output
         
     | 
| 266 | 
         | 
| 267 | 
         
             
                def prepare_inputs_for_generation(
         
     | 
| 268 | 
         
             
                    self,
         
     | 
| 
         | 
|
| 270 | 
         
             
                    audio_values: Optional[torch.FloatTensor] = None,
         
     | 
| 271 | 
         
             
                    audio_token_start_idx: Optional[torch.Tensor] = None,
         
     | 
| 272 | 
         
             
                    audio_token_len: Optional[torch.Tensor] = None,
         
     | 
| 273 | 
         
            +
                    audio_lens: Optional[torch.Tensor] = None,
         
     | 
| 274 | 
         
            +
                    audio_batch_size: Optional[torch.Tensor] = None,
         
     | 
| 275 | 
         
             
                    past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]] = None,
         
     | 
| 276 | 
         
             
                    attention_mask: Optional[torch.Tensor] = None,
         
     | 
| 277 | 
         
             
                    inputs_embeds: Optional[torch.Tensor] = None,
         
     | 
| 278 | 
         
            +
                    cache_position: Optional[torch.Tensor] = None,
         
     | 
| 279 | 
         
             
                    **kwargs,
         
     | 
| 280 | 
         
             
                ) -> Dict[str, Any]:
         
     | 
| 281 | 
         
             
                    model_input = self.language_model.prepare_inputs_for_generation(
         
     | 
| 
         | 
|
| 283 | 
         
             
                        past_key_values=past_key_values,
         
     | 
| 284 | 
         
             
                        attention_mask=attention_mask,
         
     | 
| 285 | 
         
             
                        inputs_embeds=inputs_embeds,
         
     | 
| 286 | 
         
            +
                        cache_position=cache_position,
         
     | 
| 287 | 
         
             
                        **kwargs,
         
     | 
| 288 | 
         
             
                    )
         
     | 
| 289 | 
         | 
| 290 | 
         
            +
                    # include audio information in model_input only when it is needed during prefilling
         
     | 
| 291 | 
         
            +
                    # audio_token_start_idx should always be relative to the current cache position
         
     | 
| 292 | 
         
            +
                    prefill_start_idx = 0 if cache_position is None else cache_position[0]
         
     | 
| 293 | 
         
            +
                    if (
         
     | 
| 294 | 
         
            +
                        audio_values is not None
         
     | 
| 295 | 
         
            +
                        and audio_token_start_idx is not None
         
     | 
| 296 | 
         
            +
                        and prefill_start_idx <= torch.max(audio_token_start_idx)
         
     | 
| 297 | 
         
            +
                    ):
         
     | 
| 298 | 
         
             
                        model_input["audio_values"] = audio_values
         
     | 
| 299 | 
         
            +
                        model_input["audio_token_start_idx"] = (
         
     | 
| 300 | 
         
            +
                            audio_token_start_idx - prefill_start_idx
         
     | 
| 301 | 
         
            +
                        )
         
     | 
| 302 | 
         
             
                        model_input["audio_token_len"] = audio_token_len
         
     | 
| 303 | 
         
            +
                        model_input["audio_batch_size"] = audio_batch_size
         
     | 
| 304 | 
         
            +
                        model_input["audio_lens"] = audio_lens
         
     | 
| 305 | 
         | 
| 306 | 
         
             
                    return model_input
         
     | 
| 307 | 
         | 
| 308 | 
         
            +
                @classmethod
         
     | 
| 309 | 
         
            +
                def _create_multi_modal_projector(
         
     | 
| 310 | 
         
            +
                    cls, config: UltravoxConfig
         
     | 
| 311 | 
         
            +
                ) -> "UltravoxProjector":
         
     | 
| 312 | 
         
            +
                    projector = UltravoxProjector(config)
         
     | 
| 313 | 
         
            +
                    projector.to(config.torch_dtype)
         
     | 
| 314 | 
         
            +
                    return projector
         
     | 
| 315 | 
         
            +
             
     | 
| 316 | 
         
             
                @classmethod
         
     | 
| 317 | 
         
             
                def _create_audio_tower(
         
     | 
| 318 | 
         
             
                    cls, config: UltravoxConfig
         
     | 
| 319 | 
         
            +
                ) -> Union[transformers.Wav2Vec2Model, "ModifiedWhisperEncoder"]:
         
     | 
| 320 | 
         
             
                    if config.audio_model_id is not None:
         
     | 
| 321 | 
         
            +
                        if "whisper" in config.audio_model_id.lower():
         
     | 
| 322 | 
         
             
                            audio_tower = ModifiedWhisperEncoder.from_pretrained(
         
     | 
| 323 | 
         
            +
                                config.audio_model_id, torch_dtype=config.torch_dtype
         
     | 
| 324 | 
         
            +
                            )
         
     | 
| 325 | 
         
            +
                            audio_tower.init_latency_mask(
         
     | 
| 326 | 
         
            +
                                config.audio_latency_block_size, dtype=config.torch_dtype
         
     | 
| 327 | 
         
             
                            )
         
     | 
| 328 | 
         
             
                        else:
         
     | 
| 329 | 
         
            +
                            assert config.audio_latency_block_size in (
         
     | 
| 330 | 
         
            +
                                None,
         
     | 
| 331 | 
         
            +
                                0,
         
     | 
| 332 | 
         
            +
                            ), "only whisper audio tower supports audio latency masking, got non-zero value for 'audio_latency_block_size'"
         
     | 
| 333 | 
         
             
                            audio_tower = transformers.AutoModel.from_pretrained(
         
     | 
| 334 | 
         
            +
                                config.audio_model_id, torch_dtype=config.torch_dtype
         
     | 
| 335 | 
         
             
                            )
         
     | 
| 336 | 
         
             
                    else:
         
     | 
| 337 | 
         
            +
                        if "whisper" in config.audio_config._name_or_path.lower():
         
     | 
| 338 | 
         
             
                            audio_tower = ModifiedWhisperEncoder(config.audio_config)
         
     | 
| 339 | 
         
            +
                            audio_tower.init_latency_mask(
         
     | 
| 340 | 
         
            +
                                config.audio_latency_block_size, dtype=config.torch_dtype
         
     | 
| 341 | 
         
            +
                            )
         
     | 
| 342 | 
         
             
                        else:
         
     | 
| 343 | 
         
            +
                            assert config.audio_latency_block_size in (
         
     | 
| 344 | 
         
            +
                                None,
         
     | 
| 345 | 
         
            +
                                0,
         
     | 
| 346 | 
         
            +
                            ), "only whisper audio tower supports audio latency masking, got non-zero value for 'audio_latency_block_size'"
         
     | 
| 347 | 
         
            +
                            with transformers.modeling_utils.no_init_weights():
         
     | 
| 348 | 
         
            +
                                # we only ever use from_config if the weights are retrained, hence initializing is not
         
     | 
| 349 | 
         
            +
                                # required. This makes the model quite creation faster since init on CPU is quite slow.
         
     | 
| 350 | 
         
            +
                                audio_tower = transformers.AutoModel.from_config(
         
     | 
| 351 | 
         
            +
                                    config.audio_config
         
     | 
| 352 | 
         
            +
                                )
         
     | 
| 353 | 
         | 
| 354 | 
         
             
                    if isinstance(
         
     | 
| 355 | 
         
             
                        audio_tower,
         
     | 
| 
         | 
|
| 369 | 
         
             
                ) -> transformers.LlamaForCausalLM:
         
     | 
| 370 | 
         
             
                    if config.text_model_id is not None:
         
     | 
| 371 | 
         
             
                        language_model = transformers.AutoModelForCausalLM.from_pretrained(
         
     | 
| 372 | 
         
            +
                            config.text_model_id,
         
     | 
| 373 | 
         
            +
                            attn_implementation=config._attn_implementation,
         
     | 
| 374 | 
         
            +
                            torch_dtype=config.torch_dtype,
         
     | 
| 375 | 
         
             
                        )
         
     | 
| 376 | 
         
             
                    else:
         
     | 
| 377 | 
         
            +
                        with transformers.modeling_utils.no_init_weights():
         
     | 
| 378 | 
         
            +
                            # we only ever use from_config if the weights are retrained, hence initializing is not
         
     | 
| 379 | 
         
            +
                            # required. This makes the model quite creation faster since init on CPU is quite slow.
         
     | 
| 380 | 
         
            +
                            language_model = transformers.AutoModelForCausalLM.from_config(
         
     | 
| 381 | 
         
            +
                                config.text_config,
         
     | 
| 382 | 
         
            +
                                attn_implementation=config._attn_implementation,
         
     | 
| 383 | 
         
            +
                                torch_dtype=config.torch_dtype,
         
     | 
| 384 | 
         
            +
                            )
         
     | 
| 385 | 
         | 
| 386 | 
         
             
                    language_model = apply_lora(language_model, config.text_model_lora_config)
         
     | 
| 387 | 
         
             
                    return language_model
         
     | 
| 
         | 
|
| 419 | 
         | 
| 420 | 
         
             
                def push_to_hub(self, *args, **kwargs):
         
     | 
| 421 | 
         
             
                    self.merge_and_unload()
         
     | 
| 
         | 
|
| 422 | 
         
             
                    return super().push_to_hub(*args, **kwargs)
         
     | 
| 423 | 
         | 
| 424 | 
         
            +
                def diff_state_dict(
         
     | 
| 425 | 
         
            +
                    self, state_dict: Optional[Dict[str, Any]] = None
         
     | 
| 426 | 
         
            +
                ) -> Dict[str, Any]:
         
     | 
| 427 | 
         
            +
                    if state_dict is None:
         
     | 
| 428 | 
         
            +
                        state_dict = super().state_dict()
         
     | 
| 429 | 
         
            +
             
     | 
| 430 | 
         
            +
                    trainable_params = {k for k, v in self.named_parameters() if v.requires_grad}
         
     | 
| 431 | 
         
            +
                    # normalize the keys to match the original model
         
     | 
| 432 | 
         
            +
                    # Example: audio_tower.base_model.model.layers.0._fsdp_wrapped_module.self_attn.k_proj.lora_B.default.weight
         
     | 
| 433 | 
         
            +
                    trainable_params = {
         
     | 
| 434 | 
         
            +
                        k.replace("_fsdp_wrapped_module.", "") for k in trainable_params
         
     | 
| 435 | 
         
            +
                    }
         
     | 
| 436 | 
         | 
| 437 | 
         
             
                    state_dict = {
         
     | 
| 438 | 
         
             
                        k: v
         
     | 
| 439 | 
         
             
                        for k, v in state_dict.items()
         
     | 
| 440 | 
         
            +
                        if k in self.keep_params or k in trainable_params
         
     | 
| 
         | 
|
| 441 | 
         
             
                    }
         
     | 
| 442 | 
         
            +
             
     | 
| 443 | 
         
             
                    return state_dict
         
     | 
| 444 | 
         | 
| 445 | 
         
            +
                def save_pretrained(
         
     | 
| 446 | 
         
            +
                    self, *args, state_dict: Optional[Dict[str, Any]] = None, **kwargs
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 447 | 
         
             
                ):
         
     | 
| 448 | 
         
            +
                    state_dict = self.diff_state_dict(state_dict)
         
     | 
| 449 | 
         
            +
             
     | 
| 450 | 
         
            +
                    super().save_pretrained(*args, state_dict=state_dict, **kwargs)
         
     | 
| 451 | 
         
            +
             
     | 
| 452 | 
         
            +
                def _pre_load_state_dict_hook(self, state_dict: Dict[str, Any], *args, **kwargs):
         
     | 
| 453 | 
         
             
                    self.keep_params.update(set(state_dict.keys()))
         
     | 
| 
         | 
|
| 454 | 
         | 
| 455 | 
         
             
                def print_trainable_parameters(self):
         
     | 
| 456 | 
         
             
                    """
         
     | 
| 
         | 
|
| 481 | 
         
             
                    )
         
     | 
| 482 | 
         | 
| 483 | 
         | 
| 484 | 
         
            +
            # TODO: refactor common parts to a shared module
         
     | 
| 485 | 
         
             
            def is_cache_empty(
         
     | 
| 486 | 
         
            +
                past_key_values: Optional[Union[Tuple, transformers.cache_utils.Cache]],
         
     | 
| 487 | 
         
             
            ) -> bool:
         
     | 
| 488 | 
         
             
                """
         
     | 
| 489 | 
         
             
                Check if the cache is empty.
         
     | 
| 
         | 
|
| 499 | 
         
             
                """
         
     | 
| 500 | 
         
             
                Applies LoRA finetuning to the model. If the `r` parameter is set to 0, the model is frozen instead.
         
     | 
| 501 | 
         
             
                """
         
     | 
| 502 | 
         
            +
                unfreeze_layers = lora_config.pop("unfreeze_layers", None)
         
     | 
| 503 | 
         
             
                lora_config = peft.LoraConfig(**lora_config or {})
         
     | 
| 504 | 
         | 
| 505 | 
         
             
                if lora_config.r == 0:
         
     | 
| 506 | 
         
            +
                    # freeze the model entirely, except for the specified layers
         
     | 
| 507 | 
         
            +
                    for name, param in model.named_parameters():
         
     | 
| 508 | 
         
            +
                        if not unfreeze_layers or not any(
         
     | 
| 509 | 
         
            +
                            re.match(layer, name) for layer in unfreeze_layers
         
     | 
| 510 | 
         
            +
                        ):
         
     | 
| 511 | 
         
            +
                            param.requires_grad = False
         
     | 
| 512 | 
         
            +
                        else:
         
     | 
| 513 | 
         
            +
                            logging.info(f"Unfreezing layer: {name} with #{param.numel()} params")
         
     | 
| 514 | 
         
             
                else:
         
     | 
| 515 | 
         
             
                    model = peft.get_peft_model(model, lora_config)
         
     | 
| 516 | 
         | 
| 
         | 
|
| 519 | 
         | 
| 520 | 
         
             
            class StackAudioFrames(nn.Module):
         
     | 
| 521 | 
         
             
                """
         
     | 
| 522 | 
         
            +
                Stack the audio embedding frames to reduce the sequence length by a factor
         
     | 
| 523 | 
         
            +
                of `stack_factor`.
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 524 | 
         
             
                """
         
     | 
| 525 | 
         | 
| 526 | 
         
             
                def __init__(self, stack_factor: int = 8):
         
     | 
| 
         | 
|
| 530 | 
         
             
                def forward(self, audio_embeds: torch.Tensor) -> torch.Tensor:
         
     | 
| 531 | 
         
             
                    B, T, C = audio_embeds.shape
         
     | 
| 532 | 
         
             
                    T_pad = (T + self.stack_factor - 1) // self.stack_factor * self.stack_factor
         
     | 
| 533 | 
         
            +
                    audio_embeds = F.pad(audio_embeds, (0, 0, 0, T_pad - T))
         
     | 
| 534 | 
         
             
                    B, T, C = audio_embeds.shape
         
     | 
| 535 | 
         
             
                    audio_embeds = audio_embeds.view(
         
     | 
| 536 | 
         
             
                        B, T // self.stack_factor, C * self.stack_factor
         
     | 
| 
         | 
|
| 550 | 
         
             
                    return F.silu(gate) * x
         
     | 
| 551 | 
         | 
| 552 | 
         | 
| 553 | 
         
            +
            class UltravoxProjector(nn.Module):
         
     | 
| 554 | 
         
             
                def __init__(self, config: UltravoxConfig):
         
     | 
| 555 | 
         
             
                    super().__init__()
         
     | 
| 556 | 
         
             
                    self.hidden_dim = config.hidden_size
         
     | 
| 557 | 
         
             
                    self._pad_and_stack = StackAudioFrames(config.stack_factor)
         
     | 
| 558 | 
         
            +
                    dim_in = config.audio_config.hidden_size * config.stack_factor
         
     | 
| 559 | 
         
            +
                    self.ln_pre = RMSNorm(dim_in, init=config.norm_init)
         
     | 
| 560 | 
         
            +
                    self.linear_1 = nn.Linear(dim_in, self.hidden_dim, bias=False)
         
     | 
| 561 | 
         
            +
                    dim_mid = self.hidden_dim
         
     | 
| 562 | 
         
             
                    self.act = transformers.activations.get_activation(config.projector_act)
         
     | 
| 563 | 
         
            +
                    dim_mid = dim_mid // 2 if config.projector_act == "swiglu" else dim_mid
         
     | 
| 564 | 
         
            +
                    dim_out = config.text_config.hidden_size
         
     | 
| 565 | 
         
            +
                    self.linear_2 = nn.Linear(dim_mid, dim_out, bias=False)
         
     | 
| 566 | 
         
            +
             
     | 
| 567 | 
         
            +
                    # Ultravox v0.4.1 and below uses layer_norm after the second linear layer,
         
     | 
| 568 | 
         
            +
                    # while v0.5.0 and above uses layer_norm after the first linear layer.
         
     | 
| 569 | 
         
            +
                    if config.projector_ln_mid:
         
     | 
| 570 | 
         
            +
                        self.ln_mid: nn.Module = RMSNorm(dim_mid, init=config.norm_init)
         
     | 
| 571 | 
         
            +
                        self.ln_post: nn.Module = nn.Identity()
         
     | 
| 572 | 
         
            +
                    else:
         
     | 
| 573 | 
         
            +
                        self.ln_mid = nn.Identity()
         
     | 
| 574 | 
         
            +
                        self.ln_post = RMSNorm(dim_out, init=config.norm_init)
         
     | 
| 575 | 
         | 
| 576 | 
         
             
                def forward(self, audio_features: torch.Tensor) -> torch.Tensor:
         
     | 
| 577 | 
         
             
                    audio_features = self._pad_and_stack(audio_features)
         
     | 
| 578 | 
         
             
                    audio_features = self.ln_pre(audio_features)
         
     | 
| 579 | 
         
             
                    hidden_states = self.linear_1(audio_features)
         
     | 
| 580 | 
         
             
                    hidden_states = self.act(hidden_states)
         
     | 
| 581 | 
         
            +
                    hidden_states = self.ln_mid(hidden_states)
         
     | 
| 582 | 
         
             
                    hidden_states = self.linear_2(hidden_states)
         
     | 
| 583 | 
         
             
                    hidden_states = self.ln_post(hidden_states)
         
     | 
| 584 | 
         
             
                    return hidden_states
         
     | 
| 585 | 
         | 
| 586 | 
         | 
| 587 | 
         
            +
            class ModifiedWhisperEncoder(
         
     | 
| 588 | 
         
            +
                whisper.WhisperEncoder, transformers.modeling_utils.ModuleUtilsMixin
         
     | 
| 589 | 
         
            +
            ):
         
     | 
| 590 | 
         
            +
                """
         
     | 
| 591 | 
         
            +
                Encoder portion of OpenAI's Whisper model.
         
     | 
| 592 | 
         
            +
             
     | 
| 593 | 
         
            +
                This implementation is a slightly modified version of HF Transformers' Whisper Encoder, with only a few fixes:
         
     | 
| 594 | 
         
            +
                1. base_model_prefix updated to allow for doing `.from_pretrained` directly on the encoder
         
     | 
| 595 | 
         
            +
                2. allow less than 30 second of audio padding to be passed in:
         
     | 
| 596 | 
         
            +
                    - relaxed ValueError check for `input_features` length to be less than or equal to `expected_seq_length` instead of strictly equal
         
     | 
| 597 | 
         
            +
                    - embed_pos is now sliced to match the length of `inputs_embeds`
         
     | 
| 598 | 
         
            +
             
     | 
| 599 | 
         
            +
                Original: https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py
         
     | 
| 600 | 
         
            +
                """
         
     | 
| 601 | 
         
            +
             
     | 
| 602 | 
         
            +
                base_model_prefix = "model.encoder"
         
     | 
| 603 | 
         
            +
                _no_split_modules = ["WhisperEncoderLayer"]
         
     | 
| 604 | 
         
            +
             
     | 
| 605 | 
         
            +
                def __init__(self, config: transformers.WhisperConfig):
         
     | 
| 606 | 
         
            +
                    super().__init__(config)
         
     | 
| 607 | 
         
            +
                    self.config.is_decoder = False
         
     | 
| 608 | 
         
            +
             
     | 
| 609 | 
         
            +
                @property
         
     | 
| 610 | 
         
            +
                def max_context_length(self):
         
     | 
| 611 | 
         
            +
                    return (
         
     | 
| 612 | 
         
            +
                        self.config.max_source_positions
         
     | 
| 613 | 
         
            +
                        * self.conv1.stride[0]
         
     | 
| 614 | 
         
            +
                        * self.conv2.stride[0]
         
     | 
| 615 | 
         
            +
                    )
         
     | 
| 616 | 
         
            +
             
     | 
| 617 | 
         
            +
                def init_latency_mask(self, audio_latency_block_size: int, dtype: torch.dtype):
         
     | 
| 618 | 
         
            +
                    if audio_latency_block_size is None:
         
     | 
| 619 | 
         
            +
                        self.audio_streaming_mask = None
         
     | 
| 620 | 
         
            +
                        return
         
     | 
| 621 | 
         
            +
             
     | 
| 622 | 
         
            +
                    # Use max_context_length directly in the calculation
         
     | 
| 623 | 
         
            +
                    max_seqlen = self.max_context_length
         
     | 
| 624 | 
         
            +
                    assert (
         
     | 
| 625 | 
         
            +
                        max_seqlen > 0
         
     | 
| 626 | 
         
            +
                    ), f"maximum sequence length must be positive, got {max_seqlen}"
         
     | 
| 627 | 
         
            +
                    assert (
         
     | 
| 628 | 
         
            +
                        max_seqlen % audio_latency_block_size == 0
         
     | 
| 629 | 
         
            +
                    ), f"audio_latency_block_size {audio_latency_block_size} must divide {max_seqlen} evenly."
         
     | 
| 630 | 
         
            +
                    # Given the block size, we calculate number of blocks.
         
     | 
| 631 | 
         
            +
                    audio_latency_nblocks = max_seqlen // audio_latency_block_size
         
     | 
| 632 | 
         
            +
                    audio_streaming_mask = (
         
     | 
| 633 | 
         
            +
                        torch.tril(
         
     | 
| 634 | 
         
            +
                            torch.ones(audio_latency_nblocks, audio_latency_nblocks),
         
     | 
| 635 | 
         
            +
                            diagonal=0,
         
     | 
| 636 | 
         
            +
                        )
         
     | 
| 637 | 
         
            +
                        .repeat_interleave(audio_latency_block_size, dim=0)
         
     | 
| 638 | 
         
            +
                        .repeat_interleave(audio_latency_block_size, dim=1)
         
     | 
| 639 | 
         
            +
                    )
         
     | 
| 640 | 
         
            +
                    audio_streaming_mask = (1.0 - audio_streaming_mask) * torch.finfo(dtype).min
         
     | 
| 641 | 
         
            +
                    audio_streaming_mask = audio_streaming_mask[None, None, :, :]
         
     | 
| 642 | 
         
            +
                    self.register_buffer(
         
     | 
| 643 | 
         
            +
                        "audio_streaming_mask", audio_streaming_mask, persistent=False
         
     | 
| 644 | 
         
            +
                    )
         
     | 
| 645 | 
         
            +
             
     | 
| 646 | 
         
            +
                def forward(
         
     | 
| 647 | 
         
            +
                    self,
         
     | 
| 648 | 
         
            +
                    input_features,
         
     | 
| 649 | 
         
            +
                    audio_len=None,
         
     | 
| 650 | 
         
            +
                    head_mask=None,
         
     | 
| 651 | 
         
            +
                    output_attentions=None,
         
     | 
| 652 | 
         
            +
                    output_hidden_states=None,
         
     | 
| 653 | 
         
            +
                    return_dict=None,
         
     | 
| 654 | 
         
            +
                ):
         
     | 
| 655 | 
         
            +
                    expected_seq_length = self.max_context_length
         
     | 
| 656 | 
         
            +
                    if input_features.shape[-1] > expected_seq_length:
         
     | 
| 657 | 
         
            +
                        raise ValueError(
         
     | 
| 658 | 
         
            +
                            f"Whisper expects the mel input features to be of length {expected_seq_length} or less, but found {input_features.shape[-1]}. Make sure to pad the input mel features to {expected_seq_length}."
         
     | 
| 659 | 
         
            +
                        )
         
     | 
| 660 | 
         
            +
             
     | 
| 661 | 
         
            +
                    output_attentions = (
         
     | 
| 662 | 
         
            +
                        output_attentions
         
     | 
| 663 | 
         
            +
                        if output_attentions is not None
         
     | 
| 664 | 
         
            +
                        else self.config.output_attentions
         
     | 
| 665 | 
         
            +
                    )
         
     | 
| 666 | 
         
            +
                    output_hidden_states = (
         
     | 
| 667 | 
         
            +
                        output_hidden_states
         
     | 
| 668 | 
         
            +
                        if output_hidden_states is not None
         
     | 
| 669 | 
         
            +
                        else self.config.output_hidden_states
         
     | 
| 670 | 
         
            +
                    )
         
     | 
| 671 | 
         
            +
                    return_dict = (
         
     | 
| 672 | 
         
            +
                        return_dict if return_dict is not None else self.config.use_return_dict
         
     | 
| 673 | 
         
            +
                    )
         
     | 
| 674 | 
         
            +
                    inputs_embeds = nn.functional.gelu(self.conv1(input_features))
         
     | 
| 675 | 
         
            +
                    inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
         
     | 
| 676 | 
         
            +
             
     | 
| 677 | 
         
            +
                    inputs_embeds = inputs_embeds.permute(0, 2, 1)
         
     | 
| 678 | 
         
            +
                    embed_pos = self.embed_positions.weight[: inputs_embeds.size(-2)]
         
     | 
| 679 | 
         
            +
             
     | 
| 680 | 
         
            +
                    hidden_states = inputs_embeds + embed_pos
         
     | 
| 681 | 
         
            +
                    hidden_states = nn.functional.dropout(
         
     | 
| 682 | 
         
            +
                        hidden_states, p=self.dropout, training=self.training
         
     | 
| 683 | 
         
            +
                    )
         
     | 
| 684 | 
         
            +
             
     | 
| 685 | 
         
            +
                    encoder_states = () if output_hidden_states else None
         
     | 
| 686 | 
         
            +
                    all_attentions = () if output_attentions else None
         
     | 
| 687 | 
         
            +
             
     | 
| 688 | 
         
            +
                    # Create attention mask based on audio lengths to mask out padding tokens
         
     | 
| 689 | 
         
            +
                    # For each sample in batch:
         
     | 
| 690 | 
         
            +
                    # - Convert raw audio length to feature length after convolutions
         
     | 
| 691 | 
         
            +
                    # - Create boolean mask that is True for valid positions and False for padding
         
     | 
| 692 | 
         
            +
                    # - Convert to extended attention mask format expected by transformer layers
         
     | 
| 693 | 
         
            +
                    #   (1.0 for positions to attend to, large negative for positions to ignore)
         
     | 
| 694 | 
         
            +
                    # This masking ensures consistent behavior between training and inference
         
     | 
| 695 | 
         
            +
                    # by preventing the model from attending to padding tokens in both cases
         
     | 
| 696 | 
         
            +
                    attention_mask = None
         
     | 
| 697 | 
         
            +
                    if audio_len != None:
         
     | 
| 698 | 
         
            +
                        audio_feature_len = self._get_feat_extract_output_lengths(audio_len)
         
     | 
| 699 | 
         
            +
                        max_seq_len = hidden_states.shape[1]
         
     | 
| 700 | 
         
            +
                        attention_mask = torch.arange(max_seq_len, device=hidden_states.device)[
         
     | 
| 701 | 
         
            +
                            None, :
         
     | 
| 702 | 
         
            +
                        ].lt(audio_feature_len.view(-1, 1))
         
     | 
| 703 | 
         
            +
                        attention_mask = self.get_extended_attention_mask(
         
     | 
| 704 | 
         
            +
                            attention_mask,
         
     | 
| 705 | 
         
            +
                            None,
         
     | 
| 706 | 
         
            +
                            dtype=hidden_states.dtype,
         
     | 
| 707 | 
         
            +
                        )
         
     | 
| 708 | 
         
            +
             
     | 
| 709 | 
         
            +
                    if self.audio_streaming_mask is not None:
         
     | 
| 710 | 
         
            +
                        seqlen = hidden_states.size(-2)
         
     | 
| 711 | 
         
            +
                        if attention_mask is not None:
         
     | 
| 712 | 
         
            +
                            attention_mask = torch.minimum(
         
     | 
| 713 | 
         
            +
                                self.audio_streaming_mask[:, :, :seqlen, :seqlen], attention_mask
         
     | 
| 714 | 
         
            +
                            )  # merge
         
     | 
| 715 | 
         
            +
                        else:
         
     | 
| 716 | 
         
            +
                            attention_mask = self.audio_streaming_mask[:, :, :seqlen, :seqlen]
         
     | 
| 717 | 
         
            +
                        attention_mask = attention_mask.to(hidden_states.dtype)
         
     | 
| 718 | 
         
            +
             
     | 
| 719 | 
         
            +
                    # check if head_mask has a correct number of layers specified if desired
         
     | 
| 720 | 
         
            +
                    if head_mask is not None:
         
     | 
| 721 | 
         
            +
                        assert head_mask.size()[0] == (
         
     | 
| 722 | 
         
            +
                            len(self.layers)
         
     | 
| 723 | 
         
            +
                        ), f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
         
     | 
| 724 | 
         
            +
             
     | 
| 725 | 
         
            +
                    for idx, encoder_layer in enumerate(self.layers):
         
     | 
| 726 | 
         
            +
                        if output_hidden_states:
         
     | 
| 727 | 
         
            +
                            encoder_states = encoder_states + (hidden_states,)
         
     | 
| 728 | 
         
            +
                        # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
         
     | 
| 729 | 
         
            +
                        to_drop = False
         
     | 
| 730 | 
         
            +
                        if self.training:
         
     | 
| 731 | 
         
            +
                            dropout_probability = torch.rand([])
         
     | 
| 732 | 
         
            +
                            if dropout_probability < self.layerdrop:  # skip the layer
         
     | 
| 733 | 
         
            +
                                to_drop = True
         
     | 
| 734 | 
         
            +
             
     | 
| 735 | 
         
            +
                        if to_drop:
         
     | 
| 736 | 
         
            +
                            layer_outputs = (None, None)
         
     | 
| 737 | 
         
            +
                        else:
         
     | 
| 738 | 
         
            +
                            if self.gradient_checkpointing and self.training:
         
     | 
| 739 | 
         
            +
                                layer_outputs = self._gradient_checkpointing_func(
         
     | 
| 740 | 
         
            +
                                    encoder_layer.__call__,
         
     | 
| 741 | 
         
            +
                                    hidden_states,
         
     | 
| 742 | 
         
            +
                                    attention_mask,
         
     | 
| 743 | 
         
            +
                                    (head_mask[idx] if head_mask is not None else None),
         
     | 
| 744 | 
         
            +
                                    output_attentions,
         
     | 
| 745 | 
         
            +
                                )
         
     | 
| 746 | 
         
            +
                            else:
         
     | 
| 747 | 
         
            +
                                layer_outputs = encoder_layer(
         
     | 
| 748 | 
         
            +
                                    hidden_states,
         
     | 
| 749 | 
         
            +
                                    attention_mask,
         
     | 
| 750 | 
         
            +
                                    layer_head_mask=(
         
     | 
| 751 | 
         
            +
                                        head_mask[idx] if head_mask is not None else None
         
     | 
| 752 | 
         
            +
                                    ),
         
     | 
| 753 | 
         
            +
                                    output_attentions=output_attentions,
         
     | 
| 754 | 
         
            +
                                )
         
     | 
| 755 | 
         
            +
             
     | 
| 756 | 
         
            +
                            hidden_states = layer_outputs[0]
         
     | 
| 757 | 
         
            +
             
     | 
| 758 | 
         
            +
                        if output_attentions:
         
     | 
| 759 | 
         
            +
                            all_attentions = all_attentions + (layer_outputs[1],)
         
     | 
| 760 | 
         
            +
             
     | 
| 761 | 
         
            +
                    hidden_states = self.layer_norm(hidden_states)
         
     | 
| 762 | 
         
            +
                    if output_hidden_states:
         
     | 
| 763 | 
         
            +
                        encoder_states = encoder_states + (hidden_states,)
         
     | 
| 764 | 
         
            +
             
     | 
| 765 | 
         
            +
                    if not return_dict:
         
     | 
| 766 | 
         
            +
                        return tuple(
         
     | 
| 767 | 
         
            +
                            v
         
     | 
| 768 | 
         
            +
                            for v in [hidden_states, encoder_states, all_attentions]
         
     | 
| 769 | 
         
            +
                            if v is not None
         
     | 
| 770 | 
         
            +
                        )
         
     | 
| 771 | 
         
            +
                    return transformers.modeling_outputs.BaseModelOutput(
         
     | 
| 772 | 
         
            +
                        last_hidden_state=hidden_states,
         
     | 
| 773 | 
         
            +
                        hidden_states=encoder_states,
         
     | 
| 774 | 
         
            +
                        attentions=all_attentions,
         
     | 
| 775 | 
         
            +
                    )
         
     | 
| 776 | 
         
            +
             
     | 
| 777 | 
         
            +
             
     | 
| 778 | 
         
             
            UltravoxConfig.register_for_auto_class()
         
     | 
| 779 | 
         
             
            UltravoxModel.register_for_auto_class()
         
     | 
| 780 | 
         | 
| 781 | 
         
             
            transformers.AutoConfig.register("ultravox", UltravoxConfig)
         
     | 
| 782 | 
         
             
            transformers.AutoModel.register(UltravoxConfig, UltravoxModel)
         
     | 
| 
         | 
|
| 783 | 
         | 
| 784 | 
         
             
            transformers.activations.ACT2FN["swiglu"] = SwiGLU
         
     | 
    	
        ultravox_processing.py
    CHANGED
    
    | 
         @@ -1,9 +1,68 @@ 
     | 
|
| 1 | 
         
            -
             
     | 
| 
         | 
|
| 2 | 
         | 
| 3 | 
         
             
            import numpy as np
         
     | 
| 4 | 
         
             
            import torch
         
     | 
| 
         | 
|
| 5 | 
         
             
            import transformers
         
     | 
| 6 | 
         | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 7 | 
         | 
| 8 | 
         
             
            class UltravoxProcessor(transformers.ProcessorMixin):
         
     | 
| 9 | 
         
             
                """
         
     | 
| 
         @@ -15,11 +74,7 @@ class UltravoxProcessor(transformers.ProcessorMixin): 
     | 
|
| 15 | 
         
             
                """
         
     | 
| 16 | 
         | 
| 17 | 
         
             
                attributes = ["audio_processor", "tokenizer"]
         
     | 
| 18 | 
         
            -
                audio_processor_class = (
         
     | 
| 19 | 
         
            -
                    "Wav2Vec2Processor",
         
     | 
| 20 | 
         
            -
                    "SeamlessM4TFeatureExtractor",
         
     | 
| 21 | 
         
            -
                    "WhisperProcessor",
         
     | 
| 22 | 
         
            -
                )
         
     | 
| 23 | 
         
             
                tokenizer_class = (
         
     | 
| 24 | 
         
             
                    "PreTrainedTokenizer",
         
     | 
| 25 | 
         
             
                    "PreTrainedTokenizerFast",
         
     | 
| 
         @@ -33,53 +88,154 @@ class UltravoxProcessor(transformers.ProcessorMixin): 
     | 
|
| 33 | 
         
             
                    audio_processor=None,
         
     | 
| 34 | 
         
             
                    tokenizer=None,
         
     | 
| 35 | 
         
             
                    audio_padding: str = "longest",
         
     | 
| 36 | 
         
            -
                    encoder_ds_factor: int =  
     | 
| 37 | 
         
             
                    stack_factor: int = 8,
         
     | 
| 38 | 
         
             
                    audio_placeholder: str = "<|audio|>",
         
     | 
| 
         | 
|
| 
         | 
|
| 39 | 
         
             
                ):
         
     | 
| 40 | 
         
             
                    """
         
     | 
| 41 | 
         
             
                    Args:
         
     | 
| 42 | 
         
             
                        audio_processor: The audio processor for the audio encoder.
         
     | 
| 43 | 
         
             
                        tokenizer: The tokenizer for the language model.
         
     | 
| 44 | 
         
             
                        audio_padding: The padding strategy for the audio encoder.
         
     | 
| 45 | 
         
            -
                        encoder_ds_factor: The downsample factor of the audio encoder.
         
     | 
| 46 | 
         
             
                        stack_factor: The factor by which the audio encoder output is stacked in the multimodal projector.
         
     | 
| 
         | 
|
| 47 | 
         
             
                        audio_placeholder: The placeholder for the audio in the text.
         
     | 
| 
         | 
|
| 48 | 
         
             
                    """
         
     | 
| 49 | 
         
             
                    self.audio_padding = audio_padding
         
     | 
| 50 | 
         
             
                    self.encoder_ds_factor = encoder_ds_factor
         
     | 
| 51 | 
         
             
                    self.stack_factor = stack_factor
         
     | 
| 52 | 
         
             
                    self.audio_placeholder = audio_placeholder
         
     | 
| 53 | 
         
            -
                    self. 
     | 
| 54 | 
         
             
                    assert (
         
     | 
| 55 | 
         
            -
                         
     | 
| 56 | 
         
             
                    ), "The tokenizer has no EOS token. Cannot recover."
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 57 | 
         
             
                    super().__init__(audio_processor=audio_processor, tokenizer=tokenizer)
         
     | 
| 58 | 
         | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 59 | 
         
             
                def __call__(
         
     | 
| 60 | 
         
             
                    self,
         
     | 
| 61 | 
         
             
                    text: Optional[str] = None,
         
     | 
| 62 | 
         
             
                    audio: Optional[Union[np.ndarray, torch.Tensor]] = None,
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 63 | 
         
             
                    sampling_rate: Optional[int] = None,
         
     | 
| 64 | 
         
             
                    return_tensors: Optional[
         
     | 
| 65 | 
         
             
                        Union[str, transformers.TensorType]
         
     | 
| 66 | 
         
             
                    ] = transformers.TensorType.PYTORCH,
         
     | 
| 
         | 
|
| 67 | 
         
             
                    **kwargs,
         
     | 
| 68 | 
         
             
                ) -> transformers.BatchFeature:
         
     | 
| 69 | 
         
             
                    """
         
     | 
| 70 | 
         
             
                    Main method to prepare for the model one text sequence and audio. This method forwards the `text`
         
     | 
| 71 | 
         
             
                    and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode
         
     | 
| 72 | 
         
             
                    the text. To prepare the audio(s), this method forwards the `audio`, `sampling_rate` and `kwargs` arguments to
         
     | 
| 73 | 
         
            -
                    audio processor's [`~ 
     | 
| 74 | 
         
             
                    of the above two methods for more information.
         
     | 
| 75 | 
         | 
| 76 | 
         
             
                    Args:
         
     | 
| 77 | 
         
             
                        text (`str`, `List[str]`):
         
     | 
| 78 | 
         
             
                            The sequence to be encoded. Sequence can be a string or (pretokenized string).
         
     | 
| 79 | 
         
             
                        audio (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
         
     | 
| 80 | 
         
            -
                            The audio to be prepared. Audio can be NumPy array or PyTorch tensor. 
     | 
| 81 | 
         
            -
             
     | 
| 82 | 
         
            -
                             
     | 
| 83 | 
         
             
                        sampling_rate (`int`, *optional*, defaults to 16000):
         
     | 
| 84 | 
         
             
                            Sampling rate of the input audio. We expect 16kHz audio. Don't change this value unless you know what
         
     | 
| 85 | 
         
             
                            you are doing.
         
     | 
| 
         @@ -103,64 +259,105 @@ class UltravoxProcessor(transformers.ProcessorMixin): 
     | 
|
| 103 | 
         
             
                          Returned when `audio` is not `None`.
         
     | 
| 104 | 
         
             
                        - **audio_token_start_idx** -- The index in the tokenized text where the audio starts. Returned when `audio` is not `None`.
         
     | 
| 105 | 
         
             
                    """
         
     | 
| 106 | 
         
            -
                    # TODO: Add support for multiple  
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 107 | 
         
             
                    data = {}
         
     | 
| 108 | 
         
            -
                     
     | 
| 109 | 
         
            -
                    if  
     | 
| 110 | 
         
            -
                        if  
     | 
| 111 | 
         
            -
             
     | 
| 112 | 
         
            -
             
     | 
| 113 | 
         
            -
             
     | 
| 114 | 
         
            -
                         
     | 
| 115 | 
         
            -
                             
     | 
| 116 | 
         
            -
             
     | 
| 117 | 
         
            -
             
     | 
| 118 | 
         
            -
             
     | 
| 119 | 
         
            -
             
     | 
| 120 | 
         
            -
             
     | 
| 121 | 
         
            -
                         
     | 
| 122 | 
         | 
| 123 | 
         
             
                        # Main audio processing. The processor is model-specific.
         
     | 
| 124 | 
         
            -
                        x = self.audio_processor(
         
     | 
| 125 | 
         
            -
                             
     | 
| 126 | 
         
             
                            sampling_rate=sampling_rate,
         
     | 
| 127 | 
         
             
                            padding="longest",
         
     | 
| 128 | 
         
            -
                             
     | 
| 
         | 
|
| 
         | 
|
| 129 | 
         
             
                            **kwargs,
         
     | 
| 130 | 
         
             
                        )
         
     | 
| 131 | 
         
            -
                        if "input_features" in x:
         
     | 
| 132 | 
         
            -
                            data["audio_values"] = x.input_features
         
     | 
| 133 | 
         
            -
                        else:
         
     | 
| 134 | 
         
            -
                            data["audio_values"] = x.input_values
         
     | 
| 135 | 
         | 
| 136 | 
         
            -
             
     | 
| 137 | 
         
            -
             
     | 
| 138 | 
         
            -
             
     | 
| 139 | 
         
            -
             
     | 
| 140 | 
         
            -
             
     | 
| 141 | 
         
            -
             
     | 
| 142 | 
         
            -
                                 
     | 
| 143 | 
         
            -
                                    f"audio must be provided when using audio placeholder ({self.audio_placeholder}) in text."
         
     | 
| 144 | 
         
            -
                                )
         
     | 
| 145 | 
         
            -
             
     | 
| 146 | 
         
            -
                            start_idx = len(
         
     | 
| 147 | 
         
            -
                                self.tokenizer.encode(
         
     | 
| 148 | 
         
            -
                                    text[: text.index(self.audio_placeholder)],
         
     | 
| 149 | 
         
            -
                                    add_special_tokens=False,
         
     | 
| 150 | 
         
            -
                                )
         
     | 
| 151 | 
         
            -
                            )
         
     | 
| 152 | 
         
            -
                            data["audio_token_start_idx"] = [start_idx]
         
     | 
| 153 | 
         
            -
             
     | 
| 154 | 
         
            -
                            # Replace the audio placeholder with the audio token.
         
     | 
| 155 | 
         
            -
                            #   e.g. "Transcribe <|audio|>" -> "Transcribe </s></s></s></s></s></s></s></s>"
         
     | 
| 156 | 
         
            -
                            #        where the number of </s> is the number of audio frames.
         
     | 
| 157 | 
         
            -
                            text = text.replace(
         
     | 
| 158 | 
         
            -
                                self.audio_placeholder,
         
     | 
| 159 | 
         
            -
                                self.audio_token_replacement * audio_embed_frames,
         
     | 
| 160 | 
         
             
                            )
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 161 | 
         | 
| 162 | 
         
             
                        # Special tokens like BOS should already have been added by the caller.
         
     | 
| 163 | 
         
            -
                         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 164 | 
         | 
| 165 | 
         
             
                    return transformers.BatchFeature(data=data, tensor_type=return_tensors)
         
     | 
| 166 | 
         | 
| 
         @@ -175,3 +372,8 @@ class UltravoxProcessor(transformers.ProcessorMixin): 
     | 
|
| 175 | 
         
             
                    tokenizer_input_names = self.tokenizer.model_input_names
         
     | 
| 176 | 
         
             
                    audio_processor_input_names = self.audio_processor.model_input_names
         
     | 
| 177 | 
         
             
                    return list(set(tokenizer_input_names + audio_processor_input_names))
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
| 
         | 
|
| 1 | 
         
            +
            import dataclasses
         
     | 
| 2 | 
         
            +
            from typing import Any, Dict, List, Optional, Union
         
     | 
| 3 | 
         | 
| 4 | 
         
             
            import numpy as np
         
     | 
| 5 | 
         
             
            import torch
         
     | 
| 6 | 
         
            +
            import torch.nn.functional as F
         
     | 
| 7 | 
         
             
            import transformers
         
     | 
| 8 | 
         | 
| 9 | 
         
            +
            from .ultravox_config import UltravoxConfig
         
     | 
| 10 | 
         
            +
             
     | 
| 11 | 
         
            +
             
     | 
| 12 | 
         
            +
            @dataclasses.dataclass
         
     | 
| 13 | 
         
            +
            class DataCollatorForSeq2SeqWithAudio(transformers.DataCollatorForSeq2Seq):
         
     | 
| 14 | 
         
            +
                # when enabled, the alt_input_ids, alt_attention_mask, and alt_labels fields are used for computing the KL loss in UltravoxModel
         
     | 
| 15 | 
         
            +
                include_alt_fields: bool = False
         
     | 
| 16 | 
         
            +
             
     | 
| 17 | 
         
            +
                def __call__(self, features, *args, **kwargs):
         
     | 
| 18 | 
         
            +
                    audio_values = [x for f in features for x in f.pop("audio_values", [])]
         
     | 
| 19 | 
         
            +
                    audio_lens = [x for f in features for x in f.pop("audio_lens", [])]
         
     | 
| 20 | 
         
            +
                    audio_token_len = [x for f in features for x in f.pop("audio_token_len", [])]
         
     | 
| 21 | 
         
            +
                    audio_token_start_idx = [
         
     | 
| 22 | 
         
            +
                        x for f in features for x in f.pop("audio_token_start_idx", [])
         
     | 
| 23 | 
         
            +
                    ]
         
     | 
| 24 | 
         
            +
             
     | 
| 25 | 
         
            +
                    if self.include_alt_fields:
         
     | 
| 26 | 
         
            +
                        # these fields are hard-coded in the transformer data collator, so they need special handling before calling the super method
         
     | 
| 27 | 
         
            +
                        alt_features = [
         
     | 
| 28 | 
         
            +
                            {
         
     | 
| 29 | 
         
            +
                                "input_ids": f.pop("alt_input_ids"),
         
     | 
| 30 | 
         
            +
                                "attention_mask": f.pop("alt_attention_mask"),
         
     | 
| 31 | 
         
            +
                                "labels": f.pop("alt_labels"),
         
     | 
| 32 | 
         
            +
                            }
         
     | 
| 33 | 
         
            +
                            for f in features
         
     | 
| 34 | 
         
            +
                        ]
         
     | 
| 35 | 
         
            +
             
     | 
| 36 | 
         
            +
                    batch = super().__call__(features, *args, **kwargs)
         
     | 
| 37 | 
         
            +
                    if self.include_alt_fields:
         
     | 
| 38 | 
         
            +
                        alt_batch = super().__call__(alt_features, *args, **kwargs)
         
     | 
| 39 | 
         
            +
                        batch["alt_input_ids"] = alt_batch["input_ids"]
         
     | 
| 40 | 
         
            +
                        batch["alt_attention_mask"] = alt_batch["attention_mask"]
         
     | 
| 41 | 
         
            +
                        batch["alt_labels"] = alt_batch["labels"]
         
     | 
| 42 | 
         
            +
             
     | 
| 43 | 
         
            +
                    batch["audio_token_start_idx"] = torch.stack(audio_token_start_idx)
         
     | 
| 44 | 
         
            +
                    batch["audio_lens"] = torch.stack(audio_lens)
         
     | 
| 45 | 
         
            +
                    batch["audio_token_len"] = torch.stack(audio_token_len)
         
     | 
| 46 | 
         
            +
             
     | 
| 47 | 
         
            +
                    # Pad the last dimension of all audio_values to the same length, with 0s on the right.
         
     | 
| 48 | 
         
            +
                    if audio_values:
         
     | 
| 49 | 
         
            +
                        max_len = max([x.shape[-1] for x in audio_values])
         
     | 
| 50 | 
         
            +
                        batch["audio_values"] = torch.stack(
         
     | 
| 51 | 
         
            +
                            [F.pad(x, (0, max_len - x.shape[-1])) for x in audio_values]
         
     | 
| 52 | 
         
            +
                        )
         
     | 
| 53 | 
         
            +
                        if self.tokenizer.padding_side == "left":
         
     | 
| 54 | 
         
            +
                            input_ids_lens = torch.LongTensor(
         
     | 
| 55 | 
         
            +
                                [f["input_ids"].shape[-1] for f in features]
         
     | 
| 56 | 
         
            +
                            )
         
     | 
| 57 | 
         
            +
                            displacement = batch["input_ids"].shape[-1] - input_ids_lens
         
     | 
| 58 | 
         
            +
                            displacement = displacement.repeat_interleave(
         
     | 
| 59 | 
         
            +
                                batch["audio_batch_size"].squeeze(-1)
         
     | 
| 60 | 
         
            +
                            )
         
     | 
| 61 | 
         
            +
                            batch["audio_token_start_idx"] += displacement.to(
         
     | 
| 62 | 
         
            +
                                batch["audio_token_start_idx"].device
         
     | 
| 63 | 
         
            +
                            )
         
     | 
| 64 | 
         
            +
                    return batch
         
     | 
| 65 | 
         
            +
             
     | 
| 66 | 
         | 
| 67 | 
         
             
            class UltravoxProcessor(transformers.ProcessorMixin):
         
     | 
| 68 | 
         
             
                """
         
     | 
| 
         | 
|
| 74 | 
         
             
                """
         
     | 
| 75 | 
         | 
| 76 | 
         
             
                attributes = ["audio_processor", "tokenizer"]
         
     | 
| 77 | 
         
            +
                audio_processor_class = ("WhisperProcessor",)
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 78 | 
         
             
                tokenizer_class = (
         
     | 
| 79 | 
         
             
                    "PreTrainedTokenizer",
         
     | 
| 80 | 
         
             
                    "PreTrainedTokenizerFast",
         
     | 
| 
         | 
|
| 88 | 
         
             
                    audio_processor=None,
         
     | 
| 89 | 
         
             
                    tokenizer=None,
         
     | 
| 90 | 
         
             
                    audio_padding: str = "longest",
         
     | 
| 91 | 
         
            +
                    encoder_ds_factor: int = 2,
         
     | 
| 92 | 
         
             
                    stack_factor: int = 8,
         
     | 
| 93 | 
         
             
                    audio_placeholder: str = "<|audio|>",
         
     | 
| 94 | 
         
            +
                    # Defaults to whisper encoder context size
         
     | 
| 95 | 
         
            +
                    audio_context_size: Optional[int] = 3000,
         
     | 
| 96 | 
         
             
                ):
         
     | 
| 97 | 
         
             
                    """
         
     | 
| 98 | 
         
             
                    Args:
         
     | 
| 99 | 
         
             
                        audio_processor: The audio processor for the audio encoder.
         
     | 
| 100 | 
         
             
                        tokenizer: The tokenizer for the language model.
         
     | 
| 101 | 
         
             
                        audio_padding: The padding strategy for the audio encoder.
         
     | 
| 
         | 
|
| 102 | 
         
             
                        stack_factor: The factor by which the audio encoder output is stacked in the multimodal projector.
         
     | 
| 103 | 
         
            +
                        encoder_ds_factor: The downsampling factor of the audio encoder.
         
     | 
| 104 | 
         
             
                        audio_placeholder: The placeholder for the audio in the text.
         
     | 
| 105 | 
         
            +
                        audio_context_size: The maximum number of frames that the audio encoder can handle.
         
     | 
| 106 | 
         
             
                    """
         
     | 
| 107 | 
         
             
                    self.audio_padding = audio_padding
         
     | 
| 108 | 
         
             
                    self.encoder_ds_factor = encoder_ds_factor
         
     | 
| 109 | 
         
             
                    self.stack_factor = stack_factor
         
     | 
| 110 | 
         
             
                    self.audio_placeholder = audio_placeholder
         
     | 
| 111 | 
         
            +
                    self.audio_context_size = audio_context_size
         
     | 
| 112 | 
         
             
                    assert (
         
     | 
| 113 | 
         
            +
                        tokenizer.eos_token is not None
         
     | 
| 114 | 
         
             
                    ), "The tokenizer has no EOS token. Cannot recover."
         
     | 
| 115 | 
         
            +
                    self.vocab = tokenizer.get_vocab()
         
     | 
| 116 | 
         
            +
                    self.audio_token_replacement = tokenizer.eos_token
         
     | 
| 117 | 
         
            +
                    if tokenizer.pad_token_id is None:
         
     | 
| 118 | 
         
            +
                        tokenizer.pad_token_id = tokenizer.eos_token_id
         
     | 
| 119 | 
         
            +
             
     | 
| 120 | 
         
             
                    super().__init__(audio_processor=audio_processor, tokenizer=tokenizer)
         
     | 
| 121 | 
         | 
| 122 | 
         
            +
                @classmethod
         
     | 
| 123 | 
         
            +
                def from_pretrained(cls, pretrained_model_name_or_path: str, **kwargs):
         
     | 
| 124 | 
         
            +
                    config: UltravoxConfig = transformers.AutoConfig.from_pretrained(
         
     | 
| 125 | 
         
            +
                        pretrained_model_name_or_path, **kwargs
         
     | 
| 126 | 
         
            +
                    )
         
     | 
| 127 | 
         
            +
                    audio_processor = transformers.AutoProcessor.from_pretrained(
         
     | 
| 128 | 
         
            +
                        config.audio_model_id
         
     | 
| 129 | 
         
            +
                        or config.audio_config._name_or_path
         
     | 
| 130 | 
         
            +
                        or "openai/whisper-tiny"
         
     | 
| 131 | 
         
            +
                    )
         
     | 
| 132 | 
         
            +
             
     | 
| 133 | 
         
            +
                    tokenizer = transformers.AutoTokenizer.from_pretrained(
         
     | 
| 134 | 
         
            +
                        pretrained_model_name_or_path, **kwargs
         
     | 
| 135 | 
         
            +
                    )
         
     | 
| 136 | 
         
            +
                    tokenizer.padding_side = "left"
         
     | 
| 137 | 
         
            +
                    tokenizer.pad_token = tokenizer.eos_token
         
     | 
| 138 | 
         
            +
             
     | 
| 139 | 
         
            +
                    return cls(
         
     | 
| 140 | 
         
            +
                        audio_processor=audio_processor,
         
     | 
| 141 | 
         
            +
                        tokenizer=tokenizer,
         
     | 
| 142 | 
         
            +
                        stack_factor=config.stack_factor,
         
     | 
| 143 | 
         
            +
                    )
         
     | 
| 144 | 
         
            +
             
     | 
| 145 | 
         
            +
                def _chunk_and_pad_audio(
         
     | 
| 146 | 
         
            +
                    self,
         
     | 
| 147 | 
         
            +
                    audio_values: torch.Tensor,
         
     | 
| 148 | 
         
            +
                    audio_lens: torch.Tensor,
         
     | 
| 149 | 
         
            +
                    include_audio_num_chunks: bool = False,
         
     | 
| 150 | 
         
            +
                ) -> Dict[str, Any]:
         
     | 
| 151 | 
         
            +
                    """
         
     | 
| 152 | 
         
            +
                    Processes the audio batch by chunking any items in the batch according to the audio_context_size,
         
     | 
| 153 | 
         
            +
                    padding the last chunk if needed, and returns a dictionary with updated audio data.
         
     | 
| 154 | 
         
            +
             
     | 
| 155 | 
         
            +
                    Args:
         
     | 
| 156 | 
         
            +
                        audio_values (torch.Tensor): A tensor of audio values (e.g., in B, D, T format).
         
     | 
| 157 | 
         
            +
                        audio_lens (torch.Tensor): A tensor of audio lengths.
         
     | 
| 158 | 
         
            +
             
     | 
| 159 | 
         
            +
                    Returns:
         
     | 
| 160 | 
         
            +
                        Dict[str, Any]: Dictionary with the following keys:
         
     | 
| 161 | 
         
            +
                            - "audio_values": The concatenated audio tensor after chunking and padding.
         
     | 
| 162 | 
         
            +
                            - "audio_lens": Tensor of lengths for each chunk.
         
     | 
| 163 | 
         
            +
                            - "audio_is_continuation": Tensor of booleans indicating if the chunk is a continuation of the previous chunk.
         
     | 
| 164 | 
         
            +
                            - "audio_batch_size": A Tensor with one integer representing the number of chunks.
         
     | 
| 165 | 
         
            +
             
     | 
| 166 | 
         
            +
                    """
         
     | 
| 167 | 
         
            +
                    chunked_audio_values: List[torch.Tensor] = []
         
     | 
| 168 | 
         
            +
                    chunked_audio_lens: List[int] = []
         
     | 
| 169 | 
         
            +
                    is_continuation_list: List[bool] = []
         
     | 
| 170 | 
         
            +
                    num_chunks: List[int] = []
         
     | 
| 171 | 
         
            +
                    context_size = self.audio_context_size or audio_values.shape[-1]
         
     | 
| 172 | 
         
            +
             
     | 
| 173 | 
         
            +
                    for i in range(audio_values.shape[0]):  # iterate over the batch
         
     | 
| 174 | 
         
            +
                        num_chunks.append(int(np.ceil(audio_lens[i] / context_size)))
         
     | 
| 175 | 
         
            +
                        for offset in range(0, audio_lens[i], context_size):
         
     | 
| 176 | 
         
            +
                            is_continuation = offset > 0
         
     | 
| 177 | 
         
            +
                            chunk = audio_values[i, :, offset : offset + context_size]
         
     | 
| 178 | 
         
            +
                            if is_continuation and chunk.shape[-1] < context_size:
         
     | 
| 179 | 
         
            +
                                # N.B. We only need to pad continuation chunks. If none of the samples require chunking, the
         
     | 
| 180 | 
         
            +
                                # batch might not (need to) be padded all the way to the audio_context_size, in which case
         
     | 
| 181 | 
         
            +
                                # we've already included the padding above. On the other hand, if we have any continuation
         
     | 
| 182 | 
         
            +
                                # chunks we know that the batch needs to be padded to audio_context_size because that's what
         
     | 
| 183 | 
         
            +
                                # we're slicing to.
         
     | 
| 184 | 
         
            +
                                chunk = F.pad(chunk, (0, context_size - chunk.shape[-1]))
         
     | 
| 185 | 
         
            +
                            chunked_audio_values.append(chunk)
         
     | 
| 186 | 
         
            +
                            chunked_audio_lens.append(
         
     | 
| 187 | 
         
            +
                                min(int(audio_lens[i].item()) - offset, context_size)
         
     | 
| 188 | 
         
            +
                            )
         
     | 
| 189 | 
         
            +
                            is_continuation_list.append(is_continuation)
         
     | 
| 190 | 
         
            +
             
     | 
| 191 | 
         
            +
                    data = {
         
     | 
| 192 | 
         
            +
                        "audio_values": torch.stack(chunked_audio_values, dim=0),
         
     | 
| 193 | 
         
            +
                        "audio_lens": torch.tensor(
         
     | 
| 194 | 
         
            +
                            chunked_audio_lens, dtype=torch.int64, device=audio_values.device
         
     | 
| 195 | 
         
            +
                        ),
         
     | 
| 196 | 
         
            +
                        "audio_is_continuation": torch.tensor(
         
     | 
| 197 | 
         
            +
                            is_continuation_list, dtype=torch.bool, device=audio_values.device
         
     | 
| 198 | 
         
            +
                        ),
         
     | 
| 199 | 
         
            +
                        "audio_batch_size": torch.tensor(
         
     | 
| 200 | 
         
            +
                            [len(chunked_audio_values)], device=audio_values.device
         
     | 
| 201 | 
         
            +
                        ),
         
     | 
| 202 | 
         
            +
                    }
         
     | 
| 203 | 
         
            +
                    if include_audio_num_chunks:
         
     | 
| 204 | 
         
            +
                        data["audio_num_chunks"] = torch.tensor(
         
     | 
| 205 | 
         
            +
                            num_chunks, dtype=torch.int64, device=audio_values.device
         
     | 
| 206 | 
         
            +
                        )
         
     | 
| 207 | 
         
            +
                    return data
         
     | 
| 208 | 
         
            +
             
     | 
| 209 | 
         
             
                def __call__(
         
     | 
| 210 | 
         
             
                    self,
         
     | 
| 211 | 
         
             
                    text: Optional[str] = None,
         
     | 
| 212 | 
         
             
                    audio: Optional[Union[np.ndarray, torch.Tensor]] = None,
         
     | 
| 213 | 
         
            +
                    audios: Optional[
         
     | 
| 214 | 
         
            +
                        Union[
         
     | 
| 215 | 
         
            +
                            List[Union[np.ndarray, torch.Tensor]], Union[np.ndarray, torch.Tensor]
         
     | 
| 216 | 
         
            +
                        ]
         
     | 
| 217 | 
         
            +
                    ] = None,
         
     | 
| 218 | 
         
             
                    sampling_rate: Optional[int] = None,
         
     | 
| 219 | 
         
             
                    return_tensors: Optional[
         
     | 
| 220 | 
         
             
                        Union[str, transformers.TensorType]
         
     | 
| 221 | 
         
             
                    ] = transformers.TensorType.PYTORCH,
         
     | 
| 222 | 
         
            +
                    include_audio_num_chunks: bool = False,
         
     | 
| 223 | 
         
             
                    **kwargs,
         
     | 
| 224 | 
         
             
                ) -> transformers.BatchFeature:
         
     | 
| 225 | 
         
             
                    """
         
     | 
| 226 | 
         
             
                    Main method to prepare for the model one text sequence and audio. This method forwards the `text`
         
     | 
| 227 | 
         
             
                    and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode
         
     | 
| 228 | 
         
             
                    the text. To prepare the audio(s), this method forwards the `audio`, `sampling_rate` and `kwargs` arguments to
         
     | 
| 229 | 
         
            +
                    audio processor's [`~WhisperProcessor.__call__`] if `audio` is not `None`. Please refer to the docstring
         
     | 
| 230 | 
         
             
                    of the above two methods for more information.
         
     | 
| 231 | 
         | 
| 232 | 
         
             
                    Args:
         
     | 
| 233 | 
         
             
                        text (`str`, `List[str]`):
         
     | 
| 234 | 
         
             
                            The sequence to be encoded. Sequence can be a string or (pretokenized string).
         
     | 
| 235 | 
         
             
                        audio (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
         
     | 
| 236 | 
         
            +
                            The audio to be prepared. Audio can be a single-channel (1-dimensional) NumPy array or PyTorch tensor.
         
     | 
| 237 | 
         
            +
                        audios (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`):
         
     | 
| 238 | 
         
            +
                            A list or two dimensional array of audio to be prepared.
         
     | 
| 239 | 
         
             
                        sampling_rate (`int`, *optional*, defaults to 16000):
         
     | 
| 240 | 
         
             
                            Sampling rate of the input audio. We expect 16kHz audio. Don't change this value unless you know what
         
     | 
| 241 | 
         
             
                            you are doing.
         
     | 
| 
         | 
|
| 259 | 
         
             
                          Returned when `audio` is not `None`.
         
     | 
| 260 | 
         
             
                        - **audio_token_start_idx** -- The index in the tokenized text where the audio starts. Returned when `audio` is not `None`.
         
     | 
| 261 | 
         
             
                    """
         
     | 
| 262 | 
         
            +
                    # TODO: Add support for multiple text inputs.
         
     | 
| 263 | 
         
            +
                    if audio is not None and audios is not None:
         
     | 
| 264 | 
         
            +
                        raise ValueError("Only one of `audio` or `audios` should be provided.")
         
     | 
| 265 | 
         
            +
                    elif audio is not None:
         
     | 
| 266 | 
         
            +
                        audios = audio if isinstance(audio, list) or audio.ndim == 2 else [audio]
         
     | 
| 267 | 
         
            +
                    elif audios is None:
         
     | 
| 268 | 
         
            +
                        audios = []
         
     | 
| 269 | 
         
            +
             
     | 
| 270 | 
         
             
                    data = {}
         
     | 
| 271 | 
         
            +
                    audio_is_continuation = []
         
     | 
| 272 | 
         
            +
                    if len(audios) > 0:
         
     | 
| 273 | 
         
            +
                        audios = [x.numpy() if isinstance(x, torch.Tensor) else x for x in audios]
         
     | 
| 274 | 
         
            +
             
     | 
| 275 | 
         
            +
                        # Pad out each audio to at least 2 hops (the minimum required by the processor).
         
     | 
| 276 | 
         
            +
                        hop_length = self.audio_processor.feature_extractor.hop_length
         
     | 
| 277 | 
         
            +
                        audios = [
         
     | 
| 278 | 
         
            +
                            (
         
     | 
| 279 | 
         
            +
                                np.pad(x, (0, 2 * hop_length - len(x)), mode="constant")
         
     | 
| 280 | 
         
            +
                                if len(x) < 2 * hop_length
         
     | 
| 281 | 
         
            +
                                else x
         
     | 
| 282 | 
         
            +
                            )
         
     | 
| 283 | 
         
            +
                            for x in audios
         
     | 
| 284 | 
         
            +
                        ]
         
     | 
| 285 | 
         | 
| 286 | 
         
             
                        # Main audio processing. The processor is model-specific.
         
     | 
| 287 | 
         
            +
                        x: transformers.BatchFeature = self.audio_processor(
         
     | 
| 288 | 
         
            +
                            audios,
         
     | 
| 289 | 
         
             
                            sampling_rate=sampling_rate,
         
     | 
| 290 | 
         
             
                            padding="longest",
         
     | 
| 291 | 
         
            +
                            pad_to_multiple_of=hop_length,  # The attention mask effectively gets padded to the hop length, so pad the audio to be consistent.
         
     | 
| 292 | 
         
            +
                            truncation=False,
         
     | 
| 293 | 
         
            +
                            return_attention_mask=True,
         
     | 
| 294 | 
         
             
                            **kwargs,
         
     | 
| 295 | 
         
             
                        )
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 296 | 
         | 
| 297 | 
         
            +
                        data.update(
         
     | 
| 298 | 
         
            +
                            self._chunk_and_pad_audio(
         
     | 
| 299 | 
         
            +
                                audio_values=torch.as_tensor(
         
     | 
| 300 | 
         
            +
                                    x.input_features if "input_features" in x else x.input_values
         
     | 
| 301 | 
         
            +
                                ),
         
     | 
| 302 | 
         
            +
                                audio_lens=torch.as_tensor(x.attention_mask).sum(-1),
         
     | 
| 303 | 
         
            +
                                include_audio_num_chunks=include_audio_num_chunks,
         
     | 
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 
         | 
|
| 304 | 
         
             
                            )
         
     | 
| 305 | 
         
            +
                        )
         
     | 
| 306 | 
         
            +
             
     | 
| 307 | 
         
            +
                        audio_is_continuation = data.pop("audio_is_continuation")
         
     | 
| 308 | 
         
            +
                        data["audio_token_len"] = torch.ceil(
         
     | 
| 309 | 
         
            +
                            data["audio_lens"] / (self.encoder_ds_factor * self.stack_factor)
         
     | 
| 310 | 
         
            +
                        ).to(dtype=torch.int)
         
     | 
| 311 | 
         
            +
             
     | 
| 312 | 
         
            +
                    if text is not None:
         
     | 
| 313 | 
         
            +
                        if not isinstance(text, str):
         
     | 
| 314 | 
         
            +
                            raise ValueError("Text must be a string. Batch mode not supported yet.")
         
     | 
| 315 | 
         | 
| 316 | 
         
             
                        # Special tokens like BOS should already have been added by the caller.
         
     | 
| 317 | 
         
            +
                        tokenized_parts = self.tokenizer(
         
     | 
| 318 | 
         
            +
                            text.split(
         
     | 
| 319 | 
         
            +
                                "<|audio|>"  # The placeholder isn't part of the vocabulary, so split the text around it.
         
     | 
| 320 | 
         
            +
                            ),
         
     | 
| 321 | 
         
            +
                            add_special_tokens=False,
         
     | 
| 322 | 
         
            +
                            **kwargs,
         
     | 
| 323 | 
         
            +
                        )
         
     | 
| 324 | 
         
            +
             
     | 
| 325 | 
         
            +
                        audio_token_start_idx = []
         
     | 
| 326 | 
         
            +
                        placeholder_index = -1
         
     | 
| 327 | 
         
            +
                        split_input_ids = tokenized_parts["input_ids"]
         
     | 
| 328 | 
         
            +
                        input_ids: List[int] = []
         
     | 
| 329 | 
         
            +
             
     | 
| 330 | 
         
            +
                        audio_token_replacement_token_id = self.vocab[self.audio_token_replacement]
         
     | 
| 331 | 
         
            +
             
     | 
| 332 | 
         
            +
                        for i, token_len in enumerate(data.get("audio_token_len", [])):
         
     | 
| 333 | 
         
            +
                            if not audio_is_continuation[i]:
         
     | 
| 334 | 
         
            +
                                placeholder_index += 1
         
     | 
| 335 | 
         
            +
                                if placeholder_index >= len(split_input_ids):
         
     | 
| 336 | 
         
            +
                                    raise ValueError(
         
     | 
| 337 | 
         
            +
                                        f"Text contains too few audio placeholders. (Expected {len(audios)} placeholders)"
         
     | 
| 338 | 
         
            +
                                    )
         
     | 
| 339 | 
         
            +
             
     | 
| 340 | 
         
            +
                                input_ids.extend(split_input_ids[placeholder_index])
         
     | 
| 341 | 
         
            +
             
     | 
| 342 | 
         
            +
                            audio_token_start_idx.append(len(input_ids))
         
     | 
| 343 | 
         
            +
             
     | 
| 344 | 
         
            +
                            input_ids.extend([audio_token_replacement_token_id] * token_len)
         
     | 
| 345 | 
         
            +
             
     | 
| 346 | 
         
            +
                        # Include any tokens after the last audio.
         
     | 
| 347 | 
         
            +
                        placeholder_index += 1
         
     | 
| 348 | 
         
            +
                        if placeholder_index != len(split_input_ids) - 1:
         
     | 
| 349 | 
         
            +
                            raise ValueError(
         
     | 
| 350 | 
         
            +
                                f"Text contains too many audio placeholders. (Expected {len(audios)} placeholders)"
         
     | 
| 351 | 
         
            +
                            )
         
     | 
| 352 | 
         
            +
                        input_ids.extend(split_input_ids[placeholder_index])
         
     | 
| 353 | 
         
            +
             
     | 
| 354 | 
         
            +
                        if "audio_token_len" in data:
         
     | 
| 355 | 
         
            +
                            data["audio_token_start_idx"] = torch.as_tensor(audio_token_start_idx)
         
     | 
| 356 | 
         
            +
             
     | 
| 357 | 
         
            +
                        data["input_ids"] = [input_ids]
         
     | 
| 358 | 
         
            +
                        data["attention_mask"] = [[1] * len(input_ids)]
         
     | 
| 359 | 
         
            +
             
     | 
| 360 | 
         
            +
                        # Ensure that there are no audio placeholders after the last audio.
         
     | 
| 361 | 
         | 
| 362 | 
         
             
                    return transformers.BatchFeature(data=data, tensor_type=return_tensors)
         
     | 
| 363 | 
         | 
| 
         | 
|
| 372 | 
         
             
                    tokenizer_input_names = self.tokenizer.model_input_names
         
     | 
| 373 | 
         
             
                    audio_processor_input_names = self.audio_processor.model_input_names
         
     | 
| 374 | 
         
             
                    return list(set(tokenizer_input_names + audio_processor_input_names))
         
     | 
| 375 | 
         
            +
             
     | 
| 376 | 
         
            +
             
     | 
| 377 | 
         
            +
            UltravoxProcessor.register_for_auto_class()
         
     | 
| 378 | 
         
            +
             
     | 
| 379 | 
         
            +
            transformers.AutoProcessor.register(UltravoxConfig, UltravoxProcessor)
         
     |