Download source/scripts/verify_position_tracking.py from willynilly-fr/evm-positions-scratch-20ep: direct link, hf CLI and curl.
- Browser
- Download file 22.6 kB
-
https://huggingface.co/willynilly-fr/evm-positions-scratch-20ep/resolve/main/source/scripts/verify_position_tracking.py
- Command line
-
hf download hf://willynilly-fr/evm-positions-scratch-20ep/source/scripts/verify_position_tracking.py
-
curl -L -o verify_position_tracking.py https://huggingface.co/willynilly-fr/evm-positions-scratch-20ep/resolve/main/source/scripts/verify_position_tracking.py
22.6 kB
| """Read-only W&B verification of all positional/Lightning campaign updates. | |
| Twelve training stages occupy eleven W&B runs: the Part 1 transferred and | |
| scratch classifiers intentionally share one run and use distinct field prefixes. | |
| Every history row is scanned without key filtering, including explicit SDK | |
| ``_step`` counters. Missing counters are never reconstructed from user steps. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import math | |
| from datetime import UTC, datetime | |
| from pathlib import Path | |
| import click | |
| PROJECT = "somehowchris/willynilly" | |
| def sha256(path): | |
| return hashlib.sha256(Path(path).read_bytes()).hexdigest() | |
| def scalar(value): | |
| return isinstance(value, (int, float)) and not isinstance(value, bool) | |
| def integer(value): | |
| return scalar(value) and math.isfinite(value) and int(value) == value | |
| def local_values(records, expected_steps): | |
| records = list(records) | |
| if not isinstance(expected_steps, int) or isinstance(expected_steps, bool) or expected_steps < 1: | |
| raise ValueError("Expected update count must be a positive integer") | |
| if [row.get("step") for row in records] != list(range(1, expected_steps + 1)): | |
| raise ValueError("Local user steps must cover exactly continuous 1..expected_updates") | |
| values = [] | |
| for row in records: | |
| if not isinstance(row.get("step"), int) or isinstance(row["step"], bool): | |
| raise ValueError("Local user steps must be integer counters") | |
| numeric = {key: value for key, value in row.items() if scalar(value)} | |
| if not integer(numeric.get("step")) or any(not math.isfinite(value) for value in numeric.values()): | |
| raise ValueError("Local counters/scalars must be finite") | |
| for key in ("gradients/pre_clip_global_l2", "gradients/post_clip_global_l2"): | |
| if numeric.get(key, 0) <= 0: | |
| raise ValueError("Local evidence requires positive pre/post clipping norms") | |
| maximum = numeric.get("gradients/clip_max_norm") | |
| if maximum != 1. or numeric["gradients/post_clip_global_l2"] > maximum + 1e-5: | |
| raise ValueError("Local post-clipping norm exceeds the authorized bound of one") | |
| if numeric.get("gradients/clipping_applied") != int(numeric["gradients/pre_clip_global_l2"] > maximum): | |
| raise ValueError("Local clipping decision differs from the observed norm") | |
| if not any(key in numeric for key in ("loss", "train/loss")): | |
| raise ValueError("Local update has no scalar loss") | |
| if any(value <= 0 for key, value in numeric.items() | |
| if key.startswith("gradients/") and "layer_" in key and key.endswith("_l2")): | |
| raise ValueError("Local encoder layer has no positive gradient") | |
| values.append(numeric) | |
| return values | |
| def scanned_values(records): | |
| """Require genuine, unique SDK counters even for non-gradient server rows.""" | |
| records = list(records) | |
| indexed = {} | |
| for row in records: | |
| step = row.get("_step") | |
| if not integer(step) or step < 0: | |
| raise ValueError("Every scanned W&B row requires an explicit integer SDK _step") | |
| if int(step) in indexed: | |
| raise ValueError("Duplicate W&B SDK _step in the unfiltered scan") | |
| indexed[int(step)] = row | |
| return indexed | |
| def verify_rows(local, server, *, expected_steps, prefix="", sdk_steps=None, | |
| rtol=1e-6, atol=1e-8): | |
| """Compare every numeric local field against its explicit remote counters.""" | |
| local = local_values(local, expected_steps) | |
| indexed = scanned_values(server) | |
| expected_sdk = list(range(1, expected_steps + 1)) if sdk_steps is None else list(sdk_steps) | |
| if len(expected_sdk) != expected_steps or len(set(expected_sdk)) != expected_steps: | |
| raise ValueError("Expected SDK map must name one unique counter per local update") | |
| gradient_rows = {step: row for step, row in indexed.items() | |
| if any(key.startswith(prefix + "gradients/") and | |
| (key.endswith("_l2") or key.endswith("/clip_max_norm") or key.endswith("/clipping_applied")) | |
| for key in row)} | |
| if set(gradient_rows) != set(expected_sdk): | |
| raise ValueError("W&B gradient rows differ from exact expected coverage (missing or extra rows)") | |
| scalars = gradient_scalars = clipped = 0 | |
| for row, sdk_step in zip(local, expected_sdk, strict=True): | |
| actual = gradient_rows[sdk_step] | |
| if actual.get(prefix + "step") != row["step"] or not integer(actual.get(prefix + "step")): | |
| raise ValueError("W&B user step differs from the explicit SDK-to-local mapping") | |
| for key, expected in row.items(): | |
| observed = actual.get(prefix + key) | |
| if not scalar(observed) or not math.isfinite(observed): | |
| raise ValueError(f"Missing/nonfinite W&B scalar at SDK {sdk_step}: {prefix + key}") | |
| match = observed == expected if isinstance(expected, int) else math.isclose( | |
| observed, expected, rel_tol=rtol, abs_tol=atol) | |
| if not match: | |
| raise ValueError(f"W&B scalar differs at SDK {sdk_step}: {prefix + key}") | |
| scalars += 1 | |
| gradient_scalars += int(key.startswith("gradients/")) | |
| clipped += row["gradients/clipping_applied"] | |
| return {"optimizer_updates": expected_steps, "scalar_values_verified": scalars, | |
| "gradient_scalar_values_verified": gradient_scalars, "clipped_updates": clipped, | |
| "sdk_steps": expected_sdk, "all_sdk_counters_explicit": True, | |
| "all_local_scalars_match": True, "no_extra_gradient_rows": True, | |
| "field_prefix": prefix, "float_tolerance": {"relative": rtol, "absolute": atol}} | |
| def resolve_path(path, root): | |
| path = Path(path) | |
| if path.is_absolute() or path.is_file(): | |
| return path | |
| if (root / path).is_file(): | |
| return root / path | |
| raise FileNotFoundError(path) | |
| def legacy_history_optimizer_binding(path, gradients, report, updates, runtime, audit_path): | |
| """Accept a missing old runtime field only with separately bound evidence. | |
| This does not reconstruct or assert the unrecorded Python class. It binds the | |
| recorded optimizer name and independently checked original gradient stream. | |
| """ | |
| if (report.get("stage") not in {"history-pretraining", "history-account-finetuning"} | |
| or report.get("optimizer") != "AdamW" or audit_path is None): | |
| raise ValueError("Missing optimizer class requires an independently audited AdamW history report") | |
| audit_path = Path(audit_path) | |
| audit = json.loads(audit_path.read_text()) | |
| if audit.get("status") != "passed": | |
| raise ValueError("Legacy history optimizer evidence requires a passed independent audit") | |
| bound = audit.get("all_file_sha256", {}) | |
| hashes = {str(Path(value).resolve()): sha256(value) for value in (path, gradients)} | |
| if any(bound.get(name) != digest for name, digest in hashes.items()): | |
| raise ValueError("Independent audit does not bind the unchanged history report and gradients") | |
| run_directory = Path(path).parent if report["stage"] == "history-pretraining" else Path(path).parent.parent | |
| candidates = [run for run in audit["runs"] if | |
| run_directory.name == f"{run['profile']}-{run['architecture']}-s{run['seed']}" and | |
| run["architecture"] == report["architecture"] and run["seed"] == report["seed"]] | |
| if len(candidates) != 1: | |
| raise ValueError("Independent audit does not uniquely identify the original history stage") | |
| key = "pretraining_clipping" if report["stage"] == "history-pretraining" else "finetuning_clipping" | |
| checked = candidates[0][key] | |
| if (checked["optimizer_updates"] != updates or checked["clipped_updates"] != runtime["clipped_updates"] | |
| or checked.get("all_encoder_layers_and_history_vectors_receive_positive_gradients") is not True): | |
| raise ValueError("Independent audit gradient counts differ from the legacy stage") | |
| return {"evidence_level": "report optimizer name plus independently bound completed audit", | |
| "runtime_recorded_value": None, | |
| "runtime_class_recording": "not recorded in initial runtime", | |
| "optimizer_name_recorded_in_report": report["optimizer"], | |
| "independent_audit": {"path": str(audit_path.resolve()), "sha256": sha256(audit_path), | |
| "status": "passed", "bound_original_files": hashes, "optimizer_updates": updates}, | |
| "limitation": "The exact Python optimizer class was not recorded in the original runtime; no class value is fabricated."} | |
| def stage_spec(name, path, report, *, run_id, gradients, updates, prefix="", sdk_steps=None, | |
| runtime=None, expected_summary=None, tracking_replayed=False, job_type=None, | |
| legacy_audit_path=None): | |
| runtime = report.get("lightning", report.get("lightning_runtime")) if runtime is None else runtime | |
| if not runtime or runtime["framework"] != "lightning.pytorch" or runtime["trainer"] != "lightning.pytorch.Trainer": | |
| raise ValueError("A campaign stage did not use the actual Lightning Trainer") | |
| if "optimizer_class" not in runtime: | |
| optimizer_binding = legacy_history_optimizer_binding(path, gradients, report, | |
| updates, runtime, legacy_audit_path) | |
| elif runtime["optimizer_class"] != "torch.optim.adamw.AdamW": | |
| raise ValueError("A campaign stage did not use AdamW") | |
| else: | |
| optimizer_binding = {"evidence_level": "recorded in original runtime", | |
| "runtime_recorded_value": runtime["optimizer_class"]} | |
| if runtime["optimizer_updates"] != updates or runtime["trainer_global_step"] != updates: | |
| raise ValueError("Stage Lightning counters differ from the report's update count") | |
| if not isinstance(run_id, str) or not run_id or "/" in run_id: | |
| raise ValueError("Invalid W&B run ID") | |
| return {"name": name, "report_path": Path(path), "run_id": run_id, | |
| "gradients_path": Path(gradients), "updates": updates, "prefix": prefix, | |
| "sdk_steps": list(range(1, updates + 1)) if sdk_steps is None else list(sdk_steps), | |
| "runtime": runtime, "expected_summary": expected_summary or {}, | |
| "tracking_replayed": tracking_replayed, "job_type": job_type, | |
| "optimizer_class_binding": optimizer_binding} | |
| def collect_stages(root): | |
| root = Path(root) | |
| comparison_path, proof_path = root / "comparison.json", root / "lightning-proof" / "proof.json" | |
| comparison, proof = json.loads(comparison_path.read_text()), json.loads(proof_path.read_text()) | |
| predeclared_path = root / "predeclared.json" | |
| if comparison["contract"] != json.loads(predeclared_path.read_text()): | |
| raise ValueError("Completed comparison differs from its predeclared campaign contract") | |
| expected = {(profile, architecture) for profile in ("absolute", "rotary") for architecture in ("separate", "shared")} | |
| if ({(row["profile"], row["architecture"]) for row in comparison["results"]} != expected | |
| or len(comparison["results"]) != 4): | |
| raise ValueError("Position comparison must contain all four distinct configurations") | |
| if proof["status"] != "passed" or set(proof["stages"]) != { | |
| "step_mlm", "epoch_mlm", "account_pretrained", "account_random_init" | |
| }: | |
| raise ValueError("Part 1 Lightning proof is incomplete") | |
| stages, metadata = [], {comparison_path: sha256(comparison_path), proof_path: sha256(proof_path), | |
| predeclared_path: sha256(predeclared_path)} | |
| for row in comparison["results"]: | |
| profile, architecture = row["profile"], row["architecture"] | |
| directory = root / f"{profile}-{architecture}-s17" | |
| for kind in ("pretraining", "finetuning"): | |
| path = directory / ("report.json" if kind == "pretraining" else "finetune/report.json") | |
| report = json.loads(path.read_text()) | |
| if report != row[kind] or report["architecture"] != architecture or report["seed"] != 17: | |
| raise ValueError("Comparison metadata differs from its completed report") | |
| summary = {"optimizer_steps": report["optimizer_steps"], "selected_epoch": report["selected_epoch"]} | |
| if kind == "pretraining": | |
| summary.update({"test/loss": report["test"]["causal"]["loss"], | |
| "test/erased_loss": report["test"]["erased"]["loss"]}) | |
| else: | |
| summary.update({f"test/{key}": value for key, value in report["test"].items() if scalar(value)}) | |
| stages.append(stage_spec(f"{profile}_{architecture}_{kind}", path, report, | |
| run_id=report["wandb_run_id"], gradients=path.parent / "gradients.jsonl", | |
| updates=report["optimizer_steps"], expected_summary=summary, | |
| legacy_audit_path=root / "audit.json")) | |
| for name in ("step_mlm", "epoch_mlm"): | |
| declaration = proof["stages"][name] | |
| path = resolve_path(declaration["report"], root) | |
| report = json.loads(path.read_text()) | |
| if report["wandb"]["mode"] != "online": | |
| raise ValueError("Part 1 stage was not tracked online") | |
| if name == "epoch_mlm" and report["epochs"] != 1: | |
| raise ValueError("This fixed campaign expects one Part 1 smoke epoch") | |
| gradients = path.parent / "metrics.jsonl" | |
| if sha256(gradients) != declaration["gradient_records_sha256"]: | |
| raise ValueError("Smoke gradient file differs from its proof checksum") | |
| if name == "step_mlm": | |
| summary = {"validation/final_loss": report["validation_after"]["loss"], "parameters": report["parameters"]} | |
| else: | |
| summary = {"optimizer_steps": report["steps"], "epochs_completed": report["epochs"], | |
| "validation_final_loss": report["validation_after"]["loss"]} | |
| stages.append(stage_spec(name, path, report, run_id=report["wandb"]["run_id"], | |
| gradients=gradients, updates=report["steps"], expected_summary=summary, | |
| sdk_steps=range(report["steps"]) if name == "epoch_mlm" else None)) | |
| declaration = proof["stages"]["account_pretrained"] | |
| account_path = resolve_path(declaration["report"], root) | |
| account = json.loads(account_path.read_text()) | |
| if account["wandb"]["mode"] != "online": | |
| raise ValueError("Part 1 account run was not tracked online") | |
| sdk_offset = 0 | |
| for tag in ("pretrained", "random_init"): | |
| name = f"account_{tag}" | |
| declaration = proof["stages"][name] | |
| if resolve_path(declaration["report"], root).resolve() != account_path.resolve(): | |
| raise ValueError("Account smoke stages must bind the same combined run report") | |
| measurement = account[tag] | |
| updates = measurement["optimizer_steps"] | |
| if measurement["epochs"] != 1: | |
| raise ValueError("This fixed campaign expects one account smoke epoch") | |
| gradients = account_path.parent / f"{tag}_metrics.jsonl" | |
| if sha256(gradients) != declaration["gradient_records_sha256"]: | |
| raise ValueError("Account gradient file differs from its proof checksum") | |
| summary = {f"{tag}/test/{key}": value for key, value in measurement["test"].items() if scalar(value)} | |
| summary[f"{tag}/selected_epoch"] = measurement["selected_epoch"] | |
| stages.append(stage_spec(name, account_path, measurement, | |
| run_id=account["wandb"]["run_id"], gradients=gradients, updates=updates, | |
| prefix=f"{tag}/", sdk_steps=range(sdk_offset, sdk_offset + updates), expected_summary=summary)) | |
| sdk_offset += updates + measurement["epochs"] # One validation log after each complete epoch. | |
| ids = [stage["run_id"] for stage in stages] | |
| if len(stages) != 12 or len(set(ids)) != 11 or ids[-1] != ids[-2]: | |
| raise ValueError("Campaign must have twelve stages in eleven distinct W&B runs") | |
| replay_path = root / "relative-learning" / "tracking.json" | |
| if replay_path.exists(): | |
| declaration = json.loads(replay_path.read_text()) | |
| if declaration.get("tracking_replayed") is not True or declaration.get("project") != PROJECT: | |
| raise ValueError("Synthetic control tracking must explicitly declare authorized post-hoc replay") | |
| path, gradients = replay_path.parent / "report.json", replay_path.parent / "gradients.jsonl" | |
| if (sha256(path) != declaration.get("report_sha256") or | |
| sha256(gradients) != declaration.get("gradient_records_sha256")): | |
| raise ValueError("Synthetic replay hashes differ from the completed CPU evidence") | |
| report = json.loads(path.read_text()) | |
| if (report["status"] != "completed" or report["device"] != "cpu" or | |
| report["protocol"]["steps"] != 500 or declaration.get("optimizer_steps") != 500): | |
| raise ValueError("Synthetic replay must bind the completed 500-update CPU control") | |
| job_type = "relative-position-control-replay" | |
| if declaration.get("job_type") != job_type: | |
| raise ValueError("Synthetic replay requires its explicit replay job type") | |
| if declaration.get("run_id") in set(ids): | |
| raise ValueError("Synthetic replay must have a distinct tracking run") | |
| stages.append(stage_spec("relative_learning_replay", path, report, | |
| run_id=declaration["run_id"], gradients=gradients, updates=500, | |
| expected_summary={"optimizer_steps": 500}, tracking_replayed=True, job_type=job_type)) | |
| metadata[replay_path] = sha256(replay_path) | |
| for stage in stages: | |
| metadata[stage["report_path"]] = sha256(stage["report_path"]) | |
| metadata[stage["gradients_path"]] = sha256(stage["gradients_path"]) | |
| binding = stage["optimizer_class_binding"] | |
| if "independent_audit" in binding: | |
| metadata[Path(binding["independent_audit"]["path"])] = binding["independent_audit"]["sha256"] | |
| return stages, metadata | |
| def verify_campaign(root, api): | |
| stages, metadata = collect_stages(root) | |
| fetched, verified = {}, [] | |
| for stage in stages: | |
| run_id = stage["run_id"] | |
| if run_id not in fetched: | |
| run = api.run(f"{PROJECT}/{run_id}") | |
| if list(run.path) != [*PROJECT.split("/"), run_id] or run.state != "finished": | |
| raise ValueError("Campaign W&B run must be finished in the authorized project") | |
| # An unfiltered scan is essential: filtering on expected columns | |
| # would silently hide rows with missing columns or extra updates. | |
| fetched[run_id] = run, list(run.scan_history(page_size=10000)) | |
| run, server = fetched[run_id] | |
| if stage["job_type"] is not None and run.job_type != stage["job_type"]: | |
| raise ValueError("Replay W&B job type differs from its explicit logging provenance") | |
| local = [json.loads(line) for line in stage["gradients_path"].read_text().splitlines() if line.strip()] | |
| result = verify_rows(local, server, expected_steps=stage["updates"], | |
| prefix=stage["prefix"], sdk_steps=stage["sdk_steps"]) | |
| if result["clipped_updates"] != stage["runtime"]["clipped_updates"]: | |
| raise ValueError("Runtime clipping count differs from the verified per-update stream") | |
| for key, expected in stage["expected_summary"].items(): | |
| observed = run.summary.get(key) | |
| if not scalar(observed) or not math.isfinite(observed) or not math.isclose(observed, expected, rel_tol=1e-6, abs_tol=1e-8): | |
| raise ValueError(f"Final W&B summary differs from the saved report: {key}") | |
| verified.append({"name": stage["name"], "run_id": run_id, "run_state": run.state, | |
| "run_url": f"https://forge.coreweave.com/wandb/{PROJECT}/runs/{run_id}", | |
| "tracking_replayed": stage["tracking_replayed"], | |
| "optimizer_class_binding": stage["optimizer_class_binding"], | |
| "logging_scope": "post-hoc replay of previously completed CPU updates; no retraining" if | |
| stage["tracking_replayed"] else "original training run", | |
| "report": {"path": str(stage["report_path"].resolve()), "sha256": metadata[stage["report_path"]]}, | |
| "gradients": {"path": str(stage["gradients_path"].resolve()), "sha256": metadata[stage["gradients_path"]]}, | |
| "final_summary_metrics_verified": stage["expected_summary"], **result}) | |
| if any(sha256(path) != digest for path, digest in metadata.items()): | |
| raise ValueError("Local campaign evidence changed during remote verification") | |
| return {"status": "verified", "created_at": datetime.now(UTC).isoformat(), "project": PROJECT, | |
| "training_stages": len(verified), "unique_finished_wandb_runs": len(fetched), | |
| "original_training_stage_streams": sum(not stage["tracking_replayed"] for stage in verified), | |
| "posthoc_replayed_stage_streams": sum(stage["tracking_replayed"] for stage in verified), | |
| "optimizer_updates_verified": sum(stage["optimizer_updates"] for stage in verified), | |
| "scalar_values_verified": sum(stage["scalar_values_verified"] for stage in verified), | |
| "gradient_scalar_values_verified": sum(stage["gradient_scalar_values_verified"] for stage in verified), | |
| "clipped_updates_verified": sum(stage["clipped_updates"] for stage in verified), | |
| "scans_unfiltered": True, "scan_page_size": 10000, "verification_is_read_only": True, | |
| "metadata_sha256": {str(path.resolve()): digest for path, digest in metadata.items()}, "stages": verified} | |
| def main(root, output): | |
| """Verify every campaign update and clipping scalar against finished W&B runs.""" | |
| import wandb | |
| output = root / "tracking-verification.json" if output is None else output | |
| if output.exists(): | |
| raise click.ClickException("Verification output exists; choose a new --output") | |
| report = verify_campaign(root, wandb.Api(timeout=60)) | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| output.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n") | |
| click.echo(json.dumps({key: report[key] for key in ("training_stages", "unique_finished_wandb_runs", | |
| "optimizer_updates_verified", "gradient_scalar_values_verified", "clipped_updates_verified")}, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |