|
import glob |
|
import json |
|
import os |
|
from collections import defaultdict |
|
from dataclasses import dataclass |
|
from pathlib import Path |
|
|
|
import numpy as np |
|
|
|
from src.display.formatting import make_clickable_model |
|
from src.display.utils import AutoEvalColumn, ModelTraining, Tasks, Precision, WeightType, MalteseTraining |
|
from src.envs import TOKEN, API |
|
from src.submission.check_validity import is_model_on_hub, get_model_size |
|
|
|
|
|
@dataclass |
|
class EvalResult: |
|
"""Represents one full evaluation. Built from a combination of the result and request file for a given run. |
|
""" |
|
eval_name: str |
|
full_model: str |
|
org: str |
|
model: str |
|
revision: str |
|
results: dict |
|
precision: Precision = Precision.Unknown |
|
n_shot: int = 0 |
|
prompt_version: str = "1.0_english" |
|
seed: int = 0 |
|
model_training: ModelTraining = ModelTraining.NK |
|
maltese_training: MalteseTraining = MalteseTraining.NK |
|
language_count: int = None |
|
weight_type: WeightType = WeightType.Original |
|
architecture: str = "Unknown" |
|
license: str = "?" |
|
likes: int = 0 |
|
num_params: int = 0 |
|
date: str = "" |
|
still_on_hub: bool = False |
|
|
|
@classmethod |
|
def init_from_json_files(self, seed_directory): |
|
"""Inits the result from the specific model result file""" |
|
with open(list(seed_directory.values())[0][0]) as fp: |
|
data = json.load(fp) |
|
|
|
config = data.get("config") |
|
precision = Precision.from_str(config.get("model_dtype")) |
|
|
|
n_shot = config.get("n_shot") |
|
|
|
prompt_version = config.get("prompt_version") |
|
|
|
seed = config.get("seed") |
|
|
|
model_training = ModelTraining.from_str(config.get("model_training")) |
|
|
|
maltese_training = MalteseTraining.from_str(config.get("maltese_training")) |
|
|
|
language_count = config.get("language_count") |
|
|
|
model_size = config.get("model_num_parameters") |
|
|
|
|
|
org_and_model = config.get("model", None) |
|
org_and_model = org_and_model.split("/", 1) |
|
full_model = "/".join(org_and_model) |
|
|
|
revision = config.get("model_sha", config.get("model_revision", "main")) |
|
|
|
model_args = config.get("model_args") |
|
model_args["revision"] = revision |
|
model_args["trust_remote_code"] = True |
|
model_args["cache_dir"] = None |
|
base_model = None |
|
if "pretrained" in model_args: |
|
base_model = model_args.pop("pretrained") |
|
still_on_hub, _, model_config = is_model_on_hub( |
|
base_model or full_model, model_args, test_tokenizer=False, token=TOKEN, |
|
) |
|
architecture = "?" |
|
if model_config is not None: |
|
architectures = getattr(model_config, "architectures", None) |
|
if architectures: |
|
architecture = ";".join(architectures) |
|
license = "?" |
|
likes = 0 |
|
if still_on_hub: |
|
try: |
|
model_info = API.model_info(repo_id=full_model, revision=revision, token=TOKEN) |
|
if not model_size: |
|
model_size = get_model_size(model_info=model_info, precision=precision) |
|
license = model_info.cardData.get("license") |
|
likes = model_info.likes |
|
except Exception: |
|
pass |
|
|
|
|
|
results = defaultdict(dict) |
|
for seed, file_paths in seed_directory.items(): |
|
for file_path in file_paths: |
|
with open(file_path) as file: |
|
data = json.load(file)["results"] |
|
|
|
for task in Tasks: |
|
task = task.value |
|
if task.benchmark not in data or task.metric not in data[task.benchmark]: |
|
continue |
|
score = data[task.benchmark][task.metric] |
|
if task.metric in ("accuracy", "f1", "loglikelihood", "rouge"): |
|
score *= 100 |
|
results[task.benchmark + "_" + task.metric][seed] = score |
|
|
|
results = {task: np.mean(list(seed_results.values())) for task, seed_results in results.items()} |
|
|
|
if len(org_and_model) == 1: |
|
org = None |
|
model = org_and_model[0] |
|
else: |
|
org = org_and_model[0] |
|
model = org_and_model[1] |
|
result_key = f"{'_'.join(org_and_model)}_{revision}_{precision.value.name}_{n_shot}_{prompt_version}_{seed}" |
|
|
|
return self( |
|
eval_name=result_key, |
|
full_model=full_model, |
|
org=org, |
|
model=model, |
|
results=results, |
|
model_training=model_training, |
|
maltese_training=maltese_training, |
|
language_count=language_count or "?", |
|
precision=precision, |
|
revision=revision, |
|
n_shot=n_shot, |
|
prompt_version=prompt_version, |
|
seed=seed, |
|
still_on_hub=still_on_hub, |
|
architecture=architecture, |
|
likes=likes or "?", |
|
num_params=model_size and round(model_size / 1e9, 3), |
|
license=license, |
|
) |
|
|
|
def update_with_request_file(self, requests_path): |
|
"""Finds the relevant request file for the current model and updates info with it""" |
|
request_file = get_request_file_for_model(requests_path, self.full_model, self.precision.value.name) |
|
|
|
try: |
|
with open(request_file, "r") as f: |
|
request = json.load(f) |
|
self.model_training = ModelTraining.from_str(request.get("model_training", "")) |
|
self.weight_type = WeightType[request.get("weight_type", "Original")] |
|
self.license = request.get("license", "?") |
|
self.likes = request.get("likes", 0) |
|
self.num_params = request.get("params", 0) |
|
self.date = request.get("submitted_time", "") |
|
except Exception: |
|
print(f"Could not find request file for {self.org}/{self.model} with precision {self.precision.value.name}") |
|
|
|
def to_dict(self): |
|
"""Converts the Eval Result to a dict compatible with our dataframe display""" |
|
average = sum([v for v in self.results.values() if v is not None]) / len(Tasks) |
|
data_dict = { |
|
"eval_name": self.eval_name, |
|
AutoEvalColumn.precision.name: self.precision.value.name, |
|
AutoEvalColumn.n_shot.name: self.n_shot, |
|
AutoEvalColumn.prompt_version.name: self.prompt_version, |
|
AutoEvalColumn.model_training.name: self.model_training.value.name, |
|
AutoEvalColumn.maltese_training.name: self.maltese_training.value.name, |
|
AutoEvalColumn.model_symbol.name: self.model_training.value.symbol + "/" + self.maltese_training.value.symbol, |
|
AutoEvalColumn.language_count.name: self.language_count, |
|
AutoEvalColumn.weight_type.name: self.weight_type.value.name, |
|
AutoEvalColumn.architecture.name: self.architecture, |
|
AutoEvalColumn.model.name: make_clickable_model(self.full_model), |
|
AutoEvalColumn.revision.name: self.revision, |
|
AutoEvalColumn.average.name: average, |
|
AutoEvalColumn.license.name: self.license, |
|
AutoEvalColumn.likes.name: self.likes, |
|
AutoEvalColumn.params.name: self.num_params, |
|
AutoEvalColumn.still_on_hub.name: self.still_on_hub, |
|
} |
|
|
|
results_by_task_type = defaultdict(list) |
|
for task in Tasks: |
|
result = self.results.get(task.value.benchmark + "_" + task.value.metric) |
|
data_dict[task.value.col_name] = result |
|
if task.value.is_primary_metric: |
|
results_by_task_type[task.value.task_type].append(result) |
|
results_averages = [] |
|
for task_type, task_type_results in results_by_task_type.items(): |
|
average = sum([score for score in task_type_results if score is not None]) / len(task_type_results) |
|
data_dict[getattr(AutoEvalColumn, task_type.value.name).name] = average |
|
results_averages.append(average) |
|
data_dict[AutoEvalColumn.average.name] = np.mean(results_averages) if len(results_averages) > 1 else results_averages[0] |
|
|
|
return data_dict |
|
|
|
|
|
def get_request_file_for_model(requests_path, model_name, precision): |
|
"""Selects the correct request file for a given model. Only keeps runs tagged as FINISHED""" |
|
request_files = os.path.join( |
|
requests_path, |
|
f"{model_name}_eval_request_*.json", |
|
) |
|
request_files = glob.glob(request_files) |
|
|
|
|
|
request_file = "" |
|
request_files = sorted(request_files, reverse=True) |
|
for tmp_request_file in request_files: |
|
with open(tmp_request_file, "r") as f: |
|
req_content = json.load(f) |
|
if ( |
|
req_content["status"] in ["FINISHED"] |
|
and req_content["precision"] == precision.split(".")[-1] |
|
): |
|
request_file = tmp_request_file |
|
return request_file |
|
|
|
|
|
def get_raw_eval_results(results_path: str) -> list[EvalResult]: |
|
"""From the path of the results folder root, extract all needed info for results""" |
|
model_result_filepaths = defaultdict(lambda: defaultdict(list)) |
|
|
|
for directory_path in Path(results_path).rglob("*-shot/*/*/"): |
|
for file_path in directory_path.rglob("*-seed/results_*.json"): |
|
seed = file_path.parent.name.removesuffix("-seed") |
|
model_result_filepaths[directory_path.relative_to(results_path)][seed].append(file_path) |
|
|
|
eval_results = {} |
|
for model_result_filepath in model_result_filepaths.values(): |
|
|
|
eval_result = EvalResult.init_from_json_files(model_result_filepath) |
|
|
|
|
|
eval_name = eval_result.eval_name |
|
if eval_name in eval_results.keys(): |
|
eval_results[eval_name].results.update({k: v for k, v in eval_result.results.items() if v is not None}) |
|
else: |
|
eval_results[eval_name] = eval_result |
|
|
|
results = [] |
|
for v in eval_results.values(): |
|
try: |
|
v.to_dict() |
|
results.append(v) |
|
except KeyError: |
|
continue |
|
|
|
return results |
|
|