File size: 10,445 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""``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())