MultiTarget.py
7.11 KB
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
'''import logging
logger = logging.getLogger(__name__)
import typing
import torch
from torch import nn
from transformers import PretrainedConfig
from transformers.modeling_outputs import TokenClassifierOutput
from transformers.modeling_utils import PreTrainedModel
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs
from transformers.utils.generic import can_return_tuple
from .training_utils import _get_loss
from .constants import (
ADJACENCY_MATRIX,
GRAPH_DEPRELS,
GRAPH_ADJACENCY_MATRIX,
)
class MultiTargetTokenClassification(PreTrainedModel):
lm_layer_input_keys = (
'input_ids',
'attention_mask',
'token_type_ids',
'position_ids',
'head_mask',
'inputs_embeds',
'output_attentions',
'output_hidden_states',
'return_dict',
'training',
)
linear_size = 128
@property
def lm_layer(self) -> torch.nn.Module:
print(self)
print(type(self))
raise NotImplementedError
def set_loss_weights(self, loss_weights : dict[str, float]) -> None:
self.loss_weights = loss_weights
def __init__(self, config : PretrainedConfig, **kwargs : typing.Any) -> None:
logger.info(f'config.model_type: {config.model_type}')
logger.info(f'self.config_class: {self.config_class}')
categories = kwargs.pop('categories')
labels = kwargs.pop('labels')
logger.info(f'categories: {categories}')
logger.info(f'labels: {self.config_class}')
super().__init__(config)
self.loss_weights = {}
self.categories, self.categories2d, self.categories3d = [], [], []
for cat in categories:
if cat == GRAPH_DEPRELS:
self.categories3d.append(cat)
elif cat in (ADJACENCY_MATRIX, GRAPH_ADJACENCY_MATRIX):
self.categories2d.append(cat)
else:
self.categories.append(cat)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifiers = nn.ModuleList([
nn.Linear(config.hidden_size, len(labels[cat])) for cat in self.categories
])
logger.info(f'created {len(self.classifiers)} classifier(s): {", ".join(self.categories)}')
self.mappings2d = nn.ModuleList([
nn.ModuleDict({
'head': nn.Linear(config.hidden_size, self.linear_size),
'dependent' : nn.Linear(config.hidden_size, self.linear_size),
}) for cat in self.categories2d
])
logger.info(f'created {len(self.mappings2d)} head/dependent mapping(s): {", ".join(self.categories2d)}')
self.mappings3d = nn.ModuleList([
nn.ModuleDict({
'head' : nn.Linear(config.hidden_size, self.linear_size),
'dependent' : nn.Linear(config.hidden_size, self.linear_size),
'classifier' : nn.Linear(2 * self.linear_size, len(labels[cat])),
}) for cat in self.categories3d
])
logger.info(f'created {len(self.mappings3d)} head/dependent mapping(s) with classifier: {", ".join(self.categories3d)}')
# Initialize weights and apply final processing
self.post_init() # type: ignore[no-untyped-call]
def get_lm_layer_outputs(
self,
input_ids: torch.Tensor | None = None,
attention_mask: torch.Tensor | None = None,
token_type_ids: torch.Tensor | None = None,
position_ids: torch.Tensor | None = None,
inputs_embeds: torch.Tensor | None = None,
**kwargs: typing.Any,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
outputs = self.lm_layer(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
return_dict=True,
**kwargs,
)
return outputs[0], outputs.hidden_states, outputs.attentions
@can_return_tuple
def forward(
self,
input_ids: torch.Tensor | None = None,
attention_mask: torch.Tensor | None = None,
token_type_ids: torch.Tensor | None = None,
position_ids: torch.Tensor | None = None,
inputs_embeds: torch.Tensor | None = None,
labels: torch.Tensor | None = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor] | TokenClassifierOutput:
#outputs = self.lm_layer(
# input_ids,
# attention_mask=attention_mask,
# token_type_ids=token_type_ids,
# position_ids=position_ids,
# inputs_embeds=inputs_embeds,
# return_dict=True,
# **kwargs,
#)
#sequence_output = outputs[0]
sequence_output, hidden_states, attentions = self.get_lm_layer_outputs(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
**kwargs,
)
sequence_output = self.dropout(sequence_output)
logits = [classifier(sequence_output) for classifier in self.classifiers]
for mapping in self.mappings2d:
heads = mapping['head'](sequence_output)
dependents = mapping['dependent'](sequence_output)
product = torch.einsum('bin, bjn -> bij', heads, dependents)
logits.append(product)
for mapping in self.mappings3d:
seq_len = sequence_output.shape[1]
hds = mapping['head'](sequence_output) # batch x seq_len x linear_size
dps = mapping['dependent'](sequence_output) # batch x seq_len x linear_size
h_expanded = hds.unsqueeze(dim=2).expand(-1, -1, seq_len, -1) # batch x seq_len x 1 x linear_size -> batch x seq_len x seq_len x linear_size
d_expanded = dps.unsqueeze(dim=1).expand(-1, seq_len, -1, -1) # batch x 1 x seq_len x linear_size -> batch x seq_len x seq_len x linear_size
concatenated = torch.cat([h_expanded, d_expanded], dim=-1) # batch x seq_len x seq_len x (linear_size*2)
result = mapping['classifier'](concatenated)
logits.append(result)
keys = self.categories + self.categories2d + self.categories3d
losses = []
for cat, _logits in zip(keys, logits):
if cat in kwargs:
# ground truth labels were passed, so compute loss
_labels = kwargs[cat]
loss_fn = _get_loss(cat)
_loss = loss_fn(_logits, _labels)
weight = self.loss_weights.get(cat, 1.0)
losses.append(weight * _loss)
return TokenClassifierOutput(
loss=sum(losses),
logits=dict(zip(keys, logits)),
hidden_states=hidden_states,
attentions=attentions,
)'''