mpt.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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__(
  40. self,
  41. d_model: int = 2048,
  42. n_heads: int = 16,
  43. n_layers: int = 24,
  44. expansion_ratio: int = 4,
  45. max_seq_len: int = 2048,
  46. vocab_size: int = 50368,
  47. resid_pdrop: float = 0.0,
  48. emb_pdrop: float = 0.0,
  49. learned_pos_emb: bool = True,
  50. attn_config: Dict = attn_config_defaults,
  51. ffn_config: Dict = ffn_config_defaults,
  52. init_device: str = "cpu",
  53. logit_scale: Optional[Union[float, str]] = None,
  54. no_bias: bool = False,
  55. embedding_fraction: float = 1.0,
  56. norm_type: str = "low_precision_layernorm",
  57. use_cache: bool = False,
  58. init_config: Dict = init_config_defaults,
  59. fc_type: str = "torch",
  60. verbose: Optional[int] = None,
  61. **kwargs: Any,
  62. ):
  63. self.d_model = d_model
  64. self.n_heads = n_heads
  65. self.n_layers = n_layers
  66. self.expansion_ratio = expansion_ratio
  67. self.max_seq_len = max_seq_len
  68. self.vocab_size = vocab_size
  69. self.resid_pdrop = resid_pdrop
  70. self.emb_pdrop = emb_pdrop
  71. self.learned_pos_emb = learned_pos_emb
  72. self.attn_config = attn_config
  73. self.ffn_config = ffn_config
  74. self.init_device = init_device
  75. self.logit_scale = logit_scale
  76. self.no_bias = no_bias
  77. self.embedding_fraction = embedding_fraction
  78. self.norm_type = norm_type
  79. self.use_cache = use_cache
  80. self.init_config = init_config
  81. self.fc_type = fc_type
  82. if verbose is not None:
  83. warnings.warn(
  84. DeprecationWarning(
  85. "verbose argument for MPTConfig is now ignored and will be"
  86. " removed. Use python_log_level instead."),
  87. stacklevel=2,
  88. )
  89. if "name" in kwargs:
  90. del kwargs["name"]
  91. if "loss_fn" in kwargs:
  92. del kwargs["loss_fn"]
  93. if self.attn_config.get("alibi", False):
  94. self.learned_pos_emb = False
  95. warnings.warn(
  96. "alibi is turned on, setting `learned_pos_emb` to "
  97. f"{self.learned_pos_emb}`",
  98. stacklevel=2,
  99. )
  100. super().__init__(**kwargs)
  101. self._validate_config()
  102. def _set_config_defaults(
  103. self, config: Dict[str, Any],
  104. config_defaults: Dict[str, Any]) -> Dict[str, Any]:
  105. for k, v in config_defaults.items():
  106. if k not in config:
  107. config[k] = v
  108. return config
  109. def _validate_config(self) -> None:
  110. self.attn_config = self._set_config_defaults(self.attn_config,
  111. attn_config_defaults)
  112. self.ffn_config = self._set_config_defaults(self.ffn_config,
  113. ffn_config_defaults)
  114. self.init_config = self._set_config_defaults(self.init_config,
  115. init_config_defaults)
  116. if self.d_model % self.n_heads != 0:
  117. raise ValueError("d_model must be divisible by n_heads")
  118. if any((prob < 0 or prob > 1 for prob in [
  119. self.attn_config["attn_pdrop"],
  120. self.resid_pdrop,
  121. self.emb_pdrop,
  122. ])):
  123. raise ValueError(
  124. "self.attn_config['attn_pdrop'], resid_pdrop, emb_pdrop "
  125. "are probabilities and must be between 0 and 1")
  126. if self.attn_config["attn_impl"] not in ["torch", "flash", "triton"]:
  127. raise ValueError(
  128. f"Unknown attn_impl={self.attn_config['attn_impl']}")
  129. if self.attn_config["prefix_lm"] and self.attn_config[
  130. "attn_impl"] not in ["torch", "triton"]:
  131. raise NotImplementedError(
  132. "prefix_lm only implemented with torch and triton attention.")
  133. if self.attn_config["alibi"] and self.attn_config["attn_impl"] not in [
  134. "torch",
  135. "triton",
  136. ]:
  137. raise NotImplementedError(
  138. "alibi only implemented with torch and triton attention.")
  139. if self.attn_config["attn_uses_sequence_id"] and self.attn_config[
  140. "attn_impl"] not in ["torch", "triton"]:
  141. raise NotImplementedError(
  142. "attn_uses_sequence_id only implemented with torch and triton "
  143. "attention.")
  144. if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
  145. raise ValueError(
  146. "model.embedding_fraction must be between 0 (exclusive) and 1 "
  147. "(inclusive)!")
  148. if (isinstance(self.logit_scale, str)
  149. and self.logit_scale != "inv_sqrt_d_model"):
  150. raise ValueError(
  151. f"self.logit_scale={self.logit_scale!r} is not recognized as "
  152. "an option; use numeric value or 'inv_sqrt_d_model'.")
  153. if self.init_config.get("name", None) is None:
  154. raise ValueError(
  155. f"self.init_config={self.init_config!r} 'name' needs to be set."
  156. )
  157. if not self.learned_pos_emb and (not self.attn_config["alibi"]):
  158. warnings.warn(
  159. "Positional information not being provided to the model.",
  160. stacklevel=2,
  161. )
  162. if self.fc_type == "te" or self.ffn_config[ # codespell:ignore
  163. "ffn_type"] == "te_ln_mlp":
  164. try:
  165. # pylint: disable=import-outside-toplevel
  166. import transformer_engine.pytorch as te
  167. del te
  168. except Exception as exc:
  169. raise ImportError(
  170. # pylint: disable=line-too-long
  171. "TransformerEngine import fail. `fc_type: te` requires "
  172. "TransformerEngine be installed. " +
  173. "The required version of transformer_engine also "
  174. "requires FlashAttention v1.0.6 is installed:\n" +
  175. "pip install flash-attn==1.0.6 --no-build-isolation \n" +
  176. "pip install git+https://github.com/NVIDIA/TransformerEngine.git@144e4888b2cdd60bd52e706d5b7a79cb9c1a7156"
  177. ) from exc
  178. if self.ffn_config["ffn_type"] == "mptmlp":
  179. self.ffn_config["fc_type"] = self.fc_type
  180. elif self.ffn_config["ffn_type"] == "te_ln_mlp":
  181. self.ffn_config["bias"] = not self.no_bias