Update models.py
Browse files
models.py
CHANGED
|
@@ -1,20 +1,70 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import os
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from transformers import RobertaPreTrainedModel, RobertaModel, AutoConfig
|
| 5 |
+
from transformers.modeling_outputs import SequenceClassifierOutput
|
| 6 |
+
|
| 7 |
+
class TransformerForABSA(RobertaPreTrainedModel):
|
| 8 |
+
base_model_prefix = "roberta"
|
| 9 |
+
|
| 10 |
+
def __init__(self, config):
|
| 11 |
+
super().__init__(config)
|
| 12 |
+
self.roberta = RobertaModel(config)
|
| 13 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 14 |
+
# Thêm lớp "none" vào num_sentiments
|
| 15 |
+
self.sentiment_classifiers = nn.ModuleList([
|
| 16 |
+
nn.Linear(config.hidden_size, config.num_sentiments + 1) # +1 cho "none"
|
| 17 |
+
for _ in range(config.num_aspects)
|
| 18 |
+
])
|
| 19 |
+
self.init_weights()
|
| 20 |
+
|
| 21 |
+
def forward(
|
| 22 |
+
self,
|
| 23 |
+
input_ids=None,
|
| 24 |
+
attention_mask=None,
|
| 25 |
+
labels=None,
|
| 26 |
+
return_dict=None
|
| 27 |
+
):
|
| 28 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 29 |
+
outputs = self.roberta(input_ids, attention_mask=attention_mask, return_dict=return_dict)
|
| 30 |
+
pooled = self.dropout(outputs.pooler_output) # [B, H]
|
| 31 |
+
all_logits = torch.stack([cls(pooled) for cls in self.sentiment_classifiers], dim=1) # [B, A, S+1]
|
| 32 |
+
|
| 33 |
+
loss = None
|
| 34 |
+
if labels is not None:
|
| 35 |
+
# labels: [B, A], với lớp "none" thay vì -100
|
| 36 |
+
B, A, _ = all_logits.size()
|
| 37 |
+
logits_flat = all_logits.view(-1, all_logits.size(-1))
|
| 38 |
+
targets_flat = labels.view(-1)
|
| 39 |
+
loss_fct = nn.CrossEntropyLoss() # Không dùng ignore_index
|
| 40 |
+
loss = loss_fct(logits_flat, targets_flat)
|
| 41 |
+
|
| 42 |
+
if not return_dict:
|
| 43 |
+
return ((loss, all_logits) + outputs[2:]) if loss is not None else (all_logits,) + outputs[2:]
|
| 44 |
+
return SequenceClassifierOutput(
|
| 45 |
+
loss=loss,
|
| 46 |
+
logits=all_logits,
|
| 47 |
+
hidden_states=outputs.hidden_states,
|
| 48 |
+
attentions=outputs.attentions,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def save_pretrained(self, save_directory: str, **kwargs):
|
| 52 |
+
"""
|
| 53 |
+
HuggingFace Trainer đôi khi truyền vào state_dict=..., nên ta
|
| 54 |
+
chấp nhận thêm **kwargs để không vướng lỗi.
|
| 55 |
+
"""
|
| 56 |
+
# 1) Lưu phần backbone (encoder)
|
| 57 |
+
self.roberta.save_pretrained(save_directory, **kwargs)
|
| 58 |
+
|
| 59 |
+
# 2) Cập nhật config rồi lưu
|
| 60 |
+
config = self.roberta.config
|
| 61 |
+
config.num_aspects = len(self.sentiment_classifiers)
|
| 62 |
+
config.num_sentiments = self.sentiment_classifiers[0].out_features
|
| 63 |
+
config.auto_map = {"AutoModel": "models.TransformerForABSA"}
|
| 64 |
+
config.save_pretrained(save_directory, **kwargs)
|
| 65 |
+
|
| 66 |
+
# 3) Lưu toàn bộ state_dict (bao gồm cả 2 head) —
|
| 67 |
+
# nếu Trainer đã truyền state_dict trong kwargs, có thể dùng luôn,
|
| 68 |
+
# nếu không, lấy từ self.state_dict()
|
| 69 |
+
sd = kwargs.get("state_dict", None) or self.state_dict()
|
| 70 |
+
torch.save(sd, os.path.join(save_directory, "pytorch_model.bin"))
|