-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_evaluation.py
306 lines (248 loc) · 10.3 KB
/
local_evaluation.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import os
import metrics
import numpy as np
import pandas as pd
import parsers
import torch
from tqdm import tqdm
import json
import fire
VERSION = "0.1.0"
def print_sample(idx, generation, truth, metric, score):
"""
Print a sample's generated output, the truth, and its evaluation score.
"""
print(f"Sample {idx}, generation: {generation}")
print(f"Sample {idx}, truth: {truth}")
if isinstance(score, tuple) and len(score) == 3:
print(
f"Per Sample Metric Score ({metric}): tp {score[0]}, fp {score[1]}, fn {score[2]}"
)
else:
print(f"Per Sample Metric Score ({metric}): {score}")
print()
# Function to load development data from a JSON file
def load_development_data(filename):
"""
Load development data from a specified JSON file.
Parameters:
- filename: Path to the JSON file containing the development data.
Returns:
- A pandas DataFrame containing the loaded data.
"""
if "EC-Guide" in filename:
return pd.read_json(filename)
else:
return pd.read_json(filename, lines=True)
# Function to generate model outputs based on the input data
def generate_model_outputs(data_df, model):
"""
Generate predictions for each entry in the data DataFrame using a given model.
Parameters:
- data_df: A pandas DataFrame containing the input data for predictions.
- model: The model instance used for generating predictions.
Returns:
- A list containing the model outputs for each entry in the data DataFrame.
"""
outputs = []
task_grouped_df = data_df.groupby(by=["task_type"])
for task_type, task_group_data_df in task_grouped_df:
# if task_type[0] != 'multiple-choice':
# continue
task_group_data_df = task_group_data_df.reset_index(drop=True)
is_multiple_choice = task_type[0] == "multiple-choice"
batch_size = model.get_batch_size()
batches = [task_group_data_df[i:i+batch_size] for i in range(0,len(task_group_data_df),batch_size)]
for batch_df in tqdm(batches):
batch = {
"prompt": batch_df["input_field"].tolist(),
}
model_output, formatted_prompt = model.batch_predict(
batch,
is_multiple_choice,
task_type[0]
)
# outputs.append(
# pd.DataFrame({
# "input_field": batch["prompt"],
# "model_output_str": model_output
# }))
outputs.append(
pd.DataFrame({
"input_field": batch["prompt"],
"model_output_str": model_output,
"formatted_prompt": formatted_prompt
}))
df_outputs = pd.concat(outputs)
return df_outputs
# Function to evaluate the generated model outputs
def evaluate_outputs(data_df, log_every_n_steps=1):
"""
Evaluate the model outputs against ground truth values using specified metrics.
Parameters:
- data_df: DataFrame containing the development data, including ground truth.
- outputs: The generated outputs from the model to be evaluated.
- log_every_n_steps: Logs samples every N steps
Returns:
- A dictionary containing evaluation metrics and scores for each task.
"""
eval_methods = get_evaluation_methods()
task_parsers = get_task_parsers()
per_task_metrics = {}
for row_idx, row in tqdm(
data_df.iterrows(), total=len(data_df), desc="Evaluating"
):
task_name, task_type, metric, ground_truth, model_output_str = (
row["task_name"],
row["task_type"],
row["metric"],
row["output_field"],
row["model_output_str"],
)
if metric not in eval_methods:
print(metric)
raise NotImplementedError(f"No metric for {metric=}")
model_output = task_parsers[task_type].parse(model_output_str)
eval_fn = eval_methods[metric]
metric_score = eval_fn(model_output, ground_truth)
if task_name not in per_task_metrics:
per_task_metrics[task_name] = {
"task_type": task_type,
"metric": metric,
"sample_score": [],
}
per_task_metrics[task_name]["sample_score"].append(metric_score)
if (row_idx + 1) % log_every_n_steps == 0:
print_sample(
row_idx + 1, model_output, ground_truth, metric, metric_score
)
return per_task_metrics
# Function to aggregate scores from evaluations
def aggregate_scores(per_task_metrics):
"""
Aggregate evaluation scores across different tasks and metrics.
Parameters:
- per_task_metrics: A dictionary containing raw evaluation scores for each task.
Returns:
- A pandas DataFrame summarizing the overall metrics and scores.
"""
overall_metrics = {
"task_name": [],
"task_type": [],
"metric": [],
"num_samples": [],
"overall_score": [],
}
for task_name, values in per_task_metrics.items():
task_type, metric, sample_scores = (
values["task_type"],
values["metric"],
values["sample_score"],
)
overall_score = (
np.mean(sample_scores)
if metric != "micro f1"
else metrics.calculate_f1_score(sample_scores)
)
overall_metrics["task_name"].append(task_name)
overall_metrics["task_type"].append(task_type)
overall_metrics["metric"].append(metric)
overall_metrics["num_samples"].append(len(sample_scores))
overall_metrics["overall_score"].append(overall_score)
return pd.DataFrame(overall_metrics)
# Define and return evaluation methods
def get_evaluation_methods():
"""
Get evaluation methods including accuracy, sentence transformers, and other metrics.
Returns:
- A dictionary mapping metric names to their respective evaluation functions.
"""
return {
"accuracy": metrics.calculate_per_sample_accuracy,
"hit rate@3": metrics.calculate_hit_rate_3,
"rougel": metrics.calculate_rougel,
"sent-transformer": lambda generated_text, reference_texts: metrics.calculate_cosine_similarity(
generated_text=generated_text,
reference_texts=reference_texts,
model_name="/all-MiniLM-L6-v2",
),
"multilingual-sent-transformer": lambda generated_text, reference_texts: metrics.calculate_cosine_similarity(
generated_text=generated_text,
reference_texts=reference_texts,
model_name="/paraphrase-multilingual-MiniLM-L12-v2",
),
"micro f1": metrics.calculate_true_positive_false_positives_false_negatives,
"ndcg": metrics.calculate_ndcg,
"bleu": metrics.calculate_bleu_score,
"jp-bleu": lambda generated_text, reference_text: metrics.calculate_bleu_score(
generated_text=generated_text,
reference_text=reference_text,
is_japanese=True,
),
}
# Define and return task parsers
def get_task_parsers():
"""
Define parsers for different task types to format model outputs accordingly.
Returns:
- A dictionary mapping task types to their respective parsers.
"""
return {
"multiple-choice": parsers.ShoppingBenchTaskParsers("multichoice"),
"generation": parsers.ShoppingBenchTaskParsers("generation"),
"retrieval": parsers.ShoppingBenchTaskParsers("retrieval"),
"ranking": parsers.ShoppingBenchTaskParsers("ranking"),
"named_entity_recognition": parsers.ShoppingBenchTaskParsers(
"named_entity_recognition"
),
}
# Main execution function to load data, generate model outputs, evaluate, and aggregate scores
def main(model_path, data_path, instruction="None"):
# Load development data
# Please download the development data from : https://www.aicrowd.com/challenges/amazon-kdd-cup-2024-multi-task-online-shopping-challenge-for-llms/dataset_files
# and place it at: ./data/development.json
if not os.path.exists(data_path):
raise FileNotFoundError(
f"Development data file not found at {data_path}."
"Please download the development data from : https://www.aicrowd.com/challenges/amazon-kdd-cup-2024-multi-task-online-shopping-challenge-for-llms/dataset_files"
"and place it at: ./data/development.json"
)
data_df = load_development_data(data_path)
# Load the model from the user's custom configuration
# Note: The evaluator **Always** imports the UserModel, please reference your own class
# by setting the `UserModel` variable in models.user_config
from models.user_config import UserModel
model = UserModel(model_path, instruction)
# Generate model outputs
df_outputs = generate_model_outputs(data_df, model)
# add outputs to the data_df
merged_data_df = pd.merge(data_df, df_outputs, on="input_field")
for index, row in merged_data_df.iterrows():
print("==========input_field {} [{}]==================".format(index + 1, row['task_name']))
print(row['formatted_prompt'])
print("==========model_output_str==================")
print(row['model_output_str'])
print("==========output_field==================")
print(row['output_field'])
print(merged_data_df.head())
# Evaluate the generated outputs and calculate metrics
per_task_metrics = evaluate_outputs(merged_data_df)
# Aggregate and display the evaluation scores
overall_metrics = aggregate_scores(per_task_metrics)
print("=" * 100)
print("Task specific metrics: ")
print(overall_metrics)
overall_metrics.to_csv(log_path, index=False)
print()
# Calculate and print the overall score across all tasks and metrics
# overall_score = overall_metrics["overall_score"].mean()
overall_score = 0
num_samples_list = overall_metrics['num_samples']
for i,j in zip(num_samples_list, overall_metrics['overall_score']):
overall_score += i*j/sum(num_samples_list)
print(f"Overall Score: {overall_score}")
with open(log_path, 'a') as f:
f.writelines(f"Overall Score: {overall_score}")
if __name__ == "__main__":
fire.Fire(main)
# main()