| """``explicit-eval`` — frozen prediction, scoring, and paired statistics.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import sys |
| from pathlib import Path |
|
|
| from ..atomic_io import atomic_write_json, read_jsonl |
| from ..config import ConfigError, load_resources |
| from ..evaluation import ( |
| RETENTION_SOURCES, |
| EvaluationError, |
| compare_runs, |
| freeze_certified_groups, |
| freeze_retention_items, |
| load_evaluation_manifest, |
| materialize_hf_retention, |
| score_predictions, |
| ) |
| from ..evaluation.core import write_score_outputs |
| from ..evaluation.inference import predict_run |
| from ..paths import repo_root |
|
|
|
|
| def _assignment(value: str, *, label: str) -> tuple[str, str]: |
| if "=" not in value: |
| raise argparse.ArgumentTypeError(f"{label} must use NAME=PATH") |
| name, path = value.split("=", 1) |
| if not name or not path: |
| raise argparse.ArgumentTypeError(f"{label} must use non-empty NAME=PATH") |
| return name, path |
|
|
|
|
| def _run_assignment(value: str) -> tuple[str, str]: |
| return _assignment(value, label="--run") |
|
|
|
|
| def _score_assignment(value: str) -> tuple[str, str]: |
| return _assignment(value, label="--score") |
|
|
|
|
| def cmd_freeze(args: argparse.Namespace) -> int: |
| try: |
| summary = freeze_certified_groups( |
| args.groups, |
| args.output, |
| expected_groups=args.expected_groups, |
| ) |
| except (EvaluationError, OSError, json.JSONDecodeError) as exc: |
| print(f"EVALUATION FREEZE FAILED: {exc}", file=sys.stderr) |
| return 1 |
| print(json.dumps(summary, sort_keys=True)) |
| return 0 |
|
|
|
|
| def cmd_predict_matrix(args: argparse.Namespace) -> int: |
| try: |
| rows = load_evaluation_manifest(args.manifest) |
| run_specs = dict(args.run) |
| if len(run_specs) != len(args.run): |
| raise EvaluationError("duplicate --run name") |
| summaries = [] |
| for run_id, raw_adapter in run_specs.items(): |
| adapter = None if raw_adapter == "BASE" else Path(raw_adapter) |
| summaries.append( |
| predict_run( |
| rows, |
| run_id=run_id, |
| base_model=args.base_model, |
| adapter=adapter, |
| asset_root=args.asset_root, |
| output_path=args.output_dir / f"{run_id}.predictions.jsonl", |
| max_prompt_tokens=args.max_prompt_tokens, |
| max_new_tokens=args.max_new_tokens, |
| limit=args.limit, |
| input_mode=args.input_mode, |
| constant_answer=args.constant_answer, |
| ) |
| ) |
| except (EvaluationError, OSError, json.JSONDecodeError, RuntimeError) as exc: |
| print(f"EVALUATION PREDICTION FAILED: {exc}", file=sys.stderr) |
| return 1 |
| print(json.dumps({"status": "completed", "runs": summaries}, sort_keys=True)) |
| return 0 |
|
|
|
|
| def cmd_score(args: argparse.Namespace) -> int: |
| try: |
| gold = load_evaluation_manifest(args.manifest) |
| predictions = tuple(read_jsonl(args.predictions)) |
| metrics, scored = score_predictions(gold, predictions) |
| write_score_outputs(args.output_dir, metrics, scored) |
| except (EvaluationError, OSError, json.JSONDecodeError) as exc: |
| print(f"EVALUATION SCORE FAILED: {exc}", file=sys.stderr) |
| return 1 |
| print( |
| json.dumps( |
| { |
| "status": "completed", |
| "run_id": metrics["run_id"], |
| "metrics": str((args.output_dir / "metrics.json").resolve()), |
| "scored": str((args.output_dir / "scored.jsonl").resolve()), |
| "strict_group_accuracy": metrics["strict_group_accuracy"], |
| }, |
| sort_keys=True, |
| ) |
| ) |
| return 0 |
|
|
|
|
| def cmd_freeze_retention(args: argparse.Namespace) -> int: |
| try: |
| summary = freeze_retention_items( |
| args.items, |
| args.output, |
| expected_items=args.expected_items, |
| ) |
| except (EvaluationError, OSError, json.JSONDecodeError) as exc: |
| print(f"RETENTION FREEZE FAILED: {exc}", file=sys.stderr) |
| return 1 |
| print(json.dumps(summary, sort_keys=True)) |
| return 0 |
|
|
|
|
| def cmd_materialize_retention_hf(args: argparse.Namespace) -> int: |
| try: |
| resources = load_resources(args.resources) |
| summary = materialize_hf_retention( |
| resources, |
| args.output, |
| args.asset_root, |
| cache_dir=args.cache_dir, |
| sources=args.source or RETENTION_SOURCES, |
| ) |
| except (ConfigError, EvaluationError, ImportError, OSError, ValueError) as exc: |
| print(f"RETENTION MATERIALIZATION FAILED: {exc}", file=sys.stderr) |
| return 1 |
| print(json.dumps(summary, sort_keys=True)) |
| return 0 |
|
|
|
|
| def cmd_statistics(args: argparse.Namespace) -> int: |
| try: |
| score_paths = dict(args.score) |
| if len(score_paths) != len(args.score): |
| raise EvaluationError("duplicate --score run name") |
| runs = {run_id: tuple(read_jsonl(Path(path))) for run_id, path in score_paths.items()} |
| result = compare_runs( |
| runs, |
| reference=args.reference, |
| metric=args.metric, |
| benchmark=args.benchmark, |
| bootstrap_replicates=args.bootstrap_replicates, |
| permutation_replicates=args.permutation_replicates, |
| seed=args.seed, |
| ) |
| atomic_write_json(args.output, result) |
| except (EvaluationError, OSError, json.JSONDecodeError) as exc: |
| print(f"EVALUATION STATISTICS FAILED: {exc}", file=sys.stderr) |
| return 1 |
| print( |
| json.dumps( |
| { |
| "status": "completed", |
| "output": str(args.output.resolve()), |
| "comparison_count": len(result["comparisons"]), |
| }, |
| sort_keys=True, |
| ) |
| ) |
| return 0 |
|
|
|
|
| def build_parser() -> argparse.ArgumentParser: |
| parser = argparse.ArgumentParser(prog="explicit-eval") |
| sub = parser.add_subparsers(dest="command", required=True) |
|
|
| freeze = sub.add_parser( |
| "freeze", |
| help="Flatten certified release groups into one write-once evaluation manifest.", |
| ) |
| freeze.add_argument("--groups", type=Path, action="append", required=True) |
| freeze.add_argument("--output", type=Path, required=True) |
| freeze.add_argument("--expected-groups", type=int) |
| freeze.set_defaults(func=cmd_freeze) |
|
|
| retention = sub.add_parser( |
| "freeze-retention", |
| help="Convert untouched normalized eval items into the common evaluation manifest.", |
| ) |
| retention.add_argument("--items", type=Path, action="append", required=True) |
| retention.add_argument("--output", type=Path, required=True) |
| retention.add_argument("--expected-items", type=int) |
| retention.set_defaults(func=cmd_freeze_retention) |
|
|
| materialize = sub.add_parser( |
| "materialize-retention-hf", |
| help="Download exact pinned HF retention splits and build the common manifest.", |
| ) |
| materialize.add_argument( |
| "--resources", |
| type=Path, |
| default=repo_root() / "configs" / "resources.yaml", |
| ) |
| materialize.add_argument( |
| "--source", |
| choices=RETENTION_SOURCES, |
| action="append", |
| help="Repeat to select a subset; defaults to all four untouched sources.", |
| ) |
| materialize.add_argument("--output", type=Path, required=True) |
| materialize.add_argument("--asset-root", type=Path, required=True) |
| materialize.add_argument("--cache-dir", type=Path) |
| materialize.set_defaults(func=cmd_materialize_retention_hf) |
|
|
| predict = sub.add_parser( |
| "predict-matrix", |
| help="Generate deterministic predictions for one or more base/adapter checkpoints.", |
| ) |
| predict.add_argument("--manifest", type=Path, required=True) |
| predict.add_argument("--asset-root", type=Path, required=True) |
| predict.add_argument("--base-model", type=Path, required=True) |
| predict.add_argument( |
| "--run", |
| type=_run_assignment, |
| action="append", |
| required=True, |
| metavar="RUN_ID=ADAPTER_PATH", |
| help="Use RUN_ID=BASE for the unadapted base model.", |
| ) |
| predict.add_argument("--output-dir", type=Path, required=True) |
| predict.add_argument("--max-prompt-tokens", type=int, default=4096) |
| predict.add_argument("--max-new-tokens", type=int, default=256) |
| predict.add_argument("--limit", type=int) |
| predict.add_argument( |
| "--input-mode", |
| choices=["standard", "question_only", "full_image_control"], |
| default="standard", |
| ) |
| predict.add_argument( |
| "--constant-answer", |
| help="Skip model inference and emit this answer for every item (diagnostic baseline).", |
| ) |
| predict.set_defaults(func=cmd_predict_matrix) |
|
|
| score = sub.add_parser("score", help="Join exact prediction coverage and compute metrics.") |
| score.add_argument("--manifest", type=Path, required=True) |
| score.add_argument("--predictions", type=Path, required=True) |
| score.add_argument("--output-dir", type=Path, required=True) |
| score.set_defaults(func=cmd_score) |
|
|
| statistics = sub.add_parser( |
| "statistics", |
| help="Run group-clustered bootstrap, paired permutation, and Holm correction.", |
| ) |
| statistics.add_argument( |
| "--score", |
| type=_score_assignment, |
| action="append", |
| required=True, |
| metavar="RUN_ID=SCORED_JSONL", |
| ) |
| statistics.add_argument("--reference", required=True) |
| statistics.add_argument( |
| "--metric", choices=["strict_group_accuracy", "accuracy"], default="strict_group_accuracy" |
| ) |
| statistics.add_argument( |
| "--benchmark", |
| help="Required when scored rows contain more than one benchmark suite.", |
| ) |
| statistics.add_argument("--bootstrap-replicates", type=int, default=10_000) |
| statistics.add_argument("--permutation-replicates", type=int, default=10_000) |
| statistics.add_argument("--seed", type=int, default=20260728) |
| statistics.add_argument("--output", type=Path, required=True) |
| statistics.set_defaults(func=cmd_statistics) |
| return parser |
|
|
|
|
| def main(argv: list[str] | None = None) -> int: |
| if argv == []: |
| build_parser().print_usage(sys.stderr) |
| return 2 |
| args = build_parser().parse_args(argv) |
| return int(args.func(args)) |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|