Download evaluate.py from saxenan3/mncri: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/datasets/saxenan3/mncri/resolve/main/evaluate.py
- Command line
-
hf download hf://datasets/saxenan3/mncri/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/datasets/saxenan3/mncri/resolve/main/evaluate.py
17.3 kB
| """Score MNCRI responses and audit recorded no-CoT evidence offline. | |
| Manifest records contain item_id, family, rung, gold and split. Use the release | |
| Parquet shards directly, or supply JSON Lines, a JSON array, CSV or Parquet. | |
| A wide record expands to one prediction key for each non-null text, image, | |
| audio, video, av_grouped or av_alternating column. A narrow record gives a | |
| single explicit variant. Parquet requires pyarrow and projects media paths | |
| when available to avoid loading media bytes. Supply world_id when several | |
| items reuse one generated world. | |
| Each prediction supplies model, item_id, variant, response, and an optional | |
| recipe name (default: default). Use one mode per response: | |
| * answer_only (default) or reasoning_enabled: exact grading only. | |
| * open_first_position: evidence contains forward_passes=1, | |
| generated_tokens_before_answer=0, selection="full_vocab_argmax", a nonnegative | |
| selected_token_id, and gold_single_token=true. Check the gold tokenization | |
| with the real model tokenizer and answer prefix before collecting a row. | |
| response is the decoded selected token. An invalid answer token still counts | |
| as a witnessed incorrect response. Never put forced-choice results here. | |
| * hosted_no_cot: provide endpoint, native usage, content_cot (boolean audit of | |
| the full raw response) and positive_control_id. An additional JSONL record | |
| with kind="positive_control" provides control_id, model, item_id, variant, | |
| endpoint, recipe and native usage showing positive reasoning tokens. Take | |
| the control on the same endpoint and item with the scratchpad enabled. Use | |
| the recipe name to identify the shared evaluation setup in both conditions. | |
| This script checks logged claims and native counters. The collection harness | |
| is responsible for their provenance and for preserving full provider output. | |
| Example: | |
| python tools/evaluate.py --manifest data/test-000.parquet --predictions predictions.jsonl | |
| """ | |
| import argparse | |
| from collections import Counter, defaultdict | |
| import csv | |
| import json | |
| from pathlib import Path | |
| import random | |
| import re | |
| INTEGER = re.compile(r"(?:Answer:\s*)?([+-]?[0-9]+)\Z") | |
| REASONING_TAG = re.compile(r"<(?:think|analysis|reasoning)(?:\s|>)", re.I) | |
| MODES = {"answer_only", "reasoning_enabled", "open_first_position", "hosted_no_cot"} | |
| REQUIRED_MANIFEST_FIELDS = {"item_id", "family", "rung", "gold", "split"} | |
| WIDE_VARIANTS = ("text", "image", "audio", "video", "av_grouped", "av_alternating") | |
| def parse_integer(response): | |
| if not isinstance(response, str): | |
| return None | |
| match = INTEGER.fullmatch(response.strip()) | |
| if match is None: | |
| return None | |
| try: | |
| return int(match[1]) | |
| except ValueError: | |
| return None | |
| def read_manifest_parquet(path): | |
| try: | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| except ImportError as exc: | |
| raise ValueError("Parquet input needs pyarrow") from exc | |
| file = pq.ParquetFile(path) | |
| schema = file.schema_arrow | |
| names = set(schema.names) | |
| columns = sorted((REQUIRED_MANIFEST_FIELDS | {"world_id", "variant"}) & names) | |
| if "variant" not in names: | |
| for name in WIDE_VARIANTS: | |
| if name not in names: | |
| continue | |
| data_type = schema.field(name).type | |
| if pa.types.is_struct(data_type) and data_type.get_field_index("path") >= 0: | |
| columns.append(f"{name}.path") | |
| else: | |
| columns.append(name) | |
| for batch in file.iter_batches(columns=columns, batch_size=32): | |
| yield from batch.to_pylist() | |
| def read_records(path): | |
| suffix = path.suffix.lower() | |
| with path.open(encoding="utf-8-sig", newline="") as file: | |
| if suffix == ".csv": | |
| yield from csv.DictReader(file) | |
| elif suffix == ".json": | |
| rows = json.load(file) | |
| if not isinstance(rows, list): | |
| raise ValueError(f"{path} must contain a JSON array") | |
| yield from rows | |
| else: | |
| for line_number, line in enumerate(file, 1): | |
| if line.strip(): | |
| try: | |
| yield json.loads(line) | |
| except json.JSONDecodeError as exc: | |
| raise ValueError(f"{path}:{line_number}: {exc.msg}") from exc | |
| def required_text(row, field): | |
| value = row.get(field) | |
| if not isinstance(value, str) or not value.strip(): | |
| raise ValueError(f"missing or invalid {field}: {value!r}") | |
| return value | |
| def available_variants(row): | |
| if "variant" in row: | |
| return [required_text(row, "variant")] | |
| variants = [name for name in WIDE_VARIANTS if row.get(name) is not None and row[name] != ""] | |
| if not variants: | |
| raise ValueError(f"no variants for manifest item {row['item_id']!r}") | |
| return variants | |
| def load_manifest(paths): | |
| manifest = {} | |
| for path in paths: | |
| records = read_manifest_parquet(path) if path.suffix.lower() == ".parquet" else read_records(path) | |
| for row in records: | |
| if not isinstance(row, dict) or not REQUIRED_MANIFEST_FIELDS <= row.keys(): | |
| raise ValueError(f"{path} has a row missing required manifest fields") | |
| item_id = required_text(row, "item_id") | |
| family = required_text(row, "family") | |
| split = required_text(row, "split") | |
| gold = row["gold"] | |
| if isinstance(gold, str) and re.fullmatch(r"[+-]?[0-9]+", gold.strip()): | |
| gold = int(gold) | |
| if type(gold) is not int: | |
| raise ValueError(f"non-integer gold for {item_id!r}") | |
| for variant in available_variants(row): | |
| key = (item_id, variant) | |
| if key in manifest: | |
| raise ValueError(f"duplicate manifest key {key!r}") | |
| manifest[key] = { | |
| "item_id": item_id, "family": family, "split": split, "gold": gold, | |
| "variant": variant, "rung": str(row["rung"]), | |
| "world_id": row.get("world_id") or item_id, | |
| } | |
| if not manifest: | |
| raise ValueError("manifest is empty") | |
| return manifest | |
| def positive_int(value): | |
| return type(value) is int and value > 0 | |
| def nonnegative_int(value): | |
| return type(value) is int and value >= 0 | |
| def native_usage(row): | |
| usage = row.get("usage") | |
| if not isinstance(usage, dict): | |
| return {}, None | |
| details = usage.get("completion_tokens_details") | |
| reasoning = details.get("reasoning_tokens") if isinstance(details, dict) else None | |
| return usage, reasoning | |
| def audit_open(row): | |
| evidence = row.get("evidence") | |
| if not isinstance(evidence, dict): | |
| return "unknown", "missing open-model evidence" | |
| passes = evidence.get("forward_passes") | |
| tokens = evidence.get("generated_tokens_before_answer") | |
| token_id = evidence.get("selected_token_id") | |
| selection = evidence.get("selection") | |
| if evidence.get("gold_single_token") is False: | |
| return "ineligible", "gold answer spans more than one token" | |
| if ( | |
| (nonnegative_int(passes) and passes != 1) | |
| or (nonnegative_int(tokens) and tokens != 0) | |
| or (selection is not None and selection != "full_vocab_argmax") | |
| ): | |
| return "violated", "collection did not use unrestricted first-position logits" | |
| if ( | |
| positive_int(passes) | |
| and nonnegative_int(tokens) | |
| and nonnegative_int(token_id) | |
| and selection == "full_vocab_argmax" | |
| and evidence.get("gold_single_token") is True | |
| ): | |
| return "verified", "first-position evidence complete" | |
| return "unknown", "incomplete first-position evidence" | |
| def audit_hosted(row, controls): | |
| usage, reasoning = native_usage(row) | |
| counts = [usage.get(name) for name in ("prompt_tokens", "completion_tokens", "total_tokens")] | |
| if positive_int(reasoning) or row.get("content_cot") is True: | |
| return "violated", "reasoning observed" | |
| if REASONING_TAG.search(row["response"]): | |
| return "violated", "reasoning tag in raw response" | |
| if all(positive_int(count) for count in counts) and counts[0] + counts[1] != counts[2]: | |
| return "violated", "token accounting differs" | |
| if not (nonnegative_int(reasoning) and all(positive_int(count) for count in counts) | |
| and row.get("content_cot") is False): | |
| return "unknown", "missing native token usage or full-response audit" | |
| control_id = row.get("positive_control_id") | |
| control = controls.get(control_id) if isinstance(control_id, str) else None | |
| endpoint = row.get("endpoint") | |
| if not isinstance(endpoint, str) or not endpoint.strip() or control is None: | |
| return "unknown", "missing matched positive control or endpoint" | |
| match_fields = ("model", "recipe", "endpoint", "item_id", "variant") | |
| if any(row.get(field) != control.get(field) for field in match_fields): | |
| return "unknown", "positive control refers to a different evaluation row" | |
| control_usage, control_reasoning = native_usage(control) | |
| if not positive_int(control_reasoning) or not positive_int(control_usage.get("total_tokens")): | |
| return "unknown", "positive control did not report reasoning tokens" | |
| return "verified", "native usage, full-response audit and positive control passed" | |
| def score_rows(manifest, records): | |
| controls = {} | |
| predictions = [] | |
| for record in records: | |
| if not isinstance(record, dict): | |
| raise ValueError("prediction lines must contain JSON objects") | |
| record = dict(record) | |
| record.setdefault("recipe", "default") | |
| for field in ("item_id", "variant", "model", "recipe"): | |
| required_text(record, field) | |
| kind = record.get("kind", "prediction") | |
| if kind == "positive_control": | |
| control_id = required_text(record, "control_id") | |
| if control_id in controls: | |
| raise ValueError(f"duplicate positive control {control_id!r}") | |
| controls[control_id] = record | |
| elif kind == "prediction": | |
| if not isinstance(record.get("response"), str): | |
| raise ValueError("prediction response must be the full response string") | |
| predictions.append(record) | |
| else: | |
| raise ValueError(f"unknown record kind {kind!r}") | |
| seen = set() | |
| for row in predictions: | |
| key = (row["item_id"], row["variant"]) | |
| if key not in manifest: | |
| raise ValueError(f"prediction key absent from manifest: {key!r}") | |
| mode = row.get("mode", "answer_only") | |
| if not isinstance(mode, str) or mode not in MODES: | |
| raise ValueError(f"unknown prediction mode {mode!r}") | |
| run_key = (row["model"], row["recipe"], mode, *key) | |
| if run_key in seen: | |
| raise ValueError(f"duplicate prediction: {run_key!r}; use a distinct recipe for repeats") | |
| seen.add(run_key) | |
| status, reason = "not_requested", "answer grading without no-CoT evidence" | |
| if mode == "open_first_position": | |
| status, reason = audit_open(row) | |
| elif mode == "hosted_no_cot": | |
| status, reason = audit_hosted(row, controls) | |
| item = manifest[key] | |
| correct = parse_integer(row["response"]) == item["gold"] | |
| yield {**item, "model": row["model"], "recipe": row["recipe"], "mode": mode, | |
| "correct": correct, "witness": status, "witness_reason": reason} | |
| def accuracy(rows): | |
| witnessed = [row for row in rows if row["witness"] == "verified"] | |
| witnessed_correct = sum(row["correct"] for row in witnessed) | |
| return { | |
| "count": len(rows), | |
| "exact_accuracy": sum(row["correct"] for row in rows) / len(rows), | |
| "witness_counts": dict(Counter(row["witness"] for row in rows)), | |
| "witness_reasons": dict(Counter(row["witness_reason"] for row in rows)), | |
| "verified_only_accuracy": witnessed_correct / len(witnessed) if witnessed else None, | |
| "verified_correct_over_submitted": witnessed_correct / len(rows), | |
| } | |
| def summarize(rows, fields, statistic): | |
| groups = defaultdict(list) | |
| for row in rows: | |
| groups[tuple(row[field] for field in fields)].append(row) | |
| return [{**dict(zip(fields, key)), **statistic(group)} for key, group in sorted(groups.items())] | |
| def percentile(values, probability): | |
| position = probability * (len(values) - 1) | |
| low = int(position) | |
| high = min(low + 1, len(values) - 1) | |
| return values[low] + (position - low) * (values[high] - values[low]) | |
| def cluster_interval(clusters, draws, seed): | |
| if len(clusters) < 2 or not draws: | |
| return None | |
| world_stats = [(len(values), sum(values)) for values in clusters.values()] | |
| rng = random.Random(seed) | |
| estimates = [] | |
| for _ in range(draws): | |
| sample = rng.choices(world_stats, k=len(world_stats)) | |
| estimates.append(sum(total for _, total in sample) / sum(n for n, _ in sample)) | |
| estimates.sort() | |
| return [percentile(estimates, 0.025), percentile(estimates, 0.975)] | |
| def paired_statistics(pairs, draws, seed): | |
| clusters = defaultdict(list) | |
| scores = Counter() | |
| for left, right in pairs: | |
| scores[(left["correct"], right["correct"])] += 1 | |
| clusters[left["world_id"]].append(int(right["correct"]) - int(left["correct"])) | |
| left_only = scores[(True, False)] | |
| right_only = scores[(False, True)] | |
| return { | |
| "pairs": len(pairs), | |
| "worlds": len(clusters), | |
| "both_correct": scores[(True, True)], | |
| "left_only_correct": left_only, | |
| "right_only_correct": right_only, | |
| "neither_correct": scores[(False, False)], | |
| "accuracy_delta_right_minus_left": (right_only - left_only) / len(pairs) if pairs else None, | |
| "world_cluster_bootstrap_ci95": cluster_interval(clusters, draws, seed), | |
| } | |
| def compare_pairs(rows, variants, draws, seed): | |
| left_name, right_name = variants | |
| by_item = defaultdict(dict) | |
| for row in rows: | |
| if row["variant"] in variants: | |
| by_item[row["item_id"]][row["variant"]] = row | |
| pairs = [] | |
| for matched in by_item.values(): | |
| if left_name not in matched or right_name not in matched: | |
| continue | |
| left, right = matched[left_name], matched[right_name] | |
| if any(left[field] != right[field] for field in ("gold", "family", "rung", "split", "world_id")): | |
| raise ValueError(f"paired variants disagree on metadata for {left['item_id']!r}") | |
| pairs.append((left, right)) | |
| witnessed = [(left, right) for left, right in pairs | |
| if left["witness"] == right["witness"] == "verified"] | |
| return { | |
| "left_variant": left_name, | |
| "right_variant": right_name, | |
| "left_only_submitted": sum(set(row) == {left_name} for row in by_item.values()), | |
| "right_only_submitted": sum(set(row) == {right_name} for row in by_item.values()), | |
| "all_matched": paired_statistics(pairs, draws, seed), | |
| "both_verified": paired_statistics(witnessed, draws, seed), | |
| } | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--manifest", type=Path, nargs="+", required=True) | |
| parser.add_argument("--predictions", type=Path, required=True) | |
| parser.add_argument("--output", type=Path, help="write JSON report (default: stdout)") | |
| parser.add_argument("--pair-variants", nargs=2, metavar=("LEFT", "RIGHT"), | |
| default=("av_grouped", "av_alternating")) | |
| parser.add_argument("--bootstrap", type=int, default=2000, help="world-cluster draws (0 disables)") | |
| parser.add_argument("--seed", type=int, default=241) | |
| args = parser.parse_args() | |
| if args.bootstrap < 0 or args.pair_variants[0] == args.pair_variants[1]: | |
| parser.error("bootstrap must be nonnegative and paired variants must differ") | |
| try: | |
| manifest = load_manifest(args.manifest) | |
| rows = list(score_rows(manifest, read_records(args.predictions))) | |
| if not rows: | |
| raise ValueError("no prediction rows") | |
| base_fields = ("model", "recipe", "mode", "split") | |
| paired_rows = [row for row in rows if row["variant"] in args.pair_variants] | |
| def contrast(group): | |
| return compare_pairs(group, args.pair_variants, args.bootstrap, args.seed) | |
| report = { | |
| "manifest_records": len(manifest), | |
| "manifest_items": len({item_id for item_id, _ in manifest}), | |
| "predictions": len(rows), | |
| "bootstrap_seed": args.seed, | |
| "bootstrap_draws": args.bootstrap, | |
| "scores": summarize(rows, (*base_fields, "variant"), accuracy), | |
| "scores_by_family_and_rung": summarize(rows, (*base_fields, "variant", "family", "rung"), accuracy), | |
| "paired_contrasts": summarize(paired_rows, base_fields, contrast), | |
| "paired_contrasts_by_family_and_rung": summarize(paired_rows, (*base_fields, "family", "rung"), contrast), | |
| } | |
| result = json.dumps(report, indent=2, ensure_ascii=False) + "\n" | |
| if args.output: | |
| args.output.write_text(result, encoding="utf-8") | |
| else: | |
| print(result, end="") | |
| except (OSError, ValueError) as exc: | |
| parser.error(str(exc)) | |
| if __name__ == "__main__": | |
| main() | |