configuration_mpt.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # coding=utf-8
  2. # Copyright 2023 HuggingFace Inc. team and MosaicML NLP team.
  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. """Mpt configuration"""
  16. from typing import Optional, Union
  17. from ...configuration_utils import PretrainedConfig
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. class MptAttentionConfig(PretrainedConfig):
  21. """
  22. This is the configuration class to store the configuration of a [`MptAttention`] class. It is used to instantiate
  23. attention layers according to the specified arguments, defining the layers architecture. Instantiating a
  24. configuration with the defaults will yield a similar configuration to that of the MPT
  25. [mosaicml/mpt-7b](https://huggingface.co/mosaicml/mpt-7b) architecture. Most of the arguments are kept for backward
  26. compatibility with previous MPT models that are hosted on the Hub (previously with `trust_remote_code=True`).
  27. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  28. documentation from [`PretrainedConfig`] for more information.
  29. Args:
  30. attn_type (`str`, *optional*, defaults to `"multihead_attention"`):
  31. type of attention to use. Options: `"multihead_attention"`, `"multiquery_attention"`.
  32. attn_pdrop (`float`, *optional*, defaults to `0.0`):
  33. The dropout probability for the attention layers.
  34. attn_impl (`str`, *optional*, defaults to `"torch"`):
  35. The attention implementation to use. One of `"torch"`, `"flash"`, or `"triton"`.
  36. clip_qkv (`float`, *optional*):
  37. If not `None`, clip the queries, keys, and values in the attention layer to this value.
  38. softmax_scale (`float`, *optional*):
  39. If not `None`, scale the softmax in the attention layer by this value. If `None`, will default to
  40. `1/sqrt(hidden_size)`.
  41. prefix_lm (`bool`, *optional*, defaults to `False`):
  42. Whether the model should operate as a Prefix LM. This requires passing an extra `prefix_mask` argument
  43. which indicates which tokens belong to the prefix. Tokens in the prefix can attend to one another
  44. bi-directionally. Tokens outside the prefix use causal attention.
  45. qk_ln (`bool`, *optional*, defaults to `False`):
  46. Whether to apply layer normalization to the queries and keys in the attention layer.
  47. attn_uses_sequence_id (`bool`, *optional*, defaults to `False`):
  48. Whether to restrict attention to tokens that have the same token_type_ids. When the model is in `train`
  49. mode, this requires passing an extra *token_type_ids* argument which indicates which sub-sequence each
  50. token belongs to. Defaults to `False` meaning any provided *token_type_ids* will be ignored.
  51. alibi (`bool`, *optional*, defaults to `True`):
  52. Whether or not to use the alibi bias instead of positional embedding.
  53. alibi_bias_max (`int`, *optional*, defaults to 8):
  54. The maximum value of the alibi bias.
  55. """
  56. base_config_key = "attn_config"
  57. def __init__(
  58. self,
  59. attn_type="multihead_attention",
  60. attn_pdrop=0,
  61. attn_impl="torch",
  62. clip_qkv=None,
  63. softmax_scale=None,
  64. prefix_lm=False,
  65. qk_ln=False,
  66. attn_uses_sequence_id=False,
  67. alibi=True,
  68. alibi_bias_max=8,
  69. **kwargs,
  70. ):
  71. super().__init__()
  72. self.attn_type = attn_type
  73. self.attn_pdrop = attn_pdrop
  74. self.attn_impl = attn_impl
  75. self.clip_qkv = clip_qkv
  76. self.softmax_scale = softmax_scale
  77. self.prefix_lm = prefix_lm
  78. self.attn_uses_sequence_id = attn_uses_sequence_id
  79. self.alibi = alibi
  80. self.qk_ln = qk_ln
  81. self.alibi_bias_max = alibi_bias_max
  82. if attn_type not in ["multihead_attention", "multiquery_attention"]:
  83. raise ValueError(
  84. f"`attn_type` has to be either `multihead_attention` or `multiquery_attention`. Received: {attn_type}"
  85. )
  86. class MptConfig(PretrainedConfig):
  87. """
  88. This is the configuration class to store the configuration of a [`MptModel`]. It is used to instantiate a Mpt model
  89. according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  90. defaults will yield a similar configuration to the Mpt-7b architecture
  91. [mosaicml/mpt-7b](https://huggingface.co/mosaicml/mpt-7b).
  92. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  93. documentation from [`PretrainedConfig`] for more information.
  94. Args:
  95. d_model (`int`, *optional*, defaults to 2048):
  96. Dimensionality of the embeddings and hidden states.
  97. n_heads (`int`, *optional*, defaults to 16):
  98. Number of attention heads for each attention layer in the Transformer encoder.
  99. n_layers (`int`, *optional*, defaults to 24):
  100. Number of hidden layers in the Transformer encoder.
  101. expansion_ratio (`int`, *optional*, defaults to 4):
  102. The ratio of the up/down scale in the MLP.
  103. max_seq_len (`int`, *optional*, defaults to 2048):
  104. The maximum sequence length of the model.
  105. vocab_size (`int`, *optional*, defaults to 50368):
  106. Vocabulary size of the Mpt model. Defines the maximum number of different tokens that can be represented by
  107. the `inputs_ids` passed when calling [`MptModel`]. Check [this
  108. discussion](https://huggingface.co/bigscience/mpt/discussions/120#633d28389addb8530b406c2a) on how the
  109. `vocab_size` has been defined.
  110. resid_pdrop (`float`, *optional*, defaults to 0.0):
  111. The dropout probability applied to the attention output before combining with residual.
  112. layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
  113. The epsilon to use in the layer normalization layers.
  114. emb_pdrop (`float`, *optional*, defaults to 0.0):
  115. The dropout probability for the embedding layer.
  116. learned_pos_emb (`bool`, *optional*, defaults to `True`):
  117. Whether to use learned positional embeddings.
  118. attn_config (`dict`, *optional*):
  119. A dictionary used to configure the model's attention module.
  120. init_device (`str`, *optional*, defaults to `"cpu"`):
  121. The device to use for parameter initialization. Defined for backward compatibility
  122. logit_scale (`float`, *optional*):
  123. If not None, scale the logits by this value.
  124. no_bias (`bool`, *optional*, defaults to `True`):
  125. Whether to use bias in all linear layers.
  126. verbose (`int`, *optional*, defaults to 0):
  127. The verbosity level to use for logging. Used in the previous versions of MPT models for logging. This
  128. argument is deprecated.
  129. embedding_fraction (`float`, *optional*, defaults to 1.0):
  130. The fraction to scale the gradients of the embedding layer by.
  131. norm_type (`str`, *optional*, defaults to `"low_precision_layernorm"`):
  132. Type of layer norm to use. All MPT models uses the same layer norm implementation. Defined for backward
  133. compatibility.
  134. use_cache (`bool`, *optional*, defaults to `False`):
  135. Whether or not the model should return the last key/values attentions (not used by all models).
  136. initializer_range (`float`, *optional*, defaults to 0.02):
  137. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  138. Example:
  139. ```python
  140. >>> from transformers import MptConfig, MptModel
  141. >>> # Initializing a Mpt configuration
  142. >>> configuration = MptConfig()
  143. >>> # Initializing a model (with random weights) from the configuration
  144. >>> model = MptModel(configuration)
  145. >>> # Accessing the model configuration
  146. >>> configuration = model.config
  147. ```
  148. """
  149. model_type = "mpt"
  150. sub_configs = {"attn_config": MptAttentionConfig}
  151. attribute_map = {
  152. "num_attention_heads": "n_heads",
  153. "hidden_size": "d_model",
  154. "num_hidden_layers": "n_layers",
  155. }
  156. def __init__(
  157. self,
  158. d_model: int = 2048,
  159. n_heads: int = 16,
  160. n_layers: int = 24,
  161. expansion_ratio: int = 4,
  162. max_seq_len: int = 2048,
  163. vocab_size: int = 50368,
  164. resid_pdrop: float = 0.0,
  165. layer_norm_epsilon: float = 1e-5,
  166. emb_pdrop: float = 0.0,
  167. learned_pos_emb: bool = True,
  168. attn_config: MptAttentionConfig = None,
  169. init_device: str = "cpu",
  170. logit_scale: Optional[Union[float, str]] = None,
  171. no_bias: bool = True,
  172. verbose: int = 0,
  173. embedding_fraction: float = 1.0,
  174. norm_type: str = "low_precision_layernorm",
  175. use_cache: bool = False,
  176. initializer_range=0.02,
  177. **kwargs,
  178. ):
  179. if attn_config is None:
  180. self.attn_config = MptAttentionConfig()
  181. elif isinstance(attn_config, dict):
  182. self.attn_config = MptAttentionConfig(**attn_config)
  183. else:
  184. self.attn_config = attn_config
  185. self.d_model = d_model
  186. self.n_heads = n_heads
  187. self.n_layers = n_layers
  188. self.expansion_ratio = expansion_ratio
  189. self.max_seq_len = max_seq_len
  190. self.vocab_size = vocab_size
  191. self.resid_pdrop = resid_pdrop
  192. self.emb_pdrop = emb_pdrop
  193. self.learned_pos_emb = learned_pos_emb
  194. self.init_device = init_device
  195. self.logit_scale = logit_scale
  196. self.no_bias = no_bias
  197. self.verbose = verbose
  198. self.embedding_fraction = embedding_fraction
  199. self.norm_type = norm_type
  200. self.layer_norm_epsilon = layer_norm_epsilon
  201. self.use_cache = use_cache
  202. self.initializer_range = initializer_range
  203. super().__init__(**kwargs)
  204. __all__ = ["MptConfig"]