luffyevil114 commited on
Commit
e4db9f4
1 Parent(s): c4751e2

Create configuration_mpt.py

Browse files
Files changed (1) hide show
  1. configuration_mpt.py +183 -0
configuration_mpt.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A HuggingFace-style model configuration."""
2
+ import warnings
3
+ from typing import Any, Dict, Optional, Union
4
+ from transformers import PretrainedConfig
5
+ from .attention import check_alibi_support, is_flash_v1_installed, is_flash_v2_installed
6
+ from .blocks import attn_config_defaults
7
+ from .fc import FC_CLASS_REGISTRY
8
+ from .norm import LPLayerNorm
9
+ from .ffn import FFN_CLASS_REGISTRY
10
+ from .warnings import VersionedDeprecationWarning
11
+ ffn_config_defaults: Dict = {'ffn_type': 'mptmlp'}
12
+ 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}
13
+
14
+ class MPTConfig(PretrainedConfig):
15
+ model_type = 'mpt'
16
+
17
+ def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: Union[int, float]=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', tie_word_embeddings: bool=True, use_pad_tok_in_ffn: bool=True, **kwargs: Any):
18
+ """The MPT configuration class.
19
+
20
+ Args:
21
+ d_model (int): The size of the embedding dimension of the model.
22
+ n_heads (int): The number of attention heads.
23
+ n_layers (int): The number of layers in the model.
24
+ expansion_ratio (Union[int, float]): The ratio of the up/down scale in the ffn.
25
+ max_seq_len (int): The maximum sequence length of the model.
26
+ vocab_size (int): The size of the vocabulary.
27
+ resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
28
+ emb_pdrop (float): The dropout probability for the embedding layer.
29
+ learned_pos_emb (bool): Whether to use learned positional embeddings
30
+ attn_config (Dict): A dictionary used to configure the model's attention module:
31
+ attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention, grouped_query_attention
32
+ attn_pdrop (float): The dropout probability for the attention layers.
33
+ attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'.
34
+ qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer.
35
+ qk_gn (bool): Whether to apply group normalization to the queries and keys in the attention layer.
36
+ clip_qkv (Optional[float]): If not None, clip the queries, keys, and values in the attention layer to
37
+ this value.
38
+ softmax_scale (Optional[float]): If not None, scale the softmax in the attention layer by this value. If None,
39
+ use the default scale of ``1/sqrt(d_keys)``.
40
+ prefix_lm (Optional[bool]): Whether the model should operate as a Prefix LM. This requires passing an
41
+ extra `prefix_mask` argument which indicates which tokens belong to the prefix. Tokens in the prefix
42
+ can attend to one another bi-directionally. Tokens outside the prefix use causal attention.
43
+ attn_uses_sequence_id (Optional[bool]): Whether to restrict attention to tokens that have the same sequence_id.
44
+ When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates
45
+ which sub-sequence each token belongs to.
46
+ Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
47
+ sliding_window_size (int): Window size for sliding window local attention. Defaults to -1, which means no sliding window. Query at position i will only attend to keys between [i + seqlen_k - seqlen_q - window_size, i + seqlen_k - seqlen_q + window_size] inclusive. Only works for flash attention v2.3.0 or higher.
48
+ alibi (bool): Whether to use the alibi bias instead of position embeddings.
49
+ alibi_bias_max (int): The maximum value of the alibi bias.
50
+ rope (bool): Whether to use rotary positional embeddings.
51
+ rope_theta (int): The base frequency for rope.
52
+ rope_impl (str): The implementation of rope to use. One of 'hf' (to use the implementation from https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py) or 'dail' (to use the implementation from https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/layers/rotary.py).
53
+ rope_dail_config (Dict): The configuration for the dail implementation of rope.
54
+ type (str): The type of rotary position embedding to use. Options: 'original' (for https://arxiv.org/pdf/2104.09864.pdf), 'xpos' (for https://arxiv.org/pdf/2212.10554.pdf).
55
+ pos_idx_in_fp32 (bool): If True, the position indices [0, ..., seqlen - 1] are in fp32, otherwise they might be in lower precision. A consequence could be, for example, that bf16 rounds position 1995 to 2000, which leads to them having the same positional embedding.
56
+ xpos_scale_base (float): The scale base for XPos (if using XPos).
57
+ rope_hf_config (Dict): A dictionary used to configure rope's scaling behavior (when scaling beyond the training length).
58
+ type (str): Can be one of 'no_scaling', 'linear', or 'dynamic'. 'no_scaling' uses the default implementation for rotary embeddings, 'linear' uses linear scaling as proposed by the Reddit user /u/kaiokendev, and 'dynamic' uses Dynamic NTK scaling as proposed by the Reddit users /u/bloc97 and /u/emozilla.
59
+ factor (float): Scaling factor to use if using 'linear' or 'dynamic' as rope_scaling.type.
60
+ kv_n_heads (Optional[int]): For grouped_query_attention only, allow user to specify number of kv heads.
61
+ ffn_config (Dict): A dictionary used to configure the model's ffn module:
62
+ ffn_type (str): type of ffn to use. Options: mptmlp, mptglu, te_ln_mlp
63
+ init_device (str): The device to use for parameter initialization.
64
+ logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
65
+ no_bias (bool): Whether to use bias in all layers.
66
+ embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
67
+ norm_type (str): choose type of norm to use
68
+ use_cache (bool): Whether or not the model should return the last key/values attentions
69
+ init_config (Dict): A dictionary used to configure the model initialization:
70
+ init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_',
71
+ 'kaiming_uniform_', 'kaiming_normal_', 'neox_init_', 'small_init_', 'xavier_uniform_', or
72
+ 'xavier_normal_'. These mimic the parameter initialization methods in PyTorch.
73
+ init_div_is_residual (Union[int, float, str, bool]): Value to divide initial weights by if ``module._is_residual`` is True.
74
+ emb_init_std (Optional[float]): The standard deviation of the normal distribution used to initialize the embedding layer.
75
+ emb_init_uniform_lim (Optional[Union[Tuple[float, float], float]]): The lower and upper limits of the uniform distribution
76
+ used to initialize the embedding layer. Mutually exclusive with ``emb_init_std``.
77
+ init_std (float): The standard deviation of the normal distribution used to initialize the model,
78
+ if using the baseline_ parameter initialization scheme.
79
+ init_gain (float): The gain to use for parameter initialization with kaiming or xavier initialization schemes.
80
+ fan_mode (str): The fan mode to use for parameter initialization with kaiming initialization schemes.
81
+ init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes.
82
+ ---
83
+ See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
84
+ fc_type (str): choose fc layer implementation. Options: torch and te. te layers support fp8 when using H100 GPUs.
85
+ tie_word_embeddings (bool): Whether to tie the input embedding and output layers.
86
+ use_pad_tok_in_ffn (bool): Whether to forward the pad token in the feedforward networks.
87
+ """
88
+ self.d_model = d_model
89
+ self.n_heads = n_heads
90
+ self.n_layers = n_layers
91
+ self.expansion_ratio = expansion_ratio
92
+ self.max_seq_len = max_seq_len
93
+ self.vocab_size = vocab_size
94
+ self.resid_pdrop = resid_pdrop
95
+ self.emb_pdrop = emb_pdrop
96
+ self.learned_pos_emb = learned_pos_emb
97
+ self.attn_config = attn_config
98
+ self.ffn_config = ffn_config
99
+ self.init_device = init_device
100
+ self.logit_scale = logit_scale
101
+ self.no_bias = no_bias
102
+ self.embedding_fraction = embedding_fraction
103
+ self.norm_type = norm_type
104
+ self.use_cache = use_cache
105
+ self.init_config = init_config
106
+ self.fc_type = fc_type
107
+ self.use_pad_tok_in_ffn = use_pad_tok_in_ffn
108
+ if 'name' in kwargs:
109
+ del kwargs['name']
110
+ if 'loss_fn' in kwargs:
111
+ del kwargs['loss_fn']
112
+ if self.attn_config.get('alibi', False) or self.attn_config.get('rope', False):
113
+ self.learned_pos_emb = False
114
+ warnings.warn(f'alibi or rope is turned on, setting `learned_pos_emb` to `False.`')
115
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
116
+ self._validate_config()
117
+
118
+ def _set_config_defaults(self, config: Dict[str, Any], config_defaults: Dict[str, Any]) -> Dict[str, Any]:
119
+ for (k, v) in config_defaults.items():
120
+ if k not in config:
121
+ config[k] = v
122
+ elif isinstance(v, dict):
123
+ config[k] = self._set_config_defaults(config[k] if config[k] is not None else {}, v)
124
+ return config
125
+
126
+ def _validate_config(self) -> None:
127
+ self.attn_config = self._set_config_defaults(self.attn_config, attn_config_defaults)
128
+ self.ffn_config = self._set_config_defaults(self.ffn_config, ffn_config_defaults)
129
+ self.init_config = self._set_config_defaults(self.init_config, init_config_defaults)
130
+ if self.d_model % self.n_heads != 0:
131
+ raise ValueError('d_model must be divisible by n_heads')
132
+ if any((prob < 0 or prob > 1 for prob in [self.attn_config['attn_pdrop'], self.resid_pdrop, self.emb_pdrop])):
133
+ raise ValueError("self.attn_config['attn_pdrop'], resid_pdrop, emb_pdrop are probabilities and must be between 0 and 1")
134
+ if self.attn_config['attn_impl'] not in ['torch', 'flash', 'triton']:
135
+ raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}")
136
+ if self.attn_config['prefix_lm'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
137
+ raise NotImplementedError('prefix_lm only implemented with torch and triton attention.')
138
+ if self.attn_config['attn_impl'] == 'flash' and is_flash_v1_installed():
139
+ warnings.warn(VersionedDeprecationWarning('Support for Flash Attention v1 is deprecated. Please upgrade to Flash Attention v2.4.2. To install Flash Attention v2.4.2, please run `pip install -e ".[gpu-flash2]"` from the root directory of the llm-foundry repository.', remove_version='0.6.0'))
140
+ if self.attn_config['attn_impl'] == 'triton' and (not self.attn_config['prefix_lm']):
141
+ warnings.warn(UserWarning('If not using a Prefix Language Model, we recommend setting "attn_impl" to "flash" instead of "triton".'))
142
+ if self.attn_config['alibi'] and (not check_alibi_support(self.attn_config['attn_impl'])):
143
+ raise NotImplementedError('alibi only implemented with torch, triton, and flash (v2.4.2 or higher) attention.')
144
+ if self.attn_config['attn_uses_sequence_id'] and (not (self.attn_config['attn_impl'] in ['torch', 'triton'] or (self.attn_config['attn_impl'] == 'flash' and is_flash_v2_installed(v2_version='v2.1.2')))):
145
+ raise NotImplementedError('attn_uses_sequence_id only implemented with torch, triton, and flash (v2.1.2 or higher) attention.')
146
+ if self.attn_config['rope'] and self.attn_config['rope_impl'] not in ['dail', 'hf']:
147
+ raise ValueError('If rope is being used then rope_impl should be either "dail", or "hf".')
148
+ if self.attn_config['rope'] and self.attn_config['rope_impl'] == 'hf' and (self.attn_config['rope_hf_config']['type'] not in ['no_scaling', 'linear', 'dynamic']):
149
+ raise ValueError('If using hf implementation of rope, the type should be one of "no_scaling", "linear" or "dynamic".')
150
+ if self.attn_config['rope'] and self.attn_config['rope_impl'] == 'dail':
151
+ if self.attn_config['rope_dail_config']['type'] not in ['original', 'xpos']:
152
+ raise ValueError('If using the dail implementation of rope, the type should be one of "original" or "xpos".')
153
+ if not is_flash_v2_installed(v2_version='2.0.1'):
154
+ raise ImportError('If using the dail implementation of rope, the flash_attn library v2.0.1 or higher must be installed. Please check the instructions at https://github.com/mosaicml/llm-foundry/blob/main/TUTORIAL.md#what-kinds-of-positional-embeddings-does-llm-foundry-support')
155
+ if self.attn_config['sliding_window_size'] != -1 and (not (self.attn_config['attn_impl'] == 'flash' and is_flash_v2_installed(v2_version='v2.3.0'))):
156
+ raise NotImplementedError('sliding window only implemented with flash attention v2.3.0 or higher.')
157
+ if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
158
+ raise ValueError('model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!')
159
+ if isinstance(self.logit_scale, str) and self.logit_scale != 'inv_sqrt_d_model':
160
+ raise ValueError(f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
161
+ if self.init_config.get('name', None) is None:
162
+ raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
163
+ if not (self.learned_pos_emb or self.attn_config['alibi'] or self.attn_config['rope']):
164
+ warnings.warn(f'Positional information not being provided to the model using either learned_pos_emb or alibi or rope.')
165
+ if self.fc_type == 'te' or self.ffn_config['ffn_type'] == 'te_ln_mlp':
166
+ try:
167
+ import transformer_engine.pytorch as te
168
+ del te
169
+ except:
170
+ 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')
171
+ if self.ffn_config['ffn_type'] == 'mptgeglu':
172
+ raise ValueError('API CHANGE: `ffn_type=="mptgeglu"` changed to `ffn_type=="mptglu"`. ' + 'See [#829](https://github.com/mosaicml/llm-foundry/pull/829) for details.')
173
+ elif self.ffn_config['ffn_type'] in ['mptmlp', 'mptglu']:
174
+ self.ffn_config['fc_type'] = self.fc_type
175
+ elif self.ffn_config['ffn_type'] == 'te_ln_mlp':
176
+ self.ffn_config['bias'] = not self.no_bias
177
+ if 'ffn_act_fn' in self.ffn_config.keys():
178
+ raise ValueError(f'Transformer Engine block does not support custom activation functions.')
179
+ if not self.use_pad_tok_in_ffn:
180
+ try:
181
+ from flash_attn.bert_padding import unpad_input, pad_input
182
+ except:
183
+ raise ImportError('In order to set `use_pad_tok_in_ffn=False`, please install flash-attn==1.0.9 or flash-attn==2.3.6')