Download code/tests/test_experiment_001b_analysis_integrity.py from PratikBuilds/modelclinic-experiment-001: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/tests/test_experiment_001b_analysis_integrity.py
- Command line
-
hf download hf://datasets/PratikBuilds/modelclinic-experiment-001/code/tests/test_experiment_001b_analysis_integrity.py
-
curl -L -o test_experiment_001b_analysis_integrity.py https://huggingface.co/datasets/PratikBuilds/modelclinic-experiment-001/resolve/main/code/tests/test_experiment_001b_analysis_integrity.py
13.9 kB
| """Integrity and predeclared-comparison checks for the 001B analysis path.""" | |
| from __future__ import annotations | |
| import hashlib | |
| import csv | |
| import json | |
| import sys | |
| from pathlib import Path | |
| import pytest | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT / "src")) | |
| from analyze_experiment_001b import ( # noqa: E402 | |
| calibration_attempt_history, | |
| condition_summary, | |
| normalize_calibration_grid, | |
| verify_calibration_artifact_binding, | |
| verify_split_input_hash, | |
| write_per_question, | |
| ) | |
| from experiment_001b_analysis import ( # noqa: E402 | |
| paired_heldout_summary, | |
| select_calibration_winners, | |
| summarize_experiment_001b_contrasts, | |
| ) | |
| def _canonical_hash(payload: dict) -> str: | |
| raw = (json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode() | |
| return hashlib.sha256(raw).hexdigest() | |
| def _with_artifact_hash(payload: dict) -> dict: | |
| result = dict(payload) | |
| result["calibration_artifact_sha256"] = _canonical_hash(payload) | |
| return result | |
| def test_split_input_hash_is_anchored_to_frozen_manifest_even_with_same_rows(): | |
| original = b'{"source_row":3,"problem":"original","answer":"2"}\n' | |
| changed_content_same_row = b'{"source_row":3,"problem":"changed","answer":"2"}\n' | |
| manifest = { | |
| "split_rows": {"calibration": [3]}, | |
| "split_file_sha256": { | |
| "001b_calibration_1.jsonl": hashlib.sha256(original).hexdigest(), | |
| }, | |
| } | |
| assert verify_split_input_hash(manifest, "calibration", original) == hashlib.sha256(original).hexdigest() | |
| with pytest.raises(ValueError, match="differs from frozen split manifest"): | |
| verify_split_input_hash(manifest, "calibration", changed_content_same_row) | |
| def test_calibration_artifact_hash_must_match_contents_and_manifest(): | |
| artifact = _with_artifact_hash({"phase": "screen", "calibration_stage": "screen_8192"}) | |
| manifest = { | |
| "status": "complete", | |
| "calibration_artifact_sha256": artifact["calibration_artifact_sha256"], | |
| } | |
| path = Path("screen/calibration.json") | |
| assert verify_calibration_artifact_binding(artifact, manifest, path) == artifact[ | |
| "calibration_artifact_sha256" | |
| ] | |
| assert verify_calibration_artifact_binding(artifact, {"status": "complete"}, path) == artifact[ | |
| "calibration_artifact_sha256" | |
| ] | |
| tampered = dict(artifact, selected={"published_constant": "other"}) | |
| with pytest.raises(ValueError, match="does not match its contents"): | |
| verify_calibration_artifact_binding(tampered, manifest, path) | |
| with pytest.raises(ValueError, match="manifest artifact hash differs"): | |
| verify_calibration_artifact_binding(artifact, dict(manifest, calibration_artifact_sha256="wrong"), path) | |
| def test_calibration_manifest_coefficients_must_match_scored_candidate(): | |
| candidate = { | |
| "candidate_id": "candidate_a", | |
| "family": "family", | |
| "condition": "family", | |
| "heldout_condition": "family", | |
| "coefficients": {"15": 0.5}, | |
| "max_new_tokens": 100, | |
| "max_generation_seconds": 10, | |
| "sampling": {"temperature": 0.6}, | |
| } | |
| calibration = { | |
| "grid_candidates": [{ | |
| **candidate, | |
| "coefficients": {"15": 0.25}, | |
| "seed": 0, | |
| "status": "complete", | |
| "prompt_outcomes": [], | |
| }], | |
| } | |
| manifest = { | |
| "calibration_candidates": [candidate], | |
| "selection_families": {"family": ["candidate_a"]}, | |
| } | |
| with pytest.raises(ValueError, match="coefficients differs"): | |
| normalize_calibration_grid(calibration, [1], manifest) | |
| def test_calibration_candidates_must_share_sampling_and_generation_caps(): | |
| base = { | |
| "family": "family", | |
| "condition": "family", | |
| "heldout_condition": "family", | |
| "coefficients": {"15": 0.5}, | |
| "max_new_tokens": 100, | |
| "max_generation_seconds": 10, | |
| "sampling": {"temperature": 0.6}, | |
| } | |
| configs = [ | |
| {"candidate_id": "candidate_a", **base}, | |
| {"candidate_id": "candidate_b", **{ | |
| **base, | |
| "coefficients": {"15": -0.5}, | |
| "max_new_tokens": 200, | |
| }}, | |
| ] | |
| rows = [ | |
| { | |
| **config, | |
| "seed": 0, | |
| "status": "complete", | |
| "prompt_outcomes": [], | |
| "calibration_rows": [1], | |
| } | |
| for config in configs | |
| ] | |
| calibration = {"grid_candidates": rows} | |
| manifest = { | |
| "calibration_candidates": configs, | |
| "selection_families": {"family": ["candidate_a", "candidate_b"]}, | |
| } | |
| with pytest.raises(ValueError, match="do not share one seed, sampling setup, and cap"): | |
| normalize_calibration_grid(calibration, [1], manifest) | |
| def test_grid_history_latest_attempt_must_match_frozen_calibration_outcome(tmp_path): | |
| first = { | |
| "candidate_id": "candidate_a", | |
| "candidate_attempt": 1, | |
| "status": "error", | |
| "error": "retryable engine error", | |
| "prompt_outcomes": [], | |
| } | |
| final = { | |
| "candidate_id": "candidate_a", | |
| "candidate_attempt": 2, | |
| "status": "complete", | |
| "error": None, | |
| "prompt_outcomes": [{"source_row": 1, "score": {"status": "correct", "correct": True}}], | |
| } | |
| grid = tmp_path / "grid_records.jsonl" | |
| grid.write_text("\n".join(json.dumps(row) for row in (first, final)) + "\n", encoding="utf-8") | |
| calibration = {"grid_candidates": [final]} | |
| result = calibration_attempt_history(grid, calibration) | |
| assert result["retry_candidates"]["candidate_a"][-1]["attempt"] == 2 | |
| corrupted = dict(final, prompt_outcomes=[{"source_row": 1, "score": {"status": "incorrect", "correct": False}}]) | |
| calibration["grid_candidates"] = [corrupted] | |
| with pytest.raises(ValueError, match="latest calibration grid row differs"): | |
| calibration_attempt_history(grid, calibration) | |
| def test_long_calibration_artifact_must_bind_to_the_parent_screen(tmp_path): | |
| parent_dir = tmp_path / "calibration" | |
| child_dir = tmp_path / "calibration_long" | |
| parent_dir.mkdir() | |
| child_dir.mkdir() | |
| frozen_inputs = { | |
| "run_id": "run-1", | |
| "model": {"base_revision": "base", "edited_revision": "edited", "precision": "bfloat16"}, | |
| "calibration_sha256": "cal-data-hash", | |
| "independent_sha256": "direction-hash", | |
| "split_manifest_sha256": "split-hash", | |
| } | |
| parent = _with_artifact_hash({ | |
| **frozen_inputs, | |
| "phase": "screen", | |
| "calibration_stage": "screen_8192", | |
| }) | |
| parent_path = parent_dir / "calibration.json" | |
| parent_path.write_text(json.dumps(parent), encoding="utf-8") | |
| (parent_dir / "manifest.json").write_text( | |
| json.dumps({ | |
| "status": "complete", | |
| }), | |
| encoding="utf-8", | |
| ) | |
| child = _with_artifact_hash({ | |
| **frozen_inputs, | |
| "phase": "finalists", | |
| "calibration_stage": "narrowed_finalists_32768", | |
| "parent_calibration_artifact_sha256": parent["calibration_artifact_sha256"], | |
| }) | |
| child_path = child_dir / "calibration.json" | |
| manifest = { | |
| "status": "complete", | |
| "parent_calibration_artifact_sha256": parent["calibration_artifact_sha256"], | |
| } | |
| verify_calibration_artifact_binding(child, manifest, child_path) | |
| wrong_parent = _with_artifact_hash({ | |
| **frozen_inputs, | |
| "phase": "finalists", | |
| "calibration_stage": "narrowed_finalists_32768", | |
| "parent_calibration_artifact_sha256": "wrong-parent", | |
| }) | |
| with pytest.raises(ValueError, match="does not match screen calibration artifact"): | |
| verify_calibration_artifact_binding( | |
| wrong_parent, | |
| dict(manifest, | |
| calibration_artifact_sha256=wrong_parent["calibration_artifact_sha256"], | |
| parent_calibration_artifact_sha256="wrong-parent"), | |
| child_path, | |
| ) | |
| mismatched_input = _with_artifact_hash({ | |
| **frozen_inputs, | |
| "calibration_sha256": "different-cal-data", | |
| "phase": "finalists", | |
| "calibration_stage": "narrowed_finalists_32768", | |
| "parent_calibration_artifact_sha256": parent["calibration_artifact_sha256"], | |
| }) | |
| with pytest.raises(ValueError, match="calibration_sha256 differs from its parent"): | |
| verify_calibration_artifact_binding( | |
| mismatched_input, | |
| dict(manifest, | |
| calibration_artifact_sha256=mismatched_input["calibration_artifact_sha256"], | |
| parent_calibration_artifact_sha256=parent["calibration_artifact_sha256"]), | |
| child_path, | |
| ) | |
| def test_malformed_calibration_score_blocks_the_family_instead_of_becoming_no_credit(): | |
| malformed = { | |
| "candidate_id": "candidate_a", | |
| "source_row": 1, | |
| "seed": 0, | |
| "score": {"status": "correct", "correct": False}, | |
| "finish_reason": "stop", | |
| "tokens": 10, | |
| } | |
| result = select_calibration_winners( | |
| {"candidate_a": [malformed]}, | |
| {"family": ["candidate_a"]}, | |
| [(1, 0)], | |
| max_new_tokens=100, | |
| ) | |
| family = result["families"]["family"] | |
| assert family["status"] == "incomplete" | |
| assert family["selected_candidate_id"] is None | |
| assert family["candidates"]["candidate_a"]["n_scoring_errors"] == 1 | |
| assert "scoring_errors:candidate_a" in family["blockers"] | |
| def test_unknown_or_missing_score_fields_block_calibration_selection(score): | |
| record = { | |
| "candidate_id": "candidate_a", | |
| "source_row": 1, | |
| "seed": 0, | |
| "score": score, | |
| "finish_reason": "stop", | |
| "tokens": 10, | |
| } | |
| result = select_calibration_winners( | |
| {"candidate_a": [record]}, | |
| {"family": ["candidate_a"]}, | |
| [(1, 0)], | |
| max_new_tokens=100, | |
| ) | |
| assert result["families"]["family"]["status"] == "incomplete" | |
| assert result["families"]["family"]["selected_candidate_id"] is None | |
| def test_malformed_heldout_score_is_excluded_and_suppresses_inference(): | |
| records = [ | |
| { | |
| "condition": "edited", | |
| "source_row": 1, | |
| "seed": 0, | |
| "score": {"status": "correct", "correct": False}, | |
| }, | |
| { | |
| "condition": "base", | |
| "source_row": 1, | |
| "seed": 0, | |
| "score": {"status": "incorrect", "correct": False}, | |
| }, | |
| ] | |
| result = paired_heldout_summary(records, "edited", "base", [(1, 0)], bootstrap_samples=0) | |
| assert result["complete_matched_generation_pairs"] == 0 | |
| assert result["exact_mcnemar_two_sided_p"] is None | |
| assert result["inference_suppressed"] | |
| assert result["incomplete_pairs"][0]["scoring_errors"] == { | |
| "edited": "scoring_error:correct_status_mismatch" | |
| } | |
| def test_condition_summary_and_per_question_csv_expose_malformed_grades(tmp_path): | |
| malformed = { | |
| "condition": "edited", | |
| "candidate_id": "edited", | |
| "source_row": 1, | |
| "seed": 0, | |
| "score": None, | |
| "finish_reason": "stop", | |
| "tokens": 8, | |
| } | |
| summary = condition_summary([malformed], "edited", "edited", [(1, 0)], cap=100) | |
| assert summary["complete"] is False | |
| assert summary["accuracy_over_expected"] is None | |
| assert summary["scoring_errors"] == [ | |
| {"question_seed": [1, 0], "reason": "scoring_error:missing_score_object"} | |
| ] | |
| output = tmp_path / "per_question.csv" | |
| write_per_question(output, [malformed], [1], [0], ["edited"], {"edited": "edited"}, 100) | |
| with output.open(newline="", encoding="utf-8") as stream: | |
| row = next(csv.DictReader(stream)) | |
| assert row["record_status"] == "scoring_error" | |
| assert row["solve_credit"] == "" | |
| assert row["error"] == "scoring_error:missing_score_object" | |
| def test_comparison_plan_marks_one_primary_and_three_diagnostic_pairs_exploratory(): | |
| condition_ids = { | |
| "base": "base", | |
| "edited": "edited", | |
| "published_constant": "published-winner", | |
| "independent_constant": "independent-winner", | |
| "norm_matched_random": "random", | |
| "rank1_activation_dependent": "rank1", | |
| } | |
| records = [] | |
| for row in (1, 2): | |
| for condition, candidate in condition_ids.items(): | |
| status = "correct" if row == 1 and condition in {"edited", "rank1_activation_dependent"} else "incorrect" | |
| records.append({ | |
| "condition": condition, | |
| "candidate_id": candidate, | |
| "source_row": row, | |
| "seed": 0, | |
| "score": { | |
| "status": status, | |
| "correct": status == "correct", | |
| }, | |
| }) | |
| result = summarize_experiment_001b_contrasts( | |
| records, [(1, 0), (2, 0)], condition_ids, bootstrap_samples=0 | |
| ) | |
| assert result["plan"]["primary"] == "edited_minus_published_constant" | |
| assert result["primary_prespecified"]["summary"]["first_candidate_id"] == "edited" | |
| assert result["primary_prespecified"]["summary"]["comparator_candidate_id"] == "published-winner" | |
| assert "unadjusted" in result["plan"]["other_comparisons"] | |
| assert set(result["exploratory_diagnostic_pairs_unadjusted"]) == { | |
| "rank1_activation_dependent_minus_published_constant", | |
| "rank1_activation_dependent_minus_norm_matched_random", | |
| "edited_minus_rank1_activation_dependent", | |
| } | |