configuration_voxtral.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # coding=utf-8
  2. # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from ...configuration_utils import PretrainedConfig
  16. from ..auto import CONFIG_MAPPING, AutoConfig
  17. class VoxtralEncoderConfig(PretrainedConfig):
  18. r"""
  19. This is the configuration class to store the configuration of a [`VoxtralEncoder`]. It is used to instantiate a
  20. Voxtral audio encoder according to the specified arguments, defining the model architecture. Instantiating a
  21. configuration with the defaults will yield a similar configuration to that of the audio encoder of the Voxtral
  22. architecture.
  23. e.g. [mistralai/Voxtral-Mini-3B-2507](https://huggingface.co/mistralai/Voxtral-Mini-3B-2507)
  24. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  25. documentation from [`PretrainedConfig`] for more information.
  26. Args:
  27. vocab_size (`int`, *optional*, defaults to 51866):
  28. Vocabulary size of the model.
  29. hidden_size (`int`, *optional*, defaults to 1280):
  30. Dimensionality of the hidden representations.
  31. intermediate_size (`int`, *optional*, defaults to 5120):
  32. Dimension of the MLP representations.
  33. num_hidden_layers (`int`, *optional*, defaults to 32):
  34. Number of hidden layers in the Transformer encoder.
  35. num_attention_heads (`int`, *optional*, defaults to 20):
  36. Number of attention heads for each attention layer in the Transformer encoder.
  37. scale_embedding (`bool`, *optional*, defaults to `False`):
  38. Scale embeddings by dividing by sqrt(hidden_size) if True.
  39. activation_function (`str`, *optional*, defaults to `"gelu"`):
  40. The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu",
  41. num_mel_bins (`int`, *optional*, defaults to 128):
  42. Number of mel features used per input features. Should correspond to the value used in the
  43. `VoxtralProcessor` class.
  44. max_source_positions (`int`, *optional*, defaults to 1500):
  45. The maximum sequence length of log-mel filter-bank features that this model might ever be used with.
  46. initializer_range (`float`, *optional*, defaults to 0.02):
  47. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  48. attention_dropout (`float`, *optional*, defaults to 0.0):
  49. The dropout ratio for the attention probabilities.
  50. ```python
  51. >>> from transformers import VoxtralEncoderConfig, VoxtralEncoder
  52. >>> # Initializing a VoxtralEncoderConfig
  53. >>> configuration = VoxtralEncoderConfig()
  54. >>> # Initializing a VoxtralEncoder (with random weights)
  55. >>> model = VoxtralEncoder(configuration)
  56. >>> # Accessing the model configuration
  57. >>> configuration = model.config
  58. ```"""
  59. model_type = "voxtral_encoder"
  60. attribute_map = {
  61. "d_model": "hidden_size",
  62. "encoder_layers": "num_hidden_layers",
  63. "encoder_attention_heads": "num_attention_heads",
  64. "encoder_ffn_dim": "intermediate_size",
  65. "encoder_layerdrop": "layerdrop",
  66. }
  67. def __init__(
  68. self,
  69. vocab_size=51866,
  70. hidden_size=1280,
  71. intermediate_size=5120,
  72. num_hidden_layers=32,
  73. num_attention_heads=20,
  74. scale_embedding=False,
  75. activation_function="gelu",
  76. num_mel_bins=128,
  77. max_source_positions=1500,
  78. initializer_range=0.02,
  79. attention_dropout=0.0,
  80. **kwargs,
  81. ):
  82. super().__init__(**kwargs)
  83. self.vocab_size = vocab_size
  84. self.hidden_size = hidden_size
  85. self.intermediate_size = intermediate_size
  86. self.num_hidden_layers = num_hidden_layers
  87. self.num_attention_heads = num_attention_heads
  88. self.scale_embedding = scale_embedding # scale factor will be sqrt(hidden_size) if True
  89. self.activation_function = activation_function
  90. self.num_mel_bins = num_mel_bins
  91. self.max_source_positions = max_source_positions
  92. self.initializer_range = initializer_range
  93. # TODO: @eustlb, we do not use dropout and layerdrop, yet we need to hardcode them
  94. # to be able to use Whisper with modular (here actually from Qwen2-Audio and copied from).
  95. # After a future Whisper refactor, we should remove this.
  96. self.dropout = 0.0
  97. self.layerdrop = 0.0
  98. self.activation_dropout = 0.0
  99. self.attention_dropout = attention_dropout
  100. class VoxtralConfig(PretrainedConfig):
  101. r"""
  102. This is the configuration class to store the configuration of a [`VoxtralForConditionalGeneration`]. It is used to instantiate an
  103. Voxtral model according to the specified arguments, defining the model architecture. Instantiating a configuration
  104. with the defaults will yield a similar configuration to that of the Voxtral-Mini-3B.
  105. e.g. [mistralai/Voxtral-Mini-3B-2507](https://huggingface.co/mistralai/Voxtral-Mini-3B-2507)
  106. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  107. documentation from [`PretrainedConfig`] for more information.
  108. Args:
  109. audio_config (`Union[AutoConfig, dict]`, *optional*):
  110. The config object or dictionary of the audio encoder.
  111. text_config (`Union[AutoConfig, dict]`, *optional*):
  112. The config object or dictionary of the text model.
  113. audio_token_id (`int`, *optional*):
  114. The image token index to encode the image prompt.
  115. projector_hidden_act (`str`, *optional*, defaults to `"gelu"`):
  116. The activation function (function or string) in the multi-modal projector.
  117. ```python
  118. >>> from transformers import VoxtralForConditionalGeneration, VoxtralConfig
  119. >>> # Initializing a Voxtral configuration
  120. >>> configuration = VoxtralConfig(audio_token_id=24, projector_hidden_act="gelu")
  121. >>> # Initializing a 3B model with random weights
  122. >>> model = VoxtralForConditionalGeneration(configuration)
  123. >>> # Accessing the model configuration
  124. >>> configuration = model.config
  125. ```"""
  126. model_type = "voxtral"
  127. sub_configs = {"text_config": AutoConfig, "audio_config": AutoConfig}
  128. _default_text_config_kwargs = {
  129. "vocab_size": 131072,
  130. "hidden_size": 3072,
  131. "intermediate_size": 8192,
  132. "num_hidden_layers": 30,
  133. "num_key_value_heads": 8,
  134. "max_position_embeddings": 131072,
  135. "rms_norm_eps": 1e-05,
  136. "use_cache": True,
  137. "rope_theta": 100000000.0,
  138. "head_dim": 128,
  139. }
  140. def __init__(
  141. self,
  142. audio_config=None,
  143. text_config=None,
  144. audio_token_id=None,
  145. projector_hidden_act="gelu",
  146. **kwargs,
  147. ):
  148. if isinstance(audio_config, dict):
  149. audio_config["model_type"] = audio_config.get("model_type", "voxtral_encoder")
  150. audio_config = CONFIG_MAPPING[audio_config["model_type"]](**audio_config)
  151. elif audio_config is None:
  152. audio_config = CONFIG_MAPPING["voxtral_encoder"]()
  153. self.audio_config = audio_config
  154. if isinstance(text_config, dict):
  155. text_config["model_type"] = text_config.get("model_type", "llama")
  156. text_config = CONFIG_MAPPING[text_config["model_type"]](
  157. **{**self._default_text_config_kwargs, **text_config}
  158. )
  159. elif text_config is None:
  160. text_config = CONFIG_MAPPING["llama"](**self._default_text_config_kwargs)
  161. self.text_config = text_config
  162. self.vocab_size = text_config.vocab_size
  163. self.hidden_size = text_config.hidden_size
  164. self.audio_token_id = audio_token_id
  165. self.projector_hidden_act = projector_hidden_act
  166. super().__init__(**kwargs)
  167. __all__ = ["VoxtralEncoderConfig", "VoxtralConfig"]