File size: 25,713 Bytes
0edf333 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 | """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()
|