glaiveai/glaive-function-calling-v2-small
1569
1"""A simple, flexible implementation of a GPT model.2 3Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py4"""5import math6import warnings7from typing import List, Optional, Tuple, Union8import torch9import torch.nn as nn10import torch.nn.functional as F11from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast12from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast13from .attention import attn_bias_shape, build_attn_bias14from .blocks import MPTBlock15from .norm import NORM_CLASS_REGISTRY16from .configuration_mpt import MPTConfig17from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising18from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm19from .meta_init_context import init_empty_weights20from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_21Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]22 23class MPTPreTrainedModel(PreTrainedModel):24 config_class = MPTConfig25 base_model_prefix = 'model'26 _no_split_modules=["MPTBlock"]27 28class MPTModel(MPTPreTrainedModel):29 30 def __init__(self, config: MPTConfig):31 config._validate_config()32 super().__init__(config)33 self.attn_impl = config.attn_config['attn_impl']34 self.prefix_lm = config.attn_config['prefix_lm']35 self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']36 self.alibi = config.attn_config['alibi']37 self.alibi_bias_max = config.attn_config['alibi_bias_max']38 if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys():39 norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys())40 raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).')41 norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()]42 self.embedding_fraction = config.embedding_fraction43 self.wte = nn.Embedding(config.vocab_size, config.d_model, device=config.init_device)44 if not self.alibi:45 self.wpe = nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device)46 self.emb_drop = nn.Dropout(config.emb_pdrop)47 self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])48 self.norm_f = norm_class(config.d_model, device=config.init_device)49 if config.init_device != 'meta':50 print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.')51 self.apply(self.param_init_fn)52 self.is_causal = not self.prefix_lm53 self._attn_bias_initialized = False54 self.attn_bias = None55 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)56 if config.no_bias:57 for module in self.modules():58 if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):59 if config.verbose:60 warnings.warn(f'Removing bias ({module.bias}) from {module}.')61 module.register_parameter('bias', None)62 if config.verbose and config.verbose > 2:63 print(self)64 if 'verbose' not in self.config.init_config:65 self.config.init_config['verbose'] = self.config.verbose66 if self.config.init_config['verbose'] > 1:67 init_fn_name = self.config.init_config['name']68 warnings.warn(f'Using {init_fn_name} initialization.')69 70 def get_input_embeddings(self):71 return self.wte72 73 def set_input_embeddings(self, value):74 self.wte = value75 76 @torch.no_grad()77 def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None):78 if not self._attn_bias_initialized:79 if self.attn_bias_shape:80 self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)81 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)82 self._attn_bias_initialized = True83 if self.attn_impl == 'flash':84 return (self.attn_bias, attention_mask)85 if self.attn_bias is not None:86 self.attn_bias = self.attn_bias.to(dtype=dtype, device=device)87 attn_bias = self.attn_bias88 if self.prefix_lm:89 assert isinstance(attn_bias, torch.Tensor)90 assert isinstance(prefix_mask, torch.Tensor)91 attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)92 if self.attn_uses_sequence_id and sequence_id is not None:93 assert isinstance(attn_bias, torch.Tensor)94 attn_bias = self._apply_sequence_id(attn_bias, sequence_id)95 if attention_mask is not None:96 s_k = attention_mask.shape[-1]97 if attn_bias is None:98 attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype)99 else:100 attn_bias = attn_bias[:, :, :, -s_k:]101 if prefix_mask is not None and attention_mask.shape != prefix_mask.shape:102 raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.')103 min_val = torch.finfo(attn_bias.dtype).min104 attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val)105 return (attn_bias, None)106 107 def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor):108 (s_k, s_q) = attn_bias.shape[-2:]109 if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len:110 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}.')111 seq_len = prefix_mask.shape[-1]112 if seq_len > self.config.max_seq_len:113 raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}')114 attn_bias = attn_bias[..., :seq_len, :seq_len]115 causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len)116 prefix = prefix_mask.view(-1, 1, 1, seq_len)117 cannot_attend = ~torch.logical_or(causal, prefix.bool())118 min_val = torch.finfo(attn_bias.dtype).min119 attn_bias = attn_bias.masked_fill(cannot_attend, min_val)120 return attn_bias121 122 def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor):123 seq_len = sequence_id.shape[-1]124 if seq_len > self.config.max_seq_len:125 raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}')126 attn_bias = attn_bias[..., :seq_len, :seq_len]127 cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1)128 min_val = torch.finfo(attn_bias.dtype).min129 attn_bias = attn_bias.masked_fill(cannot_attend, min_val)130 return attn_bias131 132 def forward(self, input_ids: torch.LongTensor, 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):133 return_dict = return_dict if return_dict is not None else self.config.return_dict134 use_cache = use_cache if use_cache is not None else self.config.use_cache135 if attention_mask is not None:136 attention_mask = attention_mask.bool()137 if prefix_mask is not None:138 prefix_mask = prefix_mask.bool()139 if not return_dict:140 raise NotImplementedError('return_dict False is not implemented yet for MPT')141 if output_attentions:142 raise NotImplementedError('output_attentions is not implemented yet for MPT')143 if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training:144 raise NotImplementedError('MPT does not support training with left padding.')145 if self.prefix_lm and prefix_mask is None:146 raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')147 if self.training:148 if self.attn_uses_sequence_id and sequence_id is None:149 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.')150 elif self.attn_uses_sequence_id is False and sequence_id is not None:151 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.')152 S = input_ids.size(1)153 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}'154 tok_emb = self.wte(input_ids)155 if self.alibi:156 x = tok_emb157 else:158 past_position = 0159 if past_key_values is not None:160 if len(past_key_values) != self.config.n_layers:161 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}).')162 past_position = past_key_values[0][0].size(1)163 if S + past_position > self.config.max_seq_len:164 raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.')165 pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0)166 if attention_mask is not None:167 pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0)168 pos_emb = self.wpe(pos)169 x = tok_emb + pos_emb170 if self.embedding_fraction == 1:171 x = self.emb_drop(x)172 else:173 x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction)174 assert isinstance(self.emb_drop, nn.Module)175 x = self.emb_drop(x_shrunk)176 (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=x.dtype, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id)177 if use_cache and past_key_values is None:178 past_key_values = [() for _ in range(self.config.n_layers)]179 all_hidden_states = () if output_hidden_states else None180 for (b_idx, block) in enumerate(self.blocks):181 if output_hidden_states:182 assert all_hidden_states is not None183 all_hidden_states = all_hidden_states + (x,)184 past_key_value = past_key_values[b_idx] if past_key_values is not None else None185 (x, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal)186 if past_key_values is not None:187 past_key_values[b_idx] = past_key_value188 x = self.norm_f(x)189 return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states)190 191 def param_init_fn(self, module):192 init_fn_name = self.config.init_config['name']193 MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)194 195 def fsdp_wrap_fn(self, module):196 return isinstance(module, MPTBlock)197 198 def activation_checkpointing_fn(self, module):199 return isinstance(module, MPTBlock)200 201class MPTForCausalLM(MPTPreTrainedModel):202 203 def __init__(self, config: MPTConfig):204 super().__init__(config)205 if not config.tie_word_embeddings:206 raise ValueError('MPTForCausalLM only supports tied word embeddings')207 self.transformer = MPTModel(config)208 self.logit_scale = None209 if config.logit_scale is not None:210 logit_scale = config.logit_scale211 if isinstance(logit_scale, str):212 if logit_scale == 'inv_sqrt_d_model':213 logit_scale = 1 / math.sqrt(config.d_model)214 else:215 raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")216 self.logit_scale = logit_scale217 218 def get_input_embeddings(self):219 return self.transformer.wte220 221 def set_input_embeddings(self, value):222 self.transformer.wte = value223 224 def get_output_embeddings(self):225 return self.transformer.wte226 227 def set_output_embeddings(self, new_embeddings):228 self.transformer.wte = new_embeddings229 230 def set_decoder(self, decoder):231 self.transformer = decoder232 233 def get_decoder(self):234 return self.transformer235 236 def forward(self, input_ids: torch.LongTensor, 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):237 return_dict = return_dict if return_dict is not None else self.config.return_dict238 use_cache = use_cache if use_cache is not None else self.config.use_cache239 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)240 logits = F.linear(outputs.last_hidden_state, self.transformer.wte.weight)241 if self.logit_scale is not None:242 if self.logit_scale == 0:243 warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')244 logits *= self.logit_scale245 loss = None246 if labels is not None:247 labels = torch.roll(labels, shifts=-1)248 labels[:, -1] = -100249 loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1))250 return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states)251 252 def param_init_fn(self, module):253 init_fn_name = self.config.init_config['name']254 MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)255 256 def fsdp_wrap_fn(self, module):257 return isinstance(module, MPTBlock)258 259 def activation_checkpointing_fn(self, module):260 return isinstance(module, MPTBlock)261 262 def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):263 if inputs_embeds is not None:264 raise NotImplementedError('inputs_embeds is not implemented for MPT yet')265 attention_mask = kwargs['attention_mask'].bool()266 if attention_mask[:, -1].sum() != attention_mask.shape[0]:267 raise NotImplementedError('MPT does not support generation with right padding.')268 if self.transformer.attn_uses_sequence_id and self.training:269 sequence_id = torch.zeros_like(input_ids[:1])270 else:271 sequence_id = None272 if past_key_values is not None:273 input_ids = input_ids[:, -1].unsqueeze(-1)274 if self.transformer.prefix_lm:275 prefix_mask = torch.ones_like(attention_mask)276 if kwargs.get('use_cache') == False:277 raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')278 else:279 prefix_mask = None280 return {'input_ids': input_ids, '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)}281 282 @staticmethod283 def _reorder_cache(past_key_values, beam_idx):284 """Used by HuggingFace generate when using beam search with kv-caching.285 286 See https://github.com/huggingface/transformers/blob/3ec7a47664ebe40c40f4b722f6bb1cd30c3821ec/src/transformers/models/gpt2/modeling_gpt2.py#L1122-L1133287 for an example in transformers.288 """289 reordered_past = []290 for layer_past in past_key_values:291 reordered_past += [tuple((past_state.index_select(0, beam_idx) for past_state in layer_past))]292 return reordered_past