configuration_zamba.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. # coding=utf-8
  2. # Copyright 2024 Zyphra Technologies 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. """Zamba model configuration"""
  16. import math
  17. from ...configuration_utils import PretrainedConfig
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. class ZambaConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`ZambaModel`]. It is used to instantiate a
  23. Zamba 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 Zamba-v0.1 model.
  25. [Zyphra/Zamba-7B-v1](https://huggingface.co/Zyphra/Zamba-7B-v1)
  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 32000):
  30. Vocabulary size of the Zamba model. Defines the number of different tokens that can be represented by the
  31. `inputs_ids` passed when calling [`ZambaModel`]
  32. tie_word_embeddings (`bool`, *optional*, defaults to `True`):
  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 3712):
  36. Dimension of the hidden representations.
  37. attention_hidden_size (`int`, *optional*):
  38. Dimension of the hidden representations of the inputs to the Attention layer.
  39. intermediate_size (`int`, *optional*, defaults to 14848):
  40. Dimension of the MLP representations.
  41. num_hidden_layers (`int`, *optional*, defaults to 76):
  42. Number of hidden layers in the model.
  43. num_attention_heads (`int`, *optional*, defaults to 16):
  44. Number of attention heads for each attention layer in the Transformer decoder.
  45. attention_head_dim (`int`, *optional*):
  46. Dimension of the attention head in the Transformer decoder.
  47. num_key_value_heads (`int`, *optional*, defaults to 16):
  48. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  49. `num_key_value_heads=None`, the model will use Multi Head Attention (MHA), if
  50. `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  51. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  52. by meanpooling all the original heads within that group. For more details, check out [this
  53. paper](https://huggingface.co/papers/2305.13245).
  54. n_mamba_heads (`int`, *optional*, defaults to 2):
  55. Number of mamba heads for each mamba layer.
  56. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  57. The non-linear activation function (function or string) in the decoder.
  58. hidden_mamba_act (`str` or `function`, *optional*, defaults to `"silu"`):
  59. The non-linear activation function (function or string) in the mamba layer.
  60. initializer_range (`float`, *optional*, defaults to 0.02):
  61. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  62. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  63. The epsilon used by the rms normalization layers.
  64. use_cache (`bool`, *optional*, defaults to `True`):
  65. Whether or not the model should return the last key/values attentions (not used by all models). Only
  66. relevant if `config.is_decoder=True`.
  67. num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
  68. Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
  69. integer value, only last `num_logits_to_keep` logits will be calculated. Default is 1 because only the
  70. logits of the last prompt token are needed for generation. For long sequences, the logits for the entire
  71. sequence may use a lot of memory so, setting `num_logits_to_keep=1` will reduce memory footprint
  72. significantly.
  73. pad_token_id (`int`, *optional*, defaults to 0):
  74. The id of the padding token.
  75. bos_token_id (`int`, *optional*, defaults to 1):
  76. The id of the "beginning-of-sequence" token.
  77. eos_token_id (`int`, *optional*, defaults to 2):
  78. The id of the "end-of-sequence" token.
  79. max_position_embeddings (`int`, *optional*, defaults to 4096):
  80. This value doesn't have any real effect. The maximum sequence length that this model is intended to be
  81. used with. It can be used with longer sequences, but performance may degrade.
  82. attention_dropout (`float`, *optional*, defaults to 0.0):
  83. The dropout ratio for the attention probabilities.
  84. attn_layer_period (`int`, *optional*, defaults to 6):
  85. Once in this many layers, we will have a shared attention layer
  86. attn_layer_offset (`int`, *optional*, defaults to 4):
  87. Offset of the shared attention layer
  88. use_mamba_kernels (`bool`, *optional*, defaults to `True`):
  89. Flag indicating whether or not to use the fast mamba kernels. These are available only if `mamba-ssm` and
  90. `causal-conv1d` are installed, and the mamba modules are running on a CUDA device. Raises ValueError if
  91. `True` and kernels are not available
  92. mamba_d_state (`int`, *optional*, defaults to 16):
  93. The dimension the mamba state space latents
  94. mamba_d_conv (`int`, *optional*, defaults to 4):
  95. The size of the mamba convolution kernel
  96. mamba_expand (`int`, *optional*, defaults to 2):
  97. Expanding factor (relative to hidden_size) used to determine the mamba intermediate size
  98. mamba_dt_rank (`Union[int,str]`, *optional*, defaults to `"auto"`):
  99. Rank of the mamba discretization projection matrix. `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)`
  100. time_step_min (`float`, *optional*, defaults to 0.001):
  101. Minimum `time_step` used to bound `dt_proj_bias`.
  102. time_step_max (`float`, *optional*, defaults to 0.1):
  103. Maximum `time_step` used to bound `dt_proj_bias`.
  104. time_step_floor (`float`, *optional*, defaults to 0.0001):
  105. Minimum clamping value of the `dt_proj.bias` layer initialization.
  106. mamba_conv_bias (`bool`, *optional*, defaults to `True`):
  107. Flag indicating whether or not to use bias in the convolution layer of the mamba mixer block.
  108. mamba_proj_bias (`bool`, *optional*, defaults to `False`):
  109. Flag indicating whether or not to use bias in the input and output projections (["in_proj", "out_proj"]) of the mamba mixer block
  110. """
  111. model_type = "zamba"
  112. keys_to_ignore_at_inference = ["past_key_values"]
  113. def __init__(
  114. self,
  115. vocab_size=32000,
  116. tie_word_embeddings=True,
  117. hidden_size=3712,
  118. attention_hidden_size=None,
  119. intermediate_size=14848,
  120. num_hidden_layers=76,
  121. num_attention_heads=16,
  122. attention_head_dim=None,
  123. num_key_value_heads=16,
  124. n_mamba_heads=2,
  125. hidden_act="gelu",
  126. hidden_mamba_act="silu",
  127. initializer_range=0.02,
  128. rms_norm_eps=1e-5,
  129. use_cache=True,
  130. num_logits_to_keep=1,
  131. pad_token_id=0,
  132. bos_token_id=1,
  133. eos_token_id=2,
  134. max_position_embeddings=4096,
  135. attention_dropout=0.0,
  136. attn_layer_period=6,
  137. attn_layer_offset=4,
  138. use_mamba_kernels=True,
  139. mamba_d_state=16,
  140. mamba_d_conv=4,
  141. mamba_expand=2,
  142. mamba_dt_rank="auto",
  143. time_step_min=0.001,
  144. time_step_max=0.1,
  145. time_step_floor=1e-4,
  146. mamba_conv_bias=True,
  147. mamba_proj_bias=False,
  148. **kwargs,
  149. ):
  150. self.vocab_size = vocab_size
  151. self.tie_word_embeddings = tie_word_embeddings
  152. self.hidden_size = hidden_size
  153. if attention_hidden_size is None:
  154. self.attention_hidden_size = 2 * hidden_size
  155. else:
  156. self.attention_hidden_size = attention_hidden_size
  157. self.intermediate_size = intermediate_size
  158. self.num_hidden_layers = num_hidden_layers
  159. self.num_attention_heads = num_attention_heads
  160. if attention_head_dim is None:
  161. self.attention_head_dim = 2 * self.hidden_size // self.num_attention_heads
  162. else:
  163. self.attention_head_dim = attention_head_dim
  164. self.max_position_embeddings = max_position_embeddings
  165. self.attention_dropout = attention_dropout
  166. self.num_key_value_heads = num_key_value_heads
  167. self.n_mamba_heads = n_mamba_heads
  168. self.hidden_act = hidden_act
  169. self.hidden_mamba_act = hidden_mamba_act
  170. self.initializer_range = initializer_range
  171. self.rms_norm_eps = rms_norm_eps
  172. self.use_cache = use_cache
  173. self.num_logits_to_keep = num_logits_to_keep
  174. self.attn_layer_period = attn_layer_period
  175. self.attn_layer_offset = attn_layer_offset
  176. self.use_mamba_kernels = use_mamba_kernels
  177. self.mamba_d_state = mamba_d_state
  178. self.mamba_d_conv = mamba_d_conv
  179. self.mamba_expand = mamba_expand
  180. self.mamba_dt_rank = math.ceil(self.hidden_size / 16) if mamba_dt_rank == "auto" else mamba_dt_rank
  181. self.time_step_min = time_step_min
  182. self.time_step_max = time_step_max
  183. self.time_step_floor = time_step_floor
  184. self.mamba_conv_bias = mamba_conv_bias
  185. self.mamba_proj_bias = mamba_proj_bias
  186. self.layers_block_type = self._layers_block_type(num_hidden_layers, attn_layer_period, attn_layer_offset)
  187. assert (self.mamba_expand * self.hidden_size) % self.n_mamba_heads == 0, (
  188. "`intermediate_size` should be divisible by `n_mamba_heads`."
  189. )
  190. super().__init__(
  191. pad_token_id=pad_token_id,
  192. bos_token_id=bos_token_id,
  193. eos_token_id=eos_token_id,
  194. tie_word_embeddings=tie_word_embeddings,
  195. **kwargs,
  196. )
  197. def _layers_block_type(self, num_hidden_layers, attn_layer_period, attn_layer_offset):
  198. layers = [
  199. "mamba",
  200. "mamba",
  201. "hybrid",
  202. ] + ["hybrid" if i % attn_layer_period == attn_layer_offset else "mamba" for i in range(num_hidden_layers - 3)]
  203. return layers
  204. __all__ = ["ZambaConfig"]