Update configuration_mpt.py
Browse files- configuration_mpt.py +32 -10
configuration_mpt.py
CHANGED
@@ -1,27 +1,29 @@
|
|
1 |
"""A HuggingFace-style model configuration."""
|
2 |
-
|
|
|
3 |
from transformers import PretrainedConfig
|
4 |
attn_config_defaults: Dict = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}
|
|
|
5 |
init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0}
|
6 |
|
7 |
class MPTConfig(PretrainedConfig):
|
8 |
model_type = 'mpt'
|
9 |
|
10 |
-
def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: int=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults, init_device: str='cpu', logit_scale: Optional[Union[float, str]]=None, no_bias: bool=False,
|
11 |
"""The MPT configuration class.
|
12 |
|
13 |
Args:
|
14 |
d_model (int): The size of the embedding dimension of the model.
|
15 |
n_heads (int): The number of attention heads.
|
16 |
n_layers (int): The number of layers in the model.
|
17 |
-
expansion_ratio (int): The ratio of the up/down scale in the
|
18 |
max_seq_len (int): The maximum sequence length of the model.
|
19 |
vocab_size (int): The size of the vocabulary.
|
20 |
resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
|
21 |
emb_pdrop (float): The dropout probability for the embedding layer.
|
22 |
learned_pos_emb (bool): Whether to use learned positional embeddings
|
23 |
-
attn_config (Dict):
|
24 |
-
attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention
|
25 |
attn_pdrop (float): The dropout probability for the attention layers.
|
26 |
attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'.
|
27 |
qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer.
|
@@ -38,13 +40,15 @@ class MPTConfig(PretrainedConfig):
|
|
38 |
Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
|
39 |
alibi (bool): Whether to use the alibi bias instead of position embeddings.
|
40 |
alibi_bias_max (int): The maximum value of the alibi bias.
|
|
|
|
|
|
|
41 |
init_device (str): The device to use for parameter initialization.
|
42 |
logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
|
43 |
no_bias (bool): Whether to use bias in all layers.
|
44 |
verbose (int): The verbosity level. 0 is silent.
|
45 |
embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
|
46 |
norm_type (str): choose type of norm to use
|
47 |
-
multiquery_attention (bool): Whether to use multiquery attention implementation.
|
48 |
use_cache (bool): Whether or not the model should return the last key/values attentions
|
49 |
init_config (Dict): A dictionary used to configure the model initialization:
|
50 |
init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_',
|
@@ -61,6 +65,7 @@ class MPTConfig(PretrainedConfig):
|
|
61 |
init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes.
|
62 |
---
|
63 |
See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
|
|
|
64 |
"""
|
65 |
self.d_model = d_model
|
66 |
self.n_heads = n_heads
|
@@ -72,29 +77,36 @@ class MPTConfig(PretrainedConfig):
|
|
72 |
self.emb_pdrop = emb_pdrop
|
73 |
self.learned_pos_emb = learned_pos_emb
|
74 |
self.attn_config = attn_config
|
|
|
75 |
self.init_device = init_device
|
76 |
self.logit_scale = logit_scale
|
77 |
self.no_bias = no_bias
|
78 |
-
self.verbose = verbose
|
79 |
self.embedding_fraction = embedding_fraction
|
80 |
self.norm_type = norm_type
|
81 |
self.use_cache = use_cache
|
82 |
self.init_config = init_config
|
|
|
|
|
|
|
83 |
if 'name' in kwargs:
|
84 |
del kwargs['name']
|
85 |
if 'loss_fn' in kwargs:
|
86 |
del kwargs['loss_fn']
|
|
|
|
|
|
|
87 |
super().__init__(**kwargs)
|
88 |
self._validate_config()
|
89 |
|
90 |
-
def _set_config_defaults(self, config, config_defaults):
|
91 |
for (k, v) in config_defaults.items():
|
92 |
if k not in config:
|
93 |
config[k] = v
|
94 |
return config
|
95 |
|
96 |
-
def _validate_config(self):
|
97 |
self.attn_config = self._set_config_defaults(self.attn_config, attn_config_defaults)
|
|
|
98 |
self.init_config = self._set_config_defaults(self.init_config, init_config_defaults)
|
99 |
if self.d_model % self.n_heads != 0:
|
100 |
raise ValueError('d_model must be divisible by n_heads')
|
@@ -115,4 +127,14 @@ class MPTConfig(PretrainedConfig):
|
|
115 |
if self.init_config.get('name', None) is None:
|
116 |
raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
|
117 |
if not self.learned_pos_emb and (not self.attn_config['alibi']):
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
"""A HuggingFace-style model configuration."""
|
2 |
+
import warnings
|
3 |
+
from typing import Any, Dict, Optional, Union
|
4 |
from transformers import PretrainedConfig
|
5 |
attn_config_defaults: Dict = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}
|
6 |
+
ffn_config_defaults: Dict = {'ffn_type': 'mptmlp'}
|
7 |
init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0}
|
8 |
|
9 |
class MPTConfig(PretrainedConfig):
|
10 |
model_type = 'mpt'
|
11 |
|
12 |
+
def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: int=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults, ffn_config: Dict=ffn_config_defaults, init_device: str='cpu', logit_scale: Optional[Union[float, str]]=None, no_bias: bool=False, embedding_fraction: float=1.0, norm_type: str='low_precision_layernorm', use_cache: bool=False, init_config: Dict=init_config_defaults, fc_type: str='torch', verbose: Optional[int]=None, **kwargs: Any):
|
13 |
"""The MPT configuration class.
|
14 |
|
15 |
Args:
|
16 |
d_model (int): The size of the embedding dimension of the model.
|
17 |
n_heads (int): The number of attention heads.
|
18 |
n_layers (int): The number of layers in the model.
|
19 |
+
expansion_ratio (int): The ratio of the up/down scale in the ffn.
|
20 |
max_seq_len (int): The maximum sequence length of the model.
|
21 |
vocab_size (int): The size of the vocabulary.
|
22 |
resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
|
23 |
emb_pdrop (float): The dropout probability for the embedding layer.
|
24 |
learned_pos_emb (bool): Whether to use learned positional embeddings
|
25 |
+
attn_config (Dict): A dictionary used to configure the model's attention module:
|
26 |
+
attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention, grouped_query_attention
|
27 |
attn_pdrop (float): The dropout probability for the attention layers.
|
28 |
attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'.
|
29 |
qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer.
|
|
|
40 |
Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
|
41 |
alibi (bool): Whether to use the alibi bias instead of position embeddings.
|
42 |
alibi_bias_max (int): The maximum value of the alibi bias.
|
43 |
+
kv_n_heads (Optional[int]): For grouped_query_attention only, allow user to specify number of kv heads.
|
44 |
+
ffn_config (Dict): A dictionary used to configure the model's ffn module:
|
45 |
+
ffn_type (str): type of ffn to use. Options: mptmlp, te_ln_mlp
|
46 |
init_device (str): The device to use for parameter initialization.
|
47 |
logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
|
48 |
no_bias (bool): Whether to use bias in all layers.
|
49 |
verbose (int): The verbosity level. 0 is silent.
|
50 |
embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
|
51 |
norm_type (str): choose type of norm to use
|
|
|
52 |
use_cache (bool): Whether or not the model should return the last key/values attentions
|
53 |
init_config (Dict): A dictionary used to configure the model initialization:
|
54 |
init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_',
|
|
|
65 |
init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes.
|
66 |
---
|
67 |
See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
|
68 |
+
fc_type (str): choose fc layer implementation. Options: torch and te. te layers support fp8 when using H100 GPUs.
|
69 |
"""
|
70 |
self.d_model = d_model
|
71 |
self.n_heads = n_heads
|
|
|
77 |
self.emb_pdrop = emb_pdrop
|
78 |
self.learned_pos_emb = learned_pos_emb
|
79 |
self.attn_config = attn_config
|
80 |
+
self.ffn_config = ffn_config
|
81 |
self.init_device = init_device
|
82 |
self.logit_scale = logit_scale
|
83 |
self.no_bias = no_bias
|
|
|
84 |
self.embedding_fraction = embedding_fraction
|
85 |
self.norm_type = norm_type
|
86 |
self.use_cache = use_cache
|
87 |
self.init_config = init_config
|
88 |
+
self.fc_type = fc_type
|
89 |
+
if verbose is not None:
|
90 |
+
warnings.warn(DeprecationWarning('verbose argument for MPTConfig is now ignored and will be removed. Use python_log_level instead.'))
|
91 |
if 'name' in kwargs:
|
92 |
del kwargs['name']
|
93 |
if 'loss_fn' in kwargs:
|
94 |
del kwargs['loss_fn']
|
95 |
+
if self.attn_config.get('alibi', False):
|
96 |
+
self.learned_pos_emb = False
|
97 |
+
warnings.warn(f'alibi is turned on, setting `learned_pos_emb` to `False.`')
|
98 |
super().__init__(**kwargs)
|
99 |
self._validate_config()
|
100 |
|
101 |
+
def _set_config_defaults(self, config: Dict[str, Any], config_defaults: Dict[str, Any]) -> Dict[str, Any]:
|
102 |
for (k, v) in config_defaults.items():
|
103 |
if k not in config:
|
104 |
config[k] = v
|
105 |
return config
|
106 |
|
107 |
+
def _validate_config(self) -> None:
|
108 |
self.attn_config = self._set_config_defaults(self.attn_config, attn_config_defaults)
|
109 |
+
self.ffn_config = self._set_config_defaults(self.ffn_config, ffn_config_defaults)
|
110 |
self.init_config = self._set_config_defaults(self.init_config, init_config_defaults)
|
111 |
if self.d_model % self.n_heads != 0:
|
112 |
raise ValueError('d_model must be divisible by n_heads')
|
|
|
127 |
if self.init_config.get('name', None) is None:
|
128 |
raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
|
129 |
if not self.learned_pos_emb and (not self.attn_config['alibi']):
|
130 |
+
warnings.warn(f'Positional information not being provided to the model using either learned_pos_emb or alibi.')
|
131 |
+
if self.fc_type == 'te' or self.ffn_config['ffn_type'] == 'te_ln_mlp':
|
132 |
+
try:
|
133 |
+
import transformer_engine.pytorch as te
|
134 |
+
del te
|
135 |
+
except:
|
136 |
+
raise ImportError('TransformerEngine import fail. `fc_type: te` requires TransformerEngine be installed. ' + 'The required version of transformer_engine also requires FlashAttention v1.0.6 is installed:\n' + 'pip install flash-attn==1.0.6 --no-build-isolation \n' + 'pip install git+https://github.com/NVIDIA/TransformerEngine.git@144e4888b2cdd60bd52e706d5b7a79cb9c1a7156')
|
137 |
+
if self.ffn_config['ffn_type'] == 'mptmlp':
|
138 |
+
self.ffn_config['fc_type'] = self.fc_type
|
139 |
+
elif self.ffn_config['ffn_type'] == 'te_ln_mlp':
|
140 |
+
self.ffn_config['bias'] = not self.no_bias
|