Download tasks/hydrogel-additional-formulation-adhesion/tests/grade.py from UnipatAI/SPU: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/datasets/UnipatAI/SPU/resolve/main/tasks/hydrogel-additional-formulation-adhesion/tests/grade.py
- Command line
-
hf download hf://datasets/UnipatAI/SPU/tasks/hydrogel-additional-formulation-adhesion/tests/grade.py
-
curl -L -o grade.py https://huggingface.co/datasets/UnipatAI/SPU/resolve/main/tasks/hydrogel-additional-formulation-adhesion/tests/grade.py
12.1 kB
| """Score complete experimental rankings by weighted Spearman correlation.""" | |
| import argparse | |
| import errno | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| import stat | |
| from pathlib import Path | |
| class TaskError(ValueError): | |
| pass | |
| class SubmissionError(ValueError): | |
| pass | |
| def unique_object(pairs): | |
| result = {} | |
| for key, value in pairs: | |
| if key in result: | |
| raise SubmissionError("duplicate_json_key") | |
| result[key] = value | |
| return result | |
| def load_json(raw): | |
| def reject_constant(value): | |
| raise SubmissionError("nonfinite_json_constant") | |
| return json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object, | |
| parse_constant=reject_constant) | |
| def finite(value, name, minimum=None): | |
| if isinstance(value, bool) or not isinstance(value, (int, float)): | |
| raise TaskError(name + " is not numeric") | |
| if not math.isfinite(value) or (minimum is not None and value < minimum): | |
| raise TaskError(name + " is out of range") | |
| return float(value) | |
| def bounded(value): | |
| if not math.isfinite(value) or not -1 - 1e-12 <= value <= 1 + 1e-12: | |
| raise TaskError('Spearman outside its finite range') | |
| return min(1.0, max(-1.0, value)) | |
| def average_ranks(values): | |
| if len(values) < 2 or any(isinstance(x, bool) or not isinstance(x, (int, float)) | |
| or not math.isfinite(x) for x in values): | |
| raise TaskError('Invalid measurements') | |
| ordered = sorted(range(len(values)), key=values.__getitem__) | |
| ranks = [0.0] * len(values) | |
| start = 0 | |
| while start < len(values): | |
| stop = start + 1 | |
| while stop < len(values) and values[ordered[stop]] == values[ordered[start]]: | |
| stop += 1 | |
| mean_rank = (start + 1 + stop) / 2 | |
| for index in ordered[start:stop]: | |
| ranks[index] = mean_rank | |
| start = stop | |
| return ranks | |
| def spearman(values, predicted_positions): | |
| ranks = average_ranks(values) | |
| n = len(values) | |
| if sorted(predicted_positions) != list(range(n)): | |
| raise ValueError('Not a complete permutation') | |
| predicted_ranks = [p + 1 for p in predicted_positions] | |
| true_mean = math.fsum(ranks) / n | |
| predicted_mean = math.fsum(predicted_ranks) / n | |
| x = [r - true_mean for r in ranks] | |
| y = [p - predicted_mean for p in predicted_ranks] | |
| denominator = math.sqrt(math.fsum(r * r for r in x) * math.fsum(p * p for p in y)) | |
| if denominator <= 0: | |
| raise TaskError('Undefined Spearman for constant results') | |
| return bounded(math.fsum(r * p for r, p in zip(x, y)) / denominator) | |
| def read_regular(path, limit): | |
| try: | |
| fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) | |
| try: | |
| info = os.fstat(fd) | |
| if not stat.S_ISREG(info.st_mode): | |
| raise SubmissionError("not_regular_file") | |
| if info.st_size > limit: | |
| raise SubmissionError("submission_too_large") | |
| with os.fdopen(fd, "rb", closefd=False) as stream: | |
| raw = stream.read(limit + 1) | |
| if len(raw) > limit: | |
| raise SubmissionError("submission_too_large") | |
| return raw | |
| finally: | |
| os.close(fd) | |
| except OSError as error: | |
| if error.errno in (errno.ENOENT, errno.ELOOP, errno.EISDIR, errno.ENOTDIR, | |
| errno.ENXIO, errno.EACCES, errno.EPERM): | |
| raise SubmissionError("missing_or_unreadable_submission") from error | |
| raise | |
| def validate_task(contract, answers): | |
| expected = { | |
| "scoring_method": "spearman", | |
| "primary_score": "task_spearman", | |
| "spearman_range": [-1, 1], | |
| "spearman_tie_method": "average", | |
| "spearman_undefined_policy": "task_error", | |
| } | |
| if any(contract.get(key) != value for key, value in expected.items()): | |
| raise TaskError("Unsupported scoring contract") | |
| for key in ("task_id", "task_version"): | |
| if not isinstance(contract.get(key), str) or answers.get(key) != contract[key]: | |
| raise TaskError("Invalid task identity") | |
| limit = contract.get("max_submission_bytes") | |
| if type(limit) is not int or not 0 < limit <= 1048576: | |
| raise TaskError("Invalid submission size limit") | |
| minimum = contract.get("minimum_conditions_per_group", 2) | |
| if type(minimum) is not int or minimum < 2: | |
| raise TaskError("Invalid minimum group size") | |
| groups = contract["groups"] | |
| references = {g["group_id"]: g for g in answers["groups"]} | |
| if not groups or len(groups) != len(references) or len(references) != len(answers["groups"]): | |
| raise TaskError("Invalid reference groups") | |
| measurements = {} | |
| all_ids = set() | |
| for group in groups: | |
| gid = group["group_id"] | |
| ids = group["item_ids"] | |
| if not isinstance(gid, str) or not gid or gid in measurements or gid not in references: | |
| raise TaskError("Invalid group ID") | |
| if (group["direction"] != "ascending" or not isinstance(ids, list) or len(ids) < minimum | |
| or any(not isinstance(i, str) or not i for i in ids) | |
| or len(set(ids)) != len(ids) or all_ids.intersection(ids)): | |
| raise TaskError("Invalid group definition") | |
| all_ids.update(ids) | |
| if finite(group["group_weight"], "group_weight", 0) == 0: | |
| raise TaskError("Zero group weight") | |
| items = references[gid]["items"] | |
| values = {item["item_id"]: item["mean"] for item in items} | |
| if len(items) != len(ids) or set(values) != set(ids): | |
| raise TaskError("Reference items differ from the contract") | |
| measurements[gid] = [values[i] for i in ids] | |
| spearman(measurements[gid], list(range(len(ids)))) | |
| if not math.isclose(math.fsum(g["group_weight"] for g in groups), 1.0, rel_tol=0, abs_tol=1e-12): | |
| raise TaskError("Group weights must sum to one") | |
| return measurements | |
| def group_entries(submission, contract): | |
| if not isinstance(submission, dict): | |
| raise SubmissionError("invalid_top_level_structure") | |
| if any(submission.get(key) != contract[key] for key in ("task_id", "task_version")): | |
| raise SubmissionError("task_identity_mismatch") | |
| if not isinstance(submission.get("rankings"), list): | |
| raise SubmissionError("rankings_not_array") | |
| entries = {group["group_id"]: [] for group in contract["groups"]} | |
| for entry in submission["rankings"]: | |
| if not isinstance(entry, dict) or not isinstance(entry.get("group_id"), str): | |
| raise SubmissionError("unassignable_group_entry") | |
| if entry["group_id"] not in entries: | |
| raise SubmissionError("unknown_group_id") | |
| entries[entry["group_id"]].append(entry) | |
| return entries | |
| def score_group(group, entries, values): | |
| gid = group["group_id"] | |
| ids = group["item_ids"] | |
| result = {"group_id": gid, "group_weight": group["group_weight"], | |
| "group_spearman_g": None, "spearman_for_aggregation": -1.0} | |
| if entries is None: | |
| result["status"] = "whole_task_format_error" | |
| return result | |
| matches = entries[gid] | |
| if len(matches) != 1: | |
| result["status"] = "duplicate_group" if matches else "missing_group" | |
| return result | |
| order = matches[0].get("order") | |
| if (not isinstance(order, list) or len(order) != len(ids) | |
| or any(not isinstance(i, str) for i in order) or set(order) != set(ids)): | |
| result["status"] = "invalid_permutation" | |
| return result | |
| positions = {item: p for p, item in enumerate(order)} | |
| rho = spearman(values, [positions[i] for i in ids]) | |
| result.update(status="valid", order=order, group_spearman_g=rho, spearman_for_aggregation=rho) | |
| return result | |
| def grade_file(contract, answers, path): | |
| measurements = validate_task(contract, answers) | |
| report = {"task_id": contract["task_id"], "task_version": contract["task_version"], | |
| "scoring_method": "spearman", "primary_score": "task_spearman", | |
| "evaluation_status": "completed"} | |
| entries = None | |
| try: | |
| raw = read_regular(path, contract["max_submission_bytes"]) | |
| submission = load_json(raw) | |
| report["submission_sha256"] = hashlib.sha256(raw).hexdigest() | |
| entries = group_entries(submission, contract) | |
| except (SubmissionError, UnicodeError, json.JSONDecodeError, RecursionError) as error: | |
| report["submission_status"] = str(error) or type(error).__name__ | |
| report["core_penalty_reason"] = "whole_task_format_error" | |
| groups = [score_group(g, entries, measurements[g["group_id"]]) for g in contract["groups"]] | |
| report["groups"] = groups | |
| if entries is None: | |
| report["task_spearman"] = -1.0 | |
| else: | |
| report["submission_status"] = "valid" if all(g["status"] == "valid" for g in groups) else "group_errors" | |
| report["task_spearman"] = bounded(math.fsum(g["group_weight"] * g["spearman_for_aggregation"] | |
| for g in groups)) | |
| return report | |
| def dump(path, value): | |
| path.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n", encoding="utf-8") | |
| def supporting_artifact_status(submission): | |
| root = submission.parent | |
| report_path = root / 'report.md' | |
| paths = {'report_file': report_path, 'sources_file': root / 'sources.json', | |
| 'analysis_directory': root / 'analysis'} | |
| present = {} | |
| for name, path in paths.items(): | |
| try: | |
| mode = path.lstat().st_mode | |
| present[name] = stat.S_ISDIR(mode) if name == 'analysis_directory' else stat.S_ISREG(mode) | |
| except OSError: | |
| present[name] = False | |
| declared_stop = False | |
| if present['report_file']: | |
| try: | |
| fd = os.open(report_path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) | |
| with os.fdopen(fd, 'rb') as stream: | |
| if stat.S_ISREG(os.fstat(stream.fileno()).st_mode): | |
| declared_stop = stream.readline(256).rstrip(b'\r\n') == b'SPU_POLICY_STOP' | |
| except OSError: | |
| pass | |
| status = 'artifacts_present' if all(present.values()) else 'artifacts_incomplete' | |
| if declared_stop: | |
| status = 'declared_stop_with_ranking' if os.path.lexists(submission) else 'declared_stop' | |
| return {'status': status, **present, 'policy_stop_declared': declared_stop} | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('--interface', choices=['txt', 'json'], default='txt') | |
| parser.add_argument('--root', type=Path, default=Path('/tests')) | |
| parser.add_argument('--submission', type=Path, default=Path('/logs/artifacts/rankings.json')) | |
| parser.add_argument('--output', type=Path, default=Path('/logs/verifier')) | |
| args = parser.parse_args() | |
| args.output.mkdir(parents=True, exist_ok=True) | |
| for name in ('reward.txt', 'reward.json', 'report.json', 'evaluator_error.json'): | |
| (args.output / name).unlink(missing_ok=True) | |
| try: | |
| bindings = load_json((args.root / 'scoring_hashes.json').read_bytes()) | |
| for name in ('contract.json', 'answers.json', 'grade.py'): | |
| if hashlib.sha256((args.root / name).read_bytes()).hexdigest() != bindings[name]: | |
| raise TaskError('Scoring file hash mismatch: ' + name) | |
| contract = load_json((args.root / 'contract.json').read_bytes()) | |
| answers = load_json((args.root / 'answers.json').read_bytes()) | |
| report = grade_file(contract, answers, args.submission) | |
| except (TaskError, SubmissionError, OSError, ValueError, KeyError, TypeError) as error: | |
| dump(args.output / 'evaluator_error.json', {'status': 'task_error', 'error': str(error)}) | |
| raise SystemExit(2) from error | |
| report['supporting_artifact_review'] = supporting_artifact_status(args.submission) | |
| dump(args.output / 'report.json', report) | |
| if args.interface == 'txt': | |
| (args.output / 'reward.txt').write_text(str(report['task_spearman']) + '\n') | |
| else: | |
| dump(args.output / 'reward.json', {'reward': report['task_spearman']}) | |
| if __name__ == '__main__': | |
| main() | |