Upload BertForMorphTagging.py with huggingface_hub
Browse files- BertForMorphTagging.py +212 -0
BertForMorphTagging.py
ADDED
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import OrderedDict
|
2 |
+
from operator import itemgetter
|
3 |
+
from transformers.utils import ModelOutput
|
4 |
+
import torch
|
5 |
+
from torch import nn
|
6 |
+
from typing import Dict, List, Tuple, Optional
|
7 |
+
from dataclasses import dataclass
|
8 |
+
from transformers import BertPreTrainedModel, BertModel, BertTokenizerFast
|
9 |
+
|
10 |
+
ALL_POS = ['DET', 'NOUN', 'VERB', 'CCONJ', 'ADP', 'PRON', 'PUNCT', 'ADJ', 'ADV', 'SCONJ', 'NUM', 'PROPN', 'AUX', 'X', 'INTJ', 'SYM']
|
11 |
+
ALL_PREFIX_POS = ['SCONJ', 'DET', 'ADV', 'CCONJ', 'ADP', 'NUM']
|
12 |
+
ALL_SUFFIX_POS = ['none', 'ADP_PRON', 'PRON']
|
13 |
+
ALL_FEATURES = [
|
14 |
+
('Gender', ['none', 'Masc', 'Fem', 'Fem,Masc']),
|
15 |
+
('Number', ['none', 'Sing', 'Plur', 'Plur,Sing', 'Dual', 'Dual,Plur']),
|
16 |
+
('Person', ['none', '1', '2', '3', '1,2,3']),
|
17 |
+
('Tense', ['none', 'Past', 'Fut', 'Pres', 'Imp'])
|
18 |
+
]
|
19 |
+
|
20 |
+
@dataclass
|
21 |
+
class MorphLogitsOutput(ModelOutput):
|
22 |
+
prefix_logits: torch.FloatTensor = None
|
23 |
+
pos_logits: torch.FloatTensor = None
|
24 |
+
features_logits: List[torch.FloatTensor] = None
|
25 |
+
suffix_logits: torch.FloatTensor = None
|
26 |
+
suffix_features_logits: List[torch.FloatTensor] = None
|
27 |
+
|
28 |
+
def detach(self):
|
29 |
+
return MorphLogitsOutput(self.prefix_logits.detach(), self.pos_logits.detach(), [logits.deatch() for logits in self.features_logits], self.suffix_logits.detach(), [logits.deatch() for logits in self.suffix_features_logits])
|
30 |
+
|
31 |
+
|
32 |
+
@dataclass
|
33 |
+
class MorphTaggingOutput(ModelOutput):
|
34 |
+
loss: Optional[torch.FloatTensor] = None
|
35 |
+
logits: Optional[MorphLogitsOutput] = None
|
36 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
37 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
38 |
+
|
39 |
+
@dataclass
|
40 |
+
class MorphLabels(ModelOutput):
|
41 |
+
prefix_labels: Optional[torch.FloatTensor] = None
|
42 |
+
pos_labels: Optional[torch.FloatTensor] = None
|
43 |
+
features_labels: Optional[List[torch.FloatTensor]] = None
|
44 |
+
suffix_labels: Optional[torch.FloatTensor] = None
|
45 |
+
suffix_features_labels: Optional[List[torch.FloatTensor]] = None
|
46 |
+
|
47 |
+
def detach(self):
|
48 |
+
return MorphLabels(self.prefix_labels.detach(), self.pos_labels.detach(), [labels.detach() for labels in self.features_labels], self.suffix_labels.detach(), [labels.detach() for labels in self.suffix_features_labels])
|
49 |
+
|
50 |
+
def to(self, device):
|
51 |
+
return MorphLabels(self.prefix_labels.to(device), self.pos_labels.to(device), [feat.to(device) for feat in self.features_labels], self.suffix_labels.to(device), [feat.to(device) for feat in self.suffix_features_labels])
|
52 |
+
|
53 |
+
class BertMorphTaggingHead(nn.Module):
|
54 |
+
def __init__(self, config):
|
55 |
+
super().__init__()
|
56 |
+
self.config = config
|
57 |
+
|
58 |
+
self.num_prefix_classes = len(ALL_PREFIX_POS)
|
59 |
+
self.num_pos_classes = len(ALL_POS)
|
60 |
+
self.num_suffix_classes = len(ALL_SUFFIX_POS)
|
61 |
+
self.num_features_classes = list(map(len, map(itemgetter(1), ALL_FEATURES)))
|
62 |
+
# we need a classifier for prefix cls and POS cls
|
63 |
+
# the prefix will use BCEWithLogits for multiple labels cls
|
64 |
+
self.prefix_cls = nn.Linear(config.hidden_size, self.num_prefix_classes)
|
65 |
+
# and pos + feats will use good old cross entropy for single label
|
66 |
+
self.pos_cls = nn.Linear(config.hidden_size, self.num_pos_classes)
|
67 |
+
self.features_cls = nn.ModuleList([nn.Linear(config.hidden_size, len(features)) for _, features in ALL_FEATURES])
|
68 |
+
# and suffix + feats will also be cross entropy
|
69 |
+
self.suffix_cls = nn.Linear(config.hidden_size, self.num_suffix_classes)
|
70 |
+
self.suffix_features_cls = nn.ModuleList([nn.Linear(config.hidden_size, len(features)) for _, features in ALL_FEATURES])
|
71 |
+
|
72 |
+
def forward(
|
73 |
+
self,
|
74 |
+
hidden_states: torch.Tensor,
|
75 |
+
labels: Optional[MorphLabels] = None):
|
76 |
+
# run each of the classifiers on the transformed output
|
77 |
+
prefix_logits = self.prefix_cls(hidden_states)
|
78 |
+
pos_logits = self.pos_cls(hidden_states)
|
79 |
+
suffix_logits = self.suffix_cls(hidden_states)
|
80 |
+
features_logits = [cls(hidden_states) for cls in self.features_cls]
|
81 |
+
suffix_features_logits = [cls(hidden_states) for cls in self.suffix_features_cls]
|
82 |
+
|
83 |
+
loss = None
|
84 |
+
if labels is not None:
|
85 |
+
# step 1: prefix labels loss
|
86 |
+
loss_fct = nn.BCEWithLogitsLoss(weight=(labels.prefix_labels != -100).float())
|
87 |
+
loss = loss_fct(prefix_logits, labels.prefix_labels)
|
88 |
+
# step 2: pos labels loss
|
89 |
+
loss_fct = nn.CrossEntropyLoss()
|
90 |
+
loss += loss_fct(pos_logits.view(-1, self.num_pos_classes), labels.pos_labels.view(-1))
|
91 |
+
# step 2b: features
|
92 |
+
for feat_logits,feat_labels,num_features in zip(features_logits, labels.features_labels, self.num_features_classes):
|
93 |
+
loss += loss_fct(feat_logits.view(-1, num_features), feat_labels.view(-1))
|
94 |
+
# step 3: suffix logits loss
|
95 |
+
loss += loss_fct(suffix_logits.view(-1, self.num_suffix_classes), labels.suffix_labels.view(-1))
|
96 |
+
# step 3b: suffix features
|
97 |
+
for feat_logits,feat_labels,num_features in zip(suffix_features_logits, labels.suffix_features_labels, self.num_features_classes):
|
98 |
+
loss += loss_fct(feat_logits.view(-1, num_features), feat_labels.view(-1))
|
99 |
+
|
100 |
+
return loss, MorphLogitsOutput(prefix_logits, pos_logits, features_logits, suffix_logits, suffix_features_logits)
|
101 |
+
|
102 |
+
class BertForMorphTagging(BertPreTrainedModel):
|
103 |
+
|
104 |
+
def __init__(self, config):
|
105 |
+
super().__init__(config)
|
106 |
+
|
107 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
108 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
109 |
+
self.morph = BertMorphTaggingHead(config)
|
110 |
+
|
111 |
+
# Initialize weights and apply final processing
|
112 |
+
self.post_init()
|
113 |
+
|
114 |
+
def forward(
|
115 |
+
self,
|
116 |
+
input_ids: Optional[torch.Tensor] = None,
|
117 |
+
attention_mask: Optional[torch.Tensor] = None,
|
118 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
119 |
+
position_ids: Optional[torch.Tensor] = None,
|
120 |
+
labels: Optional[MorphLabels] = None,
|
121 |
+
head_mask: Optional[torch.Tensor] = None,
|
122 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
123 |
+
output_attentions: Optional[bool] = None,
|
124 |
+
output_hidden_states: Optional[bool] = None,
|
125 |
+
return_dict: Optional[bool] = None,
|
126 |
+
):
|
127 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
128 |
+
|
129 |
+
bert_outputs = self.bert(
|
130 |
+
input_ids,
|
131 |
+
attention_mask=attention_mask,
|
132 |
+
token_type_ids=token_type_ids,
|
133 |
+
position_ids=position_ids,
|
134 |
+
head_mask=head_mask,
|
135 |
+
inputs_embeds=inputs_embeds,
|
136 |
+
output_attentions=output_attentions,
|
137 |
+
output_hidden_states=output_hidden_states,
|
138 |
+
return_dict=return_dict,
|
139 |
+
)
|
140 |
+
|
141 |
+
hidden_states = bert_outputs[0]
|
142 |
+
hidden_states = self.dropout(hidden_states)
|
143 |
+
|
144 |
+
loss, logits = self.morph(hidden_states, labels)
|
145 |
+
|
146 |
+
if not return_dict:
|
147 |
+
return (loss,logits) + bert_outputs[2:]
|
148 |
+
|
149 |
+
return MorphTaggingOutput(
|
150 |
+
loss=loss,
|
151 |
+
logits=logits,
|
152 |
+
hidden_states=bert_outputs.hidden_states,
|
153 |
+
attentions=bert_outputs.attentions,
|
154 |
+
)
|
155 |
+
|
156 |
+
def predict(self, sentences: List[str], tokenizer: BertTokenizerFast, padding='longest'):
|
157 |
+
# tokenize the inputs and convert them to relevant device
|
158 |
+
inputs = tokenizer(sentences, padding=padding, truncation=True, return_tensors='pt')
|
159 |
+
inputs = {k:v.to(self.device) for k,v in inputs.items()}
|
160 |
+
# calculate the logits
|
161 |
+
logits = self.forward(**inputs, return_dict=True).logits
|
162 |
+
return parse_logits(inputs['input_ids'].tolist(), sentences, tokenizer, logits)
|
163 |
+
|
164 |
+
def parse_logits(input_ids: List[List[int]], sentences: List[str], tokenizer: BertTokenizerFast, logits: MorphLogitsOutput):
|
165 |
+
prefix_logits, pos_logits, feats_logits, suffix_logits, suffix_feats_logits = \
|
166 |
+
logits.prefix_logits, logits.pos_logits, logits.features_logits, logits.suffix_logits, logits.suffix_features_logits
|
167 |
+
|
168 |
+
prefix_predictions = (prefix_logits > 0.5).int().tolist() # Threshold at 0.5 for multi-label classification
|
169 |
+
pos_predictions = pos_logits.argmax(axis=-1).tolist()
|
170 |
+
suffix_predictions = suffix_logits.argmax(axis=-1).tolist()
|
171 |
+
feats_predictions = [logits.argmax(axis=-1).tolist() for logits in feats_logits]
|
172 |
+
suffix_feats_predictions = [logits.argmax(axis=-1).tolist() for logits in suffix_feats_logits]
|
173 |
+
|
174 |
+
# create the return dictionary
|
175 |
+
# for each sentence, return a dict object with the following files { text, tokens }
|
176 |
+
# Where tokens is a list of dicts, where each dict is:
|
177 |
+
# { pos: str, feats: dict, prefixes: List[str], suffix: str | bool, suffix_feats: dict | None}
|
178 |
+
special_toks = tokenizer.all_special_tokens
|
179 |
+
ret = []
|
180 |
+
for sent_idx,sentence in enumerate(sentences):
|
181 |
+
input_id_strs = tokenizer.convert_ids_to_tokens(input_ids[sent_idx])
|
182 |
+
# iterate through each token in the sentence, ignoring special tokens
|
183 |
+
tokens = []
|
184 |
+
for token_idx,token_str in enumerate(input_id_strs):
|
185 |
+
if token_str in special_toks: continue
|
186 |
+
if token_str.startswith('##'):
|
187 |
+
tokens[-1]['token'] += token_str[2:]
|
188 |
+
continue
|
189 |
+
tokens.append(dict(
|
190 |
+
token=token_str,
|
191 |
+
pos=ALL_POS[pos_predictions[sent_idx][token_idx]],
|
192 |
+
feats=get_features_dict_from_predictions(feats_predictions, (sent_idx, token_idx)),
|
193 |
+
prefixes=[ALL_PREFIX_POS[idx] for idx,i in enumerate(prefix_predictions[sent_idx][token_idx]) if i > 0],
|
194 |
+
suffix=get_suffix_or_false(ALL_SUFFIX_POS[suffix_predictions[sent_idx][token_idx]]),
|
195 |
+
))
|
196 |
+
if tokens[-1]['suffix']:
|
197 |
+
tokens[-1]['suffix_feats'] = get_features_dict_from_predictions(suffix_feats_predictions, (sent_idx, token_idx))
|
198 |
+
ret.append(dict(text=sentence, tokens=tokens))
|
199 |
+
return ret
|
200 |
+
|
201 |
+
def get_suffix_or_false(suffix):
|
202 |
+
return False if suffix == 'none' else suffix
|
203 |
+
|
204 |
+
def get_features_dict_from_predictions(predictions, idx):
|
205 |
+
ret = {}
|
206 |
+
for (feat_idx, (feat_name, feat_values)) in enumerate(ALL_FEATURES):
|
207 |
+
val = feat_values[predictions[feat_idx][idx[0]][idx[1]]]
|
208 |
+
if val != 'none':
|
209 |
+
ret[feat_name] = val
|
210 |
+
return ret
|
211 |
+
|
212 |
+
|