Download code/src/analyze_experiment_001b.py from PratikBuilds/modelclinic-experiment-001: direct link, hf CLI and curl.
- Browser
- Download file 43.7 kB
-
https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/analyze_experiment_001b.py
- Command line
-
hf download hf://datasets/PratikBuilds/modelclinic-experiment-001/code/src/analyze_experiment_001b.py
-
curl -L -o analyze_experiment_001b.py https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/src/analyze_experiment_001b.py
43.7 kB
| """Analyze Experiment 001B from frozen calibration and held-out artifacts. | |
| Selection is recomputed only from the calibration grid. A calibration family | |
| with any missing or errored candidate record has no winner and blocks a | |
| held-out selection. Held-out outputs are only compared after that selection | |
| has been independently verified. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import hashlib | |
| import json | |
| from collections import Counter | |
| from pathlib import Path | |
| from experiment_001b_analysis import ( | |
| DEFAULT_CONDITIONS, | |
| paired_heldout_summary, | |
| record_validation_issue, | |
| select_calibration_winners, | |
| summarize_experiment_001b_contrasts, | |
| ) | |
| def read_json_records(root: Path) -> list[dict]: | |
| paths = [root] if root.is_file() else sorted(root.rglob("*.json")) | |
| records = [] | |
| for path in paths: | |
| if ( | |
| ".partial." in path.name | |
| or path.name.endswith(".tmp") | |
| or "batch_summary" in path.name | |
| or "attempts" in path.parts | |
| or "partials" in path.parts | |
| ): | |
| continue | |
| record = json.loads(path.read_text(encoding="utf-8")) | |
| if record.get("status") == "running": | |
| continue | |
| if root.is_dir() and not {"source_row", "condition", "seed"}.issubset(record): | |
| continue | |
| record["_source_file"] = str(path) | |
| records.append(record) | |
| return records | |
| def normalize_calibration_grid(calibration: dict, calibration_rows: list[int], calibration_manifest=None): | |
| candidates = {} | |
| families = {} | |
| metadata = {} | |
| seeds = set() | |
| expected_rows = set(calibration_rows) | |
| grid = calibration.get("grid_candidates", []) | |
| if not grid: | |
| raise ValueError("calibration artifact has no grid_candidates") | |
| grid_by_id = {} | |
| for row in grid: | |
| candidate_id = str(row["candidate_id"]) | |
| if candidate_id in grid_by_id: | |
| raise ValueError(f"duplicate candidate ID in frozen calibration artifact: {candidate_id}") | |
| grid_by_id[candidate_id] = row | |
| manifest_candidates = {} | |
| common_protocol = None | |
| if calibration_manifest is not None: | |
| manifest_candidates = { | |
| str(candidate["candidate_id"]): candidate | |
| for candidate in calibration_manifest.get("calibration_candidates", []) | |
| } | |
| if len(manifest_candidates) != len(calibration_manifest.get("calibration_candidates", [])): | |
| raise ValueError("calibration manifest contains duplicate candidate IDs") | |
| expected_families = calibration_manifest.get("selection_families") | |
| if not isinstance(expected_families, dict) or not expected_families: | |
| raise ValueError("calibration manifest is missing selection_families") | |
| candidate_ids = {candidate for values in expected_families.values() for candidate in values} | |
| if candidate_ids != set(manifest_candidates): | |
| raise ValueError("calibration candidate manifest and family membership disagree") | |
| if set(grid_by_id) - candidate_ids: | |
| raise ValueError("calibration artifact contains candidates absent from its frozen manifest") | |
| families = {family: list(values) for family, values in expected_families.items()} | |
| for candidate_id in candidate_ids: | |
| config = manifest_candidates[candidate_id] | |
| family = str(config["family"]) | |
| if family not in families or candidate_id not in families[family]: | |
| raise ValueError(f"candidate family mismatch in calibration manifest: {candidate_id}") | |
| metadata[candidate_id] = { | |
| "family": family, | |
| "heldout_condition": str(config["heldout_condition"]), | |
| "coefficients": config.get("coefficients"), | |
| "settings": config, | |
| } | |
| candidates[candidate_id] = [] | |
| for candidate_id, row in grid_by_id.items(): | |
| family = str(row["family"]) | |
| if calibration_manifest is not None and metadata[candidate_id]["family"] != family: | |
| raise ValueError(f"candidate family differs between grid and manifest: {candidate_id}") | |
| seed = int(row.get("seed", 0)) | |
| seeds.add(seed) | |
| protocol = ( | |
| seed, | |
| int(row.get("max_new_tokens", -1)), | |
| int(row.get("max_generation_seconds", -1)), | |
| json.dumps(row.get("sampling"), sort_keys=True, separators=(",", ":")), | |
| ) | |
| if protocol[1] <= 0 or protocol[2] <= 0 or not isinstance(row.get("sampling"), dict): | |
| raise ValueError(f"calibration candidate {candidate_id} has incomplete sampling/cap settings") | |
| if common_protocol is None: | |
| common_protocol = protocol | |
| elif protocol != common_protocol: | |
| raise ValueError("calibration candidates do not share one seed, sampling setup, and cap") | |
| if "heldout_condition" not in row: | |
| raise ValueError(f"candidate {candidate_id} has no heldout_condition") | |
| if calibration_manifest is None: | |
| families.setdefault(family, []).append(candidate_id) | |
| metadata[candidate_id] = { | |
| "family": family, | |
| "heldout_condition": str(row["heldout_condition"]), | |
| "coefficients": row.get("coefficients"), | |
| } | |
| elif str(row["heldout_condition"]) != metadata[candidate_id]["heldout_condition"]: | |
| raise ValueError(f"heldout condition differs between grid and manifest: {candidate_id}") | |
| if calibration_manifest is not None: | |
| config = manifest_candidates[candidate_id] | |
| for field in ( | |
| "coefficients", | |
| "condition", | |
| "heldout_condition", | |
| "sampling", | |
| "max_new_tokens", | |
| "max_generation_seconds", | |
| ): | |
| if field in config and field in row and config[field] != row[field]: | |
| raise ValueError( | |
| f"candidate {field} differs between calibration artifact and manifest: {candidate_id}" | |
| ) | |
| if "coefficients" not in config or "coefficients" not in row: | |
| raise ValueError(f"candidate {candidate_id} is missing frozen coefficients") | |
| outcomes = row.get("prompt_outcomes", []) | |
| normalized = [] | |
| if row.get("status") != "complete": | |
| error = row.get("error") or f"candidate status={row.get('status')}" | |
| for source_row in sorted(expected_rows): | |
| normalized.append({ | |
| "candidate_id": candidate_id, | |
| "source_row": source_row, | |
| "seed": seed, | |
| "score": {"status": "error", "correct": None}, | |
| "finish_reason": "error", | |
| "tokens": 0, | |
| "error": error, | |
| }) | |
| else: | |
| for outcome in outcomes: | |
| normalized.append({ | |
| **outcome, | |
| "candidate_id": candidate_id, | |
| "seed": int(outcome.get("seed", seed)), | |
| }) | |
| outcome_rows = [int(outcome["source_row"]) for outcome in outcomes] | |
| if set(outcome_rows) - expected_rows: | |
| raise ValueError(f"candidate {candidate_id} contains non-calibration rows") | |
| declared = row.get("calibration_rows") | |
| if declared is not None and set(map(int, declared)) != expected_rows: | |
| raise ValueError(f"candidate {candidate_id} declares wrong calibration rows") | |
| candidates[candidate_id] = normalized | |
| if len(seeds) != 1: | |
| raise ValueError("all calibration candidates must use the same single seed") | |
| return candidates, families, metadata, next(iter(seeds)) | |
| def condition_summary(records, condition, candidate_id, expected, cap): | |
| selected = [ | |
| row for row in records | |
| if row.get("condition") == condition | |
| and (candidate_id is None or row.get("candidate_id") == candidate_id) | |
| ] | |
| by_key = {} | |
| for row in selected: | |
| key = (int(row["source_row"]), int(row["seed"])) | |
| if key in by_key: | |
| raise ValueError(f"duplicate heldout record for {condition}/{key}") | |
| by_key[key] = row | |
| expected_set = set(expected) | |
| extra = set(by_key) - expected_set | |
| if extra: | |
| raise ValueError(f"unexpected heldout keys for {condition}: {sorted(extra)}") | |
| missing = expected_set - set(by_key) | |
| issues = {key: record_validation_issue(row) for key, row in by_key.items()} | |
| errors = {key for key, issue in issues.items() if issue == "technical_error"} | |
| scoring_errors = { | |
| key for key, issue in issues.items() | |
| if issue is not None and issue != "technical_error" | |
| } | |
| valid = [row for key, row in by_key.items() if issues[key] is None] | |
| score_status = lambda row: row["score"]["status"] | |
| statuses = Counter(score_status(row) for row in valid) | |
| solves = sum(row["score"].get("correct") is True or score_status(row) == "correct" for row in valid) | |
| natural = sum(row.get("finish_reason") == "stop" and not row.get("truncated", False) for row in valid) | |
| unscorable = sum(score_status(row) not in {"correct", "incorrect"} for row in valid) | |
| lengths = [min(cap, max(0, int(row.get("tokens", cap)))) for row in valid] | |
| complete = not missing and not errors and not scoring_errors | |
| return { | |
| "expected": len(expected_set), | |
| "recorded": len(by_key), | |
| "valid": len(valid), | |
| "missing": [list(key) for key in sorted(missing)], | |
| "technical_errors": [list(key) for key in sorted(errors)], | |
| "scoring_errors": [ | |
| {"question_seed": list(key), "reason": issues[key]} | |
| for key in sorted(scoring_errors) | |
| ], | |
| "score_status_counts": dict(statuses), | |
| "solves": solves, | |
| "natural_completions": natural, | |
| "unscorable": unscorable, | |
| "accuracy_over_expected": solves / len(expected_set) if complete and expected_set else None, | |
| "mean_capped_tokens_observed": sum(lengths) / len(lengths) if lengths else None, | |
| "complete": complete, | |
| } | |
| def write_per_question(path, records, rows, seeds, conditions, selected_by_condition, cap): | |
| indexed = {} | |
| for row in records: | |
| condition = str(row.get("condition", "")) | |
| candidate = str(row.get("candidate_id", condition)) | |
| key = (int(row["source_row"]), int(row["seed"]), condition, candidate) | |
| if key in indexed: | |
| raise ValueError(f"duplicate per-question key: {key}") | |
| indexed[key] = row | |
| fields = [ | |
| "source_row", "seed", "condition", "candidate_id", "record_status", | |
| "grade_status", "solve_credit", "finish_reason", "tokens", | |
| "capped_tokens", "natural_completion", "unscorable", "truncated", | |
| "error", "calibration_artifact_sha256", | |
| ] | |
| with path.open("w", newline="", encoding="utf-8") as stream: | |
| writer = csv.DictWriter(stream, fieldnames=fields) | |
| writer.writeheader() | |
| for source_row in rows: | |
| for seed in seeds: | |
| for condition in conditions: | |
| candidate = selected_by_condition.get(condition, condition) | |
| record = indexed.get((source_row, seed, condition, candidate)) | |
| if record is None: | |
| writer.writerow({ | |
| "source_row": source_row, "seed": seed, "condition": condition, | |
| "candidate_id": candidate, "record_status": "missing", | |
| "capped_tokens": cap, | |
| }) | |
| continue | |
| score = record.get("score") | |
| if not isinstance(score, dict): | |
| score = {} | |
| status = score.get("status") | |
| issue = record_validation_issue(record) | |
| error = issue == "technical_error" | |
| scoring_error = issue is not None and not error | |
| tokens = min(cap, max(0, int(record.get("tokens", cap)))) | |
| writer.writerow({ | |
| "source_row": source_row, "seed": seed, "condition": condition, | |
| "candidate_id": candidate, | |
| "record_status": ( | |
| "technical_error" if error else "scoring_error" if scoring_error else "complete" | |
| ), | |
| "grade_status": status or "missing_status", | |
| "solve_credit": "" if issue is not None else int(status == "correct" or score.get("correct") is True), | |
| "finish_reason": record.get("finish_reason"), | |
| "tokens": record.get("tokens"), | |
| "capped_tokens": tokens, | |
| "natural_completion": "" if issue is not None else int(record.get("finish_reason") == "stop" and not record.get("truncated", False)), | |
| "unscorable": "" if issue is not None else int(status not in {"correct", "incorrect"}), | |
| "truncated": record.get("truncated"), | |
| "error": record.get("error") or issue, | |
| "calibration_artifact_sha256": record.get("calibration_artifact_sha256"), | |
| }) | |
| def read_jsonl(path: Path): | |
| return [ | |
| json.loads(line) | |
| for line in path.read_text(encoding="utf-8").splitlines() | |
| if line.strip() | |
| ] | |
| def read_question_rows(path: Path): | |
| return [ | |
| json.loads(line) | |
| for line in path.read_text(encoding="utf-8").splitlines() | |
| if line.strip() | |
| ] | |
| def verify_split_input_hash(split_manifest: dict, split_name: str, raw: bytes) -> str: | |
| """Anchor an input JSONL to the exact split bytes declared by the manifest.""" | |
| rows = split_manifest.get("split_rows", {}).get(split_name) | |
| if not isinstance(rows, list) or not rows: | |
| raise ValueError(f"split manifest has no non-empty {split_name} rows") | |
| filename = f"001b_{split_name}_{len(rows)}.jsonl" | |
| expected = split_manifest.get("split_file_sha256", {}).get(filename) | |
| if not isinstance(expected, str) or not expected: | |
| raise ValueError(f"split manifest has no hash for {filename}") | |
| actual = hashlib.sha256(raw).hexdigest() | |
| if actual != expected: | |
| raise ValueError(f"{split_name} JSONL hash differs from frozen split manifest") | |
| return actual | |
| def _verify_calibration_artifact_hash(calibration: dict, label: str) -> str: | |
| declared = calibration.get("calibration_artifact_sha256") | |
| if not isinstance(declared, str) or not declared: | |
| raise ValueError(f"{label} calibration artifact is missing calibration_artifact_sha256") | |
| hash_payload = dict(calibration) | |
| hash_payload.pop("calibration_artifact_sha256", None) | |
| canonical = ( | |
| json.dumps(hash_payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" | |
| ).encode("utf-8") | |
| actual = hashlib.sha256(canonical).hexdigest() | |
| if declared != actual: | |
| raise ValueError(f"{label} calibration artifact hash does not match its contents") | |
| return declared | |
| def verify_calibration_artifact_binding( | |
| calibration: dict, | |
| calibration_manifest: dict, | |
| calibration_path: Path, | |
| parent_calibration_path: Path | None = None, | |
| ) -> str: | |
| """Validate artifact self-hash, manifest binding, and long-stage lineage.""" | |
| declared = _verify_calibration_artifact_hash(calibration, "current") | |
| manifest_hash = calibration_manifest.get("calibration_artifact_sha256") | |
| if manifest_hash is not None and manifest_hash != declared: | |
| raise ValueError("calibration manifest artifact hash differs from calibration JSON") | |
| is_long_stage = ( | |
| calibration.get("phase") == "finalists" | |
| or calibration.get("calibration_stage") == "narrowed_finalists_32768" | |
| ) | |
| artifact_parent = calibration.get("parent_calibration_artifact_sha256") | |
| manifest_parent = calibration_manifest.get("parent_calibration_artifact_sha256") | |
| if not is_long_stage: | |
| if artifact_parent not in (None, "") or manifest_parent not in (None, ""): | |
| raise ValueError("screen calibration unexpectedly declares a parent artifact") | |
| return declared | |
| if not isinstance(artifact_parent, str) or not artifact_parent: | |
| raise ValueError("long-stage calibration artifact is missing its parent screen hash") | |
| if manifest_parent != artifact_parent: | |
| raise ValueError("long-stage manifest parent hash differs from calibration artifact") | |
| if parent_calibration_path is None: | |
| parent_calibration_path = calibration_path.parent.parent / "calibration" / "calibration.json" | |
| parent_calibration_path = Path(parent_calibration_path) | |
| if not parent_calibration_path.exists(): | |
| raise FileNotFoundError(f"parent screen calibration artifact is missing: {parent_calibration_path}") | |
| parent = json.loads(parent_calibration_path.read_text(encoding="utf-8")) | |
| parent_hash = _verify_calibration_artifact_hash(parent, "parent screen") | |
| if parent_hash != artifact_parent: | |
| raise ValueError("long-stage parent hash does not match screen calibration artifact") | |
| if parent.get("phase") not in (None, "screen"): | |
| raise ValueError("long-stage parent artifact is not the 8,192-token screen") | |
| for field in ("run_id", "model", "calibration_sha256", "independent_sha256", "split_manifest_sha256"): | |
| if parent.get(field) != calibration.get(field): | |
| raise ValueError(f"long-stage artifact {field} differs from its parent screen") | |
| parent_manifest_path = parent_calibration_path.parent / "manifest.json" | |
| if not parent_manifest_path.exists(): | |
| raise FileNotFoundError(f"parent screen calibration manifest is missing: {parent_manifest_path}") | |
| parent_manifest = json.loads(parent_manifest_path.read_text(encoding="utf-8")) | |
| if parent_manifest.get("status") != "complete": | |
| raise ValueError("parent screen calibration manifest is incomplete") | |
| parent_manifest_hash = parent_manifest.get("calibration_artifact_sha256") | |
| if parent_manifest_hash is not None and parent_manifest_hash != parent_hash: | |
| raise ValueError("parent screen manifest artifact hash differs from screen JSON") | |
| return declared | |
| def verify_heldout_gate_manifest_hash(calibration_manifest: dict) -> str | None: | |
| """Verify the self-hash on the heldout-gate copy when it is supplied.""" | |
| declared = calibration_manifest.get("heldout_gate_manifest_sha256") | |
| if declared is None: | |
| return None | |
| if not isinstance(declared, str) or not declared: | |
| raise ValueError("heldout gate manifest has an invalid self-hash") | |
| payload = dict(calibration_manifest) | |
| payload.pop("heldout_gate_manifest_sha256", None) | |
| canonical = ( | |
| json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n" | |
| ).encode("utf-8") | |
| actual = hashlib.sha256(canonical).hexdigest() | |
| if declared != actual: | |
| raise ValueError("heldout gate manifest self-hash does not match its contents") | |
| return declared | |
| def calibration_attempt_history(grid_path: Path, calibration: dict): | |
| if not grid_path.exists(): | |
| return { | |
| "available": False, | |
| "note": "grid_records.jsonl was not exported; prior retry attempts cannot be audited locally.", | |
| "candidates": {}, | |
| } | |
| history = read_jsonl(grid_path) | |
| by_candidate = {} | |
| latest_history_row = {} | |
| for row in history: | |
| candidate_id = str(row["candidate_id"]) | |
| previous_attempts = by_candidate.setdefault(candidate_id, []) | |
| attempt_number = int(row.get("candidate_attempt", len(previous_attempts) + 1)) | |
| if attempt_number <= 0 or any(item["attempt"] == attempt_number for item in previous_attempts): | |
| raise ValueError(f"duplicate or invalid calibration attempt number for {candidate_id}") | |
| by_candidate.setdefault(candidate_id, []).append({ | |
| "attempt": attempt_number, | |
| "status": row.get("status"), | |
| "error": row.get("error"), | |
| "source_rows": [int(item.get("source_row")) for item in row.get("prompt_outcomes", [])], | |
| }) | |
| latest_history_row.setdefault(candidate_id, {})[attempt_number] = row | |
| latest = { | |
| str(row["candidate_id"]): row | |
| for row in calibration.get("grid_candidates", []) | |
| } | |
| if set(by_candidate) != set(latest): | |
| raise ValueError("exported calibration grid history does not match frozen candidate IDs") | |
| for candidate_id, attempts in by_candidate.items(): | |
| final_attempt = max(attempts, key=lambda item: item["attempt"]) | |
| attempt_numbers = sorted(item["attempt"] for item in attempts) | |
| if attempt_numbers != list(range(1, len(attempt_numbers) + 1)): | |
| raise ValueError(f"calibration attempt history has gaps for {candidate_id}") | |
| frozen = latest[candidate_id] | |
| if final_attempt["status"] != frozen.get("status"): | |
| raise ValueError(f"latest grid attempt status differs from calibration artifact for {candidate_id}") | |
| if int(frozen.get("candidate_attempt", final_attempt["attempt"])) != final_attempt["attempt"]: | |
| raise ValueError(f"latest grid attempt number differs for {candidate_id}") | |
| latest_row = latest_history_row[candidate_id][final_attempt["attempt"]] | |
| if json.dumps(latest_row, sort_keys=True, separators=(",", ":")) != json.dumps( | |
| frozen, sort_keys=True, separators=(",", ":") | |
| ): | |
| raise ValueError(f"latest calibration grid row differs from frozen artifact for {candidate_id}") | |
| return { | |
| "available": True, | |
| "candidates": by_candidate, | |
| "retry_candidates": { | |
| candidate: attempts | |
| for candidate, attempts in by_candidate.items() | |
| if len(attempts) > 1 | |
| }, | |
| } | |
| def analyze(calibration_path, heldout_root, split_manifest_path, output_dir, seeds, conditions, | |
| calibration_manifest_path=None, calibration_grid_path=None, | |
| calibration_data_path=None, heldout_data_path=None, | |
| parent_calibration_path=None): | |
| calibration = json.loads(Path(calibration_path).read_text(encoding="utf-8")) | |
| split_manifest = json.loads(Path(split_manifest_path).read_text(encoding="utf-8")) | |
| calibration_manifest_path = ( | |
| Path(calibration_manifest_path) | |
| if calibration_manifest_path is not None | |
| else Path(calibration_path).parent / "manifest.json" | |
| ) | |
| if not calibration_manifest_path.exists(): | |
| raise FileNotFoundError( | |
| f"frozen calibration manifest is required for candidate coverage: {calibration_manifest_path}" | |
| ) | |
| calibration_manifest = json.loads(calibration_manifest_path.read_text(encoding="utf-8")) | |
| if calibration_manifest.get("status") != "complete": | |
| raise ValueError("calibration manifest is incomplete; no heldout analysis is valid") | |
| heldout_gate_manifest_sha256 = verify_heldout_gate_manifest_hash(calibration_manifest) | |
| calibration_artifact_sha256 = verify_calibration_artifact_binding( | |
| calibration, | |
| calibration_manifest, | |
| Path(calibration_path), | |
| Path(parent_calibration_path) if parent_calibration_path is not None else None, | |
| ) | |
| calibration_rows = [int(row) for row in split_manifest["split_rows"]["calibration"]] | |
| heldout_rows = [int(row) for row in split_manifest["split_rows"]["heldout"]] | |
| previous_rows = set(map(int, split_manifest.get("excluded_previous_rows", []))) | |
| if set(calibration_rows) & set(heldout_rows) or ( | |
| set(calibration_rows) | set(heldout_rows) | |
| ) & previous_rows: | |
| raise ValueError("calibration/heldout rows overlap each other or prior ModelClinic runs") | |
| if calibration_data_path is None or heldout_data_path is None: | |
| raise ValueError("calibration and heldout JSONL paths are required for frozen split hash validation") | |
| calibration_raw = Path(calibration_data_path).read_bytes() | |
| calibration_data_sha256 = verify_split_input_hash(split_manifest, "calibration", calibration_raw) | |
| if calibration_data_sha256 != calibration.get("calibration_sha256"): | |
| raise ValueError("calibration artifact input hash differs from frozen calibration JSONL") | |
| input_rows = [int(row["source_row"]) for row in read_question_rows(Path(calibration_data_path))] | |
| if input_rows != calibration_rows: | |
| raise ValueError("calibration JSONL rows differ from frozen split manifest") | |
| heldout_raw = Path(heldout_data_path).read_bytes() | |
| heldout_data_sha256 = verify_split_input_hash(split_manifest, "heldout", heldout_raw) | |
| input_rows = [int(row["source_row"]) for row in read_question_rows(Path(heldout_data_path))] | |
| if input_rows != heldout_rows: | |
| raise ValueError("heldout JSONL rows differ from frozen split manifest") | |
| if calibration.get("selection", {}).get("heldout_used") is not False: | |
| raise ValueError("calibration artifact does not attest heldout was excluded") | |
| split_manifest_sha256 = hashlib.sha256(Path(split_manifest_path).read_bytes()).hexdigest() | |
| if calibration.get("split_manifest_sha256") != split_manifest_sha256: | |
| raise ValueError("calibration artifact split hash differs from frozen manifest") | |
| if calibration_manifest.get("split_manifest_sha256") != split_manifest_sha256: | |
| raise ValueError("calibration manifest split hash differs from frozen manifest") | |
| if calibration_manifest.get("calibration_sha256") != calibration.get("calibration_sha256"): | |
| raise ValueError("calibration manifest input hash differs from calibration artifact") | |
| if calibration_manifest.get("heldout_condition_config_ids") != calibration.get("heldout_condition_config_ids"): | |
| raise ValueError("calibration manifest and artifact heldout config maps differ") | |
| candidate_sampling = { | |
| json.dumps(candidate.get("sampling"), sort_keys=True, separators=(",", ":")) | |
| for candidate in calibration_manifest.get("calibration_candidates", []) | |
| } | |
| heldout_sampling = calibration_manifest.get("heldout_sampling") | |
| if len(candidate_sampling) != 1 or json.dumps( | |
| heldout_sampling, sort_keys=True, separators=(",", ":") | |
| ) != next(iter(candidate_sampling)): | |
| raise ValueError("heldout sampling does not match the frozen calibration sampling setup") | |
| candidate_caps = [ | |
| int(candidate.get("max_new_tokens", -1)) | |
| for candidate in calibration.get("grid_candidates", []) | |
| ] | |
| if not candidate_caps or any(cap <= 0 for cap in candidate_caps): | |
| raise ValueError("calibration artifact is missing candidate token caps") | |
| if len(set(candidate_caps)) != 1: | |
| raise ValueError("long calibration candidates do not share one token cap") | |
| heldout_cap = int(calibration_manifest.get("heldout_max_new_tokens", -1)) | |
| if heldout_cap <= 0 or any(cap != heldout_cap for cap in candidate_caps): | |
| raise ValueError( | |
| "heldout token cap differs from the frozen long-calibration candidate caps" | |
| ) | |
| artifact_heldout_cap = calibration.get("heldout_max_new_tokens") | |
| if artifact_heldout_cap is not None and int(artifact_heldout_cap) != heldout_cap: | |
| raise ValueError("heldout token cap differs between calibration artifact and manifest") | |
| heldout_max_generation_seconds = int( | |
| calibration_manifest.get("heldout_max_generation_seconds", -1) | |
| ) | |
| if heldout_max_generation_seconds <= 0: | |
| raise ValueError("calibration manifest is missing the frozen heldout wall limit") | |
| candidates, families, metadata, calibration_seed = normalize_calibration_grid( | |
| calibration, calibration_rows, calibration_manifest | |
| ) | |
| if calibration.get("calibration", {}).get("source_rows") != calibration_rows: | |
| raise ValueError("calibration artifact rows differ from frozen calibration split") | |
| expected_manifest_keys = ( | |
| calibration_manifest.get("expected_calibration_question_seeds") | |
| if calibration_manifest is not None | |
| else None | |
| ) | |
| expected_calibration = ( | |
| [(int(row), int(seed)) for row, seed in expected_manifest_keys] | |
| if expected_manifest_keys | |
| else [(row, calibration_seed) for row in calibration_rows] | |
| ) | |
| if {(row, seed) for row, seed in expected_calibration} != { | |
| (row, calibration_seed) for row in calibration_rows | |
| }: | |
| raise ValueError("calibration manifest question/seed keys disagree with frozen split") | |
| cap_calibration = int(calibration["grid_candidates"][0].get("max_new_tokens", 256)) | |
| selection = select_calibration_winners( | |
| candidates, families, expected_calibration, max_new_tokens=cap_calibration | |
| ) | |
| selection["candidate_metadata"] = metadata | |
| selection["direction_discovery_caveat"] = ( | |
| "The independent direction artifact is derived from prior long-diagnostic traces rather than discovery_4; early-versus-late positions are confounded, and the 8-gram proxy is post-hoc. No productive-versus-repetitive causal claim follows." | |
| ) | |
| grid_path = ( | |
| Path(calibration_grid_path) | |
| if calibration_grid_path is not None | |
| else Path(output_dir).parent / "calibration" / "grid_records.jsonl" | |
| ) | |
| selection["attempt_history"] = calibration_attempt_history(grid_path, calibration) | |
| recorded = calibration.get("selected", {}) | |
| for family, result in selection["families"].items(): | |
| recorded_id = recorded.get(family, {}).get("candidate_id") | |
| selected_id = result["selected_candidate_id"] | |
| if result["status"] == "selected" and recorded_id != selected_id: | |
| raise ValueError(f"runner selection differs for {family}: {recorded_id!r} vs {selected_id!r}") | |
| if result["status"] == "selected": | |
| selected_coefficients = metadata[selected_id].get("coefficients") | |
| if recorded.get(family, {}).get("coefficients") != selected_coefficients: | |
| raise ValueError(f"runner selected coefficients differ from frozen grid for {family}") | |
| if result["status"] == "incomplete" and recorded_id is not None: | |
| raise ValueError(f"runner selected incomplete family {family}") | |
| if calibration_manifest is not None: | |
| manifest_selected = calibration_manifest.get("selected_conditions", {}) | |
| for family, result in selection["families"].items(): | |
| manifest_id = manifest_selected.get(family, {}).get("candidate_id") | |
| if manifest_id != result["selected_candidate_id"]: | |
| raise ValueError(f"calibration manifest selection differs for {family}") | |
| if result["status"] == "selected" and manifest_selected.get(family, {}).get("coefficients") != metadata[manifest_id].get("coefficients"): | |
| raise ValueError(f"calibration manifest selected coefficients differ for {family}") | |
| heldout_condition = metadata.get(result["selected_candidate_id"], {}).get("heldout_condition") | |
| if heldout_condition: | |
| artifact_mapping = calibration.get("heldout_condition_config_ids", {}).get(heldout_condition) | |
| if artifact_mapping != result["selected_candidate_id"]: | |
| raise ValueError( | |
| f"calibration artifact heldout config map differs for {heldout_condition}" | |
| ) | |
| heldout_records = read_json_records(Path(heldout_root)) | |
| expected_record_settings = { | |
| **heldout_sampling, | |
| "max_new_tokens": heldout_cap, | |
| "max_generation_seconds": heldout_max_generation_seconds, | |
| "thinking": True, | |
| } | |
| for row in heldout_records: | |
| condition = str(row.get("condition", "")) | |
| row["candidate_id"] = row.get("condition_config_id", condition) | |
| settings = row.get("settings") | |
| if not isinstance(settings, dict): | |
| raise ValueError(f"heldout record has no settings object in {row.get('_source_file')}") | |
| for setting, expected_value in expected_record_settings.items(): | |
| if settings.get(setting) != expected_value: | |
| raise ValueError( | |
| f"heldout setting {setting} differs from the frozen manifest in " | |
| f"{row.get('_source_file')}: {settings.get(setting)!r} vs {expected_value!r}" | |
| ) | |
| if row.get("run_id") != calibration.get("run_id"): | |
| raise ValueError(f"heldout record run ID mismatch in {row.get('_source_file')}") | |
| if row.get("calibration_artifact_sha256") != calibration.get("calibration_artifact_sha256"): | |
| raise ValueError(f"heldout calibration hash mismatch in {row.get('_source_file')}") | |
| if heldout_data_sha256 and row.get("split_sha256") != heldout_data_sha256: | |
| raise ValueError(f"heldout split hash mismatch in {row.get('_source_file')}") | |
| selected_by_condition = { | |
| metadata[candidate_id]["heldout_condition"]: candidate_id | |
| for family in selection["families"].values() | |
| for candidate_id in [family["selected_candidate_id"]] | |
| if candidate_id is not None | |
| } | |
| family_condition_map = {} | |
| for data in metadata.values(): | |
| condition = data["heldout_condition"] | |
| family = data["family"] | |
| if condition in family_condition_map and family_condition_map[condition] != family: | |
| raise ValueError("multiple calibration families map to the same heldout condition") | |
| family_condition_map[condition] = family | |
| condition_config_ids = ( | |
| calibration_manifest.get("heldout_condition_config_ids", {}) | |
| if calibration_manifest is not None | |
| else {} | |
| ) | |
| expected_candidate_by_condition = { | |
| condition: condition_config_ids.get( | |
| condition, selected_by_condition.get(condition, condition) | |
| ) | |
| for condition in conditions | |
| } | |
| for condition, candidate_id in selected_by_condition.items(): | |
| if condition in condition_config_ids and condition_config_ids[condition] != candidate_id: | |
| raise ValueError(f"heldout config ID for {condition} differs from selected calibration candidate") | |
| for row in heldout_records: | |
| condition = str(row.get("condition", "")) | |
| expected_id = condition_config_ids.get(condition, selected_by_condition.get(condition, condition)) | |
| if expected_id and row["candidate_id"] != expected_id: | |
| raise ValueError(f"heldout {condition} uses {row['candidate_id']!r}, expected selected {expected_id!r}") | |
| if condition in family_condition_map: | |
| family = family_condition_map[condition] | |
| if selection["families"][family]["status"] != "selected": | |
| raise ValueError(f"heldout outputs exist for incomplete family {family}") | |
| selected_id = selected_by_condition.get(condition) | |
| if not selected_id or expected_id != selected_id: | |
| raise ValueError(f"heldout {condition} has no verified calibration-selected candidate") | |
| if condition not in family_condition_map: | |
| fixed_condition_id = condition_config_ids.get(condition, condition) | |
| if row["candidate_id"] != fixed_condition_id: | |
| raise ValueError( | |
| f"unexpected heldout config ID for fixed condition {condition}: " | |
| f"{row['candidate_id']!r}, expected {fixed_condition_id!r}" | |
| ) | |
| seeds = [int(seed) for seed in seeds] | |
| if not seeds or len(seeds) != len(set(seeds)): | |
| raise ValueError("heldout seeds must be unique and non-empty") | |
| expected = [(row, seed) for row in heldout_rows for seed in seeds] | |
| cap = heldout_cap | |
| heldout_summaries = {} | |
| paired = {} | |
| for condition in conditions: | |
| candidate_id = condition_config_ids.get( | |
| condition, selected_by_condition.get(condition, condition) | |
| ) | |
| family = family_condition_map.get(condition) | |
| if family and selection["families"][family]["status"] != "selected": | |
| heldout_summaries[condition] = {"status": "no_selected_calibration_candidate", "family": family} | |
| paired[condition + "_minus_base"] = {"status": "no_selected_calibration_candidate", "family": family} | |
| continue | |
| heldout_summaries[condition] = condition_summary( | |
| heldout_records, condition, candidate_id, expected, cap | |
| ) | |
| if condition == "base": | |
| continue | |
| paired[condition + "_minus_base"] = paired_heldout_summary( | |
| heldout_records, | |
| condition, | |
| "base", | |
| expected, | |
| first_candidate_id=candidate_id, | |
| comparator_candidate_id=condition_config_ids.get("base", "base"), | |
| ) | |
| comparison_ids = dict(condition_config_ids) | |
| comparison_ids.update(selected_by_condition) | |
| comparisons = summarize_experiment_001b_contrasts( | |
| heldout_records, | |
| expected, | |
| comparison_ids, | |
| ) | |
| output_dir = Path(output_dir) | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| (output_dir / "selection.json").write_text( | |
| json.dumps(selection, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| result = { | |
| "run_id": calibration.get("run_id"), | |
| "calibration_sha256": calibration.get("calibration_sha256"), | |
| "calibration_artifact_sha256": calibration.get("calibration_artifact_sha256"), | |
| "calibration_artifact_integrity": { | |
| "self_hash_verified": True, | |
| "manifest_hash_present": calibration_manifest.get("calibration_artifact_sha256") is not None, | |
| "manifest_hash_verified": ( | |
| calibration_manifest.get("calibration_artifact_sha256") == calibration_artifact_sha256 | |
| if calibration_manifest.get("calibration_artifact_sha256") is not None else None | |
| ), | |
| "parent_artifact_verified": ( | |
| calibration.get("phase") == "finalists" | |
| or calibration.get("calibration_stage") == "narrowed_finalists_32768" | |
| ), | |
| }, | |
| "calibration_manifest_sha256": ( | |
| hashlib.sha256(calibration_manifest_path.read_bytes()).hexdigest() | |
| if calibration_manifest_path.exists() | |
| else None | |
| ), | |
| "split_manifest_sha256": split_manifest_sha256, | |
| "heldout_rows": heldout_rows, | |
| "heldout_seeds": seeds, | |
| "heldout_max_new_tokens": cap, | |
| "heldout_max_generation_seconds": heldout_max_generation_seconds, | |
| "heldout_gate_manifest_sha256": heldout_gate_manifest_sha256, | |
| "heldout_record_settings": { | |
| "verified_records": len(heldout_records), | |
| "expected_values": expected_record_settings, | |
| "heldout_cap_source": ( | |
| "calibration manifest, cross-checked against every long-stage grid candidate; " | |
| "the artifact has no separate heldout_max_new_tokens field" | |
| if artifact_heldout_cap is None | |
| else "calibration artifact and manifest, cross-checked against every long-stage grid candidate" | |
| ), | |
| }, | |
| "selection": selection, | |
| "heldout_conditions": heldout_summaries, | |
| "paired_vs_base": paired, | |
| "comparisons": comparisons, | |
| "heldout_used_for_selection": False, | |
| "direction_discovery_caveat": ( | |
| "The independent direction artifact is currently derived from the prior five long-diagnostic traces, not the new discovery_4 split; early-versus-late positions are confounded with context/length, and the 8-gram proxy is post-hoc. This supports no productive-versus-repetitive causal claim." | |
| ), | |
| } | |
| (output_dir / "analysis.json").write_text( | |
| json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" | |
| ) | |
| write_per_question( | |
| output_dir / "per_question.csv", | |
| heldout_records, | |
| heldout_rows, | |
| seeds, | |
| conditions, | |
| expected_candidate_by_condition, | |
| cap, | |
| ) | |
| return result | |
| def _int_list(value): | |
| try: | |
| result = [int(part.strip()) for part in value.split(",") if part.strip()] | |
| except ValueError as exc: | |
| raise argparse.ArgumentTypeError("expected comma-separated integers") from exc | |
| if not result or len(result) != len(set(result)): | |
| raise argparse.ArgumentTypeError("values must be non-empty and unique") | |
| return result | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--calibration", type=Path, default=Path("experiments/calibration/long_finalists_and_restarts/calibration.json")) | |
| parser.add_argument("--calibration-manifest", type=Path, default=Path("experiments/calibration/long_finalists_and_restarts/heldout_gate_manifest.json")) | |
| parser.add_argument("--calibration-grid", type=Path, default=Path("experiments/calibration/long_finalists_and_restarts/grid_records.jsonl")) | |
| parser.add_argument("--parent-calibration", type=Path, default=Path("experiments/calibration/short_screen/calibration.json"), | |
| help="parent screen calibration JSON for the long-stage artifact") | |
| parser.add_argument("--calibration-data", type=Path, default=Path("experiments/evaluation/001b_calibration_6.jsonl")) | |
| parser.add_argument("--heldout-data", type=Path, default=Path("experiments/evaluation/001b_heldout_10.jsonl")) | |
| parser.add_argument("--heldout-root", type=Path, default=Path("results/experiment_001b/raw_generation_records")) | |
| parser.add_argument("--split-manifest", type=Path, default=Path("experiments/configurations/001b_splits_manifest.json")) | |
| parser.add_argument("--output-dir", type=Path, default=Path("results/experiment_001b/recomputed_analysis")) | |
| parser.add_argument("--seeds", type=_int_list, default=[0, 1]) | |
| parser.add_argument("--conditions", default=",".join(DEFAULT_CONDITIONS)) | |
| args = parser.parse_args() | |
| conditions = [part.strip() for part in args.conditions.split(",") if part.strip()] | |
| result = analyze( | |
| args.calibration, | |
| args.heldout_root, | |
| args.split_manifest, | |
| args.output_dir, | |
| args.seeds, | |
| conditions, | |
| calibration_manifest_path=args.calibration_manifest, | |
| calibration_grid_path=args.calibration_grid, | |
| calibration_data_path=args.calibration_data, | |
| heldout_data_path=args.heldout_data, | |
| parent_calibration_path=args.parent_calibration, | |
| ) | |
| print(json.dumps({ | |
| "output_dir": str(args.output_dir), | |
| "selected": {family: data["selected_candidate_id"] for family, data in result["selection"]["families"].items()}, | |
| "heldout_conditions": result["heldout_conditions"], | |
| }, indent=2), flush=True) | |
| if __name__ == "__main__": | |
| main() | |