-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
192 lines (146 loc) · 5.55 KB
/
model.py
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
"""Build Model"""
import torch
from tokenizers import BertWordPieceTokenizer, ByteLevelBPETokenizer
from transformers import BertModel, BertConfig
from transformers import RobertaModel, RobertaConfig
from transformers import ElectraModel, ElectraConfig, ElectraTokenizerFast
from transformers import AutoModelForQuestionAnswering
from transformers.modeling_bert import BertPreTrainedModel
import config as cfg
def init_tokenizer(model_type):
"""토크나이저 사용 전에 반드시 호출"""
model_path_dict = cfg.get_model_path(model_type)
print(model_path_dict)
if model_type in ['bert', 'electra']:
tokenizer = BertWordPieceTokenizer(
model_path_dict['tokenizer'],
lowercase=True
)
elif model_type == 'roberta':
tokenizer = ByteLevelBPETokenizer(
vocab_file=model_path_dict['tokenizer']['vocab_file'],
merges_file=model_path_dict['tokenizer']['merges_file'],
lowercase=True,
add_prefix_space=True
)
return tokenizer
def _get_bert(
model_type,
model_path_dict):
if model_type == 'bert':
config = BertConfig.from_pretrained(
model_path_dict['config']
)
config.output_hidden_states = True
bert = BertModel.from_pretrained(
model_path_dict['model'],
config=config)
elif model_type == 'electra':
config = ElectraConfig.from_pretrained(
model_path_dict['config'])
config.output_hidden_states = True
bert = ElectraModel.from_pretrained(
model_path_dict['model'],
config=config)
elif model_type == 'roberta':
config = RobertaConfig.from_pretrained(
model_path_dict['config'])
config.output_hidden_states = True
bert = RobertaModel.from_pretrained(
model_path_dict['model'],
config=config)
return bert, config
def _get_hidden(bert, model_type, input_ids, attention_mask, token_type_ids):
if model_type == 'bert':
hidden_states, _, hidden = bert(input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids)
elif model_type == 'electra':
hidden_states, hidden = bert(input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids)
elif model_type == 'roberta':
hidden_states, _, hidden = bert(input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids)
return hidden
class SentimentExtractor(torch.nn.Module):
def __init__(self, model_type='electra', max_seq_len=128, dropout_rate=0.1, last_n_layers=2):
super(SentimentExtractor, self).__init__()
model_path_dict = cfg.get_model_path(model_type)
self.model_type = model_type.lower()
self.last_n_layers = last_n_layers
self.bert, self.config = _get_bert(self.model_type, model_path_dict)
bert_hidden_dim = self.bert.config.hidden_size
self.fc_for_idx = torch.nn.Linear(bert_hidden_dim*last_n_layers, 2)
self.fc_for_seq = torch.nn.Linear(bert_hidden_dim*last_n_layers, 1)
self.bn_1 = torch.nn.BatchNorm1d(max_seq_len)
self.bn_2 = torch.nn.BatchNorm1d(max_seq_len)
self.dropout = torch.nn.Dropout(dropout_rate)
torch.nn.init.normal_(self.fc_for_idx.weight, std=0.02)
torch.nn.init.normal_(self.fc_for_seq.weight, std=0.02)
def forward(self, input_ids, attention_mask, token_type_ids):
hidden = _get_hidden(self.bert, self.model_type, input_ids, attention_mask, token_type_ids)
hidden_concat = torch.cat(
tuple(
hidden[-(idx+1)] for idx in range(self.last_n_layers)
),
dim=-1
)
hidden_concat = self.bn_1(hidden_concat)
hidden_concat = self.dropout(hidden_concat) # (batch, seq, 2)
seq_logits = self.fc_for_seq(hidden_concat) # (batch, seq, 1)
seq_logits = self.bn_2(seq_logits)
seq_attn = torch.sigmoid(seq_logits)
_seq_logits = seq_logits.squeeze(-1) # (batch, seq)
hidden_attn = hidden_concat*seq_attn
idx_logits = self.fc_for_idx(hidden_attn)
idx_logits_splited = torch.split(idx_logits, split_size_or_sections=1, dim=-1) # (batch, seq, 1), (batch, seq, 1)
start_logits = idx_logits_splited[0].squeeze(-1)
end_logits = idx_logits_splited[1].squeeze(-1)
return start_logits, end_logits, _seq_logits
if __name__ == '__main__':
a = torch.tensor([
[
[1,1,1,1],
[2,2,2,2],
],
[
[3,3.1,3.2,3.3],
[4,4.1,4.2,4.3],
],
[
[5,5,5,5],
[6,6,6,6],
]
]) # (3b, 2t, 4h)
a = torch.tensor([
[
[1,1,10],
[2,2,9],
[3,3,11],
]
]) # (3b, 3tokens)
b = torch.tensor([
[0.1, 0.5, 0.1],
[0.3, 0.7, 0.2],
[0.8, 0.2, 0.1],
]) # (3b, 3tokens)
# b = b.unsqueeze(-1)
print(a.size())
print(a)
print()
print(b.size())
print(b)
print()
print(a*b)
x = torch.tensor([
[
[0.9, 0.9, 0.1, 0.1, 0.1, 0.9, 0.9, 0.9],
[0.1, 0.1, 0.9, 0.9, 0.9, 0.1, 0.1, 0.1],
],
])
y = torch.tensor([
[0, 0, 1, 1, 1, 0, 0, 0]
])
print(torch.nn.CrossEntropyLoss()(x, y))