#!/usr/bin/env python """Replay a captured CMFM microbatch and attribute the non-finite gradient. This is a localization tool, not a fix. It answers exactly two questions about a dump written by ``BBFlowModule._dump_cmfm_failure``: 1. which loss component -- ``official``, ``latent``, or ``collective`` -- is the first to produce a non-finite parameter gradient on that microbatch; 2. whether the same component still explodes in fp32, i.e. whether the target is mathematically singular or bf16 merely amplified it. Each component is backpropagated on its own with ``torch.autograd.grad`` so the buffers never mix. Nothing is clipped, skipped, or rescaled. Usage:: python scripts/cmfm_replay_failure.py \ --dump outputs/.../cmfm_failure_dumps/rank1_epoch0_step170_micro3.pt \ --config outputs/ckpt/.../config.yaml \ --precision both """ from __future__ import annotations import argparse import json from pathlib import Path import torch from omegaconf import OmegaConf from bbflow.models.bbflow_module import BBFlowModule COMPONENTS = ("official", "latent", "collective") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--dump", type=Path, required=True, help="Path to the rank*_epoch*_step*_micro*.pt failure dump.", ) parser.add_argument( "--config", type=Path, default=None, help=( "Training config.yaml. Defaults to the config embedded in the dump, " "then to config.yaml next to the run checkpoint directory." ), ) parser.add_argument( "--ckpt", type=Path, default=None, help=( "Optional checkpoint to load instead of the state_dict embedded in " "the dump. The embedded weights are the pre-step weights and are " "what you normally want." ), ) parser.add_argument( "--precision", choices=("bf16", "fp32", "both"), default="both", help="Replay under bf16 autocast, in pure fp32, or both.", ) parser.add_argument("--device", default="cuda") parser.add_argument( "--json-out", type=Path, default=None, help="Optional path for the machine-readable report.", ) return parser.parse_args() def load_config(args: argparse.Namespace, payload: dict) -> OmegaConf: if args.config is not None: return OmegaConf.load(args.config) embedded = payload.get("config") if embedded is not None: return OmegaConf.create(embedded) checkpoint_dir = payload.get("metadata", {}).get("checkpoint_dir", "") candidate = Path(checkpoint_dir) / "config.yaml" if candidate.is_file(): return OmegaConf.load(candidate) raise SystemExit( "No config found: pass --config with the training config.yaml." ) def build_module(cfg, payload: dict, args: argparse.Namespace) -> BBFlowModule: module = BBFlowModule(cfg) if args.ckpt is not None: checkpoint = torch.load(args.ckpt, map_location="cpu", weights_only=False) state_dict = checkpoint.get("state_dict", checkpoint) else: state_dict = payload.get("state_dict") if state_dict is None: raise SystemExit( "The dump carries no state_dict (experiment.training." "cmfm_dump_state_dict was false); pass --ckpt instead." ) missing, unexpected = module.load_state_dict(state_dict, strict=False) if missing or unexpected: print( f"[replay] load_state_dict: {len(missing)} missing, " f"{len(unexpected)} unexpected keys" ) module.to(args.device) # Train mode so dropout/checkpointing match the failing step. Dropout draws # differ from the original step; that changes the sample, not whether a # component's Jacobian is astronomically large. module.train() return module def move_batch(batch: dict, device: str) -> dict: moved = {} for key, value in batch.items(): moved[key] = value.to(device) if torch.is_tensor(value) else value return moved def grad_report(loss: torch.Tensor, parameters, names) -> dict: grads = torch.autograd.grad( loss, parameters, retain_graph=True, allow_unused=True, ) total_square = 0.0 finite_absmax = 0.0 nonfinite = [] for name, grad in zip(names, grads): if grad is None: continue grad = grad.detach().float() finite = torch.isfinite(grad) if not bool(finite.all()): nonfinite.append(name) if bool(finite.any()): selected = grad[finite] total_square += float(selected.square().sum().item()) finite_absmax = max(finite_absmax, float(selected.abs().max().item())) return { "loss": float(loss.detach().float().item()), "grad_norm_finite_part": total_square ** 0.5, "grad_absmax_finite_part": finite_absmax, "nonfinite_parameter_count": len(nonfinite), "nonfinite_parameters": nonfinite[:20], } def replay_once(module: BBFlowModule, batch: dict, use_bf16: bool) -> dict: named = [ (name, param) for name, param in module.named_parameters() if param.requires_grad ] names = [name for name, _ in named] parameters = [param for _, param in named] torch.manual_seed(0) module.zero_grad(set_to_none=True) with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=use_bf16): outputs = module.cmfm_debug_losses(dict(batch)) report = { "precision": "bf16-mixed" if use_bf16 else "fp32", "components": {}, "group_diagnostics": [ { key: ( float(value.detach().float().item()) if torch.is_tensor(value) else value ) for key, value in entry.items() } for entry in outputs["group_diagnostics"] ], "collective_parts": { key: float(value.detach().float().item()) for key, value in outputs["collective_parts"].items() if torch.is_tensor(value) }, } # "official" is a sum of sub-losses with very different numerics, so the # module also exposes them individually as "official:". Attributing a # non-finite backward to "official" alone is not a location. components = list(COMPONENTS) + sorted( key for key in outputs if isinstance(key, str) and key.startswith("official:") ) report["component_order"] = components for component in components: loss = outputs[component] if not torch.is_tensor(loss) or not loss.requires_grad: report["components"][component] = { "loss": float(loss) if not torch.is_tensor(loss) else float(loss.detach().float().item()), "grad_norm_finite_part": 0.0, "grad_absmax_finite_part": 0.0, "nonfinite_parameter_count": 0, "nonfinite_parameters": [], "note": "component does not require grad", } continue report["components"][component] = grad_report(loss, parameters, names) return report def print_report(report: dict) -> None: print(f"\n=== replay precision={report['precision']} ===") components = report.get("component_order", list(COMPONENTS)) header = ( f"{'component':<26}{'loss':>14}{'|grad| norm':>16}" f"{'|grad| max':>14}{'nonfinite params':>19}" ) print(header) print("-" * len(header)) for component in components: entry = report["components"][component] print( f"{component:<26}{entry['loss']:>14.6g}" f"{entry['grad_norm_finite_part']:>16.6g}" f"{entry['grad_absmax_finite_part']:>14.6g}" f"{entry['nonfinite_parameter_count']:>19d}" ) for component in components: entry = report["components"][component] if entry["nonfinite_parameters"]: print(f" {component} first non-finite: {entry['nonfinite_parameters']}") print("\n per-group collective diagnostics:") for entry in report["group_diagnostics"]: print( f" group={entry.get('group')} size={entry.get('size')} " f"obs_var_min={entry.get('observed_target_variance_min'):.6g} " f"cov_scale_min={entry.get('covariance_scale_min'):.6g} " f"1/cov_scale_max={entry.get('covariance_inverse_scale_max'):.6g} " f"target_rate_absmax={entry.get('target_cov_rate_absmax'):.6g} " f"pred_rate_absmax={entry.get('predicted_cov_rate_absmax'):.6g}" ) def main() -> None: args = parse_args() payload = torch.load(args.dump, map_location="cpu", weights_only=False) metadata = payload.get("metadata", {}) batch = payload.get("batch") if batch is None: raise SystemExit( "The dump carries no batch (experiment.training.cmfm_capture_failure " "was false); the failure cannot be replayed." ) print("[replay] captured microbatch") for key in ( "rank", "epoch", "global_step", "microbatch", "precision", "accumulate_grad_batches", "nonfinite_parameter_count", ): if key in metadata: print(f" {key}={metadata[key]}") if metadata.get("pdb_name"): print(f" pdb_name={metadata['pdb_name'][0]}") for key in ("group_index", "trajectory_idx", "conformation_idx", "t"): if key in metadata: print(f" {key}={metadata[key]}") cfg = load_config(args, payload) module = build_module(cfg, payload, args) device_batch = move_batch(batch, args.device) precisions = ( [True, False] if args.precision == "both" else [args.precision == "bf16"] ) reports = [] for use_bf16 in precisions: report = replay_once(module, device_batch, use_bf16) print_report(report) reports.append(report) verdict = [] for report in reports: offenders = [ component for component in report.get("component_order", COMPONENTS) if report["components"][component]["nonfinite_parameter_count"] > 0 ] verdict.append( f"{report['precision']}: " + (", ".join(offenders) if offenders else "no non-finite gradient") ) print("\n=== verdict ===") for line in verdict: print(f" {line}") out_path = args.json_out or args.dump.with_suffix(".replay.json") with out_path.open("w") as handle: json.dump( {"metadata": metadata, "reports": reports, "verdict": verdict}, handle, indent=2, default=str, ) print(f"\n[replay] report written to {out_path}") if __name__ == "__main__": main()