ubuntu commited on
Commit
bbd6d64
·
1 Parent(s): 30cba57

first version

Browse files
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/workspace/Embedding/SimCSE/shenxiangyang_bert_3",
3
+ "architectures": [
4
+ "BertForCL"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "bos_token_id": 0,
8
+ "classifier_dropout": null,
9
+ "directionality": "bidi",
10
+ "eos_token_id": 2,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout_prob": 0.1,
13
+ "hidden_size": 768,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 3072,
16
+ "layer_norm_eps": 1e-12,
17
+ "max_position_embeddings": 512,
18
+ "model_type": "bert",
19
+ "num_attention_heads": 12,
20
+ "num_hidden_layers": 12,
21
+ "output_past": true,
22
+ "pad_token_id": 0,
23
+ "pooler_fc_size": 768,
24
+ "pooler_num_attention_heads": 12,
25
+ "pooler_num_fc_layers": 3,
26
+ "pooler_size_per_head": 128,
27
+ "pooler_type": "first_token_transform",
28
+ "position_embedding_type": "absolute",
29
+ "torch_dtype": "float32",
30
+ "transformers_version": "4.27.1",
31
+ "type_vocab_size": 2,
32
+ "use_cache": true,
33
+ "vocab_size": 21128,
34
+ "auto_map": {
35
+ "AutoModel": "models.BertForCL"
36
+ }
37
+ }
models.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import torch.distributed as dist
5
+
6
+ # from simcse.modeling_glm import GLMModel, GLMPreTrainedModel
7
+
8
+ # import simcse.readEmbeddings
9
+ # import simcse.mse_loss
10
+
11
+ import transformers
12
+ from transformers import RobertaTokenizer, AutoModel, PreTrainedModel
13
+ from transformers.models.roberta.modeling_roberta import RobertaPreTrainedModel, RobertaModel, RobertaLMHead
14
+ from transformers.models.bert.modeling_bert import BertPreTrainedModel, BertModel, BertLMPredictionHead
15
+ from transformers.activations import gelu
16
+ from transformers.file_utils import (
17
+ add_code_sample_docstrings,
18
+ add_start_docstrings,
19
+ add_start_docstrings_to_model_forward,
20
+ replace_return_docstrings,
21
+ )
22
+ from transformers.modeling_outputs import SequenceClassifierOutput, BaseModelOutputWithPoolingAndCrossAttentions
23
+
24
+ glm_model = None
25
+
26
+ def init_glm(path):
27
+ global glm_model
28
+ glm_model = AutoModel.from_pretrained(path, trust_remote_code=True).to("cuda:0")
29
+ for param in glm_model.parameters():
30
+ param.requires_grad = False
31
+
32
+
33
+
34
+ class MLPLayer(nn.Module):
35
+ """
36
+ Head for getting sentence representations over RoBERTa/BERT's CLS representation.
37
+ """
38
+
39
+ def __init__(self, config):
40
+ super().__init__()
41
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
42
+ # 1536
43
+ self.fc = nn.Linear(config.hidden_size, 1536)
44
+ self.activation = nn.Tanh()
45
+
46
+ def forward(self, features, **kwargs):
47
+ x = self.dense(features)
48
+ x = self.fc(x)
49
+ x = self.activation(x)
50
+
51
+ return x
52
+
53
+ class Similarity(nn.Module):
54
+ """
55
+ Dot product or cosine similarity
56
+ """
57
+
58
+ def __init__(self, temp):
59
+ super().__init__()
60
+ self.temp = temp
61
+ self.cos = nn.CosineSimilarity(dim=-1)
62
+
63
+ def forward(self, x, y):
64
+ return self.cos(x, y) / self.temp
65
+
66
+
67
+ class Pooler(nn.Module):
68
+ """
69
+ Parameter-free poolers to get the sentence embedding
70
+ 'cls': [CLS] representation with BERT/RoBERTa's MLP pooler.
71
+ 'cls_before_pooler': [CLS] representation without the original MLP pooler.
72
+ 'avg': average of the last layers' hidden states at each token.
73
+ 'avg_top2': average of the last two layers.
74
+ 'avg_first_last': average of the first and the last layers.
75
+ """
76
+
77
+ def __init__(self, pooler_type):
78
+ super().__init__()
79
+ self.pooler_type = pooler_type
80
+ assert self.pooler_type in ["cls", "cls_before_pooler", "avg", "avg_top2",
81
+ "avg_first_last"], "unrecognized pooling type %s" % self.pooler_type
82
+
83
+ def forward(self, attention_mask, outputs):
84
+ last_hidden = outputs.last_hidden_state
85
+ # pooler_output = outputs.pooler_output
86
+ hidden_states = outputs.hidden_states
87
+
88
+ if self.pooler_type in ['cls_before_pooler', 'cls']:
89
+ return last_hidden[:, 0]
90
+ elif self.pooler_type == "avg":
91
+ return ((last_hidden * attention_mask.unsqueeze(-1)).sum(1) / attention_mask.sum(-1).unsqueeze(-1))
92
+ elif self.pooler_type == "avg_first_last":
93
+ first_hidden = hidden_states[1]
94
+ last_hidden = hidden_states[-1]
95
+ pooled_result = ((first_hidden + last_hidden) / 2.0 * attention_mask.unsqueeze(-1)).sum(
96
+ 1) / attention_mask.sum(-1).unsqueeze(-1)
97
+ return pooled_result
98
+ elif self.pooler_type == "avg_top2":
99
+ second_last_hidden = hidden_states[-2]
100
+ last_hidden = hidden_states[-1]
101
+ pooled_result = ((last_hidden + second_last_hidden) / 2.0 * attention_mask.unsqueeze(-1)).sum(
102
+ 1) / attention_mask.sum(-1).unsqueeze(-1)
103
+ return pooled_result
104
+ else:
105
+ raise NotImplementedError
106
+
107
+
108
+ def cl_init(cls, config):
109
+ """
110
+ Contrastive learning class init function.
111
+ """
112
+ cls.pooler_type = cls.model_args.pooler_type
113
+ cls.pooler = Pooler(cls.model_args.pooler_type)
114
+ if cls.model_args.pooler_type == "cls":
115
+ cls.mlp = MLPLayer(config)
116
+ cls.sim = Similarity(temp=cls.model_args.temp)
117
+ cls.init_weights()
118
+
119
+
120
+ def cl_forward(cls,
121
+ encoder,
122
+ input_ids=None,
123
+ attention_mask=None,
124
+ token_type_ids=None,
125
+ position_ids=None,
126
+ head_mask=None,
127
+ inputs_embeds=None,
128
+ labels=None,
129
+ output_attentions=None,
130
+ output_hidden_states=None,
131
+ return_dict=None,
132
+ mlm_input_ids=None,
133
+ mlm_labels=None,
134
+ ):
135
+ return_dict = return_dict if return_dict is not None else cls.config.use_return_dict
136
+ ori_input_ids = input_ids
137
+ batch_size = input_ids.size(0)
138
+ # Number of sentences in one instance
139
+ # 2: pair instance; 3: pair instance with a hard negative
140
+ num_sent = input_ids.size(1)
141
+
142
+ mlm_outputs = None
143
+ # Flatten input for encoding
144
+ input_ids = input_ids.view((-1, input_ids.size(-1))) # (bs * num_sent, len)
145
+ attention_mask = attention_mask.view((-1, attention_mask.size(-1))) # (bs * num_sent len)
146
+ if token_type_ids is not None:
147
+ token_type_ids = token_type_ids.view((-1, token_type_ids.size(-1))) # (bs * num_sent, len)
148
+
149
+ if inputs_embeds is not None:
150
+ input_ids = None
151
+
152
+ # Get raw embeddings
153
+ outputs = encoder(
154
+ input_ids,
155
+ attention_mask=attention_mask,
156
+ token_type_ids=token_type_ids,
157
+ position_ids=position_ids,
158
+ head_mask=head_mask,
159
+ inputs_embeds=inputs_embeds,
160
+ output_attentions=output_attentions,
161
+ output_hidden_states=True if cls.model_args.pooler_type in ['avg_top2', 'avg_first_last'] else False,
162
+ return_dict=True,
163
+ )
164
+
165
+ # MLM auxiliary objective
166
+ if mlm_input_ids is not None:
167
+ mlm_input_ids = mlm_input_ids.view((-1, mlm_input_ids.size(-1)))
168
+ mlm_outputs = encoder(
169
+ mlm_input_ids,
170
+ attention_mask=attention_mask,
171
+ token_type_ids=token_type_ids,
172
+ position_ids=position_ids,
173
+ head_mask=head_mask,
174
+ inputs_embeds=inputs_embeds,
175
+ output_attentions=output_attentions,
176
+ output_hidden_states=True if cls.model_args.pooler_type in ['avg_top2', 'avg_first_last'] else False,
177
+ return_dict=True,
178
+ )
179
+
180
+ # Pooling
181
+ pooler_output = cls.pooler(attention_mask, outputs)
182
+ pooler_output = pooler_output.view((batch_size, num_sent, pooler_output.size(-1))) # (bs, num_sent, hidden)
183
+ # If using "cls", we add an extra MLP layer
184
+ # (same as BERT's original implementation) over the representation.
185
+ if cls.pooler_type == "cls":
186
+ # print("this pooler is cls and running mlp")
187
+ pooler_output = cls.mlp(pooler_output)
188
+
189
+ # Separate representation
190
+ z1, z2 = pooler_output[:, 0], pooler_output[:, 1]
191
+
192
+ # simcse.mse_loss.global_num += 8
193
+ # print(simcse.mse_loss.global_num)
194
+ tensor_left, tensor_right = simcse.mse_loss.giveMeBatchEmbeddings(simcse.mse_loss.global_num,
195
+ simcse.readEmbeddings.data)
196
+ simcse.mse_loss.global_num += 32
197
+ # print(F.mse_loss(z1,tensor_left))
198
+ # print(F.mse_loss(z2,tensor_right))
199
+
200
+ # print(tensor_left.size())
201
+ # print(tensor_right.size())
202
+ # print(len(pooler_output[:,]))
203
+ # print(len(z1))
204
+ # print(len(z2))
205
+ # print(len(z1[0]))
206
+ # print(len(z2[0]))
207
+
208
+ # print(F.mse_loss(z1[0], z2[0]))
209
+
210
+ # Hard negative
211
+ if num_sent == 3:
212
+ z3 = pooler_output[:, 2]
213
+
214
+ # Gather all embeddings if using distributed training
215
+ if dist.is_initialized() and cls.training:
216
+ # Gather hard negative
217
+ if num_sent >= 3:
218
+ z3_list = [torch.zeros_like(z3) for _ in range(dist.get_world_size())]
219
+ dist.all_gather(tensor_list=z3_list, tensor=z3.contiguous())
220
+ z3_list[dist.get_rank()] = z3
221
+ z3 = torch.cat(z3_list, 0)
222
+
223
+ # Dummy vectors for allgather
224
+ z1_list = [torch.zeros_like(z1) for _ in range(dist.get_world_size())]
225
+ z2_list = [torch.zeros_like(z2) for _ in range(dist.get_world_size())]
226
+ # Allgather
227
+ dist.all_gather(tensor_list=z1_list, tensor=z1.contiguous())
228
+ dist.all_gather(tensor_list=z2_list, tensor=z2.contiguous())
229
+
230
+ # Since allgather results do not have gradients, we replace the
231
+ # current process's corresponding embeddings with original tensors
232
+ z1_list[dist.get_rank()] = z1
233
+ z2_list[dist.get_rank()] = z2
234
+ # Get full batch embeddings: (bs x N, hidden)
235
+ z1 = torch.cat(z1_list, 0)
236
+ z2 = torch.cat(z2_list, 0)
237
+
238
+ ziang_loss = F.mse_loss(z1, tensor_left) + F.mse_loss(z2, tensor_right)
239
+ # print("\n MSE Loss is : ", ziang_loss)
240
+
241
+ softmax_row, softmax_col = simcse.mse_loss.giveMeMatrix(tensor_left, tensor_right)
242
+ softmax_row_model, softmax_col_model = simcse.mse_loss.giveMeMatrix(z1,z2)
243
+
244
+ ziang_labels = torch.tensor([i for i in range(32)], device='cuda:0')
245
+
246
+ """
247
+ this is cross entropy loss
248
+ """
249
+ row_loss = F.cross_entropy(softmax_row, ziang_labels)
250
+ col_loss = F.cross_entropy(softmax_col, ziang_labels)
251
+ softmax_loss = (row_loss + col_loss) / 2
252
+
253
+ """
254
+ this is KL div loss
255
+ """
256
+ KL_row_loss = F.kl_div(softmax_row_model.log(), softmax_row, reduction='batchmean')
257
+ KL_col_loss = F.kl_div(softmax_col_model.log(), softmax_col, reduction='batchmean')
258
+ KL_loss = (KL_row_loss + KL_col_loss) / 2
259
+
260
+ ziang_loss = KL_loss + ziang_loss + softmax_loss
261
+ # ziang_loss = softmax_loss + ziang_loss
262
+
263
+ # ziang_loss = F.mse_loss(
264
+ # torch.nn.functional.cosine_similarity(tensor_left, tensor_right),
265
+ # torch.nn.functional.cosine_similarity(z1,z2)
266
+ # )
267
+ # ziang_loss /= 0.5
268
+ # print("\n Softmax Loss is : ", softmax_loss)
269
+ # print("\n Openai Cos Similarity between two paragraph: \n", torch.nn.functional.cosine_similarity(tensor_left, tensor_right))
270
+ # print("\nCos Similarity between two paragraph: \n", torch.nn.functional.cosine_similarity(z1, z2))
271
+ # print("\n My total loss currently: ", ziang_loss)
272
+
273
+ # print(z1.size())
274
+ # print(z2.size())
275
+
276
+ cos_sim = cls.sim(z1.unsqueeze(1), z2.unsqueeze(0))
277
+
278
+ # Hard negative
279
+ if num_sent >= 3:
280
+ z1_z3_cos = cls.sim(z1.unsqueeze(1), z3.unsqueeze(0))
281
+ cos_sim = torch.cat([cos_sim, z1_z3_cos], 1)
282
+
283
+ labels = torch.arange(cos_sim.size(0)).long().to(cls.device)
284
+ loss_fct = nn.CrossEntropyLoss()
285
+
286
+ # Calculate loss with hard negatives
287
+ if num_sent == 3:
288
+ # Note that weights are actually logits of weights
289
+ z3_weight = cls.model_args.hard_negative_weight
290
+ weights = torch.tensor(
291
+ [[0.0] * (cos_sim.size(-1) - z1_z3_cos.size(-1)) + [0.0] * i + [z3_weight] + [0.0] * (
292
+ z1_z3_cos.size(-1) - i - 1) for i in range(z1_z3_cos.size(-1))]
293
+ ).to(cls.device)
294
+ cos_sim = cos_sim + weights
295
+
296
+ loss = loss_fct(cos_sim, labels)
297
+
298
+ # Calculate loss for MLM
299
+ if mlm_outputs is not None and mlm_labels is not None:
300
+ mlm_labels = mlm_labels.view(-1, mlm_labels.size(-1))
301
+ prediction_scores = cls.lm_head(mlm_outputs.last_hidden_state)
302
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, cls.config.vocab_size), mlm_labels.view(-1))
303
+ loss = loss + cls.model_args.mlm_weight * masked_lm_loss
304
+
305
+ if not return_dict:
306
+ output = (cos_sim,) + outputs[2:]
307
+ return ((loss,) + output) if loss is not None else output
308
+
309
+ # print("original " , loss)
310
+
311
+ return SequenceClassifierOutput(
312
+ # loss=loss,
313
+ loss=ziang_loss,
314
+ logits=cos_sim,
315
+ hidden_states=outputs.hidden_states,
316
+ # attentions=outputs.attentions,
317
+ )
318
+
319
+
320
+ def sentemb_forward(
321
+ cls,
322
+ encoder,
323
+ input_ids=None,
324
+ attention_mask=None,
325
+ token_type_ids=None,
326
+ position_ids=None,
327
+ head_mask=None,
328
+ inputs_embeds=None,
329
+ labels=None,
330
+ output_attentions=None,
331
+ output_hidden_states=None,
332
+ return_dict=None,
333
+ ):
334
+ return_dict = return_dict if return_dict is not None else cls.config.use_return_dict
335
+
336
+ if inputs_embeds is not None:
337
+ input_ids = None
338
+
339
+ outputs = encoder(
340
+ input_ids,
341
+ attention_mask=attention_mask,
342
+ token_type_ids=token_type_ids,
343
+ position_ids=position_ids,
344
+ head_mask=head_mask,
345
+ inputs_embeds=inputs_embeds,
346
+ output_attentions=output_attentions,
347
+ output_hidden_states=True if cls.pooler_type in ['avg_top2', 'avg_first_last'] else False,
348
+ return_dict=True,
349
+ )
350
+
351
+ pooler_output = cls.pooler(attention_mask, outputs)
352
+ if cls.pooler_type == "cls" and not cls.model_args.mlp_only_train:
353
+ pooler_output = cls.mlp(pooler_output)
354
+
355
+ if not return_dict:
356
+ return (outputs[0], pooler_output) + outputs[2:]
357
+
358
+ return BaseModelOutputWithPoolingAndCrossAttentions(
359
+ pooler_output=pooler_output,
360
+ last_hidden_state=outputs.last_hidden_state,
361
+ hidden_states=outputs.hidden_states,
362
+ )
363
+
364
+
365
+ class BertForCL(BertPreTrainedModel):
366
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
367
+
368
+ def __init__(self, config, *model_args, **model_kargs):
369
+ super().__init__(config)
370
+ self.model_args = model_kargs["model_args"]
371
+ self.bert = BertModel(config, add_pooling_layer=False)
372
+
373
+ if self.model_args.do_mlm:
374
+ self.lm_head = BertLMPredictionHead(config)
375
+
376
+ if self.model_args.init_embeddings_model:
377
+ if "glm" in self.model_args.init_embeddings_model:
378
+ init_glm(self.model_args.init_embeddings_model)
379
+ self.fc = nn.Linear(glm_model.config.hidden_size, config.hidden_size)
380
+ else:
381
+ raise NotImplementedError
382
+
383
+ cl_init(self, config)
384
+
385
+ def forward(self,
386
+ input_ids=None,
387
+ attention_mask=None,
388
+ token_type_ids=None,
389
+ position_ids=None,
390
+ head_mask=None,
391
+ inputs_embeds=None,
392
+ labels=None,
393
+ output_attentions=None,
394
+ output_hidden_states=None,
395
+ return_dict=None,
396
+ sent_emb=False,
397
+ mlm_input_ids=None,
398
+ mlm_labels=None,
399
+ ):
400
+ if self.model_args.init_embeddings_model:
401
+ input_ids_for_glm = input_ids.view((-1, input_ids.size(-1))) # (bs * num_sent, len)
402
+ attention_mask_for_glm = attention_mask.view((-1, attention_mask.size(-1))) # (bs * num_sent len)
403
+ if token_type_ids is not None:
404
+ token_type_ids_for_glm = token_type_ids.view((-1, token_type_ids.size(-1))) # (bs * num_sent, len)
405
+
406
+ outputs_from_glm = glm_model(input_ids_for_glm,
407
+ attention_mask=attention_mask_for_glm,
408
+ token_type_ids=token_type_ids_for_glm,
409
+ position_ids=position_ids,
410
+ head_mask=head_mask,
411
+ inputs_embeds=inputs_embeds,
412
+ labels=labels,
413
+ output_attentions=output_attentions,
414
+ output_hidden_states=output_hidden_states,
415
+ return_dict=return_dict,
416
+ )
417
+
418
+ inputs_embeds = self.fc(outputs_from_glm.last_hidden_state)
419
+
420
+ if sent_emb:
421
+ return sentemb_forward(self, self.bert,
422
+ input_ids=input_ids,
423
+ attention_mask=attention_mask,
424
+ token_type_ids=token_type_ids,
425
+ position_ids=position_ids,
426
+ head_mask=head_mask,
427
+ inputs_embeds=inputs_embeds,
428
+ labels=labels,
429
+ output_attentions=output_attentions,
430
+ output_hidden_states=output_hidden_states,
431
+ return_dict=return_dict,
432
+ )
433
+ else:
434
+ return cl_forward(self, self.bert,
435
+ input_ids=input_ids,
436
+ attention_mask=attention_mask,
437
+ token_type_ids=token_type_ids,
438
+ position_ids=position_ids,
439
+ head_mask=head_mask,
440
+ inputs_embeds=inputs_embeds,
441
+ labels=labels,
442
+ output_attentions=output_attentions,
443
+ output_hidden_states=output_hidden_states,
444
+ return_dict=return_dict,
445
+ mlm_input_ids=mlm_input_ids,
446
+ mlm_labels=mlm_labels,
447
+ )
448
+
449
+
450
+ class RobertaForCL(RobertaPreTrainedModel):
451
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
452
+
453
+ def __init__(self, config, *model_args, **model_kargs):
454
+ super().__init__(config)
455
+ self.model_args = model_kargs["model_args"]
456
+ self.roberta = RobertaModel(config, add_pooling_layer=False)
457
+
458
+ if self.model_args.do_mlm:
459
+ self.lm_head = RobertaLMHead(config)
460
+
461
+ if self.model_args.init_embeddings_model:
462
+ if "glm" in self.model_args.init_embeddings_model:
463
+ init_glm(self.model_args.init_embeddings_model)
464
+ self.fc = nn.Linear(glm_model.config.hidden_size, config.hidden_size)
465
+ else:
466
+ raise NotImplementedError
467
+
468
+ cl_init(self, config)
469
+
470
+ def forward(self,
471
+ input_ids=None,
472
+ attention_mask=None,
473
+ token_type_ids=None,
474
+ position_ids=None,
475
+ head_mask=None,
476
+ inputs_embeds=None,
477
+ labels=None,
478
+ output_attentions=None,
479
+ output_hidden_states=None,
480
+ return_dict=None,
481
+ sent_emb=False,
482
+ mlm_input_ids=None,
483
+ mlm_labels=None,
484
+ ):
485
+
486
+ if self.model_args.init_embeddings_model and not sent_emb:
487
+ input_ids_for_glm = input_ids.view((-1, input_ids.size(-1))) # (bs * num_sent, len)
488
+ attention_mask_for_glm = attention_mask.view((-1, attention_mask.size(-1))) # (bs * num_sent len)
489
+ if token_type_ids is not None:
490
+ token_type_ids_for_glm = token_type_ids.view((-1, token_type_ids.size(-1))) # (bs * num_sent, len)
491
+
492
+ outputs_from_glm = glm_model(input_ids_for_glm,
493
+ attention_mask=attention_mask_for_glm,
494
+ token_type_ids=token_type_ids_for_glm,
495
+ position_ids=position_ids,
496
+ head_mask=head_mask,
497
+ inputs_embeds=inputs_embeds,
498
+ labels=labels,
499
+ output_attentions=output_attentions,
500
+ output_hidden_states=output_hidden_states,
501
+ return_dict=return_dict,
502
+ )
503
+
504
+ inputs_embeds = self.fc(outputs_from_glm.last_hidden_state)
505
+
506
+ if sent_emb:
507
+ return sentemb_forward(self, self.roberta,
508
+ input_ids=input_ids,
509
+ attention_mask=attention_mask,
510
+ token_type_ids=token_type_ids,
511
+ position_ids=position_ids,
512
+ head_mask=head_mask,
513
+ inputs_embeds=inputs_embeds,
514
+ labels=labels,
515
+ output_attentions=output_attentions,
516
+ output_hidden_states=output_hidden_states,
517
+ return_dict=return_dict,
518
+ )
519
+ else:
520
+ return cl_forward(self, self.roberta,
521
+ input_ids=input_ids,
522
+ attention_mask=attention_mask,
523
+ token_type_ids=token_type_ids,
524
+ position_ids=position_ids,
525
+ head_mask=head_mask,
526
+ inputs_embeds=inputs_embeds,
527
+ labels=labels,
528
+ output_attentions=output_attentions,
529
+ output_hidden_states=output_hidden_states,
530
+ return_dict=return_dict,
531
+ mlm_input_ids=mlm_input_ids,
532
+ mlm_labels=mlm_labels,
533
+ )
534
+
optimizer.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e01f5b79c18202de4a4eeb6f5ada1401c2db48d1450487b9ffdf040a704c8d7b
3
+ size 827708549
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a0a82772934eb24055fc3af28176176f17c78180f6c72309bc05177ef4231be7
3
+ size 413868149
scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f65d514eaec6c76c6ec10a1783c783b393dbd61b5def51de7a17365db021f302
3
+ size 627
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "do_basic_tokenize": true,
4
+ "do_lower_case": true,
5
+ "mask_token": "[MASK]",
6
+ "model_max_length": 1000000000000000019884624838656,
7
+ "never_split": null,
8
+ "pad_token": "[PAD]",
9
+ "sep_token": "[SEP]",
10
+ "special_tokens_map_file": "/home/chenweifeng/.cache/huggingface/hub/models--hfl--chinese-roberta-wwm-ext/snapshots/5c58d0b8ec1d9014354d691c538661bf00bfdb44/special_tokens_map.json",
11
+ "strip_accents": null,
12
+ "tokenize_chinese_chars": true,
13
+ "tokenizer_class": "BertTokenizer",
14
+ "unk_token": "[UNK]"
15
+ }
trainer_state.json ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 0.9549795361527967,
5
+ "global_step": 7000,
6
+ "is_hyper_param_search": false,
7
+ "is_local_process_zero": true,
8
+ "is_world_process_zero": true,
9
+ "log_history": [
10
+ {
11
+ "epoch": 0.07,
12
+ "learning_rate": 2.795361527967258e-05,
13
+ "loss": 3.4231,
14
+ "step": 500
15
+ },
16
+ {
17
+ "epoch": 0.14,
18
+ "learning_rate": 2.5907230559345156e-05,
19
+ "loss": 3.423,
20
+ "step": 1000
21
+ },
22
+ {
23
+ "epoch": 0.14,
24
+ "eval_stsb_spearman": 0.4829721958511661,
25
+ "step": 1000
26
+ },
27
+ {
28
+ "epoch": 0.2,
29
+ "learning_rate": 2.386084583901774e-05,
30
+ "loss": 3.4229,
31
+ "step": 1500
32
+ },
33
+ {
34
+ "epoch": 0.27,
35
+ "learning_rate": 2.1814461118690315e-05,
36
+ "loss": 3.4229,
37
+ "step": 2000
38
+ },
39
+ {
40
+ "epoch": 0.27,
41
+ "eval_stsb_spearman": 0.5840087248870882,
42
+ "step": 2000
43
+ },
44
+ {
45
+ "epoch": 0.34,
46
+ "learning_rate": 1.9768076398362894e-05,
47
+ "loss": 3.4229,
48
+ "step": 2500
49
+ },
50
+ {
51
+ "epoch": 0.41,
52
+ "learning_rate": 1.772169167803547e-05,
53
+ "loss": 3.4229,
54
+ "step": 3000
55
+ },
56
+ {
57
+ "epoch": 0.41,
58
+ "eval_stsb_spearman": 0.6250461828473922,
59
+ "step": 3000
60
+ },
61
+ {
62
+ "epoch": 0.48,
63
+ "learning_rate": 1.567530695770805e-05,
64
+ "loss": 3.4229,
65
+ "step": 3500
66
+ },
67
+ {
68
+ "epoch": 0.55,
69
+ "learning_rate": 1.3628922237380627e-05,
70
+ "loss": 3.4229,
71
+ "step": 4000
72
+ },
73
+ {
74
+ "epoch": 0.55,
75
+ "eval_stsb_spearman": 0.656661075878988,
76
+ "step": 4000
77
+ },
78
+ {
79
+ "epoch": 0.61,
80
+ "learning_rate": 1.1582537517053206e-05,
81
+ "loss": 3.4229,
82
+ "step": 4500
83
+ },
84
+ {
85
+ "epoch": 0.68,
86
+ "learning_rate": 9.536152796725784e-06,
87
+ "loss": 3.4228,
88
+ "step": 5000
89
+ },
90
+ {
91
+ "epoch": 0.68,
92
+ "eval_stsb_spearman": 0.6699952089868008,
93
+ "step": 5000
94
+ },
95
+ {
96
+ "epoch": 0.75,
97
+ "learning_rate": 7.489768076398363e-06,
98
+ "loss": 3.4229,
99
+ "step": 5500
100
+ },
101
+ {
102
+ "epoch": 0.82,
103
+ "learning_rate": 5.443383356070941e-06,
104
+ "loss": 3.4228,
105
+ "step": 6000
106
+ },
107
+ {
108
+ "epoch": 0.82,
109
+ "eval_stsb_spearman": 0.6815928788452451,
110
+ "step": 6000
111
+ },
112
+ {
113
+ "epoch": 0.89,
114
+ "learning_rate": 3.39699863574352e-06,
115
+ "loss": 3.4228,
116
+ "step": 6500
117
+ },
118
+ {
119
+ "epoch": 0.95,
120
+ "learning_rate": 1.3506139154160984e-06,
121
+ "loss": 3.4229,
122
+ "step": 7000
123
+ },
124
+ {
125
+ "epoch": 0.95,
126
+ "eval_stsb_spearman": 0.6869918326406103,
127
+ "step": 7000
128
+ },
129
+ {
130
+ "epoch": 0.07,
131
+ "learning_rate": 0.0,
132
+ "loss": 0.0002,
133
+ "step": 500
134
+ },
135
+ {
136
+ "epoch": 0.14,
137
+ "learning_rate": 0.0,
138
+ "loss": 0.0002,
139
+ "step": 1000
140
+ },
141
+ {
142
+ "epoch": 0.14,
143
+ "eval_stsb_spearman": 0.6832701515366976,
144
+ "step": 1000
145
+ },
146
+ {
147
+ "epoch": 0.2,
148
+ "learning_rate": 0.0,
149
+ "loss": 0.0002,
150
+ "step": 1500
151
+ },
152
+ {
153
+ "epoch": 0.27,
154
+ "learning_rate": 0.0,
155
+ "loss": 0.0002,
156
+ "step": 2000
157
+ },
158
+ {
159
+ "epoch": 0.27,
160
+ "eval_stsb_spearman": 0.6832701515366976,
161
+ "step": 2000
162
+ },
163
+ {
164
+ "epoch": 0.34,
165
+ "learning_rate": 0.0,
166
+ "loss": 0.0002,
167
+ "step": 2500
168
+ },
169
+ {
170
+ "epoch": 0.41,
171
+ "learning_rate": 0.0,
172
+ "loss": 0.0002,
173
+ "step": 3000
174
+ },
175
+ {
176
+ "epoch": 0.41,
177
+ "eval_stsb_spearman": 0.6832701515366976,
178
+ "step": 3000
179
+ },
180
+ {
181
+ "epoch": 0.48,
182
+ "learning_rate": 0.0,
183
+ "loss": 0.0002,
184
+ "step": 3500
185
+ },
186
+ {
187
+ "epoch": 0.55,
188
+ "learning_rate": 0.0,
189
+ "loss": 0.0002,
190
+ "step": 4000
191
+ },
192
+ {
193
+ "epoch": 0.55,
194
+ "eval_stsb_spearman": 0.6832701515366976,
195
+ "step": 4000
196
+ },
197
+ {
198
+ "epoch": 0.61,
199
+ "learning_rate": 0.0,
200
+ "loss": 0.0002,
201
+ "step": 4500
202
+ },
203
+ {
204
+ "epoch": 0.68,
205
+ "learning_rate": 0.0,
206
+ "loss": 0.0002,
207
+ "step": 5000
208
+ },
209
+ {
210
+ "epoch": 0.68,
211
+ "eval_stsb_spearman": 0.6832701515366976,
212
+ "step": 5000
213
+ },
214
+ {
215
+ "epoch": 0.75,
216
+ "learning_rate": 0.0,
217
+ "loss": 0.0002,
218
+ "step": 5500
219
+ },
220
+ {
221
+ "epoch": 0.82,
222
+ "learning_rate": 0.0,
223
+ "loss": 0.0002,
224
+ "step": 6000
225
+ },
226
+ {
227
+ "epoch": 0.82,
228
+ "eval_stsb_spearman": 0.6832701515366976,
229
+ "step": 6000
230
+ },
231
+ {
232
+ "epoch": 0.89,
233
+ "learning_rate": 0.0,
234
+ "loss": 0.0002,
235
+ "step": 6500
236
+ },
237
+ {
238
+ "epoch": 0.95,
239
+ "learning_rate": 0.0,
240
+ "loss": 0.0002,
241
+ "step": 7000
242
+ },
243
+ {
244
+ "epoch": 0.95,
245
+ "eval_stsb_spearman": 0.6832701515366976,
246
+ "step": 7000
247
+ },
248
+ {
249
+ "epoch": 1.0,
250
+ "step": 7330,
251
+ "total_flos": 0,
252
+ "train_runtime": 3008.4826,
253
+ "train_samples_per_second": 2.436
254
+ },
255
+ {
256
+ "epoch": 0.07,
257
+ "learning_rate": 2.795361527967258e-05,
258
+ "loss": 0.0002,
259
+ "step": 500
260
+ },
261
+ {
262
+ "epoch": 0.14,
263
+ "learning_rate": 2.5907230559345156e-05,
264
+ "loss": 0.0002,
265
+ "step": 1000
266
+ },
267
+ {
268
+ "epoch": 0.14,
269
+ "eval_stsb_spearman": 0.6647397049127042,
270
+ "step": 1000
271
+ },
272
+ {
273
+ "epoch": 0.2,
274
+ "learning_rate": 2.386084583901774e-05,
275
+ "loss": 0.0002,
276
+ "step": 1500
277
+ },
278
+ {
279
+ "epoch": 0.27,
280
+ "learning_rate": 2.1814461118690315e-05,
281
+ "loss": 0.0002,
282
+ "step": 2000
283
+ },
284
+ {
285
+ "epoch": 0.27,
286
+ "eval_stsb_spearman": 0.6705695143163508,
287
+ "step": 2000
288
+ },
289
+ {
290
+ "epoch": 0.34,
291
+ "learning_rate": 1.9768076398362894e-05,
292
+ "loss": 0.0002,
293
+ "step": 2500
294
+ },
295
+ {
296
+ "epoch": 0.41,
297
+ "learning_rate": 1.772169167803547e-05,
298
+ "loss": 0.0002,
299
+ "step": 3000
300
+ },
301
+ {
302
+ "epoch": 0.41,
303
+ "eval_stsb_spearman": 0.6834165899504511,
304
+ "step": 3000
305
+ },
306
+ {
307
+ "epoch": 0.48,
308
+ "learning_rate": 1.567530695770805e-05,
309
+ "loss": 0.0002,
310
+ "step": 3500
311
+ },
312
+ {
313
+ "epoch": 0.55,
314
+ "learning_rate": 1.3628922237380627e-05,
315
+ "loss": 0.0002,
316
+ "step": 4000
317
+ },
318
+ {
319
+ "epoch": 0.55,
320
+ "eval_stsb_spearman": 0.6889523167904467,
321
+ "step": 4000
322
+ },
323
+ {
324
+ "epoch": 0.61,
325
+ "learning_rate": 1.1582537517053206e-05,
326
+ "loss": 0.0002,
327
+ "step": 4500
328
+ },
329
+ {
330
+ "epoch": 0.68,
331
+ "learning_rate": 9.536152796725784e-06,
332
+ "loss": 0.0002,
333
+ "step": 5000
334
+ },
335
+ {
336
+ "epoch": 0.68,
337
+ "eval_stsb_spearman": 0.6907657748709582,
338
+ "step": 5000
339
+ },
340
+ {
341
+ "epoch": 0.75,
342
+ "learning_rate": 7.489768076398363e-06,
343
+ "loss": 0.0002,
344
+ "step": 5500
345
+ },
346
+ {
347
+ "epoch": 0.82,
348
+ "learning_rate": 5.443383356070941e-06,
349
+ "loss": 0.0002,
350
+ "step": 6000
351
+ },
352
+ {
353
+ "epoch": 0.82,
354
+ "eval_stsb_spearman": 0.6844441359759208,
355
+ "step": 6000
356
+ },
357
+ {
358
+ "epoch": 0.89,
359
+ "learning_rate": 3.39699863574352e-06,
360
+ "loss": 0.0002,
361
+ "step": 6500
362
+ },
363
+ {
364
+ "epoch": 0.95,
365
+ "learning_rate": 1.3506139154160984e-06,
366
+ "loss": 0.0002,
367
+ "step": 7000
368
+ },
369
+ {
370
+ "epoch": 0.95,
371
+ "eval_stsb_spearman": 0.6838872101024212,
372
+ "step": 7000
373
+ },
374
+ {
375
+ "epoch": 1.0,
376
+ "step": 7330,
377
+ "total_flos": 0,
378
+ "train_runtime": 3006.5028,
379
+ "train_samples_per_second": 2.438
380
+ },
381
+ {
382
+ "epoch": 0.07,
383
+ "learning_rate": 2.795361527967258e-05,
384
+ "loss": 3.4229,
385
+ "step": 500
386
+ },
387
+ {
388
+ "epoch": 0.14,
389
+ "learning_rate": 2.5907230559345156e-05,
390
+ "loss": 3.4229,
391
+ "step": 1000
392
+ },
393
+ {
394
+ "epoch": 0.14,
395
+ "eval_stsb_spearman": 0.6971006163293475,
396
+ "step": 1000
397
+ },
398
+ {
399
+ "epoch": 0.2,
400
+ "learning_rate": 2.386084583901774e-05,
401
+ "loss": 3.4228,
402
+ "step": 1500
403
+ },
404
+ {
405
+ "epoch": 0.27,
406
+ "learning_rate": 2.1814461118690315e-05,
407
+ "loss": 3.4229,
408
+ "step": 2000
409
+ },
410
+ {
411
+ "epoch": 0.27,
412
+ "eval_stsb_spearman": 0.7098151136325446,
413
+ "step": 2000
414
+ },
415
+ {
416
+ "epoch": 0.34,
417
+ "learning_rate": 1.9768076398362894e-05,
418
+ "loss": 3.4229,
419
+ "step": 2500
420
+ },
421
+ {
422
+ "epoch": 0.41,
423
+ "learning_rate": 1.772169167803547e-05,
424
+ "loss": 3.4228,
425
+ "step": 3000
426
+ },
427
+ {
428
+ "epoch": 0.41,
429
+ "eval_stsb_spearman": 0.7175803233471086,
430
+ "step": 3000
431
+ },
432
+ {
433
+ "epoch": 0.48,
434
+ "learning_rate": 1.567530695770805e-05,
435
+ "loss": 3.4228,
436
+ "step": 3500
437
+ },
438
+ {
439
+ "epoch": 0.55,
440
+ "learning_rate": 1.3628922237380627e-05,
441
+ "loss": 3.4229,
442
+ "step": 4000
443
+ },
444
+ {
445
+ "epoch": 0.55,
446
+ "eval_stsb_spearman": 0.7188510448496929,
447
+ "step": 4000
448
+ },
449
+ {
450
+ "epoch": 0.61,
451
+ "learning_rate": 1.1582537517053206e-05,
452
+ "loss": 3.4229,
453
+ "step": 4500
454
+ },
455
+ {
456
+ "epoch": 0.68,
457
+ "learning_rate": 9.536152796725784e-06,
458
+ "loss": 3.4228,
459
+ "step": 5000
460
+ },
461
+ {
462
+ "epoch": 0.68,
463
+ "eval_stsb_spearman": 0.71954530730918,
464
+ "step": 5000
465
+ },
466
+ {
467
+ "epoch": 0.75,
468
+ "learning_rate": 7.489768076398363e-06,
469
+ "loss": 3.4229,
470
+ "step": 5500
471
+ },
472
+ {
473
+ "epoch": 0.82,
474
+ "learning_rate": 5.443383356070941e-06,
475
+ "loss": 3.4228,
476
+ "step": 6000
477
+ },
478
+ {
479
+ "epoch": 0.82,
480
+ "eval_stsb_spearman": 0.715340103967707,
481
+ "step": 6000
482
+ },
483
+ {
484
+ "epoch": 0.89,
485
+ "learning_rate": 3.39699863574352e-06,
486
+ "loss": 3.4228,
487
+ "step": 6500
488
+ },
489
+ {
490
+ "epoch": 0.95,
491
+ "learning_rate": 1.3506139154160984e-06,
492
+ "loss": 3.4229,
493
+ "step": 7000
494
+ },
495
+ {
496
+ "epoch": 0.95,
497
+ "eval_stsb_spearman": 0.7149024415170762,
498
+ "step": 7000
499
+ }
500
+ ],
501
+ "max_steps": 7330,
502
+ "num_train_epochs": 1,
503
+ "total_flos": 0,
504
+ "trial_name": null,
505
+ "trial_params": null
506
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82ef62c98bbc42a0ce12883124231b698271139d95beae58f38eff35ab2ba06f
3
+ size 3643
vocab.txt ADDED
The diff for this file is too large to render. See raw diff