stefan-insilico commited on
Commit
e498fa6
·
verified ·
1 Parent(s): 2315e32

Create precious-multi-modal.py

Browse files
Files changed (1) hide show
  1. mpt_7b/precious-multi-modal.py +354 -0
mpt_7b/precious-multi-modal.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union, List
2
+
3
+ from transformers.models.mpt.modeling_mpt import MptBlock, build_mpt_alibi_tensor
4
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
5
+ import torch
6
+ import torch.nn as nn
7
+ from torch.nn import CrossEntropyLoss, LayerNorm
8
+ from transformers.models.mpt.modeling_mpt import MptBlock, build_mpt_alibi_tensor
9
+ from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions, CausalLMOutputWithPast, \
10
+ BaseModelOutputWithPastAndCrossAttentions, BaseModelOutputWithPast
11
+ # from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig, MptForCausalLM, MptModel
12
+ from transformers import PreTrainedTokenizerFast
13
+ import os
14
+ import torch.nn.functional as F
15
+
16
+ from modeling_mpt import MPTModel, MPTForCausalLM, gen_attention_mask_in_length
17
+ from configuration_mpt import MPTConfig
18
+ from blocks import MPTBlock
19
+ from norm import NORM_CLASS_REGISTRY
20
+ from custom_embedding import SharedEmbedding
21
+ from attention import ATTN_CLASS_REGISTRY, attn_bias_shape, build_attn_bias, gen_slopes
22
+
23
+ import logging
24
+ log = logging.getLogger(__name__)
25
+
26
+
27
+ class Custom_MPTConfig(MPTConfig):
28
+ def __init__(self):
29
+ super().__init__()
30
+
31
+ class CustomTokenizer(PreTrainedTokenizerFast):
32
+ def __init__(self, **kwargs):
33
+ super().__init__( tokenizer_file="../tokenizer.json",
34
+ unk_token="[UNK]",
35
+ pad_token="[PAD]",
36
+ eos_token="[EOS]",
37
+ bos_token="[BOS]", **kwargs)
38
+
39
+
40
+ class Custom_MptModel(MPTModel): # MptModel
41
+ def __init__(self, config: MPTConfig, modality0_dim=128, modality2_dim=1536):
42
+ config._validate_config()
43
+ super().__init__(config)
44
+ self.attn_impl = config.attn_config['attn_impl']
45
+ self.prefix_lm = config.attn_config['prefix_lm']
46
+ self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']
47
+ self.alibi = config.attn_config['alibi']
48
+ self.alibi_bias_max = config.attn_config['alibi_bias_max']
49
+ self.learned_pos_emb = config.learned_pos_emb
50
+ if config.init_device == 'mixed':
51
+ if dist.get_local_rank() == 0:
52
+ config.init_device = 'cpu'
53
+ else:
54
+ config.init_device = 'meta'
55
+ if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys():
56
+ norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys())
57
+ raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).')
58
+ norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()]
59
+ self.embedding_fraction = config.embedding_fraction
60
+ self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device)
61
+ if self.learned_pos_emb:
62
+ self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device)
63
+ self.emb_drop = nn.Dropout(config.emb_pdrop)
64
+ self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])
65
+ self.norm_f = norm_class(config.d_model, device=config.init_device)
66
+
67
+
68
+ ### Added for P3GPT - START
69
+ # Freeze all parameters except the projection layer
70
+ for param in self.wte.parameters():
71
+ param.requires_grad = False
72
+
73
+ for param in self.blocks.parameters():
74
+ param.requires_grad = False
75
+
76
+ # Add a projection layer for the custom embedding
77
+ # torch.set_default_dtype(torch.bfloat16)
78
+ self.modality0_embedding_projection = nn.ModuleList([nn.Linear(modality0_dim, config.d_model),
79
+ # nn.BatchNorm1d(config.d_model),
80
+ nn.ReLU(),
81
+ nn.Linear(config.d_model, config.d_model),
82
+ # nn.BatchNorm1d(config.d_model),
83
+ nn.ReLU(),
84
+ nn.Linear(config.d_model, config.d_model)])# nn.Linear(modality0_dim, self.hidden_size)
85
+
86
+
87
+ self.modality2_embedding_projection = nn.ModuleList([nn.Linear(modality2_dim, config.d_model),
88
+ # nn.BatchNorm1d(config.d_model),
89
+ nn.ReLU(),
90
+ nn.Linear(config.d_model, config.d_model),
91
+ # nn.BatchNorm1d(config.d_model),
92
+ nn.ReLU(),
93
+ nn.Linear(config.d_model, config.d_model)])# nn.Linear(modality0_dim, self.hidden_size)
94
+
95
+
96
+ ### Added for P3GPT - FINISH
97
+
98
+ self.rope = config.attn_config['rope']
99
+ self.rope_impl = None
100
+ if self.rope:
101
+ self.rope_impl = config.attn_config['rope_impl']
102
+ 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)
103
+ if config.init_device != 'meta':
104
+ log.info(f'We recommend using config.init_device="meta" with Composer + FSDP for faster initialization.')
105
+ self.apply(self.param_init_fn)
106
+ self.is_causal = not self.prefix_lm
107
+ self._attn_bias_initialized = False
108
+ self.attn_bias = None
109
+ 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)
110
+ if config.no_bias:
111
+ for module in self.modules():
112
+ if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
113
+ log.info(f'Removing bias from module={module!r}.')
114
+ module.register_parameter('bias', None)
115
+ if hasattr(module, 'use_bias'):
116
+ log.info(f'Setting use_bias=False for module={module!r}.')
117
+ module.use_bias = False
118
+ log.debug(self)
119
+ log.debug(f"Using {self.config.init_config['name']} initialization.")
120
+
121
+ # Initialize weights and apply final processing
122
+ # self.post_init()
123
+
124
+
125
+ def get_input_embeddings(self):
126
+ return self.wte
127
+
128
+
129
+ def set_input_embeddings(self, new_embeddings):
130
+ # self.wte = new_embeddings
131
+ self.wte.weight = new_embeddings
132
+
133
+
134
+ def forward(self, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None,
135
+ attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None,
136
+ sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None,
137
+ output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None,
138
+ inputs_embeds: Optional[torch.Tensor]=None, modality0_emb: Optional[bool] = None,
139
+ modality0_token_id: Optional[bool] = None, modality1_emb: Optional[bool] = None, modality1_token_id: Optional[bool] = None,
140
+ modality2_emb: Optional[bool] = None, modality2_token_id: Optional[bool] = None, modality3_emb: Optional[bool] = None,
141
+ modality3_token_id: Optional[bool] = None,) -> BaseModelOutputWithPast:
142
+
143
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
144
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
145
+ if attention_mask is not None:
146
+ attention_mask = attention_mask.bool()
147
+ if prefix_mask is not None:
148
+ prefix_mask = prefix_mask.bool()
149
+ if not return_dict:
150
+ raise NotImplementedError('return_dict False is not implemented yet for MPT')
151
+ if output_attentions:
152
+ if self.attn_impl != 'torch':
153
+ raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.')
154
+ if self.training and attention_mask is not None and (attention_mask[:, 0].sum() != attention_mask.shape[0]):
155
+ raise NotImplementedError('MPT does not support training with left padding.')
156
+ if self.prefix_lm and prefix_mask is None:
157
+ raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')
158
+ if self.training:
159
+ if self.attn_uses_sequence_id and sequence_id is None:
160
+ 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.')
161
+ elif self.attn_uses_sequence_id is False and sequence_id is not None:
162
+ 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.')
163
+
164
+ ### ADDED FOR P3 - START
165
+
166
+ if modality0_emb is not None:
167
+ modality0_emb = torch.tensor(modality0_emb, dtype=torch.bfloat16)
168
+ hidden_states = self.wte.weight.detach()
169
+
170
+ for layer in self.modality0_embedding_projection:
171
+ modality0_emb = layer(modality0_emb)
172
+ proj_modality0_emb = modality0_emb
173
+
174
+ # Replace the original embedding for the custom token with the custom embedding
175
+ hidden_states[modality0_token_id, :] = torch.mean(torch.squeeze(proj_modality0_emb, 1), dim=0)
176
+ self.set_input_embeddings(torch.nn.Parameter(hidden_states))
177
+
178
+ if modality1_emb is not None:
179
+ modality1_emb = torch.tensor(modality1_emb, dtype=torch.bfloat16)
180
+ hidden_states = self.wte.weight.detach()
181
+
182
+ for layer in self.modality0_embedding_projection:
183
+ modality1_emb = layer(modality1_emb)
184
+ proj_modality1_emb = modality1_emb
185
+
186
+ # Replace the original embedding for the custom token with the custom embedding
187
+ hidden_states[modality1_token_id, :] = torch.mean(torch.squeeze(proj_modality1_emb, 1), dim=0)
188
+ self.set_input_embeddings(torch.nn.Parameter(hidden_states))
189
+
190
+ if modality2_emb is not None:
191
+ modality2_emb = torch.tensor(modality2_emb, dtype=torch.bfloat16)
192
+ hidden_states = self.wte.weight.detach()
193
+
194
+ for layer in self.modality2_embedding_projection:
195
+ modality2_emb = layer(modality2_emb)
196
+ proj_modality2_emb = modality2_emb
197
+
198
+ # Replace the original embedding for the custom token with the custom embedding
199
+ hidden_states[modality2_token_id, :] = torch.mean(torch.squeeze(proj_modality2_emb, 1), dim=0)
200
+ self.set_input_embeddings(torch.nn.Parameter(hidden_states))
201
+
202
+ if modality3_emb is not None:
203
+ modality3_emb = torch.tensor(modality3_emb, dtype=torch.bfloat16)
204
+ hidden_states = self.wte.weight.detach()
205
+
206
+ for layer in self.modality2_embedding_projection:
207
+ modality3_emb = layer(modality3_emb)
208
+ proj_modality3_emb = modality3_emb
209
+
210
+ # Replace the original embedding for the custom token with the custom embedding
211
+ hidden_states[modality3_token_id, :] = torch.mean(torch.squeeze(proj_modality3_emb, 1), dim=0)
212
+ self.set_input_embeddings(torch.nn.Parameter(hidden_states))
213
+
214
+ ### ADDED FOR P3 - END
215
+
216
+ if input_ids is not None and inputs_embeds is not None:
217
+ raise ValueError('You cannot specify both input_ids and inputs_embeds.')
218
+ elif input_ids is not None:
219
+ bsz = input_ids.size(0)
220
+ S = input_ids.size(1)
221
+ x = self.wte(input_ids)
222
+ input_device = input_ids.device
223
+ elif inputs_embeds is not None:
224
+ bsz = inputs_embeds.size(0)
225
+ S = inputs_embeds.size(1)
226
+ x = inputs_embeds
227
+ input_device = inputs_embeds.device
228
+ else:
229
+ raise ValueError('You must specify input_ids or inputs_embeds')
230
+ 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}'
231
+ rotary_emb_w_meta_info = None
232
+ past_position = 0
233
+ if past_key_values is not None:
234
+ if len(past_key_values) != self.config.n_layers:
235
+ 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}).')
236
+ past_position = past_key_values[0][0].size(1)
237
+ if self.attn_impl == 'torch':
238
+ past_position = past_key_values[0][0].size(3)
239
+ if self.learned_pos_emb or self.rope:
240
+ if self.learned_pos_emb and S + past_position > self.config.max_seq_len:
241
+ 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}.')
242
+ if self.learned_pos_emb or (self.rope and self.rope_impl == 'hf'):
243
+ pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_device).unsqueeze(0)
244
+ if attention_mask is not None:
245
+ pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0)
246
+ if self.learned_pos_emb:
247
+ x = x + self.wpe(pos)
248
+ elif self.rope and self.rope_impl == 'hf':
249
+ rotary_emb_w_meta_info = {'impl': self.rope_impl, 'rotary_emb': self.rotary_embedding, 'offset_info': pos, 'seq_len': S + past_position}
250
+ elif self.rope and self.rope_impl == 'dail':
251
+ rotary_emb_w_meta_info = {'impl': self.rope_impl, 'rotary_emb': self.rotary_embedding, 'offset_info': past_position, 'seq_len': S + past_position}
252
+ if self.embedding_fraction == 1:
253
+ x = self.emb_drop(x)
254
+ else:
255
+ x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction)
256
+ assert isinstance(self.emb_drop, nn.Module)
257
+ x = self.emb_drop(x_shrunk)
258
+ (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)
259
+ 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)
260
+ alibi_slopes = None
261
+ if self.alibi and self.attn_impl == 'flash':
262
+ alibi_slopes = gen_slopes(n_heads=self.config.n_heads, alibi_bias_max=self.alibi_bias_max, device=x.device, return_1d=True)
263
+
264
+ presents = () if use_cache else None
265
+ if use_cache and past_key_values is None:
266
+ past_key_values = [() for _ in range(self.config.n_layers)]
267
+ all_hidden_states = () if output_hidden_states else None
268
+ all_self_attns = () if output_attentions else None
269
+ flash_attn_padding_info = {}
270
+ if self.attn_impl == 'flash':
271
+ flash_attn_padding_info = gen_flash_attn_padding_info(bsz, S, past_position, x.device, attention_mask_in_length, attention_mask)
272
+ for (b_idx, block) in enumerate(self.blocks):
273
+ if output_hidden_states:
274
+ assert all_hidden_states is not None
275
+ all_hidden_states = all_hidden_states + (x,)
276
+ past_key_value = past_key_values[b_idx] if past_key_values is not None else None
277
+ (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)
278
+ if presents is not None:
279
+ presents += (present,)
280
+ if output_attentions:
281
+ assert all_self_attns is not None
282
+ all_self_attns = all_self_attns + (attn_weights,)
283
+ x = self.norm_f(x)
284
+ if output_hidden_states:
285
+ assert all_hidden_states is not None
286
+ all_hidden_states = all_hidden_states + (x,)
287
+ return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attns)
288
+
289
+
290
+ class Custom_MPTForCausalLM(MPTForCausalLM):
291
+
292
+ def __init__(self, config: MPTConfig):
293
+ super().__init__(config)
294
+ # log.info(f'Instantiating an MPTForCausalLM model from {__file__}')
295
+ self.transformer: MPTModel = Custom_MptModel(config)
296
+ self.lm_head = None
297
+ if not config.tie_word_embeddings:
298
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False, device=config.init_device)
299
+ self.lm_head._fsdp_wrap = True
300
+ for child in self.transformer.children():
301
+ if isinstance(child, torch.nn.ModuleList):
302
+ continue
303
+ if isinstance(child, torch.nn.Module):
304
+ child._fsdp_wrap = True
305
+ self.logit_scale = None
306
+ if config.logit_scale is not None:
307
+ logit_scale = config.logit_scale
308
+ if isinstance(logit_scale, str):
309
+ if logit_scale == 'inv_sqrt_d_model':
310
+ logit_scale = 1 / math.sqrt(config.d_model)
311
+ else:
312
+ raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
313
+ self.logit_scale = logit_scale
314
+
315
+ def forward(self, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None,
316
+ attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None,
317
+ sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None,
318
+ return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None,
319
+ use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.FloatTensor]=None,
320
+ modality0_emb: Optional[bool] = None, modality0_token_id: Optional[bool] = None,
321
+ modality1_emb: Optional[bool] = None, modality1_token_id: Optional[bool] = None,
322
+ modality2_emb: Optional[bool] = None, modality2_token_id: Optional[bool] = None,
323
+ modality3_emb: Optional[bool] = None, modality3_token_id: Optional[bool] = None) -> CausalLMOutputWithPast:
324
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
325
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
326
+ outputs = self.transformer(
327
+ input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask,
328
+ sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states,
329
+ use_cache=use_cache, inputs_embeds=inputs_embeds,
330
+ modality0_emb=modality0_emb,
331
+ modality0_token_id=modality0_token_id,
332
+ modality1_emb=modality1_emb,
333
+ modality1_token_id=modality1_token_id,
334
+ modality2_emb=modality2_emb,
335
+ modality2_token_id=modality2_token_id,
336
+ modality3_emb=modality3_emb,
337
+ modality3_token_id=modality3_token_id
338
+ )
339
+ if self.lm_head is not None:
340
+ logits = self.lm_head(outputs.last_hidden_state)
341
+ else:
342
+ out = outputs.last_hidden_state
343
+ out = out.to(self.transformer.wte.weight.device)
344
+ logits = self.transformer.wte(out, True)
345
+ if self.logit_scale is not None:
346
+ if self.logit_scale == 0:
347
+ warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
348
+ logits *= self.logit_scale
349
+ loss = None
350
+ if labels is not None:
351
+ _labels = torch.roll(labels, shifts=-1)
352
+ _labels[:, -1] = -100
353
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), _labels.to(logits.device).view(-1))
354
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)