riccorl commited on
Commit
52ea8eb
1 Parent(s): db27370

Automatic push from sapienzanlp

Browse files
added_tokens.json ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "--NME--": 128001,
3
+ "[E-0]": 128002,
4
+ "[E-10]": 128012,
5
+ "[E-11]": 128013,
6
+ "[E-12]": 128014,
7
+ "[E-13]": 128015,
8
+ "[E-14]": 128016,
9
+ "[E-15]": 128017,
10
+ "[E-16]": 128018,
11
+ "[E-17]": 128019,
12
+ "[E-18]": 128020,
13
+ "[E-19]": 128021,
14
+ "[E-1]": 128003,
15
+ "[E-20]": 128022,
16
+ "[E-21]": 128023,
17
+ "[E-22]": 128024,
18
+ "[E-23]": 128025,
19
+ "[E-24]": 128026,
20
+ "[E-25]": 128027,
21
+ "[E-26]": 128028,
22
+ "[E-27]": 128029,
23
+ "[E-28]": 128030,
24
+ "[E-29]": 128031,
25
+ "[E-2]": 128004,
26
+ "[E-30]": 128032,
27
+ "[E-31]": 128033,
28
+ "[E-32]": 128034,
29
+ "[E-33]": 128035,
30
+ "[E-34]": 128036,
31
+ "[E-35]": 128037,
32
+ "[E-36]": 128038,
33
+ "[E-37]": 128039,
34
+ "[E-38]": 128040,
35
+ "[E-39]": 128041,
36
+ "[E-3]": 128005,
37
+ "[E-40]": 128042,
38
+ "[E-41]": 128043,
39
+ "[E-42]": 128044,
40
+ "[E-43]": 128045,
41
+ "[E-44]": 128046,
42
+ "[E-45]": 128047,
43
+ "[E-46]": 128048,
44
+ "[E-47]": 128049,
45
+ "[E-48]": 128050,
46
+ "[E-49]": 128051,
47
+ "[E-4]": 128006,
48
+ "[E-50]": 128052,
49
+ "[E-51]": 128053,
50
+ "[E-52]": 128054,
51
+ "[E-53]": 128055,
52
+ "[E-54]": 128056,
53
+ "[E-55]": 128057,
54
+ "[E-56]": 128058,
55
+ "[E-57]": 128059,
56
+ "[E-58]": 128060,
57
+ "[E-59]": 128061,
58
+ "[E-5]": 128007,
59
+ "[E-60]": 128062,
60
+ "[E-61]": 128063,
61
+ "[E-62]": 128064,
62
+ "[E-63]": 128065,
63
+ "[E-64]": 128066,
64
+ "[E-65]": 128067,
65
+ "[E-66]": 128068,
66
+ "[E-67]": 128069,
67
+ "[E-68]": 128070,
68
+ "[E-69]": 128071,
69
+ "[E-6]": 128008,
70
+ "[E-70]": 128072,
71
+ "[E-71]": 128073,
72
+ "[E-72]": 128074,
73
+ "[E-73]": 128075,
74
+ "[E-74]": 128076,
75
+ "[E-75]": 128077,
76
+ "[E-76]": 128078,
77
+ "[E-77]": 128079,
78
+ "[E-78]": 128080,
79
+ "[E-79]": 128081,
80
+ "[E-7]": 128009,
81
+ "[E-80]": 128082,
82
+ "[E-81]": 128083,
83
+ "[E-82]": 128084,
84
+ "[E-83]": 128085,
85
+ "[E-84]": 128086,
86
+ "[E-85]": 128087,
87
+ "[E-86]": 128088,
88
+ "[E-87]": 128089,
89
+ "[E-88]": 128090,
90
+ "[E-89]": 128091,
91
+ "[E-8]": 128010,
92
+ "[E-90]": 128092,
93
+ "[E-91]": 128093,
94
+ "[E-92]": 128094,
95
+ "[E-93]": 128095,
96
+ "[E-94]": 128096,
97
+ "[E-95]": 128097,
98
+ "[E-96]": 128098,
99
+ "[E-97]": 128099,
100
+ "[E-98]": 128100,
101
+ "[E-99]": 128101,
102
+ "[E-9]": 128011,
103
+ "[MASK]": 128000
104
+ }
config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation": "gelu",
3
+ "add_entity_embedding": null,
4
+ "additional_special_symbols": 101,
5
+ "additional_special_symbols_types": 0,
6
+ "architectures": [
7
+ "RelikReaderSpanModel"
8
+ ],
9
+ "auto_map": {
10
+ "AutoModel": "modeling_relik.RelikReaderSpanModel"
11
+ },
12
+ "default_reader_class": null,
13
+ "entity_type_loss": false,
14
+ "linears_hidden_size": 512,
15
+ "model_type": "relik-reader",
16
+ "num_layers": null,
17
+ "torch_dtype": "float32",
18
+ "training": true,
19
+ "transformer_model": "microsoft/deberta-v3-base",
20
+ "transformers_version": "4.33.3",
21
+ "use_last_k_layers": 1
22
+ }
configuration_relik.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from transformers import AutoConfig
4
+ from transformers.configuration_utils import PretrainedConfig
5
+
6
+
7
+ class RelikReaderConfig(PretrainedConfig):
8
+ model_type = "relik-reader"
9
+
10
+ def __init__(
11
+ self,
12
+ transformer_model: str = "microsoft/deberta-v3-base",
13
+ additional_special_symbols: int = 101,
14
+ additional_special_symbols_types: Optional[int] = 0,
15
+ num_layers: Optional[int] = None,
16
+ activation: str = "gelu",
17
+ linears_hidden_size: Optional[int] = 512,
18
+ use_last_k_layers: int = 1,
19
+ entity_type_loss: bool = False,
20
+ add_entity_embedding: bool = None,
21
+ training: bool = False,
22
+ default_reader_class: Optional[str] = None,
23
+ **kwargs
24
+ ) -> None:
25
+ # TODO: add name_or_path to kwargs
26
+ self.transformer_model = transformer_model
27
+ self.additional_special_symbols = additional_special_symbols
28
+ self.additional_special_symbols_types = additional_special_symbols_types
29
+ self.num_layers = num_layers
30
+ self.activation = activation
31
+ self.linears_hidden_size = linears_hidden_size
32
+ self.use_last_k_layers = use_last_k_layers
33
+ self.entity_type_loss = entity_type_loss
34
+ self.add_entity_embedding = (
35
+ True
36
+ if add_entity_embedding is None and entity_type_loss
37
+ else add_entity_embedding
38
+ )
39
+ self.training = training
40
+ self.default_reader_class = default_reader_class
41
+ super().__init__(**kwargs)
42
+
43
+
44
+ AutoConfig.register("relik-reader", RelikReaderConfig)
modeling_relik.py ADDED
@@ -0,0 +1,992 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional
2
+
3
+ import torch
4
+ from transformers import AutoModel, PreTrainedModel
5
+ from transformers.activations import ClippedGELUActivation, GELUActivation
6
+ from transformers.configuration_utils import PretrainedConfig
7
+ from transformers.modeling_utils import PoolerEndLogits
8
+
9
+ from .configuration_relik import RelikReaderConfig
10
+
11
+
12
+ class RelikReaderSample:
13
+ def __init__(self, **kwargs):
14
+ super().__setattr__("_d", {})
15
+ self._d = kwargs
16
+
17
+ def __getattribute__(self, item):
18
+ return super(RelikReaderSample, self).__getattribute__(item)
19
+
20
+ def __getattr__(self, item):
21
+ if item.startswith("__") and item.endswith("__"):
22
+ # this is likely some python library-specific variable (such as __deepcopy__ for copy)
23
+ # better follow standard behavior here
24
+ raise AttributeError(item)
25
+ elif item in self._d:
26
+ return self._d[item]
27
+ else:
28
+ return None
29
+
30
+ def __setattr__(self, key, value):
31
+ if key in self._d:
32
+ self._d[key] = value
33
+ else:
34
+ super().__setattr__(key, value)
35
+
36
+
37
+ activation2functions = {
38
+ "relu": torch.nn.ReLU(),
39
+ "gelu": GELUActivation(),
40
+ "gelu_10": ClippedGELUActivation(-10, 10),
41
+ }
42
+
43
+
44
+ class PoolerEndLogitsBi(PoolerEndLogits):
45
+ def __init__(self, config: PretrainedConfig):
46
+ super().__init__(config)
47
+ self.dense_1 = torch.nn.Linear(config.hidden_size, 2)
48
+
49
+ def forward(
50
+ self,
51
+ hidden_states: torch.FloatTensor,
52
+ start_states: Optional[torch.FloatTensor] = None,
53
+ start_positions: Optional[torch.LongTensor] = None,
54
+ p_mask: Optional[torch.FloatTensor] = None,
55
+ ) -> torch.FloatTensor:
56
+ if p_mask is not None:
57
+ p_mask = p_mask.unsqueeze(-1)
58
+ logits = super().forward(
59
+ hidden_states,
60
+ start_states,
61
+ start_positions,
62
+ p_mask,
63
+ )
64
+ return logits
65
+
66
+
67
+ class RelikReaderSpanModel(PreTrainedModel):
68
+ config_class = RelikReaderConfig
69
+
70
+ def __init__(self, config: RelikReaderConfig, *args, **kwargs):
71
+ super().__init__(config)
72
+ # Transformer model declaration
73
+ self.config = config
74
+ self.transformer_model = (
75
+ AutoModel.from_pretrained(self.config.transformer_model)
76
+ if self.config.num_layers is None
77
+ else AutoModel.from_pretrained(
78
+ self.config.transformer_model, num_hidden_layers=self.config.num_layers
79
+ )
80
+ )
81
+ self.transformer_model.resize_token_embeddings(
82
+ self.transformer_model.config.vocab_size
83
+ + self.config.additional_special_symbols
84
+ )
85
+
86
+ self.activation = self.config.activation
87
+ self.linears_hidden_size = self.config.linears_hidden_size
88
+ self.use_last_k_layers = self.config.use_last_k_layers
89
+
90
+ # named entity detection layers
91
+ self.ned_start_classifier = self._get_projection_layer(
92
+ self.activation, last_hidden=2, layer_norm=False
93
+ )
94
+ self.ned_end_classifier = PoolerEndLogits(self.transformer_model.config)
95
+
96
+ # END entity disambiguation layer
97
+ self.ed_start_projector = self._get_projection_layer(self.activation)
98
+ self.ed_end_projector = self._get_projection_layer(self.activation)
99
+
100
+ self.training = self.config.training
101
+
102
+ # criterion
103
+ self.criterion = torch.nn.CrossEntropyLoss()
104
+
105
+ def _get_projection_layer(
106
+ self,
107
+ activation: str,
108
+ last_hidden: Optional[int] = None,
109
+ input_hidden=None,
110
+ layer_norm: bool = True,
111
+ ) -> torch.nn.Sequential:
112
+ head_components = [
113
+ torch.nn.Dropout(0.1),
114
+ torch.nn.Linear(
115
+ (
116
+ self.transformer_model.config.hidden_size * self.use_last_k_layers
117
+ if input_hidden is None
118
+ else input_hidden
119
+ ),
120
+ self.linears_hidden_size,
121
+ ),
122
+ activation2functions[activation],
123
+ torch.nn.Dropout(0.1),
124
+ torch.nn.Linear(
125
+ self.linears_hidden_size,
126
+ self.linears_hidden_size if last_hidden is None else last_hidden,
127
+ ),
128
+ ]
129
+
130
+ if layer_norm:
131
+ head_components.append(
132
+ torch.nn.LayerNorm(
133
+ self.linears_hidden_size if last_hidden is None else last_hidden,
134
+ self.transformer_model.config.layer_norm_eps,
135
+ )
136
+ )
137
+
138
+ return torch.nn.Sequential(*head_components)
139
+
140
+ def _mask_logits(self, logits: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
141
+ mask = mask.unsqueeze(-1)
142
+ if next(self.parameters()).dtype == torch.float16:
143
+ logits = logits * (1 - mask) - 65500 * mask
144
+ else:
145
+ logits = logits * (1 - mask) - 1e30 * mask
146
+ return logits
147
+
148
+ def _get_model_features(
149
+ self,
150
+ input_ids: torch.Tensor,
151
+ attention_mask: torch.Tensor,
152
+ token_type_ids: Optional[torch.Tensor],
153
+ ):
154
+ model_input = {
155
+ "input_ids": input_ids,
156
+ "attention_mask": attention_mask,
157
+ "output_hidden_states": self.use_last_k_layers > 1,
158
+ }
159
+
160
+ if token_type_ids is not None:
161
+ model_input["token_type_ids"] = token_type_ids
162
+
163
+ model_output = self.transformer_model(**model_input)
164
+
165
+ if self.use_last_k_layers > 1:
166
+ model_features = torch.cat(
167
+ model_output[1][-self.use_last_k_layers :], dim=-1
168
+ )
169
+ else:
170
+ model_features = model_output[0]
171
+
172
+ return model_features
173
+
174
+ def compute_ned_end_logits(
175
+ self,
176
+ start_predictions,
177
+ start_labels,
178
+ model_features,
179
+ prediction_mask,
180
+ batch_size,
181
+ ) -> Optional[torch.Tensor]:
182
+ # todo: maybe when constraining on the spans,
183
+ # we should not use a prediction_mask for the end tokens.
184
+ # at least we should not during training imo
185
+ start_positions = start_labels if self.training else start_predictions
186
+ start_positions_indices = (
187
+ torch.arange(start_positions.size(1), device=start_positions.device)
188
+ .unsqueeze(0)
189
+ .expand(batch_size, -1)[start_positions > 0]
190
+ ).to(start_positions.device)
191
+
192
+ if len(start_positions_indices) > 0:
193
+ expanded_features = model_features.repeat_interleave(
194
+ torch.sum(start_positions > 0, dim=-1), dim=0
195
+ )
196
+ expanded_prediction_mask = prediction_mask.repeat_interleave(
197
+ torch.sum(start_positions > 0, dim=-1), dim=0
198
+ )
199
+ end_logits = self.ned_end_classifier(
200
+ hidden_states=expanded_features,
201
+ start_positions=start_positions_indices,
202
+ p_mask=expanded_prediction_mask,
203
+ )
204
+
205
+ return end_logits
206
+
207
+ return None
208
+
209
+ def compute_classification_logits(
210
+ self,
211
+ model_features,
212
+ special_symbols_mask,
213
+ prediction_mask,
214
+ batch_size,
215
+ start_positions=None,
216
+ end_positions=None,
217
+ ) -> torch.Tensor:
218
+ if start_positions is None or end_positions is None:
219
+ start_positions = torch.zeros_like(prediction_mask)
220
+ end_positions = torch.zeros_like(prediction_mask)
221
+
222
+ model_start_features = self.ed_start_projector(model_features)
223
+ model_end_features = self.ed_end_projector(model_features)
224
+ model_end_features[start_positions > 0] = model_end_features[end_positions > 0]
225
+
226
+ model_ed_features = torch.cat(
227
+ [model_start_features, model_end_features], dim=-1
228
+ )
229
+
230
+ # computing ed features
231
+ classes_representations = torch.sum(special_symbols_mask, dim=1)[0].item()
232
+ special_symbols_representation = model_ed_features[special_symbols_mask].view(
233
+ batch_size, classes_representations, -1
234
+ )
235
+
236
+ logits = torch.bmm(
237
+ model_ed_features,
238
+ torch.permute(special_symbols_representation, (0, 2, 1)),
239
+ )
240
+
241
+ logits = self._mask_logits(logits, prediction_mask)
242
+
243
+ return logits
244
+
245
+ def forward(
246
+ self,
247
+ input_ids: torch.Tensor,
248
+ attention_mask: torch.Tensor,
249
+ token_type_ids: Optional[torch.Tensor] = None,
250
+ prediction_mask: Optional[torch.Tensor] = None,
251
+ special_symbols_mask: Optional[torch.Tensor] = None,
252
+ start_labels: Optional[torch.Tensor] = None,
253
+ end_labels: Optional[torch.Tensor] = None,
254
+ use_predefined_spans: bool = False,
255
+ *args,
256
+ **kwargs,
257
+ ) -> Dict[str, Any]:
258
+ batch_size, seq_len = input_ids.shape
259
+
260
+ model_features = self._get_model_features(
261
+ input_ids, attention_mask, token_type_ids
262
+ )
263
+
264
+ ned_start_labels = None
265
+
266
+ # named entity detection if required
267
+ if use_predefined_spans: # no need to compute spans
268
+ ned_start_logits, ned_start_probabilities, ned_start_predictions = (
269
+ None,
270
+ None,
271
+ (
272
+ torch.clone(start_labels)
273
+ if start_labels is not None
274
+ else torch.zeros_like(input_ids)
275
+ ),
276
+ )
277
+ ned_end_logits, ned_end_probabilities, ned_end_predictions = (
278
+ None,
279
+ None,
280
+ (
281
+ torch.clone(end_labels)
282
+ if end_labels is not None
283
+ else torch.zeros_like(input_ids)
284
+ ),
285
+ )
286
+
287
+ ned_start_predictions[ned_start_predictions > 0] = 1
288
+ ned_end_predictions[ned_end_predictions > 0] = 1
289
+
290
+ else: # compute spans
291
+ # start boundary prediction
292
+ ned_start_logits = self.ned_start_classifier(model_features)
293
+ ned_start_logits = self._mask_logits(ned_start_logits, prediction_mask)
294
+ ned_start_probabilities = torch.softmax(ned_start_logits, dim=-1)
295
+ ned_start_predictions = ned_start_probabilities.argmax(dim=-1)
296
+
297
+ # end boundary prediction
298
+ ned_start_labels = (
299
+ torch.zeros_like(start_labels) if start_labels is not None else None
300
+ )
301
+
302
+ if ned_start_labels is not None:
303
+ ned_start_labels[start_labels == -100] = -100
304
+ ned_start_labels[start_labels > 0] = 1
305
+
306
+ ned_end_logits = self.compute_ned_end_logits(
307
+ ned_start_predictions,
308
+ ned_start_labels,
309
+ model_features,
310
+ prediction_mask,
311
+ batch_size,
312
+ )
313
+
314
+ if ned_end_logits is not None:
315
+ ned_end_probabilities = torch.softmax(ned_end_logits, dim=-1)
316
+ ned_end_predictions = torch.argmax(ned_end_probabilities, dim=-1)
317
+ else:
318
+ ned_end_logits, ned_end_probabilities = None, None
319
+ ned_end_predictions = ned_start_predictions.new_zeros(batch_size)
320
+
321
+ # flattening end predictions
322
+ # (flattening can happen only if the
323
+ # end boundaries were not predicted using the gold labels)
324
+ if not self.training:
325
+ flattened_end_predictions = torch.clone(ned_start_predictions)
326
+ flattened_end_predictions[flattened_end_predictions > 0] = 0
327
+
328
+ batch_start_predictions = list()
329
+ for elem_idx in range(batch_size):
330
+ batch_start_predictions.append(
331
+ torch.where(ned_start_predictions[elem_idx] > 0)[0].tolist()
332
+ )
333
+
334
+ # check that the total number of start predictions
335
+ # is equal to the end predictions
336
+ total_start_predictions = sum(map(len, batch_start_predictions))
337
+ total_end_predictions = len(ned_end_predictions)
338
+ assert (
339
+ total_start_predictions == 0
340
+ or total_start_predictions == total_end_predictions
341
+ ), (
342
+ f"Total number of start predictions = {total_start_predictions}. "
343
+ f"Total number of end predictions = {total_end_predictions}"
344
+ )
345
+
346
+ curr_end_pred_num = 0
347
+ for elem_idx, bsp in enumerate(batch_start_predictions):
348
+ for sp in bsp:
349
+ ep = ned_end_predictions[curr_end_pred_num].item()
350
+ if ep < sp:
351
+ ep = sp
352
+
353
+ # if we already set this span throw it (no overlap)
354
+ if flattened_end_predictions[elem_idx, ep] == 1:
355
+ ned_start_predictions[elem_idx, sp] = 0
356
+ else:
357
+ flattened_end_predictions[elem_idx, ep] = 1
358
+
359
+ curr_end_pred_num += 1
360
+
361
+ ned_end_predictions = flattened_end_predictions
362
+
363
+ start_position, end_position = (
364
+ (start_labels, end_labels)
365
+ if self.training
366
+ else (ned_start_predictions, ned_end_predictions)
367
+ )
368
+
369
+ # Entity disambiguation
370
+ ed_logits = self.compute_classification_logits(
371
+ model_features,
372
+ special_symbols_mask,
373
+ prediction_mask,
374
+ batch_size,
375
+ start_position,
376
+ end_position,
377
+ )
378
+ ed_probabilities = torch.softmax(ed_logits, dim=-1)
379
+ ed_predictions = torch.argmax(ed_probabilities, dim=-1)
380
+
381
+ # output build
382
+ output_dict = dict(
383
+ batch_size=batch_size,
384
+ ned_start_logits=ned_start_logits,
385
+ ned_start_probabilities=ned_start_probabilities,
386
+ ned_start_predictions=ned_start_predictions,
387
+ ned_end_logits=ned_end_logits,
388
+ ned_end_probabilities=ned_end_probabilities,
389
+ ned_end_predictions=ned_end_predictions,
390
+ ed_logits=ed_logits,
391
+ ed_probabilities=ed_probabilities,
392
+ ed_predictions=ed_predictions,
393
+ )
394
+
395
+ # compute loss if labels
396
+ if start_labels is not None and end_labels is not None and self.training:
397
+ # named entity detection loss
398
+
399
+ # start
400
+ if ned_start_logits is not None:
401
+ ned_start_loss = self.criterion(
402
+ ned_start_logits.view(-1, ned_start_logits.shape[-1]),
403
+ ned_start_labels.view(-1),
404
+ )
405
+ else:
406
+ ned_start_loss = 0
407
+
408
+ # end
409
+ if ned_end_logits is not None:
410
+ ned_end_labels = torch.zeros_like(end_labels)
411
+ ned_end_labels[end_labels == -100] = -100
412
+ ned_end_labels[end_labels > 0] = 1
413
+
414
+ ned_end_loss = self.criterion(
415
+ ned_end_logits,
416
+ (
417
+ torch.arange(
418
+ ned_end_labels.size(1), device=ned_end_labels.device
419
+ )
420
+ .unsqueeze(0)
421
+ .expand(batch_size, -1)[ned_end_labels > 0]
422
+ ).to(ned_end_labels.device),
423
+ )
424
+
425
+ else:
426
+ ned_end_loss = 0
427
+
428
+ # entity disambiguation loss
429
+ start_labels[ned_start_labels != 1] = -100
430
+ ed_labels = torch.clone(start_labels)
431
+ ed_labels[end_labels > 0] = end_labels[end_labels > 0]
432
+ ed_loss = self.criterion(
433
+ ed_logits.view(-1, ed_logits.shape[-1]),
434
+ ed_labels.view(-1),
435
+ )
436
+
437
+ output_dict["ned_start_loss"] = ned_start_loss
438
+ output_dict["ned_end_loss"] = ned_end_loss
439
+ output_dict["ed_loss"] = ed_loss
440
+
441
+ output_dict["loss"] = ned_start_loss + ned_end_loss + ed_loss
442
+
443
+ return output_dict
444
+
445
+
446
+ class RelikReaderREModel(PreTrainedModel):
447
+ config_class = RelikReaderConfig
448
+
449
+ def __init__(self, config, *args, **kwargs):
450
+ super().__init__(config)
451
+ # Transformer model declaration
452
+ # self.transformer_model_name = transformer_model
453
+ self.config = config
454
+ self.transformer_model = (
455
+ AutoModel.from_pretrained(config.transformer_model)
456
+ if config.num_layers is None
457
+ else AutoModel.from_pretrained(
458
+ config.transformer_model, num_hidden_layers=config.num_layers
459
+ )
460
+ )
461
+ self.transformer_model.resize_token_embeddings(
462
+ self.transformer_model.config.vocab_size
463
+ + config.additional_special_symbols
464
+ + config.additional_special_symbols_types
465
+ )
466
+
467
+ # named entity detection layers
468
+ self.ned_start_classifier = self._get_projection_layer(
469
+ config.activation, last_hidden=2, layer_norm=False
470
+ )
471
+
472
+ self.ned_end_classifier = PoolerEndLogitsBi(self.transformer_model.config)
473
+
474
+ self.relation_disambiguation_loss = (
475
+ config.relation_disambiguation_loss
476
+ if hasattr(config, "relation_disambiguation_loss")
477
+ else False
478
+ )
479
+
480
+ if self.config.entity_type_loss and self.config.add_entity_embedding:
481
+ input_hidden_ents = 3 * self.transformer_model.config.hidden_size
482
+ else:
483
+ input_hidden_ents = 2 * self.transformer_model.config.hidden_size
484
+
485
+ self.re_subject_projector = self._get_projection_layer(
486
+ config.activation, input_hidden=input_hidden_ents
487
+ )
488
+ self.re_object_projector = self._get_projection_layer(
489
+ config.activation, input_hidden=input_hidden_ents
490
+ )
491
+ self.re_relation_projector = self._get_projection_layer(config.activation)
492
+
493
+ if self.config.entity_type_loss or self.relation_disambiguation_loss:
494
+ self.re_entities_projector = self._get_projection_layer(
495
+ config.activation,
496
+ input_hidden=2 * self.transformer_model.config.hidden_size,
497
+ )
498
+ self.re_definition_projector = self._get_projection_layer(
499
+ config.activation,
500
+ )
501
+
502
+ self.re_classifier = self._get_projection_layer(
503
+ config.activation,
504
+ input_hidden=config.linears_hidden_size,
505
+ last_hidden=2,
506
+ layer_norm=False,
507
+ )
508
+
509
+ self.training = config.training
510
+
511
+ # criterion
512
+ self.criterion = torch.nn.CrossEntropyLoss()
513
+ self.criterion_type = torch.nn.BCEWithLogitsLoss()
514
+
515
+ def _get_projection_layer(
516
+ self,
517
+ activation: str,
518
+ last_hidden: Optional[int] = None,
519
+ input_hidden=None,
520
+ layer_norm: bool = True,
521
+ ) -> torch.nn.Sequential:
522
+ head_components = [
523
+ torch.nn.Dropout(0.1),
524
+ torch.nn.Linear(
525
+ (
526
+ self.transformer_model.config.hidden_size
527
+ * self.config.use_last_k_layers
528
+ if input_hidden is None
529
+ else input_hidden
530
+ ),
531
+ self.config.linears_hidden_size,
532
+ ),
533
+ activation2functions[activation],
534
+ torch.nn.Dropout(0.1),
535
+ torch.nn.Linear(
536
+ self.config.linears_hidden_size,
537
+ self.config.linears_hidden_size if last_hidden is None else last_hidden,
538
+ ),
539
+ ]
540
+
541
+ if layer_norm:
542
+ head_components.append(
543
+ torch.nn.LayerNorm(
544
+ (
545
+ self.config.linears_hidden_size
546
+ if last_hidden is None
547
+ else last_hidden
548
+ ),
549
+ self.transformer_model.config.layer_norm_eps,
550
+ )
551
+ )
552
+
553
+ return torch.nn.Sequential(*head_components)
554
+
555
+ def _mask_logits(self, logits: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
556
+ mask = mask.unsqueeze(-1)
557
+ if next(self.parameters()).dtype == torch.float16:
558
+ logits = logits * (1 - mask) - 65500 * mask
559
+ else:
560
+ logits = logits * (1 - mask) - 1e30 * mask
561
+ return logits
562
+
563
+ def _get_model_features(
564
+ self,
565
+ input_ids: torch.Tensor,
566
+ attention_mask: torch.Tensor,
567
+ token_type_ids: Optional[torch.Tensor],
568
+ ):
569
+ model_input = {
570
+ "input_ids": input_ids,
571
+ "attention_mask": attention_mask,
572
+ "output_hidden_states": self.config.use_last_k_layers > 1,
573
+ }
574
+
575
+ if token_type_ids is not None:
576
+ model_input["token_type_ids"] = token_type_ids
577
+
578
+ model_output = self.transformer_model(**model_input)
579
+
580
+ if self.config.use_last_k_layers > 1:
581
+ model_features = torch.cat(
582
+ model_output[1][-self.config.use_last_k_layers :], dim=-1
583
+ )
584
+ else:
585
+ model_features = model_output[0]
586
+
587
+ return model_features
588
+
589
+ def compute_ned_end_logits(
590
+ self,
591
+ start_predictions,
592
+ start_labels,
593
+ model_features,
594
+ prediction_mask,
595
+ batch_size,
596
+ mask_preceding: bool = False,
597
+ ) -> Optional[torch.Tensor]:
598
+ # todo: maybe when constraining on the spans,
599
+ # we should not use a prediction_mask for the end tokens.
600
+ # at least we should not during training imo
601
+ start_positions = start_labels if self.training else start_predictions
602
+ start_positions_indices = (
603
+ torch.arange(start_positions.size(1), device=start_positions.device)
604
+ .unsqueeze(0)
605
+ .expand(batch_size, -1)[start_positions > 0]
606
+ ).to(start_positions.device)
607
+
608
+ if len(start_positions_indices) > 0:
609
+ expanded_features = model_features.repeat_interleave(
610
+ torch.sum(start_positions > 0, dim=-1), dim=0
611
+ )
612
+ expanded_prediction_mask = prediction_mask.repeat_interleave(
613
+ torch.sum(start_positions > 0, dim=-1), dim=0
614
+ )
615
+ if mask_preceding:
616
+ expanded_prediction_mask[
617
+ torch.arange(
618
+ expanded_prediction_mask.shape[1],
619
+ device=expanded_prediction_mask.device,
620
+ )
621
+ < start_positions_indices.unsqueeze(1)
622
+ ] = 1
623
+ end_logits = self.ned_end_classifier(
624
+ hidden_states=expanded_features,
625
+ start_positions=start_positions_indices,
626
+ p_mask=expanded_prediction_mask,
627
+ )
628
+
629
+ return end_logits
630
+
631
+ return None
632
+
633
+ def compute_relation_logits(
634
+ self,
635
+ model_entity_features,
636
+ special_symbols_features,
637
+ ) -> torch.Tensor:
638
+ model_subject_features = self.re_subject_projector(model_entity_features)
639
+ model_object_features = self.re_object_projector(model_entity_features)
640
+ special_symbols_start_representation = self.re_relation_projector(
641
+ special_symbols_features
642
+ )
643
+ re_logits = torch.einsum(
644
+ "bse,bde,bfe->bsdfe",
645
+ model_subject_features,
646
+ model_object_features,
647
+ special_symbols_start_representation,
648
+ )
649
+ re_logits = self.re_classifier(re_logits)
650
+
651
+ return re_logits
652
+
653
+ def compute_entity_logits(
654
+ self,
655
+ model_entity_features,
656
+ special_symbols_features,
657
+ ) -> torch.Tensor:
658
+ model_ed_features = self.re_entities_projector(model_entity_features)
659
+ special_symbols_ed_representation = self.re_definition_projector(
660
+ special_symbols_features
661
+ )
662
+
663
+ logits = torch.bmm(
664
+ model_ed_features,
665
+ torch.permute(special_symbols_ed_representation, (0, 2, 1)),
666
+ )
667
+ logits = self._mask_logits(
668
+ logits, (model_entity_features == -100).all(2).long()
669
+ )
670
+ return logits
671
+
672
+ def compute_loss(self, logits, labels, mask=None):
673
+ logits = logits.reshape(-1, logits.shape[-1])
674
+ labels = labels.reshape(-1).long()
675
+ if mask is not None:
676
+ return self.criterion(logits[mask], labels[mask])
677
+ return self.criterion(logits, labels)
678
+
679
+ def compute_ned_type_loss(
680
+ self,
681
+ disambiguation_labels,
682
+ re_ned_entities_logits,
683
+ ned_type_logits,
684
+ re_entities_logits,
685
+ entity_types,
686
+ mask,
687
+ ):
688
+ if self.config.entity_type_loss and self.relation_disambiguation_loss:
689
+ return self.criterion_type(
690
+ re_ned_entities_logits[disambiguation_labels != -100],
691
+ disambiguation_labels[disambiguation_labels != -100],
692
+ )
693
+ if self.config.entity_type_loss:
694
+ return self.criterion_type(
695
+ ned_type_logits[mask],
696
+ disambiguation_labels[:, :, :entity_types][mask],
697
+ )
698
+
699
+ if self.relation_disambiguation_loss:
700
+ return self.criterion_type(
701
+ re_entities_logits[disambiguation_labels != -100],
702
+ disambiguation_labels[disambiguation_labels != -100],
703
+ )
704
+ return 0
705
+
706
+ def compute_relation_loss(self, relation_labels, re_logits):
707
+ return self.compute_loss(
708
+ re_logits, relation_labels, relation_labels.view(-1) != -100
709
+ )
710
+
711
+ def forward(
712
+ self,
713
+ input_ids: torch.Tensor,
714
+ attention_mask: torch.Tensor,
715
+ token_type_ids: torch.Tensor,
716
+ prediction_mask: Optional[torch.Tensor] = None,
717
+ special_symbols_mask: Optional[torch.Tensor] = None,
718
+ special_symbols_mask_entities: Optional[torch.Tensor] = None,
719
+ start_labels: Optional[torch.Tensor] = None,
720
+ end_labels: Optional[torch.Tensor] = None,
721
+ disambiguation_labels: Optional[torch.Tensor] = None,
722
+ relation_labels: Optional[torch.Tensor] = None,
723
+ relation_threshold: float = 0.5,
724
+ is_validation: bool = False,
725
+ is_prediction: bool = False,
726
+ use_predefined_spans: bool = False,
727
+ *args,
728
+ **kwargs,
729
+ ) -> Dict[str, Any]:
730
+ batch_size = input_ids.shape[0]
731
+
732
+ model_features = self._get_model_features(
733
+ input_ids, attention_mask, token_type_ids
734
+ )
735
+
736
+ # named entity detection
737
+ if use_predefined_spans:
738
+ ned_start_logits, ned_start_probabilities, ned_start_predictions = (
739
+ None,
740
+ None,
741
+ torch.zeros_like(start_labels),
742
+ )
743
+ ned_end_logits, ned_end_probabilities, ned_end_predictions = (
744
+ None,
745
+ None,
746
+ torch.zeros_like(end_labels),
747
+ )
748
+
749
+ ned_start_predictions[start_labels > 0] = 1
750
+ ned_end_predictions[end_labels > 0] = 1
751
+ ned_end_predictions = ned_end_predictions[~(end_labels == -100).all(2)]
752
+ ned_start_labels = start_labels
753
+ ned_start_labels[start_labels > 0] = 1
754
+ else:
755
+ # start boundary prediction
756
+ ned_start_logits = self.ned_start_classifier(model_features)
757
+ if is_validation or is_prediction:
758
+ ned_start_logits = self._mask_logits(
759
+ ned_start_logits, prediction_mask
760
+ ) # why?
761
+ ned_start_probabilities = torch.softmax(ned_start_logits, dim=-1)
762
+ ned_start_predictions = ned_start_probabilities.argmax(dim=-1)
763
+
764
+ # end boundary prediction
765
+ ned_start_labels = (
766
+ torch.zeros_like(start_labels) if start_labels is not None else None
767
+ )
768
+
769
+ # start_labels contain entity id at their position, we just need 1 for start of entity
770
+ if ned_start_labels is not None:
771
+ ned_start_labels[start_labels == -100] = -100
772
+ ned_start_labels[start_labels > 0] = 1
773
+
774
+ # compute end logits only if there are any start predictions.
775
+ # For each start prediction, n end predictions are made
776
+ ned_end_logits = self.compute_ned_end_logits(
777
+ ned_start_predictions,
778
+ ned_start_labels,
779
+ model_features,
780
+ prediction_mask,
781
+ batch_size,
782
+ True,
783
+ )
784
+
785
+ if ned_end_logits is not None:
786
+ # For each start prediction, n end predictions are made based on
787
+ # binary classification ie. argmax at each position.
788
+ ned_end_probabilities = torch.softmax(ned_end_logits, dim=-1)
789
+ ned_end_predictions = ned_end_probabilities.argmax(dim=-1)
790
+ else:
791
+ ned_end_logits, ned_end_probabilities = None, None
792
+ ned_end_predictions = torch.zeros_like(ned_start_predictions)
793
+
794
+ if is_prediction or is_validation:
795
+ end_preds_count = ned_end_predictions.sum(1)
796
+ # If there are no end predictions for a start prediction, remove the start prediction
797
+ if (end_preds_count == 0).any() and (ned_start_predictions > 0).any():
798
+ ned_start_predictions[ned_start_predictions == 1] = (
799
+ end_preds_count != 0
800
+ ).long()
801
+ ned_end_predictions = ned_end_predictions[end_preds_count != 0]
802
+
803
+ if end_labels is not None:
804
+ end_labels = end_labels[~(end_labels == -100).all(2)]
805
+
806
+ start_position, end_position = (
807
+ (start_labels, end_labels)
808
+ if (not is_prediction and not is_validation)
809
+ else (ned_start_predictions, ned_end_predictions)
810
+ )
811
+
812
+ start_counts = (start_position > 0).sum(1)
813
+ if (start_counts > 0).any():
814
+ ned_end_predictions = ned_end_predictions.split(start_counts.tolist())
815
+ # limit to 30 predictions per document using start_counts, by setting all po after sum is 30 to 0
816
+ # if is_validation or is_prediction:
817
+ # ned_start_predictions[ned_start_predictions == 1] = start_counts
818
+ # We can only predict relations if we have start and end predictions
819
+ if (end_position > 0).sum() > 0:
820
+ ends_count = (end_position > 0).sum(1)
821
+ model_subject_features = torch.cat(
822
+ [
823
+ torch.repeat_interleave(
824
+ model_features[start_position > 0], ends_count, dim=0
825
+ ), # start position features
826
+ torch.repeat_interleave(model_features, start_counts, dim=0)[
827
+ end_position > 0
828
+ ], # end position features
829
+ ],
830
+ dim=-1,
831
+ )
832
+ ents_count = torch.nn.utils.rnn.pad_sequence(
833
+ torch.split(ends_count, start_counts.tolist()),
834
+ batch_first=True,
835
+ padding_value=0,
836
+ ).sum(1)
837
+ model_subject_features = torch.nn.utils.rnn.pad_sequence(
838
+ torch.split(model_subject_features, ents_count.tolist()),
839
+ batch_first=True,
840
+ padding_value=-100,
841
+ )
842
+
843
+ # if is_validation or is_prediction:
844
+ # model_subject_features = model_subject_features[:, :30, :]
845
+
846
+ # entity disambiguation. Here relation_disambiguation_loss would only be useful to
847
+ # reduce the number of candidate relations for the next step, but currently unused.
848
+ if self.config.entity_type_loss or self.relation_disambiguation_loss:
849
+ (re_ned_entities_logits) = self.compute_entity_logits(
850
+ model_subject_features,
851
+ model_features[
852
+ special_symbols_mask | special_symbols_mask_entities
853
+ ].view(batch_size, -1, model_features.shape[-1]),
854
+ )
855
+ entity_types = torch.sum(special_symbols_mask_entities, dim=1)[0].item()
856
+ ned_type_logits = re_ned_entities_logits[:, :, :entity_types]
857
+ re_entities_logits = re_ned_entities_logits[:, :, entity_types:]
858
+
859
+ if self.config.entity_type_loss:
860
+ ned_type_probabilities = torch.sigmoid(ned_type_logits)
861
+ ned_type_predictions = ned_type_probabilities.argmax(dim=-1)
862
+
863
+ if self.config.add_entity_embedding:
864
+ special_symbols_representation = model_features[
865
+ special_symbols_mask_entities
866
+ ].view(batch_size, entity_types, -1)
867
+
868
+ entities_representation = torch.einsum(
869
+ "bsp,bpe->bse",
870
+ ned_type_probabilities,
871
+ special_symbols_representation,
872
+ )
873
+ model_subject_features = torch.cat(
874
+ [model_subject_features, entities_representation], dim=-1
875
+ )
876
+ re_entities_probabilities = torch.sigmoid(re_entities_logits)
877
+ re_entities_predictions = re_entities_probabilities.round()
878
+ else:
879
+ (
880
+ ned_type_logits,
881
+ ned_type_probabilities,
882
+ re_entities_logits,
883
+ re_entities_probabilities,
884
+ ) = (None, None, None, None)
885
+ ned_type_predictions, re_entities_predictions = (
886
+ torch.zeros([batch_size, 1], dtype=torch.long).to(input_ids.device),
887
+ torch.zeros([batch_size, 1], dtype=torch.long).to(input_ids.device),
888
+ )
889
+
890
+ # Compute relation logits
891
+ re_logits = self.compute_relation_logits(
892
+ model_subject_features,
893
+ model_features[special_symbols_mask].view(
894
+ batch_size, -1, model_features.shape[-1]
895
+ ),
896
+ )
897
+
898
+ re_probabilities = torch.softmax(re_logits, dim=-1)
899
+ # we set a thresshold instead of argmax in cause it needs to be tweaked
900
+ re_predictions = re_probabilities[:, :, :, :, 1] > relation_threshold
901
+ # re_predictions = re_probabilities.argmax(dim=-1)
902
+ re_probabilities = re_probabilities[:, :, :, :, 1]
903
+ # re_logits, re_probabilities, re_predictions = (
904
+ # torch.zeros(
905
+ # [batch_size, 1, 1, special_symbols_mask.sum(1)[0]], dtype=torch.long
906
+ # ).to(input_ids.device),
907
+ # torch.zeros(
908
+ # [batch_size, 1, 1, special_symbols_mask.sum(1)[0]], dtype=torch.long
909
+ # ).to(input_ids.device),
910
+ # torch.zeros(
911
+ # [batch_size, 1, 1, special_symbols_mask.sum(1)[0]], dtype=torch.long
912
+ # ).to(input_ids.device),
913
+ # )
914
+
915
+ else:
916
+ (
917
+ ned_type_logits,
918
+ ned_type_probabilities,
919
+ re_entities_logits,
920
+ re_entities_probabilities,
921
+ ) = (None, None, None, None)
922
+ ned_type_predictions, re_entities_predictions = (
923
+ torch.zeros([batch_size, 1], dtype=torch.long).to(input_ids.device),
924
+ torch.zeros([batch_size, 1], dtype=torch.long).to(input_ids.device),
925
+ )
926
+ re_logits, re_probabilities, re_predictions = (
927
+ torch.zeros(
928
+ [batch_size, 1, 1, special_symbols_mask.sum(1)[0]], dtype=torch.long
929
+ ).to(input_ids.device),
930
+ torch.zeros(
931
+ [batch_size, 1, 1, special_symbols_mask.sum(1)[0]], dtype=torch.long
932
+ ).to(input_ids.device),
933
+ torch.zeros(
934
+ [batch_size, 1, 1, special_symbols_mask.sum(1)[0]], dtype=torch.long
935
+ ).to(input_ids.device),
936
+ )
937
+
938
+ # output build
939
+ output_dict = dict(
940
+ batch_size=batch_size,
941
+ ned_start_logits=ned_start_logits,
942
+ ned_start_probabilities=ned_start_probabilities,
943
+ ned_start_predictions=ned_start_predictions,
944
+ ned_end_logits=ned_end_logits,
945
+ ned_end_probabilities=ned_end_probabilities,
946
+ ned_end_predictions=ned_end_predictions,
947
+ ned_type_logits=ned_type_logits,
948
+ ned_type_probabilities=ned_type_probabilities,
949
+ ned_type_predictions=ned_type_predictions,
950
+ re_entities_logits=re_entities_logits,
951
+ re_entities_probabilities=re_entities_probabilities,
952
+ re_entities_predictions=re_entities_predictions,
953
+ re_logits=re_logits,
954
+ re_probabilities=re_probabilities,
955
+ re_predictions=re_predictions,
956
+ )
957
+
958
+ if (
959
+ start_labels is not None
960
+ and end_labels is not None
961
+ and relation_labels is not None
962
+ and is_prediction is False
963
+ ):
964
+ ned_start_loss = self.compute_loss(ned_start_logits, ned_start_labels)
965
+ end_labels[end_labels > 0] = 1
966
+ ned_end_loss = self.compute_loss(ned_end_logits, end_labels)
967
+ if self.config.entity_type_loss or self.relation_disambiguation_loss:
968
+ ned_type_loss = self.compute_ned_type_loss(
969
+ disambiguation_labels,
970
+ re_ned_entities_logits,
971
+ ned_type_logits,
972
+ re_entities_logits,
973
+ entity_types,
974
+ (model_subject_features != -100).all(2),
975
+ )
976
+ relation_loss = self.compute_relation_loss(relation_labels, re_logits)
977
+ # compute loss. We can skip the relation loss if we are in the first epochs (optional)
978
+ if self.config.entity_type_loss or self.relation_disambiguation_loss:
979
+ output_dict["loss"] = (
980
+ ned_start_loss + ned_end_loss + relation_loss + ned_type_loss
981
+ ) / 4
982
+ output_dict["ned_type_loss"] = ned_type_loss
983
+ else:
984
+ output_dict["loss"] = ((1 / 4) * (ned_start_loss + ned_end_loss)) + (
985
+ (1 / 2) * relation_loss
986
+ )
987
+
988
+ output_dict["ned_start_loss"] = ned_start_loss
989
+ output_dict["ned_end_loss"] = ned_end_loss
990
+ output_dict["re_loss"] = relation_loss
991
+
992
+ return output_dict
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60ae577b1b5cb7bfff9776ccdbea4075e699976ecc9eb1e97afbf5a4d0933f1a
3
+ size 747283514
special_tokens_map.json ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "--NME--",
4
+ "[E-0]",
5
+ "[E-1]",
6
+ "[E-2]",
7
+ "[E-3]",
8
+ "[E-4]",
9
+ "[E-5]",
10
+ "[E-6]",
11
+ "[E-7]",
12
+ "[E-8]",
13
+ "[E-9]",
14
+ "[E-10]",
15
+ "[E-11]",
16
+ "[E-12]",
17
+ "[E-13]",
18
+ "[E-14]",
19
+ "[E-15]",
20
+ "[E-16]",
21
+ "[E-17]",
22
+ "[E-18]",
23
+ "[E-19]",
24
+ "[E-20]",
25
+ "[E-21]",
26
+ "[E-22]",
27
+ "[E-23]",
28
+ "[E-24]",
29
+ "[E-25]",
30
+ "[E-26]",
31
+ "[E-27]",
32
+ "[E-28]",
33
+ "[E-29]",
34
+ "[E-30]",
35
+ "[E-31]",
36
+ "[E-32]",
37
+ "[E-33]",
38
+ "[E-34]",
39
+ "[E-35]",
40
+ "[E-36]",
41
+ "[E-37]",
42
+ "[E-38]",
43
+ "[E-39]",
44
+ "[E-40]",
45
+ "[E-41]",
46
+ "[E-42]",
47
+ "[E-43]",
48
+ "[E-44]",
49
+ "[E-45]",
50
+ "[E-46]",
51
+ "[E-47]",
52
+ "[E-48]",
53
+ "[E-49]",
54
+ "[E-50]",
55
+ "[E-51]",
56
+ "[E-52]",
57
+ "[E-53]",
58
+ "[E-54]",
59
+ "[E-55]",
60
+ "[E-56]",
61
+ "[E-57]",
62
+ "[E-58]",
63
+ "[E-59]",
64
+ "[E-60]",
65
+ "[E-61]",
66
+ "[E-62]",
67
+ "[E-63]",
68
+ "[E-64]",
69
+ "[E-65]",
70
+ "[E-66]",
71
+ "[E-67]",
72
+ "[E-68]",
73
+ "[E-69]",
74
+ "[E-70]",
75
+ "[E-71]",
76
+ "[E-72]",
77
+ "[E-73]",
78
+ "[E-74]",
79
+ "[E-75]",
80
+ "[E-76]",
81
+ "[E-77]",
82
+ "[E-78]",
83
+ "[E-79]",
84
+ "[E-80]",
85
+ "[E-81]",
86
+ "[E-82]",
87
+ "[E-83]",
88
+ "[E-84]",
89
+ "[E-85]",
90
+ "[E-86]",
91
+ "[E-87]",
92
+ "[E-88]",
93
+ "[E-89]",
94
+ "[E-90]",
95
+ "[E-91]",
96
+ "[E-92]",
97
+ "[E-93]",
98
+ "[E-94]",
99
+ "[E-95]",
100
+ "[E-96]",
101
+ "[E-97]",
102
+ "[E-98]",
103
+ "[E-99]"
104
+ ],
105
+ "bos_token": "[CLS]",
106
+ "cls_token": "[CLS]",
107
+ "eos_token": "[SEP]",
108
+ "mask_token": "[MASK]",
109
+ "pad_token": "[PAD]",
110
+ "sep_token": "[SEP]",
111
+ "unk_token": "[UNK]"
112
+ }
spm.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c679fbf93643d19aab7ee10c0b99e460bdbc02fedf34b92b05af343b4af586fd
3
+ size 2464616
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": true,
3
+ "additional_special_tokens": [
4
+ "--NME--",
5
+ "[E-0]",
6
+ "[E-1]",
7
+ "[E-2]",
8
+ "[E-3]",
9
+ "[E-4]",
10
+ "[E-5]",
11
+ "[E-6]",
12
+ "[E-7]",
13
+ "[E-8]",
14
+ "[E-9]",
15
+ "[E-10]",
16
+ "[E-11]",
17
+ "[E-12]",
18
+ "[E-13]",
19
+ "[E-14]",
20
+ "[E-15]",
21
+ "[E-16]",
22
+ "[E-17]",
23
+ "[E-18]",
24
+ "[E-19]",
25
+ "[E-20]",
26
+ "[E-21]",
27
+ "[E-22]",
28
+ "[E-23]",
29
+ "[E-24]",
30
+ "[E-25]",
31
+ "[E-26]",
32
+ "[E-27]",
33
+ "[E-28]",
34
+ "[E-29]",
35
+ "[E-30]",
36
+ "[E-31]",
37
+ "[E-32]",
38
+ "[E-33]",
39
+ "[E-34]",
40
+ "[E-35]",
41
+ "[E-36]",
42
+ "[E-37]",
43
+ "[E-38]",
44
+ "[E-39]",
45
+ "[E-40]",
46
+ "[E-41]",
47
+ "[E-42]",
48
+ "[E-43]",
49
+ "[E-44]",
50
+ "[E-45]",
51
+ "[E-46]",
52
+ "[E-47]",
53
+ "[E-48]",
54
+ "[E-49]",
55
+ "[E-50]",
56
+ "[E-51]",
57
+ "[E-52]",
58
+ "[E-53]",
59
+ "[E-54]",
60
+ "[E-55]",
61
+ "[E-56]",
62
+ "[E-57]",
63
+ "[E-58]",
64
+ "[E-59]",
65
+ "[E-60]",
66
+ "[E-61]",
67
+ "[E-62]",
68
+ "[E-63]",
69
+ "[E-64]",
70
+ "[E-65]",
71
+ "[E-66]",
72
+ "[E-67]",
73
+ "[E-68]",
74
+ "[E-69]",
75
+ "[E-70]",
76
+ "[E-71]",
77
+ "[E-72]",
78
+ "[E-73]",
79
+ "[E-74]",
80
+ "[E-75]",
81
+ "[E-76]",
82
+ "[E-77]",
83
+ "[E-78]",
84
+ "[E-79]",
85
+ "[E-80]",
86
+ "[E-81]",
87
+ "[E-82]",
88
+ "[E-83]",
89
+ "[E-84]",
90
+ "[E-85]",
91
+ "[E-86]",
92
+ "[E-87]",
93
+ "[E-88]",
94
+ "[E-89]",
95
+ "[E-90]",
96
+ "[E-91]",
97
+ "[E-92]",
98
+ "[E-93]",
99
+ "[E-94]",
100
+ "[E-95]",
101
+ "[E-96]",
102
+ "[E-97]",
103
+ "[E-98]",
104
+ "[E-99]"
105
+ ],
106
+ "bos_token": "[CLS]",
107
+ "clean_up_tokenization_spaces": true,
108
+ "cls_token": "[CLS]",
109
+ "do_lower_case": false,
110
+ "eos_token": "[SEP]",
111
+ "mask_token": "[MASK]",
112
+ "model_max_length": 1000000000000000019884624838656,
113
+ "pad_token": "[PAD]",
114
+ "sep_token": "[SEP]",
115
+ "sp_model_kwargs": {},
116
+ "split_by_punct": false,
117
+ "tokenizer_class": "DebertaV2Tokenizer",
118
+ "unk_token": "[UNK]",
119
+ "vocab_type": "spm"
120
+ }