"""Validated full-state recovery for the fixed 300-session experiment.""" from __future__ import annotations import hashlib import json from pathlib import Path import re import socket import zipfile PROJECT = Path(__file__).resolve().parents[1] CODE_PATHS = ( "scripts/train_third_party.py", "scripts/train.py", "scripts/third_party_temp.py", "src/psi/config/train/posttrain_third_party_config.py", "src/psi/trainers/posttrain_third_party.py", "src/psi/trainers/posttrain_full_duplex.py", "src/psi/data/seed/third_party_frozen_dataset.py", "src/psi/data/seed/qwen_streaming_audio.py", "src/psi/models/full_duplex_psi0.py", "scripts/infer/third_party_checkpoint_probe.py", "scripts/infer/full_duplex_audio_to_motion.py", "scripts/third_party_resume.py", ) # Narrow migration from the audited c789791 implementation. Only resume config, # entry, trainer lifecycle and sampler-offset support change; all other model, # loss, data and optimizer-loop fingerprints must match exactly. RESUME_MIGRATION_SHA256 = { "scripts/train_third_party.py": "8b84bef7c783c4bc30cf0b2adac1fd5ea149d70254914a51e885e1c94a22c5c5", "src/psi/config/train/posttrain_third_party_config.py": "5b346830759a089e969e8ac631aa74e3065c1c75c7a4384296347b8d3485025a", "src/psi/trainers/posttrain_third_party.py": "45d6029bf11d6ef7bdc3501a0a13b57c5a1e486c987b2dced44617e27aaa7dba", "src/psi/trainers/posttrain_full_duplex.py": "d3206e69d49c55e4d5dca69ca252a1fa93f903b6df436e296d157d46d1728d59", } def sha256(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def code_identity(): return {name: sha256(PROJECT / name) for name in CODE_PATHS} def validate_code_identity(recorded): required = set(CODE_PATHS) if set(recorded) not in (required, required - {"scripts/third_party_resume.py"}): raise ValueError("Checkpoint run has an incomplete or unknown code identity") active = code_identity() migration = {} for name, saved in recorded.items(): if saved == active[name]: continue if RESUME_MIGRATION_SHA256.get(name) != saved: raise ValueError(f"Unreviewed implementation change since checkpoint: {name}") migration[name] = {"saved": saved, "active": active[name]} return migration def frozen_resume_cursor(sampler, step: int, steps_per_epoch: int, epochs: int): """Reconstruct a boundary using the original deterministic full-epoch order.""" if sampler.world_size != 1 or sampler.optimizer_accumulation_groups != 1: raise ValueError("Frozen resume supports one GPU and one source accumulation group") if not 0 <= step < steps_per_epoch * epochs: raise ValueError("Resume step is outside the unfinished training budget") target_epoch, offset = divmod(step, steps_per_epoch) for epoch in range(epochs): ordered = sampler._ordered_indices(epoch) lengths = [max(sampler.lengths[i] for i in ordered[j:j + sampler.group_size]) for j in range(0, len(ordered), sampler.group_size)] if sum(lengths) != steps_per_epoch: raise ValueError("Frozen epoch budget differs from the checkpoint schedule") if epoch != target_epoch: continue accumulated = 0 groups = 0 while accumulated < offset and groups < len(lengths): accumulated += lengths[groups] groups += 1 if accumulated != offset: raise ValueError("Checkpoint step is inside a source group, not a complete boundary") consumed = groups * sampler.group_size cursor = {"epoch": epoch, "global_step": step, "completed_source_batches_in_epoch": groups, "consumed_sources_in_epoch": consumed, "remaining_sources_in_epoch": len(ordered) - consumed, "next_source_indices": ordered[consumed:consumed + sampler.group_size], "steps_per_epoch": steps_per_epoch} return cursor def assert_source_run_stopped(run): status = json.loads((run / "run_status.json").read_text()) if status["host"] != socket.gethostname(): raise ValueError("Source run is on another host; its process state must be reviewed first") for key in ("launcher_pid", "training_pid"): pid = status.get(key) if not pid: continue directory = Path("/proc") / str(pid) try: fields = (directory / "stat").read_text().rsplit(")", 1)[1].split() args = (directory / "cmdline").read_bytes().split(b"\0") except (FileNotFoundError, ProcessLookupError): continue if fields[0] == "Z": continue if ((key == "launcher_pid" and int(fields[19]) == status["launcher_start_ticks"]) or str(run).encode() in args or str(run / "launch_spec.json").encode() in args): raise ValueError(f"Source run still has a live {key}; refusing concurrent recovery") def prepare_resume(config, checkpoint, *, manifest, run_dir): """Read-only preflight, performed both before GPU handoff and in the worker.""" from psi.config.train.posttrain_third_party_config import DynamicLaunchConfig from psi.trainers.posttrain_third_party import PosttrainThirdPartyTrainer from psi.trainers.posttrain_full_duplex import SourceLengthGroupedSampler from safetensors import safe_open import torch checkpoint = Path(checkpoint).resolve() if (not checkpoint.is_relative_to(PROJECT / "runs") or checkpoint.parent.name != "checkpoints" or not re.fullmatch(r"ckpt_[0-9]+", checkpoint.name)): raise ValueError("Use an explicit checkpoint directory under HFD_lzk/runs") source_run = checkpoint.parent.parent if run_dir == source_run or run_dir.is_relative_to(source_run) or source_run.is_relative_to(run_dir): raise ValueError("Resume output must be a separate new run, preserving the source experiment") assert_source_run_stopped(source_run) step = int(checkpoint.name.removeprefix("ckpt_")) saved = DynamicLaunchConfig.model_validate_json((source_run / "run_config.json").read_text()) if saved.train.experiment_phase != "train" or config.train.experiment_phase != "train": raise ValueError("Resume requires a formal training checkpoint, not a smoke checkpoint") input_identity = json.loads((source_run / "input_identity.json").read_text()) if input_identity["manifest_sha256"] != sha256(manifest): raise ValueError("Frozen selection changed since the source training run") migrations = validate_code_identity(json.loads((source_run / "code_identity.json").read_text())) for field in ("max_training_steps", "checkpointing_steps", "warmup_steps"): setattr(config.train, field, getattr(saved.train, field)) # Compare the full typed config, allowing only output naming and recovery # provenance. This prevents silent changes to LR, trainable layers or losses. def comparable(cfg): value = cfg.model_dump(mode="json") value.pop("timestamp", None) for name in ("output_dir", "resume_from_checkpoint", "resume_load_full_state", "resume_checkpoint_step"): value["train"].pop(name, None) return value if comparable(config) != comparable(saved): raise ValueError("Active model/data/training configuration differs from the source experiment") if config.train.dense_window_accumulation_steps != 1: raise ValueError("Resume currently requires one dense window per optimizer update") selection = json.loads(Path(manifest).read_text()) rows = selection["sessions"] if [r["session_id"] for r in rows] != selection["session_ids"]: raise ValueError("Selection index order differs from its frozen session records") class Lengths: def __len__(self): return len(rows) def estimated_stream_steps(self, index): return int(rows[index]["dense_steps"]) sampler = SourceLengthGroupedSampler(Lengths(), world_size=1, batch_size=config.train.train_batch_size, seed=config.seed) ordered = sampler._ordered_indices(0) steps_per_epoch = sum(max(sampler.lengths[i] for i in ordered[j:j + sampler.group_size]) for j in range(0, len(rows), sampler.group_size)) if config.train.max_training_steps != steps_per_epoch * config.train.coverage_epochs: raise ValueError("Saved scheduler budget does not match the frozen epoch geometry") cursor = frozen_resume_cursor(sampler, step, steps_per_epoch, config.train.coverage_epochs) cursor["next_session_ids"] = [rows[i]["session_id"] for i in cursor["next_source_indices"]] delta = json.loads((checkpoint / "hfd_fused_delta_manifest.json").read_text()) boundary = json.loads((checkpoint / "full_duplex_source_boundary.json").read_text()) trainer = object.__new__(PosttrainThirdPartyTrainer) trainer.cfg = config contract = trainer._hfdv2_checkpoint_contract() if (delta.get("format") != "hfd_qwen_serial_delta_v1" or delta.get("contract") != contract or boundary.get("train_infer_contract") != contract or boundary.get("global_step") != step or not boundary.get("source_group_complete") or boundary.get("boundary_reason") != "natural_source_end"): raise ValueError("Checkpoint contract or complete-source boundary validation failed") with safe_open(str(checkpoint / "model.safetensors"), framework="pt", device="cpu") as handle: if len(list(handle.keys())) != delta["tensor_count"]: raise ValueError("Checkpoint tensor count differs from its saved manifest") names = ("model.safetensors", "optimizer.bin", "scheduler.bin", "random_states_0.pkl", "custom_checkpoint_0.pkl", "hfd_fused_delta_manifest.json", "full_duplex_source_boundary.json") files = {} for name in names: path = checkpoint / name stat = path.stat() if stat.st_size <= 0: raise ValueError(f"Empty checkpoint file: {name}") if name.endswith((".bin", ".pkl")): with zipfile.ZipFile(path) as archive: if not archive.infolist(): raise ValueError(f"Empty state archive: {name}") files[name] = {"size": stat.st_size, "mtime_ns": stat.st_mtime_ns} scheduler = torch.load(checkpoint / "scheduler.bin", map_location="cpu", weights_only=True) if scheduler["last_epoch"] != step: raise ValueError("Saved scheduler step differs from the checkpoint step") values = config.model_dump() values["train"].update(resume_from_checkpoint=str(checkpoint), resume_load_full_state=True, resume_checkpoint_step=step) config = DynamicLaunchConfig.model_validate(values) record = {"source_run": str(source_run), "checkpoint": str(checkpoint), "step": step, "max_steps": config.train.max_training_steps, "remaining_steps": config.train.max_training_steps - step, "manifest_sha256": sha256(manifest), "checkpoint_files": files, "checkpoint_manifest_sha256": sha256(checkpoint / "hfd_fused_delta_manifest.json"), "source_run_config_sha256": sha256(source_run / "run_config.json"), "source_code_migration": migrations, "source_cursor": cursor, "saved_scheduler_last_epoch": scheduler["last_epoch"], "saved_learning_rates": scheduler["_last_lr"], "rng_policy": "model_and_flow_rng_restored; worker_rng_not_bitwise_restored; frozen_inputs_deterministic"} return config, record