Safetensors
mpt
custom_code
gosshh commited on
Commit
d502339
·
verified ·
1 Parent(s): 29cb477

Create modeling_mpt.py

Browse files

For OpenVino based optimization its looking for this file inside HF repo

Files changed (1) hide show
  1. modeling_mpt.py +540 -0
modeling_mpt.py ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A simple, flexible implementation of a GPT model.
2
+
3
+ Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
4
+ """
5
+ from __future__ import annotations
6
+ import math
7
+ import warnings
8
+ from typing import Any, Dict, List, Mapping, MutableMapping, Optional, Tuple, Union
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from .attention import is_flash_v1_installed, is_flash_v2_installed
13
+ from .norm import NORM_CLASS_REGISTRY
14
+ if is_flash_v2_installed():
15
+ try:
16
+ from flash_attn import bert_padding
17
+ from flash_attn.layers.rotary import RotaryEmbedding as DAILRotaryEmbedding
18
+ except Exception as e:
19
+ raise e
20
+ if is_flash_v1_installed():
21
+ try:
22
+ from flash_attn import bert_padding
23
+ except Exception as e:
24
+ raise e
25
+ from transformers import PreTrainedModel, PreTrainedTokenizerBase
26
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
27
+ from transformers.models.llama.modeling_llama import LlamaDynamicNTKScalingRotaryEmbedding as HFDynamicNTKScalingRotaryEmbedding
28
+ from transformers.models.llama.modeling_llama import LlamaLinearScalingRotaryEmbedding as HFLinearScalingRotaryEmbedding
29
+ from transformers.models.llama.modeling_llama import LlamaRotaryEmbedding as HFRotaryEmbedding
30
+ from .attention import attn_bias_shape, build_attn_bias, gen_slopes
31
+ from .blocks import MPTBlock
32
+ from .custom_embedding import SharedEmbedding
33
+ from .ffn import build_ffn as build_ffn
34
+ from .configuration_mpt import MPTConfig
35
+ from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising
36
+ from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm
37
+ from .meta_init_context import init_empty_weights
38
+ from .param_init_fns import generic_param_init_fn_, MODEL_INIT_REGISTRY
39
+ from .act_ckpt import pass_on_block_idx, build_act_ckpt_mod_to_blocks, check_mapping_blocks_overlap
40
+ try:
41
+ from .flash_attn_triton import flash_attn_func as flash_attn_func
42
+ except:
43
+ pass
44
+ import logging
45
+ log = logging.getLogger(__name__)
46
+
47
+ def gen_rotary_embedding(rope_head_dim: int, rope_impl: str, rope_theta: int, rope_dail_config: dict, rope_hf_config: dict, max_seq_len: int):
48
+ if rope_impl == 'dail':
49
+ return DAILRotaryEmbedding(dim=rope_head_dim, base=rope_theta, interleaved=False, scale_base=rope_dail_config['xpos_scale_base'] if rope_dail_config['type'] == 'xpos' else None, pos_idx_in_fp32=rope_dail_config['pos_idx_in_fp32'], device='cpu')
50
+ elif rope_impl == 'hf':
51
+ if rope_hf_config['type'] == 'no_scaling':
52
+ return HFRotaryEmbedding(rope_head_dim, max_position_embeddings=max_seq_len, base=rope_theta, device='cpu')
53
+ elif rope_hf_config['type'] == 'linear':
54
+ return HFLinearScalingRotaryEmbedding(rope_head_dim, max_position_embeddings=max_seq_len, base=rope_theta, scaling_factor=rope_hf_config['factor'], device='cpu')
55
+ elif rope_hf_config['type'] == 'dynamic':
56
+ return HFDynamicNTKScalingRotaryEmbedding(rope_head_dim, max_position_embeddings=max_seq_len, base=rope_theta, scaling_factor=rope_hf_config['factor'], device='cpu')
57
+ raise ValueError('rope_impl needs to be either dail or hf')
58
+
59
+ def gen_attention_mask_in_length(sequence_id: Union[None, torch.Tensor], S: int, attn_uses_sequence_id: bool, attn_impl: str, attention_mask: Union[torch.Tensor, None]):
60
+ """Generates the attention mask used for sequence masking in FA v2.
61
+
62
+ Only supports sequence id based sparse attention for no attention masking or attention masking with right padding.
63
+ In case of left padding:
64
+ 1. Training with left padding is not supported in MPT (see https://github.com/mosaicml/llm-foundry/blob/1eecd4cb8e734499f77f6a35f657b8b20c0adfcb/llmfoundry/models/mpt/modeling_mpt.py#L407).
65
+ 2. For generation with left padding, we only have a single sequence id per sample, so we don't need sequence id based sparse attention.
66
+
67
+ Args:
68
+ sequence_id (Union[None, torch.Tensor]): Tensor containing the sequence id for each token. Shape (batch_size, seq_len).
69
+ S (int): Sequence length
70
+ attn_uses_sequence_id (bool): Whether the attention uses sequence id based masking.
71
+ attn_impl (str): Attention implementation. This function is only creates attention_mask_in_length for flash attention.
72
+ attention_mask (Union[torch.Tensor, None]): Attention mask tensor of shape (batch_size, seq_len)
73
+
74
+ Returns:
75
+ attention_mask_in_length: (batch, seqlen), int, a nonzero number (e.g., 1, 2, 3, etc.) means length of concatenated sequence in b-th batch, and 0 means none. For example, if batch = 3 and seqlen = 6, the attention_mask_in_length is:
76
+ ```
77
+ [
78
+ [2, 3, 0, 0, 0, 0],
79
+ [3, 2, 0, 0, 0, 0],
80
+ [6, 0, 0, 0, 0, 0]
81
+ ]
82
+ ```
83
+ , which refers to the 3D-attention mask:
84
+ ```
85
+ [
86
+ [
87
+ [1, 0, 0, 0, 0, 0],
88
+ [1, 1, 0, 0, 0, 0],
89
+ [0, 0, 1, 0, 0, 0],
90
+ [0, 0, 1, 1, 0, 0],
91
+ [0, 0, 1, 1, 1, 0],
92
+ [0, 0, 0, 0, 0, 1]
93
+ ],
94
+ [
95
+ [1, 0, 0, 0, 0, 0],
96
+ [1, 1, 0, 0, 0, 0],
97
+ [1, 1, 1, 0, 0, 0],
98
+ [0, 0, 0, 1, 0, 0],
99
+ [0, 0, 0, 1, 1, 0],
100
+ [0, 0, 0, 0, 0, 1]
101
+ ],
102
+ [
103
+ [1, 0, 0, 0, 0, 0],
104
+ [1, 1, 0, 0, 0, 0],
105
+ [1, 1, 1, 0, 0, 0],
106
+ [1, 1, 1, 1, 0, 0],
107
+ [1, 1, 1, 1, 1, 0],
108
+ [1, 1, 1, 1, 1, 1]
109
+ ]
110
+ ]
111
+ ```.
112
+ (The description above is taken verbatim from https://github.com/Dao-AILab/flash-attention/blob/9356a1c0389660d7e231ff3163c1ac17d9e3824a/flash_attn/bert_padding.py#L125 .)
113
+ """
114
+ attention_mask_in_length = None
115
+ if sequence_id is not None and attn_uses_sequence_id and (attn_impl == 'flash'):
116
+ if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0]:
117
+ raise NotImplementedError('Left padding is not supported with flash attention when attn_uses_sequence_id is set to True.')
118
+ if S != sequence_id.shape[-1]:
119
+ raise ValueError(f'Sequence length ({S}) does not match length of sequences in sequence_id ({sequence_id.shape[-1]}).')
120
+ if attention_mask is not None:
121
+ sequence_id = sequence_id.masked_fill(~attention_mask, 0)
122
+ attention_mask_in_length = torch.nn.functional.one_hot(sequence_id)
123
+ if attention_mask is not None:
124
+ attention_mask_in_length = attention_mask_in_length.masked_fill(~attention_mask.unsqueeze(-1), 0)
125
+ attention_mask_in_length = attention_mask_in_length.sum(dim=1)
126
+ attention_mask_in_length = torch.nn.functional.pad(attention_mask_in_length, (0, S - attention_mask_in_length.shape[-1]), mode='constant', value=0)
127
+ return attention_mask_in_length
128
+
129
+ def gen_flash_attn_padding_info(bsz: int, S: int, past_key_len: int, device: torch.device, attention_mask_in_length: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None):
130
+ flash_attn_padding_info = {}
131
+ if attention_mask_in_length is None:
132
+ key_padding_mask = attention_mask
133
+ if key_padding_mask is None:
134
+ key_padding_mask = torch.ones((bsz, past_key_len + S), dtype=torch.bool, device=device)
135
+ query_padding_mask = key_padding_mask[:, -S:]
136
+ unpadding_function = bert_padding.unpad_input
137
+ else:
138
+ key_padding_mask = attention_mask_in_length
139
+ query_padding_mask = attention_mask_in_length
140
+ unpadding_function = bert_padding.unpad_input_for_concatenated_sequences
141
+ _, indices_q, cu_seqlens_q, max_seqlen_q = unpadding_function(torch.empty(bsz, S, 1, device=device), query_padding_mask)
142
+ _, indices_k, cu_seqlens_k, max_seqlen_k = unpadding_function(torch.empty(bsz, past_key_len + S, 1, device=device), key_padding_mask)
143
+ _, indices_v, _, _ = unpadding_function(torch.empty(bsz, past_key_len + S, 1, device=device), key_padding_mask)
144
+ flash_attn_padding_info['indices_q'] = indices_q
145
+ flash_attn_padding_info['indices_k'] = indices_k
146
+ flash_attn_padding_info['indices_v'] = indices_v
147
+ flash_attn_padding_info['cu_seqlens_q'] = cu_seqlens_q
148
+ flash_attn_padding_info['cu_seqlens_k'] = cu_seqlens_k
149
+ flash_attn_padding_info['max_seqlen_q'] = max_seqlen_q
150
+ flash_attn_padding_info['max_seqlen_k'] = max_seqlen_k
151
+ return flash_attn_padding_info
152
+
153
+ def apply_sequence_id(attn_bias: torch.Tensor, sequence_id: torch.LongTensor, max_seq_len: int) -> torch.Tensor:
154
+ seq_len = sequence_id.shape[-1]
155
+ if seq_len > max_seq_len:
156
+ raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={max_seq_len}')
157
+ attn_bias = attn_bias[..., :seq_len, :seq_len]
158
+ cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1)
159
+ min_val = torch.finfo(attn_bias.dtype).min
160
+ attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
161
+ return attn_bias
162
+
163
+ class MPTPreTrainedModel(PreTrainedModel):
164
+ config_class = MPTConfig
165
+ base_model_prefix = 'model'
166
+ _no_split_modules = ['MPTBlock']
167
+
168
+ def _fsdp_wrap_fn(self: Union[MPTModel, MPTForCausalLM], module: nn.Module) -> bool:
169
+ return isinstance(module, MPTBlock)
170
+
171
+ class MPTModel(MPTPreTrainedModel):
172
+
173
+ def __init__(self, config: MPTConfig):
174
+ config._validate_config()
175
+ super().__init__(config)
176
+ self.attn_impl = config.attn_config['attn_impl']
177
+ self.prefix_lm = config.attn_config['prefix_lm']
178
+ self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']
179
+ self.alibi = config.attn_config['alibi']
180
+ self.alibi_bias_max = config.attn_config['alibi_bias_max']
181
+ self.learned_pos_emb = config.learned_pos_emb
182
+ if config.init_device == 'mixed':
183
+ if dist.get_local_rank() == 0:
184
+ config.init_device = 'cpu'
185
+ else:
186
+ config.init_device = 'meta'
187
+ if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys():
188
+ norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys())
189
+ raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).')
190
+ norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()]
191
+ self.embedding_fraction = config.embedding_fraction
192
+ self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device)
193
+ if self.learned_pos_emb:
194
+ self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device)
195
+ self.emb_drop = nn.Dropout(config.emb_pdrop)
196
+ self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])
197
+ for i, block in enumerate(self.blocks):
198
+ block.block_idx = i
199
+ block.max_block_idx = config.n_layers - 1
200
+ pass_on_block_idx(block)
201
+ self.norm_f = norm_class(config.d_model, device=config.init_device)
202
+ self.rope = config.attn_config['rope']
203
+ self.rope_impl = None
204
+ if self.rope:
205
+ self.rope_impl = config.attn_config['rope_impl']
206
+ self.rotary_embedding = gen_rotary_embedding(rope_head_dim=config.d_model // config.n_heads, rope_impl=self.rope_impl, rope_theta=config.attn_config['rope_theta'], rope_dail_config=config.attn_config['rope_dail_config'], rope_hf_config=config.attn_config['rope_hf_config'], max_seq_len=self.config.max_seq_len)
207
+ if config.init_device != 'meta':
208
+ log.info(f'We recommend using config.init_device="meta" with Composer + FSDP for faster initialization.')
209
+ self.apply(self.param_init_fn)
210
+ self.is_causal = not self.prefix_lm
211
+ self._attn_bias_initialized = False
212
+ self.attn_bias = None
213
+ self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id)
214
+ if config.no_bias:
215
+ for module in self.modules():
216
+ if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
217
+ log.info(f'Removing bias from module={module!r}.')
218
+ module.register_parameter('bias', None)
219
+ if hasattr(module, 'use_bias'):
220
+ log.info(f'Setting use_bias=False for module={module!r}.')
221
+ module.use_bias = False
222
+ log.debug(self)
223
+ log.debug(f"Using {self.config.init_config['name']} initialization.")
224
+
225
+ def get_input_embeddings(self) -> Union[SharedEmbedding, nn.Embedding]:
226
+ return self.wte
227
+
228
+ def set_input_embeddings(self, value: Union[SharedEmbedding, nn.Embedding]) -> None:
229
+ self.wte = value
230
+
231
+ @torch.no_grad()
232
+ def _attn_bias(self, device: torch.device, dtype: torch.dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None) -> Tuple[Optional[torch.Tensor], Optional[torch.ByteTensor]]:
233
+ if not self._attn_bias_initialized:
234
+ if self.attn_bias_shape:
235
+ self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
236
+ self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max)
237
+ self._attn_bias_initialized = True
238
+ if self.attn_impl == 'flash':
239
+ return (self.attn_bias, attention_mask)
240
+ if self.attn_bias is not None:
241
+ self.attn_bias = self.attn_bias.to(dtype=dtype, device=device)
242
+ attn_bias = self.attn_bias
243
+ if self.prefix_lm:
244
+ assert isinstance(attn_bias, torch.Tensor)
245
+ assert isinstance(prefix_mask, torch.Tensor)
246
+ attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)
247
+ if self.attn_uses_sequence_id and sequence_id is not None:
248
+ assert isinstance(attn_bias, torch.Tensor)
249
+ attn_bias = apply_sequence_id(attn_bias, sequence_id, self.config.max_seq_len)
250
+ if attention_mask is not None:
251
+ s_k = attention_mask.shape[-1]
252
+ if attn_bias is None:
253
+ attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype)
254
+ else:
255
+ _s_k = max(0, attn_bias.size(-1) - s_k)
256
+ attn_bias = attn_bias[:, :, :, _s_k:]
257
+ if prefix_mask is not None and attention_mask.shape != prefix_mask.shape:
258
+ raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.')
259
+ min_val = torch.finfo(attn_bias.dtype).min
260
+ attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val)
261
+ return (attn_bias, attention_mask)
262
+
263
+ def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor) -> torch.Tensor:
264
+ s_k, s_q = attn_bias.shape[-2:]
265
+ if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len:
266
+ raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.')
267
+ seq_len = prefix_mask.shape[-1]
268
+ if seq_len > self.config.max_seq_len:
269
+ raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
270
+ attn_bias = attn_bias[..., :seq_len, :seq_len]
271
+ causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len)
272
+ prefix = prefix_mask.view(-1, 1, 1, seq_len)
273
+ cannot_attend = ~torch.logical_or(causal, prefix.bool())
274
+ min_val = torch.finfo(attn_bias.dtype).min
275
+ attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
276
+ return attn_bias
277
+
278
+ def forward(self, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None) -> BaseModelOutputWithPast:
279
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
280
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
281
+ if attention_mask is not None:
282
+ attention_mask = attention_mask.bool()
283
+ if prefix_mask is not None:
284
+ prefix_mask = prefix_mask.bool()
285
+ if not return_dict:
286
+ raise NotImplementedError('return_dict False is not implemented yet for MPT')
287
+ if output_attentions:
288
+ if self.attn_impl != 'torch':
289
+ raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.')
290
+ if self.training and attention_mask is not None and (attention_mask[:, 0].sum() != attention_mask.shape[0]):
291
+ raise NotImplementedError('MPT does not support training with left padding.')
292
+ if self.prefix_lm and prefix_mask is None:
293
+ raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')
294
+ if self.training:
295
+ if self.attn_uses_sequence_id and sequence_id is None:
296
+ raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.')
297
+ elif self.attn_uses_sequence_id is False and sequence_id is not None:
298
+ warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.')
299
+ if input_ids is not None and inputs_embeds is not None:
300
+ raise ValueError('You cannot specify both input_ids and inputs_embeds.')
301
+ elif input_ids is not None:
302
+ bsz = input_ids.size(0)
303
+ S = input_ids.size(1)
304
+ x = self.wte(input_ids)
305
+ input_device = input_ids.device
306
+ elif inputs_embeds is not None:
307
+ bsz = inputs_embeds.size(0)
308
+ S = inputs_embeds.size(1)
309
+ x = inputs_embeds
310
+ input_device = inputs_embeds.device
311
+ else:
312
+ raise ValueError('You must specify input_ids or inputs_embeds')
313
+ #assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}'
314
+ rotary_emb_w_meta_info = None
315
+ past_position = 0
316
+ if past_key_values is not None:
317
+ if len(past_key_values) != self.config.n_layers:
318
+ raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).')
319
+ past_position = past_key_values[0][0].size(1)
320
+ if self.attn_impl == 'torch':
321
+ past_position = past_key_values[0][0].size(3)
322
+ if self.learned_pos_emb or self.rope:
323
+ if self.learned_pos_emb and S + past_position > self.config.max_seq_len:
324
+ raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length ' + f'{S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.')
325
+ if self.learned_pos_emb or (self.rope and self.rope_impl == 'hf'):
326
+ pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_device).unsqueeze(0)
327
+ if attention_mask is not None:
328
+ pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0)
329
+ if self.learned_pos_emb:
330
+ x = x + self.wpe(pos)
331
+ elif self.rope and self.rope_impl == 'hf':
332
+ rotary_emb_w_meta_info = {'impl': self.rope_impl, 'rotary_emb': self.rotary_embedding, 'offset_info': pos, 'seq_len': S + past_position}
333
+ elif self.rope and self.rope_impl == 'dail':
334
+ rotary_emb_w_meta_info = {'impl': self.rope_impl, 'rotary_emb': self.rotary_embedding, 'offset_info': past_position, 'seq_len': S + past_position}
335
+ if self.embedding_fraction == 1:
336
+ x = self.emb_drop(x)
337
+ else:
338
+ x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction)
339
+ assert isinstance(self.emb_drop, nn.Module)
340
+ x = self.emb_drop(x_shrunk)
341
+ attn_bias, attention_mask = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id)
342
+ attention_mask_in_length = gen_attention_mask_in_length(sequence_id=sequence_id, S=S, attn_uses_sequence_id=self.attn_uses_sequence_id, attn_impl=self.attn_impl, attention_mask=attention_mask)
343
+ alibi_slopes = None
344
+ if self.alibi and self.attn_impl == 'flash':
345
+ alibi_slopes = gen_slopes(n_heads=self.config.n_heads, alibi_bias_max=self.alibi_bias_max, device=x.device, return_1d=True)
346
+ presents = () if use_cache else None
347
+ if use_cache and past_key_values is None:
348
+ past_key_values = [() for _ in range(self.config.n_layers)]
349
+ all_hidden_states = () if output_hidden_states else None
350
+ all_self_attns = () if output_attentions else None
351
+ flash_attn_padding_info = {}
352
+ if self.attn_impl == 'flash':
353
+ flash_attn_padding_info = gen_flash_attn_padding_info(bsz, S, past_position, x.device, attention_mask_in_length, attention_mask)
354
+ for b_idx, block in enumerate(self.blocks):
355
+ if output_hidden_states:
356
+ assert all_hidden_states is not None
357
+ all_hidden_states = all_hidden_states + (x,)
358
+ past_key_value = past_key_values[b_idx] if past_key_values is not None else None
359
+ x, attn_weights, present = block(x, past_key_value=past_key_value, attn_bias=attn_bias, rotary_emb_w_meta_info=rotary_emb_w_meta_info, attention_mask=attention_mask, is_causal=self.is_causal, output_attentions=bool(output_attentions), alibi_slopes=alibi_slopes, flash_attn_padding_info=flash_attn_padding_info)
360
+ if presents is not None:
361
+ presents += (present,)
362
+ if output_attentions:
363
+ assert all_self_attns is not None
364
+ all_self_attns = all_self_attns + (attn_weights,)
365
+ x = self.norm_f(x)
366
+ if output_hidden_states:
367
+ assert all_hidden_states is not None
368
+ all_hidden_states = all_hidden_states + (x,)
369
+ return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attns)
370
+
371
+ def param_init_fn(self, module: nn.Module) -> None:
372
+ init_fn_name = self.config.init_config['name']
373
+ MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
374
+
375
+ def fsdp_wrap_fn(self, module: nn.Module) -> bool:
376
+ return _fsdp_wrap_fn(self, module)
377
+
378
+ def activation_checkpointing_fn(self, module: nn.Module) -> bool:
379
+ return isinstance(module, MPTBlock)
380
+
381
+ class MPTForCausalLM(MPTPreTrainedModel):
382
+
383
+ def __init__(self, config: MPTConfig):
384
+ super().__init__(config)
385
+ log.info(f'Instantiating an MPTForCausalLM model from {__file__}')
386
+ self.transformer: MPTModel = MPTModel(config)
387
+ self.lm_head = None
388
+ if not config.tie_word_embeddings:
389
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False, device=config.init_device)
390
+ self.lm_head._fsdp_wrap = True
391
+ for child in self.transformer.children():
392
+ if isinstance(child, torch.nn.ModuleList):
393
+ continue
394
+ if isinstance(child, torch.nn.Module):
395
+ child._fsdp_wrap = True
396
+ self.logit_scale = None
397
+ if config.logit_scale is not None:
398
+ logit_scale = config.logit_scale
399
+ if isinstance(logit_scale, str):
400
+ if logit_scale == 'inv_sqrt_d_model':
401
+ logit_scale = 1 / math.sqrt(config.d_model)
402
+ else:
403
+ raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
404
+ self.logit_scale = logit_scale
405
+
406
+ def get_input_embeddings(self) -> Union[SharedEmbedding, nn.Embedding]:
407
+ return self.transformer.get_input_embeddings()
408
+
409
+ def set_input_embeddings(self, value: Union[SharedEmbedding, nn.Embedding]) -> None:
410
+ self.transformer.set_input_embeddings(value)
411
+
412
+ def get_output_embeddings(self) -> Union[SharedEmbedding, nn.Embedding, nn.Linear]:
413
+ if self.lm_head is not None:
414
+ return self.lm_head
415
+ return self.transformer.get_input_embeddings()
416
+
417
+ def set_output_embeddings(self, new_embeddings: Union[SharedEmbedding, nn.Embedding, nn.Linear]) -> None:
418
+ if self.lm_head is not None:
419
+ self.lm_head = new_embeddings
420
+ else:
421
+ if not isinstance(new_embeddings, (SharedEmbedding, nn.Embedding)):
422
+ raise ValueError('new_embeddings must be an instance of SharedEmbedding ' + f'or nn.Embedding, but got {type(new_embeddings)}.')
423
+ warnings.warn('Using `set_output_embeddings` to set the embedding layer of ' + 'MPTForCausalLM with tied weights. Given weights are tied, ' + 'using `set_input_embeddings` is recommended over using ' + '`set_output_embeddings`.')
424
+ self.transformer.set_input_embeddings(new_embeddings)
425
+
426
+ def tie_weights(self) -> None:
427
+ self.lm_head = None
428
+
429
+ def set_decoder(self, decoder: MPTModel) -> None:
430
+ self.transformer = decoder
431
+
432
+ def get_decoder(self) -> MPTModel:
433
+ return self.transformer
434
+
435
+ def forward(self, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.FloatTensor]=None) -> CausalLMOutputWithPast:
436
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
437
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
438
+ outputs = self.transformer(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache, inputs_embeds=inputs_embeds)
439
+ if self.lm_head is not None:
440
+ logits = self.lm_head(outputs.last_hidden_state)
441
+ else:
442
+ out = outputs.last_hidden_state
443
+ out = out.to(self.transformer.wte.weight.device)
444
+ logits = self.transformer.wte(out, True)
445
+ if self.logit_scale is not None:
446
+ if self.logit_scale == 0:
447
+ warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
448
+ logits *= self.logit_scale
449
+ loss = None
450
+ if labels is not None:
451
+ _labels = torch.roll(labels, shifts=-1)
452
+ _labels[:, -1] = -100
453
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), _labels.to(logits.device).view(-1))
454
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
455
+
456
+ def param_init_fn(self, module: nn.Module) -> None:
457
+ init_fn_name = self.config.init_config['name']
458
+ MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
459
+
460
+ def fsdp_wrap_fn(self, module: nn.Module) -> bool:
461
+ return _fsdp_wrap_fn(self, module)
462
+
463
+ def activation_checkpointing_fn(self, module: nn.Module) -> bool:
464
+ """The MPT activation checkpointing (act ckpt) function.
465
+
466
+ When `activation_checkpointing` in fsdp_config is set to true, this function will be called on all the modules in the FSDP wrapped model and determine whether a given module should be activation checkpointed. It checks the checkpointing target (`activation_checkpointing_target` in `model`) which can be specified as below:
467
+ 1. null (or no such field): The whole MPTBlock will be activation checkpointed on all layers
468
+ 2. a list of modules to act ckpt on all layers, e.g.,
469
+ activation_checkpointing_target:
470
+ - grouped_query_attention
471
+ - mptmlp
472
+ 3. a dictionary of module name with target_blocks, e.g.,
473
+ activation_checkpointing_target:
474
+ {
475
+ "mptblock": target_blocks_1,
476
+ "grouped_query_attention": target_blocks_2
477
+ }
478
+ target_blocks (target_blocks_1, target_blocks_2 above) can be:
479
+ - a single integer n: the first n transformer block will be activation checkpointed
480
+ - a string of first-n, middle-m, last-k, range-i-j: the first n, the middle m, the last k, or the range [i, j) layers will be activation checkpointed. E.g, 'first-2, last-2' means the first 2 and last 2 transformer blocks will be activation checkpointed
481
+ middle-m is range [start, end) where ``start = max(max_block_idx // 2 - m // 2, 0), end = min(start + m, max_block_idx + 1)``
482
+ - a list of integers corresponds to the list of transformer block ids, e.g., [2] means the second transformer block will be activation checkpointed. [2, 3] means the second and third transformer blocks will be activation checkpointed
483
+ - a list of mixed integers and strings of first-n, middle-m, last-k, range-i-j
484
+
485
+ An example in yaml config file:
486
+ fsdp_config:
487
+ activation_checkpointing: true
488
+ model:
489
+ activation_checkpointing_target:
490
+ {
491
+ "mptblock": 'first-5',
492
+ "grouped_query_attention": 'last-35'
493
+ }
494
+ """
495
+ if not hasattr(module, 'block_idx'):
496
+ log.debug(f'{module.__class__.__name__} cannot be activation checkpointed. Only transformer block or its submodules are eligible for activation checkpointing.')
497
+ return False
498
+ act_ckpt_target = getattr(self.config, 'activation_checkpointing_target', None)
499
+ act_ckpt_mod_to_blocks = build_act_ckpt_mod_to_blocks(act_ckpt_target, MPTBlock, module.max_block_idx)
500
+ check_mapping_blocks_overlap(act_ckpt_mod_to_blocks, module.max_block_idx)
501
+ for k in act_ckpt_mod_to_blocks.keys():
502
+ if isinstance(module, k):
503
+ blocks = act_ckpt_mod_to_blocks[k]
504
+ return True if blocks == -1 else module.block_idx in blocks
505
+ return False
506
+
507
+ def prepare_inputs_for_generation(self, input_ids: torch.Tensor, past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]]=None, inputs_embeds: Optional[torch.Tensor]=None, **kwargs: Any) -> Dict[str, Any]:
508
+ attention_mask = kwargs['attention_mask'].bool()
509
+ if attention_mask[:, -1].sum() != attention_mask.shape[0]:
510
+ raise NotImplementedError('MPT does not support generation with right padding.')
511
+ if self.transformer.attn_uses_sequence_id and self.training:
512
+ sequence_id = torch.zeros_like(input_ids[:1])
513
+ else:
514
+ sequence_id = None
515
+ if past_key_values is not None:
516
+ input_ids = input_ids[:, -1].unsqueeze(-1)
517
+ if self.transformer.prefix_lm:
518
+ prefix_mask = torch.ones_like(attention_mask)
519
+ if kwargs.get('use_cache') == False:
520
+ raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
521
+ else:
522
+ prefix_mask = None
523
+ if inputs_embeds is not None and past_key_values is None:
524
+ model_inputs = {'inputs_embeds': inputs_embeds}
525
+ else:
526
+ model_inputs = {'input_ids': input_ids}
527
+ model_inputs.update({'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True)})
528
+ return model_inputs
529
+
530
+ @staticmethod
531
+ def _reorder_cache(past_key_values: List[Tuple[torch.Tensor, torch.Tensor]], beam_idx: torch.LongTensor) -> List[Tuple[torch.Tensor, ...]]:
532
+ """Used by HuggingFace generate when using beam search with kv-caching.
533
+
534
+ See https://github.com/huggingface/transformers/blob/3ec7a47664ebe40c40f4b722f6bb1cd30c3821ec/src/transformers/models/gpt2/modeling_gpt2.py#L1122-L1133
535
+ for an example in transformers.
536
+ """
537
+ reordered_past = []
538
+ for layer_past in past_key_values:
539
+ reordered_past += [tuple((past_state.index_select(0, beam_idx) for past_state in layer_past))]
540
+ return reordered_past