1
0

mpt.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. # coding=utf-8
  2. # Copied from
  3. # https://huggingface.co/mosaicml/mpt-7b/blob/main/configuration_mpt.py
  4. """A HuggingFace-style model configuration."""
  5. import warnings
  6. from typing import Any, Dict, Optional, Union
  7. from transformers import PretrainedConfig
  8. attn_config_defaults: Dict = {
  9. 'attn_type': 'multihead_attention',
  10. 'attn_pdrop': 0.0,
  11. 'attn_impl': 'triton',
  12. 'qk_ln': False,
  13. 'clip_qkv': None,
  14. 'softmax_scale': None,
  15. 'prefix_lm': False,
  16. 'attn_uses_sequence_id': False,
  17. 'alibi': False,
  18. 'alibi_bias_max': 8
  19. }
  20. ffn_config_defaults: Dict = {'ffn_type': 'mptmlp'}
  21. init_config_defaults: Dict = {
  22. 'name': 'kaiming_normal_',
  23. 'fan_mode': 'fan_in',
  24. 'init_nonlinearity': 'relu',
  25. 'init_div_is_residual': True,
  26. 'emb_init_std': None,
  27. 'emb_init_uniform_lim': None,
  28. 'init_std': None,
  29. 'init_gain': 0.0
  30. }
  31. class MPTConfig(PretrainedConfig):
  32. model_type = 'mpt'
  33. attribute_map = {
  34. 'num_attention_heads': 'n_heads',
  35. 'hidden_size': 'd_model',
  36. 'num_hidden_layers': 'n_layers',
  37. }
  38. # pylint: disable=dangerous-default-value
  39. def __init__(self,
  40. d_model: int = 2048,
  41. n_heads: int = 16,
  42. n_layers: int = 24,
  43. expansion_ratio: int = 4,
  44. max_seq_len: int = 2048,
  45. vocab_size: int = 50368,
  46. resid_pdrop: float = 0.0,
  47. emb_pdrop: float = 0.0,
  48. learned_pos_emb: bool = True,
  49. attn_config: Dict = attn_config_defaults,
  50. ffn_config: Dict = ffn_config_defaults,
  51. init_device: str = 'cpu',
  52. logit_scale: Optional[Union[float, str]] = None,
  53. no_bias: bool = False,
  54. embedding_fraction: float = 1.0,
  55. norm_type: str = 'low_precision_layernorm',
  56. use_cache: bool = False,
  57. init_config: Dict = init_config_defaults,
  58. fc_type: str = 'torch',
  59. verbose: Optional[int] = None,
  60. **kwargs: Any):
  61. self.d_model = d_model
  62. self.n_heads = n_heads
  63. self.n_layers = n_layers
  64. self.expansion_ratio = expansion_ratio
  65. self.max_seq_len = max_seq_len
  66. self.vocab_size = vocab_size
  67. self.resid_pdrop = resid_pdrop
  68. self.emb_pdrop = emb_pdrop
  69. self.learned_pos_emb = learned_pos_emb
  70. self.attn_config = attn_config
  71. self.ffn_config = ffn_config
  72. self.init_device = init_device
  73. self.logit_scale = logit_scale
  74. self.no_bias = no_bias
  75. self.embedding_fraction = embedding_fraction
  76. self.norm_type = norm_type
  77. self.use_cache = use_cache
  78. self.init_config = init_config
  79. self.fc_type = fc_type
  80. if verbose is not None:
  81. warnings.warn(DeprecationWarning(
  82. 'verbose argument for MPTConfig is now ignored and '
  83. 'will be removed. Use python_log_level instead.'),
  84. stacklevel=2)
  85. if 'name' in kwargs:
  86. del kwargs['name']
  87. if 'loss_fn' in kwargs:
  88. del kwargs['loss_fn']
  89. if self.attn_config.get('alibi', False):
  90. self.learned_pos_emb = False
  91. warnings.warn(
  92. f'alibi is turned on, setting `learned_pos_emb` '
  93. f'to {self.learned_pos_emb}`',
  94. stacklevel=2)
  95. super().__init__(**kwargs)
  96. self._validate_config()
  97. def _set_config_defaults(
  98. self, config: Dict[str, Any],
  99. config_defaults: Dict[str, Any]) -> Dict[str, Any]:
  100. for (k, v) in config_defaults.items():
  101. if k not in config:
  102. config[k] = v
  103. return config
  104. def _validate_config(self) -> None:
  105. self.attn_config = self._set_config_defaults(self.attn_config,
  106. attn_config_defaults)
  107. self.ffn_config = self._set_config_defaults(self.ffn_config,
  108. ffn_config_defaults)
  109. self.init_config = self._set_config_defaults(self.init_config,
  110. init_config_defaults)
  111. if self.d_model % self.n_heads != 0:
  112. raise ValueError('d_model must be divisible by n_heads')
  113. if any((
  114. prob < 0 or prob > 1 for prob in
  115. [self.attn_config['attn_pdrop'], self.resid_pdrop, self.emb_pdrop]
  116. )):
  117. raise ValueError(
  118. "self.attn_config['attn_pdrop'], resid_pdrop, emb_pdrop are "
  119. "probabilities and must be between 0 and 1")
  120. if self.attn_config['attn_impl'] not in ['torch', 'flash', 'triton']:
  121. raise ValueError(
  122. f"Unknown attn_impl={self.attn_config['attn_impl']}")
  123. if self.attn_config['prefix_lm'] and self.attn_config[
  124. 'attn_impl'] not in ['torch', 'triton']:
  125. raise NotImplementedError(
  126. 'prefix_lm only implemented with torch and triton attention.')
  127. if self.attn_config['alibi'] and self.attn_config['attn_impl'] not in [
  128. 'torch', 'triton'
  129. ]:
  130. raise NotImplementedError(
  131. 'alibi only implemented with torch and triton attention.')
  132. if self.attn_config['attn_uses_sequence_id'] and self.attn_config[
  133. 'attn_impl'] not in ['torch', 'triton']:
  134. raise NotImplementedError(
  135. 'attn_uses_sequence_id only implemented with torch '
  136. 'and triton attention.')
  137. if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
  138. raise ValueError(
  139. 'model.embedding_fraction must be between 0 (exclusive) '
  140. 'and 1 (inclusive)!')
  141. if isinstance(self.logit_scale,
  142. str) and self.logit_scale != 'inv_sqrt_d_model':
  143. raise ValueError(
  144. f"self.logit_scale={self.logit_scale!r} is not recognized as "
  145. "an option; use numeric value or 'inv_sqrt_d_model'.")
  146. if self.init_config.get('name', None) is None:
  147. raise ValueError(
  148. f"self.init_config={self.init_config!r} 'name' needs to be set."
  149. )
  150. if not self.learned_pos_emb and (not self.attn_config['alibi']):
  151. warnings.warn(
  152. 'Positional information not being provided to the model.',
  153. stacklevel=2)
  154. if self.fc_type == 'te' or self.ffn_config['ffn_type'] == 'te_ln_mlp':
  155. try:
  156. # pylint: disable=import-outside-toplevel
  157. import transformer_engine.pytorch as te
  158. del te
  159. except Exception as exc:
  160. raise ImportError(
  161. 'TransformerEngine import fail. `fc_type: te` requires '
  162. 'TransformerEngine be installed. '
  163. 'The required version of transformer_engine also requires '
  164. 'FlashAttention v1.0.6 is installed:\n'
  165. 'pip install flash-attn==1.0.6 --no-build-isolation \n'
  166. 'pip install git+https://github.com/NVIDIA/TransformerEngine.git@144e4888b2cdd60bd52e706d5b7a79cb9c1a7156'
  167. ) from exc
  168. if self.ffn_config['ffn_type'] == 'mptmlp':
  169. self.ffn_config['fc_type'] = self.fc_type
  170. elif self.ffn_config['ffn_type'] == 'te_ln_mlp':
  171. self.ffn_config['bias'] = not self.no_bias