sclincha commited on
Commit
eebc5c6
1 Parent(s): 76659ed

Upload modeling_cocom.py

Browse files
Files changed (1) hide show
  1. modeling_cocom.py +306 -0
modeling_cocom.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, PreTrainedModel, PretrainedConfig, AutoModel
2
+ import torch
3
+ import math
4
+ from peft import get_peft_model, LoraConfig, TaskType
5
+ import os
6
+
7
+ def freeze_model(model):
8
+ for param in model.parameters():
9
+ param.requires_grad = False
10
+
11
+
12
+ class BERT_Compressor(torch.nn.Module):
13
+ def __init__(self, compr_model_name, compr_rate, compr_linear_type, decoder_hidden_size):
14
+ super().__init__()
15
+ # init model
16
+ self.model_name = compr_model_name # base model name of BERT; example: bert-base-ucased
17
+ self.model = AutoModel.from_pretrained(compr_model_name, torch_dtype=torch.bfloat16)
18
+ self.tokenizer = AutoTokenizer.from_pretrained(compr_model_name, use_fast=True)
19
+ self.compr_rate = compr_rate # compression rate
20
+ self.compressing_mode = compr_linear_type # linear layer type, could be either concat or mean.
21
+
22
+ if self.compressing_mode == 'concat': # default setting in paper
23
+ self.linear = torch.nn.Linear(self.model.config.hidden_size*self.compr_rate, decoder_hidden_size)
24
+ elif self.compressing_mode == 'mean':
25
+ self.linear = torch.nn.Linear(self.model.config.hidden_size, decoder_hidden_size)
26
+ self.linear = self.linear.bfloat16()
27
+
28
+ def forward(self, input_ids, attention_mask):
29
+ # compressing context using BERT
30
+ segment_compress_outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, output_hidden_states=True)
31
+ num_embs = math.ceil(input_ids.size(1) / self.compr_rate)
32
+ all_hidden_states_emb = list()
33
+ if self.compressing_mode == 'concat':
34
+ for segment_idx in range(num_embs):
35
+ start_idx = segment_idx * self.compr_rate
36
+ end_idx = (segment_idx + 1) * self.compr_rate
37
+ hidden_state = segment_compress_outputs.hidden_states[-1][:, start_idx:end_idx, :]
38
+ hidden_state_concat = torch.flatten(hidden_state, start_dim=1) #batch_size, hidden_state_dim * compression_rate
39
+ all_hidden_states_emb.append(hidden_state_concat)
40
+ elif self.compressing_mode == "mean":
41
+ for segment_idx in range(num_embs):
42
+ start_idx = segment_idx * self.compr_rate
43
+ end_idx = (segment_idx + 1) * self.compr_rate
44
+ hidden_state = segment_compress_outputs.hidden_states[-1][:, start_idx:end_idx, :]
45
+ # Apply mean pooling to get the final embedding for the segment
46
+ all_hidden_states_emb.append(hidden_state)
47
+ else:
48
+ raise NotImplementedError()
49
+
50
+ all_hidden_states_emb_cat = torch.stack(all_hidden_states_emb, dim=1)
51
+ transformed_embeds = self.linear(all_hidden_states_emb_cat)
52
+
53
+
54
+ if self.compressing_mode == "mean":
55
+ transformed_embeds = torch.mean(transformed_embeds, dim=2)
56
+
57
+ # dimention of transformed_embeds: (batch_size*generation_top_k, num_embs, decoder_hidden_size)
58
+ return transformed_embeds
59
+
60
+ class COCOMConfig(PretrainedConfig):
61
+
62
+ model_type = "COCOM"
63
+ def __init__(self,
64
+ decoder_model_name="meta-llama/Llama-2-7b-chat-hf",
65
+ quantization = 'no',
66
+ generation_top_k = 1,
67
+ sep = False,
68
+ compr_model_name = "bert-base-uncased",
69
+ compr_rate = 64,
70
+ compr_linear_type = 'concat',
71
+ lora = False,
72
+ training_form="both",
73
+ lora_r=16,
74
+ **kwargs):
75
+ super().__init__(**kwargs)
76
+
77
+ self.decoder_model_name = decoder_model_name # model name of decoder
78
+ self.quantization = quantization # quantization, could be no, int4, int8
79
+ self.generation_top_k = generation_top_k # top k for each query, for pretraining, set to 1
80
+ self.sep = sep # boolean type, whether to use sep token
81
+ self.compr_model_name = compr_model_name # model name of compressor
82
+ self.compr_rate = compr_rate # compression rate
83
+ self.compr_linear_type = compr_linear_type # linear layer type, could be either concat or mean
84
+ self.lora = lora # boolean type, whether to use lora trsining
85
+ self.training_form = training_form # training form, could be compressor: training only comprssor; both:
86
+ self.lora_r = lora_r # lora_r for lora training, we use 16 throughout the experiment.
87
+
88
+ class COCOM(PreTrainedModel):
89
+ config_class = COCOMConfig
90
+ def __init__(self, cfg):
91
+ super().__init__(cfg)
92
+ # define models
93
+ # model could be loaded in three quantization modes: no, int4, int8
94
+ if cfg.quantization == "no":
95
+ self.decoder = AutoModelForCausalLM.from_pretrained(
96
+ cfg.decoder_model_name,
97
+ torch_dtype=torch.bfloat16,
98
+ attn_implementation="flash_attention_2",
99
+ low_cpu_mem_usage = True,
100
+ )
101
+ elif cfg.quantization == "int4":
102
+ quant_config = BitsAndBytesConfig(
103
+ load_in_4bit=True,
104
+ bnb_4bit_quant_type='nf4',
105
+ bnb_4bit_compute_dtype='bfloat16',
106
+ low_cpu_mem_usage = True,
107
+ )
108
+ self.decoder = AutoModelForCausalLM.from_pretrained(
109
+ cfg.decoder_model_name,
110
+ quantization_config=quant_config,
111
+ attn_implementation="flash_attention_2",
112
+ torch_dtype=torch.bfloat16,
113
+ resume_download=True,
114
+ low_cpu_mem_usage = True,
115
+ trust_remote_code=True,
116
+ )
117
+ elif cfg.quantization == "int8":
118
+ quant_config = BitsAndBytesConfig(
119
+ load_in_8bit=True,
120
+ llm_int8_enable_fp32_cpu_offload=True,
121
+ bnb_4bit_compute_dtype='bfloat16',
122
+ low_cpu_mem_usage = True,
123
+ )
124
+ self.decoder = AutoModelForCausalLM.from_pretrained(
125
+ cfg.decoder_model_name,
126
+ quantization_config=quant_config,
127
+ attn_implementation="flash_attention_2",
128
+ torch_dtype=torch.bfloat16,
129
+ resume_download=True,
130
+ low_cpu_mem_usage = True,
131
+ trust_remote_code=True,
132
+ )
133
+ else:
134
+ raise NotImplementedError()
135
+
136
+ # when compr_model_name is not set, then means using a decoder-based compressor, otherwise a bert based compressor
137
+ if cfg.compr_model_name is not None:
138
+ # case bert based compressor
139
+ self.compr = BERT_Compressor(cfg.compr_model_name, cfg.compr_rate, cfg.compr_linear_type, self.decoder.config.hidden_size)
140
+ else:
141
+ # case decoder based compressor
142
+ self.compr = None
143
+
144
+ # set lora adaptors
145
+ if cfg.lora:
146
+ peft_config = LoraConfig(
147
+ task_type="CAUSAL_LM",
148
+ r=cfg.lora_r,
149
+ lora_alpha=2* cfg.lora_r,
150
+ target_modules='all-linear',
151
+ lora_dropout=0.1,
152
+ )
153
+ self.decoder = get_peft_model(self.decoder, peft_config)
154
+ self.decoder.print_trainable_parameters()
155
+
156
+ # for training_form=compressor, then freeze the decoder for BERT-based
157
+ self.training_form = cfg.training_form
158
+ if self.training_form == "compressor" and self.compr is not None:
159
+ freeze_model(self.decoder)
160
+
161
+ self.decoder_tokenizer = AutoTokenizer.from_pretrained(cfg.decoder_model_name, use_fast=True, padding_side='left')
162
+
163
+ # define special tokens
164
+ self.decoder_tokenizer.add_special_tokens({'additional_special_tokens': ['<MEM>', '<AE>', '<ENC>', '<SEP>']})
165
+ self.decoder_tokenizer.mem_token = '<MEM>' # Memory token
166
+ self.decoder_tokenizer.ae_token = '<AE>' # token for autoencoding on decoder side
167
+ self.decoder_tokenizer.enc_token = '<ENC>' # token for autoencoding on compressor side
168
+ self.decoder_tokenizer.sep_token = '<SEP>' # sep token between document
169
+
170
+ self.decoder_tokenizer.mem_token_id = self.decoder_tokenizer.convert_tokens_to_ids('<MEM>')
171
+ self.decoder_tokenizer.ae_token_id = self.decoder_tokenizer.convert_tokens_to_ids('<AE>')
172
+ self.decoder_tokenizer.sep_token_id = self.decoder_tokenizer.convert_tokens_to_ids('<SEP>')
173
+ # if pad token ecist then use pad token, othrwise bos token
174
+ if self.decoder_tokenizer.pad_token_id is None:
175
+ self.decoder_tokenizer.pad_token_id = self.decoder_tokenizer.bos_token_id
176
+
177
+ # resize the tokenizer embedding
178
+ self.decoder.resize_token_embeddings(len(self.decoder_tokenizer))
179
+ self.decoder.generation_config.top_p=None
180
+ self.decoder.generation_config.temperature=None
181
+ self.compr_model_name = cfg.compr_model_name
182
+ # other settings
183
+ self.generation_top_k = cfg.generation_top_k
184
+ self.sep = cfg.sep
185
+ self.compr_rate = cfg.compr_rate
186
+ self.local_rank = os.getenv('LOCAL_RANK', '0')
187
+
188
+ def compress_and_replace_emb(self, enc_input_ids, enc_attention_mask, dec_input_ids):
189
+ indices = range(0, enc_input_ids.size(0) + 1, self.generation_top_k)
190
+ if self.compr:
191
+ compressed_embs = self.compr(enc_input_ids, enc_attention_mask)
192
+ input_embeds = self.replace_embeddings(compressed_embs, dec_input_ids, indices)
193
+ else:
194
+ compressed_embs = self.compr_decoder(enc_input_ids, enc_attention_mask)
195
+ input_embeds = self.replace_embeddings(compressed_embs, dec_input_ids, indices)
196
+ return input_embeds
197
+
198
+ def compr_decoder(self, input_ids, attention_mask):
199
+ emb = self.decoder(input_ids=input_ids, attention_mask=attention_mask, output_hidden_states=True).hidden_states[-1]
200
+ mask = input_ids == self.decoder_tokenizer.mem_token_id
201
+ return emb[mask].reshape(emb.size(0), -1, emb.size(-1))
202
+
203
+
204
+ def replace_embeddings(self, compressed_embs, dec_input_ids, indices):
205
+ # Embed the decoder input
206
+ inputs_embeds = self.decoder.get_input_embeddings()(dec_input_ids)
207
+ num_embs = compressed_embs.size(1)
208
+ if self.sep:
209
+ slot_len = num_embs + 1
210
+ else:
211
+ slot_len = num_embs
212
+ # get first mem_token inidices
213
+ first_mem_token_indices = torch.argmax((dec_input_ids == self.decoder_tokenizer.mem_token_id).int(), dim=1)
214
+ batch_size = inputs_embeds.size(0)
215
+ # for each example in batch, replace them with compressed embeddings
216
+ for i in range(batch_size):
217
+ for j in range(indices[i], indices[i + 1]):
218
+ start_idx = first_mem_token_indices[i].item() + (j-indices[i]) * slot_len
219
+ inputs_embeds[i, start_idx:start_idx + num_embs, :] = compressed_embs[j]
220
+ return inputs_embeds
221
+
222
+
223
+ def forward(self,
224
+ enc_input_ids: torch.LongTensor = None,
225
+ enc_attention_mask: torch.LongTensor = None,
226
+ dec_input_ids: torch.LongTensor = None,
227
+ dec_attention_mask: torch.LongTensor = None,
228
+ labels: torch.LongTensor = None):
229
+
230
+ # enc_input_ids: stores the contexts, should be flattened from all queries before input, dimention (batch_size*generation_top_k, token_length)
231
+ # enc_attention_mask: attention mask of enc_input_ids
232
+ # dec_input_ids: stores the prompts (including mem tokens), dimention (batch_size, token_length)
233
+ # dec_attention_mask: attention mask of dec_input_ids
234
+
235
+ # Perform compression with gradient tracking
236
+ inputs_embeds = self.compress_and_replace_emb(enc_input_ids, enc_attention_mask, dec_input_ids)
237
+
238
+ # if training_form is compressor, then detach the inputs_embeds, to make gradient not count in decoder
239
+ if (self.training_form == "compressor") and (self.compr is None):
240
+ inputs_embeds = inputs_embeds.detach()
241
+
242
+ # decoding
243
+ decoder_outputs = self.decoder(inputs_embeds=inputs_embeds, attention_mask=dec_attention_mask, labels=labels)
244
+
245
+ return {"loss": decoder_outputs.loss, "logits": decoder_outputs.logits}
246
+
247
+
248
+
249
+ def generate(self, model_input, max_new_tokens=128):
250
+ device = self.decoder.device
251
+ enc_input_ids, enc_attention_mask, dec_input_ids, dec_attention_mask = model_input['enc_input_ids'], model_input['enc_attention_mask'], model_input['dec_input_ids'], model_input['dec_attention_mask']
252
+ inputs_embeds = self.compress_and_replace_emb(enc_input_ids.to(device), enc_attention_mask.to(device), dec_input_ids.to(device))
253
+ output_ids = self.decoder.generate(
254
+ inputs_embeds=inputs_embeds.to(device),
255
+ attention_mask=dec_attention_mask.to(device),
256
+ do_sample=False,
257
+ top_p=None,
258
+ max_new_tokens=max_new_tokens
259
+ )
260
+ decoded = self.decoder_tokenizer.batch_decode(output_ids, skip_special_tokens=True)
261
+ return decoded
262
+
263
+ def generate_from_text(self, contexts, questions, max_new_tokens=128):
264
+ # for each question in list give input a list of contexts of equal length
265
+ # first make sure that every list in contexts are having the same length
266
+ assert len(contexts) == len(questions)
267
+ assert all([len(context) == len(contexts[0]) for context in contexts])
268
+
269
+ # prepare inp_enc for compression
270
+ # first flatten the contexts
271
+ self.generation_top_k = len(contexts[0])
272
+ flat_contexts = sum(contexts, [])
273
+ #tokenize the contexts, depending if compr exist or not
274
+ if self.compr is not None:
275
+ enc_input = self.compr.tokenizer(flat_contexts, padding=True, truncation=True, return_tensors='pt', pad_to_multiple_of=self.compr_rate)
276
+ num_mem_tokens = math.ceil(enc_input['input_ids'].size(1) / self.compr_rate)
277
+ else:
278
+ # first need to add special token in flat_contexts
279
+ flat_contexts = [self.decoder_tokenizer.enc_token + self.decoder_tokenizer.bos_token + context + self.decoder_tokenizer.bos_token for context in flat_contexts]
280
+ enc_input = self.decoder_tokenizer(flat_contexts, truncation=True, return_tensors='pt', padding="longest")
281
+ num_mem_tokens = math.ceil((enc_input['input_ids'].size(1)-3) / self.compr_rate)
282
+ mem_tokens = torch.full((enc_input['input_ids'].size(0), num_mem_tokens), self.decoder_tokenizer.mem_token_id, dtype=torch.long)
283
+ enc_input['input_ids'] = torch.cat([mem_tokens, enc_input['input_ids']], dim=1)
284
+ enc_input['attention_mask'] = torch.cat([torch.ones_like(mem_tokens), enc_input['attention_mask']], dim=1)
285
+
286
+
287
+ # prepare inp_dec
288
+ mem_tokens = self.decoder_tokenizer.mem_token * num_mem_tokens
289
+ if self.sep:
290
+ mem_tokens += self.decoder_tokenizer.sep_token
291
+
292
+ instr = [self.decoder_tokenizer.bos_token + mem_tokens* self.generation_top_k + '[INST]' + question + '\n[/INST]\n' for question in questions]
293
+ inp_dec = self.decoder_tokenizer(instr, truncation=True, return_tensors='pt', padding="longest")
294
+
295
+ # generate
296
+ model_input = {
297
+ 'enc_input_ids': enc_input['input_ids'],
298
+ 'enc_attention_mask': enc_input['attention_mask'],
299
+ 'dec_input_ids': inp_dec['input_ids'],
300
+ 'dec_attention_mask': inp_dec['attention_mask']
301
+ }
302
+
303
+ return self.generate(model_input, max_new_tokens)
304
+
305
+
306
+