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|
|
1 |
+
import copy
|
2 |
+
import warnings
|
3 |
+
from typing import List, Optional, Tuple, Union
|
4 |
+
|
5 |
+
import torch
|
6 |
+
from torch import nn
|
7 |
+
from torch.nn import CrossEntropyLoss, MSELoss, BCEWithLogitsLoss
|
8 |
+
|
9 |
+
from transformers import AutoModelForSequenceClassification
|
10 |
+
from transformers.modeling_outputs import (
|
11 |
+
BaseModelOutput,
|
12 |
+
Seq2SeqSequenceClassifierOutput,
|
13 |
+
)
|
14 |
+
from transformers.models.t5.configuration_t5 import T5Config
|
15 |
+
from transformers.models.t5.modeling_t5 import T5PreTrainedModel, T5Stack
|
16 |
+
|
17 |
+
|
18 |
+
class T5ClassificationHead(nn.Module):
|
19 |
+
"""Head for sentence-level classification tasks."""
|
20 |
+
|
21 |
+
def __init__(
|
22 |
+
self,
|
23 |
+
input_dim: int,
|
24 |
+
inner_dim: int,
|
25 |
+
num_classes: int,
|
26 |
+
pooler_dropout: float,
|
27 |
+
):
|
28 |
+
super().__init__()
|
29 |
+
self.dense = nn.Linear(input_dim, inner_dim)
|
30 |
+
self.dropout = nn.Dropout(p=pooler_dropout)
|
31 |
+
self.out_proj = nn.Linear(inner_dim, num_classes)
|
32 |
+
|
33 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
34 |
+
hidden_states = self.dropout(hidden_states)
|
35 |
+
hidden_states = self.dense(hidden_states)
|
36 |
+
hidden_states = torch.tanh(hidden_states)
|
37 |
+
hidden_states = self.dropout(hidden_states)
|
38 |
+
hidden_states = self.out_proj(hidden_states)
|
39 |
+
return hidden_states
|
40 |
+
|
41 |
+
|
42 |
+
class T5ForSequenceClassification(T5PreTrainedModel):
|
43 |
+
_keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"]
|
44 |
+
_tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
|
45 |
+
|
46 |
+
def __init__(self, config: T5Config):
|
47 |
+
super().__init__(config)
|
48 |
+
self.model_dim = config.d_model
|
49 |
+
|
50 |
+
self.shared = nn.Embedding(config.vocab_size, config.d_model)
|
51 |
+
|
52 |
+
encoder_config = copy.deepcopy(config)
|
53 |
+
encoder_config.is_decoder = False
|
54 |
+
encoder_config.use_cache = False
|
55 |
+
encoder_config.is_encoder_decoder = False
|
56 |
+
self.encoder = T5Stack(encoder_config, self.shared)
|
57 |
+
|
58 |
+
decoder_config = copy.deepcopy(config)
|
59 |
+
decoder_config.is_decoder = True
|
60 |
+
decoder_config.is_encoder_decoder = False
|
61 |
+
decoder_config.num_layers = config.num_decoder_layers
|
62 |
+
self.decoder = T5Stack(decoder_config, self.shared)
|
63 |
+
|
64 |
+
self.num_labels = config.num_labels
|
65 |
+
|
66 |
+
self.classification_head = T5ClassificationHead(
|
67 |
+
config.d_model,
|
68 |
+
config.d_model,
|
69 |
+
config.num_labels,
|
70 |
+
config.classifier_dropout,
|
71 |
+
)
|
72 |
+
|
73 |
+
# Initialize weights and apply final processing
|
74 |
+
self.post_init()
|
75 |
+
|
76 |
+
self.model_parallel = False
|
77 |
+
|
78 |
+
def get_input_embeddings(self):
|
79 |
+
return self.shared
|
80 |
+
|
81 |
+
def set_input_embeddings(self, new_embeddings):
|
82 |
+
self.shared = new_embeddings
|
83 |
+
self.encoder.set_input_embeddings(new_embeddings)
|
84 |
+
self.decoder.set_input_embeddings(new_embeddings)
|
85 |
+
|
86 |
+
def get_encoder(self):
|
87 |
+
return self.encoder
|
88 |
+
|
89 |
+
def get_decoder(self):
|
90 |
+
return self.decoder
|
91 |
+
|
92 |
+
def forward(
|
93 |
+
self,
|
94 |
+
input_ids: torch.LongTensor = None,
|
95 |
+
attention_mask: Optional[torch.Tensor] = None,
|
96 |
+
decoder_input_ids: Optional[torch.LongTensor] = None,
|
97 |
+
decoder_attention_mask: Optional[torch.LongTensor] = None,
|
98 |
+
head_mask: Optional[torch.Tensor] = None,
|
99 |
+
decoder_head_mask: Optional[torch.Tensor] = None,
|
100 |
+
cross_attn_head_mask: Optional[torch.Tensor] = None,
|
101 |
+
encoder_outputs: Optional[List[torch.FloatTensor]] = None,
|
102 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
103 |
+
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
|
104 |
+
labels: Optional[torch.LongTensor] = None,
|
105 |
+
use_cache: Optional[bool] = None,
|
106 |
+
output_attentions: Optional[bool] = None,
|
107 |
+
output_hidden_states: Optional[bool] = None,
|
108 |
+
return_dict: Optional[bool] = None,
|
109 |
+
) -> Union[Tuple, Seq2SeqSequenceClassifierOutput]:
|
110 |
+
r"""
|
111 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
112 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
113 |
+
config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
114 |
+
Returns:
|
115 |
+
"""
|
116 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
117 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
118 |
+
if labels is not None:
|
119 |
+
use_cache = False
|
120 |
+
|
121 |
+
# Copied from models.bart.modeling_bart.BartModel.forward
|
122 |
+
# different to other models, T5 automatically creates decoder_input_ids from
|
123 |
+
# input_ids if no decoder_input_ids are provided
|
124 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
125 |
+
if input_ids is None:
|
126 |
+
raise ValueError(
|
127 |
+
"If no `decoder_input_ids` or `decoder_inputs_embeds` are "
|
128 |
+
"passed, `input_ids` cannot be `None`. Please pass either "
|
129 |
+
"`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
|
130 |
+
)
|
131 |
+
decoder_input_ids = self._shift_right(input_ids)
|
132 |
+
|
133 |
+
# FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
|
134 |
+
if head_mask is not None and decoder_head_mask is None:
|
135 |
+
if self.config.num_layers == self.config.num_decoder_layers:
|
136 |
+
warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)
|
137 |
+
decoder_head_mask = head_mask
|
138 |
+
|
139 |
+
# Encode if needed (training, first prediction pass)
|
140 |
+
if encoder_outputs is None:
|
141 |
+
encoder_outputs = self.encoder(
|
142 |
+
input_ids=input_ids,
|
143 |
+
attention_mask=attention_mask,
|
144 |
+
inputs_embeds=inputs_embeds,
|
145 |
+
head_mask=head_mask,
|
146 |
+
output_attentions=output_attentions,
|
147 |
+
output_hidden_states=output_hidden_states,
|
148 |
+
return_dict=return_dict,
|
149 |
+
)
|
150 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
151 |
+
encoder_outputs = BaseModelOutput(
|
152 |
+
last_hidden_state=encoder_outputs[0],
|
153 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
154 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
155 |
+
)
|
156 |
+
|
157 |
+
hidden_states = encoder_outputs[0]
|
158 |
+
|
159 |
+
# Decode
|
160 |
+
decoder_outputs = self.decoder(
|
161 |
+
input_ids=decoder_input_ids,
|
162 |
+
attention_mask=decoder_attention_mask,
|
163 |
+
inputs_embeds=decoder_inputs_embeds,
|
164 |
+
past_key_values=None,
|
165 |
+
encoder_hidden_states=hidden_states,
|
166 |
+
encoder_attention_mask=attention_mask,
|
167 |
+
head_mask=decoder_head_mask,
|
168 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
169 |
+
use_cache=use_cache,
|
170 |
+
output_attentions=output_attentions,
|
171 |
+
output_hidden_states=output_hidden_states,
|
172 |
+
return_dict=return_dict,
|
173 |
+
)
|
174 |
+
|
175 |
+
sequence_output = decoder_outputs[0]
|
176 |
+
|
177 |
+
eos_mask = input_ids.eq(self.config.eos_token_id).to(sequence_output.device)
|
178 |
+
|
179 |
+
if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:
|
180 |
+
raise ValueError("All examples must have the same number of <eos> tokens.")
|
181 |
+
sentence_representation = sequence_output[eos_mask, :].view(
|
182 |
+
sequence_output.size(0), -1, sequence_output.size(-1)
|
183 |
+
)[:, -1, :]
|
184 |
+
logits = self.classification_head(sentence_representation)
|
185 |
+
|
186 |
+
loss = None
|
187 |
+
if labels is not None:
|
188 |
+
labels = labels.to(logits.device)
|
189 |
+
if self.config.problem_type is None:
|
190 |
+
if self.config.num_labels == 1:
|
191 |
+
self.config.problem_type = "regression"
|
192 |
+
elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
193 |
+
self.config.problem_type = "single_label_classification"
|
194 |
+
else:
|
195 |
+
self.config.problem_type = "multi_label_classification"
|
196 |
+
|
197 |
+
if self.config.problem_type == "regression":
|
198 |
+
loss_fct = MSELoss()
|
199 |
+
if self.config.num_labels == 1:
|
200 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
201 |
+
else:
|
202 |
+
loss = loss_fct(logits, labels)
|
203 |
+
elif self.config.problem_type == "single_label_classification":
|
204 |
+
loss_fct = CrossEntropyLoss()
|
205 |
+
loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
|
206 |
+
elif self.config.problem_type == "multi_label_classification":
|
207 |
+
loss_fct = BCEWithLogitsLoss()
|
208 |
+
loss = loss_fct(logits, labels)
|
209 |
+
if not return_dict:
|
210 |
+
output = (logits,) + decoder_outputs[1:] + encoder_outputs
|
211 |
+
return ((loss,) + output) if loss is not None else output
|
212 |
+
|
213 |
+
return Seq2SeqSequenceClassifierOutput(
|
214 |
+
loss=loss,
|
215 |
+
logits=logits,
|
216 |
+
past_key_values=decoder_outputs.past_key_values,
|
217 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
218 |
+
decoder_attentions=decoder_outputs.attentions,
|
219 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
220 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
221 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
222 |
+
encoder_attentions=encoder_outputs.attentions,
|
223 |
+
)
|
224 |
+
|
225 |
+
|
226 |
+
AutoModelForSequenceClassification.register(T5Config, T5ForSequenceClassification)
|
227 |
+
|