"""Read-only verification of ten original MPS scratch-campaign W&B runs. Every numeric optimizer-update field is checked with the shared strict scanner. SDK counters are taken only from the unfiltered server history. The independent local audit binds masked-input digests even if the API omits string columns. """ from __future__ import annotations import importlib.util import json import math from datetime import UTC, datetime from pathlib import Path import click from omegaconf import OmegaConf SPEC = importlib.util.spec_from_file_location( "scratch_shared_tracking_helpers", Path(__file__).with_name("verify_position_tracking.py") ) H = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(H) PROJECT = H.PROJECT PROFILES = ("absolute", "rotary") ARCHITECTURES = ("separate", "shared") UPDATES = {"scratch_mlm": 200, "history_pretraining": 1790, "history_finetuning": 225} BACKWARDS = {"scratch_mlm": 1600, "history_pretraining": 1790, "history_finetuning": 225} TOTAL_UPDATES = 8460 TOTAL_BACKWARDS = 11260 def read_json(path): return json.loads(Path(path).read_text()) def records(path): return [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()] def require(condition, message): if not condition: raise ValueError(message) def verify_mps_runtime(runtime, *, updates, backwards): """Require recorded original accelerator/class evidence; no legacy fallback.""" expected = { "framework": "lightning.pytorch", "trainer": "lightning.pytorch.Trainer", "optimizer_class": "torch.optim.adamw.AdamW", "precision": "32-true", "optimizer_updates": updates, "trainer_global_step": updates, "backward_calls": backwards, "gradient_clip_max_norm": 1.0, "all_post_clip_norms_within_limit": True, "all_parameters_on_requested_accelerator": True, "accelerator_class": "lightning.pytorch.accelerators.mps.MPSAccelerator", } require(isinstance(runtime, dict), "Original MPS runtime evidence is required") for name, value in expected.items(): require(runtime.get(name) == value, f"Recorded MPS/Lightning runtime differs: {name}") if isinstance(value, bool): require(runtime.get(name) is value, f"Recorded runtime boolean differs: {name}") require( runtime.get("requested_device") in {"mps", "mps:0"} and runtime.get("actual_root_device") in {"mps", "mps:0"}, "Actual and requested neural devices must be MPS", ) require( runtime.get("actual_parameter_devices") == [runtime["actual_root_device"]], "All original model parameters must be on the actual MPS device", ) clipped = runtime.get("clipped_updates") require(H.integer(clipped) and 0 <= clipped <= updates, "Invalid runtime clipping count") for key in ("maximum_pre_clip_global_l2", "maximum_post_clip_global_l2"): require( H.scalar(runtime.get(key)) and math.isfinite(runtime[key]) and runtime[key] > 0, f"Missing finite runtime gradient maximum: {key}", ) require( runtime["maximum_post_clip_global_l2"] <= 1.00001, "Runtime post-clipping norm exceeds the bound of one", ) def verify_update_protocol(local, stage): """Check actual accumulation, full epoch coverage and active layer gradients.""" kind, architecture = stage["kind"], stage.get("architecture") H.local_values(local, stage["updates"]) layer_prefixes = [""] if kind == "scratch_mlm" else ["mlm.bert/"] if architecture == "separate": layer_prefixes.append("history_bert/") positives = [ f"gradients/{prefix}layer_{index}_l2" for prefix in layer_prefixes for index in range(3) ] if kind == "scratch_mlm": positives += ["gradients/embeddings_l2", "gradients/mlm_head_l2"] elif kind == "history_pretraining": positives.append("gradients/transaction_vectors_l2") else: positives += ["gradients/prior_transaction_vectors_l2", "gradients/classifier_l2"] for index, row in enumerate(local): for key in positives: require( H.scalar(row.get(key)) and math.isfinite(row[key]) and row[key] > 0, f"Missing finite positive encoder/history gradient: {key}", ) if kind == "scratch_mlm": epoch = index // 10 + 1 expected = { "epoch": epoch, "train/effective_batch_size": 4096, "train/physical_batch_size": 512, "train/micro_batch_size": 512, "train/gradient_accumulation_steps": 8, "train/backward_calls": 8, "train/physical_batches": 8, "train/partial_accumulation_group": 0, "train/learning_rate": 1e-4, "train/windows_seen": (index + 1) * 4096, } for key, value in expected.items(): require(row.get(key) == value, f"Scratch accumulation/order differs: {key}") require( H.integer(row.get("train/masked_tokens")) and row["train/masked_tokens"] > 0, "Scratch masked-target count must be a positive integer", ) digest = row.get("train/masked_batch_sha256") require( isinstance(digest, str) and len(digest) == 64 and all(character in "0123456789abcdef" for character in digest), "Every scratch update requires its independently audited mask SHA256", ) else: per_epoch = 179 if kind == "history_pretraining" else 15 require( row.get("epoch") == index // per_epoch + 1, "History gradient epochs differ from complete matched coverage", ) if kind == "history_finetuning": require( row.get("accounts") == 16, "Dropped-tail fine-tuning requires full 16-account batches", ) runtime = stage["runtime"] for local_key, runtime_key in ( ("gradients/pre_clip_global_l2", "maximum_pre_clip_global_l2"), ("gradients/post_clip_global_l2", "maximum_post_clip_global_l2"), ): require( math.isclose( max(row[local_key] for row in local), runtime[runtime_key], rel_tol=1e-6, abs_tol=1e-8, ), "Recorded runtime gradient maxima differ from the complete local stream", ) def _bound_path(path, expected): path = Path(path) require( path.resolve() == expected.resolve(), "Scratch stage path points outside its declared profile", ) return expected def collect_stages(root): root = Path(root).resolve() declaration_path, comparison_path, audit_path = ( root / "predeclared.json", root / "comparison.json", root / "audit.json", ) contract, comparison, audit = map(read_json, (declaration_path, comparison_path, audit_path)) require( comparison.get("status") == "completed", "Scratch campaign must finish before verification" ) require( comparison["contract"] == contract, "Scratch comparison differs from its predeclared contract", ) require( audit.get("status") == "passed" and audit.get("comparison_contract") == contract and audit.get("optimizer_updates") == TOTAL_UPDATES and audit.get("backward_calls") == TOTAL_BACKWARDS, "Complete unchanged independent scratch audit is required", ) for key, value in { "seed": 17, "device": "mps", "mps_cpu_fallback": False, "scratch_epochs": 20, "physical_batch_size": 512, "gradient_accumulation_steps": 8, "effective_batch_size": 4096, "learning_rate": 1e-4, "weight_decay": 0.01, "history_epochs": 10, "classification_epochs": 15, "attention_backend": "eager for both", }.items(): require(contract.get(key) == value, f"Scratch declaration differs: {key}") if isinstance(value, bool): require(contract.get(key) is value, f"Scratch declaration boolean differs: {key}") expected_pairs = { (profile, architecture) for profile in PROFILES for architecture in ARCHITECTURES } require( set(comparison["pretraining"]) == set(PROFILES), "Both scratch MLM profiles are required" ) require( len(comparison["results"]) == 4 and {(row["profile"], row["architecture"]) for row in comparison["results"]} == expected_pairs, "Exactly four distinct history configurations are required", ) metadata = {Path(path).resolve(): digest for path, digest in audit["all_file_sha256"].items()} require(metadata, "Independent scratch audit must bind original files") for path in (declaration_path, comparison_path): require( metadata.get(path) == H.sha256(path), "Audit does not bind unchanged campaign metadata" ) for path, digest in metadata.items(): require(H.sha256(path) == digest, f"Independently audited local evidence changed: {path}") metadata[audit_path] = H.sha256(audit_path) stages = [] def append( kind, profile, path, report, *, run_id, summary, config_path, architecture=None, sdk_steps=None, job_types=None, ): updates, backwards = UPDATES[kind], BACKWARDS[kind] runtime = report.get("lightning", report.get("lightning_runtime")) verify_mps_runtime(runtime, updates=updates, backwards=backwards) gradients = path.parent / ("metrics.jsonl" if kind == "scratch_mlm" else "gradients.jsonl") for value in (path, gradients, config_path): require( metadata.get(value.resolve()) == H.sha256(value), f"Audit does not bind unchanged stage evidence: {value}", ) stage = H.stage_spec( f"{profile}_{architecture or 'scratch'}_{kind}", path, report, run_id=run_id, gradients=gradients, updates=updates, runtime=runtime, expected_summary=summary, sdk_steps=sdk_steps, ) stage.update( { "kind": kind, "profile": profile, "architecture": architecture, "backwards": backwards, "job_types": set(job_types), "config": OmegaConf.to_container(OmegaConf.load(config_path), resolve=True), } ) if kind == "scratch_mlm": require( stage["config"].get("training", {}).get("drop_last") is True, "Scratch resolved configuration must declare drop_last", ) elif kind == "history_finetuning": require( stage["config"].get("history", {}).get("classification_drop_last") is True, "Fine-tuning resolved configuration must declare classification_drop_last", ) verify_update_protocol(records(gradients), stage) stages.append(stage) for profile in PROFILES: directory = root / "pretraining" / profile declaration = comparison["pretraining"][profile] path = _bound_path(declaration["report_path"], directory / "training/report.json") evaluation_path = _bound_path( declaration["test_report_path"], directory / "training/evaluation.json" ) require( metadata.get(evaluation_path) == H.sha256(evaluation_path), "Audit does not bind unchanged scratch MLM evaluation", ) report, evaluation = read_json(path), read_json(evaluation_path) for key, expected in { "initialization": "random", "epochs": 20, "requested_epochs": 20, "seed": 17, "optimizer": "AdamW", "learning_rate": 1e-4, "weight_decay": 0.01, "steps": 200, "batch_size": 512, "physical_batch_size": 512, "micro_batch_size": 512, "gradient_accumulation_steps": 8, "effective_batch_size": 4096, "physical_batches_seen": 1600, "forward_backward_calls": 1600, "windows_seen": 819200, "device": "mps", "drop_last": True, "available_windows_per_epoch": 41013, "used_windows_per_epoch": 40960, "omitted_windows_per_epoch": 53, "omitted_window_exposures": 1060, }.items(): require(report.get(key) == expected, f"Scratch completed report differs: {key}") require( report["wandb"].get("mode") == "online", "Scratch MLM must have original online tracking", ) require( report.get("all_epochs_complete_no_dropped_windows") is False, "Scratch report must explicitly acknowledge deliberately dropped windows", ) require( report.get("all_epochs_complete_under_drop_last_policy") is True, "Scratch training must complete every declared retained batch", ) summary = { "optimizer_steps": 200, "epochs_completed": 20, "windows_seen": 819200, "validation_final_loss": report["validation_after"]["loss"], "parameter_delta_l2": report["parameter_delta_l2"], "all_epochs_complete_no_dropped_windows": False, "all_epochs_complete_under_drop_last_policy": True, "checkpoint_reload_identical_logits": True, **{ key: report[key] for key in ( "drop_last", "physical_batch_size", "gradient_accumulation_steps", "effective_batch_size", "used_windows_per_epoch", "omitted_windows_per_epoch", "omitted_window_exposures", "forward_backward_calls", ) }, "test_checkpoint_sha256": evaluation["checkpoint_sha256"], **{ f"test/{key}": evaluation[key] for key in ("loss", "masked_accuracy", "masked_tokens", "windows") }, } append( "scratch_mlm", profile, path, report, run_id=report["wandb"]["run_id"], summary=summary, config_path=path.parent / "resolved_config.yaml", sdk_steps=[index + index // 10 for index in range(200)], job_types={"masked-language-model-pretraining", "heldout-evaluation"}, ) for item in comparison["results"]: profile, architecture = item["profile"], item["architecture"] directory = root / f"{profile}-{architecture}-s17" for kind, suffix, stage_label in ( ("history_pretraining", Path("report.json"), "history-pretraining"), ("history_finetuning", Path("finetune/report.json"), "history-account-finetuning"), ): path = directory / suffix report = read_json(path) embedded = item["pretraining" if kind == "history_pretraining" else "finetuning"] require( report == embedded and report.get("architecture") == architecture and report.get("seed") == 17 and report.get("stage") == stage_label, "History comparison differs from the original completed report", ) require( report.get("epochs") == (10 if kind == "history_pretraining" else 15) and report.get("optimizer_steps") == UPDATES[kind], "History completed training budget differs", ) summary = {"optimizer_steps": UPDATES[kind], "selected_epoch": report["selected_epoch"]} if kind == "history_pretraining": summary.update( { "test/loss": report["test"]["causal"]["loss"], "test/erased_loss": report["test"]["erased"]["loss"], } ) else: require( report.get("classification_drop_last") is True and report.get("classification_batch_size") == 16, "Fine-tuning report must declare its full-batch drop policy", ) coverage = report.get("training_account_coverage", {}) require( all( coverage.get(key) == value for key, value in { "available_accounts": 251, "accounts_used_per_epoch": 240, "accounts_omitted_per_epoch": 11, "total_account_exposures": 3600, "total_omitted_account_exposures": 165, }.items() ), "Fine-tuning account exposure/omission budget differs", ) summary.update( { f"test/{key}": value for key, value in report["test"].items() if H.scalar(value) } ) append( kind, profile, path, report, run_id=report["wandb_run_id"], summary=summary, config_path=directory / "resolved_config.yaml", architecture=architecture, job_types={stage_label}, ) require( len(stages) == 10 and len({stage["run_id"] for stage in stages}) == 10, "Ten distinct original W&B runs are required; combined/replayed streams are not accepted", ) return stages, metadata def _match(expected, observed): if isinstance(expected, dict): return isinstance(observed, dict) and all( key in observed and _match(value, observed[key]) for key, value in expected.items() ) if isinstance(expected, list): return ( isinstance(observed, list) and len(expected) == len(observed) and all(_match(left, right) for left, right in zip(expected, observed, strict=True)) ) if isinstance(expected, bool): return observed is expected if H.scalar(expected): return ( H.scalar(observed) and math.isfinite(observed) and math.isclose(expected, observed, rel_tol=1e-6, abs_tol=1e-8) ) return expected == observed def verify_optional_strings(local, server, sdk_steps): """Compare logged strings when exposed; report omissions without inventing data.""" indexed = H.scanned_values(server) checked = missing = 0 for row, sdk in zip(local, sdk_steps, strict=True): for key, expected in row.items(): if not isinstance(expected, str): continue observed = indexed[sdk].get(key) if observed is None: missing += 1 continue require( isinstance(observed, str) and observed == expected, f"Remote string differs from original audited input at SDK {sdk}: {key}", ) checked += 1 return { "remote_string_fields_verified": checked, "remote_string_fields_unavailable": missing, "string_evidence_scope": "Available server strings checked exactly; missing strings remain bound by independent local audit, not reconstructed", } def verify_campaign(root, api): stages, metadata = collect_stages(root) verified = [] for stage in stages: run_id = stage["run_id"] run = api.run(f"{PROJECT}/{run_id}") require( list(run.path) == [*PROJECT.split("/"), run_id] and run.state == "finished", "Original W&B run must be finished in the authorized project", ) require( run.job_type in stage["job_types"], "Original training/evaluation job type required; replay is not accepted", ) require( _match(stage["config"], dict(run.config)), "Remote resolved training configuration differs", ) server = list(run.scan_history(page_size=10000)) local = records(stage["gradients_path"]) result = H.verify_rows( local, server, expected_steps=stage["updates"], sdk_steps=stage["sdk_steps"] ) require( result["clipped_updates"] == stage["runtime"]["clipped_updates"], "Original runtime clipping count differs from all verified updates", ) for key, expected in stage["expected_summary"].items(): require(_match(expected, run.summary.get(key)), f"Final W&B summary differs: {key}") strings = verify_optional_strings(local, server, stage["sdk_steps"]) verified.append( { "name": stage["name"], "profile": stage["profile"], "architecture": stage["architecture"], "kind": stage["kind"], "run_id": run_id, "run_state": run.state, "job_type": run.job_type, "run_url": f"https://forge.coreweave.com/wandb/{PROJECT}/runs/{run_id}", "tracking_replayed": False, "logging_scope": "original online training run; no replay", "mps_runtime": stage["runtime"], "backward_calls": stage["backwards"], "report": { "path": str(stage["report_path"]), "sha256": metadata[stage["report_path"]], }, "gradients": { "path": str(stage["gradients_path"]), "sha256": metadata[stage["gradients_path"]], }, "resolved_remote_config_verified": True, "final_summary_metrics_verified": stage["expected_summary"], **result, **strings, } ) require( sum(stage["optimizer_updates"] for stage in verified) == TOTAL_UPDATES and sum(stage["backward_calls"] for stage in verified) == TOTAL_BACKWARDS, "Verified complete campaign optimizer/backward totals differ", ) for path, digest in metadata.items(): require( H.sha256(path) == digest, f"Local scratch evidence changed during remote verification: {path}", ) return { "status": "verified", "created_at": datetime.now(UTC).isoformat(), "project": PROJECT, "training_stages": 10, "unique_finished_wandb_runs": 10, "original_training_stage_streams": 10, "posthoc_replayed_stage_streams": 0, "optimizer_updates_verified": TOTAL_UPDATES, "backward_calls_verified": TOTAL_BACKWARDS, "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), "remote_string_fields_verified": sum( stage["remote_string_fields_verified"] for stage in verified ), "remote_string_fields_unavailable": sum( stage["remote_string_fields_unavailable"] for stage in verified ), "all_original_runs_mps_and_float32": True, "all_original_runs_adamw": True, "scans_unfiltered": True, "scan_page_size": 10000, "verification_is_read_only": True, "metadata_sha256": {str(path): digest for path, digest in metadata.items()}, "stages": verified, } @click.command() @click.option( "--root", type=click.Path(path_type=Path, exists=True, file_okay=False), default=Path("artifacts/positions-scratch-20ep"), show_default=True, ) @click.option("--output", type=click.Path(path_type=Path, dir_okay=False), default=None) def main(root, output): """Verify all original scratch, history and fine-tuning W&B update streams.""" import wandb output = root / "tracking-verification.json" if output is None else output if output.exists(): raise click.ClickException("Verification output exists; choose a fresh --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", "backward_calls_verified", "gradient_scalar_values_verified", "clipped_updates_verified", ) }, indent=2, ) ) if __name__ == "__main__": main()