-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_disc_ner.py
2265 lines (1949 loc) · 101 KB
/
run_disc_ner.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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import sys
import json
import yaml
import math
import random
import argparse
import numpy as np
import pandas as pd
from typing import *
from tqdm import tqdm
from copy import deepcopy
from itertools import chain, product
from collections import defaultdict, Counter
use_wandb = False
if os.environ.get("WANDB_ENABLE", False):
try:
import wandb
use_wandb = True
"""
- https://github.com/wandb/examples
- https://docs.wandb.ai/guides/sweeps
"""
except ImportError:
use_wandb = False
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence
from transformers import (
BertConfig, BertPreTrainedModel, BertModel, BertTokenizerFast,
RobertaConfig, RobertaPreTrainedModel, RobertaModel, RobertaTokenizerFast,
PreTrainedModel, AdamW,
)
from transformers.file_utils import ModelOutput
from torchblocks.callback import ProgressBar
# from torchblocks.data.dataset import DatasetBase
from torchblocks.data.process_base import ProcessBase
from torchblocks.metrics.sequence_labeling.scheme import get_scheme
from torchblocks.metrics.sequence_labeling.precision_recall_fscore import _precision_recall_fscore_support
from torchblocks.metrics.sequence_labeling.seqTag_score import SequenceLabelingScore
from torchblocks.layers.layer_norm import ConditionalLayerNorm
from torchblocks.losses.focal_loss import FocalLoss
from torchblocks.losses.label_smoothing import LabelSmoothingCE
from torchblocks.core import TrainerBase
from torchblocks.utils.options import Argparser
from torchblocks.utils.logger import Logger
from torchblocks.utils.device import prepare_device
from torchblocks.utils.paths import check_dir, load_pickle, check_file, is_file
from torchblocks.utils.paths import find_all_checkpoints
from torchblocks.utils.seed import seed_everything
IGNORE_INDEX = -100
Span = NewType("Span", Tuple[int, int, str])
Entity = NewType("Entity", List[Span])
import logging
logger = logging.getLogger(__name__)
def default_data_collator(features: List[Dict[str, torch.Tensor]],
dynamic_batch=False,
dynamic_keys=[]) -> Dict[
str, Any]:
batch = {}
first = features[0]
max_input_length = first['input_ids'].size(0)
if dynamic_batch:
max_input_length = max([torch.sum(f["attention_mask"]) for f in features])
if "label" in first and first["label"] is not None:
label = first["label"].item() if isinstance(first["label"], torch.Tensor) else first["label"]
dtype = torch.long if isinstance(label, int) else torch.float
batch["labels"] = torch.tensor([f["label"] for f in features], dtype=dtype)
elif "label_ids" in first and first["label_ids"] is not None:
if isinstance(first["label_ids"], torch.Tensor):
batch["labels"] = torch.stack([f["label_ids"] for f in features])
else:
dtype = torch.long if type(first["label_ids"][0]) is int else torch.float
batch["labels"] = torch.tensor([f["label_ids"] for f in features], dtype=dtype)
# Handling of all other possible keys.
# Again, we will use the first element to figure out which key/values are not None for this model.
for k, v in first.items():
if k not in ("label", "label_ids") and v is not None and not isinstance(v, str):
bv = torch.stack([f[k] for f in features]) if isinstance(v, torch.Tensor) else torch.tensor(
[f[k] for f in features])
batch[k] = bv
if dynamic_batch:
for k in dynamic_keys:
if k not in batch: continue
if batch[k].dim() >= 2: batch[k] = batch[k][:, : max_input_length]
return batch
class DatasetBase(torch.utils.data.Dataset):
keys_to_truncate_on_dynamic_batch = ['input_ids', 'attention_mask', 'token_type_ids']
def __init__(self,
data_name,
data_dir,
data_type,
process_piplines: List[Callable],
max_examples: int = None,
use_cache: bool = False,
collate_dynamic: bool = True,
cached_features_file: str = None,
overwrite_cache: bool = False) -> None:
super().__init__()
self.data_dir = data_dir
self.data_name = data_name
if not is_file(data_name):
file_path = os.path.join(data_dir, data_name)
check_file(file_path)
self.examples = self.create_examples(self.read_data(file_path), data_type)
if max_examples is not None: self.examples = self.examples[: max_examples]
self.process_piplines = process_piplines if isinstance(process_piplines, list) else [process_piplines]
self.num_examples = len(self.examples)
self.num_labels = len(self.get_labels())
self.use_cache = use_cache
self.collate_dynamic = collate_dynamic
self.cached_features_file = cached_features_file
if self.cached_features_file is None: self.cached_features_file = ""
self.overwrite_cache = overwrite_cache
if self.use_cache:
self.create_cache()
def create_cache(self):
self.cached_features_file = os.path.join(self.data_dir, self.cached_features_file)
if is_file(self.cached_features_file) and not self.overwrite_cache:
logger.info("Loading features from cached file %s", self.cached_features_file)
self.features = torch.load(self.cached_features_file)
else:
logger.info(f"Creating features from dataset file at {self.data_dir}")
self.features = [
self.process_example(example) for example in
tqdm(self.examples, total=self.num_examples, desc="Converting examples to features...")]
# FIXED: is_file必须在文件存在情况下才返回True
# if is_file(self.cached_features_file):
if not os.path.isdir(self.cached_features_file):
logger.info("Saving features to cached file %s", self.cached_features_file)
torch.save(self.features, self.cached_features_file)
def __getitem__(self, index: int) -> Dict[str, torch.Tensor]:
if self.use_cache:
feature = self.features[index]
else:
feature = self.process_example(self.examples[index])
return feature
def __len__(self):
return self.num_examples
@classmethod
def get_labels(self) -> List[str]:
raise NotImplementedError('Method [get_labels] should be implemented.')
@classmethod
def label2id(cls):
return {label: i for i, label in enumerate(cls.get_labels())}
@classmethod
def id2label(cls):
return {i: label for i, label in enumerate(cls.get_labels())}
def read_data(self, input_file: str) -> Any:
raise NotImplementedError('Method [read_data] should be implemented.')
def create_examples(self, data: Any, set_type: str, **kwargs) -> List[Dict[str, Any]]:
raise NotImplementedError('Method [create_examples] should be implemented.')
def process_example(self, example: Dict[str, Any]) -> Dict[str, torch.Tensor]:
for proc in self.process_piplines:
if proc is None: continue
example = proc(example)
return example
def collate_fn(self, features: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
return default_data_collator(features,
dynamic_batch=self.collate_dynamic,
dynamic_keys=self.keys_to_truncate_on_dynamic_batch)
class SpanClassificationDataset(DatasetBase):
"""
Attributes
----------
examples:
!!! WARN: word-level
"""
keys_to_truncate_on_dynamic_batch = [
"input_ids", "attention_mask", "token_type_ids", "conditional_ids", "syntactic_upos_ids",
]
def __init__(
self,
data_name,
data_dir,
data_type,
process_piplines: List[Callable],
context_size: int = 0,
max_examples: int = None,
labels: List[str] = None,
use_cache: bool = False,
collate_dynamic: bool = True,
cached_features_file: str = None,
overwrite_cache: bool = False
) -> None:
self.labels = labels
self.context_size = max(0, context_size)
super().__init__(data_name, data_dir, data_type, process_piplines, max_examples,
use_cache,collate_dynamic, cached_features_file, overwrite_cache)
# add context
if self.context_size > 0:
examples = []
for i, example in tqdm(enumerate(self.examples), total=len(self.examples),
desc=f"Adding Context({self.context_size})..."):
examples.append(self.set_example_context(example, i))
self.examples = examples
def set_example_type(self, example):
is_overlap = False
is_discontinuous = False
if example["entities"] is not None:
entities = []
for entity in example["entities"]:
entities.append(set())
if len(entity) > 1:
is_discontinuous = True
for start, end, _, _ in entity:
for pos in range(start, end):
entities[-1].add(pos)
for i in range(len(entities)):
for j in range(i + 1, len(entities)):
entity_a, entity_b = entities[i], entities[j]
if len(entity_a.intersection(entity_b)) > 0:
is_overlap = True
example["is_overlap"] = is_overlap
example["is_discontinuous"] = is_discontinuous
return example
def set_example_context(self, example, example_no):
example = deepcopy(example)
# left context
left_context_size = 0
context_no = example_no
while True:
context_no -= 1
if context_no < 0:
break
context_size = max(0, self.context_size - left_context_size)
context_text = self.examples[context_no]["text"][- context_size: ]
left_context_size += len(context_text)
example["text"] = context_text + example["text"]
if left_context_size >= self.context_size:
break
# right context
right_context_size = 0
context_no = example_no
while True:
context_no += 1
if context_no >= len(self.examples):
break
context_size = max(0, self.context_size - right_context_size)
context_text = self.examples[context_no]["text"][: context_size]
right_context_size += len(context_text)
example["text"] = example["text"] + context_text
if right_context_size >= self.context_size:
break
example["sent_start"] = left_context_size
example["sent_end"] = len(example["text"]) - right_context_size
if example["entities"] is not None:
for entity in example["entities"]:
for i, (start, end, label, string) in enumerate(entity):
entity[i] = (start + left_context_size, end + left_context_size, label, string)
return example
def collate_fn(self, features: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
batch = {}
first = features[0]
max_input_length = None
if self.collate_dynamic:
max_input_length = max([torch.sum(f["attention_mask"]) for f in features])
for k in first.keys():
bv = None
if k in ["input_ids", "attention_mask", "token_type_ids", "conditional_ids", "syntactic_upos_ids"]:
bv = torch.stack([f[k] for f in features], dim=0) # (batch_size, sequence_length)
elif k in ["spans", "spans_mask", "labels"]:
if first[k] is not None:
bv = pad_sequence([f[k] for f in features], batch_first=True) # (batch_size, num_spans, *)
elif k in []:
bv = torch.stack([f[k] for f in features]) # (batch_size,)
elif k in []:
bv = [f[k] for f in features] # (batch_size,)
else:
continue
batch[k] = bv
if self.collate_dynamic:
for k in self.keys_to_truncate_on_dynamic_batch:
if k in batch:
if batch[k].dim() >= 2: batch[k] = batch[k][:, : max_input_length]
if batch["labels"] is None: batch.pop("labels")
return batch
class CadecDataset(SpanClassificationDataset):
"""
File Format:
``` txt
Remaining issue is chest spasm - - have been through tests ruling out heart , GERD , pneumonia , etc Spasms persist although less and less .
3,4 ADR|20,20 ADR
Last 48 hours , epsiodes seemed to increase again but may be attributable to some combination of muscle weakness and heavy non - stop rains we ' ve enjoyed for several days .
17,18 ADR
```
"""
@classmethod
def get_labels(cls) -> List[str]:
return ["O", "II-N"] + [f"{prefix}-{label}" for label in (
"ADR",
) for prefix in ("BI", "BE", "II", "IE")]
def read_data(self, input_file: str) -> Any:
with open(input_file, "r", encoding="utf-8") as f:
lines = [line.rstrip("\n") for line in f.readlines()]
return lines
def create_examples(self, data: Any, data_type: str, **kwargs) -> List[Dict[str, Any]]:
texts = data[0::3]; annos = data[1::3]
assert len(texts) == len(annos)
examples = []
for i, (text, anno) in enumerate(zip(texts, annos)):
guid = f"{data_type}-{i}"
words = text.split() # based on whitespace
entities = None
if data_type != "test":
entities = []
if anno != "":
for entity in anno.split("|"):
entities.append([])
positions, label = entity.split(" ")
positions = list(map(int, positions.split(",")))
num_spans = len(positions) // 2
for j in range(num_spans):
start, end = positions[j * 2], positions[j * 2 + 1] + 1 # 左闭右开
entities[-1].append((start, end, label, words[start: end]))
examples.append(self.set_example_type(dict(guid=guid, text=words, entities=entities, sent_start=0, sent_end=len(words))))
return examples
class ShAReDataset(SpanClassificationDataset):
@classmethod
def get_labels(cls) -> List[str]:
return ["O", "II-N"] + [f"{prefix}-{label}" for label in (
"Disorder",
) for prefix in ("BI", "BE", "II", "IE")]
def read_data(self, input_file: str) -> Any:
with open(input_file, "r", encoding="utf-8") as f:
lines = [line.rstrip("\n") for line in f.readlines()]
return lines
def create_examples(self, data: Any, data_type: str, **kwargs) -> List[Dict[str, Any]]:
texts = data[0::3]; annos = data[1::3]
assert len(texts) == len(annos)
examples = []
for i, (text, anno) in enumerate(zip(texts, annos)):
guid = f"{data_type}-{i}"
words = text.split() # based on whitespace
entities = None
if data_type != "test":
entities = []
if anno != "":
for entity in anno.split("|"):
entities.append([])
positions, label = entity.split(" ")
positions = list(map(int, positions.split(",")))
num_spans = len(positions) // 2
for j in range(num_spans):
start, end = positions[j * 2], positions[j * 2 + 1]
if start > end:
print(text)
print(anno)
print(f"({start}, {end}) -> ({end}, {start})")
start, end = end, start
end += 1 # 左闭右开
entities[-1].append((start, end, label, words[start: end]))
examples.append(self.set_example_type(dict(guid=guid, text=words, entities=entities, sent_start=0, sent_end=len(words))))
return examples
class LevelConvertorBase:
do_convert_check = False
def _convert(self, raw: str) -> Tuple[List[str], List[List[int]]]:
raise NotImplementedError
def _forward(self, tokens: List[str]) -> str:
raise NotImplementedError
def _backward(self, raw: str) -> List[str]:
return self._convert(raw)[0]
def forward(self, raw, raw_level_entities):
tokens, offset_mapping = self._convert(raw)
raw2token_map = dict()
for i, (raw_start, raw_end) in enumerate(offset_mapping):
for j in range(raw_start, raw_end):
raw2token_map[j] = i
if raw_level_entities is not None:
token_level_entities = []
for raw_level_entity in raw_level_entities:
token_level_entity= []
for raw_level_start, raw_level_end, label, span_raws in raw_level_entity:
try:
token_level_start = raw2token_map[raw_level_start]
token_level_end = raw2token_map[raw_level_end - 1] + 1
except KeyError as e:
import pdb; pdb.set_trace()
span_tokens = tokens[token_level_start: token_level_end]
token_level_string = self._forward(span_tokens)
raw_level_string = raw[raw_level_start: raw_level_end]
try:
assert token_level_string == raw_level_string
except AssertionError as e:
if self.do_convert_check:
print(e)
import pdb; pdb.set_trace()
token_level_entity.append((token_level_start, token_level_end, label, span_tokens))
token_level_entities.append(token_level_entity)
else:
token_level_entities = None
return tokens, token_level_entities
def backward(self, tokens, token_level_entities):
chars = self._forward(tokens)
tokens, offset_mapping = self._convert(chars)
if token_level_entities is not None:
char_level_entities = []
token2char_map = dict(enumerate(offset_mapping))
for token_level_entity in token_level_entities:
char_level_entity = []
for token_level_start, token_level_end, label, span_tokens in token_level_entity:
char_level_start, char_level_end = float('inf'), float('-inf')
for i in range(token_level_start, token_level_end):
start, end = token2char_map[i]
char_level_start = min(char_level_start, start)
char_level_end = max(char_level_end, end )
span_tokens = tokens[token_level_start: token_level_end]
token_level_string = self._forward(span_tokens)
char_level_string = chars[char_level_start: char_level_end]
try:
assert token_level_string == char_level_string
except AssertionError as e:
if self.do_convert_check:
print(e)
import pdb; pdb.set_trace()
char_level_entity.append((char_level_start, char_level_end, label, char_level_string))
char_level_entities.append(char_level_entity)
else:
char_level_entities = None
return chars, char_level_entities
class LevelConvertorWhitespace(LevelConvertorBase):
"""
Example:
>>> text = "Unified Named Entity Recognition as Word-Word Relation Classification"
>>> entities = [
>>> [(8, 8 + len("Named Entity Recognition"), "x", "Named Entity Recognition")],
>>> ]
>>> convertor = LevelConvertorWhitespace()
>>> tokens2, entities2 = convertor.forward(text, entities)
>>> chars3, entities3 = convertor.backward(tokens2, entities2)
"""
def _convert(self, text):
segments = re.split(r"( )", text)
words = []; offset_mapping = []
word_idx = 0; start = 0
for seg in segments:
if seg == " ":
start += 1
continue
words.append(seg)
word_idx += 1
offset_mapping.append((start, start + len(seg)))
start += len(seg)
return words, offset_mapping
def _forward(self, words):
return " ".join(words)
class LevelConvertorHuggingFace(LevelConvertorBase):
"""
Example:
>>> text = "Unified Named Entity Recognition as Word-Word Relation Classification"
>>> entities = [
>>> [(8, 8 + len("Named Entity Recognition"), "x", "Named Entity Recognition")],
>>> ]
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("roberta-base")
>>> convertor = LevelConvertorHuggingFace(tokenizer)
>>> tokens2, entities2 = convertor.forward(text, entities)
>>> chars3, entities3 = convertor.backward(tokens2, entities2)
"""
def __init__(self, tokenizer) -> None:
super().__init__()
self.tokenizer = tokenizer
def _convert(self, text):
inputs = self.tokenizer(text, return_offsets_mapping=True, return_tensors="np")
tokens = self.tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])[1:-1]
offset_mapping = inputs["offset_mapping"][0].tolist()[1:-1] # [CLS], [SEP]
return tokens, offset_mapping
def _forward(self, tokens):
return self.tokenizer.convert_tokens_to_string(tokens).strip()
class LevelConvertorHuggingFaceZh(LevelConvertorHuggingFace):
def _convert(self, text):
tokens = [ch if ch in self.tokenizer.vocab else
self.tokenizer.unk_token for ch in text]
inputs = self.tokenizer(tokens, is_split_into_words=True, return_tensors="np",)
tokens = self.tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])[1:-1]
offset_mapping = [[i, i + 1] for i, ch in enumerate(tokens)]
return tokens, offset_mapping
class ProcessConvertLevel(ProcessBase):
def __init__(self, tokenizer, conversion, lang="en"):
self.tokenizer = tokenizer
self.conversion = conversion
self.whitespace_converter = LevelConvertorWhitespace()
if lang == "en":
self.huggingface_converter = LevelConvertorHuggingFace(tokenizer)
elif lang == "zh":
self.huggingface_converter = LevelConvertorHuggingFaceZh(tokenizer)
self.conversion2func_map = {
"word2char": self.word_to_char,
"char2word": self.char_to_word,
"char2token": self.char_to_token,
"token2char": self.token_to_char,
"word2token": self.word_to_token,
"token2word": self.token_to_word,
}
self.convert_func = self.conversion2func_map[self.conversion]
def __call__(self, example):
example = deepcopy(example)
converted, entities = self.convert_func(
example["text"], example["entities"])
if "sent_start" in example and "sent_end" in example:
sent_start, sent_end = example["sent_start"], example["sent_end"]
sentence = [[(sent_start, sent_end, "_", example["text"][sent_start: sent_end])]]
_, sentence = self.convert_func(example["text"], sentence)
example["sent_start"], example["sent_end"] = sentence[0][0][:2]
example["text"] = converted
example["entities"] = entities
return example
def char_to_word(self, chars, char_level_entities):
return self.whitespace_converter.forward(chars, char_level_entities)
def word_to_char(self, words, word_level_entities):
return self.whitespace_converter.backward(words, word_level_entities)
def char_to_token(self, chars, char_level_entities):
return self.huggingface_converter.forward(chars, char_level_entities)
def token_to_char(self, tokens, token_level_entities):
return self.huggingface_converter.backward(tokens, token_level_entities)
def word_to_token(self, words, word_level_entities):
return self.char_to_token(*self.word_to_char(words, word_level_entities))
def token_to_word(self, tokens, token_level_entities):
return self.char_to_word(*self.token_to_char(tokens, token_level_entities))
class ProcessMergeDiscontinuousSpans(ProcessBase):
def __call__(self, example):
if example["entities"] is None:
return example
example = deepcopy(example)
entities = []
for entity in example["entities"]:
if len(entity) == 1:
entities.append(entity)
else:
entities.append([])
entity = sorted(entity, key=lambda x: x[:2])
for span in entity:
start, end, label, string = span
if len(entities[-1]) == 0:
entities[-1].append(span)
continue
last_start, last_end, last_label, last_string = entities[-1][-1]
if label != last_label or example["text"][last_end: start].strip() != "":
entities[-1].append(span)
continue
last_entity = entities[-1].pop(-1)
new_string = example["text"][last_start: end]
try:
assert new_string == last_string + " " + string
except AssertionError:
import pdb; pdb.set_trace()
merged_span = (last_start, end, label, new_string)
entities[-1].append(merged_span)
# print(f"\nMerge {last_entity}, {span} to {merged_span}")
example["entities"] = entities
return example
class ProcessExample2Feature(ProcessBase):
def __init__(self, label2id, tokenizer, max_sequence_length,
max_span_length, negative_sampling, keep_full_spans, stanza_nlp=None):
super().__init__()
self.label2id = label2id
self.tokenizer = tokenizer
self.max_sequence_length = max_sequence_length
self.max_span_length = max_span_length
self.negative_sampling = negative_sampling
self.converter = ProcessConvertLevel(tokenizer, "char2token")
self.keep_full_spans = keep_full_spans
self.stanza_nlp = stanza_nlp
if stanza_nlp is not None:
self.stanza_upos_unit2id = self.stanza_nlp.processors['pos'].vocab._vocabs['upos']._unit2id
def _encode_text(self, text: str):
return self.tokenizer(
text,
padding="max_length",
truncation="longest_first",
max_length=self.max_sequence_length,
return_offsets_mapping=True,
return_tensors="pt",
)
def _encode_spans(self, input_length, sent_start, sent_end, word_ids):
spans = []; spans_mask = []
sent_start = min(sent_start, self.max_sequence_length - 1)
sent_end = min(sent_end, self.max_sequence_length - 1)
span_starts = np.arange(sent_start, sent_end) + 1 # (sequence_length,)
span_lengths = np.arange(self.max_span_length) # (input_length,)
span_ends = span_starts.reshape(-1, 1) + span_lengths # (sequence_length, input_length)
span_starts = np.expand_dims(span_starts, 1) \
.repeat(self.max_span_length, axis=1) # (sequence_length, input_length)
span_starts, span_ends = span_starts.reshape(-1), span_ends.reshape(-1)
spans = np.stack([span_starts, span_ends], axis=-1) # (sequence_length * input_length, 2)
spans = spans[span_ends <= sent_end] # (num_spans, 2)
if self.keep_full_spans:
word_ids = word_ids[sent_start: sent_end]
is_start = np.array(word_ids) != np.array([-1] + word_ids[:-1])
is_end = np.array(word_ids) != np.array(word_ids[1:] + [-1] )
spans = spans[is_start[spans[:, 0] - 1] & is_end[spans[:, 1] - 1]]
spans = [tuple(span) for span in spans.tolist()]
spans_mask = np.ones(len(spans), dtype=np.int).tolist()
return spans, spans_mask
def _encode_syntactic(self, text, bert_offset_mapping):
doc = self.stanza_nlp([text.split()]).to_dict()
offset = 0
upos = []; deprel = []
stanza_offset_mapping = []
for sent in doc:
for token in sent:
upos.append(token["upos"])
deprel.append((
token["id"] + offset - 1,
token["head"] - 1,
token["deprel"],
))
stanza_offset_mapping.append((
token["start_char"],
token["end_char"],
))
offset += len(sent)
j = 0
syntactic_upos_ids = []
for i, (start, end) in enumerate(bert_offset_mapping):
if start == end:
syntactic_upos_ids.append(self.stanza_upos_unit2id["<PAD>"])
continue
syntactic_upos_ids.append(self.stanza_upos_unit2id[upos[j]])
if end >= stanza_offset_mapping[j][1]:
j += 1
return syntactic_upos_ids
def _encode_labels(self, entities, spans, input_length, offset_mapping):
span2label_map = defaultdict(list)
for entity in entities:
# keep entities which are not truncated
if any([start >= input_length or end >= start >= input_length for start, end, *_ in entity]):
continue
# span-to-label map(token-level)
num_spans = len(entity)
entity = sorted(entity, key=lambda x: (x[0], x[1]))
for i, (start, end, label, string) in enumerate(entity):
start, end = start + 1, end + 1 # CLS, SEP
start_prefix = "B" if i == 0 else "I"
end_prefix = "E" if i == num_spans - 1 else "I"
prefix = start_prefix + end_prefix
span = (start, end - 1)
label = prefix + "-" + label
span2label_map[span].append(label)
for span_a, span_b in zip(entity[:-1], entity[1:]):
start, end = span_a[1], span_b[0]
start, end = start + 1, end + 1 # CLS, SEP
span = (start, end - 1)
label = "II" + "-" + "N"
span2label_map[span].append(label)
labels_onehot = []
for span in spans:
label_onehot = [self.label2id["O"]] * len(self.label2id)
for label in span2label_map.get(span, []):
label = self.label2id[label]
label_onehot[label] = 1
labels_onehot.append(label_onehot)
return labels_onehot
def __call__(self, example):
text: str = example["text"]
inputs = self._encode_text(text)
word_ids = inputs.word_ids()[1:-1]
inputs = {k: v.squeeze(0) for k, v in inputs.items()}
input_length = inputs["attention_mask"].sum().item()
offset_mapping = inputs["offset_mapping"].numpy().tolist()
example = self.converter(example) # char -> token
tokens, entities = example["text"], example["entities"]
sent_start = example.get("sent_start", 0)
sent_end = example.get("sent_end", len(tokens))
# encode spans
spans, spans_mask = self._encode_spans(input_length, sent_start, sent_end, word_ids)
inputs["spans"], inputs["spans_mask"] = torch.tensor(spans), torch.tensor(spans_mask)
# encode pos & depparse
if self.stanza_nlp is not None:
syntactic_upos_ids = self._encode_syntactic(text, offset_mapping)
inputs["syntactic_upos_ids"] = torch.tensor(syntactic_upos_ids)
if entities is None:
inputs["labels"] = None
return inputs
labels = self._encode_labels(entities, spans, input_length - 2, offset_mapping)
inputs["labels"] = torch.tensor(labels) # (num_spans,)
return inputs
class CadecProcessExample2Feature(ProcessExample2Feature):
pass
class ShAReProcessExample2Feature(ProcessExample2Feature):
pass
def load_dataset(data_class, process_class, data_name, data_dir, data_type, tokenizer, max_sequence_length,
context_size, max_span_length, negative_sampling, keep_full_spans, stanza_nlp=None, **kwargs):
process_piplines = [
ProcessConvertLevel(tokenizer, "word2char") if data_class in [ # english
CadecDataset, ShAReDataset,
] else None,
ProcessMergeDiscontinuousSpans(),
process_class(
data_class.label2id(), tokenizer, max_sequence_length,
max_span_length, negative_sampling, keep_full_spans, stanza_nlp,
),
]
return data_class(data_name, data_dir, data_type, process_piplines,
context_size=context_size, max_examples=None, use_cache=True, **kwargs)
class XBilinear(nn.Module):
def __init__(self, in1_features: int, in2_features: int, out_features: int, bias: bool = True, div: int = 1) -> None:
super().__init__()
self.features1_projection = nn.Linear(in1_features, in1_features // div)
self.features2_projection = nn.Linear(in2_features, in2_features // div)
self.bilinear = nn.Bilinear(in1_features // div, in2_features // div, out_features, bias=bias)
def forward(self, input1: torch.Tensor, input2: torch.Tensor) -> torch.Tensor:
input1 = self.features1_projection(input1)
input2 = self.features2_projection(input2)
return self.bilinear(input1, input2)
class XBiaffineRel(nn.Module):
def __init__(self, hidden_size: int, out_features: int, bias: bool = True, div: int = 1) -> None:
super().__init__()
self.W1 = nn.Parameter(torch.Tensor(hidden_size, hidden_size // div, out_features))
self.W2 = nn.Parameter(torch.Tensor(hidden_size, hidden_size // div))
self.linear = nn.Linear(hidden_size + hidden_size + hidden_size // div, out_features, bias=False)
if bias:
self.bias = nn.Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
relative_positions_embeddings = self._generate_relative_positions_embeddings(512, hidden_size // div)
self.register_buffer("relative_positions_embeddings", relative_positions_embeddings)
def reset_parameters(self) -> None:
bound = 1 / math.sqrt(self.W2.size(1))
init.uniform_(self.W1, -bound, bound)
init.uniform_(self.W2, -bound, bound)
if self.bias is not None:
init.uniform_(self.bias, -bound, bound)
@classmethod
def _generate_relative_positions_embeddings(cls, length, depth, max_relative_position=127):
vocab_size = max_relative_position * 2 + 1
range_vec = torch.arange(length)
range_mat = range_vec.repeat(length).view(length, length)
distance_mat = range_mat - torch.t(range_mat)
distance_mat_clipped = torch.clamp(distance_mat, -max_relative_position, max_relative_position)
final_mat = distance_mat_clipped + max_relative_position
embeddings_table = np.zeros([vocab_size, depth])
for pos in range(vocab_size):
for i in range(depth // 2):
embeddings_table[pos, 2 * i] = np.sin(pos / np.power(10000, 2 * i / depth))
embeddings_table[pos, 2 * i + 1] = np.cos(pos / np.power(10000, 2 * i / depth))
embeddings_table_tensor = torch.tensor(embeddings_table).float()
flat_relative_positions_matrix = final_mat.view(-1)
one_hot_relative_positions_matrix = torch.nn.functional.one_hot(
flat_relative_positions_matrix,num_classes=vocab_size).float()
embeddings = torch.matmul(one_hot_relative_positions_matrix, embeddings_table_tensor)
my_shape = list(final_mat.size())
my_shape.append(depth)
embeddings = embeddings.view(my_shape)
return embeddings
def forward(self, input1: torch.Tensor, input2: torch.Tensor, spans: torch.Tensor) -> torch.Tensor:
"""
Parameters
----------
input1: torch.Tensor[batch_size, num_spans, hidden_size]
input2: torch.Tensor[batch_size, num_spans, hidden_size]
spans: torch.Tensor[batch_size, num_spans, 2]
"""
pe = self.relative_positions_embeddings[spans[..., 0], spans[..., 1]]
# [x; y; p] W3
output = self.linear(torch.cat([input1, input2, pe], dim=-1))
# (x W1)(y W2 + p) / d
input1 = torch.einsum("bnh,hdc->bndc", input1, self.W1)
input2 = torch.einsum("bnh,hd->bnd", input2, self.W2)
scale = math.sqrt(self.relative_positions_embeddings.size(-1))
output = output + torch.einsum("bndc,bnd->bnc", input1, input2 + pe) / scale
if self.bias is not None:
output = output + self.bias
return output
class GCNConv(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.linear = nn.Linear(in_features, out_features)
def forward(self, x, A):
# x: (batch_size, num_nodes, in_features)
# A: (batch_size, num_nodes, num_nodes)
return F.relu(torch.einsum("bmn,bnh->bmh", A, self.linear(x)))
class GCN(nn.Module):
def __init__(self, in_features, out_features, hidden_size,
num_layers=2, p=0.1, residual=False, symmetric=True):
super().__init__()
assert num_layers > 0
self.layers = nn.ModuleList([])
n_dims = in_features
for i in range(num_layers - 1):
self.layers.append(GCNConv(n_dims, hidden_size))
n_dims = hidden_size
self.layers.append(GCNConv(n_dims, out_features))
self.relu = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(p)
self.symmetric = symmetric
self.residual = residual
def normalize(self, A, symmetric):
# A = A+I
A = A + torch.eye(A.size(0), device=A.device)
# 所有节点的度
d = A.sum(1)
if symmetric:
# D = D^-1/2
D = torch.diag(torch.pow(d, -0.5))
D = D.mm(A).mm(D)
else:
# D=D^-1
D = torch.diag(torch.pow(d, -1))
D = D.mm(A)
return D
def forward(self, x, A):
if self.residual:
res = x
A = torch.stack([
self.normalize(a, self.symmetric) for a in A
], dim=0)
for layer in self.layers:
x = layer(x, A)
x = self.dropout(x)
if self.residual:
x = x + res
return x
class SpanClassificationHead(nn.Module):
def __init__(self, hidden_size, num_labels, max_span_length, width_embedding_size,
do_projection=False, do_biaffine=False, do_biaffine_rel=False,
extract_method="endpoint", do_gcn=False, gcn_hidden_size=64, gcn_num_layers=2,
gcn_dropout=0.1, gcn_residual=False):
super().__init__()
self.width_embedding = nn.Embedding(max_span_length + 1, width_embedding_size)
self.do_projection = do_projection
if self.do_projection:
self.start_projection = nn.Linear(hidden_size, hidden_size)
self.end_projection = nn.Linear(hidden_size, hidden_size)
extract_method_func_map = {
"endpoint": (
self.forward_endpoint,
hidden_size * 2,
),
"maxpool": (
lambda sequence_output, spans: self.forward_pool(
sequence_output, spans, pool_method="max"),
hidden_size,
),
"meanpool": (
lambda sequence_output, spans: self.forward_pool(
sequence_output, spans, pool_method="mean"),
hidden_size,
),
"endpoint-pool": (
self.forward_endpoint_pool,
hidden_size * 4,
),
"cln": (
self.forward_cln,
hidden_size * 2,
)
}
self.forward, num_features = extract_method_func_map[extract_method]
if extract_method == "cln":
self.head2tail_cln = ConditionalLayerNorm(hidden_size, hidden_size)
self.tail2head_cln = ConditionalLayerNorm(hidden_size, hidden_size)