-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscore.py
277 lines (248 loc) · 8.83 KB
/
score.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import torch
from torch import Tensor
import pandas as pd
from pandas import DataFrame
from tqdm.auto import tqdm
from method.postprocessor import PostProcessor
from method.calibration import get_calibrated_prob_and_predscore
from method.utils import (
is_zps,
is_ppl,
get_predictions,
get_f1_acc,
)
from method.prompt_filter import (
get_prompt_filter_indices,
apply_filter,
apply_filter_on_info
)
from method.methods import (
get_le,
get_mdl_m,
get_ge,
get_ge_m,
get_mi,
get_mi_g,
get_mi_l,
get_mi_gl,
get_mdl,
get_ppl,
get_i_ppl,
get_zlp,
get_zpm,
get_zmv,
)
from typing import Dict, Callable, List, Tuple, Union
def get_prob_for_scoring(
tensor_dict: Dict[str, Tensor], cali_score: bool, cali_type: str, cali_norm_type: str
) -> Tensor:
score_prob = tensor_dict['prob']
if cali_score:
score_prob, _ = get_calibrated_prob_and_predscore(score_prob, tensor_dict['log_unnorm_prob'], tensor_dict, cali_type, cali_norm_type, X_axis=1)
return score_prob
def get_predscore(
tensor_dict: Dict[str, Tensor], cali_eval: bool, cali_type: str, cali_norm_type: str
) -> Tensor:
if cali_eval:
_, predscore = get_calibrated_prob_and_predscore(tensor_dict['prob'], tensor_dict['log_unnorm_prob'], tensor_dict, cali_type, cali_norm_type, X_axis=1)
else:
predscore = tensor_dict['log_unnorm_prob'] # no need to normalize cuz we just argmax
return predscore
def get_task_wise_ps_scores(
methodFunc: Callable, tensor_dict_value: Tensor, zps: bool
) -> List[float]:
T = tensor_dict_value.size(0)
ps_scores = []
for t in range(T):
template_prob = tensor_dict_value[t]
if zps:
ps_score = methodFunc(template_prob, tensor_dict_value)
else:
ps_score = methodFunc(template_prob)
if isinstance(ps_score, torch.Tensor):
ps_score = ps_score.item()
ps_scores.append(ps_score)
return ps_scores
def get_instance_wise_ps_scores(
methodFunc: Callable, tensor_dict_value: Tensor
) -> Tuple[List[float], List[int]]:
return methodFunc(tensor_dict_value)
def get_task_wise_ps_result(
method: str,
post_processor: PostProcessor,
one_hot: bool,
cali_type: str,
cali_norm_type: str,
filter: bool,
unbalance: bool,
is_dynamic: bool,
) -> Tuple[DataFrame, Dict[str, Dict[str, List[int]]], List[int]]:
methodFuncMap = {
'MI': get_mi_g if one_hot else get_mi,
'GE': get_ge if one_hot else get_ge_m,
'LE': get_le,
'MDL': get_mdl_m,
'PPL': get_ppl,
'ZLP': get_zlp,
'ZPM': get_zpm,
'ZMV': get_zmv,
}
assert method in methodFuncMap, (
f"you can only use the following methods: {methodFuncMap.keys()}",
"Check the value of the method argument in ./conf/method.yaml",
)
methodFunc = methodFuncMap[method]
zps = is_zps(method)
ppl = is_ppl(method)
dfs = []
calibration_to_prompts_to_predictions = dict()
for combn, cali_score, cali_eval in tqdm([
('X', False, False),
('A', False, True),
('P', True, False),
('PA', True, True),
]):
tasks, models, prompts, tokens = post_processor.get_tasks_models_prompts_tokens()
if unbalance and is_dynamic:
tensor_dict, targets = post_processor.get_unbalanced_tensor_dict_and_targets()
tasks = [f"U_{task}" for task in tasks]
elif unbalance and not is_dynamic:
raise ValueError(
"The Unbalance argument is only available for dynamic tasks. Please adjust the configuration."
)
else:
tensor_dict, targets = post_processor.get_tensor_dict_and_targets()
# SCORE CALCULATION
score_prob = get_prob_for_scoring(tensor_dict, cali_score, cali_type, cali_norm_type)
# and then filter using the calibrated score
if filter:
filter_indices = get_prompt_filter_indices(score_prob)
score_prob, tensor_dict = apply_filter(score_prob, tensor_dict, filter_indices)
filtered_infos = [
apply_filter_on_info(infos, filter_indices)
for infos in [tasks, models, prompts, tokens]
]
tasks, models, prompts, tokens = filtered_infos
# PREDICTION
predscore = get_predscore(tensor_dict, cali_eval, cali_type, cali_norm_type) # [T, X, Y]
predictions = get_predictions(predscore)
f1, acc = get_f1_acc(predictions, targets)
calibration_to_prompts_to_predictions[combn] = {k: v for k, v in zip(prompts, predictions)}
if ppl:
score_prob = tensor_dict['perplexity']
ps_scores = get_task_wise_ps_scores(
methodFunc, score_prob, zps
)
dfs.append(pd.DataFrame({
'model': models,
'task': tasks,
'token': tokens,
'prompt': prompts,
'combn': [combn] * len(acc),
'acc': acc,
'f1': f1,
f'{method}': ps_scores,
}))
return pd.concat(dfs, ignore_index=True), calibration_to_prompts_to_predictions, targets.tolist()
def get_instance_wise_ps_result(
method: str,
post_processor: PostProcessor,
one_hot: bool,
cali_type: str,
cali_norm_type: str,
filter: bool,
unbalance: bool,
is_dynamic: bool,
) -> DataFrame:
methodFuncMap = {
'PPL': get_i_ppl,
'MDL': get_mdl,
'MI': get_mi_gl if one_hot else get_mi_l,
}
assert method in methodFuncMap, (
f"If select_for_each_x == True, you can only use the following methods: {methodFuncMap.keys()}",
"Check the value of the method argument in ./conf/method.yaml",
)
methodFunc = methodFuncMap[method]
ppl = is_ppl(method)
df_rows = []
for combn, cali_score, cali_eval in tqdm([
('X', False, False),
('A', False, True),
('P', True, False),
('PA', True, True),
]):
tasks, models, prompts, tokens = post_processor.get_tasks_models_prompts_tokens()
if unbalance and is_dynamic:
tensor_dict, targets = post_processor.get_unbalanced_tensor_dict_and_targets()
tasks = [f"U_{task}" for task in tasks]
elif unbalance and not is_dynamic:
raise ValueError(
"The Unbalance argument is only available for dynamic tasks. Please adjust the configuration."
)
else:
tensor_dict, targets = post_processor.get_tensor_dict_and_targets()
# SCORE CALCULATION
score_prob = get_prob_for_scoring(tensor_dict, cali_score, cali_type, cali_norm_type)
# and then filter using the calibrated score
if filter:
filter_indices = get_prompt_filter_indices(score_prob)
score_prob, tensor_dict = apply_filter(score_prob, tensor_dict, filter_indices)
filtered_infos = [
apply_filter_on_info(infos, filter_indices)
for infos in [tasks, models, prompts, tokens]
]
tasks, models, prompts, tokens = filtered_infos
# PREDICTION
predscore = get_predscore(tensor_dict, cali_eval, cali_type, cali_norm_type) # [T, X, Y]
if ppl:
score_prob = tensor_dict['perplexity']
ps_scores, selected_prompt_indices = get_instance_wise_ps_scores(
methodFunc, score_prob
)
T, X, Y = predscore.size()
for i in range(X):
selected_prompt_idx = selected_prompt_indices[i]
prediction = predscore[selected_prompt_idx][i].argmax().item()
target = targets[i].item()
df_rows.append({
'model': models[selected_prompt_idx],
'task': tasks[selected_prompt_idx],
'token': tokens[selected_prompt_idx],
'prompt': prompts[selected_prompt_idx],
'combn': combn,
'instance': i,
'prediction': prediction,
'target': target,
'correct': prediction == target,
f'{method}': ps_scores[i],
})
return pd.DataFrame(df_rows)
def get_ps_result(
method: str,
post_processor: PostProcessor,
one_hot: bool,
cali_type: str,
cali_norm_type: str,
filter: bool,
unbalance: bool,
is_dynamic: bool,
select_for_each_x: bool,
) -> Union[
Tuple[DataFrame, Dict[str, Dict[str, List[int]]], List[int]],
DataFrame
]:
if select_for_each_x:
scoreFunc = get_instance_wise_ps_result
else:
scoreFunc = get_task_wise_ps_result
return scoreFunc(
method=method,
post_processor=post_processor,
one_hot=one_hot,
cali_type=cali_type,
cali_norm_type=cali_norm_type,
filter=filter,
unbalance=unbalance,
is_dynamic=is_dynamic,
)