configuration_jamba.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. # coding=utf-8
  2. # Copyright 2024 AI21 Labs Ltd. and 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. """Jamba model configuration"""
  16. import math
  17. from ...configuration_utils import PretrainedConfig
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. class JambaConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`JambaModel`]. It is used to instantiate a
  23. Jamba model according to the specified arguments, defining the model architecture. Instantiating a configuration
  24. with the defaults will yield a similar configuration to that of the Jamba-v0.1 model.
  25. [ai21labs/Jamba-v0.1](https://huggingface.co/ai21labs/Jamba-v0.1)
  26. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  27. documentation from [`PretrainedConfig`] for more information.
  28. Args:
  29. vocab_size (`int`, *optional*, defaults to 65536):
  30. Vocabulary size of the Jamba model. Defines the number of different tokens that can be represented by the
  31. `inputs_ids` passed when calling [`JambaModel`]
  32. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  33. Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
  34. model has a output word embedding layer.
  35. hidden_size (`int`, *optional*, defaults to 4096):
  36. Dimension of the hidden representations.
  37. intermediate_size (`int`, *optional*, defaults to 14336):
  38. Dimension of the MLP representations.
  39. num_hidden_layers (`int`, *optional*, defaults to 32):
  40. Number of hidden layers in the Transformer encoder.
  41. num_attention_heads (`int`, *optional*, defaults to 32):
  42. Number of attention heads for each attention layer in the Transformer encoder.
  43. num_key_value_heads (`int`, *optional*, defaults to 8):
  44. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  45. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  46. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  47. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  48. by meanpooling all the original heads within that group. For more details, check out [this
  49. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `8`.
  50. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  51. The non-linear activation function (function or string) in the decoder.
  52. initializer_range (`float`, *optional*, defaults to 0.02):
  53. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  54. rms_norm_eps (`float`, *optional*, defaults to 1e-06):
  55. The epsilon used by the rms normalization layers.
  56. use_cache (`bool`, *optional*, defaults to `True`):
  57. Whether or not the model should return the last key/values attentions (not used by all models). Only
  58. relevant if `config.is_decoder=True`.
  59. num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
  60. Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
  61. integer value, only last `num_logits_to_keep` logits will be calculated. Default is 1 because only the
  62. logits of the last prompt token are needed for generation. For long sequences, the logits for the entire
  63. sequence may use a lot of memory so, setting `num_logits_to_keep=1` will reduce memory footprint
  64. significantly.
  65. output_router_logits (`bool`, *optional*, defaults to `False`):
  66. Whether or not the router logits should be returned by the model. Enabling this will also
  67. allow the model to output the auxiliary loss. See [here]() for more details
  68. router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
  69. The aux loss factor for the total loss.
  70. pad_token_id (`int`, *optional*, defaults to 0):
  71. The id of the padding token.
  72. bos_token_id (`int`, *optional*, defaults to 1):
  73. The id of the "beginning-of-sequence" token.
  74. eos_token_id (`int`, *optional*, defaults to 2):
  75. The id of the "end-of-sequence" token.
  76. sliding_window (`int`, *optional*):
  77. Sliding window attention window size. If not specified, will default to `None`.
  78. max_position_embeddings (`int`, *optional*, defaults to 262144):
  79. This value doesn't have any real effect. The maximum sequence length that this model is intended to be
  80. used with. It can be used with longer sequences, but performance may degrade.
  81. attention_dropout (`float`, *optional*, defaults to 0.0):
  82. The dropout ratio for the attention probabilities.
  83. num_experts_per_tok (`int`, *optional*, defaults to 2):
  84. The number of experts to root per-token, can be also interpreted as the `top-p` routing
  85. parameter
  86. num_experts (`int`, *optional*, defaults to 16):
  87. Number of experts per Sparse MLP layer.
  88. expert_layer_period (`int`, *optional*, defaults to 2):
  89. Once in this many layers, we will have an expert layer
  90. expert_layer_offset (`int`, *optional*, defaults to 1):
  91. The first layer index that contains an expert mlp layer
  92. attn_layer_period (`int`, *optional*, defaults to 8):
  93. Once in this many layers, we will have a vanilla attention layer
  94. attn_layer_offset (`int`, *optional*, defaults to 4):
  95. The first layer index that contains a vanilla attention mlp layer
  96. use_mamba_kernels (`bool`, *optional*, defaults to `True`):
  97. Flag indicating whether or not to use the fast mamba kernels. These are available only if `mamba-ssm` and
  98. `causal-conv1d` are installed, and the mamba modules are running on a CUDA device. Raises ValueError if
  99. `True` and kernels are not available
  100. mamba_d_state (`int`, *optional*, defaults to 16):
  101. The dimension the mamba state space latents
  102. mamba_d_conv (`int`, *optional*, defaults to 4):
  103. The size of the mamba convolution kernel
  104. mamba_expand (`int`, *optional*, defaults to 2):
  105. Expanding factor (relative to hidden_size) used to determine the mamba intermediate size
  106. mamba_dt_rank (`Union[int,str]`, *optional*, defaults to `"auto"`):
  107. Rank of the mamba discretization projection matrix. `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)`
  108. mamba_conv_bias (`bool`, *optional*, defaults to `True`):
  109. Flag indicating whether or not to use bias in the convolution layer of the mamba mixer block.
  110. mamba_proj_bias (`bool`, *optional*, defaults to `False`):
  111. Flag indicating whether or not to use bias in the input and output projections (["in_proj", "out_proj"]) of the mamba mixer block
  112. """
  113. model_type = "jamba"
  114. keys_to_ignore_at_inference = ["past_key_values"]
  115. def __init__(
  116. self,
  117. vocab_size=65536,
  118. tie_word_embeddings=False,
  119. hidden_size=4096,
  120. intermediate_size=14336,
  121. num_hidden_layers=32,
  122. num_attention_heads=32,
  123. num_key_value_heads=8,
  124. hidden_act="silu",
  125. initializer_range=0.02,
  126. rms_norm_eps=1e-6,
  127. use_cache=True,
  128. num_logits_to_keep=1,
  129. output_router_logits=False,
  130. router_aux_loss_coef=0.001,
  131. pad_token_id=0,
  132. bos_token_id=1,
  133. eos_token_id=2,
  134. sliding_window=None,
  135. max_position_embeddings=262144,
  136. attention_dropout=0.0,
  137. num_experts_per_tok=2,
  138. num_experts=16,
  139. expert_layer_period=2,
  140. expert_layer_offset=1,
  141. attn_layer_period=8,
  142. attn_layer_offset=4,
  143. use_mamba_kernels=True,
  144. mamba_d_state=16,
  145. mamba_d_conv=4,
  146. mamba_expand=2,
  147. mamba_dt_rank="auto",
  148. mamba_conv_bias=True,
  149. mamba_proj_bias=False,
  150. **kwargs,
  151. ):
  152. self.vocab_size = vocab_size
  153. self.tie_word_embeddings = tie_word_embeddings
  154. self.hidden_size = hidden_size
  155. self.intermediate_size = intermediate_size
  156. self.num_hidden_layers = num_hidden_layers
  157. self.num_attention_heads = num_attention_heads
  158. self.sliding_window = sliding_window
  159. self.max_position_embeddings = max_position_embeddings
  160. self.attention_dropout = attention_dropout
  161. # for backward compatibility
  162. if num_key_value_heads is None:
  163. num_key_value_heads = num_attention_heads
  164. self.num_key_value_heads = num_key_value_heads
  165. self.hidden_act = hidden_act
  166. self.initializer_range = initializer_range
  167. self.rms_norm_eps = rms_norm_eps
  168. self.use_cache = use_cache
  169. self.num_logits_to_keep = num_logits_to_keep
  170. self.output_router_logits = output_router_logits
  171. self.router_aux_loss_coef = router_aux_loss_coef
  172. self.num_experts_per_tok = num_experts_per_tok
  173. self.num_experts = num_experts
  174. self.expert_layer_period = expert_layer_period
  175. self.expert_layer_offset = expert_layer_offset
  176. self.attn_layer_period = attn_layer_period
  177. self.attn_layer_offset = attn_layer_offset
  178. self._check_supported_offset("attention", self.attn_layer_period, self.attn_layer_offset)
  179. self._check_supported_offset("expert", self.expert_layer_period, self.expert_layer_offset)
  180. self.use_mamba_kernels = use_mamba_kernels
  181. self.mamba_d_state = mamba_d_state
  182. self.mamba_d_conv = mamba_d_conv
  183. self.mamba_expand = mamba_expand
  184. self.mamba_dt_rank = math.ceil(self.hidden_size / 16) if mamba_dt_rank == "auto" else mamba_dt_rank
  185. self.mamba_conv_bias = mamba_conv_bias
  186. self.mamba_proj_bias = mamba_proj_bias
  187. super().__init__(
  188. pad_token_id=pad_token_id,
  189. bos_token_id=bos_token_id,
  190. eos_token_id=eos_token_id,
  191. tie_word_embeddings=tie_word_embeddings,
  192. **kwargs,
  193. )
  194. @property
  195. def layers_block_type(self):
  196. return [
  197. "attention" if i % self.attn_layer_period == self.attn_layer_offset else "mamba"
  198. for i in range(self.num_hidden_layers)
  199. ]
  200. @property
  201. def layers_num_experts(self):
  202. return [
  203. self.num_experts if i % self.expert_layer_period == self.expert_layer_offset else 1
  204. for i in range(self.num_hidden_layers)
  205. ]
  206. def _check_supported_offset(self, property_: str, period: int, offset: int):
  207. if offset >= period:
  208. raise ValueError(
  209. f"{property_} layer offset ({offset}) must be smaller than {property_} layer period ({period})"
  210. )
  211. __all__ = ["JambaConfig"]