Download bbflow_base/scripts/check_latent_smoke.py from hanghang214/data_transfer: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/check_latent_smoke.py
- Command line
-
hf download hf://datasets/hanghang214/data_transfer/bbflow_base/scripts/check_latent_smoke.py
-
curl -L -o check_latent_smoke.py https://huggingface.co/datasets/hanghang214/data_transfer/resolve/main/bbflow_base/scripts/check_latent_smoke.py
14.1 kB
| import argparse | |
| import json | |
| from pathlib import Path | |
| import pandas as pd | |
| import torch | |
| from hydra import compose, initialize_config_dir | |
| from omegaconf import OmegaConf | |
| from bbflow.data.pdb_dataloader_bbflow import PdbDataModuleBBFlow | |
| from bbflow.models.bbflow_module import BBFlowModule | |
| def grad_norm(parameters): | |
| total = 0.0 | |
| count = 0 | |
| for param in parameters: | |
| if param is None or param.grad is None: | |
| continue | |
| value = param.grad.detach().float().norm().cpu().item() | |
| total += value * value | |
| count += 1 | |
| return total ** 0.5, count | |
| def move_to_device(batch, device): | |
| return {key: value.to(device) if torch.is_tensor(value) else value for key, value in batch.items()} | |
| def load_model_warm_start(module, ckpt_path): | |
| if ckpt_path is None: | |
| return {"loaded": 0, "skipped": 0, "ckpt_path": None, "skipped_keys": []} | |
| ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=True) | |
| state_dict = ckpt["state_dict"] | |
| model_state = {k.replace("model.", ""): v for k, v in state_dict.items() if k.startswith("model.")} | |
| current_state = module.model.state_dict() | |
| compatible_state = {} | |
| skipped = [] | |
| for key, value in model_state.items(): | |
| if key in current_state and current_state[key].shape == value.shape: | |
| compatible_state[key] = value | |
| elif key in current_state: | |
| skipped.append({"key": key, "ckpt_shape": list(value.shape), "model_shape": list(current_state[key].shape)}) | |
| module.model.load_state_dict(compatible_state, strict=False) | |
| return { | |
| "loaded": len(compatible_state), | |
| "skipped": len(skipped), | |
| "ckpt_path": str(ckpt_path), | |
| "skipped_keys": skipped[:20], | |
| } | |
| def autocast_context(cfg, device): | |
| precision = str(getattr(cfg.experiment.trainer, "precision", "32-true")) | |
| if device.type == "cuda" and precision == "bf16-mixed": | |
| return torch.autocast(device_type="cuda", dtype=torch.bfloat16) | |
| if device.type == "cuda" and precision == "16-mixed": | |
| return torch.autocast(device_type="cuda", dtype=torch.float16) | |
| return torch.autocast(device_type="cpu", enabled=False) | |
| def fp32_context(device): | |
| return torch.autocast(device_type=device.type, enabled=False) | |
| def summarize_batch(batch): | |
| names = [str(name) for name in batch["pdb_name"]] | |
| return [ | |
| { | |
| "sample": idx, | |
| "pdb_name": name, | |
| "num_res": int(batch["res_mask"][idx].sum().item()), | |
| } | |
| for idx, name in enumerate(names) | |
| ] | |
| def injection_parameters(model): | |
| params = [] | |
| if getattr(model.embedder, "z_node_adapter", None) is not None: | |
| params.extend(model.embedder.z_node_adapter.parameters()) | |
| if getattr(model.embedder, "z_edge_adapter", None) is not None: | |
| params.extend(model.embedder.z_edge_adapter.parameters()) | |
| if getattr(model.embedder, "disp_node_adapter", None) is not None: | |
| params.extend(model.embedder.disp_node_adapter.parameters()) | |
| if getattr(model.embedder, "disp_edge_adapter", None) is not None: | |
| params.extend(model.embedder.disp_edge_adapter.parameters()) | |
| if getattr(model, "film_mlp", None) is not None: | |
| params.extend(model.film_mlp.parameters()) | |
| return params | |
| def condition_tensor_summary(condition): | |
| out = {} | |
| for key in ["node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond", "energy", "u_local", "u_global", "local_cov_pred", "cross_cov_pred", "rmsf_pred"]: | |
| value = condition.get(key) | |
| if torch.is_tensor(value): | |
| value_f = value.detach().float() | |
| out[f"{key}_shape"] = list(value.shape) | |
| out[f"{key}_abs_mean"] = float(value_f.abs().mean().cpu().item()) | |
| out[f"{key}_std"] = float(value_f.std().cpu().item()) if value_f.numel() > 1 else 0.0 | |
| return out | |
| def known_rotation(device): | |
| # Fixed +90 degree rotation around z. This gives a deterministic | |
| # equivariance check with a known answer: output_rotated == R @ output. | |
| return torch.tensor( | |
| [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], | |
| device=device, | |
| dtype=torch.float32, | |
| ) | |
| def equivariance_diagnostics(module, noisy_batch, condition): | |
| with torch.no_grad(), fp32_context(noisy_batch["res_mask"].device): | |
| rot = known_rotation(noisy_batch["res_mask"].device) | |
| trans_rot = torch.einsum("ij,bnj->bni", rot, noisy_batch["trans_equilibrium"].float()) | |
| rotmats_rot = torch.einsum("ij,bnjk->bnik", rot, noisy_batch["rotmats_equilibrium"].float()) | |
| condition_rot, _ = module.latent_encoder.forward_prior( | |
| trans_rot, | |
| rotmats_rot, | |
| noisy_batch["seq"], | |
| noisy_batch["res_mask"], | |
| ) | |
| expected_u = torch.einsum("ij,bnkj->bnki", rot, condition["u_global"].float()) | |
| expected_center = torch.einsum("ij,bkj->bki", rot, condition["template_center"].float()) | |
| expected_omega = torch.einsum("ij,bkj->bki", rot, condition["template_omega"].float()) | |
| expected_velocity = torch.einsum("ij,bkj->bki", rot, condition["template_velocity"].float()) | |
| return { | |
| "equivariance_rotation": "fixed_z_90deg", | |
| "equivariance_u_global_max_abs_diff": float((condition_rot["u_global"].float() - expected_u).abs().max().detach().cpu().item()), | |
| "equivariance_template_center_max_abs_diff": float((condition_rot["template_center"].float() - expected_center).abs().max().detach().cpu().item()), | |
| "equivariance_template_omega_max_abs_diff": float((condition_rot["template_omega"].float() - expected_omega).abs().max().detach().cpu().item()), | |
| "equivariance_template_velocity_max_abs_diff": float((condition_rot["template_velocity"].float() - expected_velocity).abs().max().detach().cpu().item()), | |
| } | |
| def zero_condition(condition): | |
| zeroed = {} | |
| for key, value in condition.items(): | |
| if torch.is_tensor(value): | |
| if key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}: | |
| zeroed[key] = torch.zeros_like(value) | |
| else: | |
| zeroed[key] = value.detach() | |
| else: | |
| zeroed[key] = value | |
| return zeroed | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--out_dir", required=True) | |
| parser.add_argument("--device", default="cuda") | |
| parser.add_argument("--ckpt_path", default=None) | |
| parser.add_argument("--override", action="append", default=[]) | |
| args = parser.parse_args() | |
| repo_root = Path(__file__).resolve().parents[1] | |
| with initialize_config_dir(version_base=None, config_dir=str(repo_root / "configs")): | |
| cfg = compose(config_name="train", overrides=args.override) | |
| OmegaConf.set_struct(cfg, False) | |
| cfg.experiment.use_wandb = False | |
| cfg.experiment.num_devices = 1 | |
| cfg.latent.enable = True | |
| device = torch.device(args.device if torch.cuda.is_available() or args.device == "cpu" else "cpu") | |
| datamodule = PdbDataModuleBBFlow(cfg.data, training_cfg=cfg.experiment.training, latent_cfg=cfg.latent) | |
| datamodule.setup("fit") | |
| loader = datamodule.train_dataloader(rank=0, num_replicas=1) | |
| batch = move_to_device(next(iter(loader)), device) | |
| batch_rows = summarize_batch(batch) | |
| module = BBFlowModule(cfg).to(device) | |
| load_info = load_model_warm_start(module, args.ckpt_path) | |
| module.train() | |
| module._set_frozen_foundation_eval() | |
| module.interpolant.set_device(device) | |
| with fp32_context(device): | |
| noisy_batch = module.interpolant.corrupt_batch(batch) | |
| prior_feature_breakdown = module.latent_encoder.prior_feature_breakdown( | |
| noisy_batch["trans_equilibrium"], | |
| noisy_batch["rotmats_equilibrium"], | |
| noisy_batch["seq"], | |
| noisy_batch["res_mask"], | |
| ) | |
| ( | |
| condition, | |
| group_index, | |
| latent_metrics, | |
| motion_loss, | |
| shape_baseline_error, | |
| ) = module._latent_group_z(noisy_batch) | |
| for key in ["node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"]: | |
| if torch.is_tensor(condition.get(key)): | |
| condition[key].retain_grad() | |
| noisy_batch["z"] = condition | |
| with autocast_context(cfg, device): | |
| module.model.embedder.track_condition_debug = True | |
| model_output = module.model(noisy_batch) | |
| model_output["pred_trans"].retain_grad() | |
| probe_batch = dict(noisy_batch) | |
| probe_batch["z"] = zero_condition(condition) | |
| with torch.no_grad(), autocast_context(cfg, device): | |
| probe_output = module.model(probe_batch) | |
| z_output_delta = torch.mean(torch.abs(probe_output["pred_trans"] - model_output["pred_trans"].detach())) | |
| with autocast_context(cfg, device): | |
| losses = module.loss_fn(noisy_batch, model_output) | |
| total_losses = {key: torch.mean(value) for key, value in losses.items()} | |
| official_loss = total_losses[module._exp_cfg.training.loss] + total_losses["auxiliary_loss"] | |
| total_loss = official_loss + float(getattr(module._exp_cfg.training, "lambda_shape", 1.0)) * motion_loss | |
| prior_params = list(module.latent_encoder.parameters()) | |
| inject_params = injection_parameters(module.model) | |
| module.zero_grad(set_to_none=True) | |
| motion_loss.backward(retain_graph=True) | |
| motion_prior_grad, motion_prior_count = grad_norm(prior_params) | |
| motion_inject_grad, motion_inject_count = grad_norm(inject_params) | |
| module.zero_grad(set_to_none=True) | |
| for key in ["node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"]: | |
| if torch.is_tensor(condition.get(key)): | |
| condition[key].grad = None | |
| model_output["pred_trans"].grad = None | |
| total_loss.backward() | |
| node_cond_grad, node_cond_grad_count = grad_norm([condition.get("node_cond")]) | |
| edge_cond_grad, edge_cond_grad_count = grad_norm([condition.get("edge_cond")]) | |
| pred_trans_grad, pred_trans_grad_count = grad_norm([model_output["pred_trans"]]) | |
| total_prior_grad, total_prior_count = grad_norm(prior_params) | |
| total_inject_grad, total_inject_count = grad_norm(inject_params) | |
| total_model_grad, total_model_count = grad_norm(module.model.parameters()) | |
| rigid_metrics = module.latent_encoder.rigid_component_metrics( | |
| condition, | |
| noisy_batch["trans_equilibrium"], | |
| noisy_batch["res_mask"], | |
| ) | |
| equiv_metrics = equivariance_diagnostics(module, noisy_batch, condition) | |
| alignment_metrics = {} | |
| if module.motion_loss_enabled: | |
| motion_targets = module._lookup_motion_targets( | |
| noisy_batch["pdb_name"], | |
| device=device, | |
| dtype=condition["cross_cov_pred"].dtype, | |
| num_res=noisy_batch["res_mask"].shape[1], | |
| ) | |
| with torch.autocast(device_type=device.type, enabled=False): | |
| spatial_dists = torch.cdist( | |
| noisy_batch["trans_equilibrium"].float(), | |
| noisy_batch["trans_equilibrium"].float(), | |
| ) | |
| alignment_metrics = module.latent_encoder.motion_alignment_metrics( | |
| condition, | |
| motion_targets, | |
| noisy_batch["res_mask"], | |
| spatial_dists, | |
| ) | |
| summary = { | |
| "batch_size": int(batch["res_mask"].shape[0]), | |
| "warm_start": load_info, | |
| "seq_len": int(batch["res_mask"].shape[1]), | |
| "num_batch_entries": len(batch_rows), | |
| "batch_entries": batch_rows[:10], | |
| "official_loss": float(official_loss.detach().cpu().item()), | |
| "motion_loss": float(motion_loss.detach().cpu().item()), | |
| "shape_recon_loss": float(motion_loss.detach().cpu().item()), | |
| "shape_baseline_error": float(shape_baseline_error.detach().cpu().item()), | |
| "prior_feature_breakdown": prior_feature_breakdown, | |
| "embedder_z_seen": bool(getattr(module.model.embedder, "_last_z_seen", False)), | |
| "embedder_z_requires_grad": bool(getattr(module.model.embedder, "_last_z_requires_grad", False)), | |
| "embedder_z_shape": getattr(module.model.embedder, "_last_z_shape", None), | |
| "embedder_z_abs_mean": float(getattr(module.model.embedder, "_last_z_abs_mean", 0.0)), | |
| "condition_zero_output_delta_mean_abs": float(z_output_delta.detach().cpu().item()), | |
| "motion_prior_grad_norm": motion_prior_grad, | |
| "motion_prior_grad_count": motion_prior_count, | |
| "motion_injection_grad_norm": motion_inject_grad, | |
| "motion_injection_grad_count": motion_inject_count, | |
| "total_node_cond_grad_norm": node_cond_grad, | |
| "total_node_cond_grad_count": node_cond_grad_count, | |
| "total_edge_cond_grad_norm": edge_cond_grad, | |
| "total_edge_cond_grad_count": edge_cond_grad_count, | |
| "total_pred_trans_grad_norm": pred_trans_grad, | |
| "total_pred_trans_grad_count": pred_trans_grad_count, | |
| "total_prior_grad_norm": total_prior_grad, | |
| "total_prior_grad_count": total_prior_count, | |
| "total_injection_grad_norm": total_inject_grad, | |
| "total_injection_grad_count": total_inject_count, | |
| "total_model_grad_norm": total_model_grad, | |
| "total_model_grad_count": total_model_count, | |
| } | |
| summary.update(condition_tensor_summary(condition)) | |
| for key, value in latent_metrics.items(): | |
| summary[key] = float(value.detach().cpu().item()) if torch.is_tensor(value) else float(value) | |
| for key, value in rigid_metrics.items(): | |
| summary[key] = float(value.detach().cpu().item()) if torch.is_tensor(value) else float(value) | |
| for key, value in alignment_metrics.items(): | |
| summary[key] = float(value.detach().cpu().item()) if torch.is_tensor(value) else float(value) | |
| summary.update(equiv_metrics) | |
| out_dir = Path(args.out_dir) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| with (out_dir / "latent_smoke_summary.json").open("w") as handle: | |
| json.dump(summary, handle, indent=2) | |
| pd.DataFrame(batch_rows).to_csv(out_dir / "latent_smoke_batch.tsv", sep="\t", index=False) | |
| print(json.dumps(summary, indent=2)) | |
| print(f"Wrote template-mode smoke diagnostics to {out_dir}") | |
| if __name__ == "__main__": | |
| main() | |