Update modeling.py
Browse files- modeling.py +51 -51
modeling.py
CHANGED
|
@@ -1,51 +1,51 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import torch.nn as nn
|
| 3 |
-
|
| 4 |
-
from transformers import
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
class
|
| 8 |
-
def __init__(self,
|
| 9 |
-
super().__init__()
|
| 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 |
-
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from transformers.modeling_outputs import SequenceClassifierOutput
|
| 4 |
+
from transformers.models.roberta.modeling_roberta import RobertaPreTrainedModel, RobertaModel
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class RobertaForSequenceClassification(RobertaPreTrainedModel):
|
| 8 |
+
def __init__(self, config):
|
| 9 |
+
super().__init__(config)
|
| 10 |
+
|
| 11 |
+
self.num_labels = config.num_labels
|
| 12 |
+
self.roberta = RobertaModel(config)
|
| 13 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 14 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 15 |
+
|
| 16 |
+
# Load weights
|
| 17 |
+
self.post_init()
|
| 18 |
+
|
| 19 |
+
def forward(
|
| 20 |
+
self,
|
| 21 |
+
input_ids=None,
|
| 22 |
+
attention_mask=None,
|
| 23 |
+
token_type_ids=None,
|
| 24 |
+
labels=None,
|
| 25 |
+
**kwargs
|
| 26 |
+
):
|
| 27 |
+
outputs = self.roberta(
|
| 28 |
+
input_ids=input_ids,
|
| 29 |
+
attention_mask=attention_mask,
|
| 30 |
+
token_type_ids=token_type_ids,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
pooled_output = outputs[1] # CLS token
|
| 34 |
+
pooled_output = self.dropout(pooled_output)
|
| 35 |
+
logits = self.classifier(pooled_output)
|
| 36 |
+
|
| 37 |
+
loss = None
|
| 38 |
+
if labels is not None:
|
| 39 |
+
if self.num_labels == 1:
|
| 40 |
+
loss_fct = nn.MSELoss()
|
| 41 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 42 |
+
else:
|
| 43 |
+
loss_fct = nn.BCEWithLogitsLoss()
|
| 44 |
+
loss = loss_fct(logits, labels.float())
|
| 45 |
+
|
| 46 |
+
return SequenceClassifierOutput(
|
| 47 |
+
loss=loss,
|
| 48 |
+
logits=logits,
|
| 49 |
+
hidden_states=outputs.hidden_states,
|
| 50 |
+
attentions=outputs.attentions,
|
| 51 |
+
)
|