modelclinic-experiment-001 / code /src /experiment_001c_gate_pairing.py
PratikBuilds's picture
Publish complete available Experiment 001 research release (001A–001D)
cb8c6af verified
Raw History Blame Contribute Delete
13.2 kB
"""Frozen design helpers and analysis for Experiment 001C gate coupling."""
from __future__ import annotations
import gzip
import hashlib
import json
import random
from pathlib import Path
from typing import Any, Mapping, Sequence
DONOR_SEED = 20261104
BOOTSTRAP_SEED = 20261105
BOOTSTRAP_SAMPLES = 20_000
EQUIVALENCE_MARGIN_NATS = 0.01
RUN_ID = "experiment_001c_gate_pairing_v1"
def sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def sha256_file(path: str | Path) -> str:
digest = hashlib.sha256()
with Path(path).open("rb") as handle:
for block in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def canonical_json_bytes(value: Any) -> bytes:
return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8")
def read_jsonl(path: str | Path) -> list[dict[str, Any]]:
rows = []
for line_no, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), 1):
if not line.strip():
continue
try:
item = json.loads(line)
except json.JSONDecodeError as exc:
raise ValueError(f"invalid JSONL at {path}:{line_no}: {exc}") from exc
if not isinstance(item, dict):
raise ValueError(f"expected an object at {path}:{line_no}")
rows.append(item)
return rows
def eligible_rows(source_rows: Sequence[Mapping[str, Any]], split_manifest: Mapping[str, Any]) -> list[dict[str, Any]]:
"""Return all rows not used in prior ModelClinic model runs."""
used = {
int(row)
for row in split_manifest.get("excluded_previous_rows", [])
} | {
int(row)
for row in split_manifest.get("selection_order", [])
}
eligible = []
for source_row, item in enumerate(source_rows):
if source_row in used:
continue
if not {"problem", "solution", "answer", "unique_id"}.issubset(item):
raise ValueError(f"source row {source_row} is missing required fields")
row = dict(item)
row["source_row"] = source_row
eligible.append(row)
return eligible
def build_donor_schedule(solution_lengths: Mapping[int | str, int], seed: int = DONOR_SEED) -> dict[int, dict[int, int | None]]:
"""Build a per-answer-position derangement among rows with that position.
A random cyclic shift of a random ordering gives each eligible question one
non-self donor and preserves the coefficient multiset exactly at every
answer position.
"""
lengths = {int(row): int(length) for row, length in solution_lengths.items()}
if not lengths or any(length < 1 for length in lengths.values()):
raise ValueError("solution lengths must be non-empty positive integers")
rng = random.Random(seed)
schedule: dict[int, dict[int, int | None]] = {}
for position in range(max(lengths.values())):
active = sorted(row for row, length in lengths.items() if position < length)
assignment: dict[int, int | None] = {row: None for row in active}
if len(active) >= 2:
order = list(active)
rng.shuffle(order)
shift = rng.randrange(1, len(order))
for index, row in enumerate(order):
donor = order[(index + shift) % len(order)]
if donor == row:
raise AssertionError("derangement unexpectedly mapped a row to itself")
assignment[row] = donor
schedule[position] = assignment
return schedule
def percentile(sorted_values: Sequence[float], probability: float) -> float:
if not sorted_values:
raise ValueError("cannot take a percentile of an empty sequence")
position = (len(sorted_values) - 1) * probability
low = int(position)
high = min(low + 1, len(sorted_values) - 1)
fraction = position - low
return sorted_values[low] * (1.0 - fraction) + sorted_values[high] * fraction
def analyze_records(
records: Sequence[Mapping[str, Any]],
*,
bootstrap_samples: int = BOOTSTRAP_SAMPLES,
bootstrap_seed: int = BOOTSTRAP_SEED,
) -> dict[str, Any]:
"""Analyze paired per-question NLLs; tokens are not independent units."""
if bootstrap_samples < 1:
raise ValueError("bootstrap_samples must be positive")
per_question = []
for record in sorted(records, key=lambda item: int(item["source_row"])):
row = int(record["source_row"])
dynamic = [float(value) for value in record["dynamic_nll_by_token"]]
shuffled = [float(value) for value in record["shuffled_nll_by_token"]]
donors = record["donor_row_by_position"]
if len(dynamic) != len(shuffled) or len(dynamic) != len(donors):
raise ValueError(f"per-token output length mismatch for row {row}")
if any(donor is not None and int(donor) == row for donor in donors):
raise ValueError(f"donor schedule maps row {row} to itself")
positions = [index for index, donor in enumerate(donors) if donor is not None]
if not positions:
raise ValueError(f"row {row} has no positions with an eligible donor")
dynamic_mean = sum(dynamic[index] for index in positions) / len(positions)
shuffled_mean = sum(shuffled[index] for index in positions) / len(positions)
per_question.append(
{
"source_row": row,
"unique_id": str(record.get("unique_id", row)),
"eligible_tokens": len(positions),
"solution_tokens": len(dynamic),
"dynamic_mean_nll": dynamic_mean,
"shuffled_mean_nll": shuffled_mean,
"shuffled_minus_dynamic_nll": shuffled_mean - dynamic_mean,
}
)
if len(per_question) < 2:
raise ValueError("at least two question clusters are required")
differences = [float(item["shuffled_minus_dynamic_nll"]) for item in per_question]
mean_difference = sum(differences) / len(differences)
rng = random.Random(bootstrap_seed)
means = sorted(
sum(rng.choice(differences) for _ in range(len(differences))) / len(differences)
for _ in range(bootstrap_samples)
)
ci95 = [percentile(means, 0.025), percentile(means, 0.975)]
ci90 = [percentile(means, 0.05), percentile(means, 0.95)]
positive = sum(value > 0 for value in differences)
negative = sum(value < 0 for value in differences)
equal = len(differences) - positive - negative
return {
"run_id": RUN_ID,
"primary_outcome": "question-equal mean of donor-shuffled NLL minus dynamic NLL, in nats per reference-solution token",
"positive_favors": "activation-matched dynamic gate",
"n_question_clusters": len(per_question),
"n_eligible_answer_tokens": sum(int(item["eligible_tokens"]) for item in per_question),
"mean_question_weighted_difference": mean_difference,
"question_cluster_bootstrap_95": ci95,
"question_cluster_bootstrap_90": ci90,
"equivalence_margin_nats_per_token": EQUIVALENCE_MARGIN_NATS,
"activation_pairing_likelihood_advantage_supported": ci95[0] > 0,
"practical_equivalence_for_likelihood_supported": (
ci90[0] > -EQUIVALENCE_MARGIN_NATS and ci90[1] < EQUIVALENCE_MARGIN_NATS
),
"question_difference_signs": {"dynamic_favored": positive, "shuffle_favored": negative, "tie": equal},
"bootstrap_samples": bootstrap_samples,
"bootstrap_seed": bootstrap_seed,
"per_question": per_question,
"interpretation_limit": (
"Teacher-forced reference-solution likelihood only; this is not a free-generation solve-rate result."
),
}
def freeze_manifest(
*,
source_path: str | Path,
split_manifest_path: str | Path,
calibration_path: str | Path,
preregistration_path: str | Path,
helper_path: str | Path,
runner_path: str | Path,
prompt_path: str | Path,
output_path: str | Path,
) -> dict[str, Any]:
source_rows = read_jsonl(source_path)
split_manifest = json.loads(Path(split_manifest_path).read_text(encoding="utf-8"))
if sha256_file(source_path) != split_manifest["source_sha256"]:
raise ValueError("source MATH-500 file hash differs from the pinned split manifest")
if len(source_rows) != int(split_manifest["source_row_count"]):
raise ValueError("source MATH-500 row count differs from the pinned split manifest")
selected = eligible_rows(source_rows, split_manifest)
if len(selected) != 455:
raise ValueError(f"expected 455 prior-run-excluded rows, got {len(selected)}")
calibration = json.loads(Path(calibration_path).read_text(encoding="utf-8"))
declared_calibration_hash = calibration.get("calibration_artifact_sha256")
hash_payload = dict(calibration)
hash_payload.pop("calibration_artifact_sha256", None)
if declared_calibration_hash != sha256_bytes(canonical_json_bytes(hash_payload)):
raise ValueError("calibration artifact self-hash is invalid")
if set(calibration.get("layers", {})) != {"15", "19"}:
raise ValueError("calibration artifact does not have the frozen layers 15 and 19")
for layer, layer_data in calibration["layers"].items():
if len(layer_data.get("direction", [])) != 1024 or len(layer_data.get("rank1_gate_vector", [])) != 3584:
raise ValueError(f"invalid frozen direction/gate dimensions for layer {layer}")
output_path = Path(output_path)
manifest = {
"run_id": RUN_ID,
"status": "frozen_before_model_outcomes",
"created_utc": __import__("datetime").datetime.now(__import__("datetime").timezone.utc).isoformat(),
"dataset": "HuggingFaceH4/MATH-500",
"dataset_revision": split_manifest["revision"],
"dataset_source_url": split_manifest["source_url"],
"source_rows": len(source_rows),
"prior_modelclinic_run_exclusions": sorted(
{int(row) for row in split_manifest.get("excluded_previous_rows", [])}
| {int(row) for row in split_manifest.get("selection_order", [])}
),
"eligible_rows": [
{"source_row": int(row["source_row"]), "unique_id": str(row["unique_id"])}
for row in selected
],
"eligible_row_count": len(selected),
"source_sha256": sha256_file(source_path),
"split_manifest_sha256": sha256_file(split_manifest_path),
"calibration_path": str(calibration_path).replace("\\", "/"),
"calibration_file_sha256": sha256_file(calibration_path),
"calibration_artifact_sha256": declared_calibration_hash,
"preregistration_sha256": sha256_file(preregistration_path),
"helper_sha256": sha256_file(helper_path),
"modal_runner_sha256": sha256_file(runner_path),
"prompt_builder_sha256": sha256_file(prompt_path),
"model": {
"base_revision": "2fc06364715b967f1860aea9cf38778875588b17",
"precision": "bfloat16",
"runtime": "Transformers 5.20.2 on Modal A10",
},
"intervention": {
"layers": [15, 19],
"source": "rank-one decomposition frozen in Experiment 001B calibration_long",
"prompt_template": "src/long_protocol.py build_prompt + Qwen thinking-enabled chat template",
"reference_target": "dataset solution field, tokenized without rewriting",
},
"donor_shuffle": {
"seed": DONOR_SEED,
"assignment": "random permutation followed by nonzero cyclic shift at every answer-token position",
"preserves": "coefficient multiset exactly at each answer-token position among rows with that position",
"singleton_tail": "own dynamic coefficient; excluded from primary outcome",
},
"primary_outcome": "question-equal mean NLL_donor_shuffled minus NLL_dynamic, nats per reference-solution token",
"primary_unit": "question cluster",
"bootstrap": {"samples": BOOTSTRAP_SAMPLES, "seed": BOOTSTRAP_SEED, "intervals": [0.95, 0.90]},
"equivalence_margin_nats_per_token": EQUIVALENCE_MARGIN_NATS,
"cost_control": {
"one_gpu_function_timeout_seconds": 14400,
"conservative_blended_usd_per_hour": 2.0,
"worst_case_function_reservation_usd": 8.0,
"no_automatic_retry": True,
},
"scope_limit": "Teacher-forced likelihood; not generated solve rate or a general claim about weight editing.",
}
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_bytes(canonical_json_bytes(manifest))
return manifest
def load_gzip_json(path: str | Path) -> dict[str, Any]:
with gzip.open(path, "rt", encoding="utf-8") as handle:
return json.load(handle)
__all__ = [
"BOOTSTRAP_SAMPLES",
"BOOTSTRAP_SEED",
"DONOR_SEED",
"EQUIVALENCE_MARGIN_NATS",
"RUN_ID",
"analyze_records",
"build_donor_schedule",
"canonical_json_bytes",
"eligible_rows",
"freeze_manifest",
"load_gzip_json",
"read_jsonl",
"sha256_bytes",
"sha256_file",
]