-
Notifications
You must be signed in to change notification settings - Fork 161
/
Copy pathtask_sentence_embedding_sup_concat_CrossEntropyLoss.py
170 lines (141 loc) · 7.23 KB
/
task_sentence_embedding_sup_concat_CrossEntropyLoss.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#! -*- coding:utf-8 -*-
# loss: 句向量concat后 (u, v, u-v, u*v) 走CrossEntropyLoss
from bert4torch.tokenizers import Tokenizer
from bert4torch.models import build_transformer_model, BaseModel
from bert4torch.callbacks import Callback
from bert4torch.snippets import sequence_padding, ListDataset, get_pool_emb, seed_everything
import torch.nn as nn
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from sklearn.metrics.pairwise import paired_cosine_distances
from scipy.stats import spearmanr
from tqdm import tqdm
import argparse
import numpy as np
# =============================基本参数=============================
parser = argparse.ArgumentParser()
parser.add_argument('--pooling', default='cls', choices=['first-last-avg', 'last-avg', 'cls', 'pooler'])
parser.add_argument('--task_name', default='ATEC', choices=['ATEC', 'BQ', 'LCQMC', 'PAWSX', 'STS-B'])
args = parser.parse_args()
pooling = args.pooling
task_name = args.task_name
maxlen = 64 if task_name != 'PAWSX' else 128
batch_size = 32
config_path = 'E:/data/pretrain_ckpt/bert/google@chinese_L-12_H-768_A-12/bert4torch_config.json'
checkpoint_path = 'E:/data/pretrain_ckpt/bert/google@chinese_L-12_H-768_A-12/pytorch_model.bin'
dict_path = 'E:/data/pretrain_ckpt/bert/google@chinese_L-12_H-768_A-12/vocab.txt'
device = 'cuda' if torch.cuda.is_available() else 'cpu'
seed_everything(42)
# 建立分词器
tokenizer = Tokenizer(dict_path, do_lower_case=True)
class MyDataset(ListDataset):
@staticmethod
def load_data(filename):
"""加载数据
单条格式:(文本1, 文本2, 标签id)
"""
D = []
with open(filename, encoding='utf-8') as f:
for l in f:
l = l.strip().split('\t')
if len(l) == 3:
D.append((l[0], l[1], int(l[2])))
return D
def collate_fn(batch):
batch_token1_ids, batch_token2_ids, batch_labels = [], [], []
for text1, text2, label in batch:
label = int(label > 2.5) if task_name == 'STS-B' else label
token1_ids, _ = tokenizer.encode(text1, maxlen=maxlen)
batch_token1_ids.append(token1_ids)
token2_ids, _ = tokenizer.encode(text2, maxlen=maxlen)
batch_token2_ids.append(token2_ids)
batch_labels.append([label])
batch_token1_ids = torch.tensor(sequence_padding(batch_token1_ids), dtype=torch.long, device=device)
batch_token2_ids = torch.tensor(sequence_padding(batch_token2_ids), dtype=torch.long, device=device)
batch_labels = torch.tensor(batch_labels, dtype=torch.long, device=device)
return (batch_token1_ids, batch_token2_ids), batch_labels.flatten()
# 加载数据集
train_dataloader = DataLoader(MyDataset(f'F:/data/corpus/sentence_embedding/{task_name}/{task_name}.train.data'), batch_size=batch_size, shuffle=True, collate_fn=collate_fn)
valid_dataloader = DataLoader(MyDataset(f'F:/data/corpus/sentence_embedding/{task_name}/{task_name}.valid.data'), batch_size=batch_size, collate_fn=collate_fn)
test_dataloader = DataLoader(MyDataset(f'F:/data/corpus/sentence_embedding/{task_name}/{task_name}.test.data'), batch_size=batch_size, collate_fn=collate_fn)
# 定义bert上的模型结构
class Model(BaseModel):
def __init__(self, pool_method='cls', concatenation_sent_rep=True, concatenation_sent_difference=True, concatenation_sent_multiplication=False):
super().__init__()
self.pool_method = pool_method
with_pool = 'linear' if pool_method == 'pooler' else True
output_all_encoded_layers = True if pool_method == 'first-last-avg' else False
self.bert = build_transformer_model(config_path, checkpoint_path, segment_vocab_size=0,
with_pool=with_pool, output_all_encoded_layers=output_all_encoded_layers)
self.concatenation_sent_rep = concatenation_sent_rep
self.concatenation_sent_difference = concatenation_sent_difference
self.concatenation_sent_multiplication = concatenation_sent_multiplication
hidden_unit = 0
hidden_unit += 768*2 if self.concatenation_sent_rep else 0
hidden_unit += 768 if self.concatenation_sent_difference else 0
hidden_unit += 768 if self.concatenation_sent_multiplication else 0
self.fc = nn.Linear(hidden_unit, 2)
def forward(self, token1_ids, token2_ids):
hidden_state1, pooler1 = self.bert([token1_ids])
rep_a = get_pool_emb(hidden_state1, pooler1, token1_ids.gt(0).long(), self.pool_method)
hidden_state2, pooler2 = self.bert([token2_ids])
rep_b = get_pool_emb(hidden_state2, pooler2, token2_ids.gt(0).long(), self.pool_method)
vectors_concat = []
if self.concatenation_sent_rep:
vectors_concat.append(rep_a)
vectors_concat.append(rep_b)
if self.concatenation_sent_difference:
vectors_concat.append(torch.abs(rep_a - rep_b))
if self.concatenation_sent_multiplication:
vectors_concat.append(rep_a * rep_b)
vectors_concat = torch.cat(vectors_concat, dim=1)
return self.fc(vectors_concat)
def predict(self, token_ids):
self.eval()
with torch.no_grad():
hidden_state, pooler = self.bert([token_ids])
attention_mask = token_ids.gt(0).long()
output = get_pool_emb(hidden_state, pooler, attention_mask, self.pool_method)
return output
model = Model().to(device)
# 定义使用的loss和optimizer,这里支持自定义
model.compile(
loss=nn.CrossEntropyLoss(),
optimizer=optim.Adam(model.parameters(), lr=2e-5),
metrics=['accuracy']
)
class Evaluator(Callback):
"""评估与保存
"""
def __init__(self):
self.best_val_consine = 0.
def on_epoch_end(self, global_step, epoch, logs=None):
val_consine = self.evaluate(valid_dataloader)
test_consine = self.evaluate(test_dataloader)
if val_consine > self.best_val_consine:
self.best_val_consine = val_consine
# model.save_weights('best_model.pt')
print(f'valid_consine: {val_consine:.5f}, test_consine: {test_consine:.5f}, best_val_consine: {self.best_val_consine:.5f}\n')
# 定义评价函数
def evaluate(self, data):
cosine_scores, labels = [], []
for (batch_token1_ids, batch_token2_ids), batch_labels in tqdm(data, desc='Evaluate'):
embeddings1 = model.predict(batch_token1_ids).cpu().numpy()
embeddings2 = model.predict(batch_token2_ids).cpu().numpy()
cosine_score = 1 - paired_cosine_distances(embeddings1, embeddings2)
cosine_scores.append(cosine_score)
labels.append(batch_labels.cpu().numpy())
labels = np.concatenate(labels)
cosine_scores = np.concatenate(cosine_scores)
eval_pearson_cosine, _ = spearmanr(labels, cosine_scores)
return eval_pearson_cosine
if __name__ == '__main__':
evaluator = Evaluator()
model.fit(train_dataloader,
epochs=5,
steps_per_epoch=None,
callbacks=[evaluator]
)
else:
model.load_weights('best_model.pt')