"""Run the matched 20-epoch scratch position comparison sequentially on this Mac.""" import os # This campaign explicitly forbids neural CPU fallback before torch is imported. os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "0" import json from pathlib import Path import platform import time import click from omegaconf import OmegaConf import torch from evm_bert.config import load_config from evm_bert.history_train import ( file_sha256, finetune_history, release_device_cache, train_history, validate_completed_history, write_json, ) from evm_bert.model import load_mlm_model from evm_bert.train import evaluate_mlm, train_mlm_epochs ROPE = {"rotary_dim": 8, "local_layers": 2, "local_base": 10000, "scaled_base": 160000, "original_context": 512, "factor": 4., "beta_fast": 32., "beta_slow": 1.} SOURCE_FILES = ( "data/transactions/manifest.json", "data/transactions/transactions.jsonl", "data/kaggle/history-transactions/audit.json", "data/kaggle/history-transactions/transactions.jsonl", "artifacts/tokenizer/tokenizer.json", "artifacts/tokenizer/byte_encoding.json", "artifacts/pretrained-20ep/model/model.safetensors", "artifacts/pretrained-20ep/model/config.json", ) def pretraining_config(base, root, profile): cfg = OmegaConf.create(OmegaConf.to_container(base, resolve=True)) cfg.model.output_dir = str(root / "pretraining" / profile / "model") cfg.model.position_encoding = "deepseek_rotary" if profile == "rotary" else "absolute" cfg.model.max_position_embeddings = 2048 if profile == "rotary" else 512 if profile == "rotary": cfg.model.rope = ROPE cfg.training.output_dir = str(root / "pretraining" / profile / "training") cfg.training.resume_from = None cfg.logging.wandb_dir = str(root / "wandb") return cfg def validate_pretraining(cfg, report): expected = {"initialization": "random", "epochs": 20, "requested_epochs": 20, "optimizer": "AdamW", "learning_rate": 1e-4, "batch_size": 512, "micro_batch_size": 512, "gradient_accumulation_steps": 8, "effective_batch_size": 4096, "steps": 200, "forward_backward_calls": 1600, "windows_seen": 819200, "device": "mps", "drop_last": True, "all_epochs_complete_no_dropped_windows": False, "all_epochs_complete_under_drop_last_policy": True, "omitted_window_exposures": 1060} if any(report.get(key) != value for key, value in expected.items()): raise ValueError("Completed scratch pretraining differs from the requested experiment") model_dir = Path(cfg.model.output_dir) for name, digest in report["artifact_sha256"].items(): if file_sha256(model_dir / name) != digest: raise ValueError(f"Measured scratch artifact changed: {name}") saved = OmegaConf.load(Path(cfg.training.output_dir) / "resolved_config.yaml") requested = OmegaConf.to_container(cfg, resolve=True) actual = OmegaConf.to_container(saved, resolve=True) requested["training"].pop("resume_from", None) actual["training"].pop("resume_from", None) if actual != requested: raise ValueError("Completed scratch configuration changed") @click.command() @click.option("--output", default="artifacts/positions-scratch-20ep") def main(output): if not torch.backends.mps.is_built() or not torch.backends.mps.is_available(): raise click.ClickException("MPS is required on this Mac; CPU fallback is disabled") root = Path(output) root.mkdir(parents=True, exist_ok=True) base = load_config("configs/scratch-positions.yaml") expected = {"training.epochs": 20, "training.batch_size": 512, "training.micro_batch_size": 512, "training.gradient_accumulation_steps": 8, "training.drop_last": True, "training.learning_rate": 1e-4, "training.device": "mps", "history.epochs": 10, "history.classification_epochs": 15, "history.classification_drop_last": True, "history.classification_batch_size": 16, "history.device": "mps", "model.attn_implementation": "eager", "model.paired_random_initialization": True} if any(OmegaConf.select(base, key) != value for key, value in expected.items()): raise click.ClickException("Campaign configuration differs from the declared matched budget") contract = {"format_version": 1, "base_config": OmegaConf.to_container(base, resolve=True), "profiles": ["rotary", "absolute"], "architectures": ["separate", "shared"], "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": .01, "history_epochs": 10, "classification_epochs": 15, "rope": ROPE, "drop_last": True, "classification_drop_last": True, "initialization": "paired fresh random common weights; no trained checkpoint", "attention_backend": "eager for both", "test_policy": "fixed splits/masks; validation-only downstream selection", "source_sha256": {path: file_sha256(path) for path in SOURCE_FILES}} declared = root / "predeclared.json" if declared.exists() and json.loads(declared.read_text()) != contract: raise click.ClickException("Existing scratch experiment contract differs; use a new output") write_json(declared, contract) comparison = {"contract": contract, "pretraining": {}, "results": [], "host": {"system": platform.system(), "machine": platform.machine(), "mps_built": True, "mps_available": True, "cpu_fallback": False}} started = time.monotonic() def save(): comparison["elapsed_seconds_current_invocation"] = time.monotonic() - started write_json(root / "comparison.json", comparison) for profile in contract["profiles"]: cfg = pretraining_config(base, root, profile) directory = Path(cfg.training.output_dir) directory.parent.mkdir(parents=True, exist_ok=True) OmegaConf.save(cfg, directory.parent / "config.yaml") report_path = directory / "report.json" if not report_path.exists(): checkpoints = sorted((directory / "checkpoints").glob("epoch-*.pt")) if checkpoints: cfg.training.resume_from = str(checkpoints[-1]) click.echo(json.dumps({"stage": "scratch-pretraining", "profile": profile, "device": "mps", "epochs": 20, "batch": 512, "accumulation": 8, "drop_last": True}), err=True) train_mlm_epochs(cfg) report = json.loads(report_path.read_text()) validate_pretraining(cfg, report) evaluation_path = directory / "evaluation.json" if not evaluation_path.exists(): evaluate_mlm(cfg) if json.loads(evaluation_path.read_text())["checkpoint_sha256"] != file_sha256(Path(cfg.model.output_dir) / "model.safetensors"): raise ValueError("MLM test evaluation belongs to a different checkpoint") model = load_mlm_model(cfg.model.output_dir).eval() if (model.config.evm_initialization["kind"] != "paired random common weights; no trained checkpoint" or model.config.evm_attention_backend != "eager"): raise ValueError("Scratch initialization/backend provenance changed") del model comparison["pretraining"][profile] = {"report_path": str(report_path), "model_path": str(cfg.model.output_dir), "test_report_path": str(evaluation_path)} save() release_device_cache("mps", force=True) for profile in contract["profiles"]: for architecture in contract["architectures"]: cfg = OmegaConf.create(contract["base_config"]) cfg.history.pretrained_model_dir = comparison["pretraining"][profile]["model_path"] cfg.history.output_dir = str(root / f"{profile}-{architecture}-s17") cfg.history.architecture = architecture cfg.logging.wandb_dir = str(root / "wandb") directory = Path(cfg.history.output_dir) report_path, fine_path = directory / "report.json", directory / "finetune" / "report.json" if not report_path.exists(): if (directory / "resume.pt").exists(): cfg.history.resume_from = str(directory / "resume.pt") train_history(cfg) else: validate_completed_history(cfg, report_path) if not fine_path.exists(): finetune_history(cfg) else: validate_completed_history(cfg, fine_path, classification=True) comparison["results"].append({"profile": profile, "architecture": architecture, "pretraining": json.loads(report_path.read_text()), "finetuning": json.loads(fine_path.read_text())}) save() release_device_cache("mps", force=True) if any(file_sha256(path) != digest for path, digest in contract["source_sha256"].items()): raise RuntimeError("An original input or old model changed during the campaign") comparison["status"] = "completed" save() click.echo(json.dumps({"status": "completed", "device": "mps", "results": len(comparison["results"])})) if __name__ == "__main__": main()