-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRoberta_metric.py
190 lines (161 loc) · 6.97 KB
/
Roberta_metric.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
import os
from typing import List
import torch
from torch import nn
#import texar.torch as tx
# from texar.torch.modules import BERTEncoder
from transformers import AutoTokenizer, AutoModel
#from util.config_base import Config
class RoBERTaMetric(nn.Module):
NAME = 'Roberta_metric'
def __init__(self, args):
super().__init__()
self.tokenizer = AutoTokenizer.from_pretrained(
'roberta-base')
self.max_seq_length = args.max_seq_length
self.backbone = AutoModel.from_pretrained(args.pretrained_model_name)
roberta_hidden_size = self.backbone.config.hidden_size
mlp_hidden_size_1 = int(roberta_hidden_size / 2)
mlp_hidden_size_2 = int(mlp_hidden_size_1 / 2)
'''
self.mlp = nn.Sequential(
nn.Linear(roberta_hidden_size, mlp_hidden_size_1),
nn.ELU(),
nn.Linear(mlp_hidden_size_1, mlp_hidden_size_2),
nn.ELU(),
nn.Linear(mlp_hidden_size_2, 1),
nn.Sigmoid())
'''
self.turn_mlp = nn.Sequential(
nn.Linear(roberta_hidden_size*2, roberta_hidden_size),
nn.ELU()
)
self.diag_mlp = nn.Sequential(
nn.Linear(roberta_hidden_size*2, mlp_hidden_size_1),
nn.ELU(),
nn.Linear(mlp_hidden_size_1, mlp_hidden_size_2),
nn.ELU(),
nn.Linear(mlp_hidden_size_2, 1),
nn.Sigmoid()
)
self.device = torch.device("cuda".format(args.gpu))
self.to(self.device)
if hasattr(args, 'checkpoint_file_name'):
# loads checkpoint
checkpoint_file_path = os.path.join(
args.checkpoint_dir_path, args.checkpoint_file_name)
state_dict = torch.load(
checkpoint_file_path,
map_location='cuda:{}'.format(args.gpu))
self.load_state_dict(state_dict)
print('loading checkpoint from: {}'.format(checkpoint_file_path))
if hasattr(args, 'pretrain_checkpoint_file_name'):
# loads checkpoint
checkpoint_file_path = os.path.join(
args.pretrain_checkpoint_dir_path,
args.pretrain_checkpoint_file_name)
state_dict = torch.load(
checkpoint_file_path,
map_location='cuda:{}'.format(args.gpu))
self.load_state_dict(state_dict)
print('loading checkpoint from: {}'.format(checkpoint_file_path))
def get_hidden_size(self):
return self.backbone.config.hidden_size
def forward(self, input_ids, attention_mask, indice=[]):
output_dict = self.backbone(
input_ids=input_ids, attention_mask=attention_mask,
output_attentions=True,
output_hidden_states=True,
return_dict=True)
pooled_output = output_dict['pooler_output']
score = torch.tensor([0]) #self.mlp(pooled_output)
#get dialog score
last_hidden_state = output_dict['last_hidden_state'] #size:1*512*768
left = 0
last_hidden_state = last_hidden_state.squeeze(0)
diag_rep = last_hidden_state[0].unsqueeze(0)
for i in indice:
right = i
if right == 1: break
if right == left+1:
left=right
continue
turn_mean = torch.mean(last_hidden_state[int(left)+1:int(right)],0)
turn_max,_ = torch.max(last_hidden_state[int(left)+1:int(right)],0)
turn = torch.cat((turn_mean,turn_max),0)
turn_rep = self.turn_mlp(turn)
turn_rep = turn_rep.squeeze()
#print(diag_rep.size())
#print(turn_rep.size())
diag_rep = torch.cat((diag_rep, turn_rep.unsqueeze(0)), 0)
left = right
diag1 = torch.mean(diag_rep, 0)
diag2,_ = torch.max(diag_rep, 0)
diag = torch.cat((diag1,diag2), 0)
diag_score = self.diag_mlp(diag)
return output_dict, score, diag_score
@torch.no_grad()
def get_score(self, sample: list):
self.eval()
input_ids, attention_mask, indice = self.encode_dialog(
sample)
_, score, dscore = self.forward(input_ids, attention_mask, indice)
return score[0].item(), dscore[0].item()
def encode_dialog(self, dialog: str):
"""Encodes the given context-response pair into ids.
"""
tokenizer_outputs = self.tokenizer(
dialog,
return_tensors='pt', truncation=True,
padding='max_length')
input_ids = tokenizer_outputs['input_ids']
attention_mask = tokenizer_outputs['attention_mask']
ts_sep = torch.ones(600)
t_len = 0
#print(input_ids.size())
for n1,k in enumerate(input_ids[0]):
if k == 2:
ts_sep[t_len] = n1
t_len += 1
input_ids = input_ids.to(self.device)
#token_type_ids = token_type_ids.to(self.device)
attention_mask = attention_mask.to(self.device)
ts_sep = ts_sep.to(self.device)
'''
assert input_ids.size() == torch.Size([1, self.max_seq_length])
assert token_type_ids.size() == torch.Size([1, self.max_seq_length])
assert attention_mask.size() == torch.Size([1, self.max_seq_length])
'''
# tokenized_text = self.tokenizer.convert_ids_to_tokens(input_ids)
# print('context: ', context)
# print('response: ', response)
# print('tokenizer_outputs: ', tokenizer_outputs)
# print('tokenized_text: ', ' '.join(tokenized_text))
# print('length: ', len(tokenized_text))
# exit()
return input_ids, attention_mask, ts_sep
def encode_ctx_res_pair(self, context: List[str], response: str):
"""Encodes the given context-response pair into ids.
"""
context = ' '.join(context)
tokenizer_outputs = self.tokenizer(
text=context, text_pair=response,
return_tensors='pt', truncation=True,
padding='max_length', max_length=self.max_seq_length)
input_ids = tokenizer_outputs['input_ids']
token_type_ids = tokenizer_outputs['token_type_ids']
attention_mask = tokenizer_outputs['attention_mask']
input_ids = input_ids.to(self.device)
token_type_ids = token_type_ids.to(self.device)
attention_mask = attention_mask.to(self.device)
assert input_ids.size() == torch.Size([1, self.max_seq_length])
assert token_type_ids.size() == torch.Size([1, self.max_seq_length])
assert attention_mask.size() == torch.Size([1, self.max_seq_length])
# tokenized_text = self.tokenizer.convert_ids_to_tokens(input_ids)
# print('context: ', context)
# print('response: ', response)
# print('tokenizer_outputs: ', tokenizer_outputs)
# print('tokenized_text: ', ' '.join(tokenized_text))
# print('length: ', len(tokenized_text))
# exit()
return input_ids, token_type_ids, attention_mask