configuration_moshi.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # Copyright 2024 Meta AI and The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Moshi model configuration"""
  15. from huggingface_hub.dataclasses import strict
  16. from ...configuration_utils import PreTrainedConfig
  17. from ...modeling_rope_utils import RopeParameters
  18. from ...utils import auto_docstring
  19. from ..auto.configuration_auto import AutoConfig
  20. @auto_docstring(checkpoint="kmhf/hf-moshiko")
  21. @strict
  22. class MoshiDepthConfig(PreTrainedConfig):
  23. r"""
  24. input_size (`int`, *optional*, defaults to 4096):
  25. Dimensionality of the input hidden states. Used to connect the main decoder to the depth decoder.
  26. audio_vocab_size (`int`, *optional*, defaults to 2048):
  27. Vocabulary size of the audio part of model. Defines the number of different tokens that can be
  28. represented by the `audio_codes` passed when calling the Moshi models.
  29. ffn_dim (`int`, *optional*, defaults to 5632):
  30. Dimensionality of the "intermediate" (often named feed-forward) layer in the depth decoder block. Must be even.
  31. Example:
  32. ```python
  33. >>> from transformers import (
  34. ... MoshiDepthConfig,
  35. ... MoshiDepthDecoder,
  36. ... )
  37. >>> configuration = MoshiDepthConfig()
  38. >>> # Initializing a MoshiDepthDecoder (with random weights) from the kmhf/hf-moshiko style configuration
  39. >>> model = MoshiDepthDecoder(configuration)
  40. >>> # Accessing the model configuration
  41. >>> configuration = model.config
  42. ```"""
  43. model_type = "moshi_depth"
  44. keys_to_ignore_at_inference = ["past_key_values"]
  45. vocab_size: int = 32000
  46. hidden_size: int = 1024
  47. input_size: int = 4096
  48. num_hidden_layers: int = 6
  49. num_attention_heads: int = 16
  50. num_key_value_heads: int | None = None
  51. audio_vocab_size: int = 2048
  52. max_position_embeddings: int = 9
  53. hidden_act: str = "silu"
  54. head_dim: int | None = None
  55. initializer_range: float = 0.02
  56. use_cache: bool = True
  57. sliding_window: int = 8
  58. attention_dropout: float | int = 0.0
  59. ffn_dim: int = 5632
  60. rms_norm_eps: float = 1e-8
  61. num_codebooks: int = 8
  62. tie_word_embeddings: bool = False
  63. pad_token_id: int | None = None
  64. bos_token_id: int | None = None
  65. eos_token_id: int | list[int] | None = None
  66. def __post_init__(self, **kwargs):
  67. self.num_key_value_heads = (
  68. self.num_key_value_heads if self.num_key_value_heads is not None else self.num_attention_heads
  69. )
  70. self.head_dim = self.head_dim or self.hidden_size // self.num_attention_heads
  71. super().__post_init__(**kwargs)
  72. def validate_architecture(self):
  73. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  74. if self.ffn_dim % 2 == 1:
  75. raise ValueError(f"`ffn_dim={self.ffn_dim}` must be even.")
  76. @auto_docstring(checkpoint="kmhf/hf-moshiko")
  77. @strict
  78. class MoshiConfig(PreTrainedConfig):
  79. r"""
  80. audio_vocab_size (`int`, *optional*):
  81. Vocabulary size of the audio part of model. Defines the number of different tokens that can be
  82. represented by the `audio_codes` passed when calling the Moshi models.
  83. ffn_dim (`int`, *optional*, defaults to 22528):
  84. Dimensionality of the "intermediate" (often named feed-forward) layer in the main decoder block. Must be even.
  85. audio_encoder_config (`PreTrainedConfig | dict`, *optional*):
  86. Configuration for the audio encoder.
  87. depth_decoder_config (`PreTrainedConfig | dict`, *optional*):
  88. Configuration for the depth decoder.
  89. Example:
  90. ```python
  91. >>> from transformers import (
  92. ... MoshiConfig,
  93. ... MoshiForConditionalGeneration,
  94. ... )
  95. >>> configuration = MoshiConfig()
  96. >>> # Initializing a MoshiForConditionalGeneration (with random weights) from the kmhf/hf-moshiko style configuration
  97. >>> model = MoshiForConditionalGeneration(configuration)
  98. >>> # Accessing the model configuration
  99. >>> configuration = model.config
  100. >>> # Saving the model, including its configuration
  101. >>> model.save_pretrained("kmhf/hf-moshiko")
  102. >>> # loading model and config from pretrained folder
  103. >>> moshi_config = MoshiConfig.from_pretrained("kmhf/hf-moshiko")
  104. >>> model = MoshiForConditionalGeneration.from_pretrained("kmhf/hf-moshiko", config=moshi_config)
  105. ```"""
  106. model_type = "moshi"
  107. keys_to_ignore_at_inference = ["past_key_values"]
  108. sub_configs = {"audio_encoder_config": AutoConfig, "depth_decoder_config": MoshiDepthConfig}
  109. vocab_size: int = 32000
  110. hidden_size: int = 4096
  111. num_hidden_layers: int = 32
  112. num_attention_heads: int = 32
  113. num_key_value_heads: int | None = None
  114. audio_vocab_size: int | None = None
  115. max_position_embeddings: int = 3000
  116. rope_parameters: RopeParameters | dict | None = None
  117. hidden_act: str = "silu"
  118. head_dim: int | None = None
  119. initializer_range: float = 0.02
  120. use_cache: bool = True
  121. sliding_window: int = 3000
  122. attention_dropout: float | int = 0.0
  123. ffn_dim: int = 22528
  124. rms_norm_eps: float = 1e-8
  125. num_codebooks: int = 8
  126. tie_word_embeddings: bool = False
  127. pad_token_id: int | None = None
  128. bos_token_id: int | None = None
  129. eos_token_id: int | list[int] | None = None
  130. audio_encoder_config: dict | PreTrainedConfig | None = None
  131. depth_decoder_config: dict | PreTrainedConfig | None = None
  132. def __post_init__(self, **kwargs):
  133. self.num_key_value_heads = (
  134. self.num_key_value_heads if self.num_key_value_heads is not None else self.num_attention_heads
  135. )
  136. self.head_dim = self.head_dim or self.hidden_size // self.num_attention_heads
  137. if isinstance(self.audio_encoder_config, dict):
  138. audio_encoder_model_type = self.audio_encoder_config.pop("model_type", "mimi")
  139. self.audio_encoder_config = AutoConfig.for_model(audio_encoder_model_type, **self.audio_encoder_config)
  140. elif self.audio_encoder_config is None:
  141. self.audio_encoder_config = AutoConfig.for_model("mimi")
  142. self.audio_vocab_size = (
  143. self.audio_encoder_config.codebook_size if self.audio_vocab_size is None else self.audio_vocab_size
  144. )
  145. if isinstance(self.depth_decoder_config, dict):
  146. self.depth_decoder_config.update(
  147. {
  148. "audio_vocab_size": self.audio_vocab_size,
  149. "input_size": self.hidden_size,
  150. "vocab_size": self.vocab_size,
  151. "num_codebooks": self.num_codebooks,
  152. }
  153. )
  154. self.depth_decoder_config = MoshiDepthConfig(**self.depth_decoder_config)
  155. elif self.depth_decoder_config is None:
  156. self.depth_decoder_config = MoshiDepthConfig()
  157. super().__post_init__(**kwargs)
  158. def validate_architecture(self):
  159. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  160. if self.ffn_dim % 2 == 1:
  161. raise ValueError(f"`ffn_dim={self.ffn_dim}` must be even.")
  162. if self.num_codebooks > self.audio_encoder_config.num_codebooks:
  163. raise ValueError(
  164. f"`num_codebooks={self.num_codebooks}` is greater than the maximum number of codebooks that the audio encoder can deal with ({self.audio_encoder_config.num_codebooks}). Please lower it."
  165. )
  166. @property
  167. def sampling_rate(self):
  168. return self.audio_encoder_config.sampling_rate
  169. @classmethod
  170. def from_audio_encoder_config(
  171. cls,
  172. audio_encoder_config: PreTrainedConfig,
  173. **kwargs,
  174. ):
  175. r"""
  176. Instantiate a [`MoshiConfig`] (or a derived class) from an audio encoder configuration.
  177. Returns:
  178. [`MoshiConfig`]: An instance of a configuration object
  179. """
  180. return cls(
  181. audio_encoder_config=audio_encoder_config.to_dict(),
  182. **kwargs,
  183. )
  184. __all__ = ["MoshiConfig", "MoshiDepthConfig"]