This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 232
/
main_dense.py
693 lines (592 loc) · 21.1 KB
/
main_dense.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import json
import sys
from tqdm import tqdm
import logging
import torch
import numpy as np
from colorama import init
from termcolor import colored
import blink.ner as NER
from torch.utils.data import DataLoader, SequentialSampler, TensorDataset
from blink.biencoder.biencoder import BiEncoderRanker, load_biencoder
from blink.crossencoder.crossencoder import CrossEncoderRanker, load_crossencoder
from blink.biencoder.data_process import (
process_mention_data,
get_candidate_representation,
)
import blink.candidate_ranking.utils as utils
from blink.crossencoder.train_cross import modify, evaluate
from blink.crossencoder.data_process import prepare_crossencoder_data
from blink.indexer.faiss_indexer import DenseFlatIndexer, DenseHNSWFlatIndexer
HIGHLIGHTS = [
"on_red",
"on_green",
"on_yellow",
"on_blue",
"on_magenta",
"on_cyan",
]
def _print_colorful_text(input_sentence, samples):
init() # colorful output
msg = ""
if samples and (len(samples) > 0):
msg += input_sentence[0 : int(samples[0]["start_pos"])]
for idx, sample in enumerate(samples):
msg += colored(
input_sentence[int(sample["start_pos"]) : int(sample["end_pos"])],
"grey",
HIGHLIGHTS[idx % len(HIGHLIGHTS)],
)
if idx < len(samples) - 1:
msg += input_sentence[
int(sample["end_pos"]) : int(samples[idx + 1]["start_pos"])
]
else:
msg += input_sentence[int(sample["end_pos"]) :]
else:
msg = input_sentence
print("Failed to identify entity from text:")
print("\n" + str(msg) + "\n")
def _print_colorful_prediction(
idx, sample, e_id, e_title, e_text, e_url, show_url=False
):
print(colored(sample["mention"], "grey", HIGHLIGHTS[idx % len(HIGHLIGHTS)]))
to_print = "id:{}\ntitle:{}\ntext:{}\n".format(e_id, e_title, e_text[:256])
if show_url:
to_print += "url:{}\n".format(e_url)
print(to_print)
def _annotate(ner_model, input_sentences):
ner_output_data = ner_model.predict(input_sentences)
sentences = ner_output_data["sentences"]
mentions = ner_output_data["mentions"]
samples = []
for mention in mentions:
record = {}
record["label"] = "unknown"
record["label_id"] = -1
# LOWERCASE EVERYTHING !
record["context_left"] = sentences[mention["sent_idx"]][
: mention["start_pos"]
].lower()
record["context_right"] = sentences[mention["sent_idx"]][
mention["end_pos"] :
].lower()
record["mention"] = mention["text"].lower()
record["start_pos"] = int(mention["start_pos"])
record["end_pos"] = int(mention["end_pos"])
record["sent_idx"] = mention["sent_idx"]
samples.append(record)
return samples
def _load_candidates(
entity_catalogue, entity_encoding, faiss_index=None, index_path=None, logger=None
):
# only load candidate encoding if not using faiss index
if faiss_index is None:
candidate_encoding = torch.load(entity_encoding)
indexer = None
else:
if logger:
logger.info("Using faiss index to retrieve entities.")
candidate_encoding = None
assert index_path is not None, "Error! Empty indexer path."
if faiss_index == "flat":
indexer = DenseFlatIndexer(1)
elif faiss_index == "hnsw":
indexer = DenseHNSWFlatIndexer(1)
else:
raise ValueError("Error! Unsupported indexer type! Choose from flat,hnsw.")
indexer.deserialize_from(index_path)
# load all the 5903527 entities
title2id = {}
id2title = {}
id2text = {}
wikipedia_id2local_id = {}
local_idx = 0
with open(entity_catalogue, "r") as fin:
lines = fin.readlines()
for line in lines:
entity = json.loads(line)
if "idx" in entity:
split = entity["idx"].split("curid=")
if len(split) > 1:
wikipedia_id = int(split[-1].strip())
else:
wikipedia_id = entity["idx"].strip()
assert wikipedia_id not in wikipedia_id2local_id
wikipedia_id2local_id[wikipedia_id] = local_idx
title2id[entity["title"]] = local_idx
id2title[local_idx] = entity["title"]
id2text[local_idx] = entity["text"]
local_idx += 1
return (
candidate_encoding,
title2id,
id2title,
id2text,
wikipedia_id2local_id,
indexer,
)
def __map_test_entities(test_entities_path, title2id, logger):
# load the 732859 tac_kbp_ref_know_base entities
kb2id = {}
missing_pages = 0
n = 0
with open(test_entities_path, "r") as fin:
lines = fin.readlines()
for line in lines:
entity = json.loads(line)
if entity["title"] not in title2id:
missing_pages += 1
else:
kb2id[entity["entity_id"]] = title2id[entity["title"]]
n += 1
if logger:
logger.info("missing {}/{} pages".format(missing_pages, n))
return kb2id
def __load_test(test_filename, kb2id, wikipedia_id2local_id, logger):
test_samples = []
with open(test_filename, "r") as fin:
lines = fin.readlines()
for line in lines:
record = json.loads(line)
record["label"] = str(record["label_id"])
# for tac kbp we should use a separate knowledge source to get the entity id (label_id)
if kb2id and len(kb2id) > 0:
if record["label"] in kb2id:
record["label_id"] = kb2id[record["label"]]
else:
continue
# check that each entity id (label_id) is in the entity collection
elif wikipedia_id2local_id and len(wikipedia_id2local_id) > 0:
try:
key = int(record["label"].strip())
if key in wikipedia_id2local_id:
record["label_id"] = wikipedia_id2local_id[key]
else:
continue
except:
continue
# LOWERCASE EVERYTHING !
record["context_left"] = record["context_left"].lower()
record["context_right"] = record["context_right"].lower()
record["mention"] = record["mention"].lower()
test_samples.append(record)
if logger:
logger.info("{}/{} samples considered".format(len(test_samples), len(lines)))
return test_samples
def _get_test_samples(
test_filename, test_entities_path, title2id, wikipedia_id2local_id, logger
):
kb2id = None
if test_entities_path:
kb2id = __map_test_entities(test_entities_path, title2id, logger)
test_samples = __load_test(test_filename, kb2id, wikipedia_id2local_id, logger)
return test_samples
def _process_biencoder_dataloader(samples, tokenizer, biencoder_params):
_, tensor_data = process_mention_data(
samples,
tokenizer,
biencoder_params["max_context_length"],
biencoder_params["max_cand_length"],
silent=True,
logger=None,
debug=biencoder_params["debug"],
)
sampler = SequentialSampler(tensor_data)
dataloader = DataLoader(
tensor_data, sampler=sampler, batch_size=biencoder_params["eval_batch_size"]
)
return dataloader
def _run_biencoder(biencoder, dataloader, candidate_encoding, top_k=100, indexer=None):
biencoder.model.eval()
labels = []
nns = []
all_scores = []
for batch in tqdm(dataloader):
context_input, _, label_ids = batch
with torch.no_grad():
if indexer is not None:
context_encoding = biencoder.encode_context(context_input).numpy()
context_encoding = np.ascontiguousarray(context_encoding)
scores, indicies = indexer.search_knn(context_encoding, top_k)
else:
scores = biencoder.score_candidate(
context_input, None, cand_encs=candidate_encoding # .to(device)
)
scores, indicies = scores.topk(top_k)
scores = scores.data.numpy()
indicies = indicies.data.numpy()
labels.extend(label_ids.data.numpy())
nns.extend(indicies)
all_scores.extend(scores)
return labels, nns, all_scores
def _process_crossencoder_dataloader(context_input, label_input, crossencoder_params):
tensor_data = TensorDataset(context_input, label_input)
sampler = SequentialSampler(tensor_data)
dataloader = DataLoader(
tensor_data, sampler=sampler, batch_size=crossencoder_params["eval_batch_size"]
)
return dataloader
def _run_crossencoder(crossencoder, dataloader, logger, context_len, device="cuda"):
crossencoder.model.eval()
accuracy = 0.0
crossencoder.to(device)
res = evaluate(crossencoder, dataloader, device, logger, context_len, zeshel=False, silent=False)
accuracy = res["normalized_accuracy"]
logits = res["logits"]
if accuracy > -1:
predictions = np.argsort(logits, axis=1)
else:
predictions = []
return accuracy, predictions, logits
def load_models(args, logger=None):
# load biencoder model
if logger:
logger.info("loading biencoder model")
with open(args.biencoder_config) as json_file:
biencoder_params = json.load(json_file)
biencoder_params["path_to_model"] = args.biencoder_model
biencoder = load_biencoder(biencoder_params)
crossencoder = None
crossencoder_params = None
if not args.fast:
# load crossencoder model
if logger:
logger.info("loading crossencoder model")
with open(args.crossencoder_config) as json_file:
crossencoder_params = json.load(json_file)
crossencoder_params["path_to_model"] = args.crossencoder_model
crossencoder = load_crossencoder(crossencoder_params)
# load candidate entities
if logger:
logger.info("loading candidate entities")
(
candidate_encoding,
title2id,
id2title,
id2text,
wikipedia_id2local_id,
faiss_indexer,
) = _load_candidates(
args.entity_catalogue,
args.entity_encoding,
faiss_index=getattr(args, 'faiss_index', None),
index_path=getattr(args, 'index_path' , None),
logger=logger,
)
return (
biencoder,
biencoder_params,
crossencoder,
crossencoder_params,
candidate_encoding,
title2id,
id2title,
id2text,
wikipedia_id2local_id,
faiss_indexer,
)
def run(
args,
logger,
biencoder,
biencoder_params,
crossencoder,
crossencoder_params,
candidate_encoding,
title2id,
id2title,
id2text,
wikipedia_id2local_id,
faiss_indexer=None,
test_data=None,
):
if not test_data and not args.test_mentions and not args.interactive:
msg = (
"ERROR: either you start BLINK with the "
"interactive option (-i) or you pass in input test mentions (--test_mentions)"
"and test entitied (--test_entities)"
)
raise ValueError(msg)
id2url = {
v: "https://en.wikipedia.org/wiki?curid=%s" % k
for k, v in wikipedia_id2local_id.items()
}
stopping_condition = False
while not stopping_condition:
samples = None
if args.interactive:
logger.info("interactive mode")
# biencoder_params["eval_batch_size"] = 1
# Load NER model
ner_model = NER.get_model()
# Interactive
text = input("insert text:")
# Identify mentions
samples = _annotate(ner_model, [text])
_print_colorful_text(text, samples)
else:
if logger:
logger.info("test dataset mode")
if test_data:
samples = test_data
else:
# Load test mentions
samples = _get_test_samples(
args.test_mentions,
args.test_entities,
title2id,
wikipedia_id2local_id,
logger,
)
stopping_condition = True
# don't look at labels
keep_all = (
args.interactive
or samples[0]["label"] == "unknown"
or samples[0]["label_id"] < 0
)
# prepare the data for biencoder
if logger:
logger.info("preparing data for biencoder")
dataloader = _process_biencoder_dataloader(
samples, biencoder.tokenizer, biencoder_params
)
# run biencoder
if logger:
logger.info("run biencoder")
top_k = args.top_k
labels, nns, scores = _run_biencoder(
biencoder, dataloader, candidate_encoding, top_k, faiss_indexer
)
if args.interactive:
print("\nfast (biencoder) predictions:")
_print_colorful_text(text, samples)
# print biencoder prediction
idx = 0
for entity_list, sample in zip(nns, samples):
e_id = entity_list[0]
e_title = id2title[e_id]
e_text = id2text[e_id]
e_url = id2url[e_id]
_print_colorful_prediction(
idx, sample, e_id, e_title, e_text, e_url, args.show_url
)
idx += 1
print()
if args.fast:
# use only biencoder
continue
else:
biencoder_accuracy = -1
recall_at = -1
if not keep_all:
# get recall values
top_k = args.top_k
x = []
y = []
for i in range(1, top_k):
temp_y = 0.0
for label, top in zip(labels, nns):
if label in top[:i]:
temp_y += 1
if len(labels) > 0:
temp_y /= len(labels)
x.append(i)
y.append(temp_y)
# plt.plot(x, y)
biencoder_accuracy = y[0]
recall_at = y[-1]
print("biencoder accuracy: %.4f" % biencoder_accuracy)
print("biencoder recall@%d: %.4f" % (top_k, y[-1]))
if args.fast:
predictions = []
for entity_list in nns:
sample_prediction = []
for e_id in entity_list:
e_title = id2title[e_id]
sample_prediction.append(e_title)
predictions.append(sample_prediction)
# use only biencoder
return (
biencoder_accuracy,
recall_at,
-1,
-1,
len(samples),
predictions,
scores,
)
# prepare crossencoder data
context_input, candidate_input, label_input = prepare_crossencoder_data(
crossencoder.tokenizer, samples, labels, nns, id2title, id2text, keep_all,
)
context_input = modify(
context_input, candidate_input, crossencoder_params["max_seq_length"]
)
dataloader = _process_crossencoder_dataloader(
context_input, label_input, crossencoder_params
)
# run crossencoder and get accuracy
accuracy, index_array, unsorted_scores = _run_crossencoder(
crossencoder,
dataloader,
logger,
context_len=biencoder_params["max_context_length"],
)
if args.interactive:
print("\naccurate (crossencoder) predictions:")
_print_colorful_text(text, samples)
# print crossencoder prediction
idx = 0
for entity_list, index_list, sample in zip(nns, index_array, samples):
e_id = entity_list[index_list[-1]]
e_title = id2title[e_id]
e_text = id2text[e_id]
e_url = id2url[e_id]
_print_colorful_prediction(
idx, sample, e_id, e_title, e_text, e_url, args.show_url
)
idx += 1
print()
else:
scores = []
predictions = []
for entity_list, index_list, scores_list in zip(
nns, index_array, unsorted_scores
):
index_list = index_list.tolist()
# descending order
index_list.reverse()
sample_prediction = []
sample_scores = []
for index in index_list:
e_id = entity_list[index]
e_title = id2title[e_id]
sample_prediction.append(e_title)
sample_scores.append(scores_list[index])
predictions.append(sample_prediction)
scores.append(sample_scores)
crossencoder_normalized_accuracy = -1
overall_unormalized_accuracy = -1
if not keep_all:
crossencoder_normalized_accuracy = accuracy
print(
"crossencoder normalized accuracy: %.4f"
% crossencoder_normalized_accuracy
)
if len(samples) > 0:
overall_unormalized_accuracy = (
crossencoder_normalized_accuracy * len(label_input) / len(samples)
)
print(
"overall unnormalized accuracy: %.4f" % overall_unormalized_accuracy
)
return (
biencoder_accuracy,
recall_at,
crossencoder_normalized_accuracy,
overall_unormalized_accuracy,
len(samples),
predictions,
scores,
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--interactive", "-i", action="store_true", help="Interactive mode."
)
# test_data
parser.add_argument(
"--test_mentions", dest="test_mentions", type=str, help="Test Dataset."
)
parser.add_argument(
"--test_entities", dest="test_entities", type=str, help="Test Entities."
)
# biencoder
parser.add_argument(
"--biencoder_model",
dest="biencoder_model",
type=str,
default="models/biencoder_wiki_large.bin",
help="Path to the biencoder model.",
)
parser.add_argument(
"--biencoder_config",
dest="biencoder_config",
type=str,
default="models/biencoder_wiki_large.json",
help="Path to the biencoder configuration.",
)
parser.add_argument(
"--entity_catalogue",
dest="entity_catalogue",
type=str,
# default="models/tac_entity.jsonl", # TAC-KBP
default="models/entity.jsonl", # ALL WIKIPEDIA!
help="Path to the entity catalogue.",
)
parser.add_argument(
"--entity_encoding",
dest="entity_encoding",
type=str,
# default="models/tac_candidate_encode_large.t7", # TAC-KBP
default="models/all_entities_large.t7", # ALL WIKIPEDIA!
help="Path to the entity catalogue.",
)
# crossencoder
parser.add_argument(
"--crossencoder_model",
dest="crossencoder_model",
type=str,
default="models/crossencoder_wiki_large.bin",
help="Path to the crossencoder model.",
)
parser.add_argument(
"--crossencoder_config",
dest="crossencoder_config",
type=str,
default="models/crossencoder_wiki_large.json",
help="Path to the crossencoder configuration.",
)
parser.add_argument(
"--top_k",
dest="top_k",
type=int,
default=10,
help="Number of candidates retrieved by biencoder.",
)
# output folder
parser.add_argument(
"--output_path",
dest="output_path",
type=str,
default="output",
help="Path to the output.",
)
parser.add_argument(
"--fast", dest="fast", action="store_true", help="only biencoder mode"
)
parser.add_argument(
"--show_url",
dest="show_url",
action="store_true",
help="whether to show entity url in interactive mode",
)
parser.add_argument(
"--faiss_index", type=str, default=None, help="whether to use faiss index",
)
parser.add_argument(
"--index_path", type=str, default=None, help="path to load indexer",
)
args = parser.parse_args()
logger = utils.get_logger(args.output_path)
models = load_models(args, logger)
run(args, logger, *models)