forked from kongds/Prompt-BERT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluation.py
393 lines (346 loc) · 18.3 KB
/
evaluation.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import re
import sys
import io, os
import torch
import numpy as np
import logging
import tqdm
import argparse
from prettytable import PrettyTable
import torch
import transformers
from transformers import AutoModel, AutoTokenizer
# Set up logger
logging.basicConfig(format='%(asctime)s : %(message)s', level=logging.DEBUG)
# Set PATHs
PATH_TO_SENTEVAL = './SentEval'
PATH_TO_DATA = './SentEval/data'
# Import SentEval
sys.path.insert(0, PATH_TO_SENTEVAL)
import senteval
def s_eval(args):
se, task = args[0], args[1]
return se.eval(task)
def print_table(task_names, scores):
tb = PrettyTable()
tb.field_names = task_names
tb.add_row(scores)
print(tb)
def get_delta(model, template, tokenizer, device, args):
model.eval()
template = template.replace('*mask*', tokenizer.mask_token)\
.replace('*sep+*', '')\
.replace('*cls*', '').replace('*sent_0*', ' ')
# strip for roberta tokenizer
bs_length = len(tokenizer.encode(template.split(' ')[0].replace('_', ' ').strip())) - 2 + 1
# replace for roberta tokenizer
batch = tokenizer([template.replace('_', ' ').strip().replace(' ', ' ')], return_tensors='pt')
batch['position_ids'] = torch.arange(batch['input_ids'].shape[1]).to(device).unsqueeze(0)
for k in batch:
batch[k] = batch[k].repeat(128, 1).to(device)
m_mask = batch['input_ids'] == tokenizer.mask_token_id
with torch.no_grad():
outputs = model(**batch, output_hidden_states=True, return_dict=True)
last_hidden = outputs.hidden_states[-1]
delta = last_hidden[m_mask]
delta.requires_grad = False
#import pdb;pdb.set_trace()
template_len = batch['input_ids'].shape[1]
return delta, template_len
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--embedding_only", action='store_true')
parser.add_argument('--mlm_head_predict', action='store_true')
parser.add_argument('--remove_continue_word', action='store_true')
parser.add_argument('--mask_embedding_sentence', action='store_true')
parser.add_argument('--mask_embedding_sentence_use_org_pooler', action='store_true')
parser.add_argument('--mask_embedding_sentence_template', type=str, default=None)
parser.add_argument('--mask_embedding_sentence_delta', action='store_true')
parser.add_argument('--mask_embedding_sentence_use_pooler', action='store_true')
parser.add_argument('--mask_embedding_sentence_autoprompt', action='store_true')
parser.add_argument('--mask_embedding_sentence_org_mlp', action='store_true')
parser.add_argument("--tokenizer_name", type=str, default='')
parser.add_argument("--model_name_or_path", type=str,
help="Transformers' model name or path")
parser.add_argument("--pooler", type=str,
choices=['cls', 'cls_before_pooler', 'avg', 'avg_first_last'],
default='cls',
help="Which pooler to use")
parser.add_argument("--mode", type=str,
choices=['dev', 'test', 'fasttest'],
default='test',
help="What evaluation mode to use (dev: fast mode, dev results; test: full mode, test results); fasttest: fast mode, test results")
parser.add_argument("--task_set", type=str,
choices=['sts', 'transfer', 'full', 'na'],
default='sts',
help="What set of tasks to evaluate on. If not 'na', this will override '--tasks'")
args = parser.parse_args()
# Load transformers' model checkpoint
if args.mask_embedding_sentence_org_mlp:
#only for bert-base
from transformers import BertForMaskedLM, BertConfig
config = BertConfig.from_pretrained("bert-base-uncased")
mlp = BertForMaskedLM.from_pretrained('bert-base-uncased', config=config).cls.predictions.transform
if 'result' in args.model_name_or_path:
state_dict = torch.load(args.model_name_or_path+'/pytorch_model.bin')
new_state_dict = {}
for key, param in state_dict.items():
# Replace "mlp" to "pooler"
if 'pooler' in key:
key = key.replace("pooler.", "")
new_state_dict[key] = param
mlp.load_state_dict(new_state_dict)
model = AutoModel.from_pretrained(args.model_name_or_path)
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=True)
if args.mask_embedding_sentence_autoprompt:
state_dict = torch.load(args.model_name_or_path+'/pytorch_model.bin')
p_mbv = state_dict['p_mbv']
template = args.mask_embedding_sentence_template
template = template.replace('*mask*', tokenizer.mask_token)\
.replace('*sep+*', '')\
.replace('*cls*', '').replace('*sent_0*', ' ').replace('_', ' ')
mask_embedding_template = tokenizer.encode(template)
mask_index = mask_embedding_template.index(tokenizer.mask_token_id)
index_mbv = mask_embedding_template[1:mask_index] + mask_embedding_template[mask_index+1:-1]
#mask_embedding_template = [ 101, 2023, 6251, 1997, 1000, 1000, 2965, 103, 1012, 102]
#index_mbv = mask_embedding_template[1:7] + mask_embedding_template[8:9]
dict_mbv = index_mbv
fl_mbv = [i <= 3 for i, k in enumerate(index_mbv)]
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#device = torch.device("cpu")
model = model.to(device)
if args.mask_embedding_sentence_org_mlp:
mlp = mlp.to(device)
if args.mask_embedding_sentence_delta:
delta, template_len = get_delta(model, args.mask_embedding_sentence_template, tokenizer, device, args)
# Set up the tasks
#args.tasks = ['STS12', 'STS13', 'STS14', 'STS15', 'STS16', 'STSBenchmark', 'SICKRelatedness']
#args.tasks = ['MR']
if args.task_set == 'sts':
args.tasks = ['STS12', 'STS13', 'STS14', 'STS15', 'STS16', 'STSBenchmark', 'SICKRelatedness']
elif args.task_set == 'transfer':
args.tasks = ['MR', 'CR', 'MPQA', 'SUBJ', 'SST2', 'TREC', 'MRPC']
elif args.task_set == 'full':
args.tasks = ['STS12', 'STS13', 'STS14', 'STS15', 'STS16', 'STSBenchmark', 'SICKRelatedness']
args.tasks += ['MR', 'CR', 'MPQA', 'SUBJ', 'SST2', 'TREC', 'MRPC']
# Set params for SentEval
if args.mode == 'dev' or args.mode == 'fasttest':
# Fast mode
params = {'task_path': PATH_TO_DATA, 'usepytorch': True, 'kfold': 5}
params['classifier'] = {'nhid': 0, 'optim': 'rmsprop', 'batch_size': 128,
'tenacity': 3, 'epoch_size': 2}
elif args.mode == 'test':
# Full mode
params = {'task_path': PATH_TO_DATA, 'usepytorch': True, 'kfold': 10}
params['classifier'] = {'nhid': 0, 'optim': 'adam', 'batch_size': 64,
'tenacity': 5, 'epoch_size': 4}
else:
raise NotImplementedError
# SentEval prepare and batcher
def prepare(params, samples):
return
if args.remove_continue_word:
pun_remove_set = {'?', '*', '#', '´', '’', '=', '…', '|', '~', '/', '‚', '¿', '–', '»', '-', '€', '‘', '"', '(', '•', '`', '$', ':', '[', '”', '%', '£', '<', '[UNK]', ';', '“', '@', '_', '{', '^', ',', '.', '!', '™', '&', ']', '>', '\\', "'", ')', '+', '—'}
if args.model_name_or_path == 'roberta-base':
remove_set = {'Ġ.', 'Ġa', 'Ġthe', 'Ġin', 'a', 'Ġ, ', 'Ġis', 'Ġto', 'Ġof', 'Ġand', 'Ġon', 'Ġ\'', 's', '.', 'the', 'Ġman', '-', 'Ġwith', 'Ġfor', 'Ġat', 'Ġwoman', 'Ġare', 'Ġ"', 'Ġthat', 'Ġit', 'Ġdog', 'Ġsaid', 'Ġplaying', 'Ġwas', 'Ġas', 'Ġfrom', 'Ġ:', 'Ġyou', 'Ġan', 'i', 'Ġby'}
else:
remove_set = {".", "a", "the", "in", ",", "is", "to", "of", "and", "'", "on", "man", "-", "s", "with", "for", "\"", "at", "##s", "woman", "are", "it", "two", "that", "you", "dog", "said", "playing", "i", "an", "as", "was", "from", ":", "by", "white"}
vocab = tokenizer.get_vocab()
def batcher(params, batch, max_length=None):
# Handle rare token encoding issues in the dataset
if len(batch) >= 1 and len(batch[0]) >= 1 and isinstance(batch[0][0], bytes):
batch = [[word.decode('utf-8') for word in s] for s in batch]
sentences = [' '.join(s) for s in batch]
if args.mask_embedding_sentence and args.mask_embedding_sentence_template is not None:
# *cls*_This_sentence_of_"*sent_0*"_means*mask*.*sep+*
template = args.mask_embedding_sentence_template
template = template.replace('*mask*', tokenizer.mask_token )\
.replace('_', ' ').replace('*sep+*', '')\
.replace('*cls*', '')
for i, s in enumerate(sentences):
if len(s) > 0 and s[-1] not in '.?"\'': s += '.'
sentences[i] = template.replace('*sent 0*', s).strip()
elif args.remove_continue_word:
for i, s in enumerate(sentences):
sentences[i] = ' ' if args.model_name_or_path == 'roberta-base' else ''
es = tokenizer.encode(' ' + s, add_special_tokens=False)
for iw, w in enumerate(tokenizer.convert_ids_to_tokens(es)):
if args.model_name_or_path == 'roberta-base':
# roberta base
if 'Ġ' not in w or w in remove_set:
pass
else:
if re.search('[a-zA-Z0-9]', w) is not None:
sentences[i] += w.replace('Ġ', '').lower() + ' '
elif w not in remove_set and w not in pun_remove_set and '##' not in w:
# bert base
sentences[i] += w.lower() + ' '
if len(sentences[i]) == 0: sentences[i] = '[PAD]'
if max_length is not None:
batch = tokenizer.batch_encode_plus(
sentences,
return_tensors='pt',
padding=True,
max_length=max_length,
truncation=True
)
else:
batch = tokenizer.batch_encode_plus(
sentences,
return_tensors='pt',
padding=True,
)
# Move to the correct device
for k in batch:
batch[k] = batch[k].to(device) if batch[k] is not None else None
# Get raw embeddings
with torch.no_grad():
if args.embedding_only:
hidden_states = None
pooler_output = None
last_hidden = model.embeddings.word_embeddings(batch['input_ids'])
position_ids = model.embeddings.position_ids[:, 0 : last_hidden.shape[1]]
token_type_ids = torch.zeros(batch['input_ids'].shape, dtype=torch.long,
device=model.embeddings.position_ids.device)
position_embeddings = model.embeddings.position_embeddings(position_ids)
token_type_embeddings = model.embeddings.token_type_embeddings(token_type_ids)
if args.remove_continue_word:
batch['attention_mask'][batch['input_ids'] == tokenizer.cls_token_id] = 0
batch['attention_mask'][batch['input_ids'] == tokenizer.sep_token_id] = 0
elif args.mask_embedding_sentence_autoprompt:
input_ids = batch['input_ids']
inputs_embeds = model.embeddings.word_embeddings(input_ids)
p = torch.arange(input_ids.shape[1]).to(input_ids.device).view(1, -1)
b = torch.arange(input_ids.shape[0]).to(input_ids.device)
for i, k in enumerate(dict_mbv):
if fl_mbv[i]:
index = ((input_ids == k) * p).max(-1)[1]
else:
index = ((input_ids == k) * -p).min(-1)[1]
inputs_embeds[b, index] = p_mbv[i]
batch['input_ids'], batch['inputs_embeds'] = None, inputs_embeds
outputs = model(**batch, output_hidden_states=True, return_dict=True)
batch['input_ids'] = input_ids
last_hidden = outputs.last_hidden_state
pooler_output = last_hidden[input_ids == tokenizer.mask_token_id]
if args.mask_embedding_sentence_org_mlp:
pooler_output = mlp(pooler_output)
if args.mask_embedding_sentence_delta:
blen = batch['attention_mask'].sum(-1) - template_len
if args.mask_embedding_sentence_org_mlp:
pooler_output -= mlp(delta[blen])
else:
pooler_output -= delta[blen]
if args.mask_embedding_sentence_use_pooler:
pooler_output = model.pooler.dense(pooler_output)
pooler_output = model.pooler.activation(pooler_output)
else:
outputs = model(**batch, output_hidden_states=True, return_dict=True)
try:
pooler_output = outputs.pooler_output
except AttributeError:
pooler_output = outputs['last_hidden_state'][:, 0, :]
if args.mask_embedding_sentence:
last_hidden = outputs.last_hidden_state
pooler_output = last_hidden[batch['input_ids'] == tokenizer.mask_token_id]
if args.mask_embedding_sentence_org_mlp:
pooler_output = mlp(pooler_output)
if args.mask_embedding_sentence_delta:
blen = batch['attention_mask'].sum(-1) - template_len
if args.mask_embedding_sentence_org_mlp:
pooler_output -= mlp(delta[blen])
else:
pooler_output -= delta[blen]
if args.mask_embedding_sentence_use_org_pooler:
pooler_output = mlp(pooler_output)
if args.mask_embedding_sentence_use_pooler:
pooler_output = model.pooler.dense(pooler_output)
pooler_output = model.pooler.activation(pooler_output)
else:
last_hidden = outputs.last_hidden_state
hidden_states = outputs.hidden_states
# Apply different pooler
if args.mask_embedding_sentence:
return pooler_output.view(batch['input_ids'].shape[0], -1).cpu()
elif args.pooler == 'cls':
# There is a linear+activation layer after CLS representation
return pooler_output.cpu()
elif args.pooler == 'cls_before_pooler':
batch['input_ids'][(batch['input_ids'] == 0) | (batch['input_ids'] == 101) | (batch['input_ids'] == 102)] = batch['input_ids'].max()
index = batch['input_ids'].topk(3, dim=-1, largest=False)[1]
index2 = torch.arange(batch['input_ids'].shape[0]).to(index.device)
r = last_hidden[index2, index[:, 0], :]
for i in range(1, 3):
r += last_hidden[index2, index[:, i], :]
return (r/3).cpu()
elif args.pooler == "avg":
return ((last_hidden * batch['attention_mask'].unsqueeze(-1)).sum(1) / batch['attention_mask'].sum(-1).unsqueeze(-1)).cpu()
elif args.pooler == "avg_first_last":
first_hidden = hidden_states[0]
last_hidden = hidden_states[-1]
pooled_result = ((first_hidden + last_hidden) / 2.0 * batch['attention_mask'].unsqueeze(-1)).sum(1) / batch['attention_mask'].sum(-1).unsqueeze(-1)
return pooled_result.cpu()
elif args.pooler == "avg_top2":
second_last_hidden = hidden_states[-2]
last_hidden = hidden_states[-1]
pooled_result = ((last_hidden + second_last_hidden) / 2.0 * batch['attention_mask'].unsqueeze(-1)).sum(1) / batch['attention_mask'].sum(-1).unsqueeze(-1)
return pooled_result.cpu()
else:
raise NotImplementedError
results = {}
for task in args.tasks:
se = senteval.engine.SE(params, batcher, prepare)
result = se.eval(task)
results[task] = result
# Print evaluation results
if args.mode == 'dev':
print("------ %s ------" % (args.mode))
task_names = []
scores = []
for task in ['STSBenchmark', 'SICKRelatedness']:
task_names.append(task)
if task in results:
scores.append("%.2f" % (results[task]['dev']['spearman'][0] * 100))
else:
scores.append("0.00")
print_table(task_names, scores)
task_names = []
scores = []
for task in ['MR', 'CR', 'SUBJ', 'MPQA', 'SST2', 'TREC', 'MRPC']:
task_names.append(task)
if task in results:
scores.append("%.2f" % (results[task]['devacc']))
else:
scores.append("0.00")
task_names.append("Avg.")
scores.append("%.2f" % (sum([float(score) for score in scores]) / len(scores)))
print_table(task_names, scores)
elif args.mode == 'test' or args.mode == 'fasttest':
print("------ %s ------" % (args.mode))
task_names = []
scores = []
for task in ['STS12', 'STS13', 'STS14', 'STS15', 'STS16', 'STSBenchmark', 'SICKRelatedness']:
task_names.append(task)
if task in results:
if task in ['STS12', 'STS13', 'STS14', 'STS15', 'STS16']:
scores.append("%.2f" % (results[task]['all']['spearman']['all'] * 100))
else:
scores.append("%.2f" % (results[task]['test']['spearman'].correlation * 100))
else:
scores.append("0.00")
task_names.append("Avg.")
scores.append("%.2f" % (sum([float(score) for score in scores]) / len(scores)))
print_table(task_names, scores)
task_names = []
scores = []
for task in ['MR', 'CR', 'SUBJ', 'MPQA', 'SST2', 'TREC', 'MRPC']:
task_names.append(task)
if task in results:
scores.append("%.2f" % (results[task]['acc']))
else:
scores.append("0.00")
task_names.append("Avg.")
scores.append("%.2f" % (sum([float(score) for score in scores]) / len(scores)))
print_table(task_names, scores)
if __name__ == "__main__":
main()