data_transfer / bbflow_base /bbflow /models /bbflow_module.py
hanghang214's picture
upload-bbflow-base
9ae7e2d verified
Raw History Blame Contribute Delete
136 kB
# Copyright (c) 2025 Max Planck Institute for Polymer Research # Copyright (c) 2024 HITS gGmbH # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from typing import Any import copy import torch import torch.utils.checkpoint import time import os import random import logging import wandb import numpy as np import pandas as pd import shutil import json from datetime import datetime from pytorch_lightning.utilities import rank_zero_only import torch.distributed as dist import matplotlib import mdtraj import warnings from gafl.analysis import metrics from gafl.models.flow_module import FlowModule from gafl.data import utils as du from gafl.models import utils as mu import gafl.experiment_utils as eu from bbflow.data.alignment import require_alignment_version from bbflow.models.bbflow_model import BBFlowModel from bbflow.models.latent import LatentEncoder from bbflow.models.collective import collective_measure_dynamics_loss from bbflow.analysis import utils as au from bbflow.analysis.analyse_bbflow import calc_metrics from bbflow.data.interpolant_bbflow import InterpolantBBFlow # depending on the torch version (higher than 2.6), we need to add the DictConfig and ContainerMetadata to the safe globals: from omegaconf import DictConfig, OmegaConf from omegaconf.base import ContainerMetadata if hasattr(torch.serialization, 'add_safe_globals'): torch.serialization.add_safe_globals([DictConfig, ContainerMetadata]) # needed for loading the checkpoint with weights_only=True WARMUP_EPOCH_SUMMARY_KEYS = [ "train_loss", "official_loss", "enm_warmup_loss", "enm_warmup_subspace_overlap", "enm_warmup_cross_cov_far_top10_sign_agree", "enm_warmup_cross_cov_far_corr", "enm_warmup_active", "latent_effective_modes", "condition_scaled_pred_trans_delta_rel", ] MD_EPOCH_SUMMARY_KEYS = [ "train_loss", "official_loss", "motion_loss", "mode_orth_loss", "mode_recon_loss", "q_nll_loss", "q_nll_per_dim", "mode_coeff_abs", "mode_coeff_std", "mode_recon_centered_rel_error", "mode_recon_uncentered_rel_error", "mode_gram_min_eig", "mode_gram_condition", "mode_max_cosine_abs", "local_cov_loss", "cross_cov_loss", "cross_cov_near_loss", "cross_cov_far_loss", "cross_cov_far_corr", "cross_cov_far_top10_sign_agree", "cross_cov_near_top10_sign_agree", "rmsf_loss", "gen_cov_loss", "gen_local_shape_loss", "gen_cross_shape_loss", "gen_oracle_shape_loss", "gen_oracle_weighted_loss", "gen_oracle_active_frac", "gen_oracle_rank_used", "gen_trace_anchor_loss", "gen_response_abs_mean", "gen_response_trace_mean", "gen_trace_ratio_to_teacher", "gen_trace_ratio_to_anchor", "gen_trace_anchor_mean", "gen_rollout_trace_ratio", "gen_rollout_trace_ratio_ema", "gen_rollout_trace_target_scale", "gen_rollout_trace_measured", "gen_rollout_trace_steps", "gen_rollout_batch", "gen_rollout_num_res", "gen_response_active_frac", "pca_align_loss", "pca_align_weighted_overlap", "pca_align_best_overlap", "pca_align_top_energy_overlap", "pca_align_top_energy_subspace_overlap", "condition_cycle_loss", "condition_cycle_rel_error", "condition_cycle_cosine", "enm_warmup_active", "latent_effective_modes", "condition_scaled_pred_trans_delta_rel", "collective_measure_loss", "collective_mean_dynamics_abs_error", "collective_cov_dynamics_loss", "collective_update_abs", "collective_retained_fraction", ] def epoch_summary_stage(metrics): warmup_active = float(metrics.get("enm_warmup_active", 0.0) or 0.0) > 0.5 return "enm-init" if warmup_active else "md" def epoch_summary_keys(metrics): """Return the concise console summary for the current training stage.""" return WARMUP_EPOCH_SUMMARY_KEYS if epoch_summary_stage(metrics) == "enm-init" else MD_EPOCH_SUMMARY_KEYS class BBFlowModule(FlowModule): def __init__(self, cfg, folding_cfg=None): self._latent_cfg_raw = cfg.latent if hasattr(cfg, "latent") else None super().__init__(cfg, folding_cfg) self._print_logger = eu.get_pylogger(__name__) if hasattr(self._exp_cfg, 'reset_epoch'): self.reset_epoch = self._exp_cfg.reset_epoch else: self.reset_epoch = False if hasattr(self._exp_cfg, 'reset_optimizer_on_load'): self.reset_optimizer_on_load = self._exp_cfg.reset_optimizer_on_load else: self.reset_optimizer_on_load = False # set samples per valid protein: num_ranks = cfg.experiment.num_devices total_samples_per_valid_prot = self._data_cfg.validation.samples_per_valid_protein self.samples_per_valid_protein_per_rank = total_samples_per_valid_prot // num_ranks assert total_samples_per_valid_prot % num_ranks == 0, f"Samples per valid protein ({self.samples_per_valid_protein_per_rank}) must be divisible by the number of ranks ({num_ranks}), set by the coinfig parameter experiment.num_devices." assert self.samples_per_valid_protein_per_rank > 0 def create_model(self): latent_enabled = bool(self._latent_cfg_raw is not None and getattr(self._latent_cfg_raw, "enable", False)) self.model = BBFlowModel(self._model_cfg, latent_cfg=self._latent_cfg_raw) self.interpolant = InterpolantBBFlow(self._interpolant_cfg) self.latent_enabled = latent_enabled training_cfg = self._exp_cfg.training self.motion_loss_enabled = bool( latent_enabled and float(getattr(training_cfg, "lambda_shape", 1.0)) != 0.0 ) self.condition_enabled = bool( latent_enabled and ( getattr(self._latent_cfg_raw, "inject_embedder", True) or getattr(self._latent_cfg_raw, "inject_film", True) ) ) self.collective_enabled = bool( latent_enabled and getattr(self._latent_cfg_raw, "collective_enable", False) ) self.collective_rank = int( getattr(self._latent_cfg_raw, "collective_rank", 0) ) if self.collective_enabled else 0 # Take the collective basis from the data instead of from the model's own # implied covariance. The self-referential version measures the model's # error in a basis the model chooses, which has two measured # consequences: the basis walks (its spectrum is nearly flat, so the # eigenvectors are unstable), and directions where nothing happens are # free to inflate until they reach the model's own rank-R eigenvalue -- # observed at 10^-0.15 of that level on 39 of 82 systems. Anchoring to # the cached MD principal directions removes both. It also raises the # fraction of the reference variance the objective can reach at all, # from ~18% (a random 4-plane inside the mode span) to the top-R share. self.collective_basis_from_data = bool( self.collective_enabled and getattr(self._latent_cfg_raw, "collective_basis_from_data", False) ) # Keep the 1/tau in the velocities. Default True only to leave the # existing configuration alone; see the loss docstring for why False is # the better choice. self.collective_rate_weighted = bool( getattr(self._latent_cfg_raw, "collective_rate_weighted", True) ) if self.collective_enabled: if bool(getattr(self._latent_cfg_raw, "freeze_foundation", False)): raise ValueError("CMFM requires the full BBFlow foundation to be unfrozen") # freeze_mode_head is allowed here. It used to be rejected because the # blanket requires_grad_(True) below silently undid it; that unfreeze # now respects the flag. With a stage-1 warm start the mode head # arrives aligned (mode_max_cosine 0.871, cross_cov_far_corr 0.236) # and one epoch of CMFM training destroys it -- the template head # takes a gradient norm ~24x the backbone's on 54x fewer tensors. group_size = int(getattr(training_cfg, "ensemble_group_size", 0)) if group_size <= self.collective_rank: raise ValueError( f"CMFM ensemble_group_size must exceed collective_rank=" f"{self.collective_rank}, got {group_size}" ) self.training_epoch_metrics = [] self._grad_flow_reported = False self._condition_probe_epoch = None self._gen_cov_rollout_trace_ratio_ema = None self.freeze_foundation = bool( latent_enabled and getattr(self._latent_cfg_raw, "freeze_foundation", True) ) if latent_enabled: self.latent_encoder = LatentEncoder(self._latent_cfg_raw) self.motion_target_cache = None self.motion_target_device_cache = {} self.equilibrium_distance_cache = {} self.motion_target_cache_path = getattr( self._latent_cfg_raw, "motion_target_cache_path", getattr(self._latent_cfg_raw, "shape_fingerprint_cache_path", None), ) if not self.motion_loss_enabled and not self.condition_enabled: for param in self.latent_encoder.parameters(): param.requires_grad = False if self.freeze_foundation: self._freeze_foundation_model() # Stage-2 switch: freeze U (trunk + template heads) so c* = Proj_U(D) is # a stable target and q/generator train against a fixed representation. # Orthogonal to freeze_foundation (that freezes the GENERATOR; this # freezes the LATENT mode pathway). Load a stage-1 checkpoint's weights # via experiment.warm_start before relying on this -- freezing does not # by itself give you a trained U, it just stops a loaded one from moving. self.freeze_mode_head = bool( latent_enabled and getattr(self._latent_cfg_raw, "freeze_mode_head", False) ) if self.freeze_mode_head: self.latent_encoder.freeze_prior_backbone() if int(getattr(self, "global_rank", 0)) == 0: check = self.latent_encoder.prior_backbone_grad_check() logging.info( "[freeze-mode-head] u_pathway_params=%d u_pathway_trainable=%d " "(want 0) q_head_trainable=%d (want >0)", check["u_pathway_params"], check["u_pathway_trainable"], check["q_head_trainable"], ) else: self.freeze_mode_head = False if self.collective_enabled: for param in self.model.parameters(): param.requires_grad_(True) for param in self.latent_encoder.parameters(): param.requires_grad_(True) # CMFM needs the generator and q trainable; U is optional. Re-apply # the stage-2 freeze here, after the blanket unfreeze, or it is a # no-op -- q and the collective controller then train against a # fixed U instead of dragging it along. if self.freeze_mode_head: self.latent_encoder.freeze_prior_backbone() if int(getattr(self, "global_rank", 0)) == 0: check = self.latent_encoder.prior_backbone_grad_check() print( "[freeze-mode-head] after collective unfreeze: " f"u_pathway_params={check['u_pathway_params']} " f"u_pathway_trainable={check['u_pathway_trainable']} (want 0) " f"q_head_trainable={check['q_head_trainable']} (want >0)", flush=True, ) def _freeze_foundation_model(self): for param in self.model.parameters(): param.requires_grad = False trainable_modules = [ self.model.embedder.z_node_adapter, self.model.embedder.z_edge_adapter, self.model.embedder.disp_node_adapter, self.model.embedder.disp_edge_adapter, self.model.film_mlp, ] for module in trainable_modules: if module is not None: for param in module.parameters(): param.requires_grad = True def _set_frozen_foundation_eval(self): if not getattr(self, "freeze_foundation", False): return self.model.eval() for module in [ self.model.embedder.z_node_adapter, self.model.embedder.z_edge_adapter, self.model.embedder.disp_node_adapter, self.model.embedder.disp_edge_adapter, self.model.film_mlp, ]: if module is not None: module.train() def on_train_start(self): parent_hook = getattr(super(), "on_train_start", None) if parent_hook is not None: parent_hook() if int(getattr(self, "global_rank", 0)) == 0: lrs = [ float(group["lr"]) for optimizer in self.trainer.optimizers for group in optimizer.param_groups ] print(f"[train-start-lr] lrs={lrs}", flush=True) def on_train_epoch_start(self): self._set_frozen_foundation_eval() if getattr(self, "freeze_mode_head", False): self.latent_encoder.set_frozen_prior_backbone_eval() parent_hook = getattr(super(), "on_train_epoch_start", None) if parent_hook is not None: return parent_hook() return None def _get_motion_target_cache(self): if self.motion_target_cache is not None: return self.motion_target_cache cache_path = self.motion_target_cache_path if cache_path in (None, "null", ""): return None cache_path = os.path.expanduser(str(cache_path)) if not os.path.exists(cache_path): raise FileNotFoundError(f"Missing motion target cache: {cache_path}") cache = torch.load(cache_path, map_location="cpu", weights_only=False) require_alignment_version(cache, source=str(cache_path)) if isinstance(cache, dict) and "motion_targets" in cache: targets = cache["motion_targets"] else: raise ValueError( f"Unsupported motion target cache format: {cache_path}. " "Run scripts/extract_shape_fingerprints.py again to create motion_targets." ) out = {} for key, value in targets.items(): target = { "local_cov": torch.as_tensor(value["local_cov"], dtype=torch.float32), "cross_cov": torch.as_tensor(value["cross_cov"], dtype=torch.float32), "dccm": torch.as_tensor(value.get("dccm", value["cross_cov"]), dtype=torch.float32), "rmsf": torch.as_tensor(value["rmsf"], dtype=torch.float32), "res_mask": torch.as_tensor(value.get("res_mask", torch.ones_like(torch.as_tensor(value["rmsf"]))), dtype=torch.float32), } for optional_field in [ "oracle_modes", "oracle_energy", "oracle_mean_disp", "gen_response_trace_anchor", ]: if optional_field in value: target[optional_field] = torch.as_tensor(value[optional_field], dtype=torch.float32) for name in self._pdb_name_variants(str(key)): out[name] = target if len(out) == 0: raise ValueError(f"Motion target cache is empty: {cache_path}") self.motion_target_cache = out return self.motion_target_cache @staticmethod def _pdb_name_variants(name): variants = {name} if "_" in name: variants.add(name.replace("_", "")) elif len(name) == 5: variants.add(f"{name[:4]}_{name[4]}") return variants def _lookup_motion_targets(self, pdb_names, device, dtype, num_res): cache = self._get_motion_target_cache() if cache is None: raise ValueError( "latent.motion_target_cache_path is required for motion-prior training; " "run base_stages/00_extract_shape_fingerprints.sh first." ) rows = [] missing = [] required_fields = ["local_cov", "cross_cov", "rmsf"] optional_fields = ["oracle_mean_disp", "gen_response_trace_anchor"] needs_oracle_modes = bool(getattr(self._exp_cfg.training, "oracle_condition", False)) or ( float(getattr(self._exp_cfg.training, "lambda_pca_align", 0.0)) > 0.0 ) or bool(getattr(self, "collective_basis_from_data", False)) or ( int(getattr(self._exp_cfg.training, "generator_cov_oracle_rank", 0)) > 0 ) or ( float(getattr(self._exp_cfg.training, "lambda_md_subspace", 0.0)) > 0.0 ) or ( float(getattr(self._exp_cfg.training, "lambda_md_subspace_trace", 0.0)) > 0.0 ) if needs_oracle_modes: # Append rather than replace. The previous reassignment dropped # `gen_response_trace_anchor`, which silently switched the generator # trace anchor from the cached value to constructing a frozen teacher. optional_fields = optional_fields + ["oracle_modes", "oracle_energy"] for name in pdb_names: key = str(name) value = None resolved_name = None for variant in self._pdb_name_variants(key): value = cache.get(variant) if value is not None: resolved_name = variant break if value is None: missing.append(key) continue if needs_oracle_modes: missing_oracle = [field for field in ["oracle_modes", "oracle_energy"] if field not in value] if missing_oracle: raise ValueError( f"Motion target cache entry {key} lacks {missing_oracle}; " "regenerate it with scripts/extract_shape_fingerprints.py before using lambda_pca_align." ) if int(value["rmsf"].shape[0]) != int(num_res): raise ValueError( f"Motion target length mismatch for {key}: cache {value['rmsf'].shape[0]} vs batch {num_res}" ) device_key = (resolved_name, str(device), str(dtype)) device_value = self.motion_target_device_cache.get(device_key) if device_value is None: fields = required_fields + [ field for field in optional_fields if field in value ] device_value = { field: value[field].to(device=device, dtype=dtype) for field in fields } self.motion_target_device_cache[device_key] = device_value rows.append(device_value) if missing: preview = ", ".join(missing[:10]) raise KeyError(f"Missing motion targets for {len(missing)} proteins: {preview}") out = { field: torch.stack([row[field] for row in rows], dim=0) for field in required_fields } for field in optional_fields: if all(field in row for row in rows): out[field] = torch.stack([row[field] for row in rows], dim=0) return out def _equilibrium_spatial_dists(self, pdb_names, trans_equilibrium): rows = [] num_res = int(trans_equilibrium.shape[1]) for name, coords in zip(pdb_names, trans_equilibrium): key = ( str(name), num_res, str(coords.device), str(coords.dtype), ) distances = self.equilibrium_distance_cache.get(key) if distances is None: distances = torch.cdist( coords.detach().float()[None], coords.detach().float()[None] )[0] self.equilibrium_distance_cache[key] = distances rows.append(distances) return torch.stack(rows, dim=0) def validation_step(self, batch: Any, batch_idx: int, dataloader_idx: int=0): pdb_name = batch["pdb_name"][0] epoch_dir = os.path.join(self._sample_write_dir, f'epoch_{self.current_epoch}') os.makedirs(epoch_dir, exist_ok=True) pdb_dir = os.path.join(epoch_dir, pdb_name) os.makedirs(pdb_dir, exist_ok=True) N = batch['seq'].shape[1] batch_size = self._data_cfg.validation.max_valid_num_res_squared / N**2 batch_size = max( 1, min( self._data_cfg.validation.max_valid_batch_size, int(batch_size/5)*5 ) ) self.interpolant.set_device(batch["trans_equilibrium"].device) # print(self.interpolant._cfg) sampled_conformations = self._sample_multiple( batch["trans_equilibrium"], batch["rotmats_equilibrium"], batch["seq"], self.samples_per_valid_protein_per_rank, batch_size, self.interpolant, ) rank = dist.get_rank() if dist.get_world_size() > 1: # if multi-gpu, only save npy files and combine in on_validation_epoch_end # into one pdb file. samples_path = os.path.join(pdb_dir, f'rank_{rank}_sampled_conformations.npy') np.save(samples_path, sampled_conformations) else: # if single-gpu, save pdb file directly samples_path = os.path.join(pdb_dir, f'sampled_conformations.pdb') au.write_prot_to_pdb( sampled_conformations, samples_path, no_indexing=True ) def on_validation_epoch_end(self): # wait until all ranks finished validation_step if dist.is_initialized() and dist.get_world_size() > 1: dist.barrier() # wait until all ranks wrote their .npy if dist.is_initialized() and dist.get_rank() != 0: return # only rank 0 continues # make image saving faster: matplotlib.use("Agg") # non-interactive, fast, no GUI needed import matplotlib.pyplot as plt folder = os.path.join( self._sample_write_dir, f'epoch_{self.current_epoch}', ) valid_csv_path = os.path.join(self._sample_write_dir, 'valid.csv') valid_csv = pd.read_csv(valid_csv_path) all_pdb_names = valid_csv['name'].values if 'name' in valid_csv else valid_csv['pdb_name'].values pdb_names = [] if dist.get_world_size() > 1: # combine samples that are saved in npy files into one pdb file for pdb_name in all_pdb_names: pdb_folder = os.path.join(folder, pdb_name) if self.trainer.sanity_checking and not os.path.exists(pdb_folder): continue pdb_names.append(pdb_name) coords = [] for rank in range(dist.get_world_size()): samples_path = os.path.join(pdb_folder, f'rank_{rank}_sampled_conformations.npy') coords.append(np.load(samples_path)) os.remove(samples_path) coords = np.concatenate(coords, axis=0) samples_path = os.path.join(pdb_folder, f'sampled_conformations.pdb') au.write_prot_to_pdb( coords, samples_path, no_indexing=True ) else: for pdb_name in all_pdb_names: pdb_folder = os.path.join(folder, pdb_name) if self.trainer.sanity_checking and not os.path.exists(pdb_folder): continue pdb_names.append(pdb_name) if self.trainer.sanity_checking or not self._exp_cfg.use_wandb: return metrics_subset = self._data_cfg.validation.metrics_subset with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=UserWarning) data, metrics_dict, _ = calc_metrics( pdb_names, self._data_cfg.validation.valid_xtc_paths, folder, 137, self._data_cfg.loader.num_workers, metrics_subset=metrics_subset, use_tqdm=self._exp_cfg.use_tqdm ) for key, value in metrics_dict.items(): self._log_scalar( f'valid_bbf_metrics/{key}', value, on_step=False, on_epoch=True, prog_bar=False, ) af_rmsfs = None if self._data_cfg.validation.alphaflow_valid_rmsf_path is not None and os.path.exists(self._data_cfg.validation.alphaflow_valid_rmsf_path): with open(self._data_cfg.validation.alphaflow_valid_rmsf_path, 'r') as f: af_rmsfs = json.load(f) else: af_rmsfs = None def _plot_rmsf(pdb_name, ax, md, bbf, af=None, rmsf_type="RMSF"): rmse = np.sqrt(np.mean((bbf[0] - md[0])**2)) xs = np.arange(len(md[0])) ax.plot(xs, md[0], label="MD", c="C0") ax.fill_between(xs, md[1], md[2], color="C0", alpha=0.5) ax.plot(xs, bbf[0], label="BBFlow", c="C1") ax.fill_between(xs, bbf[1], bbf[2], color="C1", alpha=0.5) if af is not None: ax.plot(xs, af["rmsf"], label="AlphaFlow", c="C2") ax.fill_between(xs, af["low"], af["high"], color="C2", alpha=0.5) ax.set_xlabel("Residue") ax.set_ylabel(f"{rmsf_type} "+r"[$\AA$]") ax.legend() ax.set_title(f"{rmsf_type} {pdb_name}, Epoch {self.current_epoch}, RMSE={rmse:.3f}") if self._exp_cfg.use_wandb and "RMSF" in metrics_subset: SMALL_SIZE = 20 MEDIUM_SIZE = 24 BIGGER_SIZE = 28 plt.rc('font', size=SMALL_SIZE) # controls default text sizes plt.rc('axes', titlesize=BIGGER_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title for pdb_name in pdb_names: fig = plt.figure(figsize=(10, 5)) _plot_rmsf( pdb_name, plt.gca(), (data[pdb_name]["CA_ref_rmsf"], data[pdb_name]["CA_ref_rmsf_low"], data[pdb_name]["CA_ref_rmsf_high"]), (data[pdb_name]["CA_model_rmsf"], data[pdb_name]["CA_model_rmsf_low"], data[pdb_name]["CA_model_rmsf_high"]), af_rmsfs[pdb_name] if af_rmsfs is not None else None, "RMSF" ) wandb.log({f"rmsf_plots/{pdb_name}": wandb.Image(fig)}) plt.close(fig) if "RMSF" in metrics_subset: rmses = [] for pdb_name in pdb_names: rmse = np.sqrt(np.mean((data[pdb_name]["model_rmsf"] - data[pdb_name]["ref_rmsf"])**2)) rmses.append(rmse) self._log_scalar( f'valid_all/{pdb_name}_rmsf_rmse', rmse, on_step=False, on_epoch=True, prog_bar=False, ) rmses = np.array(rmses) self._log_scalar( f'valid/rmsf_rmse', np.mean(rmses), on_step=False, on_epoch=True, prog_bar=False, ) def _sample_multiple(self, trans_eq, rotmats_eq, seq, num_samples, batch_size, interpolant, pdb_dir=None ): _, N = trans_eq.shape[:2] diffuse_mask = torch.ones(1, N) sample_ids_batches = np.split( np.arange(num_samples), np.arange(batch_size, num_samples, batch_size) ) sampled_conformations = [] for sample_ids in sample_ids_batches: B = len(sample_ids) z = self._sample_prior_z(trans_eq, rotmats_eq, seq, B) atom37_traj, pred_traj, _ = interpolant.sample( B, N, self.model, trans_eq.repeat(B, 1, 1), rotmats_eq.repeat(B, 1, 1, 1), seq.repeat(B, 1, 1), z=z, return_trajectory=not bool( getattr(self._infer_cfg, "final_only", True) ) or pdb_dir is not None, cache_static_features=bool( getattr(self._infer_cfg, "cache_static_features", True) ), ) atom37_traj = du.to_numpy(torch.stack(atom37_traj, dim=1)) pred_traj = du.to_numpy(torch.stack(pred_traj, dim=1)) # B, T, N, 37, 3 # remove the c betas. they are not predicted by the network but rule based and have no real meaning # Masking CB atoms # atom37 bb order = ['N', 'CA', 'C', 'CB', 'O'] atom37_traj[..., 3, :] = 0 pred_traj[..., 3, :] = 0 for i, sample_id in enumerate(sample_ids): sampled_conformations.append(atom37_traj[i, -1]) if pdb_dir is not None: sample_dir = os.path.join(pdb_dir, f'conf_{sample_id}') os.makedirs(sample_dir, exist_ok=True) eu.save_traj( atom37_traj[i, -1], np.flip(atom37_traj[i], axis=0), np.flip(pred_traj[i], axis=0), du.to_numpy(diffuse_mask)[0], output_dir=sample_dir, ) sampled_conformations = np.stack(sampled_conformations, axis=0) return sampled_conformations def _zero_condition(self, condition): if condition is None: return None out = {} for key, value in condition.items(): if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}: out[key] = torch.zeros_like(value) else: out[key] = value return out def _scale_condition(self, condition, scale): if condition is None or float(scale) == 1.0: return condition out = {} for key, value in condition.items(): if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}: out[key] = value * float(scale) else: out[key] = value return out def _shuffle_condition(self, condition, num_res): if condition is None: return None device = next( (value.device for value in condition.values() if torch.is_tensor(value)), torch.device("cpu"), ) perm = torch.randperm(int(num_res), device=device) out = {} for key, value in condition.items(): if not torch.is_tensor(value): out[key] = value elif key in {"node_cond", "disp_node_cond"} and value.ndim >= 3 and value.shape[1] == num_res: out[key] = value[:, perm, ...] elif key in {"edge_cond", "disp_edge_cond"} and value.ndim >= 4 and value.shape[1] == num_res and value.shape[2] == num_res: out[key] = value[:, perm, ...][:, :, perm, ...] else: out[key] = value return out def _sample_prior_z(self, trans_eq, rotmats_eq, seq, batch_size): if not getattr(self, "latent_enabled", False): return None device = trans_eq.device _, num_res = trans_eq.shape[:2] res_mask = torch.ones(1, num_res, device=device) infer_cfg = getattr(self, "_infer_cfg", None) z_per_sample = bool(getattr(infer_cfg, "z_per_sample", False)) if infer_cfg is not None else False z_per_sample = z_per_sample or bool(getattr(self.latent_encoder, "sample_coefficients", False)) condition_mode = str(getattr(infer_cfg, "condition_mode", "real")) if infer_cfg is not None else "real" condition_scale = float(getattr(infer_cfg, "condition_scale", 1.0)) if infer_cfg is not None else 1.0 # Per-mode tilt, read from the same place as condition_scale. The gain vector is # fixed per protein from that protein's coefficient covariance, so it has to be # set after the prior is computed -- see below. Zero leaves the gain unset and # reproduces every existing result bit for bit. tilt_alpha = (float(getattr(infer_cfg, "coefficient_tilt_alpha", 0.0) or 0.0) if infer_cfg is not None else 0.0) self.latent_encoder._tilt_gain = None with torch.no_grad(): # Fix the tilt gain for THIS protein before any sample is drawn: it is derived # from the protein's own coefficient covariance and must be identical across # its samples, or the transformed covariance is not G Gamma G and the # linearised gate no longer describes what the sampler does. if tilt_alpha != 0.0: from bbflow.models.collective import mixture_mean_and_covariance prior_for_tilt, _ = self.latent_encoder.forward_prior( trans_eq, rotmats_eq, seq, res_mask) _, cov_for_tilt = mixture_mean_and_covariance( prior_for_tilt["mixture_logits"], prior_for_tilt["mixture_mu"], prior_for_tilt["mixture_scale_tril"]) self.latent_encoder.set_tilt(tilt_alpha, cov_for_tilt) if z_per_sample: trans_in = trans_eq.repeat(batch_size, 1, 1) rot_in = rotmats_eq.repeat(batch_size, 1, 1, 1) seq_in = seq.repeat(batch_size, 1, 1) mask_in = res_mask.repeat(batch_size, 1) z = self.latent_encoder.sample_prior_z(trans_in, rot_in, seq_in, mask_in) else: z = self.latent_encoder.sample_prior_z(trans_eq, rotmats_eq, seq, res_mask) z = self.latent_encoder.repeat_condition(z, batch_size) if condition_mode == "real": pass elif condition_mode == "zero": z = self._zero_condition(z) elif condition_mode == "shuffled": z = self._shuffle_condition(z, num_res) elif condition_mode in ("disp_only", "mode_only"): # Channel ablation. The conditioning splits into two groups with # different gauge behaviour: `node_cond` and `edge_cond` are indexed by # mode, so they change under U -> U R and carry no consistent meaning # across proteins, while `disp_node_cond` and `disp_edge_cond` are built # from the displacement field sum_k c_k u_k and are gauge-invariant. # Every trained objective constrains U Gamma U^T, which is also # gauge-invariant -- so an objective can shape it well while the # generator faces per-mode coordinates whose meaning varies per protein. # If zeroing the gauge-dependent pair changes nothing, the generator was # already ignoring them and all four objective failures share one cause. drop = (("node_cond", "edge_cond") if condition_mode == "disp_only" else ("disp_node_cond", "disp_edge_cond")) z = {k: (torch.zeros_like(v) if k in drop and torch.is_tensor(v) else v) for k, v in z.items()} else: raise ValueError(f"Unknown inference.condition_mode={condition_mode}") z = self._scale_condition(z, condition_scale) if self.collective_enabled: z = dict(z) z["collective_group_index"] = torch.zeros( batch_size, device=device, dtype=torch.long ) return z def on_load_checkpoint(self, checkpoint): super().on_load_checkpoint(checkpoint) # If using a Gafl checkpoint, don't use weights of node_embedder and edge_embedder new_state_dict = {} current_state = self.state_dict() for k,v in checkpoint["state_dict"].items(): if 'node_embedder' in k: continue if 'edge_embedder' in k: continue if k not in current_state: continue if current_state[k].shape != v.shape: continue new_state_dict[k] = v for k,v in self.model.state_dict().items(): if f"model.{k}" not in new_state_dict: new_state_dict[f"model.{k}"] = v for k, v in current_state.items(): if k not in new_state_dict: new_state_dict[k] = v checkpoint['state_dict'] = new_state_dict if self.reset_optimizer_on_load: optimizers = self.configure_optimizers() if isinstance(optimizers, tuple): optimizers = optimizers[0] lr_schedulers = optimizers[1] checkpoint['optimizer_states'] = [o.state_dict() for o in optimizers] checkpoint['lr_schedulers'] = [s.state_dict() for s in lr_schedulers] else: checkpoint['optimizer_states'] = [optimizers.state_dict()] if self.reset_epoch: checkpoint["epoch"] = 0 checkpoint["global_step"] = 0 del checkpoint["loops"] def _oracle_group_z(self, noisy_batch): device = noisy_batch["res_mask"].device num_batch, num_res = noisy_batch["res_mask"].shape[:2] oracle_targets = self._lookup_motion_targets( noisy_batch["pdb_name"], device=device, dtype=torch.float32, num_res=num_res, ) missing = [field for field in ["oracle_modes", "oracle_energy", "oracle_mean_disp"] if field not in oracle_targets] if missing: raise ValueError( f"Oracle condition training requires {missing} in latent.motion_target_cache_path; " "rerun base_stages/00_extract_shape_fingerprints.sh with the updated code." ) condition = self.latent_encoder.oracle_condition_from_targets( noisy_batch["trans_1"], noisy_batch["trans_equilibrium"], noisy_batch["rotmats_equilibrium"], noisy_batch["res_mask"], oracle_targets, ) latent_metrics = {} if self._diagnostic_step(): latent_metrics.update(self.latent_encoder.motion_metrics(condition, noisy_batch["res_mask"])) coeff = condition["mode_coefficients"].detach().float() centered = condition["oracle_centered_disp"].detach().float() recon = condition["oracle_recon_disp"].detach().float() mask = noisy_batch["res_mask"].float()[:, :, None] recon_error = ((centered - recon).square() * mask).sum().sqrt() recon_denom = (centered.square() * mask).sum().sqrt().clamp_min(1e-8) latent_metrics.update({ "oracle_condition_active": noisy_batch["res_mask"].new_ones(()), "oracle_coeff_abs": coeff.abs().mean(), "oracle_coeff_std": coeff.std(), "oracle_recon_rel_error": (recon_error / recon_denom).detach(), "enm_warmup_active": noisy_batch["res_mask"].new_zeros(()), }) motion_loss = noisy_batch["res_mask"].new_zeros(()) shape_baseline_error = noisy_batch["res_mask"].new_zeros(()) return ( condition, torch.arange(num_batch, device=device, dtype=torch.long), latent_metrics, motion_loss, shape_baseline_error, ) def _motion_loss_weights(self): training_cfg = self._exp_cfg.training weights = { "local_cov_loss": float(getattr(training_cfg, "lambda_local_cov", 1.0)), "cross_cov_loss": float(getattr(training_cfg, "lambda_cross_cov", 1.0)), "rmsf_loss": float(getattr(training_cfg, "lambda_rmsf", 0.25)), } lambda_pca_align = float(getattr(training_cfg, "lambda_pca_align", 0.0)) if lambda_pca_align > 0.0: weights["pca_align_loss"] = lambda_pca_align return weights def _diagnostic_step(self): interval = int(getattr( self._exp_cfg.training, "diagnostic_interval_steps", 1 )) return interval > 0 and int(self.global_step) % interval == 0 def _collective_shared_time(self, batch): if "group_index" not in batch: raise ValueError("CMFM training requires grouped batches with group_index") group_index = batch["group_index"].long() groups, counts = torch.unique(group_index, sorted=True, return_counts=True) if torch.any(counts <= self.collective_rank): raise ValueError( f"every CMFM group must contain more than rank={self.collective_rank} " f"particles; observed sizes={counts.detach().cpu().tolist()}" ) group_time = self.interpolant.sample_t(int(groups.numel())).float() time = torch.empty( group_index.shape[0], 1, device=group_index.device, dtype=torch.float32 ) for index, group in enumerate(groups): time[group_index == group] = group_time[index] return time def _collective_group_prior_condition(self, noisy_batch): """Evaluate the equilibrium-only prior once per group and broadcast it.""" if "group_index" not in noisy_batch: raise ValueError("CMFM training requires group_index in every batch") group_index = noisy_batch["group_index"].long() groups, inverse, counts = torch.unique( group_index, sorted=True, return_inverse=True, return_counts=True, ) if torch.any(counts <= self.collective_rank): raise ValueError( f"every CMFM group must contain more than rank={self.collective_rank} " f"particles; observed sizes={counts.detach().cpu().tolist()}" ) pdb_names = noisy_batch.get("pdb_name") if pdb_names is not None: group_ids = group_index.detach().cpu().tolist() if len(pdb_names) != len(group_ids): raise ValueError("pdb_name must have one entry per CMFM particle") group_names = {} for group_id, pdb_name in zip(group_ids, pdb_names): previous = group_names.setdefault(group_id, pdb_name) if pdb_name != previous: raise ValueError( "every CMFM group must contain particles from one protein; " f"group={group_id} contains {previous!r} and {pdb_name!r}" ) representative_indices = torch.stack([ torch.nonzero(group_index == group, as_tuple=False)[0, 0] for group in groups ]) representative_condition, _ = self.latent_encoder.forward_prior( noisy_batch["trans_equilibrium"].index_select( 0, representative_indices, ), noisy_batch["rotmats_equilibrium"].index_select( 0, representative_indices, ), noisy_batch["seq"].index_select(0, representative_indices), noisy_batch["res_mask"].index_select(0, representative_indices), ) condition = {} num_groups = int(groups.numel()) for name, value in representative_condition.items(): if not torch.is_tensor(value) or value.ndim == 0: condition[name] = value continue if value.shape[0] != num_groups: raise ValueError( f"prior condition {name} must have leading group dimension " f"{num_groups}, got shape={tuple(value.shape)}" ) condition[name] = value.index_select(0, inverse) if self.collective_basis_from_data: if pdb_names is None: raise ValueError( "collective_basis_from_data needs pdb_name in the batch to " "look up the cached principal directions" ) representative_names = [ pdb_names[int(index)] for index in representative_indices ] targets = self._lookup_motion_targets( representative_names, device=group_index.device, dtype=torch.float32, num_res=int(noisy_batch["res_mask"].shape[1]), ) if "oracle_modes" not in targets or "oracle_energy" not in targets: raise ValueError( "collective_basis_from_data requires oracle_modes and " "oracle_energy in the motion target cache; regenerate it with " "scripts/extract_shape_fingerprints.py" ) rank = self.collective_rank # oracle_modes are the right singular vectors of the centred MD # displacements, so each is already unit norm in the flattened 3N # space and they are sorted by variance -- the same convention the # q-derived basis used, which makes this a drop-in replacement. # oracle_energy holds the variances along them, so the target # covariance is exactly diagonal and needs no estimation from the # group at all. basis = targets["oracle_modes"][:, :, :rank, :].contiguous() energy = targets["oracle_energy"][:, :rank].contiguous() if basis.shape[2] != rank or energy.shape[1] != rank: raise ValueError( f"cached oracle modes provide fewer than collective_rank={rank} " f"directions: modes={tuple(basis.shape)} energy={tuple(energy.shape)}" ) dtype = condition["collective_basis_global"].dtype condition["collective_basis_global"] = basis.index_select( 0, inverse ).to(dtype=dtype) condition["collective_target_variance"] = energy.index_select( 0, inverse ).to(dtype=dtype) condition["collective_target_covariance"] = torch.diag_embed( energy ).index_select(0, inverse).to(dtype=dtype) # The retained fraction is a property of the q-implied spectrum and # is meaningless once the basis comes from the data. Report the # share of MD variance the retained directions carry instead. total = targets["oracle_energy"].sum(dim=-1).clamp_min(1e-8) condition["collective_retained_fraction"] = ( energy.sum(dim=-1) / total ).index_select(0, inverse).to(dtype=dtype) return condition def _collective_population_covariance(self, condition): """Second moment in the collective basis, when it is a data quantity. Only returned for the data-anchored basis. With the q-derived basis ``collective_target_covariance`` is the model's own implied variance -- measured at 2 to 800 times the observed variance along the same directions -- so normalising by it would put the model's belief on both sides of the comparison. """ if not self.collective_basis_from_data: return None return condition.get("collective_target_covariance") def _latent_group_z(self, noisy_batch): self._gen_cov_targets = None if bool(getattr(self._exp_cfg.training, "oracle_condition", False)): return self._oracle_group_z(noisy_batch) device = noisy_batch["res_mask"].device num_batch, num_res = noisy_batch["res_mask"].shape[:2] if self.collective_enabled: prior_condition = self._collective_group_prior_condition(noisy_batch) else: prior_condition, _ = self.latent_encoder.forward_prior( noisy_batch["trans_equilibrium"], noisy_batch["rotmats_equilibrium"], noisy_batch["seq"], noisy_batch["res_mask"], ) condition = prior_condition latent_metrics = {} if self.collective_enabled: latent_metrics["collective_retained_fraction"] = prior_condition[ "collective_retained_fraction" ].detach().float().mean() latent_metrics.update({ "prior_hidden_abs_max": prior_condition[ "prior_hidden_abs_max" ].detach().float().amax(), "prior_raw_mode_abs_max": prior_condition[ "prior_raw_mode_abs_max" ].detach().float().amax(), "prior_raw_mode_rms_min": prior_condition[ "prior_raw_mode_rms_min" ].detach().float().amin(), "prior_raw_mode_rms_max": prior_condition[ "prior_raw_mode_rms_max" ].detach().float().amax(), "prior_mode_norm_min": prior_condition[ "mode_norm" ].detach().float().amin(), "prior_mode_norm_max": prior_condition[ "mode_norm" ].detach().float().amax(), "prior_q_mu_abs_max": prior_condition[ "mixture_mu" ].detach().float().abs().amax(), "prior_q_scale_abs_max": prior_condition[ "mixture_scale_tril" ].detach().float().abs().amax(), "collective_target_variance_min": prior_condition[ "collective_target_variance" ].detach().float().amin(), "collective_target_variance_max": prior_condition[ "collective_target_variance" ].detach().float().amax(), # QR backward is the second suspect: the gauge fixing can stay # finite in the forward while its Jacobian blows up. "prior_qr_diag_abs_min": prior_condition[ "prior_qr_diag_abs_min" ].detach().float().amin(), "prior_qr_rel_diag_min": prior_condition[ "prior_qr_rel_diag_min" ].detach().float().amin(), "prior_qr_condition_max": prior_condition[ "prior_qr_condition" ].detach().float().amax(), }) if self._diagnostic_step(): latent_metrics.update(self.latent_encoder.motion_metrics(prior_condition, noisy_batch["res_mask"])) shape_baseline_error = noisy_batch["res_mask"].new_zeros(()) motion_loss = noisy_batch["res_mask"].new_zeros(()) q_fit_loss = noisy_batch["res_mask"].new_zeros(()) mode_recon_loss = noisy_batch["res_mask"].new_zeros(()) # Must be the pre-gauge modes: u_global is orthonormal by construction, so # penalising it reports ~0 and leaves the mode head free to collapse -- # which is exactly what makes the gauge factorisation ill-conditioned. mode_orth_loss = self.latent_encoder.mode_orthogonality_loss( prior_condition.get("raw_modes_global", prior_condition["u_global"]), noisy_batch["res_mask"], ) motion_targets = None enm_warmup_epochs = int(getattr(self._exp_cfg.training, "enm_warmup_epochs", 0)) in_enm_warmup = bool(self.motion_loss_enabled and int(self.current_epoch) < enm_warmup_epochs) if in_enm_warmup: loss_parts = self.latent_encoder.enm_initialization_loss( prior_condition, noisy_batch["trans_equilibrium"], noisy_batch["res_mask"], ) warmup_weight = float(getattr(self._exp_cfg.training, "lambda_enm_warmup", 1.0)) motion_loss = warmup_weight * loss_parts["enm_warmup_loss"] latent_metrics.update(loss_parts) latent_metrics["enm_warmup_active"] = noisy_batch["res_mask"].new_ones(()) else: if self.motion_loss_enabled: motion_targets = self._lookup_motion_targets( noisy_batch["pdb_name"], device=device, dtype=prior_condition["local_cov_pred"].dtype, num_res=num_res, ) self._gen_cov_targets = motion_targets with torch.autocast(device_type=device.type, enabled=False): spatial_dists = self._equilibrium_spatial_dists( noisy_batch["pdb_name"], noisy_batch["trans_equilibrium"].float(), ) loss_parts = self.latent_encoder.motion_recon_loss( prior_condition, motion_targets, noisy_batch["res_mask"], spatial_dists=spatial_dists, ) weights = self._motion_loss_weights() motion_loss = sum(weight * loss_parts[name] for name, weight in weights.items()) latent_metrics.update(loss_parts) if self._diagnostic_step(): latent_metrics.update(self.latent_encoder.motion_alignment_metrics( prior_condition, motion_targets, noisy_batch["res_mask"], spatial_dists, )) latent_metrics["enm_warmup_active"] = noisy_batch["res_mask"].new_zeros(()) if bool(getattr(self._exp_cfg.training, "per_frame_coeff_condition", False)): mean_disp = None if motion_targets is None else motion_targets.get("oracle_mean_disp") with torch.autocast(device_type=device.type, enabled=False): condition, coeff_target = self.latent_encoder.frame_condition_from_projection( noisy_batch["trans_1"].float(), noisy_batch["trans_equilibrium"].float(), noisy_batch["rotmats_equilibrium"], noisy_batch["res_mask"], prior_condition, mean_disp=mean_disp, ) q_fit_loss = self.latent_encoder.mixture_nll( prior_condition, coeff_target.detach() ) mode_recon_loss = condition["projection_recon_loss"].float().mean() centered_recon = condition["projection_recon_rel_error"].detach().float().mean() latent_metrics.update({ "mode_recon_loss": mode_recon_loss.detach(), "q_nll_loss": q_fit_loss.detach(), "q_nll_per_dim": q_fit_loss.detach() / float(self.latent_encoder.num_modes), "mode_coeff_abs": coeff_target.detach().float().abs().mean(), "mode_coeff_std": coeff_target.detach().float().std(), "mode_recon_rel_error": centered_recon, "mode_recon_centered_rel_error": centered_recon, "mode_recon_uncentered_rel_error": condition[ "projection_uncentered_recon_rel_error" ].detach().float().mean(), }) if self._diagnostic_step(): # Same reason as mode_orth_loss: measured on u_global these # collinearity metrics are constant-by-construction. gram_metrics = self.latent_encoder.mode_gram_diagnostics( prior_condition.get( "raw_modes_global", prior_condition["u_global"] ), noisy_batch["res_mask"], ) latent_metrics.update({ "mode_gram_min_eig": gram_metrics["mode_gram_min_eig"].detach().float().mean(), "mode_gram_condition": gram_metrics["mode_gram_condition"].detach().float().mean(), "mode_max_cosine_abs": gram_metrics["mode_max_cosine_abs"].detach().float().mean(), }) lambda_motion = float(getattr(self._exp_cfg.training, "lambda_motion", 1.0)) lambda_q = float(getattr(self._exp_cfg.training, "lambda_q", 1.0)) lambda_mode_orth = float(getattr(self._exp_cfg.training, "lambda_mode_orth", 0.0)) lambda_mode_recon = float(getattr(self._exp_cfg.training, "lambda_mode_recon", 0.0)) lambda_md_subspace = float( getattr(self._exp_cfg.training, "lambda_md_subspace", 0.0) ) lambda_md_subspace_trace = float( getattr(self._exp_cfg.training, "lambda_md_subspace_trace", 0.0) ) md_subspace_loss = noisy_batch["res_mask"].new_zeros(()) if lambda_md_subspace > 0.0 or lambda_md_subspace_trace > 0.0: # Targets carry the reference eigenbasis; `motion_targets` is already the # cache row when the motion prior is on, otherwise fetch it here. subspace_targets = motion_targets if subspace_targets is None or "oracle_modes" not in subspace_targets: subspace_targets = self._lookup_motion_targets( noisy_batch["pdb_name"], device=device, dtype=prior_condition["u_global"].dtype, num_res=num_res, ) with torch.autocast(device_type=device.type, enabled=False): # prior_condition, not the per-frame condition: the quantity to align # with the reference covariance is q(c | x_eq), which is what inference # samples from. The per-frame condition carries coefficients read off # the target frame and is only available during training. subspace_parts = self.latent_encoder.md_subspace_shape_loss( prior_condition, subspace_targets, noisy_batch["res_mask"], weight_exp=float( getattr(self._exp_cfg.training, "md_subspace_weight_exp", 0.0) ), ) md_subspace_loss = ( lambda_md_subspace * subspace_parts["md_subspace_shape_loss"] + lambda_md_subspace_trace * subspace_parts["md_subspace_trace_loss"] ) latent_metrics.update({ key: value.detach() for key, value in subspace_parts.items() }) latent_regularizer = ( lambda_motion * motion_loss + lambda_q * q_fit_loss + lambda_mode_orth * mode_orth_loss + lambda_mode_recon * mode_recon_loss + md_subspace_loss ) latent_metrics["motion_loss"] = motion_loss.detach() latent_metrics["mode_orth_loss"] = mode_orth_loss.detach() latent_metrics["mode_recon_loss"] = mode_recon_loss.detach() latent_metrics["latent_regularizer_loss"] = latent_regularizer.detach() if self.collective_enabled: if "group_index" not in noisy_batch: raise ValueError("CMFM training requires group_index in every batch") group_index = noisy_batch["group_index"].long() condition = dict(condition) condition["collective_group_index"] = group_index else: group_index = torch.arange(num_batch, device=device, dtype=torch.long) return ( condition, group_index, latent_metrics, latent_regularizer, shape_baseline_error, ) @staticmethod def _condition_with_scale(condition, scale): if not isinstance(condition, dict): return condition * scale out = {} for key, value in condition.items(): if torch.is_tensor(value) and key in {"node_cond", "edge_cond", "disp_node_cond", "disp_edge_cond"}: out[key] = value * scale else: out[key] = value return out def _condition_cycle_loss(self, noisy_batch, model_output, condition): lambda_cycle = float(getattr(self._exp_cfg.training, "lambda_condition_cycle", 0.0)) zero = model_output["pred_trans"].new_zeros(()) if lambda_cycle == 0.0 or condition is None or not isinstance(condition, dict): return zero, {} required = {"mode_coefficients", "u_global", "projection_mean_disp"} if any(key not in condition for key in required): return zero, {} device = model_output["pred_trans"].device with torch.autocast(device_type=device.type, enabled=False): pred_trans = model_output["pred_trans"].float() trans_eq = noisy_batch["trans_equilibrium"].to(device=device, dtype=torch.float32) res_mask = noisy_batch["res_mask"].to(device=device, dtype=torch.float32) mean_disp = condition["projection_mean_disp"].to(device=device, dtype=torch.float32).detach() modes = condition["u_global"].to(device=device, dtype=torch.float32).detach() target_coeff = condition["mode_coefficients"].to(device=device, dtype=torch.float32).detach() pred_disp = self.latent_encoder.relative_displacement( pred_trans, trans_eq, res_mask, ) pred_centered = pred_disp - mean_disp pred_coeff = self.latent_encoder.project_displacement_lstsq( pred_centered, modes, res_mask, ridge=float(getattr(self.latent_encoder, "q_lstsq_ridge", 1e-4)), detach_modes=True, ) diff = pred_coeff - target_coeff denom = target_coeff.norm(dim=-1).clamp_min(1e-8) rel_error = diff.norm(dim=-1) / denom raw_loss = rel_error.mean() cosine = torch.nn.functional.cosine_similarity( pred_coeff, target_coeff, dim=-1, eps=1e-8, ).mean() weighted_loss = lambda_cycle * raw_loss metrics = { "condition_cycle_loss": raw_loss.detach(), "condition_cycle_weighted_loss": weighted_loss.detach(), "condition_cycle_rel_error": rel_error.detach().mean(), "condition_cycle_cosine": cosine.detach(), } return weighted_loss, metrics def _initial_generator_response_teacher(self): if not hasattr(self, "_gen_response_teacher_model"): self._gen_response_teacher_model = None if self._gen_response_teacher_model is None: teacher = copy.deepcopy(self.model) teacher.eval() for param in teacher.parameters(): param.requires_grad_(False) self._gen_response_teacher_model = teacher return self._gen_response_teacher_model def _generator_response_cov_loss(self, noisy_batch, condition): """Train generator response shape without rewarding global expansion. v2 samples multiple antithetic coefficient perturbations, computes the generator's central-difference responses, and matches only the trace-normalized response covariance shape to MD targets. A weak optional frozen-initial teacher trace anchor keeps response amplitude near the A30/start checkpoint under the same ``t`` and coefficient perturbations. """ lambda_gen = float(getattr(self._exp_cfg.training, "lambda_generator_cov", 0.0)) zero = noisy_batch["res_mask"].new_zeros(()) if lambda_gen == 0.0 or condition is None or not isinstance(condition, dict): return zero, {} targets = getattr(self, "_gen_cov_targets", None) if targets is None or "local_cov" not in targets or "rmsf" not in targets: return zero, {} required = ("u_global", "mixture_logits", "mixture_mu", "mixture_scale_tril") if any(key not in condition for key in required): return zero, {} use_cross = bool(getattr(self._exp_cfg.training, "generator_cov_use_cross", False)) if use_cross and "cross_cov" not in targets: use_cross = False # Projection onto the cached MD principal directions. Fails closed: if it is # requested and the cache cannot supply the basis, raise rather than train a # silently different objective. Rank is capped at the number of antithetic # perturbations, since the response covariance cannot exceed that rank. oracle_rank = int(getattr(self._exp_cfg.training, "generator_cov_oracle_rank", 0)) oracle_weight = float( getattr(self._exp_cfg.training, "lambda_gen_oracle_shape", 0.0) ) # Rank and weight must agree. Either alone is a configuration that looks # enabled and trains nothing: a positive weight with rank 0 never builds the # term, a positive rank with weight 0 builds it and discards it. if (oracle_rank > 0) != (oracle_weight > 0.0): raise ValueError( "generator_cov_oracle_rank and lambda_gen_oracle_shape must be both " f"zero or both positive; got rank={oracle_rank}, weight={oracle_weight}" ) if oracle_rank > 0: missing = [ field for field in ("oracle_modes", "oracle_energy") if field not in targets ] if missing: raise KeyError( f"generator_cov_oracle_rank={oracle_rank} requires {missing} in the " "motion target cache" ) # t = 1 is clean, t = 0 is pure noise; mid-high noise is low-to-mid t. t_min = float(getattr(self._exp_cfg.training, "generator_cov_t_min", 0.1)) t_max = float(getattr(self._exp_cfg.training, "generator_cov_t_max", 0.6)) t_vec = torch.squeeze(noisy_batch["t"]).reshape(-1).float() sample_weight = ((t_vec >= t_min) & (t_vec <= t_max)).to(dtype=t_vec.dtype) scale = float(getattr(self._exp_cfg.training, "generator_cov_delta_scale", 1.0)) num_deltas = int(getattr(self._exp_cfg.training, "generator_cov_num_deltas", 2)) num_deltas = max(num_deltas, 2) student_chunk_deltas = int( getattr(self._exp_cfg.training, "generator_cov_student_chunk_deltas", 1) ) student_chunk_deltas = max(1, min(student_chunk_deltas, num_deltas)) teacher_anchor = bool(getattr(self._exp_cfg.training, "generator_cov_initial_trace_anchor", True)) teacher_num_deltas = int(getattr(self._exp_cfg.training, "generator_cov_teacher_num_deltas", 1)) teacher_num_deltas = max(1, min(teacher_num_deltas, num_deltas)) teacher_reuse_student_delta = bool( getattr(self._exp_cfg.training, "generator_cov_teacher_reuse_student_delta", True) ) teacher_trace_denominator = str( getattr(self._exp_cfg.training, "generator_cov_teacher_trace_denominator", "teacher") ) # "md_trace" (default) anchors the response magnitude to the cached MD trace. # "teacher_trace" is retained only for reproducing the old runs: the frozen teacher # is copied at step 0 with zero-initialized condition adapters, so its response to c # is identically zero and the anchor collapses the student's response to zero. amplitude_anchor = str( getattr(self._exp_cfg.training, "generator_cov_amplitude_anchor", "md_trace") ) rollout_enabled = bool( getattr(self._exp_cfg.training, "generator_cov_rollout_calibration", False) ) if rollout_enabled and amplitude_anchor == "md_trace": amplitude_anchor = "rollout_trace" if not teacher_anchor: amplitude_anchor = "none" use_teacher = amplitude_anchor == "teacher_trace" cached_teacher_trace = targets.get("gen_response_trace_anchor") if use_teacher else None teacher_model = ( self._initial_generator_response_teacher() if use_teacher and cached_teacher_trace is None else None ) with torch.autocast(device_type=noisy_batch["res_mask"].device.type, enabled=False): logits = condition["mixture_logits"].detach().float() mu = condition["mixture_mu"].detach().float() probs = torch.softmax(logits, dim=-1) mu_bar = torch.einsum("bm,bmk->bk", probs, mu) u_global = condition["u_global"].detach() rotmats_eq = noisy_batch["rotmats_equilibrium"] res_mask = noisy_batch["res_mask"] def _concat_conditions(conditions): out = {} keys = conditions[0].keys() local_batch_size = None for value in conditions[0].values(): if torch.is_tensor(value) and value.dim() > 0: local_batch_size = value.shape[0] break for key in keys: value = conditions[0][key] if ( local_batch_size is not None and torch.is_tensor(value) and value.shape[:1] == (local_batch_size,) ): out[key] = torch.cat([cond[key] for cond in conditions], dim=0) else: out[key] = value return out def _expand_batch(batch, repeats): out = {} local_batch_size = batch["res_mask"].shape[0] for key, value in batch.items(): if key == "z": continue if torch.is_tensor(value) and value.shape[:1] == (local_batch_size,): out[key] = torch.cat([value for _ in range(repeats)], dim=0) elif isinstance(value, (list, tuple)) and len(value) == local_batch_size: out[key] = list(value) * repeats else: out[key] = value return out use_checkpoint = bool(getattr(self._exp_cfg.training, "generator_cov_checkpoint", True)) trans_eq = noisy_batch["trans_equilibrium"] conditions = [] for _ in range(num_deltas): c_sample, _ = self.latent_encoder.sample_coefficients_from_q(condition) c_sample = c_sample.detach().float() delta = (c_sample - mu_bar) * scale c_plus = mu_bar + delta c_minus = mu_bar - delta cond_plus = self.latent_encoder.condition_from_mode_coefficients( u_global, c_plus, rotmats_eq, res_mask, include_statistics=False ) cond_minus = self.latent_encoder.condition_from_mode_coefficients( u_global, c_minus, rotmats_eq, res_mask, include_statistics=False ) conditions.extend([cond_plus, cond_minus]) batch_size = res_mask.shape[0] response_chunks = [] for start_delta in range(0, num_deltas, student_chunk_deltas): end_delta = min(num_deltas, start_delta + student_chunk_deltas) chunk_conditions = conditions[2 * start_delta : 2 * end_delta] chunk_num_deltas = end_delta - start_delta merged_condition = _concat_conditions(chunk_conditions) merged_batch = _expand_batch(noisy_batch, repeats=len(chunk_conditions)) merged_batch["z"] = merged_condition def _pred_trans_merged(z_cond): probe_batch = dict(merged_batch) probe_batch["z"] = z_cond return self.model(probe_batch)["pred_trans"] if use_checkpoint: pred_merged = torch.utils.checkpoint.checkpoint( _pred_trans_merged, merged_condition, use_reentrant=False ) else: pred_merged = _pred_trans_merged(merged_condition) pred_merged = pred_merged.reshape( chunk_num_deltas, 2, batch_size, *pred_merged.shape[1:] ) pred_plus = pred_merged[:, 0].reshape( chunk_num_deltas * batch_size, *pred_merged.shape[3:] ) pred_minus = pred_merged[:, 1].reshape( chunk_num_deltas * batch_size, *pred_merged.shape[3:] ) trans_eq_rep = trans_eq[None].expand( chunk_num_deltas, -1, -1, -1 ).reshape(chunk_num_deltas * batch_size, *trans_eq.shape[1:]) res_mask_rep = res_mask[None].expand( chunk_num_deltas, -1, -1 ).reshape(chunk_num_deltas * batch_size, *res_mask.shape[1:]) disp_plus = self.latent_encoder.relative_displacement( pred_plus.float(), trans_eq_rep.float(), res_mask_rep ) disp_minus = self.latent_encoder.relative_displacement( pred_minus.float(), trans_eq_rep.float(), res_mask_rep ) chunk_response = 0.5 * (disp_plus - disp_minus) chunk_response = chunk_response.reshape( chunk_num_deltas, batch_size, *chunk_response.shape[1:] ) response_chunks.append(chunk_response) response_deltas = torch.cat(response_chunks, dim=0) def _response_trace(response, mask_value): resp = response.float() if resp.dim() == 3: resp = resp[None] resp = resp * mask_value[None, :, :, None].float() local = torch.einsum("sbni,sbnj->bnij", resp, resp) / float(resp.shape[0]) return ( torch.diagonal(local, dim1=-2, dim2=-1).sum(dim=-1) * mask_value.float() ).sum(dim=-1).clamp_min(1e-8) def _trim_residue_dims(value, max_res): if not torch.is_tensor(value): return value if value.dim() >= 2 and value.shape[1] == res_mask.shape[1]: value = value[:, :max_res, ...] if value.dim() >= 3 and value.shape[2] == res_mask.shape[1]: value = value[:, :, :max_res, ...] return value def _index_first_dim(value, example_idx, max_res=None): if torch.is_tensor(value) and value.shape[:1] == (batch_size,): value = value.index_select(0, example_idx) if max_res is not None: value = _trim_residue_dims(value, max_res) return value if isinstance(value, (list, tuple)) and len(value) == batch_size: return [value[int(i)] for i in example_idx.detach().cpu().tolist()] return value def _slice_condition(cond, example_idx, max_res=None): out = {} for key, value in cond.items(): out[key] = _index_first_dim(value, example_idx, max_res=max_res) return out def _slice_batch(batch, example_idx, max_res=None): out = {} for key, value in batch.items(): if key == "z": continue out[key] = _index_first_dim(value, example_idx, max_res=max_res) return out def _rollout_final_pred_trans(probe_batch, steps): # Faithful mirror of the real inference sampler (interpolant_bbflow.sample): # the caller has already placed the SHARED prior-noise x0 into # trans_t/rotmats_t. Integrate the full linspace(min_t, 1, steps+1) grid # with the exact euler steps inference uses (scalar t_1/d_t), then return # the final clean pred_trans. This is what makes T_full the real-sampler # c-response instead of a coarse t->1 continuation of the training state. rollout_batch = dict(probe_batch) rollout_batch.pop("trans_sc", None) rollout_batch["_embedder_static"] = self.model.prepare_inference_static(rollout_batch) trans_current = rollout_batch["trans_t"] rotmats_current = rollout_batch["rotmats_t"] n = trans_current.shape[0] device = trans_current.device min_t = float(getattr(self._interpolant_cfg, "min_t", 1e-2)) ts = torch.linspace(min_t, 1.0, int(steps) + 1, device=device) was_training = self.model.training self.model.eval() try: t_1 = ts[0] for t_2 in ts[1:]: rollout_batch["trans_t"] = trans_current rollout_batch["rotmats_t"] = rotmats_current rollout_batch["t"] = torch.ones((n, 1), device=device) * t_1 model_out = self.model(rollout_batch) pred_trans_1 = model_out["pred_trans"] pred_rotmats_1 = model_out["pred_rotmats"] if self._interpolant_cfg.self_condition: rollout_batch["trans_sc"] = pred_trans_1.detach() d_t = t_2 - t_1 trans_current = self.interpolant._trans_euler_step( d_t, t_1, pred_trans_1, trans_current ) rotmats_current = self.interpolant._rots_euler_step( d_t, t_1, pred_rotmats_1, rotmats_current ) t_1 = t_2 rollout_batch["trans_t"] = trans_current rollout_batch["rotmats_t"] = rotmats_current rollout_batch["t"] = torch.ones((n, 1), device=device) * ts[-1] model_out = self.model(rollout_batch) return model_out["pred_trans"] finally: self.model.train(was_training) rollout_metrics = {} trace_target_scale = None if rollout_enabled: rollout_interval = int( getattr(self._exp_cfg.training, "generator_cov_rollout_interval_steps", 200) ) rollout_interval = max(1, rollout_interval) should_measure = ( self._gen_cov_rollout_trace_ratio_ema is None or int(getattr(self, "global_step", 0)) % rollout_interval == 0 ) if should_measure: # Default matches inference resolution (num_timesteps=20). This is a # no_grad forward-only measurement on a few proteins once per interval, # so there is no reason to under-resolve it; a coarse 2-step rollout # gives a systematically wrong amplification G. rollout_steps = int( getattr(self._exp_cfg.training, "generator_cov_rollout_steps", 20) ) rollout_steps = max(1, rollout_steps) rollout_num_deltas = int( getattr(self._exp_cfg.training, "generator_cov_rollout_num_deltas", 1) ) rollout_num_deltas = max(1, min(rollout_num_deltas, num_deltas)) rollout_max_examples = int( getattr(self._exp_cfg.training, "generator_cov_rollout_max_examples", 4) ) rollout_max_examples = max(1, min(rollout_max_examples, batch_size)) example_idx = torch.arange( rollout_max_examples, device=res_mask.device, dtype=torch.long, ) selected_mask = res_mask.index_select(0, example_idx) selected_lengths = selected_mask.float().sum(dim=-1) rollout_max_res = int(selected_lengths.max().detach().cpu().item()) rollout_max_res = max(1, min(rollout_max_res, res_mask.shape[1])) with torch.inference_mode(): rollout_conditions = [ _slice_condition(cond, example_idx, max_res=rollout_max_res) for cond in conditions[: 2 * rollout_num_deltas] ] rollout_condition = _concat_conditions(rollout_conditions) rollout_base_batch = _slice_batch( noisy_batch, example_idx, max_res=rollout_max_res, ) # Start T_full from SHARED prior noise x0 (the real inference # start), NOT from the training-time trans_t. trans_t is anchored # to the ground-truth frame (corrupt_batch interpolates noise<->x_1), # so rolling from it measures the c-response near the true frame, # not the free-sampling response inference actually produces. # Sampling x0 on the sliced base (before expand) makes +delta and # -delta of the same example share the same x0 (supplement 1). r_trans0, r_rotmats0 = self.interpolant.sample_from_prior( rollout_max_examples, rollout_max_res, rollout_base_batch["trans_equilibrium"], rollout_base_batch["rotmats_equilibrium"], ) rollout_base_batch = dict(rollout_base_batch) rollout_base_batch["trans_t"] = r_trans0 rollout_base_batch["rotmats_t"] = r_rotmats0 rollout_batch = _expand_batch( rollout_base_batch, repeats=len(rollout_conditions), ) rollout_batch["z"] = rollout_condition rollout_pred = _rollout_final_pred_trans(rollout_batch, rollout_steps) rollout_pred = rollout_pred.reshape( rollout_num_deltas, 2, rollout_max_examples, *rollout_pred.shape[1:] ) rollout_plus = rollout_pred[:, 0].reshape( rollout_num_deltas * rollout_max_examples, *rollout_pred.shape[3:], ) rollout_minus = rollout_pred[:, 1].reshape( rollout_num_deltas * rollout_max_examples, *rollout_pred.shape[3:], ) rollout_trans_eq = trans_eq.index_select(0, example_idx) rollout_trans_eq = rollout_trans_eq[:, :rollout_max_res, :] rollout_res_mask = res_mask.index_select(0, example_idx)[:, :rollout_max_res] rollout_trans_eq_rep = rollout_trans_eq[None].expand( rollout_num_deltas, -1, -1, -1 ).reshape( rollout_num_deltas * rollout_max_examples, *rollout_trans_eq.shape[1:], ) rollout_res_mask_rep = rollout_res_mask[None].expand( rollout_num_deltas, -1, -1 ).reshape( rollout_num_deltas * rollout_max_examples, *rollout_res_mask.shape[1:], ) rollout_disp_plus = self.latent_encoder.relative_displacement( rollout_plus.float(), rollout_trans_eq_rep.float(), rollout_res_mask_rep, ) rollout_disp_minus = self.latent_encoder.relative_displacement( rollout_minus.float(), rollout_trans_eq_rep.float(), rollout_res_mask_rep, ) rollout_response = 0.5 * (rollout_disp_plus - rollout_disp_minus) rollout_response = rollout_response.reshape( rollout_num_deltas, rollout_max_examples, *rollout_response.shape[1:], ) rollout_weight = sample_weight.index_select(0, example_idx) rollout_mask = rollout_res_mask.float() * rollout_weight[:, None].float() one_step_trace = _response_trace( response_deltas[:rollout_num_deltas].index_select(1, example_idx), rollout_mask, ) rollout_trace = _response_trace(rollout_response, rollout_mask) valid = (rollout_mask.sum(dim=-1) > 0).float() trace_ratio = (rollout_trace / one_step_trace).clamp_min(1e-8) ratio_num = (trace_ratio * valid).sum() ratio_den = valid.sum() if dist.is_available() and dist.is_initialized(): ratio_num = ratio_num.detach().clone() ratio_den = ratio_den.detach().clone() dist.all_reduce(ratio_num, op=dist.ReduceOp.SUM) dist.all_reduce(ratio_den, op=dist.ReduceOp.SUM) if ratio_den.detach().item() > 0: ratio_value = ratio_num / ratio_den.clamp_min(1.0) ema_decay = float( getattr(self._exp_cfg.training, "generator_cov_rollout_ema_decay", 0.9) ) ema_decay = min(max(ema_decay, 0.0), 0.999) if self._gen_cov_rollout_trace_ratio_ema is None: self._gen_cov_rollout_trace_ratio_ema = ratio_value.detach() else: self._gen_cov_rollout_trace_ratio_ema = ( ema_decay * self._gen_cov_rollout_trace_ratio_ema.to(ratio_value.device) + (1.0 - ema_decay) * ratio_value.detach() ) rollout_metrics["gen_rollout_trace_ratio"] = ratio_value.detach() rollout_metrics["gen_rollout_trace_measured"] = ratio_value.new_tensor(1.0) rollout_metrics["gen_rollout_trace_steps"] = ratio_value.new_tensor( float(rollout_steps) ) rollout_metrics["gen_rollout_batch"] = ratio_value.new_tensor( float(2 * rollout_num_deltas * rollout_max_examples) ) rollout_metrics["gen_rollout_num_res"] = ratio_value.new_tensor( float(rollout_max_res) ) if self._gen_cov_rollout_trace_ratio_ema is not None: ema_ratio = self._gen_cov_rollout_trace_ratio_ema.to(res_mask.device).clamp_min(1e-8) trace_target_scale = (1.0 / ema_ratio).detach().reshape(1) rollout_metrics["gen_rollout_trace_ratio_ema"] = ema_ratio.detach() rollout_metrics["gen_rollout_trace_target_scale"] = trace_target_scale.detach()[0] else: trace_target_scale = res_mask.new_tensor([1.0]) rollout_metrics["gen_rollout_trace_ratio_ema"] = res_mask.new_tensor(1.0) rollout_metrics["gen_rollout_trace_target_scale"] = res_mask.new_tensor(1.0) if "gen_rollout_trace_measured" not in rollout_metrics: rollout_metrics["gen_rollout_trace_measured"] = res_mask.new_tensor(0.0) teacher_response_deltas = None if teacher_model is not None: with torch.no_grad(): if teacher_reuse_student_delta: teacher_conditions = conditions[: 2 * teacher_num_deltas] else: teacher_conditions = [] for _ in range(teacher_num_deltas): c_sample, _ = self.latent_encoder.sample_coefficients_from_q(condition) c_sample = c_sample.detach().float() delta = (c_sample - mu_bar) * scale c_plus = mu_bar + delta c_minus = mu_bar - delta teacher_conditions.append( self.latent_encoder.condition_from_mode_coefficients( u_global, c_plus, rotmats_eq, res_mask, include_statistics=False ) ) teacher_conditions.append( self.latent_encoder.condition_from_mode_coefficients( u_global, c_minus, rotmats_eq, res_mask, include_statistics=False ) ) teacher_condition = _concat_conditions(teacher_conditions) teacher_batch = _expand_batch(noisy_batch, repeats=len(teacher_conditions)) teacher_batch["z"] = teacher_condition teacher_pred = teacher_model(teacher_batch)["pred_trans"] teacher_pred = teacher_pred.reshape( teacher_num_deltas, 2, batch_size, *teacher_pred.shape[1:] ) teacher_plus = teacher_pred[:, 0].reshape( teacher_num_deltas * batch_size, *teacher_pred.shape[3:] ) teacher_minus = teacher_pred[:, 1].reshape( teacher_num_deltas * batch_size, *teacher_pred.shape[3:] ) teacher_trans_eq_rep = trans_eq[None].expand( teacher_num_deltas, -1, -1, -1 ).reshape(teacher_num_deltas * batch_size, *trans_eq.shape[1:]) teacher_res_mask_rep = res_mask[None].expand( teacher_num_deltas, -1, -1 ).reshape(teacher_num_deltas * batch_size, *res_mask.shape[1:]) teacher_disp_plus = self.latent_encoder.relative_displacement( teacher_plus.float(), teacher_trans_eq_rep.float(), teacher_res_mask_rep ) teacher_disp_minus = self.latent_encoder.relative_displacement( teacher_minus.float(), teacher_trans_eq_rep.float(), teacher_res_mask_rep ) teacher_response_deltas = 0.5 * (teacher_disp_plus - teacher_disp_minus) teacher_response_deltas = teacher_response_deltas.reshape( teacher_num_deltas, batch_size, *teacher_response_deltas.shape[1:] ) losses, metrics = self.latent_encoder.generator_response_cov_loss( response_deltas, res_mask=res_mask, targets=targets, use_cross=use_cross, sample_weight=sample_weight, teacher_response_deltas=teacher_response_deltas, teacher_trace_anchor=cached_teacher_trace, teacher_trace_denominator=teacher_trace_denominator, amplitude_anchor=amplitude_anchor, trace_target_scale=trace_target_scale, oracle_rank=oracle_rank, ) w_local = float(getattr(self._exp_cfg.training, "lambda_gen_local_shape", 1.0)) w_cross = float(getattr(self._exp_cfg.training, "lambda_gen_cross_shape", 1.0)) w_oracle = oracle_weight w_anchor = float(getattr(self._exp_cfg.training, "lambda_gen_trace_anchor", 0.05)) # Anchor warmup: ramp the amplitude-anchor weight 0 -> full over N epochs. # Slamming the calibrated anchor to full on epoch 0 drove the condition to MD # amplitude too fast and collapsed the latent mode geometry (max_cos -> 0.99, # gram_condition -> 1e13) into a NaN q-head by epoch 3. Ramping lets the latent # settle before the amplitude drive reaches full. 0 disables the ramp. anchor_warmup = int(getattr(self._exp_cfg.training, "gen_trace_anchor_warmup_epochs", 0)) if anchor_warmup > 0: w_anchor = w_anchor * min( 1.0, float(getattr(self, "current_epoch", 0)) / float(anchor_warmup) ) total = w_local * losses["gen_local_shape_loss"] if use_cross and "gen_cross_shape_loss" in losses: total = total + w_cross * losses["gen_cross_shape_loss"] oracle_weighted = None if "gen_oracle_shape_loss" in losses: oracle_weighted = w_oracle * losses["gen_oracle_shape_loss"] total = total + oracle_weighted if "gen_trace_anchor_loss" in losses: total = total + w_anchor * losses["gen_trace_anchor_loss"] weighted = lambda_gen * total out_metrics = {key: value.detach() for key, value in losses.items()} out_metrics.update(metrics) out_metrics.update(rollout_metrics) # The only number that proves the oracle term reached the backward. The # unweighted loss says nothing about its weight, `gen_oracle_active_frac` # says nothing about either, and `gen_cov_loss` may be entirely the local # term. if oracle_weighted is not None: out_metrics["gen_oracle_weighted_loss"] = ( lambda_gen * oracle_weighted ).detach() out_metrics["gen_cov_loss"] = weighted.detach() return weighted, out_metrics def _condition_probe_metrics(self, noisy_batch, model_output, condition): if condition is None or not isinstance(condition, dict): return {} enabled = bool(getattr(self._exp_cfg.training, "epoch_condition_probe", True)) if not enabled or self._condition_probe_epoch == int(self.current_epoch): return {} self._condition_probe_epoch = int(self.current_epoch) scale = float(getattr(self._exp_cfg.training, "condition_probe_scale", 2.0)) with torch.no_grad(): zero_batch = dict(noisy_batch) zero_batch["z"] = self._condition_with_scale(condition, 0.0) zero_output = self.model(zero_batch) scaled_batch = dict(noisy_batch) scaled_batch["z"] = self._condition_with_scale(condition, scale) scaled_output = self.model(scaled_batch) pred = model_output["pred_trans"].detach().float() denom = pred.abs().mean().clamp_min(1e-8) zero_delta = (pred - zero_output["pred_trans"].detach().float()).abs().mean() scaled_delta = (scaled_output["pred_trans"].detach().float() - pred).abs().mean() return { "condition_zero_pred_trans_delta": zero_delta.detach(), "condition_zero_pred_trans_delta_rel": (zero_delta / denom).detach(), "condition_scaled_pred_trans_delta": scaled_delta.detach(), "condition_scaled_pred_trans_delta_rel": (scaled_delta / denom).detach(), } def _z_separability(self, z_sample, group_index, groups): with torch.no_grad(): z_group, _ = self.latent_encoder._group_mean(z_sample, group_index) if z_group.shape[0] < 2: return None between = torch.pdist(z_group.float(), p=2) if between.numel() == 0: return None within = [] for group in groups: members = z_sample[group_index == group] if members.shape[0] > 1: within.append(torch.pdist(members.float(), p=2).mean()) if not within: return None within_mean = torch.stack(within).mean().clamp_min(1e-8) return between.mean() / within_mean def on_train_epoch_end(self): if ( getattr(self, "latent_enabled", False) and self.training_epoch_metrics and getattr(self, "global_rank", 0) == 0 ): metric_names = sorted({ key for batch_metrics in self.training_epoch_metrics for key in batch_metrics }) train_epoch_dict = {} for key in metric_names: values = [ batch_metrics[key] for batch_metrics in self.training_epoch_metrics if key in batch_metrics ] train_epoch_dict[key] = float( torch.stack(values).mean().detach().cpu().item() ) train_epoch_dict["epoch"] = int(self.current_epoch) train_epoch_dict["global_step"] = int(self.global_step) train_epoch_dict["rank"] = int(self.global_rank) out_path = os.path.join(self._exp_cfg.checkpointer.dirpath, "latent_train_epoch_metrics.csv") os.makedirs(os.path.dirname(out_path), exist_ok=True) pd.DataFrame([train_epoch_dict]).to_csv( out_path, mode="a", header=not os.path.exists(out_path), index=False, ) stage_name = epoch_summary_stage(train_epoch_dict) # Curated console watch-list: loss + <=5 decision-driving metrics, one per # line, each tagged with the wanted trend/range. The FULL metric set is # still written to latent_train_epoch_metrics.csv above; this only trims # the console noise so the few numbers that decide the run are readable. _watch = [ ("official_loss", "want ~0.85 stable; rising = backbone degrading"), ("mode_max_cosine_abs", "want down <0.9; nearing 1 = about to diverge"), ("gen_response_abs_mean", "want 0.1~0.5; ->0 = inert / blow-up = over-disperse"), ("gen_trace_ratio_to_anchor", "want ->1; response amplitude calibrating to MD"), ("cross_cov_far_corr", "want up 0.1->0.2; PCA-W2 proxy"), ] _loss = train_epoch_dict.get("train_loss", float("nan")) _lines = [f"[epoch {int(self.current_epoch):03d} {stage_name}] loss={_loss:.4g}"] for _k, _hint in _watch: if _k in train_epoch_dict and pd.notna(train_epoch_dict[_k]): _lines.append(f" {_k}={train_epoch_dict[_k]:.4g} [{_hint}]") print("\n".join(_lines), flush=True) self.training_epoch_metrics = [] self._grad_flow_reported = False return super().on_train_epoch_end() # ------------------------------------------------------------------ # CMFM failure localization # # The gradient collapse is only observable per rank and per microbatch: # the rank-0/every-50-steps log cannot explain a rank-1 step-170 failure, # and gradient accumulation hides which microbatch poisoned the buffers. # These helpers record every candidate numerator/denominator and freeze the # exact failing microbatch to disk. Nothing here clips, skips, or rescales. # ------------------------------------------------------------------ CMFM_NUMERICS_FIELDS = ( "prior_hidden_abs_max", "prior_raw_mode_abs_max", "prior_raw_mode_rms_min", "prior_raw_mode_rms_max", "prior_mode_norm_min", "prior_mode_norm_max", "prior_q_mu_abs_max", "prior_q_scale_abs_max", "prior_qr_diag_abs_min", "prior_qr_rel_diag_min", "prior_qr_condition_max", "collective_target_variance_min", "collective_target_variance_max", "collective_retained_fraction", "collective_observed_target_variance_min", "collective_observed_target_variance_max", "collective_covariance_scale_min", "collective_covariance_inverse_scale_max", "collective_target_cov_rate_absmax", "collective_predicted_cov_rate_absmax", "collective_covariance_error_absmax", "collective_z_t_absmax", "collective_z_target_absmax", "collective_target_velocity_absmax", "collective_predicted_velocity_absmax", "collective_update_abs", "collective_update_absmax", ) def _cmfm_debug_dir(self): path = os.path.join( str(self._exp_cfg.trainer.default_root_dir), "cmfm_failure_dumps" ) os.makedirs(path, exist_ok=True) return path def _record_cmfm_numerics( self, latent_metrics, official_loss, shape_recon_loss, collective_loss, group_diagnostics, noisy_batch, ): """Append one row per rank per microbatch to cmfm_numerics_rank{r}.csv.""" microbatch = int(getattr(self, "_cmfm_microbatch_index", 0)) self._cmfm_microbatch_index = microbatch + 1 available = [name for name in self.CMFM_NUMERICS_FIELDS if name in latent_metrics] values = torch.stack([ latent_metrics[name].detach().float().reshape(()) for name in available ] + [ official_loss.detach().float().reshape(()), shape_recon_loss.detach().float().reshape(()), collective_loss.detach().float().reshape(()), ]).cpu().tolist() metrics = dict(zip(list(available) + ["official", "latent", "collective"], values)) for name in self.CMFM_NUMERICS_FIELDS: metrics.setdefault(name, float("nan")) pdb_names = noisy_batch.get("pdb_name") time_values = noisy_batch["t"].detach().float().reshape(-1) row = { "rank": int(self.global_rank), "epoch": int(self.current_epoch), "global_step": int(self.global_step), "microbatch": microbatch, "num_particles": int(noisy_batch["res_mask"].shape[0]), "num_res": int(noisy_batch["res_mask"].shape[1]), "pdb_name": None if pdb_names is None else str(pdb_names[0]), "t_min": float(time_values.min().item()), "t_max": float(time_values.max().item()), "num_groups": len(group_diagnostics), **metrics, } numerics_path = os.path.join( str(self._exp_cfg.trainer.default_root_dir), f"cmfm_numerics_rank{int(self.global_rank)}.csv", ) pd.DataFrame([row]).to_csv( numerics_path, mode="a", header=not os.path.exists(numerics_path), index=False, ) message = ( "[cmfm-numerics] " f"rank={row['rank']} epoch={row['epoch']} step={row['global_step']} " f"micro={microbatch} pdb={row['pdb_name']} N={row['num_res']} " f"t=[{row['t_min']:.4g},{row['t_max']:.4g}] " f"h_max={metrics['prior_hidden_abs_max']:.4g} " f"raw_u_max={metrics['prior_raw_mode_abs_max']:.4g} " f"qr_rel_diag_min={metrics['prior_qr_rel_diag_min']:.4g} " f"qr_cond={metrics['prior_qr_condition_max']:.4g} " f"q_target_var=[{metrics['collective_target_variance_min']:.4g}," f"{metrics['collective_target_variance_max']:.4g}] " f"obs_target_var=[{metrics['collective_observed_target_variance_min']:.4g}," f"{metrics['collective_observed_target_variance_max']:.4g}] " f"cov_scale_min={metrics['collective_covariance_scale_min']:.4g} " f"cov_rate_absmax={metrics['collective_target_cov_rate_absmax']:.4g} " f"ctrl_update_absmax={metrics['collective_update_absmax']:.4g} " f"losses=[official:{metrics['official']:.4g}," f"latent:{metrics['latent']:.4g}," f"collective:{metrics['collective']:.4g}]" ) interval = int(getattr( self._exp_cfg.training, "cmfm_numerics_log_interval", 50 )) if microbatch < 5 or (interval > 0 and microbatch % interval == 0): logging.warning(message) self._cmfm_last_numerics_row = row self._cmfm_last_numerics_message = message self._cmfm_last_group_diagnostics = [ { key: ( float(value.detach().float().item()) if torch.is_tensor(value) else value ) for key, value in entry.items() } for entry in group_diagnostics ] return metrics def _stash_cmfm_microbatch(self, noisy_batch, group_index): """Keep a CPU copy of the current microbatch so a failure can be replayed.""" if not bool(getattr(self._exp_cfg.training, "cmfm_capture_failure", True)): self._cmfm_last_microbatch = None return tensors = {} for key, value in noisy_batch.items(): if key == "z": continue if torch.is_tensor(value): tensors[key] = value.detach().to("cpu").clone() elif isinstance(value, (list, tuple)) and all( isinstance(item, str) for item in value ): tensors[key] = list(value) tensors["group_index"] = group_index.detach().to("cpu").clone() self._cmfm_last_microbatch = tensors def _cmfm_grad_guard(self): """Fail on the first microbatch whose backward produced non-finite grads.""" if not bool(getattr(self._exp_cfg.training, "cmfm_grad_guard", True)): return graded = [ (name, param.grad.detach()) for name, param in self.named_parameters() if param.grad is not None ] if not graded: return # One device sync for the whole check; the per-parameter walk only runs # once the step is already known to be lost. if bool(torch.stack([ torch.isfinite(grad).all() for _, grad in graded ]).all()): return nonfinite_names = [ name for name, grad in graded if not bool(torch.isfinite(grad).all()) ] dump_path = self._dump_cmfm_failure(nonfinite_names) preview = ", ".join(nonfinite_names[:8]) if len(nonfinite_names) > 8: preview += f", ... (+{len(nonfinite_names) - 8} more)" raise FloatingPointError( "non-finite gradients after backward on a single CMFM microbatch " f"(rank={self.global_rank}, epoch={self.current_epoch}, " f"global_step={self.global_step}, " f"microbatch={int(getattr(self, '_cmfm_microbatch_index', 0)) - 1}, " f"nonfinite_parameters={len(nonfinite_names)}, [{preview}]); " f"failure dump written to {dump_path}" ) def _dump_cmfm_failure(self, nonfinite_names): """Freeze the failing microbatch, its numerics, and the pre-step weights.""" directory = self._cmfm_debug_dir() microbatch = int(getattr(self, "_cmfm_microbatch_index", 0)) - 1 stem = ( f"rank{int(self.global_rank)}_epoch{int(self.current_epoch)}" f"_step{int(self.global_step)}_micro{microbatch}" ) batch = getattr(self, "_cmfm_last_microbatch", None) numerics_row = getattr(self, "_cmfm_last_numerics_row", None) group_diagnostics = getattr(self, "_cmfm_last_group_diagnostics", None) grad_summary = [] for name, param in self.named_parameters(): if param.grad is None: continue grad = param.grad.detach() finite = torch.isfinite(grad) grad_summary.append({ "name": name, "nonfinite_elements": int((~finite).sum().item()), "elements": int(grad.numel()), "finite_absmax": float( grad[finite].abs().max().item() if bool(finite.any()) else float("nan") ), }) metadata = { "rank": int(self.global_rank), "world_size": int(getattr(self._trainer, "world_size", 1)) if getattr(self, "_trainer", None) is not None else 1, "epoch": int(self.current_epoch), "global_step": int(self.global_step), "microbatch": microbatch, "precision": str(getattr(self._exp_cfg.trainer, "precision", "unknown")), "accumulate_grad_batches": int( getattr(self._exp_cfg.trainer, "accumulate_grad_batches", 1) ), "collective_rank": int(self.collective_rank), "checkpoint_dir": str( getattr(self._exp_cfg.checkpointer, "dirpath", "") ), "nonfinite_parameter_count": len(nonfinite_names), "nonfinite_parameters": nonfinite_names, "numerics": numerics_row, "group_diagnostics": group_diagnostics, "grad_summary": grad_summary, } if batch is not None: metadata["pdb_name"] = batch.get("pdb_name") for key in ("group_index", "conformation_idx", "trajectory_idx", "t"): if key in batch: metadata[key] = batch[key].reshape(-1).tolist() json_path = os.path.join(directory, f"{stem}.json") with open(json_path, "w") as handle: json.dump(metadata, handle, indent=2, default=str) full_cfg = getattr(self, "_cfg", None) payload = { "metadata": metadata, "batch": batch, "config": ( None if full_cfg is None else OmegaConf.to_container(full_cfg, resolve=True) ), } if bool(getattr(self._exp_cfg.training, "cmfm_dump_state_dict", True)): payload["state_dict"] = { name: tensor.detach().to("cpu").clone() for name, tensor in self.state_dict().items() } dump_path = os.path.join(directory, f"{stem}.pt") torch.save(payload, dump_path) logging.error( "[cmfm-failure] wrote %s and %s (%d non-finite parameter grads)", dump_path, json_path, len(nonfinite_names), ) return dump_path def cmfm_debug_losses(self, noisy_batch): """Recompute official/latent/collective for an already-corrupted batch. Used by scripts/cmfm_replay_failure.py to backpropagate each component separately on the captured microbatch. It deliberately mirrors training_step instead of wrapping it so that no Trainer state is needed. """ ( z, group_index, latent_metrics, latent_regularizer, _, ) = self._latent_group_z(noisy_batch) noisy_batch = dict(noisy_batch) noisy_batch["z"] = z model_output = self._run_training_model(noisy_batch) collective_parts = collective_measure_dynamics_loss( noisy_batch["trans_t"], noisy_batch["trans_1"], model_output["pred_trans"], noisy_batch["trans_equilibrium"], noisy_batch["res_mask"], z["collective_basis_global"], group_index, noisy_batch["t"], t_normalize_clip=float(self._exp_cfg.training.t_normalize_clip), target_covariance=self._collective_population_covariance(z), rate_weighted=self.collective_rate_weighted, ) group_diagnostics = collective_parts.pop("collective_group_diagnostics", []) batch_losses = self.loss_fn(noisy_batch, model_output) official_loss = ( torch.mean(batch_losses[self._exp_cfg.training.loss]) + torch.mean(batch_losses["auxiliary_loss"]) ) # Sub-losses exposed individually. "official" is a sum of four terms with # very different numerics (a squared error, an SO(3) log map, and two # pairwise-distance terms), so attributing a non-finite backward to # "official" is not yet a location. official_subcomponents = { f"official:{name}": torch.mean(value) for name, value in batch_losses.items() if torch.is_tensor(value) and value.requires_grad } return { **official_subcomponents, "official": official_loss, "latent": float( getattr(self._exp_cfg.training, "lambda_shape", 1.0) ) * latent_regularizer, "collective": float( getattr(self._exp_cfg.training, "lambda_collective_measure", 0.0) ) * collective_parts["collective_measure_loss"], "metrics": { key: value for key, value in latent_metrics.items() }, "collective_parts": collective_parts, "group_diagnostics": group_diagnostics, } def on_before_optimizer_step(self, optimizer): parent_hook = getattr(super(), "on_before_optimizer_step", None) if parent_hook is not None: parent_hook(optimizer) if not getattr(self, "latent_enabled", False) or not self.collective_enabled: return training_grads = [ (name, param.grad.detach()) for name, param in self.named_parameters() if param.grad is not None ] if not training_grads: return all_finite = torch.stack([ torch.isfinite(grad).all() for _, grad in training_grads ]).all() if bool(all_finite): return nonfinite_names = [ name for name, grad in training_grads if not bool(torch.isfinite(grad).all()) ] preview = ", ".join(nonfinite_names[:8]) if len(nonfinite_names) > 8: preview += f", ... (+{len(nonfinite_names) - 8} more)" raise FloatingPointError( "non-finite training gradients before optimizer step; refusing to update " f"corrupted parameters (rank={self.global_rank}, " f"epoch={self.current_epoch}, global_step={self.global_step}, " f"parameters=[{preview}])" ) def _grad_norm_for_prefixes(self, prefixes): total = 0.0 count = 0 for name, param in self.named_parameters(): if not any(name.startswith(prefix) or prefix in name for prefix in prefixes): continue if param.grad is None: continue total += float(param.grad.detach().float().norm().cpu().item()) count += 1 return total, count def on_after_backward(self): parent_hook = getattr(super(), "on_after_backward", None) if parent_hook is not None: parent_hook() if not getattr(self, "latent_enabled", False): return if self.collective_enabled: # Runs on every rank and every microbatch, i.e. before accumulation # can smear the first bad microbatch across the whole window. self._cmfm_grad_guard() if self._grad_flow_reported: return if int(getattr(self, "global_step", 0)) != 0 or getattr(self, "global_rank", 0) != 0: return if not bool(getattr(self._exp_cfg.training, "grad_flow_check", False)): return groups = { "bbflow_backbone": ["model."], "prior_template_head": ["latent_encoder.template_"], "prior_energy_head": ["latent_encoder.energy_out"], "prior_mixture_head": ["latent_encoder.mixture_"], "collective_controller": ["model.collective_controller"], "condition_adapters_film": [ "model.embedder.z_node_adapter", "model.embedder.z_edge_adapter", "model.embedder.disp_node_adapter", "model.embedder.disp_edge_adapter", "model.film_mlp", ], } rows = [] for group_name, prefixes in groups.items(): norm, count = self._grad_norm_for_prefixes(prefixes) rows.append(f"{group_name}:grad_norm={norm:.4g}:params_with_grad={count}") print("[grad-flow-check] " + ", ".join(rows), flush=True) self._grad_flow_reported = True def _condition_usage_ranking_loss(self, noisy_batch, z, ell_pos): """Contrastive 'the generator must USE c'. Same X_t: the correct c must give a LOWER flow error than a WRONG c (another batch item's c, SAME modes). If the model ignores c then ell_pos ~= ell_neg and this loss cannot be reduced -> it forces c to matter. Cost: one extra forward on a fraction of steps (no 20-step rollout). ell_pos is detached (the main flow loss already trains it); the gradient here only pushes the wrong-c error UP. Off by default (lambda=0). NOTE: this is the single-step 'c is used' signal. It does NOT guarantee the 20-step endpoint recovers c (that is the drift/terminal-calibration question); keep measuring c* vs c_hat_20 separately. """ lam = float(getattr(self._exp_cfg.training, "lambda_condition_usage", 0.0)) if lam <= 0.0 or not isinstance(z, dict) or "mode_coefficients" not in z: return noisy_batch["res_mask"].new_zeros(()) frac = float(getattr(self._exp_cfg.training, "condition_usage_frac", 0.15)) B = int(noisy_batch["res_mask"].shape[0]) if B < 2 or random.random() > frac: return noisy_batch["res_mask"].new_zeros(()) perm = torch.roll(torch.arange(B, device=noisy_batch["res_mask"].device), shifts=1) coeff_neg = z["mode_coefficients"][perm] # wrong coefficients, SAME modes/subspace with torch.autocast(device_type="cuda", enabled=False): z_neg = self.latent_encoder.condition_from_mode_coefficients( z["u_global"].float(), coeff_neg.float(), noisy_batch["rotmats_equilibrium"], noisy_batch["res_mask"], include_statistics=False, ) neg_batch = dict(noisy_batch) neg_batch["z"] = z_neg neg_batch.pop("trans_sc", None) # no self-conditioning leakage from the + path neg_out = self.model(neg_batch) neg_losses = self.loss_fn(neg_batch, neg_out) ell_neg = torch.mean( neg_losses[self._exp_cfg.training.loss] + neg_losses["auxiliary_loss"] ) margin = float(getattr(self._exp_cfg.training, "condition_usage_margin", 0.0)) return lam * torch.clamp(margin + ell_pos.detach() - ell_neg, min=0.0) def _run_training_model(self, noisy_batch): collective_chunk_size = int( getattr( self._exp_cfg.training, "collective_backbone_chunk_size", 0, ) ) if self.collective_enabled and collective_chunk_size > 0: return self.model.forward_chunked( noisy_batch, chunk_size=collective_chunk_size, checkpoint_chunks=True, ) use_checkpoint = bool( self.training and torch.is_grad_enabled() and bool(getattr(self._exp_cfg.training, "full_model_activation_checkpoint", False)) ) if not use_checkpoint: return self.model(noisy_batch) def model_forward(batch): return self.model(batch) return torch.utils.checkpoint.checkpoint( model_forward, noisy_batch, use_reentrant=False, ) def training_step(self, batch: Any, stage: int): step_start_time = time.time() self.interpolant.set_device(batch['res_mask'].device) # Lightning bf16 autocast wraps training_step; OT/Kabsch/SVD/linalg.det need fp32. # Keep rigid-body corruption in fp32, but let the learned latent prior # use the trainer mixed-precision context. Its pairwise message passing # is checkpointed inside LatentEncoder. with torch.autocast(device_type="cuda", enabled=False): shared_time = self._collective_shared_time(batch) if self.collective_enabled else None noisy_batch = self.interpolant.corrupt_batch(batch, t=shared_time) if getattr(self, "latent_enabled", False): ( z, group_index, latent_metrics, shape_recon_loss, shape_baseline_error, ) = self._latent_group_z(noisy_batch) else: z = None group_index = torch.arange( noisy_batch["res_mask"].shape[0], device=noisy_batch["res_mask"].device, dtype=torch.long, ) latent_metrics = {} shape_recon_loss = noisy_batch["res_mask"].new_zeros(()) shape_baseline_error = noisy_batch["res_mask"].new_zeros(()) if z is not None: noisy_batch["z"] = z log_latent_batch_debug = bool( getattr(self._exp_cfg.training, "log_latent_batch_debug", False) ) should_log_latent_batch = bool( log_latent_batch_debug and getattr(self, "global_rank", 0) == 0 and not getattr(self, "_latent_batch_debug_logged", False) ) if should_log_latent_batch: groups_unique, group_counts = torch.unique( group_index.detach().cpu(), sorted=True, return_counts=True, ) logging.info( "latent batch before forward | rank=%s step=%s B=%s N=%s groups=%s group_sizes=%s precision=%s", getattr(self, "global_rank", 0), int(self.global_step), int(noisy_batch["res_mask"].shape[0]), int(noisy_batch["res_mask"].shape[1]), int(groups_unique.numel()), group_counts.tolist(), str(getattr(self._exp_cfg.trainer, "precision", "32-true")), ) self._latent_batch_debug_logged = True if self._interpolant_cfg.self_condition and random.random() > 0.5: with torch.no_grad(): model_sc = self._run_training_model(noisy_batch) noisy_batch['trans_sc'] = model_sc['pred_trans'] model_output = self._run_training_model(noisy_batch) if z is not None: latent_metrics.update(self._condition_probe_metrics(noisy_batch, model_output, z)) condition_cycle_loss, condition_cycle_metrics = self._condition_cycle_loss( noisy_batch, model_output, z, ) latent_metrics.update(condition_cycle_metrics) gen_cov_loss, gen_cov_metrics = self._generator_response_cov_loss(noisy_batch, z) latent_metrics.update(gen_cov_metrics) if self.collective_enabled: collective_parts = collective_measure_dynamics_loss( noisy_batch["trans_t"], noisy_batch["trans_1"], model_output["pred_trans"], noisy_batch["trans_equilibrium"], noisy_batch["res_mask"], z["collective_basis_global"], group_index, noisy_batch["t"], t_normalize_clip=float(self._exp_cfg.training.t_normalize_clip), target_covariance=self._collective_population_covariance(z), rate_weighted=self.collective_rate_weighted, ) collective_loss = collective_parts["collective_measure_loss"] collective_group_diagnostics = collective_parts.pop( "collective_group_diagnostics", [] ) latent_metrics.update({ key: value.detach() for key, value in collective_parts.items() }) collective_update = model_output["collective_update_global"].detach().float() latent_metrics["collective_update_abs"] = collective_update.abs().mean() latent_metrics["collective_update_absmax"] = collective_update.abs().amax() else: collective_group_diagnostics = [] collective_loss = model_output["pred_trans"].new_zeros(()) batch_losses = self.loss_fn(noisy_batch, model_output) num_batch = batch_losses['bb_atom_loss'].shape[0] total_losses = { k: torch.mean(v) for k,v in batch_losses.items() } official_loss = ( total_losses[self._exp_cfg.training.loss] + total_losses['auxiliary_loss'] ) condition_usage_loss = self._condition_usage_ranking_loss(noisy_batch, z, official_loss) train_loss = ( official_loss + float(getattr(self._exp_cfg.training, "lambda_shape", 1.0)) * shape_recon_loss + condition_cycle_loss + gen_cov_loss + condition_usage_loss + float(getattr(self._exp_cfg.training, "lambda_collective_measure", 0.0)) * collective_loss ) nonfinite_detected = (~torch.isfinite(train_loss)).float() if self.trainer.world_size > 1: dist.all_reduce(nonfinite_detected, op=dist.ReduceOp.SUM) if nonfinite_detected > 0: raise FloatingPointError( "non-finite training loss; refusing to skip a corrupted CMFM step " f"(rank={self.global_rank}, epoch={self.current_epoch}, " f"global_step={self.global_step}, " f"official={official_loss.detach().float().item():.6g}, " f"latent={shape_recon_loss.detach().float().item():.6g}, " f"collective={collective_loss.detach().float().item():.6g})" ) if self.collective_enabled: self._record_cmfm_numerics( latent_metrics, official_loss, shape_recon_loss, collective_loss, collective_group_diagnostics, noisy_batch, ) self._stash_cmfm_microbatch(noisy_batch, group_index) for k,v in total_losses.items(): self._log_scalar( f"train/{k}", v, prog_bar=False, batch_size=num_batch) self._log_scalar("train/official_loss", official_loss, prog_bar=False, batch_size=num_batch) self._log_scalar("train/shape_recon_loss", shape_recon_loss, prog_bar=False, batch_size=num_batch) self._log_scalar("train/shape_baseline_error", shape_baseline_error, prog_bar=False, batch_size=num_batch) self._log_scalar("train/condition_usage_loss", condition_usage_loss, prog_bar=False, batch_size=num_batch) for metric_name, metric_value in latent_metrics.items(): self._log_scalar(f"train/{metric_name}", metric_value, prog_bar=False, batch_size=num_batch) def detached_scalar(value): if torch.is_tensor(value): return value.detach().float().mean() return train_loss.detach().new_tensor(float(value), dtype=torch.float32) batch_metrics = { k: detached_scalar(v) for k, v in total_losses.items() } batch_metrics.update({ "official_loss": detached_scalar(official_loss), "shape_recon_loss": detached_scalar(shape_recon_loss), "shape_baseline_error": detached_scalar(shape_baseline_error), "train_loss": detached_scalar(train_loss), }) batch_metrics.update({ k: detached_scalar(v) for k, v in latent_metrics.items() }) t = torch.squeeze(noisy_batch['t']) self._log_scalar( "train/t", t.detach().float().mean(), prog_bar=False, batch_size=num_batch) if self._exp_cfg.training.t_bins > 1 and self._diagnostic_step(): for loss_name, loss_dict in batch_losses.items(): stratified_losses = mu.t_stratified_loss( t, loss_dict, num_bins=self._exp_cfg.training.t_bins, t_interval=self._interpolant_cfg.t_interval, loss_name=loss_name) batch_metrics.update({ k: detached_scalar(v) for k, v in stratified_losses.items() }) for k,v in stratified_losses.items(): self._log_scalar( f"train/{k}", v, prog_bar=False, batch_size=num_batch) self.training_epoch_metrics.append(batch_metrics) self._log_scalar( "train/length", float(batch['res_mask'].shape[1]), prog_bar=False, batch_size=num_batch) self._log_scalar( "train/batch_size", float(num_batch), prog_bar=False) step_time = time.time() - step_start_time self._log_scalar( "train/examples_per_second", num_batch / step_time) self._log_scalar( "train/loss", train_loss, batch_size=num_batch) if self._exp_cfg.use_wandb: wandb_logs = {} time_indices = torch.bucketize(noisy_batch["t"].detach().cpu(), self._time_bins) time_indices_unique, counts = torch.unique(time_indices-1, return_counts=True) time_indices_unique[time_indices_unique < 0] = 0 self._time_histogram[time_indices_unique] += counts wandb_logs["sampled_time_cumulative"] = wandb.Histogram( np_histogram=(( (self._time_histogram/self._time_histogram.sum()).numpy(), self._time_bins.numpy() )) ) time_histogram_step = torch.zeros(self._time_histogram.shape) time_histogram_step[time_indices_unique] += counts wandb_logs["sampled_time_per_step"] = wandb.Histogram( np_histogram=(( (time_histogram_step/time_histogram_step.sum()).numpy(), self._time_bins.numpy() )) ) self.logger.experiment.log(wandb_logs) return train_loss def configure_optimizers(self): if not getattr(self, "latent_enabled", False): return super().configure_optimizers() params = [p for p in list(self.model.parameters()) + list(self.latent_encoder.parameters()) if p.requires_grad] if getattr(self, "global_rank", 0) == 0 and bool(getattr(self._exp_cfg.training, "log_optimizer_coverage", True)): num_params = sum(p.numel() for p in params) print(f"[optimizer-coverage] trainable_tensors={len(params)} trainable_params={num_params}", flush=True) if not self._exp_cfg.scheduler.enabled: return torch.optim.AdamW( params=params, **self._exp_cfg.optimizer, ) optimizer = torch.optim.AdamW( params=params, **self._exp_cfg.optimizer, ) scheduler = torch.optim.lr_scheduler.LambdaLR( optimizer, lr_lambda=self.lr_lambda ) return [optimizer], [scheduler] def predict_step(self, batch, batch_idx): device = f'cuda:{torch.cuda.current_device()}' interpolant = InterpolantBBFlow(self._infer_cfg.interpolant) interpolant.set_device(device) pdb_dir = os.path.join(self._output_dir, batch["pdb_name"][0]) if os.path.exists(os.path.join(pdb_dir, "sampled_conformations.pdb")): print(f"Skipping {batch['pdb_name']} as it already exists") return os.makedirs(pdb_dir, exist_ok=True) sample_time_start = datetime.now() N = batch["trans_equilibrium"].shape[1] requested_batch_size = int(self._infer_cfg.samples.batch_size) batch_size = self._infer_cfg.samples.num_res_squared / N**2 batch_size = max( 1, min( requested_batch_size, int(batch_size/5)*5 ) ) if self.collective_enabled: if batch_size != requested_batch_size: raise ValueError( f"CMFM requested joint group size {requested_batch_size}, but the " f"length-based sampler reduced it to {batch_size} for N={N}. " "Increase inference.samples.num_res_squared; CMFM does not shrink groups." ) if batch_size <= self.collective_rank: raise ValueError( f"CMFM inference batch_size={batch_size} must exceed " f"collective_rank={self.collective_rank}" ) if int(self._infer_cfg.samples.samples_per_protein) % batch_size != 0: raise ValueError( "CMFM samples_per_protein must be divisible by the joint group size" ) sampled_conformations = self._sample_multiple( batch["trans_equilibrium"], batch["rotmats_equilibrium"], batch["seq"], self._infer_cfg.samples.samples_per_protein, batch_size, interpolant, pdb_dir=pdb_dir if self._infer_cfg.save_traj else None ) sample_time = (datetime.now()-sample_time_start).total_seconds() aatype = batch["seq"][0].argmax(-1).cpu().numpy() samples_path = os.path.join(pdb_dir, f'sampled_conformations.pdb') au.write_prot_to_pdb( sampled_conformations, samples_path, aatype=aatype, no_indexing=True ) if bool(getattr(self._infer_cfg, "postprocess_bfactors", True)): confs = mdtraj.load(samples_path) avg = np.mean(confs.xyz, axis=0) avg -= np.mean(avg[confs.top.select("name CA")], axis=0, keepdims=True) avg = mdtraj.Trajectory(avg[None, :, :], confs.top) confs = confs.superpose(avg) rmsf = mdtraj.rmsf(confs, avg) confs.save_pdb(samples_path, bfactors=rmsf) if not self._infer_cfg.single_file: os.makedirs(os.path.join(pdb_dir, "samples")) confs = mdtraj.load(samples_path) for i in range(len(confs)): single_sample_path = os.path.join(pdb_dir, "samples", f"sample_{i}.pdb") confs[i].save(single_sample_path) os.remove(samples_path) if self._infer_cfg.log_times: self._print_logger.info(f"Generating time for {batch['pdb_name']} for {self._infer_cfg.samples.samples_per_protein} samples of length {N}: {sample_time}s") sample_time = (datetime.now()-sample_time_start).total_seconds() self._print_logger.info(f"Time with pdb saving and plotting: {sample_time}s")
# Copyright (c) 2025 Max Planck Institute for Polymer Research
# Copyright (c) 2024 HITS gGmbH
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from typing import Any
import copy
import torch
import torch.utils.checkpoint
import time
import os
import random
import logging
import wandb
import numpy as np
import pandas as pd
import shutil
import json
from datetime import datetime
from pytorch_lightning.utilities import rank_zero_only
import torch.distributed as dist
import matplotlib
import mdtraj
import warnings
from gafl.analysis import metrics
from gafl.models.flow_module import FlowModule
from gafl.data import utils as du
from gafl.models import utils as mu
import gafl.experiment_utils as eu
from bbflow.data.alignment import require_alignment_version
from bbflow.models.bbflow_model import BBFlowModel
from bbflow.models.latent import LatentEncoder
from bbflow.models.collective import collective_measure_dynamics_loss
from bbflow.analysis import utils as au
from bbflow.analysis.analyse_bbflow import calc_metrics
from bbflow.data.interpolant_bbflow import InterpolantBBFlow
# depending on the torch version (higher than 2.6), we need to add the DictConfig and ContainerMetadata to the safe globals:
from omegaconf import DictConfig, OmegaConf
from omegaconf.base import ContainerMetadata
if hasattr(torch.serialization, 'add_safe_globals'):
torch.serialization.add_safe_globals([DictConfig, ContainerMetadata]) # needed for loading the checkpoint with weights_only=True
WARMUP_EPOCH_SUMMARY_KEYS = [
"train_loss",
"official_loss",
"enm_warmup_loss",
"enm_warmup_subspace_overlap",
"enm_warmup_cross_cov_far_top10_sign_agree",
"enm_warmup_cross_cov_far_corr",
"enm_warmup_active",
"latent_effective_modes",
"condition_scaled_pred_trans_delta_rel",
]
MD_EPOCH_SUMMARY_KEYS = [
"train_loss",
"official_loss",
"motion_loss",
"mode_orth_loss",
"mode_recon_loss",
"q_nll_loss",
"q_nll_per_dim",
"mode_coeff_abs",
"mode_coeff_std",
"mode_recon_centered_rel_error",
"mode_recon_uncentered_rel_error",
"mode_gram_min_eig",
"mode_gram_condition",
"mode_max_cosine_abs",
"local_cov_loss",
"cross_cov_loss",
"cross_cov_near_loss",
"cross_cov_far_loss",
"cross_cov_far_corr",
"cross_cov_far_top10_sign_agree",
"cross_cov_near_top10_sign_agree",
"rmsf_loss",
"gen_cov_loss",
"gen_local_shape_loss",
"gen_cross_shape_loss",
"gen_oracle_shape_loss",
"gen_oracle_weighted_loss",
"gen_oracle_active_frac",
"gen_oracle_rank_used",
"gen_trace_anchor_loss",
"gen_response_abs_mean",
"gen_response_trace_mean",
"gen_trace_ratio_to_teacher",
"gen_trace_ratio_to_anchor",
"gen_trace_anchor_mean",
"gen_rollout_trace_ratio",
"gen_rollout_trace_ratio_ema",
"gen_rollout_trace_target_scale",
"gen_rollout_trace_measured",
"gen_rollout_trace_steps",
"gen_rollout_batch",
"gen_rollout_num_res",